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。

refactor(remote): 用真实渲染入口验证历史懒构建

Dashd513caabba4f
diff --git a/apps/desktop/src/renderer/__tests__/historyRenderBranch.test.ts b/apps/desktop/src/renderer/__tests__/historyRenderBranch.test.ts
deleted file mode 100644
index 7267919425..0000000000
--- a/apps/desktop/src/renderer/__tests__/historyRenderBranch.test.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-import ts from 'typescript';
-import { expect, it, vi } from 'vitest';
-
-// Execute the production memo, leaving renderer builders at the test boundary.
-// A ready remote view must not parse the unused full raw transcript first.
-const source = ts.createSourceFile('MessageStream.tsx', readFileSync(resolve(process.cwd(),
- 'src/renderer/components/chat/MessageStream.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
-let callback: ts.Expression | undefined;
-function visit(node: ts.Node) {
- if (ts.isVariableDeclaration(node) && ts.isObjectBindingPattern(node.name)
- && node.name.elements.some(element => element.name.getText(source) === 'ungroupedRenderItems')
- && node.initializer && ts.isCallExpression(node.initializer)) callback = node.initializer.arguments[0];
- ts.forEachChild(node, visit);
-}
-visit(source);
-if (!callback) throw new Error('Missing production history projection');
-const code = ts.transpileModule(`return (${callback.getText(source)})();`, {
- compilerOptions: { target: ts.ScriptTarget.ES2022 },
-}).outputText;
-
-it.each([false, true])('builds only the displayed history source (ready=%s)', ready => {
- const rawItems = [{ key: 'raw' }];
- const historyItems = [{ key: 'history' }];
- const buildRaw = vi.fn(() => ({ items: rawItems, singleResultMap: new Map() }));
- const buildChunk = vi.fn(() => ({ items: historyItems, singleResultMap: new Map([['tool', 'result']]) }));
- const buildHistory = vi.fn(({ build }: { build: (rows: unknown[]) => unknown }) => build([]));
- const bindings = {
- streamProjection: (_rows: unknown, _dependencies: unknown, build: () => unknown) => build(),
- buildCachedRenderItems: buildRaw, buildRenderItems: buildChunk, renderHistoryView: buildHistory,
- getDataOwnerGeneration: () => 1, displayMessages: [], taskUpdates: new Map(), ghostCardSnapshot: {},
- historyLoaded: true, hasMoreMessages: false, historyWindowHasIsland: false, turnChangeSets: [], workingDir: '/',
- simplifiedBotConversation: false, sessionId: 's', cindyMakeSessionId: null, cindyMakeCompletionInComposer: false,
- subagentRunStatuses: new Map(), historyView: {}, historySnapshot: { ready }, historyLiveMessages: [],
- isSessionStreaming: false, handoff: {}, markdownImageTargetCacheRef: { current: new Map() },
- generatedFilesItemCacheRef: { current: new Map() }, groupWorkRuns: (items: unknown) => items,
- reuseGeneratedFilesRenderItems: (items: unknown) => items,
- };
- const result = new Function(...Object.keys(bindings), code)(...Object.values(bindings));
- expect(result.items).toEqual(ready ? historyItems : rawItems);
- expect(buildRaw).toHaveBeenCalledTimes(ready ? 0 : 1);
- expect(buildHistory).toHaveBeenCalledTimes(ready ? 1 : 0);
- expect(buildChunk).toHaveBeenCalledTimes(ready ? 1 : 0);
- if (ready) expect(result.singleResultMap.get('tool')).toBe('result');
-});
diff --git a/apps/desktop/src/renderer/__tests__/remoteHistoryHandoff.test.ts b/apps/desktop/src/renderer/__tests__/remoteHistoryHandoff.test.ts
index b25f98d91b..aef0c9d655 100644
--- a/apps/desktop/src/renderer/__tests__/remoteHistoryHandoff.test.ts
+++ b/apps/desktop/src/renderer/__tests__/remoteHistoryHandoff.test.ts
@@ -1,9 +1,9 @@
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import { readFileSync } from 'node:fs';
import {
HistoryViewController, HistoryViewHandoff, projectHistoryView, renderHistoryView, historyViewLeaves, nextHistoryCacheReceipt,
} from '@cindy/maker-shared/message-window';
-import { buildRenderItems, groupWorkRuns, selectVisibleMessages, collectTurnFinalAssistantClientIds,
+import { buildMessageStreamRenderProjection, buildRenderItems, groupWorkRuns, selectVisibleMessages, collectTurnFinalAssistantClientIds,
findLastUserMessageClientId, planSessionBelongsToLatestUserTurn } from '../components/chat/MessageStream';
import { deriveNavRailEntries } from '../components/chat/messageNavRailModel';
import { collectAssistantTurnUsageDetails } from '../lib/userTurnUsage';
@@ -353,3 +353,35 @@ describe('desktop remote history uses the shared live-to-history handoff', () =>
view.setActive(false);
});
});
+
+// Unit: exercise the projection used by MessageStream, including the lazy raw
+// fallback. Existing handoff cases call renderHistoryView below that boundary.
+it.each([false, true])('builds the displayed source and retains tool results (ready=%s)', async ready => {
+ const historyRows: HistoryChatMessage[] = [row('user'),
+ { ...row('call'), role: 'tool_use', toolName: 'Read', toolUseId: 'tool', toolInput: {} },
+ { ...row('result'), role: 'tool_result', toolUseId: 'tool', content: 'Tool output' },
+ { ...row('cached'), content: 'Cached answer' }];
+ const view = new HistoryViewController<HistoryChatMessage>({
+ page: async () => ({ version: 1, items: [{ type: 'messages', key: 'page', messages: historyRows }], hasMore: false, nextCursor: null }),
+ details: async () => ({ version: 1, messages: [], hasMore: false, nextCursor: null }),
+ expanded: async () => undefined,
+ });
+ if (ready) await view.refresh();
+ const buildRaw = vi.fn(() => buildRenderItems([{ ...row('raw'), content: 'Raw answer' }]));
+ const result = buildMessageStreamRenderProjection({
+ historyView: view, historySnapshot: view.getSnapshot(), historyLiveMessages: [],
+ isSessionStreaming: false, generatedFilesItemCache: new Map(), buildRaw,
+ });
+ expect(result.items.filter(item => item.type === 'message').map(item => item.message.content))
+ .toContain(ready ? 'Cached answer' : 'Raw answer');
+ expect(JSON.stringify(result.items)).not.toContain(ready ? 'Raw answer' : 'Cached answer');
+ expect(buildRaw).toHaveBeenCalledTimes(ready ? 0 : 1);
+ if (ready) {
+ const work = result.items.find(item => item.type === 'work_group');
+ const tool = work?.type === 'work_group' ? work.children.find(item => item.type === 'tool_segment') : undefined;
+ expect(tool?.type === 'tool_segment' && tool.resultMap.get('call')).toBe('Tool output');
+ } else {
+ expect(result.singleResultMap).toBe(buildRaw.mock.results[0].value.singleResultMap);
+ }
+ view.setActive(false);
+});
diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
index dc0b01479a..843ff08827 100644
--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx
+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
@@ -38,6 +38,8 @@ import {
} from 'react';
import {
HistoryViewHandoff,
+ type HistoryViewController,
+ type HistoryViewSnapshot,
renderHistoryView,
historyPrefetchThreshold,
historyViewLeaves,
@@ -2461,6 +2463,93 @@ export function buildCachedRenderItems(
return projection;
}
+/** 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: HistoryViewController<HistoryChatMessage> | null | undefined;
+ historySnapshot: HistoryViewSnapshot<HistoryChatMessage> | null;
+ historyLiveMessages: readonly HistoryChatMessage[];
+ isSessionStreaming: boolean;
+ handoff?: ReturnType<HistoryViewHandoff<HistoryChatMessage>['reconcile']> | null;
+ taskUpdates?: Parameters<typeof buildRenderItems>[1];
+ ghostCardSnapshot?: Parameters<typeof buildRenderItems>[2];
+ renderOptions?: Parameters<typeof buildRenderItems>[3];
+ generatedFilesItemCache: Map<string, GeneratedFilesRenderItemRef>;
+ 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 built = buildRaw();
+ return {
+ items: reuseGeneratedFilesRenderItems(built.items, generatedFilesItemCache),
+ singleResultMap: built.singleResultMap,
+ };
+}
+
type GeneratedFilesRenderItemRef = Extract<RenderItem, { type: 'generated_files' }>;
/**
@@ -3104,78 +3193,17 @@ export function MessageStream({
// MessageStream scope so history pagination and live deltas can share the
// parsed image targets without retaining state beyond the session mount.
const markdownImageTargetCacheRef = useRef<MarkdownImageTargetCache>(new Map());
- const { items: ungroupedRenderItems, singleResultMap } = useMemo(() => {
- 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, {
- historyWindowIncomplete: true,
- historyArtifacts,
- turnChangeSets,
- workingDir,
- botSessionId: simplifiedBotConversation ? sessionId : undefined,
- markdownImageTargetCache: markdownImageTargetCacheRef.current,
- cindyMakeSessionId,
- cindyMakeCompletionInComposer,
- subagentRunStatuses,
- });
- 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, generatedFilesItemCacheRef.current),
- singleResultMap: results,
- };
- }
- const built = streamProjection(
+ const { items: ungroupedRenderItems, singleResultMap } = useMemo(() => buildMessageStreamRenderProjection({
+ historyView, historySnapshot, historyLiveMessages, isSessionStreaming, handoff,
+ taskUpdates, ghostCardSnapshot,
+ generatedFilesItemCache: generatedFilesItemCacheRef.current,
+ renderOptions: {
+ turnChangeSets, workingDir,
+ botSessionId: simplifiedBotConversation ? sessionId : undefined,
+ markdownImageTargetCache: markdownImageTargetCacheRef.current,
+ cindyMakeSessionId, cindyMakeCompletionInComposer, subagentRunStatuses,
+ },
+ buildRaw: () => streamProjection(
displayMessages,
[
getDataOwnerGeneration(),
@@ -3207,12 +3235,8 @@ export function MessageStream({
subagentRunStatuses,
}),
!simplifiedBotConversation && !historyView,
- );
- return {
- items: reuseGeneratedFilesRenderItems(built.items, generatedFilesItemCacheRef.current),
- singleResultMap: built.singleResultMap,
- };
- }, [
+ ),
+ }), [
displayMessages,
cindyMakeSessionId,
cindyMakeCompletionInComposer,
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index d76af68e69..12d9a6e887 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -159,7 +159,7 @@ import { createTransientTopicSubscriptionCoordinator } from '@/device-link/trans
import { useMobileMakerTransport } from '@/device-link/useMobileMakerTransport';
import { findRemoteHistoryView, useRemoteHistoryView } from '@/session/remoteHistoryView';
import { HistoryViewHandoff, isHistoryViewUnavailable } from '@cindy/maker-shared/message-window';
-import { buildMobileHistoryRenderItems } from '@/session/mobileHistoryRender';
+import { buildMobileSessionRenderWindow } from '@/session/mobileHistoryRender';
import { createMobileMakerTransport } from '@/device-link/mobileMakerTransport';
import { startFocusedTopicSubscription } from '@/device-link/focusedTopicSubscription';
import { InteractionPanel, type MobilePlanViewerState } from '@/session/InteractionPanel';
@@ -579,15 +579,9 @@ import {
findHistoryWindowGap,
historyWindowGapKey,
} from '@/session/historyWindowGap';
+import type { MobileMessageRenderItem } from '@/session/messageRenderModel';
import {
- insertMobileForkOriginItem,
- type MobileMessageRenderItem,
-} from '@/session/messageRenderModel';
-import { reconcileMobileMessageRenderItems } from '@/session/messageRenderReconcile';
-import {
- buildMobileStreamingRenderWindow,
commitMobileStreamingPrefixItems,
- committedMobileStreamingPrefixItemCount,
type MobileStreamingRenderPrefixCache,
} from '@/session/messageRenderStreamingCache';
import { shouldSuppressEmptyMessageState } from '@/session/sessionEmptyState';
@@ -617,7 +611,6 @@ import {
findMobileRenderItemKeyByClientId,
MOBILE_MESSAGE_LIST_BOTTOM_PADDING,
} from '@/session/messageScroll';
-import { countMobileRenderItemDiffs } from '@/session/messagePresentation';
import {
buildMobileSessionDeepLink,
buildMobileSessionMessageDeepLink,
@@ -4738,69 +4731,30 @@ function SessionScreenContent() {
const streamingRenderPrefixRef = useRef<MobileStreamingRenderPrefixCache | null>(null);
const renderWindow = useMemo(
() => {
- // A ready history view owns the displayed sequence. Avoid normalizing the
- // unused raw transcript first, and retire its prefix before any fallback.
- if (historyView.snapshot.ready) streamingRenderPrefixRef.current = null;
- const builtWindow = historyView.snapshot.ready ? null : buildMobileStreamingRenderWindow({
- cacheKey: i18nInstance.language,
- messages: projectedMessages,
- messageStructureChangedIndexes: projectedMessageStructureChangedIndexes,
- messageStructureToken: renderMessageStructureToken,
- options: {
- autoResumePending: inputProjection.autoResumePending,
- preserveSourceOrder: optimisticUsers.length > 0,
- isSessionStreaming: isMessageListStreaming,
- renderOrphanTaskUpdates: makerTurnRunning,
- sessionId,
- sessionSource: currentSession?.source,
+ return buildMobileSessionRenderWindow({
+ raw: {
+ cacheKey: i18nInstance.language,
+ messages: projectedMessages,
+ messageStructureChangedIndexes: projectedMessageStructureChangedIndexes,
+ messageStructureToken: renderMessageStructureToken,
+ options: {
+ autoResumePending: inputProjection.autoResumePending,
+ preserveSourceOrder: optimisticUsers.length > 0,
+ isSessionStreaming: isMessageListStreaming,
+ renderOrphanTaskUpdates: makerTurnRunning,
+ sessionId,
+ sessionSource: currentSession?.source,
+ },
+ prefixCache: streamingRenderPrefixRef,
+ taskUpdates,
},
- prefixCache: streamingRenderPrefixRef,
- taskUpdates,
- });
- const historyItems = builtWindow ? builtWindow.items : buildMobileHistoryRenderItems({
- view: historyView.view, snapshot: historyView.snapshot, messages: projectedMessages,
- streaming: isMessageListStreaming, sessionId, sessionSource: currentSession?.source, taskUpdates,
- pendingHandoff: handoff.pending, staleTail: handoff.tail, localUserClientIds,
+ history: {
+ view: historyView.view, snapshot: historyView.snapshot, messages: projectedMessages,
+ streaming: isMessageListStreaming, sessionId, sessionSource: currentSession?.source, taskUpdates,
+ pendingHandoff: handoff.pending, staleTail: handoff.tail, localUserClientIds,
+ },
+ forkOrigin, errorTailClientId, previousRenderState: previousRenderItemsRef.current,
});
- let items = insertMobileForkOriginItem(
- // 孤儿 agent_task 兜底用 maker status 驱动的权威 turn 边界 gate,与 store 的
- // turn-start 清理同源闭环——渲染开启时 map 必已清过 stale。不用 isSessionStreaming
- // (含本地 sending / canStopQueue,发送→status 间隙会闪现残留),也不用
- // remoteSessionRunning(activity 推送 / 活跃快照会先置 true,重连场景渲染先于清理)。
- historyItems,
- forkOrigin,
- );
- if (errorTailClientId) {
- items = items.filter(
- (item) => !(item.type === 'message' && item.message.source.clientId === errorTailClientId),
- );
- }
- const previousRenderState = previousRenderItemsRef.current?.sessionId === sessionId
- ? previousRenderItemsRef.current
- : null;
- const previous = previousRenderState?.items ?? [];
- const committedPrefix = !builtWindow || forkOrigin || errorTailClientId
- ? null
- : builtWindow.prefix;
- const stablePrefixItemCount = !builtWindow || forkOrigin || errorTailClientId
- ? 0
- : committedMobileStreamingPrefixItemCount(
- builtWindow,
- previousRenderState?.prefix,
- );
- const reconciled = reconcileMobileMessageRenderItems(
- previous,
- items,
- stablePrefixItemCount,
- );
- return {
- diffCount: !builtWindow || errorTailClientId
- ? countMobileRenderItemDiffs(reconciled)
- : builtWindow.diffCount,
- items: reconciled,
- prefix: committedPrefix,
- stablePrefixItemCount,
- };
},
[optimisticUsers, currentSession?.source, localUserClientIds, renderMessageStructureToken, historyView.snapshot, historyView.view, handoff.pending, handoff.tail, errorTailClientId, forkOrigin, i18nInstance.language, inputProjection.autoResumePending, isMessageListStreaming, makerTurnRunning, messageStructureToken, projectedMessages, projectedMessageStructureChangedIndexes, sessionId, taskUpdates],
);
diff --git a/apps/mobile/src/__tests__/historyRenderBranch.test.ts b/apps/mobile/src/__tests__/historyRenderBranch.test.ts
deleted file mode 100644
index eec2691a61..0000000000
--- a/apps/mobile/src/__tests__/historyRenderBranch.test.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-import ts from 'typescript';
-import { expect, it, vi } from 'vitest';
-
-// Execute the screen's real memo body with render builders as the boundary.
-// Native mounting/timers are irrelevant to whether unused raw history is parsed.
-const source = ts.createSourceFile('session.tsx', readFileSync(resolve(process.cwd(),
- 'app/sessions/[sessionId].tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
-let callback: ts.Expression | undefined;
-function visit(node: ts.Node) {
- if (ts.isVariableDeclaration(node) && node.name.getText(source) === 'renderWindow'
- && node.initializer && ts.isCallExpression(node.initializer)) callback = node.initializer.arguments[0];
- ts.forEachChild(node, visit);
-}
-visit(source);
-if (!callback) throw new Error('Missing production render window');
-const code = ts.transpileModule(`return (${callback.getText(source)})();`, {
- compilerOptions: { target: ts.ScriptTarget.ES2022 },
-}).outputText;
-
-it.each([false, true])('builds only the displayed history source (ready=%s)', ready => {
- const rawItems = [{ key: 'raw' }];
- const historyItems = [{ key: 'history' }];
- const buildRaw = vi.fn(() => ({ items: rawItems, prefix: null, diffCount: 2 }));
- const buildHistory = vi.fn(() => historyItems);
- const prefixCache = { current: {} as unknown };
- const bindings = {
- buildMobileStreamingRenderWindow: buildRaw, buildMobileHistoryRenderItems: buildHistory,
- i18nInstance: { language: 'en' }, projectedMessages: [], projectedMessageStructureChangedIndexes: [],
- renderMessageStructureToken: {}, inputProjection: {}, optimisticUsers: [], isMessageListStreaming: false,
- makerTurnRunning: false, sessionId: 's', currentSession: {}, streamingRenderPrefixRef: prefixCache,
- taskUpdates: new Map(), historyView: { snapshot: { ready }, view: {} }, handoff: {}, localUserClientIds: new Set(),
- insertMobileForkOriginItem: (items: unknown) => items, forkOrigin: null, errorTailClientId: null,
- previousRenderItemsRef: { current: null }, committedMobileStreamingPrefixItemCount: () => 0,
- reconcileMobileMessageRenderItems: (_previous: unknown, items: unknown) => items,
- countMobileRenderItemDiffs: () => 7,
- };
- const result = new Function(...Object.keys(bindings), code)(...Object.values(bindings));
- expect(result.items).toBe(ready ? historyItems : rawItems);
- expect(result.diffCount).toBe(ready ? 7 : 2);
- expect(buildRaw).toHaveBeenCalledTimes(ready ? 0 : 1);
- expect(buildHistory).toHaveBeenCalledTimes(ready ? 1 : 0);
- if (ready) expect(prefixCache.current).toBeNull();
-});
diff --git a/apps/mobile/src/__tests__/mobileHistoryRender.test.ts b/apps/mobile/src/__tests__/mobileHistoryRender.test.ts
index 3588244e58..7ac4eb692f 100644
--- a/apps/mobile/src/__tests__/mobileHistoryRender.test.ts
+++ b/apps/mobile/src/__tests__/mobileHistoryRender.test.ts
@@ -1,9 +1,10 @@
import { describe, expect, it, vi } from 'vitest';
import { HistoryViewController, projectHistoryView, type HistoryWorkSummary } from '@cindy/maker-shared/message-window';
-import { buildMobileHistoryRenderItems } from '../session/mobileHistoryRender';
+import { buildMobileHistoryRenderItems, buildMobileSessionRenderWindow } from '../session/mobileHistoryRender';
import { buildMobileMessageRenderItems, type MobileMessageRenderItem } from '../session/messageRenderModel';
import type { RemoteMessage } from '../session/types';
import { reconcileMobileMessageRenderItems } from '../session/messageRenderReconcile';
+import { buildMobileStreamingRenderWindow } from '../session/messageRenderStreamingCache';
import { CONTINUE_AFTER_ERROR_PROMPT } from '@cindy/maker-shared/synthetic-trigger';
function row(index: number, role: RemoteMessage['role'], content: unknown, toolUseId: string | null = null): RemoteMessage {
@@ -258,3 +259,34 @@ it.each([true, false])('loads a folded subagent only on expansion while retainin
}
view.setActive(false);
});
+
+// Unit: existing history rendering tests bypassed the screen's source selection.
+// Minimal regression: distinct cached/raw answers with a previously warmed prefix.
+it.each([false, true])('selects visible rows without reading unused raw bodies (ready=%s)', async ready => {
+ const { view } = harness([row(10, 'assistant', 'Cached answer')]);
+ if (ready) await view.refresh();
+ const prefixCache = { current: null as ReturnType<typeof buildMobileStreamingRenderWindow>['prefix'] };
+ const warmed = [row(0, 'user', 'First'), row(1, 'assistant', 'Done'), row(2, 'user', 'Next'),
+ { ...row(3, 'assistant', 'Streaming'), agentMeta: { isStreaming: true } }];
+ buildMobileStreamingRenderWindow({ cacheKey: 'en', messages: warmed,
+ options: { sessionId: 'session', isSessionStreaming: true }, prefixCache });
+ expect(prefixCache.current).not.toBeNull();
+ const readRawBody = vi.fn(() => 'Raw answer');
+ const raw = row(4, 'assistant', '');
+ Object.defineProperty(raw, 'content', { get: readRawBody });
+ const result = buildMobileSessionRenderWindow({
+ raw: { cacheKey: 'en', messages: [raw], options: { sessionId: 'session' }, prefixCache },
+ history: { view, snapshot: view.getSnapshot(), messages: [], streaming: false, sessionId: 'session' },
+ });
+ expect(result.items).toMatchObject([{ type: 'message', message: { body: ready ? 'Cached answer' : 'Raw answer' } }]);
+ expect(result.diffCount).toBe(0);
+ expect(result.prefix).toBeNull();
+ expect(result.stablePrefixItemCount).toBe(0);
+ if (ready) {
+ expect(readRawBody).not.toHaveBeenCalled();
+ expect(prefixCache.current).toBeNull();
+ } else {
+ expect(readRawBody).toHaveBeenCalled();
+ }
+ view.setActive(false);
+});
diff --git a/apps/mobile/src/session/mobileHistoryRender.ts b/apps/mobile/src/session/mobileHistoryRender.ts
index 4c85da9c11..7845c92d07 100644
--- a/apps/mobile/src/session/mobileHistoryRender.ts
+++ b/apps/mobile/src/session/mobileHistoryRender.ts
@@ -1,7 +1,11 @@
import { renderHistoryView, type HistoryViewController, type HistoryViewSnapshot } from '@cindy/maker-shared/message-window';
import type { AgentTaskUpdate } from '@cindy/maker-shared/agent-task';
-import { buildMobileMessageRenderItems, type MobileMessageRenderItem, type MobileWorkChildItem } from './messageRenderModel';
+import { buildMobileMessageRenderItems, insertMobileForkOriginItem, type MobileForkOrigin, type MobileMessageRenderItem, type MobileWorkChildItem } from './messageRenderModel';
import type { RemoteMessage } from './types';
+import { buildMobileStreamingRenderWindow, committedMobileStreamingPrefixItemCount,
+ type MobileStreamingRenderPrefixCache } from './messageRenderStreamingCache';
+import { reconcileMobileMessageRenderItems } from './messageRenderReconcile';
+import { countMobileRenderItemDiffs } from './messagePresentation';
export function buildMobileHistoryRenderItems(options: {
view: HistoryViewController<RemoteMessage>;
@@ -46,3 +50,57 @@ export function buildMobileHistoryRenderItems(options: {
},
});
}
+
+/** The screen's full render window, shared by history takeover and raw fallback. */
+export function buildMobileSessionRenderWindow({
+ history, raw, previousRenderState, forkOrigin, errorTailClientId,
+}: {
+ history: Parameters<typeof buildMobileHistoryRenderItems>[0];
+ raw: Parameters<typeof buildMobileStreamingRenderWindow>[0];
+ previousRenderState?: {
+ sessionId: string;
+ items: readonly MobileMessageRenderItem[];
+ prefix: MobileStreamingRenderPrefixCache | null;
+ } | null;
+ forkOrigin?: MobileForkOrigin | null;
+ errorTailClientId?: string | null;
+}) {
+ // A ready history view owns the displayed sequence. Retire the raw prefix
+ // before a later fallback, and never normalize a transcript we will not show.
+ if (history.snapshot.ready && raw.prefixCache) raw.prefixCache.current = null;
+ const builtWindow = history.snapshot.ready ? null : buildMobileStreamingRenderWindow(raw);
+ const historyItems = builtWindow ? builtWindow.items : buildMobileHistoryRenderItems(history);
+ let items = insertMobileForkOriginItem(
+ historyItems,
+ forkOrigin,
+ );
+ if (errorTailClientId) {
+ items = items.filter(
+ (item) => !(item.type === 'message' && item.message.source.clientId === errorTailClientId),
+ );
+ }
+ const committed = previousRenderState?.sessionId === history.sessionId ? previousRenderState : null;
+ const previous = committed?.items ?? [];
+ const committedPrefix = !builtWindow || forkOrigin || errorTailClientId
+ ? null
+ : builtWindow.prefix;
+ const stablePrefixItemCount = !builtWindow || forkOrigin || errorTailClientId
+ ? 0
+ : committedMobileStreamingPrefixItemCount(
+ builtWindow,
+ committed?.prefix,
+ );
+ const reconciled = reconcileMobileMessageRenderItems(
+ previous,
+ items,
+ stablePrefixItemCount,
+ );
+ return {
+ diffCount: !builtWindow || errorTailClientId
+ ? countMobileRenderItemDiffs(reconciled)
+ : builtWindow.diffCount,
+ items: reconciled,
+ prefix: committedPrefix,
+ stablePrefixItemCount,
+ };
+}