Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): reuse ready history during streaming text updates

MagicLiziafec6e7bfa46
diff --git a/apps/desktop/src/renderer/__tests__/streamingMessageProjection.test.ts b/apps/desktop/src/renderer/__tests__/streamingMessageProjection.test.ts
index 33f5bd2696..633841c4ae 100644
--- a/apps/desktop/src/renderer/__tests__/streamingMessageProjection.test.ts
+++ b/apps/desktop/src/renderer/__tests__/streamingMessageProjection.test.ts
@@ -1,12 +1,17 @@
import { describe, expect, it, vi } from 'vitest';
-import { buildRenderItems, groupWorkRuns } from '@/components/chat/MessageStream';
+import {
+ buildMessageStreamRenderProjection,
+ buildRenderItems,
+ groupWorkRuns,
+} from '@/components/chat/MessageStream';
+import { HistoryViewController, HistoryViewHandoff } from '@cindy/maker-shared/message-window';
import {
createMessageMetadataProjection,
createStreamingMessageProjection,
createWorkGroupProjection,
createStreamingWorkGroupProjection,
} from '@/components/chat/streamingMessageProjection';
-import type { ChatMessage } from '@/lib/makerChatStore';
+import type { ChatMessage, HistoryChatMessage } from '@/lib/makerChatStore';
import type { RenderItem } from '@/components/chat/messageWorkGroups';
function fixture(): ChatMessage[] {
@@ -32,6 +37,84 @@ function replaceTail(messages: ChatMessage[], change: Partial<ChatMessage>): Cha
}
describe('streaming history projection', () => {
+ // Unit regression for the 2026-10-21 input stalls: the ready-history path
+ // rebuilt all work groups on every text delta, bypassing the local cache.
+ // Existing cases only project raw rows. Use the production history boundary
+ // with one completed tool group and a live answer, including copied rows and
+ // authoritative timestamps, to protect both reuse and the displayed content.
+ it('reuses ready history across live text updates without losing history order or corrections', async () => {
+ let messages: HistoryChatMessage[] = fixture().map((message, index) => ({
+ ...message,
+ id: message.clientId,
+ createdAt: new Date(1_700_000_000_000 + index * 1000).toISOString(),
+ }));
+ let historyRows = messages;
+ const view = new HistoryViewController<HistoryChatMessage>({
+ page: async () => ({
+ version: 1,
+ items: [{ type: 'messages', key: 'history', messages: historyRows }],
+ hasMore: false,
+ nextCursor: null,
+ }),
+ details: async () => ({ version: 1, messages: [], hasMore: false, nextCursor: null }),
+ expanded: async () => undefined,
+ });
+ const historyProjection = createStreamingMessageProjection();
+ const handoff = new HistoryViewHandoff<HistoryChatMessage>(
+ (message) => message.isStreaming === true,
+ );
+ const generatedFilesItemCache = new Map<
+ string,
+ Extract<RenderItem, { type: 'generated_files' }>
+ >();
+ const render = (reuse = true) => {
+ const snapshot = view.getSnapshot();
+ // MessageStream normalizes live rows into new objects on every batch.
+ const live = messages.map((message) => ({ ...message }));
+ return buildMessageStreamRenderProjection({
+ historyView: view,
+ historySnapshot: snapshot,
+ historyLiveMessages: live,
+ handoff: handoff.reconcile(snapshot, live),
+ isSessionStreaming: true,
+ generatedFilesItemCache,
+ historyProjection: reuse ? historyProjection : undefined,
+ buildRaw: () => buildRenderItems(messages),
+ });
+ };
+ try {
+ await view.refresh();
+ const authoritativeTime = messages.at(-1)!.createdAt;
+ messages = messages.map((message, index) =>
+ index === messages.length - 1 ? { ...message, createdAt: '2026-10-21T00:00:00Z' } : message,
+ );
+ const first = render();
+ const completed = first.items.find((item) => item.type === 'work_group');
+ expect(completed).toBeDefined();
+ for (const content of ['Starting now', '# Delivery\n\n' + 'Text. '.repeat(400)]) {
+ messages = messages.map((message, index) =>
+ index === messages.length - 1 ? { ...message, content } : message,
+ );
+ const actual = render();
+ expect(actual).toEqual(render(false));
+ expect(actual.singleResultMap).toBe(first.singleResultMap);
+ expect(actual.items.find((item) => item.type === 'work_group')).toBe(completed);
+ expect(actual.items.at(-1)).toMatchObject({
+ message: { content, createdAt: authoritativeTime },
+ });
+ }
+ historyRows = historyRows.map((message) =>
+ message.clientId === 'r1' ? { ...message, content: 'corrected result' } : message,
+ );
+ await view.refresh();
+ const corrected = render();
+ expect(corrected).toEqual(render(false));
+ expect(corrected.items.find((item) => item.type === 'work_group')).not.toBe(completed);
+ } finally {
+ view.setActive(false);
+ }
+ });
+
it('matches the full builder while retaining completed history during text-only updates', () => {
const project = createStreamingMessageProjection();
const groups = createWorkGroupProjection();
diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
index 6d0b669ab5..10758ca801 100644
--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx
+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
@@ -2492,8 +2492,17 @@ export function buildCachedRenderItems(
/** Build the displayed remote history without evaluating the raw transcript fallback. */
export function buildMessageStreamRenderProjection({
- historyView, historySnapshot, historyLiveMessages, isSessionStreaming, handoff,
- taskUpdates, ghostCardSnapshot, renderOptions, generatedFilesItemCache, buildRaw,
+ historyView,
+ historySnapshot,
+ historyLiveMessages,
+ isSessionStreaming,
+ handoff,
+ taskUpdates,
+ ghostCardSnapshot,
+ renderOptions,
+ generatedFilesItemCache,
+ historyProjection,
+ buildRaw,
}: {
historyView: HistoryViewController<HistoryChatMessage> | null | undefined;
historySnapshot: HistoryViewSnapshot<HistoryChatMessage> | null;
@@ -2504,71 +2513,109 @@ export function buildMessageStreamRenderProjection({
ghostCardSnapshot?: Parameters<typeof buildRenderItems>[2];
renderOptions?: Parameters<typeof buildRenderItems>[3];
generatedFilesItemCache: Map<string, GeneratedFilesRenderItemRef>;
+ /** Mounted-view cache for ready history, separate from the raw fallback. */
+ historyProjection?: ReturnType<typeof createStreamingMessageProjection>;
buildRaw: () => RenderProjection;
}): RenderProjection {
if (historyView && historySnapshot?.ready) {
- // Build only the displayed projection; the raw fallback is lazy below.
- const results = new Map<string, string>();
- const items = renderHistoryView<HistoryChatMessage, RenderItem>({
- view: historyView,
- snapshot: historySnapshot,
- liveMessages: historyLiveMessages,
- streaming: isSessionStreaming,
- isLive: (row) => row.isStreaming === true,
- pendingHandoff: handoff?.pending,
- staleTail: handoff?.tail,
- isLocalMessage: (row) => row.isLocalSystemCard === true,
- isLocalUser: (row) =>
- row.role === 'user' &&
- (row.isPendingPersist === true ||
- !!row.blockedByGhost ||
- !!row.localSendPrecedingClientIds),
- build: (rows, _streaming, historyArtifacts) => {
- // History chunks are freshly assembled arrays, not reusable source snapshots.
- const chunk = buildRenderItems([...rows], taskUpdates, ghostCardSnapshot, {
- ...renderOptions,
- historyWindowIncomplete: true,
- historyArtifacts,
- });
- for (const [key, value] of chunk.singleResultMap) results.set(key, value);
- return groupWorkRuns(chunk.items, isSessionStreaming);
- },
- structure: {
- placeholder: (summary) => ({
- id: summary.firstMessageId,
- clientId: summary.anchorClientId ?? summary.key.slice('work-'.length),
- role: 'thinking',
- content: '',
- createdAt: new Date(summary.startedAtMs).toISOString(),
- thinkingDurationMs: Math.max(0, summary.endedAtMs - summary.startedAtMs),
- thinkingRedacted: true,
- isStreaming: summary.isStreaming,
- }),
- children: (item) => (item.type === 'work_group' ? item.children : undefined),
- sourceIds: (item) =>
- item.type === 'message'
- ? [item.message.clientId]
- : item.type === 'tool_segment'
- ? item.toolCalls.map((tool) => tool.clientId)
- : item.type === 'agent_task' && item.toolCall
- ? [item.toolCall.clientId]
- : [],
- rebuild: (item, children, deferred) =>
- item.type === 'work_group'
- ? { ...item, children: children as WorkGroupChildItem[], deferred }
- : item,
- },
- });
- const keys = new Set<string>();
- const unique = items.filter((item) => {
- if (keys.has(item.key)) return false;
- keys.add(item.key);
- return true;
- });
- return {
- items: reuseGeneratedFilesRenderItems(unique, generatedFilesItemCache),
- singleResultMap: results,
+ const buildHistory = (): RenderProjection => {
+ // Build only the displayed projection; the raw fallback is lazy below.
+ const results = new Map<string, string>();
+ const items = renderHistoryView<HistoryChatMessage, RenderItem>({
+ view: historyView,
+ snapshot: historySnapshot,
+ liveMessages: historyLiveMessages,
+ streaming: isSessionStreaming,
+ isLive: (row) => row.isStreaming === true,
+ pendingHandoff: handoff?.pending,
+ staleTail: handoff?.tail,
+ isLocalMessage: (row) => row.isLocalSystemCard === true,
+ isLocalUser: (row) =>
+ row.role === 'user' &&
+ (row.isPendingPersist === true ||
+ !!row.blockedByGhost ||
+ !!row.localSendPrecedingClientIds),
+ build: (rows, _streaming, historyArtifacts) => {
+ // History chunks are freshly assembled arrays, not reusable source snapshots.
+ const chunk = buildRenderItems([...rows], taskUpdates, ghostCardSnapshot, {
+ ...renderOptions,
+ historyWindowIncomplete: true,
+ historyArtifacts,
+ });
+ for (const [key, value] of chunk.singleResultMap) results.set(key, value);
+ return groupWorkRuns(chunk.items, isSessionStreaming);
+ },
+ structure: {
+ placeholder: (summary) => ({
+ id: summary.firstMessageId,
+ clientId: summary.anchorClientId ?? summary.key.slice('work-'.length),
+ role: 'thinking',
+ content: '',
+ createdAt: new Date(summary.startedAtMs).toISOString(),
+ thinkingDurationMs: Math.max(0, summary.endedAtMs - summary.startedAtMs),
+ thinkingRedacted: true,
+ isStreaming: summary.isStreaming,
+ }),
+ children: (item) => (item.type === 'work_group' ? item.children : undefined),
+ sourceIds: (item) =>
+ item.type === 'message'
+ ? [item.message.clientId]
+ : item.type === 'tool_segment'
+ ? item.toolCalls.map((tool) => tool.clientId)
+ : item.type === 'agent_task' && item.toolCall
+ ? [item.toolCall.clientId]
+ : [],
+ rebuild: (item, children, deferred) =>
+ item.type === 'work_group'
+ ? { ...item, children: children as WorkGroupChildItem[], deferred }
+ : item,
+ },
+ });
+ const keys = new Set<string>();
+ const unique = items.filter((item) => {
+ if (keys.has(item.key)) return false;
+ keys.add(item.key);
+ return true;
+ });
+ return {
+ items: reuseGeneratedFilesRenderItems(unique, generatedFilesItemCache),
+ singleResultMap: results,
+ };
};
+ if (!historyProjection) return buildHistory();
+ const tail = historyLiveMessages.at(-1);
+ return historyProjection(
+ historyLiveMessages,
+ [
+ getDataOwnerGeneration(),
+ historyView,
+ historySnapshot,
+ isSessionStreaming,
+ taskUpdates,
+ ghostCardSnapshot,
+ ghostCardSnapshot?.version,
+ renderOptions?.sessionId,
+ renderOptions?.turnChangeSets,
+ renderOptions?.workingDir,
+ renderOptions?.botSessionId,
+ renderOptions?.activeVoiceCallId,
+ renderOptions?.subagentRunStatuses,
+ renderOptions?.cindyMakeSessionId,
+ renderOptions?.cindyMakeCompletionInComposer,
+ handoff?.pending.size,
+ ...(handoff?.pending ?? []),
+ handoff?.tail.size,
+ ...(handoff?.tail ?? []),
+ ],
+ buildHistory,
+ // Already-grouped history can only replace a standalone unsealed tail.
+ // Bot ordering and completed-answer grouping remain content dependent.
+ isSessionStreaming &&
+ !renderOptions?.botSessionId &&
+ !!tail &&
+ !isCompletedAssistantMessage(tail),
+ true,
+ );
}
const built = buildRaw();
return {
@@ -3211,6 +3258,7 @@ export function MessageStream({
[metadataMessages],
);
const streamProjection = useMemo(createStreamingMessageProjection, [sessionId]);
+ const historyProjection = useMemo(createStreamingMessageProjection, [sessionId]);
const workGroupProjection = useMemo(createStreamingWorkGroupProjection, [sessionId]);
const renderMetadataProjection = useMemo(createRenderItemMetadataProjection, [sessionId]);
const visibleMetadataProjection = useMemo(createRenderItemMetadataProjection, [sessionId]);
@@ -3229,6 +3277,7 @@ export function MessageStream({
const { items: ungroupedRenderItems, singleResultMap } = useMemo(() => buildMessageStreamRenderProjection({
historyView, historySnapshot, historyLiveMessages, isSessionStreaming, handoff,
taskUpdates, ghostCardSnapshot,
+ historyProjection,
generatedFilesItemCache: generatedFilesItemCacheRef.current,
renderOptions: {
sessionId, turnChangeSets, workingDir,
@@ -3294,6 +3343,7 @@ export function MessageStream({
simplifiedBotConversation,
sessionId,
streamProjection,
+ historyProjection,
]);
const assistantsWithFollowingUserBoundary = useMemo(
() => collectAssistantsWithFollowingUserBoundary(visibleMetadataMessages),
diff --git a/apps/desktop/src/renderer/components/chat/streamingMessageProjection.ts b/apps/desktop/src/renderer/components/chat/streamingMessageProjection.ts
index 08b0cbd099..2b5f6098c5 100644
--- a/apps/desktop/src/renderer/components/chat/streamingMessageProjection.ts
+++ b/apps/desktop/src/renderer/components/chat/streamingMessageProjection.ts
@@ -38,7 +38,17 @@ export function isStreamingTextOnlyUpdate(
!sameFieldsExcept(before, after, 'content')
)
return false;
- for (let index = 0; index < last; index++) if (previous[index] !== next[index]) return false;
+ // HistoryView normalizes live rows into fresh objects. Equal shallow fields
+ // still describe the same immutable row; any metadata/content change rebuilds.
+ for (let index = 0; index < last; index++) {
+ const beforeRow = previous[index];
+ const afterRow = next[index];
+ if (
+ beforeRow !== afterRow &&
+ (beforeRow.content !== afterRow.content || !sameFieldsExcept(beforeRow, afterRow, 'content'))
+ )
+ return false;
+ }
return true;
}
@@ -79,13 +89,18 @@ export function createRenderItemMetadataProjection() {
/** A view owns this projection; no session data survives its unmount. */
export function createStreamingMessageProjection() {
let previous:
- | { messages: ChatMessage[]; dependencies: readonly unknown[]; result: MessageRenderProjection }
+ | {
+ messages: readonly ChatMessage[];
+ dependencies: readonly unknown[];
+ result: MessageRenderProjection;
+ }
| undefined;
return (
- messages: ChatMessage[],
+ messages: readonly ChatMessage[],
dependencies: readonly unknown[],
build: () => MessageRenderProjection,
allowTextReuse = true,
+ alreadyGrouped = false,
): MessageRenderProjection => {
let result: MessageRenderProjection | undefined;
if (
@@ -99,12 +114,25 @@ export function createStreamingMessageProjection() {
const before = previous.messages[previous.messages.length - 1];
const after = messages[messages.length - 1];
const index = previous.result.items.findIndex(
- (item) => item.type === 'message' && item.message === before,
+ (item) =>
+ item.type === 'message' &&
+ (item.message === before ||
+ (item.message.clientId === before.clientId &&
+ item.message.role === 'assistant' &&
+ item.message.content === before.content &&
+ item.message.isStreaming === true &&
+ !isCompletedAssistantMessage(item.message))),
);
// Hidden/subagent rows and special projections must still go through the full builder.
- if (index >= 0) {
+ if (index >= 0 && (!alreadyGrouped || index === previous.result.items.length - 1)) {
const items = previous.result.items.slice();
- items[index] = { type: 'message', key: items[index].key, message: after };
+ const item = items[index] as Extract<RenderItem, { type: 'message' }>;
+ // A history row owns ordering metadata (notably createdAt). Live
+ // normalization may have a provisional timestamp: update only text.
+ items[index] = {
+ ...item,
+ message: item.message === before ? after : { ...item.message, content: after.content },
+ };
result = { items, singleResultMap: previous.result.singleResultMap };
}
}