fix(agent): unify live and historical conversation state

This commit is contained in:
yu
2026-08-01 22:11:05 +08:00
parent ee5804e586
commit ea0414e88c
24 changed files with 3245 additions and 575 deletions
+75 -17
View File
@@ -1,10 +1,10 @@
import { memo, useCallback, useEffect, useRef, useState } from "react";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { motion, useSpring, useTransform } from "motion/react";
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, AgentPendingToolCard, AgentToolCard, AgentWorkingMessage } from "./agent-chat-message";
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";
@@ -31,7 +31,9 @@ export function AgentChatTimeline({
onApprovalDecision: (approval: AgentPendingApproval, decision: "accept" | "acceptForSession" | "decline") => void;
}) {
const messages = useAgentStore((state) => state.messages);
const timeline = useMemo(() => groupTimelineMessages(messages), [messages]);
const listRef = useRef<HTMLDivElement>(null);
const contentRef = useRef<HTMLDivElement>(null);
const followMessagesRef = useRef(true);
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
const streaming = messages.some((message) => message.streamId);
@@ -54,23 +56,39 @@ export function AgentChatTimeline({
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 (
<div className="relative min-h-0 flex-1">
<div ref={listRef} className="thin-scrollbar h-full select-text space-y-4 overflow-y-auto px-4 pt-4" onScroll={updateScrollState}>
{messages.map((item) => (
isPlanMessage(item) ? null : <AgentChatMessageRow key={item.id} item={item} theme={theme} />
))}
{pendingTool ? (
<AgentPendingToolCard
summary={summarizeCanvasAgentOps(pendingTool.input?.ops || []) || toolName(pendingTool.name)}
detail={toolCallDetail(pendingTool.name, pendingTool.input, "pending")}
theme={theme}
onReject={onRejectTool}
onApprove={onApproveTool}
/>
) : null}
{pendingApprovals.map((approval) => <AgentApprovalCard key={approval.requestId} approval={approval} theme={theme} onDecision={(decision) => onApprovalDecision(approval, decision)} />)}
{(sending || waiting) && !streaming && !pendingTool && !pendingApprovals.length ? <AgentWorkingMessage text={working.text} activityKey={working.key} theme={theme} /> : null}
<div ref={listRef} className="thin-scrollbar h-full select-text overflow-y-auto" onScroll={updateScrollState}>
<div ref={contentRef} className="space-y-4 px-4 pt-4">
{timeline.map((entry) => entry.type === "commands"
? <AgentCommandGroupRow key={entry.id} items={entry.items} theme={theme} />
: <AgentChatMessageRow key={entry.item.id} item={entry.item} theme={theme} />)}
{pendingTool ? (
<AgentPendingToolCard
summary={summarizeCanvasAgentOps(pendingTool.input?.ops || []) || toolName(pendingTool.name)}
detail={toolCallDetail(pendingTool.name, pendingTool.input, "pending")}
theme={theme}
onReject={onRejectTool}
onApprove={onApproveTool}
/>
) : null}
{pendingApprovals.map((approval) => <AgentApprovalCard key={approval.requestId} approval={approval} theme={theme} onDecision={(decision) => onApprovalDecision(approval, decision)} />)}
{(sending || waiting) && !streaming && !pendingTool && !pendingApprovals.length ? <AgentWorkingMessage text={working.text} activityKey={working.key} theme={theme} /> : null}
</div>
</div>
{showScrollToBottom ? (
<AgentScrollToBottom theme={theme} title="查看最新消息" onClick={() => scrollToBottom()} />
@@ -97,6 +115,46 @@ const AgentChatMessageRow = memo(function AgentChatMessageRow({ item, theme }: {
);
});
const AgentCommandGroupRow = memo(function AgentCommandGroupRow({ items, theme }: { items: AgentChatItem[]; theme: (typeof canvasThemes)[keyof typeof canvasThemes] }) {
return (
<div style={items.some((item) => item.streamId) ? undefined : historyMessageStyle}>
<AgentCommandGroup items={items} theme={theme} />
</div>
);
});
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] }) {
return (
<div className="flex items-center justify-center gap-4 px-4 pt-1 text-[11px] tabular-nums" style={{ color: theme.node.muted }}>