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(chat): 共用远程流式正文与历史交接

Dash0d5a46581b8a
diff --git a/apps/desktop/src/renderer/__tests__/remoteHistoryHandoff.test.ts b/apps/desktop/src/renderer/__tests__/remoteHistoryHandoff.test.ts
new file mode 100644
index 0000000000..2c3899b33d
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/remoteHistoryHandoff.test.ts
@@ -0,0 +1,96 @@
+import { describe, expect, it } from 'vitest';
+import {
+ HistoryViewController, HistoryViewHandoff, projectHistoryView, renderHistoryView,
+} from '@cindy/maker-shared/message-window';
+import { buildRenderItems, groupWorkRuns } from '../components/chat/MessageStream';
+import type { HistoryChatMessage } from '../lib/makerChatStore';
+
+const row = (clientId: string, isStreaming = false): HistoryChatMessage => ({
+ id: clientId, clientId, role: clientId === 'user' ? 'user' : 'assistant',
+ content: clientId === 'user' ? 'question' : 'visible answer', isStreaming,
+ createdAt: clientId === 'user' ? '2026-09-08T00:00:01Z' : '2026-09-08T00:00:00Z',
+});
+
+function fixture() {
+ let source = [row('user')];
+ const view = new HistoryViewController<HistoryChatMessage>({
+ page: async () => ({ version: 1, items: projectHistoryView(source, false), hasMore: false, nextCursor: null }),
+ details: async () => ({ version: 1, messages: [], hasMore: false, nextCursor: null }),
+ expanded: async () => undefined,
+ });
+ const handoff = new HistoryViewHandoff<HistoryChatMessage>((message) => message.isStreaming === true);
+ const render = (raw: HistoryChatMessage[]) => {
+ const snapshot = view.getSnapshot();
+ const state = handoff.reconcile(snapshot, raw);
+ const build = (rows: readonly HistoryChatMessage[]) => groupWorkRuns(buildRenderItems([...rows]).items, false);
+ const items = snapshot.ready ? renderHistoryView({
+ view, snapshot, liveMessages: raw, streaming: false,
+ isLive: (message) => message.isStreaming === true,
+ pendingHandoff: state.pending,
+ isLocalUser: (message) => message.role === 'user' && (message.isPendingPersist === true || !!message.blockedByGhost),
+ build,
+ structure: {
+ placeholder: () => { throw new Error('This fixture contains prose only'); },
+ children: () => undefined,
+ sourceIds: () => [],
+ rebuild: (item) => item,
+ },
+ }) : build(raw);
+ return { state, text: JSON.stringify(items), items };
+ };
+ return { view, handoff, render, setSource: (rows: HistoryChatMessage[]) => { source = rows; } };
+}
+
+describe('desktop remote history uses the shared live-to-history handoff', () => {
+ it('keeps finalized prose through the first stale page and takes over once by clientId', async () => {
+ const { view, render, setSource } = fixture();
+ expect(render([row('answer', true)]).text).toContain('visible answer');
+ expect(render([row('answer')]).text).toContain('visible answer');
+ await view.refresh();
+ // The provisional timestamp is older than the history tail; it still belongs
+ // to this displayed stream, unlike an arbitrary durable cache row.
+ expect(render([row('answer')]).text).toContain('visible answer');
+ expect(render([{ ...row('answer'), id: 'persisted-id', rowid: 42 }]).text).toContain('visible answer');
+ await view.refresh();
+ expect(render([row('answer')]).text).toContain('visible answer');
+ setSource([row('user'), { ...row('answer'), id: 'persisted-id', content: 'authoritative answer' }]);
+ await view.refresh();
+ const final = render([row('answer')]);
+ expect(final.state.pending.size).toBe(0);
+ expect(final.text).not.toContain('visible answer');
+ expect(final.items.filter((item) => item.type === 'message' && item.message.clientId === 'answer')).toHaveLength(1);
+ expect(final.text).toContain('authoritative answer');
+ view.setActive(false);
+ });
+
+ it('retains local pending user bubbles while the assistant awaits history', async () => {
+ const { view, render } = fixture();
+ await view.refresh();
+ render([row('answer', true)]);
+ const pending: HistoryChatMessage = { ...row('pending'), role: 'user', content: 'queued follow-up', isPendingPersist: true };
+ const final = render([row('answer'), pending]);
+ expect(final.text).toContain('visible answer');
+ expect(final.text).toContain('queued follow-up');
+ expect(final.items.filter((item) => item.type === 'message').map((item) => item.message.clientId)).toEqual(['user', 'answer', 'pending']);
+ view.setActive(false);
+ });
+
+ it('does not resurrect finalized raw rows after removal, reset or a source switch', async () => {
+ const { view, render } = fixture();
+ await view.refresh();
+ expect(render([row('old')]).text).not.toContain('visible answer');
+ render([row('answer', true)]);
+ render([]);
+ expect(render([row('answer')]).text).not.toContain('visible answer');
+ render([row('answer', true)]);
+ view.reset();
+ render([row('answer')]);
+ await view.refresh();
+ expect(render([row('answer')]).text).not.toContain('visible answer');
+ const replacement = fixture();
+ await replacement.view.refresh();
+ expect(replacement.render([row('answer')]).text).not.toContain('visible answer');
+ replacement.view.setActive(false);
+ view.setActive(false);
+ });
+});
diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
index f182ccf6e1..e5560c4612 100644
--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx
+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
@@ -28,7 +28,7 @@ import {
type CSSProperties,
type ReactNode,
} from 'react';
-import { renderHistoryView } from '@cindy/maker-shared/message-window';
+import { HistoryViewHandoff, renderHistoryView } from '@cindy/maker-shared/message-window';
import { getRemoteHistoryView, type HistoryChatMessage } from '@/lib/makerChatStore';
import { createPortal } from 'react-dom';
import { GitFork } from 'lucide-react';
@@ -2485,6 +2485,17 @@ export function MessageStream({
historyView?.getSnapshot ?? (() => null),
historyView?.getSnapshot ?? (() => null),
);
+ const historyHandoff = useMemo(() => new HistoryViewHandoff<HistoryChatMessage>(
+ (row) => row.isStreaming === true,
+ ), [historyView]);
+ // Observe live rows before the first history page too: a stream can finish
+ // while that page is in flight. Local tasks retain their existing path.
+ const historyLiveMessages = useMemo(() => historyView ? messages.map((row) => ({
+ ...row, id: row.id ?? row.clientId, createdAt: row.createdAt ?? '',
+ })) : [], [historyView, messages]);
+ const handoff = useMemo(() => historySnapshot
+ ? historyHandoff.reconcile(historySnapshot, historyLiveMessages) : null,
+ [historyHandoff, historySnapshot, historyLiveMessages]);
// 右上角 chip 栈插槽 —— PrevMessageJumpChip 通过 portal 挂到这里,
// 与 DiffPanelToggle 在同一栈中各占一行。Provider 不存在时返回 null,
// 渲染处会兜底跳过(典型场景:其他视图直接用 MessageStream 但不需要栈)。
@@ -2733,12 +2744,10 @@ export function MessageStream({
});
if (historyView && historySnapshot?.ready) {
const results = new Map(built.singleResultMap);
- const liveMessages: HistoryChatMessage[] = messages.map((row) => ({ ...row,
- id: row.id ?? row.clientId, createdAt: row.createdAt ?? '',
- }));
const items = renderHistoryView<HistoryChatMessage, RenderItem>({
- view: historyView, snapshot: historySnapshot, liveMessages, streaming: isSessionStreaming,
+ view: historyView, snapshot: historySnapshot, liveMessages: historyLiveMessages, streaming: isSessionStreaming,
isLive: (row) => row.isStreaming === true,
+ pendingHandoff: handoff?.pending,
isLocalUser: (row) => row.role === 'user' && (row.isPendingPersist === true || !!row.blockedByGhost),
build: (rows) => {
const chunk = buildRenderItems([...rows], taskUpdates, ghostCardSnapshot, {
@@ -2775,6 +2784,8 @@ export function MessageStream({
messages,
historyView,
historySnapshot,
+ historyLiveMessages,
+ handoff,
isSessionStreaming,
taskUpdates,
ghostCardSnapshot,
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 9f9d490a64..5e75a2920d 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -110,9 +110,8 @@ import { shouldClearOperationErrorAfterSync, type SessionOperationError } from '
import { createTransientTopicSubscriptionCoordinator } from '@/device-link/transientTopicSubscription';
import { useMobileMakerTransport } from '@/device-link/useMobileMakerTransport';
import { findRemoteHistoryView, useRemoteHistoryView } from '@/session/remoteHistoryView';
-import { isHistoryViewUnavailable } from '@cindy/maker-shared/message-window';
+import { HistoryViewHandoff, isHistoryViewUnavailable } from '@cindy/maker-shared/message-window';
import { buildMobileHistoryRenderItems } from '@/session/mobileHistoryRender';
-import { MobileHistoryHandoff } from '@/session/mobileHistoryHandoff';
import { createMobileMakerTransport } from '@/device-link/mobileMakerTransport';
import { startFocusedTopicSubscription } from '@/device-link/focusedTopicSubscription';
import { InteractionPanel, type MobilePlanViewerState } from '@/session/InteractionPanel';
@@ -1023,7 +1022,9 @@ export default function SessionScreen() {
if (messageReloadRevision > 0) historyView.view.reset();
}, [messageReloadRevision, historyView.view]);
const rawMessages = useSessionMessages(sessionId, deviceId);
- const historyHandoff = useMemo(() => new MobileHistoryHandoff(), [historyView.view]);
+ const historyHandoff = useMemo(() => new HistoryViewHandoff<RemoteMessage>(
+ (row) => row.agentMeta?.isStreaming === true,
+ ), [historyView.view]);
const handoff = useMemo(() => historyHandoff.reconcile(historyView.snapshot, rawMessages),
[historyHandoff, rawMessages, historyView.snapshot]);
const messages = handoff.messages;
diff --git a/apps/mobile/src/__tests__/mobileHistoryHandoff.test.ts b/apps/mobile/src/__tests__/mobileHistoryHandoff.test.ts
index 9f8019a2f5..3b3b98faba 100644
--- a/apps/mobile/src/__tests__/mobileHistoryHandoff.test.ts
+++ b/apps/mobile/src/__tests__/mobileHistoryHandoff.test.ts
@@ -1,6 +1,5 @@
import { describe, expect, it } from 'vitest';
-import { HistoryViewController, projectHistoryView } from '@cindy/maker-shared/message-window';
-import { MobileHistoryHandoff } from '../session/mobileHistoryHandoff';
+import { HistoryViewController, HistoryViewHandoff, projectHistoryView } from '@cindy/maker-shared/message-window';
import { buildMobileHistoryRenderItems } from '../session/mobileHistoryRender';
import type { RemoteMessage } from '../session/types';
@@ -11,6 +10,8 @@ const row = (id: string, streaming = false): RemoteMessage => ({
agentMeta: streaming ? { isStreaming: true } : null,
});
+const createHandoff = () => new HistoryViewHandoff<RemoteMessage>((row) => row.agentMeta?.isStreaming === true);
+
describe('mobile history handoff', () => {
it('retains text finalized before the first history page arrives, including an older provisional time anchor', async () => {
const view = new HistoryViewController<RemoteMessage>({
@@ -18,7 +19,7 @@ describe('mobile history handoff', () => {
details: async () => ({ version: 1, messages: [], hasMore: false, nextCursor: null }),
expanded: async () => undefined,
});
- const handoff = new MobileHistoryHandoff();
+ const handoff = createHandoff();
const live = { ...row('answer', true), createdAt: '2026-09-07T23:59:59Z' };
handoff.reconcile(view.getSnapshot(), [live]);
const final = { ...live, agentMeta: null };
@@ -40,7 +41,7 @@ describe('mobile history handoff', () => {
expanded: async () => undefined,
});
await view.refresh();
- const handoff = new MobileHistoryHandoff();
+ const handoff = createHandoff();
const render = (raw: RemoteMessage[]) => {
const state = handoff.reconcile(view.getSnapshot(), raw);
const output = buildMobileHistoryRenderItems({ view, snapshot: view.getSnapshot(),
@@ -71,7 +72,7 @@ describe('mobile history handoff', () => {
expanded: async () => undefined,
});
await view.refresh();
- const handoff = new MobileHistoryHandoff();
+ const handoff = createHandoff();
expect(handoff.reconcile(view.getSnapshot(), [row('old')]).messages.map(x => x.clientId)).toEqual(['user']);
handoff.reconcile(view.getSnapshot(), [row('answer', true)]);
expect(handoff.reconcile(view.getSnapshot(), []).pending.size).toBe(0);
@@ -81,7 +82,7 @@ describe('mobile history handoff', () => {
handoff.reconcile(view.getSnapshot(), []);
await view.refresh();
expect(handoff.reconcile(view.getSnapshot(), [row('answer')]).pending.size).toBe(0);
- expect(new MobileHistoryHandoff().reconcile(view.getSnapshot(), [row('answer')]).pending.size).toBe(0);
+ expect(createHandoff().reconcile(view.getSnapshot(), [row('answer')]).pending.size).toBe(0);
view.setActive(false);
});
});
diff --git a/apps/mobile/src/session/mobileHistoryRender.ts b/apps/mobile/src/session/mobileHistoryRender.ts
index 4382570b3f..374104a795 100644
--- a/apps/mobile/src/session/mobileHistoryRender.ts
+++ b/apps/mobile/src/session/mobileHistoryRender.ts
@@ -14,8 +14,8 @@ export function buildMobileHistoryRenderItems(options: {
}): MobileMessageRenderItem[] {
return renderHistoryView<RemoteMessage, MobileMessageRenderItem>({
view: options.view, snapshot: options.snapshot, liveMessages: options.messages,
- isLive: (row) => row.agentMeta?.isStreaming === true || options.pendingHandoff?.has(row.clientId) === true,
- isPendingHandoff: (row) => options.pendingHandoff?.has(row.clientId) === true,
+ isLive: (row) => row.agentMeta?.isStreaming === true,
+ pendingHandoff: options.pendingHandoff,
streaming: options.streaming,
build: (rows, streaming) => buildMobileMessageRenderItems(rows, { isSessionStreaming: streaming, sessionId: options.sessionId }, options.taskUpdates),
structure: {
diff --git a/apps/mobile/src/session/mobileHistoryHandoff.ts b/packages/maker-shared/src/historyViewHandoff.ts
similarity index 70%
rename from apps/mobile/src/session/mobileHistoryHandoff.ts
rename to packages/maker-shared/src/historyViewHandoff.ts
index 1b6177682c..021f8e759b 100644
--- a/apps/mobile/src/session/mobileHistoryHandoff.ts
+++ b/packages/maker-shared/src/historyViewHandoff.ts
@@ -1,17 +1,17 @@
-import { historyViewLeaves, type HistoryViewSnapshot } from '@cindy/maker-shared/message-window';
-import type { RemoteMessage } from './types';
-
-const streaming = (row: RemoteMessage) => row.agentMeta?.isStreaming === true;
+import { historyViewLeaves, type HistoryMessageSource } from './historyView.js';
+import type { HistoryViewSnapshot } from './historyViewController.js';
/** View-local identities only; message bodies remain in the existing raw store.
* A finalized live row stays visible until history takes over. Removing it from
* the raw store (delete/rewind/clear) cancels the handoff rather than reviving it.
*/
-export class MobileHistoryHandoff {
+export class HistoryViewHandoff<T extends HistoryMessageSource> {
private readonly pending = new Set<string>();
private ready = false;
- reconcile(snapshot: HistoryViewSnapshot<RemoteMessage>, raw: readonly RemoteMessage[]) {
+ constructor(private readonly streaming: (row: T) => boolean) {}
+
+ reconcile(snapshot: HistoryViewSnapshot<T>, raw: readonly T[]) {
if (this.ready && !snapshot.ready) this.pending.clear();
this.ready = snapshot.ready;
const available = historyViewLeaves(snapshot.items).flatMap((item) => item.type === 'messages' ? item.messages : []);
@@ -21,8 +21,8 @@ export class MobileHistoryHandoff {
for (const id of this.pending) if (!current.has(id)) this.pending.delete(id);
for (const row of raw) {
if (row.role !== 'assistant') continue;
- if (streaming(row)) this.pending.add(row.clientId);
- else if (history.has(row.clientId) && !streaming(history.get(row.clientId)!)) this.pending.delete(row.clientId);
+ if (this.streaming(row)) this.pending.add(row.clientId);
+ else if (history.has(row.clientId) && !this.streaming(history.get(row.clientId)!)) this.pending.delete(row.clientId);
}
const pending = new Set(this.pending);
if (!snapshot.ready) return { messages: raw, pending };
diff --git a/packages/maker-shared/src/historyViewRender.ts b/packages/maker-shared/src/historyViewRender.ts
index 02bb703ee9..a2549735a4 100644
--- a/packages/maker-shared/src/historyViewRender.ts
+++ b/packages/maker-shared/src/historyViewRender.ts
@@ -10,7 +10,7 @@ export function renderHistoryView<T extends HistoryMessageSource, TItem>(options
streaming: boolean;
isLive?(message: T): boolean;
/** Already displayed assistant identities awaiting history, not arbitrary cached rows. */
- isPendingHandoff?(message: T): boolean;
+ pendingHandoff?: ReadonlySet<string>;
isLocalUser?(message: T): boolean;
structure: {
placeholder(summary: HistoryWorkSummary): T;
@@ -24,7 +24,9 @@ export function renderHistoryView<T extends HistoryMessageSource, TItem>(options
const seen = new Set<string>();
const placeholders = new Set<string>();
const references = new Map<string, HistoryWorkSummary>();
- const live = new Map(options.liveMessages.filter((row) => options.isLive?.(row)).map((row) => [row.clientId, row]));
+ const isPendingHandoff = (row: T) => row.role === 'assistant' && options.pendingHandoff?.has(row.clientId) === true;
+ const isLive = (row: T) => options.isLive?.(row) || isPendingHandoff(row);
+ const live = new Map(options.liveMessages.filter(isLive).map((row) => [row.clientId, row]));
const leaves = historyViewLeaves(snapshot.items);
const sourceIds = new Set(leaves.flatMap((item) => item.type === 'messages' ? item.messages.map((row) => row.clientId) : []));
let endMs = 0;
@@ -62,9 +64,9 @@ export function renderHistoryView<T extends HistoryMessageSource, TItem>(options
endMs = Math.max(endMs, summary.endedAtMs);
}
for (const row of options.liveMessages) {
- if (options.isLive?.(row) && !seen.has(row.clientId) && (row.role === 'assistant' || row.role === 'user')
+ if (isLive(row) && !seen.has(row.clientId) && (row.role === 'assistant' || row.role === 'user')
&& (Date.parse(row.createdAt) >= endMs
- || (row.role === 'assistant' && options.isPendingHandoff?.(row)))) rows.push(row);
+ || isPendingHandoff(row))) rows.push(row);
}
// Local pending/blocked user bubbles belong to the current UI store, not
// persisted history. Keep their store order without trusting device clocks.
diff --git a/packages/maker-shared/src/messageWindow.ts b/packages/maker-shared/src/messageWindow.ts
index dad7598c6c..a5a136a13c 100644
--- a/packages/maker-shared/src/messageWindow.ts
+++ b/packages/maker-shared/src/messageWindow.ts
@@ -2,6 +2,7 @@ export * from './historyView.js';
export { projectHistoryView, isHistoryDetailTool, hasVisibleHistoryResult } from './historyViewProjection.js';
export * from './historyViewController.js';
export { renderHistoryView } from './historyViewRender.js';
+export { HistoryViewHandoff } from './historyViewHandoff.js';
export interface MessageScrollMetrics {
contentHeight: number;