mirror of
https://github.com/MODSetter/SurfSense.git
synced 2026-05-01 20:03:30 +02:00
Merge branch 'dev' into google-drive-connector
Merge in dev
This commit is contained in:
commit
c5c61a2c6b
76 changed files with 3237 additions and 961 deletions
|
|
@ -15,8 +15,6 @@ import {
|
|||
AlertCircle,
|
||||
ArrowDownIcon,
|
||||
ArrowUpIcon,
|
||||
Brain,
|
||||
CheckCircle2,
|
||||
CheckIcon,
|
||||
ChevronLeftIcon,
|
||||
ChevronRightIcon,
|
||||
|
|
@ -28,8 +26,6 @@ import {
|
|||
Plug2,
|
||||
Plus,
|
||||
RefreshCwIcon,
|
||||
Search,
|
||||
Sparkles,
|
||||
SquareIcon,
|
||||
} from "lucide-react";
|
||||
import Link from "next/link";
|
||||
|
|
@ -75,13 +71,8 @@ import {
|
|||
DocumentMentionPicker,
|
||||
type DocumentMentionPickerRef,
|
||||
} from "@/components/new-chat/document-mention-picker";
|
||||
import {
|
||||
ChainOfThought,
|
||||
ChainOfThoughtContent,
|
||||
ChainOfThoughtItem,
|
||||
ChainOfThoughtStep,
|
||||
ChainOfThoughtTrigger,
|
||||
} from "@/components/prompt-kit/chain-of-thought";
|
||||
import { ChainOfThoughtItem } from "@/components/prompt-kit/chain-of-thought";
|
||||
import { TextShimmerLoader } from "@/components/prompt-kit/loader";
|
||||
import type { ThinkingStep } from "@/components/tool-ui/deepagent-thinking";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||
|
|
@ -103,124 +94,146 @@ interface ThreadProps {
|
|||
const ThinkingStepsContext = createContext<Map<string, ThinkingStep[]>>(new Map());
|
||||
|
||||
/**
|
||||
* Get icon based on step status and title
|
||||
*/
|
||||
function getStepIcon(status: "pending" | "in_progress" | "completed", title: string) {
|
||||
const titleLower = title.toLowerCase();
|
||||
|
||||
if (status === "in_progress") {
|
||||
return <Loader2 className="size-4 animate-spin text-primary" />;
|
||||
}
|
||||
|
||||
if (status === "completed") {
|
||||
return <CheckCircle2 className="size-4 text-emerald-500" />;
|
||||
}
|
||||
|
||||
if (titleLower.includes("search") || titleLower.includes("knowledge")) {
|
||||
return <Search className="size-4 text-muted-foreground" />;
|
||||
}
|
||||
|
||||
if (titleLower.includes("analy") || titleLower.includes("understand")) {
|
||||
return <Brain className="size-4 text-muted-foreground" />;
|
||||
}
|
||||
|
||||
return <Sparkles className="size-4 text-muted-foreground" />;
|
||||
}
|
||||
|
||||
/**
|
||||
* Chain of thought display component with smart expand/collapse behavior
|
||||
* Chain of thought display component - single collapsible dropdown design
|
||||
*/
|
||||
const ThinkingStepsDisplay: FC<{ steps: ThinkingStep[]; isThreadRunning?: boolean }> = ({
|
||||
steps,
|
||||
isThreadRunning = true,
|
||||
}) => {
|
||||
// Track which steps the user has manually toggled (overrides auto behavior)
|
||||
const [manualOverrides, setManualOverrides] = useState<Record<string, boolean>>({});
|
||||
// Track previous step statuses to detect changes
|
||||
const prevStatusesRef = useRef<Record<string, string>>({});
|
||||
const [isOpen, setIsOpen] = useState(true);
|
||||
|
||||
// Derive effective status: if thread stopped and step is in_progress, treat as completed
|
||||
const getEffectiveStatus = (step: ThinkingStep): "pending" | "in_progress" | "completed" => {
|
||||
if (step.status === "in_progress" && !isThreadRunning) {
|
||||
return "completed"; // Thread was stopped, so mark as completed
|
||||
}
|
||||
return step.status;
|
||||
};
|
||||
|
||||
// Clear manual overrides when a step's status changes
|
||||
useEffect(() => {
|
||||
const currentStatuses: Record<string, string> = {};
|
||||
steps.forEach((step) => {
|
||||
currentStatuses[step.id] = step.status;
|
||||
// If status changed, clear any manual override for this step
|
||||
if (prevStatusesRef.current[step.id] && prevStatusesRef.current[step.id] !== step.status) {
|
||||
setManualOverrides((prev) => {
|
||||
const next = { ...prev };
|
||||
delete next[step.id];
|
||||
return next;
|
||||
});
|
||||
// Derive effective status for each step
|
||||
const getEffectiveStatus = useCallback(
|
||||
(step: ThinkingStep): "pending" | "in_progress" | "completed" => {
|
||||
if (step.status === "in_progress" && !isThreadRunning) {
|
||||
return "completed";
|
||||
}
|
||||
});
|
||||
prevStatusesRef.current = currentStatuses;
|
||||
}, [steps]);
|
||||
return step.status;
|
||||
},
|
||||
[isThreadRunning]
|
||||
);
|
||||
|
||||
// Calculate summary info
|
||||
const completedSteps = steps.filter((s) => getEffectiveStatus(s) === "completed").length;
|
||||
const inProgressStep = steps.find((s) => getEffectiveStatus(s) === "in_progress");
|
||||
const allCompleted = completedSteps === steps.length && steps.length > 0 && !isThreadRunning;
|
||||
const isProcessing = isThreadRunning && !allCompleted;
|
||||
|
||||
// Auto-collapse when all tasks are completed
|
||||
useEffect(() => {
|
||||
if (allCompleted) {
|
||||
setIsOpen(false);
|
||||
}
|
||||
}, [allCompleted]);
|
||||
|
||||
if (steps.length === 0) return null;
|
||||
|
||||
const getStepOpenState = (step: ThinkingStep): boolean => {
|
||||
const effectiveStatus = getEffectiveStatus(step);
|
||||
// If user has manually toggled, respect that
|
||||
if (manualOverrides[step.id] !== undefined) {
|
||||
return manualOverrides[step.id];
|
||||
// Generate header text
|
||||
const getHeaderText = () => {
|
||||
if (allCompleted) {
|
||||
return `Reviewed ${completedSteps} ${completedSteps === 1 ? "step" : "steps"}`;
|
||||
}
|
||||
// Auto behavior: open if in progress
|
||||
if (effectiveStatus === "in_progress") {
|
||||
return true;
|
||||
if (inProgressStep) {
|
||||
return inProgressStep.title;
|
||||
}
|
||||
// Default: collapsed (all steps collapse when processing is done)
|
||||
return false;
|
||||
};
|
||||
|
||||
const handleToggle = (stepId: string, currentOpen: boolean) => {
|
||||
setManualOverrides((prev) => ({
|
||||
...prev,
|
||||
[stepId]: !currentOpen,
|
||||
}));
|
||||
if (isProcessing) {
|
||||
return `Processing ${completedSteps}/${steps.length} steps`;
|
||||
}
|
||||
return `Reviewed ${completedSteps} ${completedSteps === 1 ? "step" : "steps"}`;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-(--thread-max-width) px-2 py-2">
|
||||
<ChainOfThought>
|
||||
{steps.map((step) => {
|
||||
const effectiveStatus = getEffectiveStatus(step);
|
||||
const icon = getStepIcon(effectiveStatus, step.title);
|
||||
const isOpen = getStepOpenState(step);
|
||||
return (
|
||||
<ChainOfThoughtStep
|
||||
key={step.id}
|
||||
open={isOpen}
|
||||
onOpenChange={() => handleToggle(step.id, isOpen)}
|
||||
>
|
||||
<ChainOfThoughtTrigger
|
||||
leftIcon={icon}
|
||||
swapIconOnHover={effectiveStatus !== "in_progress"}
|
||||
className={cn(
|
||||
effectiveStatus === "in_progress" && "text-foreground font-medium",
|
||||
effectiveStatus === "completed" && "text-muted-foreground"
|
||||
)}
|
||||
>
|
||||
{step.title}
|
||||
</ChainOfThoughtTrigger>
|
||||
{step.items && step.items.length > 0 && (
|
||||
<ChainOfThoughtContent>
|
||||
{step.items.map((item, idx) => (
|
||||
<ChainOfThoughtItem key={`${step.id}-item-${idx}`}>{item}</ChainOfThoughtItem>
|
||||
))}
|
||||
</ChainOfThoughtContent>
|
||||
)}
|
||||
</ChainOfThoughtStep>
|
||||
);
|
||||
})}
|
||||
</ChainOfThought>
|
||||
<div className="rounded-lg">
|
||||
{/* Main collapsible header */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsOpen(!isOpen)}
|
||||
className={cn(
|
||||
"flex w-full items-center gap-1.5 text-left text-sm transition-colors",
|
||||
"text-muted-foreground hover:text-foreground"
|
||||
)}
|
||||
>
|
||||
{/* Header text with shimmer if processing or has in-progress step */}
|
||||
{isProcessing || inProgressStep ? (
|
||||
<TextShimmerLoader text={getHeaderText()} size="sm" />
|
||||
) : (
|
||||
<span>{getHeaderText()}</span>
|
||||
)}
|
||||
|
||||
{/* Chevron */}
|
||||
<ChevronRightIcon
|
||||
className={cn("size-4 transition-transform duration-200", isOpen && "rotate-90")}
|
||||
/>
|
||||
</button>
|
||||
|
||||
{/* Collapsible content with CSS grid animation */}
|
||||
<div
|
||||
className={cn(
|
||||
"grid transition-[grid-template-rows] duration-300 ease-out",
|
||||
isOpen ? "grid-rows-[1fr]" : "grid-rows-[0fr]"
|
||||
)}
|
||||
>
|
||||
<div className="overflow-hidden">
|
||||
<div className="mt-3 pl-1">
|
||||
{steps.map((step, index) => {
|
||||
const effectiveStatus = getEffectiveStatus(step);
|
||||
const isLast = index === steps.length - 1;
|
||||
|
||||
return (
|
||||
<div key={step.id} className="relative flex gap-3">
|
||||
{/* Dot and line column */}
|
||||
<div className="relative flex flex-col items-center w-2">
|
||||
{/* Vertical connection line - extends to next dot */}
|
||||
{!isLast && (
|
||||
<div className="absolute left-1/2 top-[15px] -bottom-[7px] w-px -translate-x-1/2 bg-muted-foreground/30" />
|
||||
)}
|
||||
{/* Step dot - on top of line */}
|
||||
<div className="relative z-10 mt-[7px] flex shrink-0 items-center justify-center">
|
||||
{effectiveStatus === "in_progress" ? (
|
||||
<span className="size-2 rounded-full bg-muted-foreground/30" />
|
||||
) : (
|
||||
<span className="size-2 rounded-full bg-muted-foreground/30" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Step content */}
|
||||
<div className="flex-1 min-w-0 pb-4">
|
||||
{/* Step title */}
|
||||
<div
|
||||
className={cn(
|
||||
"text-sm leading-5",
|
||||
effectiveStatus === "in_progress" && "text-foreground font-medium",
|
||||
effectiveStatus === "completed" && "text-muted-foreground",
|
||||
effectiveStatus === "pending" && "text-muted-foreground/60"
|
||||
)}
|
||||
>
|
||||
{effectiveStatus === "in_progress" ? (
|
||||
<TextShimmerLoader text={step.title} size="sm" />
|
||||
) : (
|
||||
step.title
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Step items (sub-content) */}
|
||||
{step.items && step.items.length > 0 && (
|
||||
<div className="mt-1 space-y-0.5">
|
||||
{step.items.map((item, idx) => (
|
||||
<ChainOfThoughtItem key={`${step.id}-item-${idx}`} className="text-xs">
|
||||
{item}
|
||||
</ChainOfThoughtItem>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
|
@ -286,7 +299,7 @@ export const Thread: FC<ThreadProps> = ({ messageThinkingSteps = new Map(), head
|
|||
>
|
||||
<ThreadPrimitive.Viewport
|
||||
turnAnchor="top"
|
||||
className="aui-thread-viewport relative flex flex-1 min-h-0 flex-col overflow-x-auto overflow-y-scroll scroll-smooth px-4 pt-4"
|
||||
className="aui-thread-viewport relative flex flex-1 min-h-0 flex-col overflow-y-auto px-4 pt-4"
|
||||
>
|
||||
{/* Optional sticky header for model selector etc. */}
|
||||
{header && <div className="sticky top-0 z-10 mb-4">{header}</div>}
|
||||
|
|
@ -428,13 +441,6 @@ const Composer: FC = () => {
|
|||
}
|
||||
}, [isThreadEmpty]);
|
||||
|
||||
// Reset auto-focus flag when thread becomes non-empty (user sent a message)
|
||||
useEffect(() => {
|
||||
if (!isThreadEmpty) {
|
||||
hasAutoFocusedRef.current = false;
|
||||
}
|
||||
}, [isThreadEmpty]);
|
||||
|
||||
// Sync mentioned document IDs to atom for use in chat request
|
||||
useEffect(() => {
|
||||
setMentionedDocumentIds(mentionedDocuments.map((doc) => doc.id));
|
||||
|
|
@ -561,7 +567,7 @@ const Composer: FC = () => {
|
|||
<div ref={editorContainerRef} className="aui-composer-input-wrapper px-3 pt-3 pb-6">
|
||||
<InlineMentionEditor
|
||||
ref={editorRef}
|
||||
placeholder="Ask SurfSense (type @ to mention docs)"
|
||||
placeholder="Ask SurfSense or @mention docs"
|
||||
onMentionTrigger={handleMentionTrigger}
|
||||
onMentionClose={handleMentionClose}
|
||||
onChange={handleEditorChange}
|
||||
|
|
@ -683,14 +689,10 @@ const ConnectorIndicator: FC = () => {
|
|||
) : (
|
||||
<>
|
||||
<Plug2 className="size-4" />
|
||||
{totalSourceCount > 0 ? (
|
||||
{totalSourceCount > 0 && (
|
||||
<span className="absolute -top-0.5 -right-0.5 flex items-center justify-center min-w-[16px] h-4 px-1 text-[10px] font-medium rounded-full bg-primary text-primary-foreground shadow-sm">
|
||||
{totalSourceCount > 99 ? "99+" : totalSourceCount}
|
||||
</span>
|
||||
) : (
|
||||
<span className="absolute -top-0.5 -right-0.5 flex items-center justify-center size-3 rounded-full bg-muted-foreground/30 border border-background">
|
||||
<span className="size-1.5 rounded-full bg-muted-foreground/60" />
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
|
@ -917,7 +919,7 @@ const AssistantMessageInner: FC = () => {
|
|||
<MessageError />
|
||||
</div>
|
||||
|
||||
<div className="aui-assistant-message-footer mt-1 ml-2 flex">
|
||||
<div className="aui-assistant-message-footer mt-1 mb-5 ml-2 flex">
|
||||
<BranchPicker />
|
||||
<AssistantActionBar />
|
||||
</div>
|
||||
|
|
|
|||
66
surfsense_web/components/prompt-kit/loader.tsx
Normal file
66
surfsense_web/components/prompt-kit/loader.tsx
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
"use client";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export interface LoaderProps {
|
||||
variant?: "text-shimmer";
|
||||
size?: "sm" | "md" | "lg";
|
||||
text?: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const textSizes = {
|
||||
sm: "text-xs",
|
||||
md: "text-sm",
|
||||
lg: "text-base",
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* TextShimmerLoader - A text loader with a shimmer gradient animation
|
||||
* Used for in-progress states in write_todos and chain-of-thought
|
||||
*/
|
||||
export function TextShimmerLoader({
|
||||
text = "Thinking",
|
||||
className,
|
||||
size = "md",
|
||||
}: {
|
||||
text?: string;
|
||||
className?: string;
|
||||
size?: "sm" | "md" | "lg";
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
<style>
|
||||
{`
|
||||
@keyframes shimmer {
|
||||
0% { background-position: 200% 50%; }
|
||||
100% { background-position: -200% 50%; }
|
||||
}
|
||||
`}
|
||||
</style>
|
||||
<span
|
||||
className={cn(
|
||||
"bg-[linear-gradient(to_right,var(--muted-foreground)_40%,var(--foreground)_60%,var(--muted-foreground)_80%)]",
|
||||
"bg-[length:200%_auto] bg-clip-text font-medium text-transparent",
|
||||
"animate-[shimmer_4s_infinite_linear]",
|
||||
textSizes[size],
|
||||
className
|
||||
)}
|
||||
>
|
||||
{text}
|
||||
</span>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Loader component - currently only supports text-shimmer variant
|
||||
* Can be extended with more variants if needed in the future
|
||||
*/
|
||||
export function Loader({ variant = "text-shimmer", size = "md", text, className }: LoaderProps) {
|
||||
switch (variant) {
|
||||
case "text-shimmer":
|
||||
default:
|
||||
return <TextShimmerLoader text={text} size={size} className={className} />;
|
||||
}
|
||||
}
|
||||
|
|
@ -3,7 +3,7 @@
|
|||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useAtomValue, useSetAtom } from "jotai";
|
||||
import { Trash2 } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useParams, useRouter } from "next/navigation";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { hasUnsavedEditorChangesAtom, pendingEditorNavigationAtom } from "@/atoms/editor/ui.atoms";
|
||||
|
|
@ -50,7 +50,13 @@ export function AppSidebarProvider({
|
|||
const t = useTranslations("dashboard");
|
||||
const tCommon = useTranslations("common");
|
||||
const router = useRouter();
|
||||
const params = useParams();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
// Get current chat ID from URL params
|
||||
const currentChatId = params?.chat_id
|
||||
? Number(Array.isArray(params.chat_id) ? params.chat_id[0] : params.chat_id)
|
||||
: null;
|
||||
const [isDeletingThread, setIsDeletingThread] = useState(false);
|
||||
|
||||
// Editor state for handling unsaved changes
|
||||
|
|
@ -61,7 +67,6 @@ export function AppSidebarProvider({
|
|||
const {
|
||||
data: threadsData,
|
||||
error: threadError,
|
||||
isLoading: isLoadingThreads,
|
||||
refetch: refetchThreads,
|
||||
} = useQuery({
|
||||
queryKey: ["threads", searchSpaceId],
|
||||
|
|
@ -73,7 +78,6 @@ export function AppSidebarProvider({
|
|||
data: searchSpace,
|
||||
isLoading: isLoadingSearchSpace,
|
||||
error: searchSpaceError,
|
||||
refetch: fetchSearchSpace,
|
||||
} = useQuery({
|
||||
queryKey: cacheKeys.searchSpaces.detail(searchSpaceId),
|
||||
queryFn: () => searchSpacesApiService.getSearchSpace({ id: Number(searchSpaceId) }),
|
||||
|
|
@ -83,12 +87,7 @@ export function AppSidebarProvider({
|
|||
const { data: user } = useAtomValue(currentUserAtom);
|
||||
|
||||
// Fetch notes
|
||||
const {
|
||||
data: notesData,
|
||||
error: notesError,
|
||||
isLoading: isLoadingNotes,
|
||||
refetch: refetchNotes,
|
||||
} = useQuery({
|
||||
const { data: notesData, refetch: refetchNotes } = useQuery({
|
||||
queryKey: ["notes", searchSpaceId],
|
||||
queryFn: () =>
|
||||
notesApiService.getNotes({
|
||||
|
|
@ -108,11 +107,6 @@ export function AppSidebarProvider({
|
|||
} | null>(null);
|
||||
const [isDeletingNote, setIsDeletingNote] = useState(false);
|
||||
|
||||
// Retry function
|
||||
const retryFetch = useCallback(() => {
|
||||
fetchSearchSpace();
|
||||
}, [fetchSearchSpace]);
|
||||
|
||||
// Transform threads to the format expected by AppSidebar
|
||||
const recentChats = useMemo(() => {
|
||||
if (!threadsData?.threads) return [];
|
||||
|
|
@ -149,6 +143,10 @@ export function AppSidebarProvider({
|
|||
await deleteThread(threadToDelete.id);
|
||||
// Invalidate threads query to refresh the list
|
||||
queryClient.invalidateQueries({ queryKey: ["threads", searchSpaceId] });
|
||||
// Only navigate to new-chat if the deleted chat is currently open
|
||||
if (currentChatId === threadToDelete.id) {
|
||||
router.push(`/dashboard/${searchSpaceId}/new-chat`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error deleting thread:", error);
|
||||
} finally {
|
||||
|
|
@ -156,7 +154,7 @@ export function AppSidebarProvider({
|
|||
setShowDeleteDialog(false);
|
||||
setThreadToDelete(null);
|
||||
}
|
||||
}, [threadToDelete, queryClient, searchSpaceId]);
|
||||
}, [threadToDelete, queryClient, searchSpaceId, router, currentChatId]);
|
||||
|
||||
// Handle delete note with confirmation
|
||||
const handleDeleteNote = useCallback(async () => {
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ import {
|
|||
X,
|
||||
} from "lucide-react";
|
||||
import { AnimatePresence, motion } from "motion/react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useParams, useRouter } from "next/navigation";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
|
|
@ -47,7 +47,15 @@ interface AllChatsSidebarProps {
|
|||
export function AllChatsSidebar({ open, onOpenChange, searchSpaceId }: AllChatsSidebarProps) {
|
||||
const t = useTranslations("sidebar");
|
||||
const router = useRouter();
|
||||
const params = useParams();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
// Get the current chat ID from URL to check if user is deleting the currently open chat
|
||||
const currentChatId = Array.isArray(params.chat_id)
|
||||
? Number(params.chat_id[0])
|
||||
: params.chat_id
|
||||
? Number(params.chat_id)
|
||||
: null;
|
||||
const [deletingThreadId, setDeletingThreadId] = useState<number | null>(null);
|
||||
const [archivingThreadId, setArchivingThreadId] = useState<number | null>(null);
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
|
|
@ -126,6 +134,15 @@ export function AllChatsSidebar({ open, onOpenChange, searchSpaceId }: AllChatsS
|
|||
queryClient.invalidateQueries({ queryKey: ["all-threads", searchSpaceId] });
|
||||
queryClient.invalidateQueries({ queryKey: ["search-threads", searchSpaceId] });
|
||||
queryClient.invalidateQueries({ queryKey: ["threads", searchSpaceId] });
|
||||
|
||||
// If the deleted chat is currently open, close sidebar first then redirect
|
||||
if (currentChatId === threadId) {
|
||||
onOpenChange(false);
|
||||
// Wait for sidebar close animation to complete before navigating
|
||||
setTimeout(() => {
|
||||
router.push(`/dashboard/${searchSpaceId}/new-chat`);
|
||||
}, 250);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error deleting thread:", error);
|
||||
toast.error(t("error_deleting_chat") || "Failed to delete chat");
|
||||
|
|
@ -133,7 +150,7 @@ export function AllChatsSidebar({ open, onOpenChange, searchSpaceId }: AllChatsS
|
|||
setDeletingThreadId(null);
|
||||
}
|
||||
},
|
||||
[queryClient, searchSpaceId, t]
|
||||
[queryClient, searchSpaceId, t, currentChatId, router, onOpenChange]
|
||||
);
|
||||
|
||||
// Handle thread archive/unarchive
|
||||
|
|
@ -293,6 +310,7 @@ export function AllChatsSidebar({ open, onOpenChange, searchSpaceId }: AllChatsS
|
|||
const isDeleting = deletingThreadId === thread.id;
|
||||
const isArchiving = archivingThreadId === thread.id;
|
||||
const isBusy = isDeleting || isArchiving;
|
||||
const isActive = currentChatId === thread.id;
|
||||
|
||||
return (
|
||||
<div
|
||||
|
|
@ -301,6 +319,7 @@ export function AllChatsSidebar({ open, onOpenChange, searchSpaceId }: AllChatsS
|
|||
"group flex items-center gap-2 rounded-md px-2 py-1.5 text-sm",
|
||||
"hover:bg-accent hover:text-accent-foreground",
|
||||
"transition-colors cursor-pointer",
|
||||
isActive && "bg-accent text-accent-foreground",
|
||||
isBusy && "opacity-50 pointer-events-none"
|
||||
)}
|
||||
>
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import { useQuery, useQueryClient } from "@tanstack/react-query";
|
|||
import { format } from "date-fns";
|
||||
import { FileText, Loader2, MoreHorizontal, Plus, Search, Trash2, X } from "lucide-react";
|
||||
import { AnimatePresence, motion } from "motion/react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useParams, useRouter } from "next/navigation";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
|
|
@ -37,7 +37,11 @@ export function AllNotesSidebar({
|
|||
}: AllNotesSidebarProps) {
|
||||
const t = useTranslations("sidebar");
|
||||
const router = useRouter();
|
||||
const params = useParams();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
// Get the current note ID from URL to highlight the open note
|
||||
const currentNoteId = params.note_id ? Number(params.note_id) : null;
|
||||
const [deletingNoteId, setDeletingNoteId] = useState<number | null>(null);
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [mounted, setMounted] = useState(false);
|
||||
|
|
@ -208,7 +212,7 @@ export function AllNotesSidebar({
|
|||
aria-label={t("all_notes") || "All Notes"}
|
||||
>
|
||||
{/* Header */}
|
||||
<div className="flex-shrink-0 p-4 pb-3 space-y-3 border-b">
|
||||
<div className="flex-shrink-0 p-4 pb-3 space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-lg font-semibold">{t("all_notes") || "All Notes"}</h2>
|
||||
<Button
|
||||
|
|
@ -260,6 +264,7 @@ export function AllNotesSidebar({
|
|||
<div className="space-y-1">
|
||||
{notes.map((note) => {
|
||||
const isDeleting = deletingNoteId === note.id;
|
||||
const isActive = currentNoteId === note.id;
|
||||
|
||||
return (
|
||||
<div
|
||||
|
|
@ -268,6 +273,7 @@ export function AllNotesSidebar({
|
|||
"group flex items-center gap-2 rounded-md px-2 py-1.5 text-sm",
|
||||
"hover:bg-accent hover:text-accent-foreground",
|
||||
"transition-colors cursor-pointer",
|
||||
isActive && "bg-accent text-accent-foreground",
|
||||
isDeleting && "opacity-50 pointer-events-none"
|
||||
)}
|
||||
>
|
||||
|
|
@ -370,7 +376,7 @@ export function AllNotesSidebar({
|
|||
|
||||
{/* Footer with Add Note button */}
|
||||
{onAddNote && notes.length > 0 && (
|
||||
<div className="flex-shrink-0 p-3 border-t">
|
||||
<div className="flex-shrink-0 p-3">
|
||||
<Button
|
||||
onClick={() => {
|
||||
onAddNote();
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ import {
|
|||
RefreshCw,
|
||||
Trash2,
|
||||
} from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
|
@ -71,6 +71,7 @@ export function NavChats({
|
|||
}: NavChatsProps) {
|
||||
const t = useTranslations("sidebar");
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const isMobile = useIsMobile();
|
||||
const [isDeleting, setIsDeleting] = useState<number | null>(null);
|
||||
const [isOpen, setIsOpen] = useState(defaultOpen);
|
||||
|
|
@ -142,6 +143,7 @@ export function NavChats({
|
|||
<SidebarMenu>
|
||||
{chats.map((chat) => {
|
||||
const isDeletingChat = isDeleting === chat.id;
|
||||
const isActive = pathname === chat.url;
|
||||
|
||||
return (
|
||||
<SidebarMenuItem key={chat.id || chat.name} className="group/chat">
|
||||
|
|
@ -151,6 +153,7 @@ export function NavChats({
|
|||
disabled={isDeletingChat}
|
||||
className={cn(
|
||||
"pr-8", // Make room for the action button
|
||||
isActive && "bg-sidebar-accent text-sidebar-accent-foreground",
|
||||
isDeletingChat && "opacity-50"
|
||||
)}
|
||||
>
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
"use client";
|
||||
|
||||
import { ChevronRight, type LucideIcon } from "lucide-react";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
|
||||
|
|
@ -35,6 +36,7 @@ interface NavMainProps {
|
|||
|
||||
export function NavMain({ items, onSourcesExpandedChange }: NavMainProps) {
|
||||
const t = useTranslations("nav_menu");
|
||||
const pathname = usePathname();
|
||||
|
||||
// Translation function that handles both exact matches and fallback to original
|
||||
const translateTitle = (title: string): string => {
|
||||
|
|
@ -55,6 +57,35 @@ export function NavMain({ items, onSourcesExpandedChange }: NavMainProps) {
|
|||
return key ? t(key) : title;
|
||||
};
|
||||
|
||||
// Check if an item is active based on pathname
|
||||
const isItemActive = useCallback(
|
||||
(item: NavItem): boolean => {
|
||||
if (!pathname) return false;
|
||||
|
||||
// For items without sub-items, check if pathname matches or starts with the URL
|
||||
if (!item.items?.length) {
|
||||
// Chat item: active ONLY when on new-chat page without a specific chat ID
|
||||
// (i.e., exactly /dashboard/{id}/new-chat, not /dashboard/{id}/new-chat/123)
|
||||
if (item.url.includes("/new-chat")) {
|
||||
// Match exactly the new-chat base URL (ends with /new-chat)
|
||||
return pathname.endsWith("/new-chat");
|
||||
}
|
||||
// Logs item: active when on logs page
|
||||
if (item.url.includes("/logs")) {
|
||||
return pathname.includes("/logs");
|
||||
}
|
||||
// Check exact match or prefix match
|
||||
return pathname === item.url || pathname.startsWith(`${item.url}/`);
|
||||
}
|
||||
|
||||
// For items with sub-items (like Sources), check if any sub-item URL matches
|
||||
return item.items.some(
|
||||
(subItem) => pathname === subItem.url || pathname.startsWith(subItem.url)
|
||||
);
|
||||
},
|
||||
[pathname]
|
||||
);
|
||||
|
||||
// Memoize items to prevent unnecessary re-renders
|
||||
const memoizedItems = useMemo(() => items, [items]);
|
||||
|
||||
|
|
@ -88,14 +119,15 @@ export function NavMain({ items, onSourcesExpandedChange }: NavMainProps) {
|
|||
{memoizedItems.map((item, index) => {
|
||||
const translatedTitle = translateTitle(item.title);
|
||||
const hasSub = !!item.items?.length;
|
||||
const isItemOpen = expandedItems[item.title] ?? item.isActive ?? false;
|
||||
const isActive = isItemActive(item);
|
||||
const isItemOpen = expandedItems[item.title] ?? isActive ?? false;
|
||||
return (
|
||||
<Collapsible
|
||||
key={`${item.title}-${index}`}
|
||||
asChild
|
||||
open={hasSub ? isItemOpen : undefined}
|
||||
onOpenChange={hasSub ? (open) => handleOpenChange(item.title, open) : undefined}
|
||||
defaultOpen={!hasSub ? item.isActive : undefined}
|
||||
defaultOpen={!hasSub ? isActive : undefined}
|
||||
>
|
||||
<SidebarMenuItem>
|
||||
{hasSub ? (
|
||||
|
|
@ -105,7 +137,7 @@ export function NavMain({ items, onSourcesExpandedChange }: NavMainProps) {
|
|||
<SidebarMenuButton
|
||||
asChild
|
||||
tooltip={translatedTitle}
|
||||
isActive={item.isActive}
|
||||
isActive={isActive}
|
||||
aria-label={`${translatedTitle} with submenu`}
|
||||
>
|
||||
<button type="button" className="flex items-center gap-2 w-full text-left">
|
||||
|
|
@ -147,7 +179,7 @@ export function NavMain({ items, onSourcesExpandedChange }: NavMainProps) {
|
|||
<SidebarMenuButton
|
||||
asChild
|
||||
tooltip={translatedTitle}
|
||||
isActive={item.isActive}
|
||||
isActive={isActive}
|
||||
aria-label={translatedTitle}
|
||||
>
|
||||
<a href={item.url}>
|
||||
|
|
|
|||
|
|
@ -10,9 +10,9 @@ import {
|
|||
Plus,
|
||||
Trash2,
|
||||
} from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
|
||||
import {
|
||||
|
|
@ -29,6 +29,7 @@ import {
|
|||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
} from "@/components/ui/sidebar";
|
||||
import { useLogsSummary } from "@/hooks/use-logs";
|
||||
import { useIsMobile } from "@/hooks/use-mobile";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { AllNotesSidebar } from "./all-notes-sidebar";
|
||||
|
|
@ -72,11 +73,27 @@ export function NavNotes({
|
|||
}: NavNotesProps) {
|
||||
const t = useTranslations("sidebar");
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const isMobile = useIsMobile();
|
||||
const [isDeleting, setIsDeleting] = useState<number | null>(null);
|
||||
const [isOpen, setIsOpen] = useState(defaultOpen);
|
||||
const [isAllNotesSidebarOpen, setIsAllNotesSidebarOpen] = useState(false);
|
||||
|
||||
// Poll for active reindexing tasks to show inline loading indicators
|
||||
const { summary } = useLogsSummary(searchSpaceId ? Number(searchSpaceId) : 0, 24, {
|
||||
refetchInterval: 2000,
|
||||
});
|
||||
|
||||
// Create a Set of document IDs that are currently being reindexed
|
||||
const reindexingDocumentIds = useMemo(() => {
|
||||
if (!summary?.active_tasks) return new Set<number>();
|
||||
return new Set(
|
||||
summary.active_tasks
|
||||
.filter((task) => task.document_id != null)
|
||||
.map((task) => task.document_id as number)
|
||||
);
|
||||
}, [summary?.active_tasks]);
|
||||
|
||||
// Auto-collapse on smaller screens when Sources is expanded
|
||||
useEffect(() => {
|
||||
if (isSourcesExpanded && isMobile) {
|
||||
|
|
@ -157,6 +174,8 @@ export function NavNotes({
|
|||
{notes.length > 0 ? (
|
||||
notes.map((note) => {
|
||||
const isDeletingNote = isDeleting === note.id;
|
||||
const isActive = pathname === note.url;
|
||||
const isReindexing = note.id ? reindexingDocumentIds.has(note.id) : false;
|
||||
|
||||
return (
|
||||
<SidebarMenuItem key={note.id || note.name} className="group/note">
|
||||
|
|
@ -166,10 +185,15 @@ export function NavNotes({
|
|||
disabled={isDeletingNote}
|
||||
className={cn(
|
||||
"pr-8", // Make room for the action button
|
||||
isActive && "bg-sidebar-accent text-sidebar-accent-foreground",
|
||||
isDeletingNote && "opacity-50"
|
||||
)}
|
||||
>
|
||||
<note.icon className="h-4 w-4 shrink-0" />
|
||||
{isReindexing ? (
|
||||
<Loader2 className="h-4 w-4 shrink-0 animate-spin text-primary" />
|
||||
) : (
|
||||
<note.icon className="h-4 w-4 shrink-0" />
|
||||
)}
|
||||
<span className="truncate">{note.name}</span>
|
||||
</SidebarMenuButton>
|
||||
|
||||
|
|
|
|||
|
|
@ -36,12 +36,21 @@ export function NavSecondary({
|
|||
<SidebarMenu>
|
||||
{memoizedItems.map((item, index) => (
|
||||
<SidebarMenuItem key={`${item.title}-${index}`}>
|
||||
<SidebarMenuButton asChild size="sm" aria-label={item.title}>
|
||||
<a href={item.url}>
|
||||
<item.icon />
|
||||
<span>{item.title}</span>
|
||||
</a>
|
||||
</SidebarMenuButton>
|
||||
{item.url === "#" ? (
|
||||
// Non-interactive display item (e.g., search space name)
|
||||
<div className="flex h-7 w-full items-center gap-2 rounded-md px-2 text-xs text-sidebar-foreground">
|
||||
<item.icon className="h-4 w-4 shrink-0" />
|
||||
<span className="truncate">{item.title}</span>
|
||||
</div>
|
||||
) : (
|
||||
// Interactive link item
|
||||
<SidebarMenuButton asChild size="sm" aria-label={item.title}>
|
||||
<a href={item.url}>
|
||||
<item.icon />
|
||||
<span>{item.title}</span>
|
||||
</a>
|
||||
</SidebarMenuButton>
|
||||
)}
|
||||
</SidebarMenuItem>
|
||||
))}
|
||||
</SidebarMenu>
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@
|
|||
|
||||
import { makeAssistantToolUI } from "@assistant-ui/react";
|
||||
import { AlertCircleIcon, ImageIcon } from "lucide-react";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
Image,
|
||||
ImageErrorBoundary,
|
||||
|
|
@ -9,27 +10,41 @@ import {
|
|||
parseSerializableImage,
|
||||
} from "@/components/tool-ui/image";
|
||||
|
||||
/**
|
||||
* Type definitions for the display_image tool
|
||||
*/
|
||||
interface DisplayImageArgs {
|
||||
src: string;
|
||||
alt?: string;
|
||||
title?: string;
|
||||
description?: string;
|
||||
}
|
||||
// ============================================================================
|
||||
// Zod Schemas
|
||||
// ============================================================================
|
||||
|
||||
interface DisplayImageResult {
|
||||
id: string;
|
||||
assetId: string;
|
||||
src: string;
|
||||
alt?: string; // Made optional - parseSerializableImage provides fallback
|
||||
title?: string;
|
||||
description?: string;
|
||||
domain?: string;
|
||||
ratio?: string;
|
||||
error?: string;
|
||||
}
|
||||
/**
|
||||
* Schema for display_image tool arguments
|
||||
*/
|
||||
const DisplayImageArgsSchema = z.object({
|
||||
src: z.string(),
|
||||
alt: z.string().nullish(),
|
||||
title: z.string().nullish(),
|
||||
description: z.string().nullish(),
|
||||
});
|
||||
|
||||
/**
|
||||
* Schema for display_image tool result
|
||||
*/
|
||||
const DisplayImageResultSchema = z.object({
|
||||
id: z.string(),
|
||||
assetId: z.string(),
|
||||
src: z.string(),
|
||||
alt: z.string().nullish(),
|
||||
title: z.string().nullish(),
|
||||
description: z.string().nullish(),
|
||||
domain: z.string().nullish(),
|
||||
ratio: z.string().nullish(),
|
||||
error: z.string().nullish(),
|
||||
});
|
||||
|
||||
// ============================================================================
|
||||
// Types
|
||||
// ============================================================================
|
||||
|
||||
type DisplayImageArgs = z.infer<typeof DisplayImageArgsSchema>;
|
||||
type DisplayImageResult = z.infer<typeof DisplayImageResultSchema>;
|
||||
|
||||
/**
|
||||
* Error state component shown when image display fails
|
||||
|
|
@ -142,4 +157,9 @@ export const DisplayImageToolUI = makeAssistantToolUI<DisplayImageArgs, DisplayI
|
|||
},
|
||||
});
|
||||
|
||||
export type { DisplayImageArgs, DisplayImageResult };
|
||||
export {
|
||||
DisplayImageArgsSchema,
|
||||
DisplayImageResultSchema,
|
||||
type DisplayImageArgs,
|
||||
type DisplayImageResult,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -25,7 +25,9 @@ export {
|
|||
} from "./deepagent-thinking";
|
||||
export {
|
||||
type DisplayImageArgs,
|
||||
DisplayImageArgsSchema,
|
||||
type DisplayImageResult,
|
||||
DisplayImageResultSchema,
|
||||
DisplayImageToolUI,
|
||||
} from "./display-image";
|
||||
export { GeneratePodcastToolUI } from "./generate-podcast";
|
||||
|
|
@ -40,10 +42,14 @@ export {
|
|||
} from "./image";
|
||||
export {
|
||||
type LinkPreviewArgs,
|
||||
LinkPreviewArgsSchema,
|
||||
type LinkPreviewResult,
|
||||
LinkPreviewResultSchema,
|
||||
LinkPreviewToolUI,
|
||||
type MultiLinkPreviewArgs,
|
||||
MultiLinkPreviewArgsSchema,
|
||||
type MultiLinkPreviewResult,
|
||||
MultiLinkPreviewResultSchema,
|
||||
MultiLinkPreviewToolUI,
|
||||
} from "./link-preview";
|
||||
export {
|
||||
|
|
@ -55,8 +61,20 @@ export {
|
|||
parseSerializableMediaCard,
|
||||
type SerializableMediaCard,
|
||||
} from "./media-card";
|
||||
export {
|
||||
Plan,
|
||||
PlanErrorBoundary,
|
||||
type PlanProps,
|
||||
type PlanTodo,
|
||||
parseSerializablePlan,
|
||||
type SerializablePlan,
|
||||
type TodoStatus,
|
||||
} from "./plan";
|
||||
export {
|
||||
type ScrapeWebpageArgs,
|
||||
ScrapeWebpageArgsSchema,
|
||||
type ScrapeWebpageResult,
|
||||
ScrapeWebpageResultSchema,
|
||||
ScrapeWebpageToolUI,
|
||||
} from "./scrape-webpage";
|
||||
export { type WriteTodosData, WriteTodosSchema, WriteTodosToolUI } from "./write-todos";
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@
|
|||
|
||||
import { makeAssistantToolUI } from "@assistant-ui/react";
|
||||
import { AlertCircleIcon, ExternalLinkIcon, LinkIcon } from "lucide-react";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
MediaCard,
|
||||
MediaCardErrorBoundary,
|
||||
|
|
@ -10,25 +11,39 @@ import {
|
|||
type SerializableMediaCard,
|
||||
} from "@/components/tool-ui/media-card";
|
||||
|
||||
/**
|
||||
* Type definitions for the link_preview tool
|
||||
*/
|
||||
interface LinkPreviewArgs {
|
||||
url: string;
|
||||
title?: string;
|
||||
}
|
||||
// ============================================================================
|
||||
// Zod Schemas
|
||||
// ============================================================================
|
||||
|
||||
interface LinkPreviewResult {
|
||||
id: string;
|
||||
assetId: string;
|
||||
kind: "link";
|
||||
href: string;
|
||||
title: string;
|
||||
description?: string;
|
||||
thumb?: string;
|
||||
domain?: string;
|
||||
error?: string;
|
||||
}
|
||||
/**
|
||||
* Schema for link_preview tool arguments
|
||||
*/
|
||||
const LinkPreviewArgsSchema = z.object({
|
||||
url: z.string(),
|
||||
title: z.string().nullish(),
|
||||
});
|
||||
|
||||
/**
|
||||
* Schema for link_preview tool result
|
||||
*/
|
||||
const LinkPreviewResultSchema = z.object({
|
||||
id: z.string(),
|
||||
assetId: z.string(),
|
||||
kind: z.literal("link"),
|
||||
href: z.string(),
|
||||
title: z.string(),
|
||||
description: z.string().nullish(),
|
||||
thumb: z.string().nullish(),
|
||||
domain: z.string().nullish(),
|
||||
error: z.string().nullish(),
|
||||
});
|
||||
|
||||
// ============================================================================
|
||||
// Types
|
||||
// ============================================================================
|
||||
|
||||
type LinkPreviewArgs = z.infer<typeof LinkPreviewArgsSchema>;
|
||||
type LinkPreviewResult = z.infer<typeof LinkPreviewResultSchema>;
|
||||
|
||||
/**
|
||||
* Error state component shown when link preview fails
|
||||
|
|
@ -150,20 +165,35 @@ export const LinkPreviewToolUI = makeAssistantToolUI<LinkPreviewArgs, LinkPrevie
|
|||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Multiple Link Previews Tool UI Component
|
||||
*
|
||||
* This component handles cases where multiple links need to be previewed.
|
||||
* It renders a grid of link preview cards.
|
||||
*/
|
||||
interface MultiLinkPreviewArgs {
|
||||
urls: string[];
|
||||
}
|
||||
// ============================================================================
|
||||
// Multi Link Preview Schemas
|
||||
// ============================================================================
|
||||
|
||||
interface MultiLinkPreviewResult {
|
||||
previews: LinkPreviewResult[];
|
||||
errors?: { url: string; error: string }[];
|
||||
}
|
||||
/**
|
||||
* Schema for multi_link_preview tool arguments
|
||||
*/
|
||||
const MultiLinkPreviewArgsSchema = z.object({
|
||||
urls: z.array(z.string()),
|
||||
});
|
||||
|
||||
/**
|
||||
* Schema for error items in multi_link_preview result
|
||||
*/
|
||||
const MultiLinkPreviewErrorSchema = z.object({
|
||||
url: z.string(),
|
||||
error: z.string(),
|
||||
});
|
||||
|
||||
/**
|
||||
* Schema for multi_link_preview tool result
|
||||
*/
|
||||
const MultiLinkPreviewResultSchema = z.object({
|
||||
previews: z.array(LinkPreviewResultSchema),
|
||||
errors: z.array(MultiLinkPreviewErrorSchema).nullish(),
|
||||
});
|
||||
|
||||
type MultiLinkPreviewArgs = z.infer<typeof MultiLinkPreviewArgsSchema>;
|
||||
type MultiLinkPreviewResult = z.infer<typeof MultiLinkPreviewResultSchema>;
|
||||
|
||||
export const MultiLinkPreviewToolUI = makeAssistantToolUI<
|
||||
MultiLinkPreviewArgs,
|
||||
|
|
@ -217,4 +247,13 @@ export const MultiLinkPreviewToolUI = makeAssistantToolUI<
|
|||
},
|
||||
});
|
||||
|
||||
export type { LinkPreviewArgs, LinkPreviewResult, MultiLinkPreviewArgs, MultiLinkPreviewResult };
|
||||
export {
|
||||
LinkPreviewArgsSchema,
|
||||
LinkPreviewResultSchema,
|
||||
MultiLinkPreviewArgsSchema,
|
||||
MultiLinkPreviewResultSchema,
|
||||
type LinkPreviewArgs,
|
||||
type LinkPreviewResult,
|
||||
type MultiLinkPreviewArgs,
|
||||
type MultiLinkPreviewResult,
|
||||
};
|
||||
|
|
|
|||
52
surfsense_web/components/tool-ui/plan/index.tsx
Normal file
52
surfsense_web/components/tool-ui/plan/index.tsx
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
"use client";
|
||||
|
||||
import { Component, type ReactNode } from "react";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
|
||||
export * from "./plan";
|
||||
export * from "./schema";
|
||||
|
||||
// ============================================================================
|
||||
// Error Boundary
|
||||
// ============================================================================
|
||||
|
||||
interface PlanErrorBoundaryProps {
|
||||
children: ReactNode;
|
||||
fallback?: ReactNode;
|
||||
}
|
||||
|
||||
interface PlanErrorBoundaryState {
|
||||
hasError: boolean;
|
||||
error?: Error;
|
||||
}
|
||||
|
||||
export class PlanErrorBoundary extends Component<PlanErrorBoundaryProps, PlanErrorBoundaryState> {
|
||||
constructor(props: PlanErrorBoundaryProps) {
|
||||
super(props);
|
||||
this.state = { hasError: false };
|
||||
}
|
||||
|
||||
static getDerivedStateFromError(error: Error): PlanErrorBoundaryState {
|
||||
return { hasError: true, error };
|
||||
}
|
||||
|
||||
render() {
|
||||
if (this.state.hasError) {
|
||||
if (this.props.fallback) {
|
||||
return this.props.fallback;
|
||||
}
|
||||
|
||||
return (
|
||||
<Card className="w-full max-w-xl border-destructive/50">
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex items-center gap-2 text-destructive">
|
||||
<span className="text-sm">Failed to render plan</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
229
surfsense_web/components/tool-ui/plan/plan.tsx
Normal file
229
surfsense_web/components/tool-ui/plan/plan.tsx
Normal file
|
|
@ -0,0 +1,229 @@
|
|||
"use client";
|
||||
|
||||
import { CheckCircle2, Circle, CircleDashed, ListTodo, PartyPopper, XCircle } from "lucide-react";
|
||||
import type { FC } from "react";
|
||||
import { useMemo, useState } from "react";
|
||||
import { TextShimmerLoader } from "@/components/prompt-kit/loader";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { Action, ActionsConfig } from "../shared/schema";
|
||||
import type { TodoStatus } from "./schema";
|
||||
|
||||
// ============================================================================
|
||||
// Status Icon Component
|
||||
// ============================================================================
|
||||
|
||||
interface StatusIconProps {
|
||||
status: TodoStatus;
|
||||
className?: string;
|
||||
/** When false, in_progress items show as static (no spinner) */
|
||||
isStreaming?: boolean;
|
||||
}
|
||||
|
||||
const StatusIcon: FC<StatusIconProps> = ({ status, className, isStreaming = true }) => {
|
||||
const baseClass = cn("size-4 shrink-0", className);
|
||||
|
||||
switch (status) {
|
||||
case "completed":
|
||||
return <CheckCircle2 className={cn(baseClass, "text-emerald-500")} />;
|
||||
case "in_progress":
|
||||
// Only animate the spinner if we're actively streaming
|
||||
// When streaming is stopped, show as a static dashed circle
|
||||
return (
|
||||
<CircleDashed
|
||||
className={cn(baseClass, "text-primary", isStreaming && "animate-spin")}
|
||||
style={isStreaming ? { animationDuration: "3s" } : undefined}
|
||||
/>
|
||||
);
|
||||
case "cancelled":
|
||||
return <XCircle className={cn(baseClass, "text-destructive")} />;
|
||||
case "pending":
|
||||
default:
|
||||
return <Circle className={cn(baseClass, "text-muted-foreground")} />;
|
||||
}
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// Todo Item Component
|
||||
// ============================================================================
|
||||
|
||||
interface TodoItemProps {
|
||||
todo: { id: string; content: string; status: TodoStatus };
|
||||
/** When false, in_progress items show as static (no spinner/pulse) */
|
||||
isStreaming?: boolean;
|
||||
}
|
||||
|
||||
const TodoItem: FC<TodoItemProps> = ({ todo, isStreaming = true }) => {
|
||||
const isStrikethrough = todo.status === "completed" || todo.status === "cancelled";
|
||||
// Only show shimmer animation if streaming and in progress
|
||||
const isShimmer = todo.status === "in_progress" && isStreaming;
|
||||
|
||||
// Render the content with optional shimmer effect
|
||||
const renderContent = () => {
|
||||
if (isShimmer) {
|
||||
return <TextShimmerLoader text={todo.content} size="md" />;
|
||||
}
|
||||
return (
|
||||
<span className={cn("text-sm text-muted-foreground", isStrikethrough && "line-through")}>
|
||||
{todo.content}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2 py-2">
|
||||
<StatusIcon status={todo.status} isStreaming={isStreaming} />
|
||||
{renderContent()}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// Plan Component
|
||||
// ============================================================================
|
||||
|
||||
export interface PlanProps {
|
||||
id: string;
|
||||
title: string;
|
||||
todos: Array<{ id: string; content: string; status: TodoStatus }>;
|
||||
maxVisibleTodos?: number;
|
||||
showProgress?: boolean;
|
||||
/** When false, in_progress items show as static (no spinner/pulse animations) */
|
||||
isStreaming?: boolean;
|
||||
responseActions?: Action[] | ActionsConfig;
|
||||
className?: string;
|
||||
onResponseAction?: (actionId: string) => void;
|
||||
onBeforeResponseAction?: (actionId: string) => boolean;
|
||||
}
|
||||
|
||||
export const Plan: FC<PlanProps> = ({
|
||||
id,
|
||||
title,
|
||||
todos,
|
||||
maxVisibleTodos = 4,
|
||||
showProgress = true,
|
||||
isStreaming = true,
|
||||
responseActions,
|
||||
className,
|
||||
onResponseAction,
|
||||
onBeforeResponseAction,
|
||||
}) => {
|
||||
const [isExpanded, setIsExpanded] = useState(false);
|
||||
|
||||
// Calculate progress
|
||||
const progress = useMemo(() => {
|
||||
const completed = todos.filter((t) => t.status === "completed").length;
|
||||
const total = todos.filter((t) => t.status !== "cancelled").length;
|
||||
return { completed, total, percentage: total > 0 ? (completed / total) * 100 : 0 };
|
||||
}, [todos]);
|
||||
|
||||
const isAllComplete = progress.completed === progress.total && progress.total > 0;
|
||||
|
||||
// Split todos for collapsible display
|
||||
const visibleTodos = todos.slice(0, maxVisibleTodos);
|
||||
const hiddenTodos = todos.slice(maxVisibleTodos);
|
||||
const hasHiddenTodos = hiddenTodos.length > 0;
|
||||
|
||||
// Handle action click
|
||||
const handleAction = (actionId: string) => {
|
||||
if (onBeforeResponseAction && !onBeforeResponseAction(actionId)) {
|
||||
return;
|
||||
}
|
||||
onResponseAction?.(actionId);
|
||||
};
|
||||
|
||||
// Normalize actions to array
|
||||
const actionArray: Action[] = useMemo(() => {
|
||||
if (!responseActions) return [];
|
||||
if (Array.isArray(responseActions)) return responseActions;
|
||||
return [
|
||||
responseActions.confirm && { ...responseActions.confirm, id: "confirm" },
|
||||
responseActions.cancel && { ...responseActions.cancel, id: "cancel" },
|
||||
].filter(Boolean) as Action[];
|
||||
}, [responseActions]);
|
||||
|
||||
const TodoList: FC<{ items: typeof todos }> = ({ items }) => {
|
||||
return (
|
||||
<div className="space-y-0">
|
||||
{items.map((todo) => (
|
||||
<TodoItem key={todo.id} todo={todo} isStreaming={isStreaming} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<Card id={id} className={cn("w-full max-w-xl", className)}>
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="flex-1 min-w-0 flex items-center gap-2">
|
||||
<ListTodo className="size-5 text-muted-foreground shrink-0" />
|
||||
<CardTitle className="text-base font-semibold text-muted-foreground">{title}</CardTitle>
|
||||
</div>
|
||||
{isAllComplete && (
|
||||
<div className="flex items-center gap-1 text-emerald-500">
|
||||
<PartyPopper className="size-5" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{showProgress && (
|
||||
<div className="mt-3 space-y-1.5">
|
||||
<div className="flex items-center justify-between text-xs text-muted-foreground">
|
||||
<span>
|
||||
{progress.completed} of {progress.total} complete
|
||||
</span>
|
||||
<span>{Math.round(progress.percentage)}%</span>
|
||||
</div>
|
||||
<Progress
|
||||
value={progress.percentage}
|
||||
className="h-1.5 bg-muted [&>div]:bg-muted-foreground"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="pt-0">
|
||||
<TodoList items={visibleTodos} />
|
||||
|
||||
{hasHiddenTodos && (
|
||||
<Collapsible open={isExpanded} onOpenChange={setIsExpanded}>
|
||||
<CollapsibleTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="w-full mt-2 text-xs text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{isExpanded
|
||||
? "Show less"
|
||||
: `Show ${hiddenTodos.length} more ${hiddenTodos.length === 1 ? "task" : "tasks"}`}
|
||||
</Button>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent>
|
||||
<TodoList items={hiddenTodos} />
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
)}
|
||||
|
||||
{actionArray.length > 0 && (
|
||||
<div className="flex flex-wrap gap-2 pt-4 mt-2 border-t">
|
||||
{actionArray.map((action) => (
|
||||
<Button
|
||||
key={action.id}
|
||||
variant={action.variant || "default"}
|
||||
size="sm"
|
||||
disabled={action.disabled}
|
||||
onClick={() => handleAction(action.id)}
|
||||
>
|
||||
{action.label}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
91
surfsense_web/components/tool-ui/plan/schema.ts
Normal file
91
surfsense_web/components/tool-ui/plan/schema.ts
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
import { z } from "zod";
|
||||
|
||||
/**
|
||||
* Todo item status
|
||||
*/
|
||||
export const TodoStatusSchema = z.enum(["pending", "in_progress", "completed", "cancelled"]);
|
||||
export type TodoStatus = z.infer<typeof TodoStatusSchema>;
|
||||
|
||||
/**
|
||||
* Single todo item in a plan
|
||||
* Matches deepagents TodoListMiddleware output: { content, status }
|
||||
* id is auto-generated if not provided
|
||||
*/
|
||||
export const PlanTodoSchema = z.object({
|
||||
id: z.string().optional(),
|
||||
content: z.string(),
|
||||
status: TodoStatusSchema,
|
||||
});
|
||||
|
||||
export type PlanTodo = z.infer<typeof PlanTodoSchema>;
|
||||
|
||||
/**
|
||||
* Serializable plan schema for tool results
|
||||
* Matches deepagents TodoListMiddleware output format
|
||||
* id/title are auto-generated if not provided
|
||||
*/
|
||||
export const SerializablePlanSchema = z.object({
|
||||
id: z.string().optional(),
|
||||
title: z.string().optional(),
|
||||
todos: z.array(PlanTodoSchema).min(1),
|
||||
maxVisibleTodos: z.number().optional(),
|
||||
showProgress: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export type SerializablePlan = z.infer<typeof SerializablePlanSchema>;
|
||||
|
||||
/**
|
||||
* Normalized plan with required fields (after auto-generation)
|
||||
*/
|
||||
export interface NormalizedPlan {
|
||||
id: string;
|
||||
title: string;
|
||||
todos: Array<{ id: string; content: string; status: TodoStatus }>;
|
||||
maxVisibleTodos?: number;
|
||||
showProgress?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse and normalize a plan from tool result
|
||||
* Auto-generates id/title if not provided (for deepagents compatibility)
|
||||
*/
|
||||
export function parseSerializablePlan(data: unknown): NormalizedPlan {
|
||||
const result = SerializablePlanSchema.safeParse(data);
|
||||
|
||||
if (!result.success) {
|
||||
console.warn("Invalid plan data:", result.error.issues);
|
||||
|
||||
// Try to extract basic info for fallback
|
||||
const obj = (data && typeof data === "object" ? data : {}) as Record<string, unknown>;
|
||||
|
||||
return {
|
||||
id: typeof obj.id === "string" ? obj.id : `plan-${Date.now()}`,
|
||||
title: typeof obj.title === "string" ? obj.title : "Plan",
|
||||
todos: Array.isArray(obj.todos)
|
||||
? obj.todos.map((t: unknown, i: number) => {
|
||||
const todo = t as Record<string, unknown>;
|
||||
return {
|
||||
id: typeof todo?.id === "string" ? todo.id : `todo-${i}`,
|
||||
content: typeof todo?.content === "string" ? todo.content : "Task",
|
||||
status: TodoStatusSchema.safeParse(todo?.status).success
|
||||
? (todo.status as TodoStatus)
|
||||
: ("pending" as const),
|
||||
};
|
||||
})
|
||||
: [{ id: "1", content: "No tasks", status: "pending" as const }],
|
||||
};
|
||||
}
|
||||
|
||||
// Normalize: add id/title if missing
|
||||
return {
|
||||
id: result.data.id || `plan-${Date.now()}`,
|
||||
title: result.data.title || "Plan",
|
||||
todos: result.data.todos.map((t, i) => ({
|
||||
id: t.id || `todo-${i}`,
|
||||
content: t.content,
|
||||
status: t.status,
|
||||
})),
|
||||
maxVisibleTodos: result.data.maxVisibleTodos,
|
||||
showProgress: result.data.showProgress,
|
||||
};
|
||||
}
|
||||
|
|
@ -2,6 +2,7 @@
|
|||
|
||||
import { makeAssistantToolUI } from "@assistant-ui/react";
|
||||
import { AlertCircleIcon, FileTextIcon } from "lucide-react";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
Article,
|
||||
ArticleErrorBoundary,
|
||||
|
|
@ -9,30 +10,44 @@ import {
|
|||
parseSerializableArticle,
|
||||
} from "@/components/tool-ui/article";
|
||||
|
||||
/**
|
||||
* Type definitions for the scrape_webpage tool
|
||||
*/
|
||||
interface ScrapeWebpageArgs {
|
||||
url: string;
|
||||
max_length?: number;
|
||||
}
|
||||
// ============================================================================
|
||||
// Zod Schemas
|
||||
// ============================================================================
|
||||
|
||||
interface ScrapeWebpageResult {
|
||||
id: string;
|
||||
assetId: string;
|
||||
kind: "article";
|
||||
href: string;
|
||||
title: string;
|
||||
description?: string;
|
||||
content?: string;
|
||||
domain?: string;
|
||||
author?: string;
|
||||
date?: string;
|
||||
word_count?: number;
|
||||
was_truncated?: boolean;
|
||||
crawler_type?: string;
|
||||
error?: string;
|
||||
}
|
||||
/**
|
||||
* Schema for scrape_webpage tool arguments
|
||||
*/
|
||||
const ScrapeWebpageArgsSchema = z.object({
|
||||
url: z.string(),
|
||||
max_length: z.number().nullish(),
|
||||
});
|
||||
|
||||
/**
|
||||
* Schema for scrape_webpage tool result
|
||||
*/
|
||||
const ScrapeWebpageResultSchema = z.object({
|
||||
id: z.string(),
|
||||
assetId: z.string(),
|
||||
kind: z.literal("article"),
|
||||
href: z.string(),
|
||||
title: z.string(),
|
||||
description: z.string().nullish(),
|
||||
content: z.string().nullish(),
|
||||
domain: z.string().nullish(),
|
||||
author: z.string().nullish(),
|
||||
date: z.string().nullish(),
|
||||
word_count: z.number().nullish(),
|
||||
was_truncated: z.boolean().nullish(),
|
||||
crawler_type: z.string().nullish(),
|
||||
error: z.string().nullish(),
|
||||
});
|
||||
|
||||
// ============================================================================
|
||||
// Types
|
||||
// ============================================================================
|
||||
|
||||
type ScrapeWebpageArgs = z.infer<typeof ScrapeWebpageArgsSchema>;
|
||||
type ScrapeWebpageResult = z.infer<typeof ScrapeWebpageResultSchema>;
|
||||
|
||||
/**
|
||||
* Error state component shown when webpage scraping fails
|
||||
|
|
@ -154,4 +169,9 @@ export const ScrapeWebpageToolUI = makeAssistantToolUI<ScrapeWebpageArgs, Scrape
|
|||
},
|
||||
});
|
||||
|
||||
export type { ScrapeWebpageArgs, ScrapeWebpageResult };
|
||||
export {
|
||||
ScrapeWebpageArgsSchema,
|
||||
ScrapeWebpageResultSchema,
|
||||
type ScrapeWebpageArgs,
|
||||
type ScrapeWebpageResult,
|
||||
};
|
||||
|
|
|
|||
41
surfsense_web/components/tool-ui/shared/action-buttons.tsx
Normal file
41
surfsense_web/components/tool-ui/shared/action-buttons.tsx
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
"use client";
|
||||
|
||||
import type { FC } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import type { Action, ActionsConfig } from "./schema";
|
||||
|
||||
interface ActionButtonsProps {
|
||||
actions?: Action[] | ActionsConfig;
|
||||
onAction?: (actionId: string) => void;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export const ActionButtons: FC<ActionButtonsProps> = ({ actions, onAction, disabled }) => {
|
||||
if (!actions) return null;
|
||||
|
||||
// Normalize actions to array format
|
||||
const actionArray: Action[] = Array.isArray(actions)
|
||||
? actions
|
||||
: ([
|
||||
actions.confirm && { ...actions.confirm, id: "confirm" },
|
||||
actions.cancel && { ...actions.cancel, id: "cancel" },
|
||||
].filter(Boolean) as Action[]);
|
||||
|
||||
if (actionArray.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap gap-2 pt-3">
|
||||
{actionArray.map((action) => (
|
||||
<Button
|
||||
key={action.id}
|
||||
variant={action.variant || "default"}
|
||||
size="sm"
|
||||
disabled={disabled || action.disabled}
|
||||
onClick={() => onAction?.(action.id)}
|
||||
>
|
||||
{action.label}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
2
surfsense_web/components/tool-ui/shared/index.ts
Normal file
2
surfsense_web/components/tool-ui/shared/index.ts
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
export * from "./action-buttons";
|
||||
export * from "./schema";
|
||||
23
surfsense_web/components/tool-ui/shared/schema.ts
Normal file
23
surfsense_web/components/tool-ui/shared/schema.ts
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
import { z } from "zod";
|
||||
|
||||
/**
|
||||
* Shared action schema for tool UI components
|
||||
*/
|
||||
export const ActionSchema = z.object({
|
||||
id: z.string(),
|
||||
label: z.string(),
|
||||
variant: z.enum(["default", "secondary", "destructive", "outline", "ghost", "link"]).optional(),
|
||||
disabled: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export type Action = z.infer<typeof ActionSchema>;
|
||||
|
||||
/**
|
||||
* Actions configuration schema
|
||||
*/
|
||||
export const ActionsConfigSchema = z.object({
|
||||
confirm: ActionSchema.optional(),
|
||||
cancel: ActionSchema.optional(),
|
||||
});
|
||||
|
||||
export type ActionsConfig = z.infer<typeof ActionsConfigSchema>;
|
||||
158
surfsense_web/components/tool-ui/write-todos.tsx
Normal file
158
surfsense_web/components/tool-ui/write-todos.tsx
Normal file
|
|
@ -0,0 +1,158 @@
|
|||
"use client";
|
||||
|
||||
import { makeAssistantToolUI, useAssistantState } from "@assistant-ui/react";
|
||||
import { useAtomValue, useSetAtom } from "jotai";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { useEffect, useMemo } from "react";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
getCanonicalPlanTitle,
|
||||
planStatesAtom,
|
||||
registerPlanOwner,
|
||||
updatePlanStateAtom,
|
||||
} from "@/atoms/chat/plan-state.atom";
|
||||
import { Plan, PlanErrorBoundary, parseSerializablePlan, TodoStatusSchema } from "./plan";
|
||||
|
||||
// ============================================================================
|
||||
// Zod Schemas - Matching deepagents TodoListMiddleware output
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Schema for a single todo item (matches deepagents output)
|
||||
*/
|
||||
const TodoItemSchema = z.object({
|
||||
content: z.string(),
|
||||
status: TodoStatusSchema,
|
||||
});
|
||||
|
||||
/**
|
||||
* Schema for write_todos tool args/result (matches deepagents output)
|
||||
* deepagents provides: { todos: [{ content, status }] }
|
||||
*/
|
||||
const WriteTodosSchema = z.object({
|
||||
todos: z.array(TodoItemSchema).nullish(),
|
||||
});
|
||||
|
||||
// ============================================================================
|
||||
// Types
|
||||
// ============================================================================
|
||||
|
||||
type WriteTodosData = z.infer<typeof WriteTodosSchema>;
|
||||
|
||||
/**
|
||||
* Loading state component
|
||||
*/
|
||||
function WriteTodosLoading() {
|
||||
return (
|
||||
<div className="my-4 w-full max-w-xl rounded-2xl border bg-card/60 px-5 py-4 shadow-sm">
|
||||
<div className="flex items-center gap-3">
|
||||
<Loader2 className="size-5 animate-spin text-primary" />
|
||||
<span className="text-sm text-muted-foreground">Creating plan...</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* WriteTodos Tool UI Component
|
||||
*
|
||||
* Displays the agent's planning/todo list with a beautiful UI.
|
||||
* Uses deepagents TodoListMiddleware output directly: { todos: [{ content, status }] }
|
||||
*
|
||||
* FIXED POSITION: When multiple write_todos calls happen in a conversation,
|
||||
* only the FIRST component renders. Subsequent updates just update the
|
||||
* shared state, and the first component reads from it.
|
||||
*/
|
||||
export const WriteTodosToolUI = makeAssistantToolUI<WriteTodosData, WriteTodosData>({
|
||||
toolName: "write_todos",
|
||||
render: function WriteTodosUI({ args, result, status, toolCallId }) {
|
||||
const updatePlanState = useSetAtom(updatePlanStateAtom);
|
||||
const planStates = useAtomValue(planStatesAtom);
|
||||
|
||||
// Check if the THREAD is running
|
||||
const isThreadRunning = useAssistantState(({ thread }) => thread.isRunning);
|
||||
|
||||
// Use result if available, otherwise args (for streaming)
|
||||
const data = result || args;
|
||||
const hasTodos = data?.todos && data.todos.length > 0;
|
||||
|
||||
// Fixed title for all plans in conversation
|
||||
const planTitle = "Plan";
|
||||
|
||||
// SYNCHRONOUS ownership check
|
||||
const isOwner = useMemo(() => {
|
||||
return registerPlanOwner(planTitle, toolCallId);
|
||||
}, [planTitle, toolCallId]);
|
||||
|
||||
// Get canonical title
|
||||
const canonicalTitle = useMemo(() => getCanonicalPlanTitle(planTitle), [planTitle]);
|
||||
|
||||
// Register/update the plan state
|
||||
useEffect(() => {
|
||||
if (hasTodos) {
|
||||
const normalizedPlan = parseSerializablePlan({ todos: data.todos });
|
||||
updatePlanState({
|
||||
id: normalizedPlan.id,
|
||||
title: canonicalTitle,
|
||||
todos: normalizedPlan.todos,
|
||||
toolCallId,
|
||||
});
|
||||
}
|
||||
}, [data, hasTodos, canonicalTitle, updatePlanState, toolCallId]);
|
||||
|
||||
// Get the current plan state
|
||||
const currentPlanState = planStates.get(canonicalTitle);
|
||||
|
||||
// If we're NOT the owner, render nothing
|
||||
if (!isOwner) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Loading state
|
||||
if (status.type === "running" || status.type === "requires-action") {
|
||||
if (hasTodos) {
|
||||
const plan = parseSerializablePlan({ todos: data.todos });
|
||||
return (
|
||||
<div className="my-4">
|
||||
<PlanErrorBoundary>
|
||||
<Plan {...plan} showProgress={true} isStreaming={isThreadRunning} />
|
||||
</PlanErrorBoundary>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return <WriteTodosLoading />;
|
||||
}
|
||||
|
||||
// Incomplete/cancelled state
|
||||
if (status.type === "incomplete") {
|
||||
if (currentPlanState || hasTodos) {
|
||||
const plan = currentPlanState || parseSerializablePlan({ todos: data?.todos || [] });
|
||||
return (
|
||||
<div className="my-4">
|
||||
<PlanErrorBoundary>
|
||||
<Plan {...plan} showProgress={true} isStreaming={isThreadRunning} />
|
||||
</PlanErrorBoundary>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Success - render the plan
|
||||
const planToRender =
|
||||
currentPlanState || (hasTodos ? parseSerializablePlan({ todos: data.todos }) : null);
|
||||
if (!planToRender) {
|
||||
return <WriteTodosLoading />;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="my-4">
|
||||
<PlanErrorBoundary>
|
||||
<Plan {...planToRender} showProgress={true} isStreaming={isThreadRunning} />
|
||||
</PlanErrorBoundary>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
export { WriteTodosSchema, type WriteTodosData };
|
||||
|
|
@ -449,7 +449,7 @@ function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
|
|||
}
|
||||
|
||||
const sidebarMenuButtonVariants = cva(
|
||||
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-hidden ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-hidden ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue