Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): harden large session history rendering
DavidShen0110985c18c2
diff --git a/apps/mobile/app/devices/[deviceId].tsx b/apps/mobile/app/devices/[deviceId].tsxindex 1720a2af68..892d3bfafc 100644--- a/apps/mobile/app/devices/[deviceId].tsx+++ b/apps/mobile/app/devices/[deviceId].tsx@@ -1,4 +1,4 @@-import { useLocalSearchParams, useRouter } from 'expo-router';+import { useIsFocused, useLocalSearchParams, useRouter } from 'expo-router';import { useCallback, useEffect, useMemo, useState } from 'react';import {ActivityIndicator,@@ -81,6 +81,7 @@ import type { SessionSwipeAction } from '@/session/swipeRowRegistry';import { useSessionListActions } from '@/session/useSessionListActions';import { useMobileMakerTransport } from '@/device-link/useMobileMakerTransport';import {+ RemoteSessionStoreSubscriptionGate,remoteSessionStore,useRemoteMessageVersion,useRemoteSessions,@@ -115,6 +116,15 @@ const STATUS_FILTERS: Array<{ value: RemoteSessionStatusFilter; labelKey: stringtype RemoteListStatusFilter = Extract<RemoteSessionStatusFilter, 'active' | 'archived' | 'all'>;export default function DeviceDetailScreen() {+ const screenFocused = useIsFocused();+ return (+ <RemoteSessionStoreSubscriptionGate enabled={screenFocused}>+ <DeviceDetailScreenContent />+ </RemoteSessionStoreSubscriptionGate>+ );+}++function DeviceDetailScreenContent() {const styles = useThemedStyles(makeStyles);const { colors } = useTheme();const { t, i18n: i18nInstance } = useTranslation();@@ -790,6 +800,9 @@ export default function DeviceDetailScreen() {<SectionListsections={displaySections}keyExtractor={(item) => item.automationGroup?.key ?? item.session.id}+ // Fabric can reattach a clipped Swipeable child before its old native parent removes it.+ // Keep JS virtualization, but avoid the Android native detach/reattach race for this list.+ removeClippedSubviews={false}refreshControl={<RefreshControl refreshing={loading} onRefresh={loadSessions} />}stickySectionHeadersEnabled={false}renderSectionHeader={() => null}diff --git a/apps/mobile/app/devices/index.tsx b/apps/mobile/app/devices/index.tsxindex ba0a5bbe55..fbb0b3342c 100644--- a/apps/mobile/app/devices/index.tsx+++ b/apps/mobile/app/devices/index.tsx@@ -1,4 +1,4 @@-import { useFocusEffect } from 'expo-router';+import { useFocusEffect, useIsFocused } from 'expo-router';import { Fragment, memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type MutableRefObject, type ReactNode } from 'react';import {ActivityIndicator,@@ -192,6 +192,7 @@ import {type RemoteSessionStatusFilter,} from '@/session/sessionList';import {+ RemoteSessionStoreSubscriptionGate,remoteSessionStore,useRemoteMessageVersion,useRemoteSessions,@@ -323,6 +324,15 @@ class HomeSyncScopeSupersededError extends Error {}export default function HomeScreen() {+ const screenFocused = useIsFocused();+ return (+ <RemoteSessionStoreSubscriptionGate enabled={screenFocused}>+ <HomeScreenContent />+ </RemoteSessionStoreSubscriptionGate>+ );+}++function HomeScreenContent() {const styles = useThemedStyles(makeStyles);const { colors } = useTheme();const { t, i18n: i18nInstance } = useTranslation();diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex 141c381821..48ac02a140 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -467,11 +467,14 @@ import {historyWindowGapKey,} from '@/session/historyWindowGap';import {- buildMobileMessageRenderItems,insertMobileForkOriginItem,type MobileMessageRenderItem,} from '@/session/messageRenderModel';import { reconcileMobileMessageRenderItems } from '@/session/messageRenderReconcile';+import {+ buildMobileStreamingRenderWindow,+ type MobileStreamingRenderPrefixCache,+} from '@/session/messageRenderStreamingCache';import { shouldSuppressEmptyMessageState } from '@/session/sessionEmptyState';import { deferScheduleIndexHydration } from '@/session/scheduleIndexDefer';import { markSessionScheduleRunsRead, unreadRunIdFromProjection } from '@/session/scheduleRunRead';@@ -4616,18 +4619,27 @@ export default function SessionScreen() {sessionId: string;items: readonly MobileMessageRenderItem[];} | null>(null);+ const streamingRenderPrefixRef = useRef<MobileStreamingRenderPrefixCache | null>(null);const renderItems = useMemo(() => {+ const builtWindow = buildMobileStreamingRenderWindow({+ cacheKey: i18nInstance.language,+ messages: projectLoadedMessageWindow(messages),+ options: {+ autoResumePending: inputProjection.autoResumePending,+ isSessionStreaming,+ renderOrphanTaskUpdates: makerTurnRunning,+ sessionId,+ },+ prefixCache: streamingRenderPrefixRef,+ taskUpdates,+ });let items = insertMobileForkOriginItem(// 孤儿 agent_task 兜底用 maker status 驱动的权威 turn 边界 gate,与 store 的// turn-start 清理同源闭环——渲染开启时 map 必已清过 stale。不用 isSessionStreaming// (含本地 sending / canStopQueue,发送→status 间隙会闪现残留),也不用// remoteSessionRunning(activity 推送 / 活跃快照会先置 true,重连场景渲染先于清理)。- buildMobileMessageRenderItems(- projectLoadedMessageWindow(messages),- { autoResumePending: inputProjection.autoResumePending, isSessionStreaming, renderOrphanTaskUpdates: makerTurnRunning, sessionId },- taskUpdates,- ),+ builtWindow.items,forkOrigin,);if (errorTailClientId) {@@ -4643,8 +4655,8 @@ export default function SessionScreen() {},[errorTailClientId, forkOrigin, i18nInstance.language, inputProjection.autoResumePending, isSessionStreaming, makerTurnRunning, messages, sessionId, taskUpdates],);- // 只在本次 render 真正 commit 后更新 reconcile 基准。写入 useMemo/ref 会让- // Concurrent Mode 下被丢弃的 render 泄漏成下一轮的 previous,破坏尾行 memo 的稳定性。+ // 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]);diff --git a/apps/mobile/src/__tests__/deviceDetailProjectListFabric.test.ts b/apps/mobile/src/__tests__/deviceDetailProjectListFabric.test.tsnew file mode 100644index 0000000000..a30ba77304--- /dev/null+++ b/apps/mobile/src/__tests__/deviceDetailProjectListFabric.test.ts@@ -0,0 +1,20 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { describe, expect, it } from 'vitest';++const source = readFileSync(+ resolve(process.cwd(), 'app/devices/[deviceId].tsx'),+ 'utf8',+);++describe('device detail project list Fabric lifecycle', () => {+ it('keeps Android clipping disabled for the swipeable project list', () => {+ const testIdIndex = source.indexOf('testID="deviceDetail.projectSessionList"');+ const listStart = source.lastIndexOf('<SectionList', testIdIndex);+ const listProps = source.slice(listStart, testIdIndex);++ expect(testIdIndex).toBeGreaterThan(0);+ expect(listStart).toBeGreaterThan(0);+ expect(listProps).toContain('removeClippedSubviews={false}');+ });+});diff --git a/apps/mobile/src/__tests__/inactiveSessionListSubscriptions.test.ts b/apps/mobile/src/__tests__/inactiveSessionListSubscriptions.test.tsnew file mode 100644index 0000000000..4700e91032--- /dev/null+++ b/apps/mobile/src/__tests__/inactiveSessionListSubscriptions.test.ts@@ -0,0 +1,34 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { describe, expect, it } from 'vitest';++function source(path: string): string {+ return readFileSync(resolve(process.cwd(), path), 'utf8');+}++describe('inactive session list subscriptions', () => {+ it('gates both mounted list routes by navigation focus', () => {+ for (const path of ['app/devices/index.tsx', 'app/devices/[deviceId].tsx']) {+ const screen = source(path);+ expect(screen).toContain('const screenFocused = useIsFocused();');+ expect(screen).toContain(+ '<RemoteSessionStoreSubscriptionGate enabled={screenFocused}>',+ );+ }+ });++ it('pauses list and row subscriptions while their route is covered', () => {+ const store = source('src/session/remoteSessionStore.ts');+ expect(store).toContain(+ 'enabled ? remoteSessionStore.subscribe : INACTIVE_REMOTE_SESSION_STORE_SUBSCRIBE',+ );+ expect(store).toContain(+ "usePausableRemoteSessionStoreSnapshot('sessions', remoteSessionStore.getSessions)",+ );+ expect(store).toContain("'message-version',\n remoteSessionStore.getMessageVersion");+ expect(store).toContain("'store-version',\n remoteSessionStore.getStoreVersion");+ expect(store).toContain(+ '() => remoteSessionStore.isSessionRunning(sessionId)',+ );+ });+});diff --git a/apps/mobile/src/__tests__/messageHistoryAnchor.test.ts b/apps/mobile/src/__tests__/messageHistoryAnchor.test.tsindex 2769867e6a..5596fb0a46 100644--- a/apps/mobile/src/__tests__/messageHistoryAnchor.test.ts+++ b/apps/mobile/src/__tests__/messageHistoryAnchor.test.ts@@ -2,8 +2,16 @@ import { describe, expect, it } from 'vitest';import {captureMobileHistoryAnchor,isMobileHistoryAnchorSettled,+ mobileHistoryTopOffsetAdjustment,resolveMobileHistoryAnchorOffset,} from '@/session/messageHistoryAnchor';+import {+ mobileMessageHistoryAnchorIdentity,+ mobileMessageHistoryOnlyExpandedFirstWorkGroup,+ mobileMessageHistoryRowKeyByIdentity,+} from '@/session/messageHistoryAnchorIdentity';+import { buildMobileMessageRenderItems } from '@/session/messageRenderModel';+import type { RemoteMessage } from '@/session/types';describe('messageHistoryAnchor', () => {it('captures the first visible row in LegendList coordinates', () => {@@ -80,12 +88,48 @@ describe('messageHistoryAnchor', () => {});it('keeps the same row at the same viewport offset after a prepend', () => {+ let identityScans = 0;const target = resolveMobileHistoryAnchorOffset(- { key: 'm80', viewportOffset: -30 },- { positionByKey: (key) => key === 'm80' ? 11_300 : undefined },+ { key: 'm80', identityKey: 'leaf-m80', viewportOffset: -30 },+ {+ keyByIdentity: () => {+ identityScans += 1;+ return 'm80';+ },+ positionByKey: (key) => key === 'm80' ? 11_300 : undefined,+ },);expect(target).toBe(11_330);+ expect(identityScans).toBe(0);+ });++ it('recovers the align-at-end spacer for an under-one-screen list', () => {+ expect(mobileHistoryTopOffsetAdjustment({+ contentLength: 720,+ data: [{ key: 'm1' }, { key: 'm2' }],+ positionAtIndex: (index) => [0, 120][index],+ scrollLength: 720,+ sizeAtIndex: (index) => [96, 168][index],+ }, {+ baseTopOffset: 64,+ bottomPadding: 32,+ footerSize: 0,+ })).toBe(400);+ });++ it('uses the explicit header and padding baseline once content overflows', () => {+ expect(mobileHistoryTopOffsetAdjustment({+ contentLength: 1_200,+ data: [{ key: 'm1' }, { key: 'm2' }],+ positionAtIndex: (index) => [0, 840][index],+ scrollLength: 720,+ sizeAtIndex: (index) => [816, 296][index],+ }, {+ baseTopOffset: 64,+ bottomPadding: 32,+ footerSize: 0,+ })).toBe(64);});it('re-resolves the target when older row measurements settle', () => {@@ -108,6 +152,51 @@ describe('messageHistoryAnchor', () => {})).toBe(11_380);});+ it('resolves an aggregate row whose outer key changed after same-turn history was prepended', () => {+ const before = buildMobileMessageRenderItems([+ toolUse('tool-b', 2),+ assistantMessage('answer', 3),+ ]);+ const after = buildMobileMessageRenderItems([+ toolUse('tool-a', 1),+ toolUse('tool-b', 2),+ assistantMessage('answer', 3),+ ]);+ const beforeGroup = before[0];+ const afterGroup = after[0];+ expect(beforeGroup.type).toBe('work_group');+ expect(afterGroup.type).toBe('work_group');+ expect(after).toHaveLength(before.length);+ expect(afterGroup.key).not.toBe(beforeGroup.key);++ const identityKey = mobileMessageHistoryAnchorIdentity(beforeGroup);+ expect(identityKey).toBeTruthy();+ expect(mobileMessageHistoryRowKeyByIdentity(after, identityKey!)).toBe(afterGroup.key);+ expect(mobileMessageHistoryOnlyExpandedFirstWorkGroup(before, before)).toBe(false);+ expect(mobileMessageHistoryOnlyExpandedFirstWorkGroup(before, after)).toBe(true);+ expect(mobileMessageHistoryOnlyExpandedFirstWorkGroup(before, buildMobileMessageRenderItems([+ userMessage('earlier-user', 0),+ toolUse('tool-a', 1),+ toolUse('tool-b', 2),+ assistantMessage('answer', 3),+ ]))).toBe(false);+ const anchor = captureMobileHistoryAnchor({+ data: before,+ positionAtIndex: (index) => [0, 180][index],+ scroll: 0,+ start: 0,+ topOffsetAdjustment: 400,+ }, (item) => item.key, mobileMessageHistoryAnchorIdentity);+ expect(anchor?.key).toBe(beforeGroup.key);+ expect(anchor?.viewportOffset).toBe(400);+ expect(resolveMobileHistoryAnchorOffset(anchor!, {+ data: after,+ keyByIdentity: (identity) => mobileMessageHistoryRowKeyByIdentity(after, identity),+ positionByKey: (key) => key === afterGroup.key ? 600 : undefined,+ topOffsetAdjustment: 64,+ })).toBe(264);+ });+it('falls back to the current data index while LegendList rebuilds its key cache', () => {expect(resolveMobileHistoryAnchorOffset({ key: 'm80', viewportOffset: -30 }, {data: [{ key: 'older' }, { key: 'm80' }],@@ -122,3 +211,46 @@ describe('messageHistoryAnchor', () => {expect(isMobileHistoryAnchorSettled(11_329, 11_330, 11_331, 2)).toBe(true);});});++function toolUse(id: string, seconds: number): RemoteMessage {+ return {+ id,+ clientId: id,+ sessionId: 's1',+ role: 'tool_use',+ content: {+ toolUseId: id,+ toolName: 'Read',+ input: { file_path: `/${id}.ts` },+ },+ toolUseId: id,+ agentMeta: null,+ createdAt: `2026-01-01T00:00:0${seconds}.000Z`,+ };+}++function assistantMessage(id: string, seconds: number): RemoteMessage {+ return {+ id,+ clientId: id,+ sessionId: 's1',+ role: 'assistant',+ content: 'done',+ toolUseId: null,+ agentMeta: null,+ createdAt: `2026-01-01T00:00:0${seconds}.000Z`,+ };+}++function userMessage(id: string, seconds: number): RemoteMessage {+ return {+ id,+ clientId: id,+ sessionId: 's1',+ role: 'user',+ content: id,+ toolUseId: null,+ agentMeta: null,+ createdAt: `2026-01-01T00:00:0${seconds}.000Z`,+ };+}diff --git a/apps/mobile/src/__tests__/messageListVirtualization.test.ts b/apps/mobile/src/__tests__/messageListVirtualization.test.tsindex 6362b271d2..e458594da3 100644--- a/apps/mobile/src/__tests__/messageListVirtualization.test.ts+++ b/apps/mobile/src/__tests__/messageListVirtualization.test.ts@@ -16,7 +16,9 @@ describe('mobile message list container', () => {const listStart = source.search(/<LegendList\s/);expect(listStart).toBeGreaterThan(-1);- const listSource = source.slice(listStart, source.indexOf('onViewableItemsChanged', listStart));+ const listEnd = source.indexOf(' />', listStart);+ expect(listEnd).toBeGreaterThan(listStart);+ const listSource = source.slice(listStart, listEnd);// 估高 + 小预渲窗口:挂载集小、mount 帧压进一帧(不可退回大挂载树)。expect(listSource).toContain('estimatedItemSize={MOBILE_MESSAGE_ESTIMATED_ITEM_SIZE}');@@ -39,7 +41,11 @@ describe('mobile message list container', () => {expect(listSource).toContain('? false');expect(listSource).toContain(': { data: true, size: true }}');expect(source).toContain('captureMobileHistoryAnchor(');- expect(source).toContain('resolveMobileHistoryAnchorOffset(anchor, listState)');+ expect(source).toContain('resolveMobileMessageHistoryAnchorOffset(');+ expect(source).toContain('getCurrentHistoryTopOffsetAdjustment()');+ expect(source).toContain('onMetricsChange={handleListMetricsChange}');+ expect(source).toContain('mobileMessageHistoryAnchorIdentity(item as MobileMessageRenderItem)');+ expect(source).toContain('mobileMessageHistoryRowKeyByIdentity(');expect(source).toContain('scheduleHistoryAnchorRestore(transaction.generation)');const historyRestoreStart = source.indexOf('const scheduleHistoryAnchorRestore = useCallback');const historyRestoreStep = source.indexOf('const step = (', historyRestoreStart);@@ -47,12 +53,26 @@ describe('mobile message list container', () => {expect(historyRestoreSetup).toContain('if (historyAnchorVerifyFrameRef.current !== null) return;');expect(historyRestoreSetup).not.toContain('cancelAnimationFrame(historyAnchorVerifyFrameRef.current)');expect(source).toContain('useLayoutEffect(() => {');- // Release 开启 native cell 回收;DEV 仍保留 listperf 的 on/off 单变量开关。+ // 普通 Release/DEV 详情页都开启 native cell 回收;listperf 仍可显式做 on/off A/B。// item type 分池 + recycling-aware state 防止菜单/展开态/媒体状态串到另一条消息。+ expect(source).toContain('devRecycleItems = true,');expect(source).toContain('const recycleItems = __DEV__ ? devRecycleItems === true : true;');expect(listSource).toContain('recycleItems={recycleItems}');expect(listSource).toContain('getItemType={mobileMessageListItemType}');expect(source).toContain('useRecyclingState');+ // 可见性必须由 cell 自己订阅。把可见 key 集合放进 React Context 会在每个+ // onViewableItemsChanged 回调里广播给所有已挂载长消息,快滑时造成整窗重渲染、GC 和白屏。+ expect(source).not.toContain('MessageListVisibleKeysContext');+ expect(source).not.toContain('visibleMessageKeys');+ expect(source).toContain("const MESSAGE_LIST_VIEWABILITY_CONFIG_ID = 'message-heavy-content';");+ expect(source).toContain('id: MESSAGE_LIST_VIEWABILITY_CONFIG_ID');+ expect(source).toContain('useViewability<MobileMessageRenderItem>(');+ expect(source).toContain('MESSAGE_LIST_VIEWABILITY_CONFIG_ID,');+ expect(source).toContain('const [isViewable, setIsViewable] = useRecyclingState(false);');+ expect(source).toContain('if (token.key !== itemKeyRef.current) return;');+ expect(source).toContain('maxTextRunInlineFragments: ANDROID_SELECTABLE_TEXT_RUN_MAX_INLINE_FRAGMENTS');+ expect(listSource).toContain('onFirstVisibleItemChanged={handleFirstVisibleItemChangedRef.current}');+ expect(listSource).not.toContain('onViewableItemsChanged=');// 上滑加载:LegendList 近顶阈值触发自动预取(替代手搓的滚动 metric 判定)。expect(listSource).toContain('onStartReached={handleStartReached}');// 自动预取必须是电平判定(shouldAutoLoadEarlier + 多时机重评估),不许退回只吃 onStartReached@@ -73,7 +93,8 @@ describe('mobile message list container', () => {expect(source).toContain('onTouchCancel={handleHistoryTouchCancel}');expect(listSource).not.toContain('onTouchMove={handleHistoryTouchMove}');expect(source).toContain('if (readingOlderRef.current || queuedLoadEarlierRef.current) return;');- expect(source).toContain('const firstItemKey = loadEarlierProgressKey ?? itemKeys[0] ?? null;');+ expect(source).toContain('const firstItemKey = itemKeys[0] ?? null;');+ expect(source).toContain('const historyProgressKey = loadEarlierProgressKey ?? firstItemKey;');expect(source).toContain('initialHistoryAutofillRemainingRef.current -= 1');// 所有 prepend 在请求、新页提交和锚点恢复期间抑制贴底。Promise settlement 强制// 一次 render,layout effect 确认新 cursor 已提交后才允许释放;generation 隔离旧请求。@@ -81,12 +102,19 @@ describe('mobile message list container', () => {expect(source).toContain('readingOlderRef.current = true');expect(source).toContain('void Promise.resolve(result).then(');expect(source).toContain('transaction.promiseSettled = true');- expect(source).toContain('transaction.startProgressKey !== firstItemKey');+ expect(source).toContain('transaction.startProgressKey !== historyProgressKey');expect(source).toContain('transaction.pageCommitted = true');expect(source).toContain('transaction.anchorStable = true');expect(source).toContain('loadingEarlierRef.current || !transaction.promiseSettled');expect(source).toContain('setLoadEarlierEvaluationVersion((version) => version + 1);');expect(source).toContain('[attemptAutoLoadEarlier, loadEarlierEvaluationVersion]');+ // 若一页只扩进顶部折叠的 Worked for,事务保位不能改变 main 的连续分页语义:+ // 锚点稳定后绕过一次 near-start 复判继续拉,直到出现可见顶层历史或到头。+ expect(source).toContain('mobileMessageHistoryOnlyExpandedFirstWorkGroup(');+ expect(source).toContain('regroupedHistoryContinuationRef.current = transaction.continueAfterRegroup');+ expect(source).toContain('const continueAfterRegroup = userScrolledForOlder');+ expect(source).toContain('if (continueAfterRegroup) {');+ expect(source).not.toContain('message.historyLoadConfirmation');expect(source).toContain('MOBILE_HISTORY_ANCHOR_VERIFY_MAX_FRAMES');expect(source).toContain('MOBILE_HISTORY_ANCHOR_VERIFY_MAX_MS');expect(source).toContain('Date.now() < currentTransaction.verifyDeadlineAt');diff --git a/apps/mobile/src/__tests__/messageMarkdown.test.ts b/apps/mobile/src/__tests__/messageMarkdown.test.tsindex 042a3b4a98..9a707206d0 100644--- a/apps/mobile/src/__tests__/messageMarkdown.test.ts+++ b/apps/mobile/src/__tests__/messageMarkdown.test.ts@@ -1611,6 +1611,43 @@ describe('groupMobileMarkdownSelectableBlocks', () => {expect(groups.map((group) => (group.type === 'text_run' ? group.blocks.length : 0))).toEqual([1, 1, 2]);});+ it('can bound one native text run by inline fragment count', () => {+ const blocks = [{+ type: 'paragraph' as const,+ key: 'paragraph:0',+ inlines: Array.from({ length: 7 }, (_, index) => ({+ type: 'strong' as const,+ text: String(index),+ })),+ }];+ const groups = groupMobileMarkdownSelectableBlocks(blocks, {+ maxTextRunInlineFragments: 3,+ });+ const chunks = groups.flatMap((group) => (group.type === 'text_run' ? group.blocks : []));++ expect(groups.map((group) => group.type)).toEqual(['text_run', 'text_run', 'text_run']);+ expect(chunks.map((block) => block.inlines.length)).toEqual([3, 3, 1]);+ expect(chunks.map((block) => block.textRunContinuation === true)).toEqual([false, true, true]);+ expect(chunks.flatMap((block) => block.inlines).map((inline) => (+ inline.type === 'image' ? inline.alt : inline.text+ )).join('')).toBe('0123456');+ });++ it('counts inline fragments across adjacent text blocks', () => {+ const blocks = Array.from({ length: 5 }, (_, index) => ({+ type: 'paragraph' as const,+ key: `paragraph:${index}`,+ inlines: [{ type: 'text' as const, text: String(index) }],+ }));+ const groups = groupMobileMarkdownSelectableBlocks(blocks, {+ maxTextRunInlineFragments: 2,+ });++ expect(groups.map((group) => (+ group.type === 'text_run' ? group.blocks.length : 0+ ))).toEqual([2, 2, 1]);+ });+it('counts rendered block separators when bounding text runs by text length', () => {const blocks = parseMobileMarkdown(['aaaa', '', 'bbbb'].join('\n'));const groups = groupMobileMarkdownSelectableBlocks(blocks, { maxTextRunUtf16Length: 8 });@@ -1693,6 +1730,7 @@ describe('groupMobileMarkdownSelectableBlocks', () => {const groups = groupMobileMarkdownSelectableBlocks(blocks, {maxTextRunBlocks: 0.5,maxTextRunUtf16Length: 0.5,+ maxTextRunInlineFragments: 0.5,});expect(groups).toHaveLength(1);expect(groups[0].type).toBe('text_run');diff --git a/apps/mobile/src/__tests__/messagePerformance.test.ts b/apps/mobile/src/__tests__/messagePerformance.test.tsindex d1284060ba..a223659efc 100644--- a/apps/mobile/src/__tests__/messagePerformance.test.ts+++ b/apps/mobile/src/__tests__/messagePerformance.test.ts@@ -1,7 +1,9 @@import { performance } from 'node:perf_hooks';+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 type { RemoteMessage } from '@/session/types';const BASE_TIME = Date.UTC(2026, 0, 1, 0, 0, 0);@@ -164,4 +166,682 @@ describe('message render performance', () => {previous = reconciled;}});++ it('reuses the normalized historical prefix while only the active turn streams', () => {+ const messages = createLargeDesktopMessageFixture(20);+ const activeUser = message({+ id: 'active-user',+ role: 'user',+ content: 'Continue',+ createdAt: timestamp(101),+ });+ const activeAssistant = message({+ id: 'active-assistant',+ role: 'assistant',+ content: 'Partial',+ agentMeta: { isStreaming: true },+ createdAt: timestamp(102),+ });+ const first = buildMobileStreamingRenderWindow({+ cacheKey: 'en',+ messages: [...messages, activeUser, activeAssistant],+ options: { isSessionStreaming: true, sessionId: 's1' },+ });+ expect(first.prefix).not.toBeNull();++ const next = buildMobileStreamingRenderWindow({+ cacheKey: 'en',+ messages: [+ ...messages,+ activeUser,+ { ...activeAssistant, content: 'Partial update' },+ ],+ options: { isSessionStreaming: true, sessionId: 's1' },+ previousPrefix: first.prefix,+ });++ expect(next.prefix).toBe(first.prefix);+ expect(next.prefix?.items).toBe(first.prefix?.items);+ expect(next.items.slice(0, first.prefix!.items.length)).toEqual(first.prefix!.items);+ });++ it('publishes a reusable prefix before a streaming render commits', () => {+ const history = createLargeDesktopMessageFixture(20);+ const activeUser = message({+ id: 'active-user',+ role: 'user',+ content: 'Continue',+ createdAt: timestamp(101),+ });+ const activeAssistant = message({+ id: 'active-assistant',+ role: 'assistant',+ content: 'Partial',+ agentMeta: { isStreaming: true },+ createdAt: timestamp(102),+ });+ const prefixCache: {+ current: ReturnType<typeof buildMobileStreamingRenderWindow>['prefix'];+ } = { current: null };++ const interrupted = buildMobileStreamingRenderWindow({+ cacheKey: 'en',+ messages: [...history, activeUser, activeAssistant],+ options: { isSessionStreaming: true, sessionId: 's1' },+ prefixCache,+ });+ expect(prefixCache.current).toBe(interrupted.prefix);++ const retry = buildMobileStreamingRenderWindow({+ cacheKey: 'en',+ messages: [+ ...history,+ activeUser,+ { ...activeAssistant, content: 'Partial update' },+ ],+ options: { isSessionStreaming: true, sessionId: 's1' },+ prefixCache,+ });++ expect(retry.prefix).toBe(interrupted.prefix);+ expect(prefixCache.current).toBe(interrupted.prefix);+ });++ it('reuses a stable assistant boundary when the active user row is outside the window', () => {+ const toolUse = message({+ id: 'tool-use',+ role: 'tool_use',+ toolUseId: 'tool-use',+ content: { toolUseId: 'tool-use', toolName: 'Read', input: { file_path: '/repo/a.ts' } },+ createdAt: timestamp(1),+ });+ const toolResult = message({+ id: 'tool-result',+ role: 'tool_result',+ toolUseId: 'tool-use',+ content: 'contents',+ createdAt: timestamp(2),+ });+ const stableAssistant = message({+ id: 'stable-assistant',+ role: 'assistant',+ content: 'The first check is complete.',+ createdAt: timestamp(3),+ });+ const activeThinking = message({+ id: 'active-thinking',+ role: 'thinking',+ content: { kind: 'thinking', text: 'Continuing', isStreaming: true },+ createdAt: timestamp(4),+ });+ const activeAssistant = message({+ id: 'active-assistant',+ role: 'assistant',+ content: 'Partial',+ agentMeta: { isStreaming: true },+ createdAt: timestamp(5),+ });+ const messages = [toolUse, toolResult, stableAssistant, activeThinking, activeAssistant];+ const prefixCache: {+ current: ReturnType<typeof buildMobileStreamingRenderWindow>['prefix'];+ } = { current: null };+ const options = { isSessionStreaming: true, sessionId: 's1' } as const;++ const first = buildMobileStreamingRenderWindow({+ cacheKey: 'en',+ messages,+ options,+ prefixCache,+ });+ expect(first.prefix?.mode).toBe('truncated-turn');+ expect(first.prefix?.boundaryMessage).toBe(stableAssistant);+ expect(first.items).toEqual(buildMobileMessageRenderItems(messages, options));++ const updatedMessages = [+ toolUse,+ toolResult,+ stableAssistant,+ activeThinking,+ { ...activeAssistant, content: 'Partial update' },+ ];+ const retry = buildMobileStreamingRenderWindow({+ cacheKey: 'en',+ messages: updatedMessages,+ options,+ prefixCache,+ });++ expect(retry.prefix).toBe(first.prefix);+ expect(retry.items).toEqual(buildMobileMessageRenderItems(updatedMessages, options));+ });++ it('advances the reusable prefix into a long visible active turn', () => {+ const history = createLargeDesktopMessageFixture(20);+ const activeUser = message({+ id: 'active-user',+ role: 'user',+ content: 'Continue',+ createdAt: timestamp(101),+ });+ const stableAssistant = message({+ id: 'stable-assistant',+ role: 'assistant',+ content: 'The first pass is complete.',+ createdAt: timestamp(102),+ });+ const activeThinking = message({+ id: 'active-thinking',+ role: 'thinking',+ content: { kind: 'thinking', text: 'Continuing', isStreaming: true },+ createdAt: timestamp(103),+ });+ const activeAssistant = message({+ id: 'active-assistant',+ role: 'assistant',+ content: 'Partial',+ agentMeta: { isStreaming: true },+ createdAt: timestamp(104),+ });+ const prefixCache: {+ current: ReturnType<typeof buildMobileStreamingRenderWindow>['prefix'];+ } = { current: null };+ const options = { isSessionStreaming: true, sessionId: 's1' } as const;++ const first = buildMobileStreamingRenderWindow({+ cacheKey: 'en',+ messages: [...history, activeUser, stableAssistant, activeThinking, activeAssistant],+ options,+ prefixCache,+ });+ expect(first.prefix?.mode).toBe('truncated-turn');+ expect(first.prefix?.boundaryMessage).toBe(stableAssistant);++ const updatedMessages = [+ ...history,+ activeUser,+ stableAssistant,+ activeThinking,+ { ...activeAssistant, content: 'Partial update' },+ ];+ const retry = buildMobileStreamingRenderWindow({+ cacheKey: 'en',+ messages: updatedMessages,+ options,+ prefixCache,+ });++ expect(retry.prefix).toBe(first.prefix);+ expect(retry.items).toEqual(buildMobileMessageRenderItems(updatedMessages, options));+ });++ it('invalidates only when a task update used by the stable prefix changes', () => {+ const prefixTask = message({+ id: 'prefix-task',+ role: 'tool_use',+ toolUseId: 'prefix-task',+ content: {+ toolUseId: 'prefix-task',+ toolName: 'collab:spawn',+ input: { task: 'Review the prefix' },+ },+ createdAt: timestamp(1),+ });+ const stableAssistant = message({+ id: 'stable-after-task',+ role: 'assistant',+ content: 'The review has started.',+ createdAt: timestamp(2),+ });+ const activeThinking = message({+ id: 'active-thinking-after-task',+ role: 'thinking',+ content: { kind: 'thinking', text: 'Continuing', isStreaming: true },+ createdAt: timestamp(3),+ });+ const prefixUpdate: AgentTaskUpdate = {+ provider: 'codex',+ taskId: 'prefix-task',+ status: 'running',+ };+ const prefixCache: {+ current: ReturnType<typeof buildMobileStreamingRenderWindow>['prefix'];+ } = { current: null };+ const options = {+ isSessionStreaming: true,+ renderOrphanTaskUpdates: true,+ sessionId: 's1',+ } as const;+ const messages = [prefixTask, stableAssistant, activeThinking];+ const first = buildMobileStreamingRenderWindow({+ cacheKey: 'en',+ messages,+ options,+ prefixCache,+ taskUpdates: new Map<string, AgentTaskUpdate>([['prefix-task', prefixUpdate]]),+ });++ const unrelatedUpdate: AgentTaskUpdate = {+ provider: 'codex',+ taskId: 'tail-task',+ status: 'running',+ };+ const unrelated = buildMobileStreamingRenderWindow({+ cacheKey: 'en',+ messages,+ options,+ prefixCache,+ taskUpdates: new Map<string, AgentTaskUpdate>([+ ['prefix-task', prefixUpdate],+ ['tail-task', unrelatedUpdate],+ ]),+ });+ expect(unrelated.prefix).toBe(first.prefix);++ const completedPrefixUpdate = { ...prefixUpdate, status: 'completed' as const };+ const changedUpdates = new Map<string, AgentTaskUpdate>([+ ['prefix-task', completedPrefixUpdate],+ ['tail-task', unrelatedUpdate],+ ]);+ const changed = buildMobileStreamingRenderWindow({+ cacheKey: 'en',+ messages,+ options,+ prefixCache,+ taskUpdates: changedUpdates,+ });++ expect(changed.prefix).not.toBe(first.prefix);+ expect(changed.items).toEqual(+ buildMobileMessageRenderItems(messages, options, changedUpdates),+ );+ });++ it('keeps whole-turn transforms together until a later stable assistant boundary', () => {+ const stableAssistant = message({+ id: 'stable-assistant-before-structural-tail',+ role: 'assistant',+ content: 'The first phase is complete.',+ createdAt: timestamp(2),+ });+ const activeThinking = message({+ id: 'active-thinking-structural-tail',+ role: 'thinking',+ content: { kind: 'thinking', text: 'Continuing', isStreaming: true },+ createdAt: timestamp(3),+ });+ const options = { isSessionStreaming: true, sessionId: 's1' } as const;++ const scenarios: RemoteMessage[][] = [+ [+ message({+ id: 'agent-before-boundary',+ role: 'tool_use',+ toolUseId: 'agent-before-boundary',+ content: {+ toolUseId: 'agent-before-boundary',+ toolName: 'Agent',+ input: { prompt: 'Inspect the code' },+ },+ createdAt: timestamp(1),+ }),+ stableAssistant,+ message({+ id: 'late-subagent-child',+ role: 'assistant',+ content: 'Late child output',+ agentMeta: { parentUuid: 'agent-before-boundary', isStreaming: true },+ createdAt: timestamp(3),+ }),+ ],+ [+ message({+ id: 'plan-before-boundary',+ role: 'tool_use',+ toolUseId: 'plan-before-boundary',+ content: {+ toolUseId: 'plan-before-boundary',+ toolName: 'update_plan',+ input: { plan: [{ step: 'First', status: 'completed' }] },+ },+ createdAt: timestamp(1),+ }),+ stableAssistant,+ message({+ id: 'plan-after-boundary',+ role: 'tool_use',+ toolUseId: 'plan-after-boundary',+ content: {+ toolUseId: 'plan-after-boundary',+ toolName: 'update_plan',+ input: { plan: [{ step: 'Second', status: 'in_progress' }] },+ },+ createdAt: timestamp(3),+ }),+ ],+ [+ message({+ id: 'tool-before-boundary',+ role: 'tool_use',+ toolUseId: 'tool-before-boundary',+ content: {+ toolUseId: 'tool-before-boundary',+ toolName: 'Read',+ input: { file_path: '/repo/image.png' },+ },+ createdAt: timestamp(1),+ }),+ stableAssistant,+ message({+ id: 'late-tool-result',+ role: 'tool_result',+ toolUseId: 'tool-before-boundary',+ content: 'late result',+ createdAt: timestamp(3),+ }),+ ],+ [+ message({+ id: 'tool-image-before-boundary',+ role: 'tool_use',+ toolUseId: 'tool-image-before-boundary',+ content: {+ toolUseId: 'tool-image-before-boundary',+ toolName: 'Read',+ input: { file_path: '/repo/image.png' },+ },+ createdAt: timestamp(1),+ }),+ stableAssistant,+ message({+ id: 'assistant-image-after-boundary',+ role: 'assistant',+ content: '',+ agentMeta: { isStreaming: true },+ createdAt: timestamp(3),+ }),+ ],+ ];++ for (const messages of scenarios) {+ const result = buildMobileStreamingRenderWindow({+ cacheKey: 'en',+ messages: [...messages, activeThinking],+ options,+ });+ expect(result.prefix).toBeNull();+ expect(result.items).toEqual(+ buildMobileMessageRenderItems([...messages, activeThinking], options),+ );+ }+ });++ it('does not treat steering or auto-resume user rows as the active turn root', () => {+ const history = createLargeDesktopMessageFixture(4);+ const activeUser = message({+ id: 'real-active-user',+ role: 'user',+ content: 'Continue',+ createdAt: timestamp(50),+ });+ const stableAssistant = message({+ id: 'stable-before-synthetic-user',+ role: 'assistant',+ content: 'First phase complete.',+ createdAt: timestamp(51),+ });+ const syntheticUsers = [+ message({+ id: 'steer-user',+ role: 'user',+ content: 'Adjust the current work',+ agentMeta: { delivery: 'steer' },+ createdAt: timestamp(52),+ }),+ message({+ id: 'auto-resume-user',+ role: 'user',+ content: '',+ agentMeta: { autoResume: true },+ createdAt: timestamp(52),+ }),+ ];++ for (const syntheticUser of syntheticUsers) {+ const messages = [+ ...history,+ activeUser,+ stableAssistant,+ syntheticUser,+ message({+ id: `streaming-after-${syntheticUser.id}`,+ role: 'assistant',+ content: 'Partial',+ agentMeta: { isStreaming: true },+ createdAt: timestamp(53),+ }),+ ];+ const result = buildMobileStreamingRenderWindow({+ cacheKey: 'en',+ messages,+ options: { isSessionStreaming: true, sessionId: 's1' },+ });++ expect(result.prefix?.mode).toBe('history');+ expect(result.prefix?.messages).toEqual(history);+ expect(result.items).toEqual(+ buildMobileMessageRenderItems(messages, { isSessionStreaming: true, sessionId: 's1' }),+ );+ }+ });++ it('invalidates a truncated-turn prefix when a late tool result settles it', () => {+ const toolUse = message({+ id: 'late-tool-use',+ role: 'tool_use',+ toolUseId: 'late-tool-use',+ content: {+ toolUseId: 'late-tool-use',+ toolName: 'Read',+ input: { file_path: '/repo/late.ts' },+ },+ createdAt: timestamp(1),+ });+ const stableAssistant = message({+ id: 'stable-after-tool',+ role: 'assistant',+ content: 'Waiting for the remaining work.',+ createdAt: timestamp(2),+ });+ const activeThinking = message({+ id: 'late-active-thinking',+ role: 'thinking',+ content: { kind: 'thinking', text: 'Continuing', isStreaming: true },+ createdAt: timestamp(3),+ });+ const options = { isSessionStreaming: true, sessionId: 's1' } as const;+ const prefixCache: {+ current: ReturnType<typeof buildMobileStreamingRenderWindow>['prefix'];+ } = { current: null };+ const first = buildMobileStreamingRenderWindow({+ cacheKey: 'en',+ messages: [toolUse, stableAssistant, activeThinking],+ options,+ prefixCache,+ });+ const lateResult = message({+ id: 'late-tool-result',+ role: 'tool_result',+ toolUseId: 'late-tool-use',+ content: 'late contents',+ createdAt: timestamp(4),+ });+ const settledMessages = [toolUse, stableAssistant, activeThinking, lateResult];++ const settled = buildMobileStreamingRenderWindow({+ cacheKey: 'en',+ messages: settledMessages,+ options,+ prefixCache,+ });++ expect(settled.prefix).not.toBe(first.prefix);+ expect(settled.items).toEqual(buildMobileMessageRenderItems(settledMessages, options));++ const retry = buildMobileStreamingRenderWindow({+ cacheKey: 'en',+ messages: settledMessages,+ options,+ prefixCache,+ });+ expect(retry.items).toEqual(buildMobileMessageRenderItems(settledMessages, options));+ });++ it('keeps full-turn image dedupe when an image assistant becomes the split boundary in one batch', () => {+ const imageUrl = 'xdt-image://lizi-art-media-images/cache-boundary.png';+ const toolUse = message({+ id: 'image-tool-use',+ role: 'tool_use',+ toolUseId: 'image-tool-use',+ content: {+ toolUseId: 'image-tool-use',+ toolName: 'Read',+ input: { file_path: '/repo/image.png' },+ },+ createdAt: timestamp(1),+ });+ const toolResult = message({+ id: 'image-tool-result',+ role: 'tool_result',+ toolUseId: 'image-tool-use',+ content: JSON.stringify({ xdt_image_url: imageUrl }),+ createdAt: timestamp(2),+ });+ const firstBoundary = message({+ id: 'first-boundary',+ role: 'assistant',+ content: 'First phase complete.',+ createdAt: timestamp(3),+ });+ const initialTail = message({+ id: 'initial-tail',+ role: 'thinking',+ content: { kind: 'thinking', text: 'Continuing', isStreaming: true },+ createdAt: timestamp(4),+ });+ const options = { isSessionStreaming: true, sessionId: 's1' } as const;+ const prefixCache: {+ current: ReturnType<typeof buildMobileStreamingRenderWindow>['prefix'];+ } = { current: null };++ buildMobileStreamingRenderWindow({+ cacheKey: 'en',+ messages: [toolUse, toolResult, firstBoundary, initialTail],+ options,+ prefixCache,+ });++ const imageBoundary = message({+ id: 'image-boundary',+ role: 'assistant',+ content: ``,+ createdAt: timestamp(5),+ });+ const nextTail = message({+ id: 'next-tail',+ role: 'thinking',+ content: { kind: 'thinking', text: 'Still working', isStreaming: true },+ createdAt: timestamp(6),+ });+ const messages = [toolUse, toolResult, firstBoundary, imageBoundary, nextTail];+ const result = buildMobileStreamingRenderWindow({+ cacheKey: 'en',+ messages,+ options,+ prefixCache,+ });++ expect(result.items).toEqual(buildMobileMessageRenderItems(messages, options));+ });++ it('keeps full-turn image dedupe between an earlier assistant and a tail tool result', () => {+ const imageUrl = 'xdt-image://lizi-art-media-images/cache-prefix.png';+ const user = message({+ id: 'image-prefix-user',+ role: 'user',+ content: 'Create an image',+ createdAt: timestamp(1),+ });+ const imageAssistant = message({+ id: 'image-prefix-assistant',+ role: 'assistant',+ content: ``,+ createdAt: timestamp(2),+ });+ const textBoundary = message({+ id: 'image-prefix-text-boundary',+ role: 'assistant',+ content: 'The first phase is complete.',+ createdAt: timestamp(3),+ });+ const initialTail = message({+ id: 'image-prefix-initial-tail',+ role: 'thinking',+ content: { kind: 'thinking', text: 'Continuing', isStreaming: true },+ createdAt: timestamp(4),+ });+ const options = { isSessionStreaming: true, sessionId: 's1' } as const;+ const prefixCache: {+ current: ReturnType<typeof buildMobileStreamingRenderWindow>['prefix'];+ } = { current: null };++ buildMobileStreamingRenderWindow({+ cacheKey: 'en',+ messages: [user, imageAssistant, textBoundary, initialTail],+ options,+ prefixCache,+ });++ const tailToolUse = message({+ id: 'image-prefix-tail-tool',+ role: 'tool_use',+ toolUseId: 'image-prefix-tail-tool',+ content: {+ toolUseId: 'image-prefix-tail-tool',+ toolName: 'image_generate',+ input: { prompt: 'variant' },+ },+ createdAt: timestamp(5),+ });+ const tailToolResult = message({+ id: 'image-prefix-tail-result',+ role: 'tool_result',+ toolUseId: 'image-prefix-tail-tool',+ content: JSON.stringify({ xdt_image_url: imageUrl }),+ createdAt: timestamp(6),+ });+ const streamingTail = message({+ id: 'image-prefix-streaming-tail',+ role: 'assistant',+ content: 'Still working',+ agentMeta: { isStreaming: true },+ createdAt: timestamp(7),+ });+ const messages = [+ user,+ imageAssistant,+ textBoundary,+ tailToolUse,+ tailToolResult,+ streamingTail,+ ];+ const result = buildMobileStreamingRenderWindow({+ cacheKey: 'en',+ messages,+ options,+ prefixCache,+ });++ expect(result.items).toEqual(buildMobileMessageRenderItems(messages, options));+ expect(result.items.some((item) => item.type === 'tool_media')).toBe(false);+ });});diff --git a/apps/mobile/src/__tests__/messageSelectionDesktopFirst.test.ts b/apps/mobile/src/__tests__/messageSelectionDesktopFirst.test.tsindex 854d5cb9f9..ec7de7a728 100644--- a/apps/mobile/src/__tests__/messageSelectionDesktopFirst.test.ts+++ b/apps/mobile/src/__tests__/messageSelectionDesktopFirst.test.ts@@ -67,6 +67,8 @@ describe('mobile message text selection', () => {// 跨段选择:连续纯文本块合并进同一个原生文本视图(text_run),原生选择手柄可横跨段落。// Android 上长 selectable Text 分块,避免单个超高原生文本视图干扰列表测高/滚动。expect(markdownBodySource).toContain('ANDROID_SELECTABLE_TEXT_RUN_GROUPING_OPTIONS');+ expect(markdownBodySource).toContain("const textRunGroupingOptions = Platform.OS === 'android'");+ expect(markdownBodySource).not.toContain("selectable === true && Platform.OS === 'android'");expect(markdownBodySource).toContain('groupMobileMarkdownSelectableBlocks(blocks, textRunGroupingOptions)');expect(markdownBodySource).toContain('testID="message.markdownTextRun"');expect(markdownBodySource).toContain("lineHeight: layout.markdownBodyGap");diff --git a/apps/mobile/src/__tests__/messageWebViewGovernance.test.ts b/apps/mobile/src/__tests__/messageWebViewGovernance.test.tsindex 4b71ccff23..3e25064b50 100644--- a/apps/mobile/src/__tests__/messageWebViewGovernance.test.ts+++ b/apps/mobile/src/__tests__/messageWebViewGovernance.test.ts@@ -44,11 +44,19 @@ describe('message WebView visibility wiring', () => {const media = readFileSync(resolve(process.cwd(), 'src/session/mediaPlayerWebView.tsx'), 'utf8');const composer = readFileSync(resolve(process.cwd(), 'src/session/ComposerRichInput.tsx'), 'utf8');- expect(renderer).toContain('MessageListVisibleKeysContext.Provider');- expect(renderer).toContain('isListItem');+ expect(renderer).not.toContain('MessageListVisibleKeysContext');+ expect(renderer).toContain('useViewability<MobileMessageRenderItem>(');+ expect(renderer).toContain('const heavyContentVisible = focused || isViewable;');+ expect(renderer).toContain('function ViewabilityGatedMermaidDiagram(');+ expect(renderer).toContain('function ViewabilityGatedMathFormula(');expect(renderer).toContain('active={heavyContentVisible}');+ const markdownBodyStart = renderer.indexOf('function MarkdownBody(');+ const markdownBodyEnd = renderer.indexOf('\nfunction ', markdownBodyStart + 1);+ const markdownBody = renderer.slice(markdownBodyStart, markdownBodyEnd);+ expect(markdownBody).not.toContain('useContext(MessageHeavyContentVisibilityContext)');expect(renderer).toContain('getWebViewMetrics: getMobileMessageWebViewMetrics');expect(renderer).toContain('getMarkdownMetrics: getMobileMarkdownRenderMetrics');+ expect(renderer).toContain('devRecycleItems = true,');expect(renderer).toContain('const recycleItems = __DEV__ ? devRecycleItems === true : true;');expect(renderer).toContain('recycleItems={recycleItems}');expect(renderer).toContain('getItemType={mobileMessageListItemType}');diff --git a/apps/mobile/src/__tests__/swipeableSessionRowLifecycle.test.ts b/apps/mobile/src/__tests__/swipeableSessionRowLifecycle.test.tsnew file mode 100644index 0000000000..f2b7fabe59--- /dev/null+++ b/apps/mobile/src/__tests__/swipeableSessionRowLifecycle.test.ts@@ -0,0 +1,20 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { describe, expect, it } from 'vitest';++const source = readFileSync(+ resolve(process.cwd(), 'src/session/SwipeableSessionRow.tsx'),+ 'utf8',+);++describe('SwipeableSessionRow native animation lifecycle', () => {+ it('does not schedule a no-op timing animation when an action panel mounts', () => {+ expect(source).toContain('const armedProgress = useSharedValue(0);');+ expect(source).toContain('if (previous === null) {');+ expect(source).toContain('armedProgress.value = next ? 1 : 0;');+ expect(source).toContain(+ 'armedProgress.value = withTiming(next ? 1 : 0, { duration: ARM_ANIMATION_MS });',+ );+ expect(source).not.toContain('const armedProgress = useDerivedValue(');+ });+});diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsxindex 3c20b85f7b..9e08935b6d 100644--- a/apps/mobile/src/session/MessageRenderer.tsx+++ b/apps/mobile/src/session/MessageRenderer.tsx@@ -54,10 +54,16 @@ import {type StyleProp,type TextStyle,type ViewStyle,- type ViewToken,} from 'react-native';import { UITextView } from 'react-native-uitextview';-import { LegendList, useRecyclingState, type LegendListRef } from '@legendapp/list/react-native';+import {+ LegendList,+ useRecyclingState,+ useViewability,+ type LegendListMetrics,+ type LegendListRef,+ type ViewToken as LegendListViewToken,+} from '@legendapp/list/react-native';import { tokenizeCode, type CodeTokenKind } from '@/session/codeHighlight';import { buildComposerTouchLayout } from '@/session/composerTouchLayout';import { useFoldableExpandedState } from '@/session/expandedBlockMemory';@@ -331,9 +337,16 @@ import {import {captureMobileHistoryAnchor,isMobileHistoryAnchorSettled,+ mobileHistoryTopOffsetAdjustment,resolveMobileHistoryAnchorOffset,type MobileHistoryAnchor,+ type MobileHistoryAnchorResolveState,} from '@/session/messageHistoryAnchor';+import {+ mobileMessageHistoryAnchorIdentity,+ mobileMessageHistoryOnlyExpandedFirstWorkGroup,+ mobileMessageHistoryRowKeyByIdentity,+} from '@/session/messageHistoryAnchorIdentity';import { ImageLightbox, type ImageLightboxAnnotationConfig } from '@/session/ImageLightbox';import {MermaidDiagramWebView,@@ -358,11 +371,11 @@ import { mobileToolRowWording } from '@/i18n/toolWording';const MESSAGE_CONTROL_HIT_SLOP = { bottom: 10, left: 10, right: 10, top: 10 };const MESSAGE_CONTROL_TOUCH_SIZE = 44;const MESSAGE_LIST_VISIBLE_PERCENT_THRESHOLD = 5;+const MESSAGE_LIST_VIEWABILITY_CONFIG_ID = 'message-heavy-content';// Heavy Markdown blocks inherit the visibility of their outer list cell. Nested// work/sub-agent cards should not create a second visibility window of their own.const MessageHeavyContentVisibilityContext = createContext(true);-const MessageListVisibleKeysContext = createContext<ReadonlySet<string> | null>(null);/** 分享模式吸顶 check 与行内 check 共用 44px 触达高度。 */const SHARE_STICKY_CHECK_HEIGHT = 44;@@ -388,9 +401,11 @@ const MOBILE_HISTORY_ANCHOR_VERIFY_MAX_MS = 3000;const MOBILE_HISTORY_ANCHOR_STABLE_FRAMES = 2;const ANDROID_SELECTABLE_TEXT_RUN_MAX_BLOCKS = 12;const ANDROID_SELECTABLE_TEXT_RUN_MAX_UTF16_LENGTH = 1800;+const ANDROID_SELECTABLE_TEXT_RUN_MAX_INLINE_FRAGMENTS = 20;const ANDROID_SELECTABLE_TEXT_RUN_GROUPING_OPTIONS: MobileMarkdownTextRunGroupingOptions = {maxTextRunBlocks: ANDROID_SELECTABLE_TEXT_RUN_MAX_BLOCKS,maxTextRunUtf16Length: ANDROID_SELECTABLE_TEXT_RUN_MAX_UTF16_LENGTH,+ maxTextRunInlineFragments: ANDROID_SELECTABLE_TEXT_RUN_MAX_INLINE_FRAGMENTS,};/** Running work groups expose only the same latest-five activity window as desktop. */const MAX_LIVE_WORK_ACTIVITIES = 5;@@ -402,13 +417,33 @@ function mobileMessageListItemType(item: MobileMessageRenderItem): MobileMessagereturn item.type;}+function resolveMobileMessageHistoryAnchorOffset(+ anchor: MobileHistoryAnchor,+ state: MobileHistoryAnchorResolveState,+ topOffsetAdjustment: number,+): number | null {+ return resolveMobileHistoryAnchorOffset(anchor, {+ ...state,+ topOffsetAdjustment,+ keyByIdentity: state.data+ ? (identityKey) => mobileMessageHistoryRowKeyByIdentity(+ state.data as readonly MobileMessageRenderItem[],+ identityKey,+ )+ : undefined,+ });+}+interface MobileHistoryPrependTransaction {anchor: MobileHistoryAnchor | null;anchorStable: boolean;+ continueAfterRegroup: boolean;generation: number;pageCommitted: boolean;promiseSettled: boolean;+ startItems: readonly MobileMessageRenderItem[];startProgressKey: string | null;+ userInitiated: boolean;userControlledAfterCommit: boolean;verifyDeadlineAt: number;}@@ -627,7 +662,7 @@ export function MessageRenderer({syncingWhileEmpty,testID,devExposeList,- devRecycleItems = false,+ devRecycleItems = true,}: {bottomOverlayHeight?: number;/** 顶部 chrome(绝对定位半透明工具栏)实测高度:内容顶部按此让位,详见 mobileMessageListTopPadding。 */@@ -645,7 +680,7 @@ export function MessageRenderer({/** 空列表且本次打开的首同步未完成:渲染「正在同步」占位(延迟显形防闪)而非「暂无消息」。 */syncingWhileEmpty?: boolean;testID?: string;- /** DEV-only A/B switch; production always enables verified row recycling. */+ /** DEV-only A/B override for listperf; regular screens match production and recycle rows. */devRecycleItems?: boolean;/** 全屏图片查看器的分享回调(由会话屏落地本地文件后唤起系统分享单)。 */onShareImage?: (@@ -679,6 +714,9 @@ export function MessageRenderer({const focusedItemKeyRef = useRef(focusedItemKey);focusedItemKeyRef.current = focusedItemKey;const listRef = useRef<LegendListRef>(null);+ const listMetricsRef = useRef<LegendListMetrics>({ footerSize: 0, headerSize: 0 });+ const listTopPaddingRef = useRef(0);+ const listBottomPaddingRef = useRef(0);const shareableMessageViewsRef = useRef(new Map<string, View>());const windowDimensions = useWindowDimensions();const viewportLayout = useMemo(() => buildMobileReadableViewportLayout({@@ -780,9 +818,9 @@ export function MessageRenderer({// Without a render tick, a user who remains at the top can stall after one page because the// page commit effect ran while readingOlderRef was still true.const [loadEarlierEvaluationVersion, setLoadEarlierEvaluationVersion] = useState(0);- const [visibleMessageKeys, setVisibleMessageKeys] = useState<ReadonlySet<string>>(- () => new Set(),- );+ // Main immediately requests another page when a prepend only expands the first collapsed+ // `Worked for` row. The app-owned anchor transaction settles first, then consumes this one-shot.+ const regroupedHistoryContinuationRef = useRef(false);// 会话切换(scrollResetKey)的 ref 复位必须在渲染期同步完成,不能只靠下方的 reset effect:// effect 在 paint 后异步执行,而重挂的新列表(key={scrollResetKey})的首批 scroll /// onStartReached 回调、以及先于 reset effect 定义的 eligibility effect,都可能带着上个会话的@@ -791,6 +829,7 @@ export function MessageRenderer({const prevScrollResetKeyRef = useRef(scrollResetKey);if (prevScrollResetKeyRef.current !== scrollResetKey) {prevScrollResetKeyRef.current = scrollResetKey;+ listMetricsRef.current = { footerSize: 0, headerSize: 0 };nearBottomRef.current = true;isDraggingRef.current = false;isMomentumScrollingRef.current = false;@@ -804,6 +843,7 @@ export function MessageRenderer({readingOlderRequestGenerationRef.current += 1;historyPrependTransactionRef.current = null;queuedLoadEarlierRef.current = false;+ regroupedHistoryContinuationRef.current = false;if (historyPrependNativeMvcpDisabled) setHistoryPrependNativeMvcpDisabled(false);if (queuedLoadEarlierFlushFrameRef.current !== null) {cancelAnimationFrame(queuedLoadEarlierFlushFrameRef.current);@@ -927,15 +967,29 @@ export function MessageRenderer({void listRef.current?.scrollToIndex({ animated: true, index, viewPosition });}, [markProgrammaticScroll]);+ const getCurrentHistoryTopOffsetAdjustment = useCallback(() => {+ const listState = listRef.current?.getState();+ if (!listState) return listTopPaddingRef.current + listMetricsRef.current.headerSize;+ return mobileHistoryTopOffsetAdjustment(listState, {+ baseTopOffset: listTopPaddingRef.current + listMetricsRef.current.headerSize,+ bottomPadding: listBottomPaddingRef.current,+ footerSize: listMetricsRef.current.footerSize,+ });+ }, []);+const captureCurrentHistoryAnchor = useCallback((): MobileHistoryAnchor | null => {const listState = listRef.current?.getState();return listState? captureMobileHistoryAnchor(- listState,+ {+ ...listState,+ topOffsetAdjustment: getCurrentHistoryTopOffsetAdjustment(),+ },(item) => (item as MobileMessageRenderItem).key,+ (item) => mobileMessageHistoryAnchorIdentity(item as MobileMessageRenderItem),): null;- }, []);+ }, [getCurrentHistoryTopOffsetAdjustment]);const finishHistoryPrependTransaction = useCallback((generation: number) => {const transaction = historyPrependTransactionRef.current;@@ -944,6 +998,9 @@ export function MessageRenderer({cancelAnimationFrame(historyAnchorVerifyFrameRef.current);historyAnchorVerifyFrameRef.current = null;}+ regroupedHistoryContinuationRef.current = transaction.continueAfterRegroup+ && transaction.userInitiated+ && !transaction.userControlledAfterCommit;historyPrependTransactionRef.current = null;readingOlderRef.current = false;setHistoryPrependNativeMvcpDisabled(false);@@ -978,6 +1035,7 @@ export function MessageRenderer({readingOlderRef.current = false;historyPrependTransactionRef.current = null;queuedLoadEarlierRef.current = false;+ regroupedHistoryContinuationRef.current = false;setHistoryPrependNativeMvcpDisabled(false);if (queuedLoadEarlierFlushFrameRef.current !== null) {cancelAnimationFrame(queuedLoadEarlierFlushFrameRef.current);@@ -1021,7 +1079,11 @@ export function MessageRenderer({const anchor = currentTransaction.anchor;const listState = listRef.current?.getState();const targetOffset = anchor && listState- ? resolveMobileHistoryAnchorOffset(anchor, listState)+ ? resolveMobileMessageHistoryAnchorOffset(+ anchor,+ listState,+ getCurrentHistoryTopOffsetAdjustment(),+ ): null;if (targetOffset !== null && listState) {@@ -1077,7 +1139,11 @@ export function MessageRenderer({) return;const finalState = listRef.current?.getState();const finalTarget = finalTransaction.anchor && finalState- ? resolveMobileHistoryAnchorOffset(finalTransaction.anchor, finalState)+ ? resolveMobileMessageHistoryAnchorOffset(+ finalTransaction.anchor,+ finalState,+ getCurrentHistoryTopOffsetAdjustment(),+ ): null;if (finalTarget !== null) scrollToOffsetProgrammatically(finalTarget, false);historyAnchorVerifyFrameRef.current = requestAnimationFrame(() => {@@ -1108,6 +1174,7 @@ export function MessageRenderer({// ScrollView offset still belongs to the pre-prepend data.step(0, 0, null);}, [+ getCurrentHistoryTopOffsetAdjustment,markMobileMvcpSettle,maybeFinishHistoryPrependTransaction,scrollToOffsetProgrammatically,@@ -1122,7 +1189,11 @@ export function MessageRenderer({) return;const listState = listRef.current?.getState();const targetOffset = transaction.anchor && listState- ? resolveMobileHistoryAnchorOffset(transaction.anchor, listState)+ ? resolveMobileMessageHistoryAnchorOffset(+ transaction.anchor,+ listState,+ getCurrentHistoryTopOffsetAdjustment(),+ ): null;if (targetOffset !== null@@ -1131,7 +1202,7 @@ export function MessageRenderer({) {scrollToOffsetProgrammatically(targetOffset, false);}- }, [scrollToOffsetProgrammatically]);+ }, [getCurrentHistoryTopOffsetAdjustment, scrollToOffsetProgrammatically]);// 贴底跟随的落底校验/补滚环:两条手动补滚路径——「跳到最新」(followLatestRequestKey)// 与 handleContentSize 的贴底追赶——都只发一次命令式 scrollToEnd,不校验是否真的到达内容@@ -1222,6 +1293,8 @@ export function MessageRenderer({// LegendList 虚拟化/回收。不能用业务尾窗代替完整数据,否则短尾窗未撑满首屏时// Android 无法产生有效滚动,运行中任务会重现“上半屏空白且历史不可拖动”。const listData = useMemo(() => [...items], [items]);+ const listDataRef = useRef(listData);+ listDataRef.current = listData;const prevListLengthRef = useRef(listData.length);if (prevListLengthRef.current !== listData.length) {if (@@ -1240,15 +1313,23 @@ export function MessageRenderer({() => mobileMessageListKeysSignature(itemKeys),[itemKeys],);- const firstItemKey = loadEarlierProgressKey ?? itemKeys[0] ?? null;+ // Keep main's rendered-row progress signal for near-start auto paging. The host cursor remains+ // the stronger transaction commit signal because local synthetic rows can sit before host data.+ const firstItemKey = itemKeys[0] ?? null;+ const historyProgressKey = loadEarlierProgressKey ?? firstItemKey;// A successful history page changes the oldest host cursor. Restore the captured visible row// in a layout effect: LegendList has accepted the new data, but React Native has not painted the// shifted absolute positions yet. This is the atomic point missing from Android native MVCP.useLayoutEffect(() => {const transaction = historyPrependTransactionRef.current;if (!transaction) return;- if (transaction.startProgressKey !== firstItemKey) {+ if (transaction.startProgressKey !== historyProgressKey) {transaction.pageCommitted = true;+ transaction.continueAfterRegroup = transaction.userInitiated+ && mobileMessageHistoryOnlyExpandedFirstWorkGroup(+ transaction.startItems,+ listDataRef.current,+ );scheduleHistoryAnchorRestore(transaction.generation);maybeFinishHistoryPrependTransaction(transaction.generation);return;@@ -1260,7 +1341,7 @@ export function MessageRenderer({maybeFinishHistoryPrependTransaction(transaction.generation);}}, [- firstItemKey,+ historyProgressKey,itemKeysSignature,loadEarlierEvaluationVersion,loadingEarlier,@@ -1314,6 +1395,8 @@ export function MessageRenderer({}, [galleryImages, payload]);const bottomPadding = mobileMessageListBottomPadding(bottomOverlayHeight);const topPadding = mobileMessageListTopPadding(topOverlayHeight);+ listBottomPaddingRef.current = bottomPadding;+ listTopPaddingRef.current = topPadding;const previousUserButtonTop = topPadding > 0 ? topPadding : null;// 上一次 topPadding,供顶部 chrome 高度变化时补偿 scroll offset(见下方 effect)。const prevTopPaddingRef = useRef(topPadding);@@ -1419,6 +1502,7 @@ export function MessageRenderer({? `${focusedRequestKey ?? 'default'}:${focusedItemKey}`: null;const viewabilityConfigRef = useRef({+ id: MESSAGE_LIST_VIEWABILITY_CONFIG_ID,itemVisiblePercentThreshold: MESSAGE_LIST_VISIBLE_PERCENT_THRESHOLD,});const shareSelectionActiveRef = useRef(shareSelectionActive);@@ -1489,26 +1573,10 @@ export function MessageRenderer({useEffect(() => () => {if (stickyCheckTimerRef.current) clearTimeout(stickyCheckTimerRef.current);}, []);- const handleViewableItemsChangedRef = useRef((info: {- viewableItems: ViewToken<MobileMessageRenderItem>[];+ const handleFirstVisibleItemChangedRef = useRef((info: {+ index: number;}) => {- let nextIndex: number | null = null;- const nextVisibleMessageKeys = new Set<string>();- for (const token of info.viewableItems) {- if (typeof token.index !== 'number') continue;- nextIndex = nextIndex === null ? token.index : Math.min(nextIndex, token.index);- if (token.isViewable && token.item?.key) nextVisibleMessageKeys.add(token.item.key);- }- if (nextIndex !== null) setFirstVisibleIndex(nextIndex);- setVisibleMessageKeys((previous) => {- if (- previous.size === nextVisibleMessageKeys.size- && [...previous].every((key) => nextVisibleMessageKeys.has(key))- ) {- return previous;- }- return nextVisibleMessageKeys;- });+ setFirstVisibleIndex((previous) => previous === info.index ? previous : info.index);});const readActuallyVisibleShareableMessageIds = useCallback(async (viewport: ShareableMessageViewport,@@ -1629,17 +1697,24 @@ export function MessageRenderer({const listState = listRef.current?.getState();const anchor = listState? captureMobileHistoryAnchor(- listState,+ {+ ...listState,+ topOffsetAdjustment: getCurrentHistoryTopOffsetAdjustment(),+ },(item) => (item as MobileMessageRenderItem).key,+ (item) => mobileMessageHistoryAnchorIdentity(item as MobileMessageRenderItem),): null;historyPrependTransactionRef.current = {anchor,anchorStable: false,+ continueAfterRegroup: false,generation,pageCommitted: false,promiseSettled: false,- startProgressKey: firstItemKey,+ startItems: listDataRef.current,+ startProgressKey: historyProgressKey,+ userInitiated: userScrollForOlderRef.current,userControlledAfterCommit: false,verifyDeadlineAt: 0,};@@ -1669,7 +1744,7 @@ export function MessageRenderer({} catch {markRequestSettled();}- }, [firstItemKey, onLoadEarlier]);+ }, [getCurrentHistoryTopOffsetAdjustment, historyProgressKey, onLoadEarlier]);const flushQueuedLoadEarlier = useCallback(() => {if (@@ -1730,8 +1805,24 @@ export function MessageRenderer({const initialAutoFillAllowed = listRevealed&& !userScrolledForOlder&& initialHistoryAutofillRemainingRef.current > 0;- if (!userScrolledForOlder && !initialAutoFillAllowed) return;+ const continueAfterRegroup = userScrolledForOlder+ && regroupedHistoryContinuationRef.current;+ if (!userScrolledForOlder && !initialAutoFillAllowed && !continueAfterRegroup) return;if (firstItemKey !== null && lastAutoLoadEarlierKeyRef.current === firstItemKey) return;+ if (continueAfterRegroup) {+ if (!loadEarlierAction.visible) {+ regroupedHistoryContinuationRef.current = false;+ return;+ }+ // A merged page did make host-cursor progress but added no visible top-level history. Do not+ // reapply the near-start gate after app-owned anchor restoration moved the viewport; main+ // immediately continues from the changed first rendered row in the same situation.+ if (loadEarlierAction.disabled || firstItemKey === null) return;+ regroupedHistoryContinuationRef.current = false;+ lastAutoLoadEarlierKeyRef.current = firstItemKey;+ requestLoadEarlier();+ return;+ }const listState = listRef.current?.getState();if (!listState) return;// LegendList's edge bookkeeping can lag behind the native ScrollView during recycling,@@ -1945,6 +2036,22 @@ export function MessageRenderer({scrollMetricsRef.current = { ...scrollMetricsRef.current, viewportHeight };}, []);+ const handleListMetricsChange = useCallback((metrics: LegendListMetrics) => {+ listMetricsRef.current = metrics;+ if (!readingOlderRef.current) return;+ const transaction = historyPrependTransactionRef.current;+ if (!transaction) return;+ if (transaction.pageCommitted) {+ scheduleHistoryAnchorRestore(transaction.generation);+ } else if (+ !isDraggingRef.current+ && !isMomentumScrollingRef.current+ && historyTouchStartYRef.current === null+ ) {+ restoreHistoryAnchorOnce(transaction.generation);+ }+ }, [restoreHistoryAnchorOnce, scheduleHistoryAnchorRestore]);+// 记录 contentHeight 供近底判定 fallback + DEV harness 就绪判定;并承担**唯一的贴底跟随**:// 内容长高(流式增长、大块一帧撑高、冷开测量结算)时,用户本就贴底(nearBottomRef,与// 「跳到底部」浮标同源)则无论这次长多少都跟到底(仿 filo onContentSizeChange → scrollToEnd);@@ -2138,7 +2245,6 @@ export function MessageRenderer({setIsAwayFromBottom(false);setFirstVisibleIndex(0);setHasNewMessages(false);- setVisibleMessageKeys(new Set());}, [scrollResetKey]);// 卸载时清掉在飞的定时器/rAF(闭包引用 listRef,卸载后触发是无害 no-op,// 但不留悬挂句柄)。@@ -2235,10 +2341,9 @@ export function MessageRenderer({const renderMessageItem = useCallback(({ item }: { item: MobileMessageRenderItem }) => {if (__DEV__) recordMobileMessageRenderItem();return (- <RenderItemView+ <RenderListItemViewactions={actions}focused={item.key === focusedItemKey}- isListItemitem={item}/>);@@ -2253,9 +2358,9 @@ export function MessageRenderer({),[pendingSend?.selectedClientId, shareSelectionActive],);- // Production uses native cell recycling after every identity-bound local- // state below was made recycling-aware. DEV stays opt-in so listperf can- // continue running the on/off control with one bundle.+ // Production and regular DEV screens use native cell recycling after every+ // identity-bound local state below was made recycling-aware. listperf passes+ // this DEV-only override explicitly so its on/off control remains available.const recycleItems = __DEV__ ? devRecycleItems === true : true;return (@@ -2269,7 +2374,6 @@ export function MessageRenderer({onTouchEnd={handleHistoryTouchEnd}onTouchCancel={handleHistoryTouchCancel}>- <MessageListVisibleKeysContext.Provider value={visibleMessageKeys}><Animated.View style={[styles.messageList, { opacity: initialRevealOpacity }]}><LegendList// 与 main 一致:每个任务用完整历史重挂;首次命令式落底在 opacity 遮罩下完成。@@ -2318,6 +2422,7 @@ export function MessageRenderer({}ListFooterComponent={queueFooter ? <>{queueFooter}</> : null}onLayout={handleListLayout}+ onMetricsChange={handleListMetricsChange}onContentSizeChange={handleContentSize}onScroll={handleScroll}onScrollBeginDrag={handleScrollBeginDrag}@@ -2331,10 +2436,9 @@ export function MessageRenderer({style={styles.messageList}testID={testID ?? 'message.list'}viewabilityConfig={viewabilityConfigRef.current}- onViewableItemsChanged={handleViewableItemsChangedRef.current}+ onFirstVisibleItemChanged={handleFirstVisibleItemChangedRef.current}/></Animated.View>- </MessageListVisibleKeysContext.Provider>{previousUserTarget && previousUserButtonTop !== null ? (<MessageListActionButtonaccessibilityLabel={t('message.renderer.previousQuestionJump', { preview: previousUserTarget.preview || t('message.renderer.noPreview') })}@@ -2406,19 +2510,12 @@ const RenderItemView = memo(function RenderItemView({item,actions,focused = false,- isListItem = false,}: {item: MobileMessageRenderItem | MobileWorkChildItem;actions: MessageActions & { firstUserMessageClientId?: string };focused?: boolean;- isListItem?: boolean;}) {const styles = useThemedStyles(makeStyles);- const inheritedHeavyContentVisible = useContext(MessageHeavyContentVisibilityContext);- const visibleKeys = useContext(MessageListVisibleKeysContext);- const heavyContentVisible = isListItem- ? focused || visibleKeys === null || visibleKeys.has(item.key)- : inheritedHeavyContentVisible;// 「user 行渲染系统卡」形态(silent-stop 自动续跑 agentMeta.autoResume):渲染层// 降级为 kind='system' 再进 MessageBubble——presentation 的 isUserAligned 判定是// `align==='user' || kind==='user'`,保持 user kind 会右对齐成用户气泡并挂上@@ -2507,11 +2604,37 @@ const RenderItemView = memo(function RenderItemView({logUnhandledRenderItem(item);break;}+ return (+ <View style={focused ? styles.focusedItem : undefined} testID={focused ? 'message.focusedItem' : undefined}>+ {node}+ </View>+ );+});++const RenderListItemView = memo(function RenderListItemView({+ item,+ actions,+ focused,+}: {+ item: MobileMessageRenderItem;+ actions: MessageActions & { firstUserMessageClientId?: string };+ focused: boolean;+}) {+ const [isViewable, setIsViewable] = useRecyclingState(false);+ const itemKeyRef = useRef(item.key);+ itemKeyRef.current = item.key;+ const handleViewabilityChange = useCallback((token: LegendListViewToken<MobileMessageRenderItem>) => {+ if (token.key !== itemKeyRef.current) return;+ setIsViewable((previous) => previous === token.isViewable ? previous : token.isViewable);+ }, [setIsViewable]);+ useViewability<MobileMessageRenderItem>(+ handleViewabilityChange,+ MESSAGE_LIST_VIEWABILITY_CONFIG_ID,+ );+ const heavyContentVisible = focused || isViewable;return (<MessageHeavyContentVisibilityContext.Provider value={heavyContentVisible}>- <View style={focused ? styles.focusedItem : undefined} testID={focused ? 'message.focusedItem' : undefined}>- {node}- </View>+ <RenderItemView actions={actions} focused={focused} item={item} /></MessageHeavyContentVisibilityContext.Provider>);});@@ -4567,6 +4690,40 @@ function OrcaCollabCard({ card, screenWidth }: { card: OrcaCollabCardModel; scre);}+const ViewabilityGatedMermaidDiagram = memo(function ViewabilityGatedMermaidDiagram({+ source,+ testID,+}: {+ source: string;+ testID?: string;+}) {+ const heavyContentVisible = useContext(MessageHeavyContentVisibilityContext);+ return (+ <MermaidDiagramWebView+ active={heavyContentVisible}+ source={source}+ testID={testID}+ />+ );+});++const ViewabilityGatedMathFormula = memo(function ViewabilityGatedMathFormula({+ source,+ testID,+}: {+ source: string;+ testID?: string;+}) {+ const heavyContentVisible = useContext(MessageHeavyContentVisibilityContext);+ return (+ <MathFormulaWebView+ active={heavyContentVisible}+ source={source}+ testID={testID}+ />+ );+});+// 消息正文统一走原生 markdown 渲染(流式与完成态同一条路径,完成时无"原生→WebView"的切换跳变)。// 文本选择 = 完成态消息的各块 Text 原生 selectable:长按文字就地弹系统选择手柄/Copy 菜单,// 不跳转界面;整条复制走操作条按钮。选择按块进行(原生 Text 能力边界,跨段选择做不到)。@@ -4606,7 +4763,6 @@ function MarkdownBody({const { colors } = useTheme();const { t } = useTranslation();const styles = useThemedStyles(makeStyles);- const heavyContentVisible = useContext(MessageHeavyContentVisibilityContext);const chatFilePathContext = useContext(ChatFilePathContext);// iOS UITextView 在 stretch/百分比宽度下会偶发只量出部分高度,LegendList 按这次// 偏矮的 onLayout 裁切 agent 回复;点分享会换上确定宽度的容器从而完整显示。@@ -4712,7 +4868,7 @@ function MarkdownBody({),[onOpenSessionLink, openMarkdownImage, sessionLinkTitles, sessionReferenceDetails, streaming, styles],);- const textRunGroupingOptions = selectable === true && Platform.OS === 'android'+ const textRunGroupingOptions = Platform.OS === 'android'? ANDROID_SELECTABLE_TEXT_RUN_GROUPING_OPTIONS: undefined;// 连续纯文本块合并为 text_run(跨段选择),代码块/表格/mermaid/含直连图块保持独立。@@ -4801,7 +4957,7 @@ function MarkdownBody({// 盖住整块——WebView 会吞掉触摸事件,不盖层拿不到点击)。return (<View key={block.key} testID="message.mermaidPreviewButton">- <MermaidDiagramWebView active={heavyContentVisible} source={block.text} testID="message.mermaidDiagram" />+ <ViewabilityGatedMermaidDiagram source={block.text} testID="message.mermaidDiagram" />{onOpenPayload ? (<PressableaccessibilityLabel={t('message.renderer.openDiagramDetail')}@@ -4818,8 +4974,7 @@ function MarkdownBody({// display 公式:WebView + KaTeX(形态对齐 mermaid 块,无 chip 卡壳——// 公式在视觉上是正文的一部分,背景与气泡底色一致)。return (- <MathFormulaWebView- active={heavyContentVisible}+ <ViewabilityGatedMathFormulakey={block.key}source={block.text}testID="message.mathFormula"diff --git a/apps/mobile/src/session/SwipeableSessionRow.tsx b/apps/mobile/src/session/SwipeableSessionRow.tsxindex 0be0656758..1e8e7e43ac 100644--- a/apps/mobile/src/session/SwipeableSessionRow.tsx+++ b/apps/mobile/src/session/SwipeableSessionRow.tsx@@ -31,7 +31,6 @@ import Animated, {interpolate,useAnimatedReaction,useAnimatedStyle,- useDerivedValue,useSharedValue,withTiming,type SharedValue,@@ -307,18 +306,22 @@ function RightActionsPanel({const { colors } = useTheme();const { t } = useTranslation();const StatusIcon = archived ? ArchiveRestore : Archive;- // armed = 位移越过全滑阈值。独立 SharedValue 只在跨越阈值时写入,避免- // useDerivedValue 里对逐帧变化的 translation 直接 withTiming(目标每帧重设,动画走不完)。- const armed = useSharedValue(false);+ // 挂载时同步落初值,只在真正跨越阈值时启动 timing。若每个面板挂载都执行+ // withTiming(0),大项目从完整首帧切到窗口行时会留下仍在更新已卸载 Fabric tag+ // 的空动画,最终用 Reanimated 警告栈堵住 Android 主线程。+ const armedProgress = useSharedValue(0);useAnimatedReaction(() => -translation.value >= fullSwipeThreshold,- (next) => {- if (next !== armed.value) armed.value = next;+ (next, previous) => {+ if (previous === null) {+ armedProgress.value = next ? 1 : 0;+ return;+ }+ if (next !== previous) {+ armedProgress.value = withTiming(next ? 1 : 0, { duration: ARM_ANIMATION_MS });+ }},);- const armedProgress = useDerivedValue(- () => withTiming(armed.value ? 1 : 0, { duration: ARM_ANIMATION_MS }),- );const optionsStyle = useAnimatedStyle(() => {const revealed = Math.max(0, -translation.value);diff --git a/apps/mobile/src/session/messageHistoryAnchor.ts b/apps/mobile/src/session/messageHistoryAnchor.tsindex b50d1d2028..451a9b515d 100644--- a/apps/mobile/src/session/messageHistoryAnchor.ts+++ b/apps/mobile/src/session/messageHistoryAnchor.ts@@ -1,5 +1,7 @@export interface MobileHistoryAnchor {key: string;+ /** Stable child identity used when a prepend changes an aggregate row's outer key. */+ identityKey?: string;/** Item top relative to the viewport top before older rows are prepended. */viewportOffset: number;/** Nearby rows captured at the same time, used if a live render group replaces the primary key. */@@ -8,6 +10,8 @@ export interface MobileHistoryAnchor {export interface MobileHistoryAnchorCandidate {key: string;+ /** Stable child identity used when a prepend changes an aggregate row's outer key. */+ identityKey?: string;viewportOffset: number;}@@ -16,17 +20,79 @@ export interface MobileHistoryAnchorCaptureState<ItemT> {positionAtIndex(index: number): number | undefined;scroll: number;start: number;+ /** Header, content padding, and align-at-end spacer before the data coordinate space. */+ topOffsetAdjustment?: number;}export interface MobileHistoryAnchorResolveState {positionByKey(key: string): number | undefined;+ /** Resolve a captured child identity to its current top-level row key. */+ keyByIdentity?(identityKey: string): string | undefined;/** LegendList can briefly omit a key from its position cache while committing a prepend. */data?: readonly { key: string }[];positionAtIndex?(index: number): number | undefined;+ /** Header, content padding, and align-at-end spacer before the data coordinate space. */+ topOffsetAdjustment?: number;+}++export interface MobileHistoryTopOffsetState {+ contentLength: number;+ data: readonly unknown[];+ positionAtIndex(index: number): number | undefined;+ scrollLength: number;+ sizeAtIndex(index: number): number | undefined;}const MAX_MOBILE_HISTORY_ANCHOR_CANDIDATES = 8;const MAX_MOBILE_HISTORY_ANCHOR_POSITION_PROBES = 24;+const MOBILE_HISTORY_SHORT_LIST_TOLERANCE = 2;++/**+ * Translate LegendList's data-relative item positions into its raw ScrollView coordinates.+ *+ * LegendList does not expose its align-at-end spacer through `getState()`. For an under-one-screen+ * list every row is measured, so the leading space can be recovered from the content length and+ * the measured end of the final row. Overflowing lists have no align spacer and use the explicit+ * header + content-padding baseline instead.+ */+export function mobileHistoryTopOffsetAdjustment(+ state: MobileHistoryTopOffsetState,+ input: {+ baseTopOffset: number;+ bottomPadding: number;+ footerSize: number;+ },+): number {+ const baseTopOffset = Number.isFinite(input.baseTopOffset)+ ? Math.max(0, input.baseTopOffset)+ : 0;+ if (+ state.data.length === 0+ || !Number.isFinite(state.contentLength)+ || !Number.isFinite(state.scrollLength)+ || state.contentLength > state.scrollLength + MOBILE_HISTORY_SHORT_LIST_TOLERANCE+ ) {+ return baseTopOffset;+ }++ const lastIndex = state.data.length - 1;+ const lastPosition = state.positionAtIndex(lastIndex);+ const lastSize = state.sizeAtIndex(lastIndex);+ if (!Number.isFinite(lastPosition) || !Number.isFinite(lastSize)) return baseTopOffset;++ const footerSize = Number.isFinite(input.footerSize) ? Math.max(0, input.footerSize) : 0;+ const bottomPadding = Number.isFinite(input.bottomPadding)+ ? Math.max(0, input.bottomPadding)+ : 0;+ const measuredLeadingSpace = state.contentLength+ - footerSize+ - bottomPadding+ - (lastPosition as number)+ - (lastSize as number);+ return Number.isFinite(measuredLeadingSpace)+ ? Math.max(baseTopOffset, measuredLeadingSpace)+ : baseTopOffset;+}function findClosestMobileHistoryAnchorIndex<ItemT>(state: MobileHistoryAnchorCaptureState<ItemT>,@@ -45,12 +111,13 @@ function findClosestMobileHistoryAnchorIndex<ItemT>(const index = Math.floor((lower + upper) / 2);const position = state.positionAtIndex(index);if (!Number.isFinite(position)) break;- const distance = Math.abs((position as number) - state.scroll);+ const dataScroll = state.scroll - (state.topOffsetAdjustment ?? 0);+ const distance = Math.abs((position as number) - dataScroll);if (distance < closestDistance) {closestDistance = distance;closestIndex = index;}- if ((position as number) < state.scroll) lower = index + 1;+ if ((position as number) < dataScroll) lower = index + 1;else upper = index - 1;}return closestIndex;@@ -66,8 +133,12 @@ function findClosestMobileHistoryAnchorIndex<ItemT>(export function captureMobileHistoryAnchor<ItemT>(state: MobileHistoryAnchorCaptureState<ItemT>,keyOf: (item: ItemT) => string,+ identityOf?: (item: ItemT) => string | undefined,): MobileHistoryAnchor | null {if (!Number.isFinite(state.scroll)) return null;+ const topOffsetAdjustment = Number.isFinite(state.topOffsetAdjustment)+ ? state.topOffsetAdjustment as number+ : 0;const closestIndex = findClosestMobileHistoryAnchorIndex(state);if (closestIndex === null) return null;@@ -93,9 +164,11 @@ export function captureMobileHistoryAnchor<ItemT>(const position = state.positionAtIndex(index);if (!key || seenKeys.has(key) || !Number.isFinite(position)) continue;seenKeys.add(key);+ const identityKey = identityOf?.(state.data[index]);candidates.push({key,- viewportOffset: (position as number) - state.scroll,+ ...(identityKey && identityKey !== key ? { identityKey } : {}),+ viewportOffset: (position as number) + topOffsetAdjustment - state.scroll,});if (candidates.length >= MAX_MOBILE_HISTORY_ANCHOR_CANDIDATES@@ -127,17 +200,41 @@ export function resolveMobileHistoryAnchorOffset(): number | null {const candidates: readonly MobileHistoryAnchorCandidate[] = [anchor, ...(anchor.fallbacks ?? [])];for (const candidate of candidates) {- let position = state.positionByKey(candidate.key);+ let currentKey = candidate.key;+ let position = state.positionByKey(currentKey);if (!Number.isFinite(position)&& state.data&& state.positionAtIndex) {- const index = state.data.findIndex((item) => item.key === candidate.key);+ const index = state.data.findIndex((item) => item.key === currentKey);if (index >= 0) position = state.positionAtIndex(index);}+ // Most prepends preserve the outer row key. Only scan aggregate children after both of+ // LegendList's direct-key paths miss, keeping the per-frame settle verifier O(1) normally.+ if (!Number.isFinite(position) && candidate.identityKey && state.keyByIdentity) {+ const replacementKey = state.keyByIdentity(candidate.identityKey);+ if (replacementKey) {+ currentKey = replacementKey;+ position = state.positionByKey(currentKey);+ if (+ !Number.isFinite(position)+ && state.data+ && state.positionAtIndex+ ) {+ const index = state.data.findIndex((item) => item.key === currentKey);+ if (index >= 0) position = state.positionAtIndex(index);+ }+ }+ }if (Number.isFinite(position)) {- return Math.max(0, (position as number) - candidate.viewportOffset);+ const topOffsetAdjustment = Number.isFinite(state.topOffsetAdjustment)+ ? state.topOffsetAdjustment as number+ : 0;+ return Math.max(+ 0,+ (position as number) + topOffsetAdjustment - candidate.viewportOffset,+ );}}return null;diff --git a/apps/mobile/src/session/messageHistoryAnchorIdentity.ts b/apps/mobile/src/session/messageHistoryAnchorIdentity.tsnew file mode 100644index 0000000000..ffcd4b61f7--- /dev/null+++ b/apps/mobile/src/session/messageHistoryAnchorIdentity.ts@@ -0,0 +1,87 @@+import type {+ MobileMessageRenderItem,+ MobileWorkChildItem,+} from '@/session/messageRenderModel';++type MobileHistoryAnchorItem = MobileMessageRenderItem | MobileWorkChildItem;++/**+ * Aggregate rows are keyed by their first activity, so prepending an older activity from the same+ * turn legitimately replaces the outer key. A leaf message/tool identity survives that regrouping+ * and lets the history transaction recognize the replacement row without changing product grouping.+ */+export function mobileMessageHistoryAnchorIdentity(+ item: MobileHistoryAnchorItem,+): string | undefined {+ switch (item.type) {+ case 'work_group':+ for (const child of item.children) {+ const identity = mobileMessageHistoryAnchorIdentity(child);+ if (identity) return identity;+ }+ return item.key;+ case 'tool_group':+ case 'tool_media':+ return item.tools[0]?.key ?? item.key;+ case 'subagent_group':+ for (const child of item.childItems) {+ const identity = mobileMessageHistoryAnchorIdentity(child);+ if (identity) return identity;+ }+ return item.key;+ default:+ return item.key;+ }+}++/** Find the current top-level row that still contains a captured stable leaf identity. */+export function mobileMessageHistoryRowKeyByIdentity(+ items: readonly MobileMessageRenderItem[],+ identityKey: string,+): string | undefined {+ return items.find((item) => mobileMessageHistoryItemContainsIdentity(item, identityKey))?.key;+}++/**+ * A history page can consist only of earlier activities from the completed turn already shown as+ * the first collapsed `Worked for` row. Its outer key changes, but it remains the first rendered+ * row, so the page added no visible top-level history for the reader. Main continues paging in this+ * case; the app-owned anchor transaction must preserve that behavior after it finishes settling.+ */+export function mobileMessageHistoryOnlyExpandedFirstWorkGroup(+ previousItems: readonly MobileMessageRenderItem[],+ nextItems: readonly MobileMessageRenderItem[],+): boolean {+ const previousFirst = previousItems[0];+ const nextFirst = nextItems[0];+ if (+ previousFirst?.type !== 'work_group'+ || nextFirst?.type !== 'work_group'+ || previousFirst.key === nextFirst.key+ ) return false;+ const identityKey = mobileMessageHistoryAnchorIdentity(previousFirst);+ return identityKey !== undefined+ && mobileMessageHistoryItemContainsIdentity(nextFirst, identityKey);+}++function mobileMessageHistoryItemContainsIdentity(+ item: MobileHistoryAnchorItem,+ identityKey: string,+): boolean {+ if (item.key === identityKey) return true;+ switch (item.type) {+ case 'work_group':+ return item.children.some((child) => (+ mobileMessageHistoryItemContainsIdentity(child, identityKey)+ ));+ case 'tool_group':+ case 'tool_media':+ return item.tools.some((tool) => tool.key === identityKey);+ case 'subagent_group':+ return item.childItems.some((child) => (+ mobileMessageHistoryItemContainsIdentity(child, identityKey)+ ));+ default:+ return false;+ }+}diff --git a/apps/mobile/src/session/messageMarkdown.ts b/apps/mobile/src/session/messageMarkdown.tsindex b06c982d87..3c84902f13 100644--- a/apps/mobile/src/session/messageMarkdown.ts+++ b/apps/mobile/src/session/messageMarkdown.ts@@ -653,6 +653,8 @@ export interface MobileMarkdownTextRunGroupingOptions {maxTextRunBlocks?: number;/** Same guard by rendered inline text length, measured in JS UTF-16 units. */maxTextRunUtf16Length?: number;+ /** Same guard by the number of inline fragments rendered as nested native text spans. */+ maxTextRunInlineFragments?: number;}const MOBILE_MARKDOWN_TEXT_RUN_BLOCK_SEPARATOR_UTF16_LENGTH = 2;@@ -665,8 +667,10 @@ export function groupMobileMarkdownSelectableBlocks(const groups: MobileMarkdownBlockGroup[] = [];let run: MobileMarkdownTextRunBlock[] = [];let runTextLength = 0;+ let runInlineFragmentCount = 0;const maxTextRunBlocks = normalizePositiveLimit(options?.maxTextRunBlocks);const maxTextRunUtf16Length = normalizePositiveLimit(options?.maxTextRunUtf16Length);+ const maxTextRunInlineFragments = normalizePositiveLimit(options?.maxTextRunInlineFragments);const flushRun = () => {if (run.length === 0) return;groups.push({@@ -677,11 +681,17 @@ export function groupMobileMarkdownSelectableBlocks(});run = [];runTextLength = 0;+ runInlineFragmentCount = 0;};for (const block of blocks) {if (isTextRunBlock(block)) {- for (const chunk of splitOversizedTextRunBlock(block, maxTextRunUtf16Length)) {+ for (const chunk of splitOversizedTextRunBlock(+ block,+ maxTextRunUtf16Length,+ maxTextRunInlineFragments,+ )) {const blockTextLength = mobileMarkdownTextRunBlockLength(chunk);+ const blockInlineFragmentCount = chunk.inlines.length;const separatorLength = run.length > 0 && !chunk.textRunContinuation? MOBILE_MARKDOWN_TEXT_RUN_BLOCK_SEPARATOR_UTF16_LENGTH: 0;@@ -690,6 +700,7 @@ export function groupMobileMarkdownSelectableBlocks(&& (run.length >= maxTextRunBlocks|| runTextLength + separatorLength + blockTextLength > maxTextRunUtf16Length+ || runInlineFragmentCount + blockInlineFragmentCount > maxTextRunInlineFragments)) {flushRun();@@ -699,6 +710,7 @@ export function groupMobileMarkdownSelectableBlocks(: 0;run.push(chunk);runTextLength += pushedSeparatorLength + blockTextLength;+ runInlineFragmentCount += blockInlineFragmentCount;}} else {flushRun();@@ -751,10 +763,13 @@ export function mobileMarkdownImageAltChipText(alt: string): string {function splitOversizedTextRunBlock(block: MobileMarkdownTextRunBlock,maxTextRunUtf16Length: number,+ maxTextRunInlineFragments: number,): MobileMarkdownTextRunBlock[] {if (- !Number.isFinite(maxTextRunUtf16Length)- || mobileMarkdownTextRunBlockLength(block) <= maxTextRunUtf16Length+ (!Number.isFinite(maxTextRunUtf16Length)+ || mobileMarkdownTextRunBlockLength(block) <= maxTextRunUtf16Length)+ && (!Number.isFinite(maxTextRunInlineFragments)+ || block.inlines.length <= maxTextRunInlineFragments)) {return [block];}@@ -778,7 +793,12 @@ function splitOversizedTextRunBlock() => {let start = 0;while (start < text.length) {- if (currentTextLength >= currentLimit()) flushCurrent();+ if (+ currentTextLength >= currentLimit()+ || current.length >= maxTextRunInlineFragments+ ) {+ flushCurrent();+ }const capacity = currentLimit() - currentTextLength;if (currentTextLength > 0@@ -798,12 +818,23 @@ function splitOversizedTextRunBlock(for (const inline of block.inlines) {if (inline.type === 'image') {const inlineLength = mobileMarkdownInlineTextLength(inline);- if (current.length > 0 && currentTextLength + inlineLength > currentLimit()) {+ if (+ current.length > 0+ && (+ currentTextLength + inlineLength > currentLimit()+ || current.length >= maxTextRunInlineFragments+ )+ ) {flushCurrent();}current.push(inline);currentTextLength += inlineLength;- if (currentTextLength >= currentLimit()) flushCurrent();+ if (+ currentTextLength >= currentLimit()+ || current.length >= maxTextRunInlineFragments+ ) {+ flushCurrent();+ }continue;}diff --git a/apps/mobile/src/session/messageNormalize.ts b/apps/mobile/src/session/messageNormalize.tsindex 0157ecd61f..2e6e85338f 100644--- a/apps/mobile/src/session/messageNormalize.ts+++ b/apps/mobile/src/session/messageNormalize.ts@@ -180,6 +180,9 @@ interface ToolUsePayload extends MessageNormalizeToolUse {diff?: NormalizedToolDiff;}+const toolResultPreviewByContent = new WeakMap<object, { language: string; preview: string }>();+const toolUsePayloadByMessage = new WeakMap<RemoteMessage, ToolUsePayload>();+export function normalizeRemoteMessages(messages: readonly RemoteMessage[]): NormalizedRemoteMessage[] {const sorted = sortMessagesByCreatedAt(messages);const toolResultPairing = buildMessageToolResultPairing(sorted, {@@ -466,6 +469,18 @@ function dedupeToolImagesAgainstAssistantMarkdown(}function toolResultContentToPreview(content: unknown): string {+ if (content !== null && typeof content === 'object') {+ const language = i18n.resolvedLanguage ?? i18n.language;+ const cached = toolResultPreviewByContent.get(content);+ if (cached?.language === language) return cached.preview;+ const preview = uncachedToolResultContentToPreview(content);+ toolResultPreviewByContent.set(content, { language, preview });+ return preview;+ }+ return uncachedToolResultContentToPreview(content);+}++function uncachedToolResultContentToPreview(content: unknown): string {const compacted = parseToolResultCompactionMarker(content);if (!compacted) return contentToPreview(content);return i18n.t('message.renderer.toolResultCompacted', {@@ -482,11 +497,15 @@ function toolResultContentFor(}function parseToolUse(message: RemoteMessage): ToolUsePayload {+ const cached = toolUsePayloadByMessage.get(message);+ if (cached) return cached;const sharedTool = parseMessageToolUse(message);const { toolName, input } = sharedTool;const summary = toolName ? formatToolUseSummary(toolName, input) : contentToPreview(message.content);const diff = buildToolDiff(toolName, input);- return { ...sharedTool, summary, diff };+ const payload = { ...sharedTool, summary, diff };+ toolUsePayloadByMessage.set(message, payload);+ return payload;}function parseUserContent(content: unknown): {diff --git a/apps/mobile/src/session/messageRenderStreamingCache.ts b/apps/mobile/src/session/messageRenderStreamingCache.tsnew file mode 100644index 0000000000..655e3f0a87--- /dev/null+++ b/apps/mobile/src/session/messageRenderStreamingCache.ts@@ -0,0 +1,521 @@+import {+ findAgentTaskUpdate,+ type AgentTaskUpdate,+} from '@cindy/maker-shared/agent-task';+import type { MessageRenderOptions } from '@cindy/maker-shared/message-render';+import { isPlanUserBoundary } from '@cindy/maker-shared/message-render';+import { parseMessageToolUse } from '@cindy/maker-shared/message-normalize';+import { extractPayloadToolResultMedia } from '@cindy/maker-shared/payload-summary';+import { isSyntheticTriggerText } from '@cindy/maker-shared/synthetic-trigger';+import {+ buildMobileMessageRenderItems,+ type MobileMessageRenderItem,+} from '@/session/messageRenderModel';+import { collectMobileMarkdownImages } from '@/session/messageMarkdown';+import type { RemoteMessage } from '@/session/types';+import { contentToPreview } from '@/utils/contentPreview';++export interface MobileStreamingRenderPrefixCache {+ boundaryMessage?: RemoteMessage;+ cacheKey: string;+ items: readonly MobileMessageRenderItem[];+ markdownImageUrls?: ReadonlySet<string>;+ messages: readonly RemoteMessage[];+ mode: 'history' | 'truncated-turn';+ sessionId: string;+ tailToolResults?: readonly RemoteMessage[];+ taskUpdateDependencies?: readonly MobileStreamingTaskUpdateDependency[];+ toolUseIds?: ReadonlySet<string>;+}++interface MobileStreamingTaskUpdateDependency {+ clientId: string;+ toolUseId: string | null;+ update: AgentTaskUpdate | undefined;+}++export interface MobileStreamingRenderPrefixCacheRef {+ current: MobileStreamingRenderPrefixCache | null;+}++interface BuildMobileStreamingRenderWindowInput {+ cacheKey: string;+ messages: readonly RemoteMessage[];+ options: MessageRenderOptions & {+ autoResumePending?: Record<string, unknown> | null;+ sessionId?: string;+ };+ prefixCache?: MobileStreamingRenderPrefixCacheRef;+ previousPrefix?: MobileStreamingRenderPrefixCache | null;+ taskUpdates?: ReadonlyMap<string, AgentTaskUpdate>;+}++export interface MobileStreamingRenderWindowResult {+ items: MobileMessageRenderItem[];+ prefix: MobileStreamingRenderPrefixCache | null;+}++/**+ * Rebuild only the active turn while a session streams.+ *+ * The loaded history is immutable during ordinary text deltas. Normalizing and grouping that+ * entire window for every token creates a large allocation stream even though row reconciliation+ * later reuses the resulting React props. Prefer a real root-user boundary. Very large active+ * turns can push that row outside the retained window, so the fallback advances across an already+ * rendered assistant boundary and keeps explicit dependencies for late tool results/task updates.+ */+export function buildMobileStreamingRenderWindow(+ input: BuildMobileStreamingRenderWindowInput,+): MobileStreamingRenderWindowResult {+ const {+ cacheKey,+ messages,+ options,+ prefixCache,+ previousPrefix = prefixCache?.current,+ taskUpdates,+ } = input;+ const sessionId = options.sessionId ?? messages[0]?.sessionId ?? '';+ const activeTurnStart = options.isSessionStreaming === true+ ? findLastRootUserMessageIndex(messages)+ : -1;+ const stableAssistantBoundary = options.isSessionStreaming === true+ ? findLastStableAssistantBoundaryIndex(messages)+ : -1;+ if (+ options.isSessionStreaming === true+ && (activeTurnStart < 0 || stableAssistantBoundary > activeTurnStart)+ && stableAssistantBoundary > 0+ && stableAssistantBoundaryCanSplit(+ messages,+ stableAssistantBoundary,+ previousPrefix?.mode === 'truncated-turn'+ && previousPrefix.messages.length === stableAssistantBoundary + 1+ && previousPrefix.boundaryMessage === messages[stableAssistantBoundary]+ ? previousPrefix.toolUseIds+ : undefined,+ previousPrefix?.mode === 'truncated-turn'+ && previousPrefix.messages.length === stableAssistantBoundary + 1+ && previousPrefix.boundaryMessage === messages[stableAssistantBoundary]+ ? previousPrefix.markdownImageUrls+ : undefined,+ )+ ) {+ return buildTruncatedActiveTurnWindow({+ boundaryIndex: stableAssistantBoundary,+ cacheKey,+ messages,+ options,+ prefixCache,+ previousPrefix,+ sessionId,+ taskUpdates,+ });+ }+ if (activeTurnStart <= 0) {+ const result = {+ items: buildMobileMessageRenderItems(messages, options, taskUpdates),+ prefix: null,+ };+ if (prefixCache) prefixCache.current = null;+ return result;+ }++ const canReusePrefix = previousPrefix?.mode === 'history'+ && previousPrefix.sessionId === sessionId+ && previousPrefix.cacheKey === cacheKey+ && sameMessagePrefixReferences(previousPrefix.messages, messages, activeTurnStart);+ const prefixMessages = canReusePrefix+ ? previousPrefix.messages+ : messages.slice(0, activeTurnStart);+ const prefixItems = canReusePrefix+ ? previousPrefix.items+ : buildMobileMessageRenderItems(prefixMessages, {+ ...options,+ autoResumePending: null,+ isSessionStreaming: false,+ renderOrphanTaskUpdates: false,+ });+ const prefix = canReusePrefix+ ? previousPrefix+ : { cacheKey, items: prefixItems, messages: prefixMessages, mode: 'history' as const, sessionId };+ const activeItems = buildMobileMessageRenderItems(+ messages.slice(activeTurnStart),+ options,+ taskUpdates,+ );+ const result = {+ items: [...prefixItems, ...activeItems],+ prefix,+ };+ // Token updates may interrupt a concurrent render before it commits. Publishing this purely+ // derived prefix only from a layout effect would then make every retry rebuild the full history.+ // A speculative entry is safe: reuse still requires the same session, render options key, and+ // exact message references, so a superseded render can affect performance but never output.+ if (prefixCache) prefixCache.current = prefix;+ return result;+}++function buildTruncatedActiveTurnWindow(+ input: BuildMobileStreamingRenderWindowInput & {+ boundaryIndex: number;+ sessionId: string;+ },+): MobileStreamingRenderWindowResult {+ const {+ boundaryIndex,+ cacheKey,+ messages,+ options,+ prefixCache,+ previousPrefix,+ sessionId,+ taskUpdates,+ } = input;+ let items: MobileMessageRenderItem[] | null = null;+ let reusedPrefix = false;++ if (+ previousPrefix?.mode === 'truncated-turn'+ && previousPrefix.sessionId === sessionId+ && previousPrefix.cacheKey === cacheKey+ && sameTaskUpdateDependencies(previousPrefix.taskUpdateDependencies, taskUpdates)+ && previousPrefix.boundaryMessage+ && previousPrefix.messages.length === boundaryIndex + 1+ && previousPrefix.boundaryMessage === messages[boundaryIndex]+ && sameMessagePrefixReferences(+ previousPrefix.messages,+ messages,+ previousPrefix.messages.length,+ )+ && sameDependentTailToolResults(+ previousPrefix.tailToolResults ?? [],+ messages,+ previousPrefix.messages.length,+ previousPrefix.toolUseIds,+ )+ ) {+ const activeItems = buildMobileMessageRenderItems(+ messages.slice(boundaryIndex),+ options,+ taskUpdates,+ );+ const duplicateBoundaryIndex = findTopLevelMessageItemIndex(+ activeItems,+ previousPrefix.boundaryMessage,+ );+ if (duplicateBoundaryIndex >= 0) {+ items = [+ ...previousPrefix.items,+ ...activeItems.slice(duplicateBoundaryIndex + 1),+ ];+ reusedPrefix = true;+ }+ }++ if (!items) items = buildMobileMessageRenderItems(messages, options, taskUpdates);+ if (reusedPrefix && previousPrefix) {+ if (prefixCache) prefixCache.current = previousPrefix;+ return { items, prefix: previousPrefix };+ }+ const builtPrefix = buildTruncatedTurnPrefix({+ boundaryIndex,+ cacheKey,+ items,+ messages,+ sessionId,+ taskUpdates,+ });+ const prefix = previousPrefix?.mode === 'truncated-turn'+ && builtPrefix !== null+ && builtPrefix.boundaryMessage === previousPrefix.boundaryMessage+ && sameTaskUpdateDependencySnapshots(+ builtPrefix.taskUpdateDependencies,+ previousPrefix.taskUpdateDependencies,+ )+ && sameMessageReferences(builtPrefix.messages, previousPrefix.messages)+ && sameMessageReferences(+ builtPrefix.tailToolResults ?? [],+ previousPrefix.tailToolResults ?? [],+ )+ ? previousPrefix+ : builtPrefix;+ if (prefixCache) prefixCache.current = prefix;+ return { items, prefix };+}++function buildTruncatedTurnPrefix(input: {+ boundaryIndex: number;+ cacheKey: string;+ items: readonly MobileMessageRenderItem[];+ messages: readonly RemoteMessage[];+ sessionId: string;+ taskUpdates?: ReadonlyMap<string, AgentTaskUpdate>;+}): MobileStreamingRenderPrefixCache | null {+ const { boundaryIndex } = input;+ if (boundaryIndex <= 0) return null;+ const boundaryMessage = input.messages[boundaryIndex];+ const boundaryItemIndex = findTopLevelMessageItemIndex(input.items, boundaryMessage);+ if (boundaryItemIndex < 0) return null;+ const prefixMessages = input.messages.slice(0, boundaryIndex + 1);+ return {+ boundaryMessage,+ cacheKey: input.cacheKey,+ items: input.items.slice(0, boundaryItemIndex + 1),+ markdownImageUrls: collectAssistantMarkdownImageUrls(prefixMessages, prefixMessages.length),+ messages: prefixMessages,+ mode: 'truncated-turn',+ sessionId: input.sessionId,+ tailToolResults: collectDependentTailToolResults(input.messages, prefixMessages.length),+ taskUpdateDependencies: collectTaskUpdateDependencies(prefixMessages, input.taskUpdates),+ toolUseIds: collectToolUseIds(prefixMessages, prefixMessages.length),+ };+}++function collectTaskUpdateDependencies(+ messages: readonly RemoteMessage[],+ taskUpdates: ReadonlyMap<string, AgentTaskUpdate> | undefined,+): MobileStreamingTaskUpdateDependency[] {+ const dependencies: MobileStreamingTaskUpdateDependency[] = [];+ for (const message of messages) {+ if (message.role !== 'tool_use') continue;+ const toolUseId = remoteToolUseId(message);+ dependencies.push({+ clientId: message.clientId,+ toolUseId,+ update: findAgentTaskUpdate(taskUpdates, toolUseId, message.clientId),+ });+ }+ return dependencies;+}++function sameTaskUpdateDependencies(+ dependencies: readonly MobileStreamingTaskUpdateDependency[] | undefined,+ taskUpdates: ReadonlyMap<string, AgentTaskUpdate> | undefined,+): boolean {+ if (!dependencies) return false;+ return dependencies.every((dependency) =>+ findAgentTaskUpdate(taskUpdates, dependency.toolUseId, dependency.clientId)+ === dependency.update);+}++function sameTaskUpdateDependencySnapshots(+ previous: readonly MobileStreamingTaskUpdateDependency[] | undefined,+ next: readonly MobileStreamingTaskUpdateDependency[] | undefined,+): boolean {+ if (!previous || !next || previous.length !== next.length) return false;+ return previous.every((dependency, index) => {+ const candidate = next[index];+ return dependency.clientId === candidate.clientId+ && dependency.toolUseId === candidate.toolUseId+ && dependency.update === candidate.update;+ });+}++function findLastStableAssistantBoundaryIndex(messages: readonly RemoteMessage[]): number {+ for (let index = messages.length - 2; index > 0; index -= 1) {+ const message = messages[index];+ const parentUuid = message.agentMeta?.parentUuid;+ if (+ message.role === 'assistant'+ && !(typeof parentUuid === 'string' && parentUuid.length > 0)+ && message.agentMeta?.isStreaming !== true+ && message.agentMeta?.streaming !== true+ && !contentIsStreaming(message.content)+ ) {+ return index;+ }+ }+ return -1;+}++/**+ * Some render transforms intentionally inspect a whole turn. Keep those messages together until+ * a later stable assistant moves the split past them; otherwise an independently rebuilt tail can+ * duplicate a plan/subagent row or miss cross-boundary media/tool-result reconciliation.+ */+function stableAssistantBoundaryCanSplit(+ messages: readonly RemoteMessage[],+ boundaryIndex: number,+ cachedPrefixToolUseIds?: ReadonlySet<string>,+ cachedPrefixMarkdownImageUrls?: ReadonlySet<string>,+): boolean {+ // The boundary assistant is rebuilt with the active tail and then discarded as a duplicate.+ // If it contains an inline image, however, full-turn normalization may use it to remove an+ // earlier tool-media row. Keep that boundary in the full build so cross-boundary image dedupe+ // cannot diverge when the completed assistant and its following delta arrive in one batch.+ if (+ collectMobileMarkdownImages(contentToPreview(messages[boundaryIndex]?.content)).length > 0+ ) {+ return false;+ }++ const prefixToolUseIds = cachedPrefixToolUseIds+ ?? collectToolUseIds(messages, boundaryIndex + 1);+ const prefixMarkdownImageUrls = cachedPrefixMarkdownImageUrls+ ?? collectAssistantMarkdownImageUrls(messages, boundaryIndex + 1);++ for (let index = boundaryIndex + 1; index < messages.length; index += 1) {+ const message = messages[index];+ if (message.role === 'user') return false;+ if (typeof message.agentMeta?.parentUuid === 'string' && message.agentMeta.parentUuid) {+ return false;+ }+ if (message.role === 'tool_result') {+ const toolUseId = remoteToolUseId(message);+ if (toolUseId && prefixToolUseIds.has(toolUseId)) return false;+ if (+ prefixMarkdownImageUrls.size > 0+ && extractPayloadToolResultMedia(contentToPreview(message.content)).some(+ (media) => media.kind === 'image' && prefixMarkdownImageUrls.has(media.url),+ )+ ) {+ return false;+ }+ }+ if (message.role === 'tool_use' && isPlanToolName(parseMessageToolUse(message).toolName)) {+ return false;+ }+ if (+ message.role === 'assistant'+ && collectMobileMarkdownImages(contentToPreview(message.content)).length > 0+ ) {+ return false;+ }+ }+ return true;+}++function isPlanToolName(toolName: string): boolean {+ return toolName === 'TodoWrite'+ || toolName === 'update_plan'+ || toolName === 'TaskCreate'+ || toolName === 'TaskUpdate'+ || toolName === 'TaskList'+ || toolName === 'TaskGet';+}++function contentIsStreaming(content: unknown): boolean {+ if (!content || typeof content !== 'object') return false;+ if (Array.isArray(content)) return content.some(contentIsStreaming);+ const record = content as Record<string, unknown>;+ return record.isStreaming === true || record.streaming === true;+}++function findTopLevelMessageItemIndex(+ items: readonly MobileMessageRenderItem[],+ source: RemoteMessage,+): number {+ return items.findIndex(+ (item) => item.type === 'message' && item.message.source === source,+ );+}++function collectDependentTailToolResults(+ messages: readonly RemoteMessage[],+ prefixLength: number,+ prefixToolUseIds = collectToolUseIds(messages, prefixLength),+): RemoteMessage[] {+ if (prefixToolUseIds.size === 0) return [];+ const results: RemoteMessage[] = [];+ for (let index = prefixLength; index < messages.length; index += 1) {+ const message = messages[index];+ if (message.role !== 'tool_result') continue;+ const toolUseId = remoteToolUseId(message);+ if (toolUseId && prefixToolUseIds.has(toolUseId)) results.push(message);+ }+ return results;+}++function sameDependentTailToolResults(+ expected: readonly RemoteMessage[],+ messages: readonly RemoteMessage[],+ prefixLength: number,+ prefixToolUseIds: ReadonlySet<string> | undefined,+): boolean {+ if (!prefixToolUseIds || prefixToolUseIds.size === 0) return expected.length === 0;+ let expectedIndex = 0;+ for (let index = prefixLength; index < messages.length; index += 1) {+ const message = messages[index];+ if (message.role !== 'tool_result') continue;+ const toolUseId = remoteToolUseId(message);+ if (!toolUseId || !prefixToolUseIds.has(toolUseId)) continue;+ if (expected[expectedIndex] !== message) return false;+ expectedIndex += 1;+ }+ return expectedIndex === expected.length;+}++function collectToolUseIds(+ messages: readonly RemoteMessage[],+ endExclusive: number,+): Set<string> {+ const toolUseIds = new Set<string>();+ const end = Math.min(messages.length, Math.max(0, endExclusive));+ for (let index = 0; index < end; index += 1) {+ const message = messages[index];+ if (message.role !== 'tool_use') continue;+ const toolUseId = remoteToolUseId(message);+ if (toolUseId) toolUseIds.add(toolUseId);+ }+ return toolUseIds;+}++function collectAssistantMarkdownImageUrls(+ messages: readonly RemoteMessage[],+ endExclusive: number,+): Set<string> {+ const urls = new Set<string>();+ const end = Math.min(messages.length, Math.max(0, endExclusive));+ for (let index = 0; index < end; index += 1) {+ const message = messages[index];+ if (message.role !== 'assistant') continue;+ for (const image of collectMobileMarkdownImages(contentToPreview(message.content))) {+ urls.add(image.url);+ }+ }+ return urls;+}++function remoteToolUseId(message: RemoteMessage): string | null {+ if (typeof message.toolUseId === 'string' && message.toolUseId.length > 0) {+ return message.toolUseId;+ }+ if (!message.content || typeof message.content !== 'object' || Array.isArray(message.content)) {+ return null;+ }+ const value = (message.content as Record<string, unknown>).toolUseId;+ return typeof value === 'string' && value.length > 0 ? value : null;+}++function findLastRootUserMessageIndex(messages: readonly RemoteMessage[]): number {+ for (let index = messages.length - 1; index >= 0; index -= 1) {+ const message = messages[index];+ if (+ message.role === 'user'+ && isPlanUserBoundary(message)+ && !isSyntheticTriggerText(contentToPreview(message.content))+ ) {+ return index;+ }+ }+ return -1;+}++function sameMessageReferences(+ previous: readonly RemoteMessage[],+ next: readonly RemoteMessage[],+): boolean {+ return previous.length === next.length+ && previous.every((message, index) => message === next[index]);+}++function sameMessagePrefixReferences(+ previous: readonly RemoteMessage[],+ next: readonly RemoteMessage[],+ prefixLength: number,+): boolean {+ return previous.length === prefixLength+ && prefixLength <= next.length+ && previous.every((message, index) => message === next[index]);+}diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.tsindex 38975f5233..9ea80fa8be 100644--- a/apps/mobile/src/session/remoteSessionStore.ts+++ b/apps/mobile/src/session/remoteSessionStore.ts@@ -1,4 +1,13 @@-import { useEffect, useRef, useSyncExternalStore } from 'react';+import {+ createContext,+ createElement,+ useCallback,+ useContext,+ useEffect,+ useRef,+ useSyncExternalStore,+ type ReactNode,+} from 'react';import {MAKER_EVENT_BATCH_CHANNEL,SESSION_ACTIVITY_CHANNEL,@@ -5155,8 +5164,52 @@ function readNumber(value: unknown, key: string): number | null {return typeof raw === 'number' && Number.isFinite(raw) ? raw : null;}+const RemoteSessionStoreSubscriptionEnabledContext = createContext(true);+const INACTIVE_REMOTE_SESSION_STORE_SUBSCRIBE = () => () => undefined;++/**+ * Keep a mounted route's remote-session projection stable while it is covered by another screen.+ * The store itself keeps receiving data; consumers resubscribe and jump to the latest snapshot when+ * the route regains focus. This preserves native list state without rendering hidden row trees for+ * every streaming token.+ */+export function RemoteSessionStoreSubscriptionGate({+ children,+ enabled,+}: {+ children: ReactNode;+ enabled: boolean;+}) {+ return createElement(+ RemoteSessionStoreSubscriptionEnabledContext.Provider,+ { value: enabled },+ children,+ );+}++function usePausableRemoteSessionStoreSnapshot<T>(+ identity: unknown,+ getSnapshot: () => T,+): T {+ const enabled = useContext(RemoteSessionStoreSubscriptionEnabledContext);+ const frozenSnapshotRef = useRef<{ identity: unknown; value: T } | null>(null);+ const readSnapshot = useCallback(() => {+ const frozen = frozenSnapshotRef.current;+ if (enabled || frozen === null || !Object.is(frozen.identity, identity)) {+ const next = { identity, value: getSnapshot() };+ frozenSnapshotRef.current = next;+ return next.value;+ }+ return frozen.value;+ }, [enabled, getSnapshot, identity]);+ return useSyncExternalStore(+ enabled ? remoteSessionStore.subscribe : INACTIVE_REMOTE_SESSION_STORE_SUBSCRIBE,+ readSnapshot,+ );+}+export function useRemoteSessions(): RemoteSession[] {- return useSyncExternalStore(remoteSessionStore.subscribe, remoteSessionStore.getSessions);+ return usePausableRemoteSessionStoreSnapshot('sessions', remoteSessionStore.getSessions);}/** Subscribe to one session's message mirror without triggering cache hydration side effects. */@@ -5273,11 +5326,17 @@ function useSessionMessageCacheSync(}export function useRemoteMessageVersion(): number {- return useSyncExternalStore(remoteSessionStore.subscribe, remoteSessionStore.getMessageVersion);+ return usePausableRemoteSessionStoreSnapshot(+ 'message-version',+ remoteSessionStore.getMessageVersion,+ );}export function useRemoteSessionStoreVersion(): number {- return useSyncExternalStore(remoteSessionStore.subscribe, remoteSessionStore.getStoreVersion);+ return usePausableRemoteSessionStoreSnapshot(+ 'store-version',+ remoteSessionStore.getStoreVersion,+ );}export function useRemoteNewMakerWorktreePreference(@@ -5321,8 +5380,8 @@ export function useSessionInputProjection(sessionId: string): InputProjection {}export function useSessionRunning(sessionId: string): boolean {- return useSyncExternalStore(- remoteSessionStore.subscribe,+ return usePausableRemoteSessionStoreSnapshot(+ sessionId,() => remoteSessionStore.isSessionRunning(sessionId),);}