Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 修正流式渲染缓存提交边界
DavidShenb7dad224b00f
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex 15ce5dfc61..55d29b14b2 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -474,6 +474,8 @@ import {import { reconcileMobileMessageRenderItems } from '@/session/messageRenderReconcile';import {buildMobileStreamingRenderWindow,+ commitMobileStreamingPrefixItems,+ committedMobileStreamingPrefixItemCount,type MobileStreamingRenderPrefixCache,} from '@/session/messageRenderStreamingCache';import { shouldSuppressEmptyMessageState } from '@/session/sessionEmptyState';@@ -4647,6 +4649,7 @@ export default function SessionScreen() {const previousRenderItemsRef = useRef<{sessionId: string;items: readonly MobileMessageRenderItem[];+ prefix: MobileStreamingRenderPrefixCache | null;} | null>(null);const streamingRenderPrefixRef = useRef<MobileStreamingRenderPrefixCache | null>(null);const renderWindow = useMemo(@@ -4678,12 +4681,19 @@ export default function SessionScreen() {(item) => !(item.type === 'message' && item.message.source.clientId === errorTailClientId),);}- const previous = previousRenderItemsRef.current?.sessionId === sessionId- ? previousRenderItemsRef.current.items- : [];+ const previousRenderState = previousRenderItemsRef.current?.sessionId === sessionId+ ? previousRenderItemsRef.current+ : null;+ const previous = previousRenderState?.items ?? [];+ const committedPrefix = forkOrigin || errorTailClientId+ ? null+ : builtWindow.prefix;const stablePrefixItemCount = forkOrigin || errorTailClientId? 0- : builtWindow.stablePrefixItemCount;+ : committedMobileStreamingPrefixItemCount(+ builtWindow,+ previousRenderState?.prefix,+ );const reconciled = reconcileMobileMessageRenderItems(previous,items,@@ -4694,6 +4704,7 @@ export default function SessionScreen() {? countMobileRenderItemDiffs(reconciled): builtWindow.diffCount,items: reconciled,+ prefix: committedPrefix,stablePrefixItemCount,};},@@ -4707,8 +4718,19 @@ export default function SessionScreen() {// Reconciliation must only use committed rows. Unlike the prefix cache above, a speculative// render-item baseline could leak rows from an abandoned render and destabilize tail memoization.useLayoutEffect(() => {- previousRenderItemsRef.current = { sessionId, items: renderItems };- }, [renderItems, sessionId]);+ if (+ renderWindow.prefix+ && previousRenderItemsRef.current?.prefix !== renderWindow.prefix+ && streamingRenderPrefixRef.current === renderWindow.prefix+ ) {+ commitMobileStreamingPrefixItems(renderWindow.prefix, renderItems);+ }+ previousRenderItemsRef.current = {+ sessionId,+ items: renderItems,+ prefix: renderWindow.prefix,+ };+ }, [renderItems, renderWindow.prefix, sessionId]);// 后台静默刷新:仅在首次加载、还没有任何内容(messages 为空)时显示"正在同步";已有内容// (重开已看过的会话,messages 还在内存)时后台对账一律静默,不再弹同步提示打扰用户。const showSyncingIndicator = loading && messages.length === 0;diff --git a/apps/mobile/src/__tests__/messagePerformance.test.ts b/apps/mobile/src/__tests__/messagePerformance.test.tsindex dec209d121..7fa1d184cc 100644--- a/apps/mobile/src/__tests__/messagePerformance.test.ts+++ b/apps/mobile/src/__tests__/messagePerformance.test.ts@@ -3,7 +3,11 @@ import type { AgentTaskUpdate } from '@cindy/maker-shared/agent-task';import { describe, expect, it } from 'vitest';import { buildMobileMessageRenderItems, type MobileMessageRenderItem } from '@/session/messageRenderModel';import { reconcileMobileMessageRenderItems } from '@/session/messageRenderReconcile';-import { buildMobileStreamingRenderWindow } from '@/session/messageRenderStreamingCache';+import {+ buildMobileStreamingRenderWindow,+ commitMobileStreamingPrefixItems,+ committedMobileStreamingPrefixItemCount,+} from '@/session/messageRenderStreamingCache';import { countMobileRenderItemDiffs } from '@/session/messagePresentation';import type { RemoteMessage } from '@/session/types';@@ -354,6 +358,220 @@ describe('message render performance', () => {expect(changed.items).toEqual(buildMobileMessageRenderItems(changedMessages, options));});+ it('invalidates the reusable prefix when its render cache key changes', () => {+ const historicalAssistant = message({+ id: 'cache-key-history',+ role: 'assistant',+ content: 'Earlier result',+ createdAt: timestamp(1),+ });+ const stableAssistant = message({+ id: 'cache-key-boundary',+ role: 'assistant',+ content: 'First phase complete',+ createdAt: timestamp(2),+ });+ const activeThinking = message({+ id: 'cache-key-thinking',+ role: 'thinking',+ content: { kind: 'thinking', text: 'Continuing', isStreaming: true },+ createdAt: timestamp(3),+ });+ const activeAssistant = message({+ id: 'cache-key-active-assistant',+ role: 'assistant',+ content: 'Partial',+ agentMeta: { isStreaming: true },+ createdAt: timestamp(4),+ });+ const messages = [+ historicalAssistant,+ stableAssistant,+ activeThinking,+ activeAssistant,+ ];+ const messageStructureToken = {};+ const messageStructureChangedIndexes = new Set([messages.length - 1]);+ const options = { isSessionStreaming: true, sessionId: 's1' } as const;+ const first = buildMobileStreamingRenderWindow({+ cacheKey: 'en',+ messages,+ messageStructureChangedIndexes,+ messageStructureToken,+ options,+ });+ expect(first.prefix?.mode).toBe('truncated-turn');++ const changed = buildMobileStreamingRenderWindow({+ cacheKey: 'zh-CN',+ messages,+ messageStructureChangedIndexes,+ messageStructureToken,+ options,+ previousPrefix: first.prefix,+ });++ expect(changed.prefix).not.toBe(first.prefix);+ expect(changed.prefix?.cacheKey).toBe('zh-CN');+ expect(changed.stablePrefixItemCount).toBe(0);+ expect(changed.items).toEqual(buildMobileMessageRenderItems(messages, options));++ const cacheKeyChangedItems = reconcileMobileMessageRenderItems(+ first.items,+ changed.items,+ committedMobileStreamingPrefixItemCount(changed, first.prefix),+ );+ expect(changed.prefix).not.toBeNull();+ commitMobileStreamingPrefixItems(changed.prefix!, cacheKeyChangedItems);++ const updatedMessages = [+ historicalAssistant,+ stableAssistant,+ activeThinking,+ { ...activeAssistant, content: 'Partial update' },+ ];+ const updated = buildMobileStreamingRenderWindow({+ cacheKey: 'zh-CN',+ messages: updatedMessages,+ messageStructureChangedIndexes,+ messageStructureToken,+ options,+ previousPrefix: changed.prefix,+ });+ expect(updated.prefix).toBe(changed.prefix);+ const updatedItems = reconcileMobileMessageRenderItems(+ cacheKeyChangedItems,+ updated.items,+ committedMobileStreamingPrefixItemCount(updated, changed.prefix),+ );+ const changedRows = updatedItems.reduce(+ (count, item, index) => count + (item === cacheKeyChangedItems[index] ? 0 : 1),+ 0,+ );+ expect(changedRows).toBe(1);+ });++ it('reconciles a speculative changed prefix before reusing committed rows', () => {+ const historicalAssistant = message({+ id: 'speculative-prefix-history',+ role: 'assistant',+ content: 'Original history',+ createdAt: timestamp(1),+ });+ const activeUser = message({+ id: 'speculative-prefix-user',+ role: 'user',+ content: 'Continue',+ createdAt: timestamp(2),+ });+ const activeAssistant = message({+ id: 'speculative-prefix-assistant',+ role: 'assistant',+ content: 'Partial',+ agentMeta: { isStreaming: true },+ createdAt: timestamp(3),+ });+ const initialMessages = [historicalAssistant, activeUser, activeAssistant];+ const messageStructureToken = {};+ const prefixCache: {+ current: ReturnType<typeof buildMobileStreamingRenderWindow>['prefix'];+ } = { current: null };+ const options = { isSessionStreaming: true, sessionId: 's1' } as const;+ const committedWindow = buildMobileStreamingRenderWindow({+ cacheKey: 'en',+ messages: initialMessages,+ messageStructureChangedIndexes: new Set([2]),+ messageStructureToken,+ options,+ prefixCache,+ });+ const committedItems = reconcileMobileMessageRenderItems([], committedWindow.items);++ const changedHistoricalAssistant = {+ ...historicalAssistant,+ content: 'Corrected history',+ };+ const changedMessages = [changedHistoricalAssistant, activeUser, activeAssistant];+ const interruptedWindow = buildMobileStreamingRenderWindow({+ cacheKey: 'en',+ messages: changedMessages,+ messageStructureChangedIndexes: new Set([0, 2]),+ messageStructureToken,+ options,+ prefixCache,+ });+ expect(interruptedWindow.prefix).not.toBe(committedWindow.prefix);++ // Model a retry after React abandons the render above. The speculative prefix is reusable by+ // the builder, but it has never been reconciled against the last committed rows.+ const retryWindow = buildMobileStreamingRenderWindow({+ cacheKey: 'en',+ messages: changedMessages,+ messageStructureChangedIndexes: new Set([2]),+ messageStructureToken,+ options,+ prefixCache,+ });+ expect(retryWindow.prefix).toBe(interruptedWindow.prefix);+ expect(retryWindow.stablePrefixItemCount).toBeGreaterThan(0);+ const retryStablePrefixItemCount = committedMobileStreamingPrefixItemCount(+ retryWindow,+ committedWindow.prefix,+ );+ expect(retryStablePrefixItemCount).toBe(0);++ const correctedItems = reconcileMobileMessageRenderItems(+ committedItems,+ retryWindow.items,+ retryStablePrefixItemCount,+ );+ expect(correctedItems).not.toBe(committedItems);+ expect(correctedItems).toEqual(buildMobileMessageRenderItems(changedMessages, options));+ commitMobileStreamingPrefixItems(retryWindow.prefix!, correctedItems);++ // Once that prefix commits, identical input should retain the complete list reference and not+ // schedule duplicate row renders.+ const unchangedWindow = buildMobileStreamingRenderWindow({+ cacheKey: 'en',+ messages: changedMessages,+ messageStructureChangedIndexes: new Set([2]),+ messageStructureToken,+ options,+ prefixCache,+ });+ const unchangedItems = reconcileMobileMessageRenderItems(+ correctedItems,+ unchangedWindow.items,+ committedMobileStreamingPrefixItemCount(unchangedWindow, retryWindow.prefix),+ );+ expect(unchangedItems).toBe(correctedItems);+ expect(new Set(unchangedItems.map((item) => item.key)).size).toBe(unchangedItems.length);++ const tailUpdatedMessages = [+ changedHistoricalAssistant,+ activeUser,+ { ...activeAssistant, content: 'Partial update' },+ ];+ const tailUpdatedWindow = buildMobileStreamingRenderWindow({+ cacheKey: 'en',+ messages: tailUpdatedMessages,+ messageStructureChangedIndexes: new Set([2]),+ messageStructureToken,+ options,+ prefixCache,+ });+ const tailUpdatedItems = reconcileMobileMessageRenderItems(+ correctedItems,+ tailUpdatedWindow.items,+ committedMobileStreamingPrefixItemCount(tailUpdatedWindow, retryWindow.prefix),+ );+ const changedRows = tailUpdatedItems.reduce(+ (count, item, index) => count + (item === correctedItems[index] ? 0 : 1),+ 0,+ );+ expect(changedRows).toBe(1);+ });+it('invalidates a historical prefix only when one of its task updates changes', () => {const prefixTask = message({id: 'historical-prefix-task',diff --git a/apps/mobile/src/session/messageRenderStreamingCache.ts b/apps/mobile/src/session/messageRenderStreamingCache.tsindex 5f795eef5f..dc60ddc682 100644--- a/apps/mobile/src/session/messageRenderStreamingCache.ts+++ b/apps/mobile/src/session/messageRenderStreamingCache.ts@@ -63,6 +63,29 @@ export interface MobileStreamingRenderWindowResult {stablePrefixItemCount: number;}+/**+ * Only a prefix that participated in the previous committed render can safely skip reconciliation.+ * A concurrently abandoned render may publish a newer speculative prefix into the cache; its rows+ * still need to be compared with the last committed rows before React can reuse them.+ */+export function committedMobileStreamingPrefixItemCount(+ renderWindow: MobileStreamingRenderWindowResult,+ committedPrefix: MobileStreamingRenderPrefixCache | null | undefined,+): number {+ return renderWindow.prefix !== null && renderWindow.prefix === committedPrefix+ ? renderWindow.stablePrefixItemCount+ : 0;+}++/** Keep a newly committed cache prefix on the exact row objects React received. */+export function commitMobileStreamingPrefixItems(+ prefix: MobileStreamingRenderPrefixCache,+ committedItems: readonly MobileMessageRenderItem[],+): void {+ if (prefix.items.length > committedItems.length) return;+ prefix.items = committedItems.slice(0, prefix.items.length);+}+/*** Rebuild only the active turn while a session streams.*@@ -324,6 +347,9 @@ function buildTruncatedActiveTurnWindow(});const prefix = previousPrefix?.mode === 'truncated-turn'&& builtPrefix !== null+ && previousPrefix.cacheKey === cacheKey+ && previousPrefix.messageStructureToken === messageStructureToken+ && previousPrefix.sessionId === sessionId&& builtPrefix.boundaryMessage === previousPrefix.boundaryMessage&& sameTaskUpdateDependencySnapshots(builtPrefix.taskUpdateDependencies,