import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react"; import { motion, useSpring, useTransform } from "motion/react"; import { useTranslation } from "react-i18next"; import { canvasThemes } from "@/lib/canvas-theme"; import { summarizeCanvasAgentOps } from "@/lib/canvas/canvas-agent-ops"; import { useAgentStore, type AgentChatItem, type AgentPendingApproval, type AgentPendingToolCall, type AgentTokenUsage } from "@/stores/use-agent-store"; import { AgentApprovalCard, AgentChatMessage, AgentCommandGroup, AgentPendingToolCard, AgentToolCard, AgentWorkingMessage } from "./agent-chat-message"; import { agentMessageToChatMessage, currentPlanMessage, isPlanMessage, latestPlanMessage, toolCallDetail, toolName, workingActivity } from "./agent-event-formatters"; import { AgentScrollToBottom } from "./agent-scroll-to-bottom"; const SCROLL_BOTTOM_THRESHOLD = 48; const historyMessageStyle = { contentVisibility: "auto", containIntrinsicSize: "0 80px" } as const; export function AgentChatTimeline({ theme, pendingTool, pendingApprovals, sending, waiting, onRejectTool, onApproveTool, onApprovalDecision, }: { theme: (typeof canvasThemes)[keyof typeof canvasThemes]; pendingTool: AgentPendingToolCall | null; pendingApprovals: AgentPendingApproval[]; sending: boolean; waiting: boolean; onRejectTool: () => void; onApproveTool: () => void; onApprovalDecision: (approval: AgentPendingApproval, decision: "accept" | "acceptForSession" | "decline") => void; }) { const { t } = useTranslation(); const messages = useAgentStore((state) => state.messages); const bootstrapStatus = useAgentStore((state) => state.bootstrapStatus); const mcpStartupStatuses = useAgentStore((state) => state.mcpStartupStatuses); const timeline = useMemo(() => groupTimelineMessages(messages), [messages]); const listRef = useRef(null); const contentRef = useRef(null); const followMessagesRef = useRef(true); const [showScrollToBottom, setShowScrollToBottom] = useState(false); const streaming = messages.some((message) => message.streamId); const showBootstrap = Boolean(bootstrapStatus && !messages.some((message) => message.role === "user" || message.role === "assistant")); const working = showBootstrap ? bootstrapStatus! : workingActivity(messages.at(-1)); const updateScrollState = useCallback(() => { const list = listRef.current; if (!list) return; const atBottom = list.scrollHeight - list.scrollTop - list.clientHeight <= SCROLL_BOTTOM_THRESHOLD; followMessagesRef.current = atBottom; setShowScrollToBottom(!atBottom); }, []); const scrollToBottom = useCallback((behavior: ScrollBehavior = "smooth") => { const list = listRef.current; if (!list) return; followMessagesRef.current = true; list.scrollTo({ top: list.scrollHeight, behavior }); setShowScrollToBottom(false); }, []); useEffect(() => { const frame = requestAnimationFrame(() => (followMessagesRef.current ? scrollToBottom("auto") : updateScrollState())); return () => cancelAnimationFrame(frame); }, [messages, pendingApprovals, pendingTool, scrollToBottom, updateScrollState, waiting]); useEffect(() => { const content = contentRef.current; if (!content) return; let frame = 0; const observer = new ResizeObserver(() => { cancelAnimationFrame(frame); frame = requestAnimationFrame(() => (followMessagesRef.current ? scrollToBottom("auto") : updateScrollState())); }); observer.observe(content); return () => { observer.disconnect(); cancelAnimationFrame(frame); }; }, [scrollToBottom, updateScrollState]); return (
{timeline.map((entry) => entry.type === "commands" ? : )} {pendingTool ? ( ) : null} {pendingApprovals.map((approval) => onApprovalDecision(approval, decision)} />)} {(sending || waiting || showBootstrap) && !streaming && !pendingTool && !pendingApprovals.length ? ({ name, ...item })) : []} activityKey={working.key} theme={theme} /> : null}
{showScrollToBottom ? ( scrollToBottom()} /> ) : null}
); } export function AgentTaskProgress({ theme, busy }: { theme: (typeof canvasThemes)[keyof typeof canvasThemes]; busy: boolean }) { const { t } = useTranslation(); const plan = useAgentStore((state) => busy ? currentPlanMessage(state.messages) : latestPlanMessage(state.messages)); if (!plan) return null; return (
); } const AgentChatMessageRow = memo(function AgentChatMessageRow({ item, theme }: { item: AgentChatItem; theme: (typeof canvasThemes)[keyof typeof canvasThemes] }) { return (
); }); const AgentCommandGroupRow = memo(function AgentCommandGroupRow({ items, theme }: { items: AgentChatItem[]; theme: (typeof canvasThemes)[keyof typeof canvasThemes] }) { return (
item.streamId) ? undefined : historyMessageStyle}>
); }); type AgentTimelineEntry = { type: "message"; item: AgentChatItem } | { type: "commands"; id: string; items: AgentChatItem[] }; function groupTimelineMessages(messages: AgentChatItem[]) { const timeline: AgentTimelineEntry[] = []; let commands: AgentChatItem[] = []; let commandScope = ""; const flushCommands = () => { if (!commands.length) return; timeline.push({ type: "commands", id: `commands:${commands[0].id}`, items: commands }); commands = []; commandScope = ""; }; messages.forEach((item) => { if (isPlanMessage(item)) return; if (isCommandMessage(item)) { const scope = item.threadId && item.turnId ? `${item.threadId}\0${item.turnId}` : item.id; if (commands.length && scope !== commandScope) flushCommands(); commands.push(item); commandScope = scope; return; } flushCommands(); timeline.push({ type: "message", item }); }); flushCommands(); return timeline; } function isCommandMessage(item: AgentChatItem) { return item.role === "tool" && item.detail && typeof item.detail === "object" && (item.detail as { kind?: unknown }).kind === "command"; } export function AgentUsageBar({ usage, theme }: { usage: AgentTokenUsage; theme: (typeof canvasThemes)[keyof typeof canvasThemes] }) { const { t } = useTranslation(); return (
{t("agent.chat.latestCall")}
); } function UsageNumber({ label, value, color }: { label: string; value: number; color: string }) { const spring = useSpring(value, { stiffness: 110, damping: 24, mass: 0.7 }); const text = useTransform(spring, (current) => Math.round(current).toLocaleString()); useEffect(() => spring.set(value), [spring, value]); return ( {label} {text} ); }