Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions packages/desktop/src/agent/AgentSidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,14 @@ export default function AgentSidebar() {
const [projectMenuOpen, setProjectMenuOpen] = useState(false);
const [hoveredThreadId, setHoveredThreadId] = useState<string | null>(null);

const rawThreads = useAgentStore((s) => s.threads);
const threadListVersion = useAgentStore((s) => s.threadListVersion);
const threadList = useMemo(() => {
const normalizedRoot = normalizeCwd(rootPath);
return Object.values(rawThreads)
return Object.values(useAgentStore.getState().threads)
.filter((t) => normalizeCwd(t.cwd).startsWith(normalizedRoot))
.map((t) => ({ id: t.id, title: t.title, cwd: t.cwd, updatedAt: t.updatedAt }))
.sort((a, b) => b.updatedAt - a.updatedAt);
}, [rawThreads, rootPath]);
}, [threadListVersion, rootPath]);

const currentProject = workspace.projects.find((p) => p.id === workspace.currentProjectId);
const projectName = currentProject?.name || workspace.name || '项目';
Expand Down
90 changes: 70 additions & 20 deletions packages/desktop/src/agent/MessageStream.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,51 @@ interface MessageStreamProps {

const EMPTY_MAPPING: Record<number, string> = {};

interface MessageEntryProps {
threadId: string;
turnId: string;
item: Item;
cwd: string;
onApprove: (threadId: string, callId: string) => void;
onReject: (threadId: string, callId: string) => void;
callIdToToolName: Record<string, string>;
onRollbackHere?: () => void;
onForkFromHere?: () => void;
toolResult?: Item & { type: 'tool_result' };
}

function StreamingMessageEntry({
threadId,
turnId,
item,
cwd,
onApprove,
onReject,
callIdToToolName,
onRollbackHere,
onForkFromHere,
toolResult,
}: MessageEntryProps) {
const currentItem = useAgentStore((state) => {
const turn = state.threads[threadId]?.turns.find((candidate) => candidate.id === turnId);
return turn?.items.find((candidate) => candidate.id === item.id) ?? item;
});

return (
<MessageItem
item={currentItem}
threadId={threadId}
cwd={cwd}
onApprove={onApprove}
onReject={onReject}
callIdToToolName={callIdToToolName}
onRollbackHere={onRollbackHere}
onForkFromHere={onForkFromHere}
toolResult={toolResult}
/>
);
}

interface TurnDiffPanelProps {
uiTurnId: string;
isInterrupted?: boolean;
Expand Down Expand Up @@ -258,15 +303,7 @@ export default function MessageStream({ threadId }: MessageStreamProps) {
.map(
(t) =>
`${t.id}:${t.status}:${t.items.length}:${t.items
.map((i) => {
const contentSize =
i.type === 'reasoning'
? i.content.length
: i.type === 'message'
? textOf(i.parts).length
: '';
return `${i.type}:${i.id}:${i.type === 'tool_call' ? i.status : ''}:${contentSize}`;
})
.map((i) => `${i.type}:${i.id}:${i.type === 'tool_call' ? i.status : ''}`)
.join(',')}`
)
.join('|'),
Expand Down Expand Up @@ -618,17 +655,30 @@ export default function MessageStream({ threadId }: MessageStreamProps) {
{entry.toolCalls ? (
<ToolCallGroup entries={entry.toolCalls} />
) : entry.item ? (
<MessageItem
item={entry.item}
threadId={threadId}
cwd={threadCwd}
onApprove={approveTool}
onReject={rejectTool}
callIdToToolName={callIdToToolName}
onRollbackHere={isUserMsg && cbs ? cbs.onRollbackHere : undefined}
onForkFromHere={isUserMsg && cbs ? cbs.onForkFromHere : undefined}
toolResult={entry.toolResult}
/>
(() => {
const isStreamingItem =
(entry.item.type === 'message' &&
entry.item.role === 'assistant' &&
entry.item.partial === true) ||
(entry.item.type === 'reasoning' && entry.item.partial === true);
const props = {
turnId: entry.turnId,
item: entry.item,
threadId,
cwd: threadCwd,
onApprove: approveTool,
onReject: rejectTool,
callIdToToolName,
onRollbackHere: isUserMsg && cbs ? cbs.onRollbackHere : undefined,
onForkFromHere: isUserMsg && cbs ? cbs.onForkFromHere : undefined,
toolResult: entry.toolResult,
};
return isStreamingItem ? (
<StreamingMessageEntry {...props} />
) : (
<MessageItem {...props} />
);
})()
) : null}
</div>
{isLastInTurn &&
Expand Down
32 changes: 31 additions & 1 deletion packages/desktop/src/hooks/useAgent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ export function useAgentCore() {
const sendQueuedInputRef = useRef<((threadId: string) => Promise<void>) | null>(null);
const startTurn = useAgentStore((s) => s.startTurn);
const applyChunk = useAgentStore((s) => s.applyChunk);
const applyChunks = useAgentStore((s) => s.applyChunks);
const updateTurnId = useAgentStore((s) => s.updateTurnId);
const completeTurn = useAgentStore((s) => s.completeTurn);
const setPendingInput = useAgentStore((s) => s.setPendingInput);
Expand Down Expand Up @@ -228,8 +229,33 @@ export function useAgentCore() {
if (!opts.preRegistered) registerInflight(threadId, controller);

const state = createStreamState(randomId());
const pendingChunks: Array<{ turnId: string; chunk: Item }> = [];
let flushScheduled = false;

const flushPending = () => {
flushScheduled = false;
if (pendingChunks.length === 0) return;
const updates = pendingChunks.splice(0, pendingChunks.length);
applyChunks(threadId, updates);
};

const scheduleFlush = () => {
if (flushScheduled) return;
flushScheduled = true;
if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') {
window.requestAnimationFrame(flushPending);
} else {
setTimeout(flushPending, 16);
}
};

const enqueueItem = (item: Item) => {
pendingChunks.push({ turnId: activeTurnId, chunk: item });
scheduleFlush();
};

const fx: StreamEffects = {
applyItem: (item) => applyChunk(threadId, activeTurnId, item),
applyItem: enqueueItem,
applyTodo: (items) => applyTodoUpdate(threadId, items),
setUsage: (usage) => {
setThreadUsage(threadId, usage);
Expand All @@ -241,6 +267,7 @@ export function useAgentCore() {
useAgentStore.getState().clearThreadUsage(threadId);
},
syncTurnId: (turnId) => {
flushPending();
const next = String(turnId);
updateTurnId(threadId, activeTurnId, next);
activeTurnId = next;
Expand All @@ -267,8 +294,10 @@ export function useAgentCore() {
} catch (err: any) {
failed = true;
const msg = err instanceof ApiError ? (err.body?.message ?? err.message) : String(err);
flushPending();
applyChunk(threadId, activeTurnId, { id: randomId(), type: 'error', message: msg });
} finally {
flushPending();
completeTurn(threadId, activeTurnId, failed || state.hasError ? 'error' : 'completed');
if (!failed && !state.hasError && state.planTitle !== null) {
setPendingPlan(threadId, { sessionId: threadId, title: state.planTitle });
Expand All @@ -281,6 +310,7 @@ export function useAgentCore() {
[
startTurn,
applyChunk,
applyChunks,
applyTodoUpdate,
completeTurn,
setPendingPlan,
Expand Down
24 changes: 16 additions & 8 deletions packages/desktop/src/shared/MarkdownRenderer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,16 @@ import remarkGfm from 'remark-gfm';
import rehypeRaw from 'rehype-raw';
import CodeBlock from './CodeBlock';

const REMARK_PLUGINS = [remarkGfm];
const REHYPE_PLUGINS = [rehypeRaw];

interface MarkdownRendererProps {
content: string;
className?: string;
partial?: boolean;
}

export default function MarkdownRenderer({ content, className }: MarkdownRendererProps) {
export default function MarkdownRenderer({ content, className, partial = false }: MarkdownRendererProps) {
const components = useMemo(
() => ({
code(props: React.HTMLAttributes<HTMLElement> & { inline?: boolean }) {
Expand Down Expand Up @@ -72,13 +76,17 @@ export default function MarkdownRenderer({ content, className }: MarkdownRendere

return (
<div className={`markdown-body ${className || ''}`}>
<ReactMarkdown
remarkPlugins={[remarkGfm]}
rehypePlugins={[rehypeRaw]}
components={components}
>
{content}
</ReactMarkdown>
{partial ? (
<div className="whitespace-pre-wrap break-words">{content}</div>
) : (
<ReactMarkdown
remarkPlugins={REMARK_PLUGINS}
rehypePlugins={REHYPE_PLUGINS}
components={components}
>
{content}
</ReactMarkdown>
)}
</div>
);
}
2 changes: 1 addition & 1 deletion packages/desktop/src/shared/MessageItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ const MessageItem = memo(function MessageItem({
<div className="cc-message-assistant flex flex-col items-start mb-1 pl-8 group">
{text && (
<div className="max-w-[80%] text-[15px] text-[var(--text-primary)] leading-relaxed">
<MarkdownRenderer content={text} />
<MarkdownRenderer content={text} partial={item.partial === true} />
{item.partial && (
<span className="inline-block w-1.5 h-[1.1em] bg-[var(--accent-primary)] animate-pulse ml-0.5 align-middle" />
)}
Expand Down
8 changes: 5 additions & 3 deletions packages/desktop/src/shared/ToolCallGroup.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useState } from 'react';
import { memo, useState } from 'react';
import { ChevronDown, ChevronRight, Wrench } from 'lucide-react';
import type { Item } from '@shared/types';
import ToolSummary from './ToolSummary';
Expand All @@ -14,7 +14,7 @@ function statusLabel(entries: ToolCallEntry[]): string {
return '已完成';
}

export default function ToolCallGroup({ entries }: { entries: ToolCallEntry[] }) {
const ToolCallGroup = memo(function ToolCallGroup({ entries }: { entries: ToolCallEntry[] }) {
const [open, setOpen] = useState(false);
if (entries.length === 1) return <ToolSummary toolCall={entries[0]!.item} toolResult={entries[0]!.toolResult} />;
const status = statusLabel(entries);
Expand Down Expand Up @@ -48,4 +48,6 @@ export default function ToolCallGroup({ entries }: { entries: ToolCallEntry[] })
)}
</div>
);
}
});

export default ToolCallGroup;
8 changes: 5 additions & 3 deletions packages/desktop/src/shared/ToolSummary.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useState, useMemo } from 'react';
import { memo, useState, useMemo } from 'react';
import { ChevronRight, ChevronDown, FilePenLine, FileText, Folder, Globe, Search, Terminal, Wrench } from 'lucide-react';
import type { Item } from '@shared/types';
import { buildToolDiff } from '../lib/diff-compute';
Expand Down Expand Up @@ -113,7 +113,7 @@ export function buildToolSummaryTitle(
};
}

export default function ToolSummary({ toolCall, toolResult }: ToolSummaryProps) {
const ToolSummary = memo(function ToolSummary({ toolCall, toolResult }: ToolSummaryProps) {
const [open, setOpen] = useState(false);
const isFileTool = toolCall.name === 'write_file' || toolCall.name === 'edit_file';

Expand Down Expand Up @@ -184,4 +184,6 @@ export default function ToolSummary({ toolCall, toolResult }: ToolSummaryProps)
)}
</div>
);
}
});

export default ToolSummary;
Loading
Loading