Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
perf(mobile): 降低长任务与外部列表内存压力
david17c1ee65dbdd
diff --git a/apps/mobile/app/devices/index.tsx b/apps/mobile/app/devices/index.tsxindex b774d33541..4bbe9a1df7 100644--- a/apps/mobile/app/devices/index.tsx+++ b/apps/mobile/app/devices/index.tsx@@ -43,7 +43,7 @@ import {X,} from 'lucide-react-native';import { Gesture, GestureDetector } from '@/platform/gestureHandler';-import Reanimated, { runOnJS, useAnimatedStyle, useSharedValue, type SharedValue } from 'react-native-reanimated';+import Reanimated, { runOnJS, useAnimatedReaction, useAnimatedStyle, useSharedValue, type SharedValue } from 'react-native-reanimated';import { useSafeAreaInsets } from 'react-native-safe-area-context';import { useTranslation } from 'react-i18next';import type { TFunction } from 'i18next';@@ -221,8 +221,16 @@ import { fontWeight, iconSize, iconStroke, lineHeight, radius, spacing, typeScalconst LIST_LIMIT = 200;const DEVICE_LIST_TIMEOUT_MS = 12_000;const HOME_LIST_SUBSCRIPTION_OWNER = 'device-list';+// Keep the device-link channel responsive while All Sessions hydrates several+// computers. This does not change the 200-row server limit; it only bounds the+// number of device snapshots processed at once.+const HOME_DEVICE_HYDRATE_CONCURRENCY = 2;// 项目组与自动化组展开后的子列表共用同一个预览限量(设备详情页也 import 复用,避免两处漂移)。export const PROJECT_PREVIEW_LIMIT = 5;+const PROJECT_CHILD_WINDOW_THRESHOLD = 20;+const PROJECT_CHILD_WINDOW_SIZE = 15;+const PROJECT_CHILD_WINDOW_OVERSCAN = 4;+const PROJECT_CHILD_WINDOW_SHIFT = 4;const HOME_SESSION_ROW_HEIGHT = 78;const HOME_SESSION_SINGLE_LINE_ROW_HEIGHT = 60;const CINDY_LIST_GUTTER = 20;@@ -231,6 +239,17 @@ const CINDY_LIST_FAB_BOTTOM = 45;const HOME_HEADER_MIN_HEIGHT = 48;const AnimatedPressable = Animated.createAnimatedComponent(Pressable);+function estimateHomeSessionRowHeight(item: RemoteSessionListItem): number {+ const running = remoteSessionStore.isSessionRunning(item.session.id)+ || item.scheduleInfo?.running === true+ || item.liveActivity?.phase === 'running';+ const hasPreview = item.automationGroup != null+ || !!buildRemoteSessionCardPreview(item, { running })?.trim()+ || !!item.scheduleInfo+ || !!item.session.pinnedAt;+ return hasPreview ? HOME_SESSION_ROW_HEIGHT : HOME_SESSION_SINGLE_LINE_ROW_HEIGHT;+}+type RemoteListStatusFilter = Extract<RemoteSessionStatusFilter, 'active' | 'archived' | 'all'>;type HomeDeviceConnectionState = 'idle' | 'syncing' | 'failed';@@ -304,6 +323,9 @@ export default function HomeScreen() {const syncInFlightRef = useRef<Promise<void> | null>(null);const syncQueuedRef = useRef<{ visible?: boolean } | null>(null);const loadHomeRef = useRef<(options?: { visible?: boolean }) => Promise<void>>(async () => undefined);+ const homePreviewCacheRef = useRef(new Map<string, { messages: readonly unknown[]; preview?: string }>());+ const homePendingCacheRef = useRef(new Map<string, { pending: readonly unknown[]; count: number }>());+ const homeLiveActivityIndexRef = useRef(new Map<string, RemoteSessionLiveActivity>());const devicesRef = useRef<DeviceView[]>([]);// HomeScreen stays mounted while switching saved accounts. Keep an owner generation beside every// local projection so requests started by the previous account cannot repopulate the new screen.@@ -413,6 +435,7 @@ export default function HomeScreen() {const projectDragEpochRef = useRef(0);const [projectDrag, setProjectDrag] = useState<ProjectDragSession | null>(null);const projectDragY = useSharedValue(0);+ const homeScrollY = useSharedValue(0);const [dialogueShowAll, setDialogueShowAll] = useState(false);const [priorityHoldEpoch, setPriorityHoldEpoch] = useState(0);// deviceId of the revoked-access device whose explanation tip is open (null = closed).@@ -691,18 +714,20 @@ export default function HomeScreen() {};}const nextSessions = Array.isArray(list) ? list : [];- remoteSessionStore.setDeviceSessions(- device.deviceId,- device.name,- nextSessions,- );- if (Array.isArray(activeSessions)) {- remoteSessionStore.setActiveSessionSnapshots(+ remoteSessionStore.batch(() => {+ remoteSessionStore.setDeviceSessions(device.deviceId,- activeSessions,- activeSessionSnapshotEpoch,+ device.name,+ nextSessions,);- }+ if (Array.isArray(activeSessions)) {+ remoteSessionStore.setActiveSessionSnapshots(+ device.deviceId,+ activeSessions,+ activeSessionSnapshotEpoch,+ );+ }+ });// schedule-index(1+N 个 listRuns)是次要徽标数据,延后发,避开"开 app→立刻点会话"时和会话关键读// 抢同一条 WS 管道(见 scheduleIndexDefer / issue #324)。home 自动化分组与名称已由 fallbackScheduleInfo// 兜底,徽标晚半拍出现即可。@@ -920,7 +945,7 @@ export default function HomeScreen() {const hydrateResults = await runHomeDeviceSyncBatch(syncRows, async (item) => {const result = await hydrateDeviceSessions(item.device, accountGenerationAtStart);return { deviceId: item.device.deviceId, result };- });+ }, HOME_DEVICE_HYDRATE_CONCURRENCY);for (const { deviceId, result } of hydrateResults) {if (result.superseded || homeAccountGenerationRef.current !== accountGenerationAtStart) continue;if (result.failure) failures.push(result.failure);@@ -1338,9 +1363,10 @@ export default function HomeScreen() {}, []);const onListScroll = useCallback((event: NativeSyntheticEvent<NativeScrollEvent>) => {+ homeScrollY.value = event.nativeEvent.contentOffset.y;const next = event.nativeEvent.contentOffset.y > 8;setHeaderFrosted((current) => (current === next ? current : next));- }, []);+ }, [homeScrollY]);const closeRenameDevice = useCallback(() => {if (renameSaving) return;@@ -1586,27 +1612,63 @@ export default function HomeScreen() {// 重建出内容相同的新 Map——若不做内容稳定化,home → sections → 全列表行整链每次// emit 都重建(2026-07-18 重渲染风暴 trace 实锤)。useStableValue 在内容未变时保留// 旧引用,下游 useMemo 依赖即可短路;内容真变(某会话预览/交互数/活动态变化)照常穿透。- const messagePreviewIndexRaw = useMemo(- () => buildSessionMessagePreviewIndex(- sessions.map((session) => session.id),- (sessionId) => remoteSessionStore.getMessages(sessionId),- ),- [messageVersion, sessions],- );+ const messagePreviewIndexRaw = useMemo(() => {+ const next = new Map<string, string>();+ const activeIds = new Set<string>();+ for (const session of sessions) {+ activeIds.add(session.id);+ const messages = remoteSessionStore.getMessages(session.id);+ const cached = homePreviewCacheRef.current.get(session.id);+ if (cached?.messages === messages) {+ if (cached.preview) next.set(session.id, cached.preview);+ continue;+ }+ const preview = buildSessionMessagePreviewIndex([session.id], () => messages).get(session.id);+ homePreviewCacheRef.current.set(session.id, { messages, preview });+ if (preview) next.set(session.id, preview);+ }+ for (const sessionId of homePreviewCacheRef.current.keys()) {+ if (!activeIds.has(sessionId)) homePreviewCacheRef.current.delete(sessionId);+ }+ return next;+ }, [messageVersion, sessions]);const messagePreviewIndex = useStableValue(messagePreviewIndexRaw, mapContentEqual);- const pendingInteractionIndexRaw = useMemo(() => new Map(- sessions- .map((session) => [session.id, remoteSessionStore.getPendingInteractions(session.id).length] as const)- .filter(([, count]) => count > 0),- ), [sessions, storeVersion]);+ const pendingInteractionIndexRaw = useMemo(() => {+ const next = new Map<string, number>();+ const activeIds = new Set<string>();+ for (const session of sessions) {+ activeIds.add(session.id);+ const pending = remoteSessionStore.getPendingInteractions(session.id);+ const cached = homePendingCacheRef.current.get(session.id);+ const count = cached?.pending === pending ? cached.count : pending.length;+ if (!cached || cached.pending !== pending) homePendingCacheRef.current.set(session.id, { pending, count });+ if (count > 0) next.set(session.id, count);+ }+ for (const sessionId of homePendingCacheRef.current.keys()) {+ if (!activeIds.has(sessionId)) homePendingCacheRef.current.delete(sessionId);+ }+ return next;+ }, [sessions, storeVersion]);const pendingInteractionIndex = useStableValue(pendingInteractionIndexRaw, mapContentEqual);const liveActivityIndexRaw = useMemo(() => {- const entries: Array<[string, RemoteSessionLiveActivity]> = [];+ const next = new Map<string, RemoteSessionLiveActivity>();for (const session of sessions) {const liveActivity = remoteSessionStore.getSessionLiveActivity(session.id);- if (liveActivity) entries.push([session.id, liveActivity]);+ if (liveActivity) next.set(session.id, liveActivity);+ }+ const previous = homeLiveActivityIndexRef.current;+ if (previous.size === next.size) {+ let unchanged = true;+ for (const [sessionId, value] of next) {+ if (previous.get(sessionId) !== value) {+ unchanged = false;+ break;+ }+ }+ if (unchanged) return previous;}- return new Map(entries);+ homeLiveActivityIndexRef.current = next;+ return next;}, [sessions, storeVersion]);const liveActivityIndex = useStableValue(liveActivityIndexRaw, mapContentEqual);// 列表隐藏 Orca worker 子会话(本期不支持进 worker 聊天);Lead + 普通会话保留。仅 mobile 侧过滤。@@ -2200,6 +2262,7 @@ export default function HomeScreen() {onToggleProject={toggleProject}projectDragging={projectDrag?.key === (item.kind === 'project' ? item.project.key : '')}projectHeaderRefs={projectHeaderRefs}+ homeScrollY={homeScrollY}onTogglePin={toggleSessionPinned}prevIsBlock={isBlockHomeRow(homeRowBefore(sections, section.key, index))}projectCollapsed={isFolderHomeRow(item) && collapsedProjectKeys.includes(item.project.key)}@@ -2230,6 +2293,7 @@ export default function HomeScreen() {toggleAutomationGroup,toggleProject,toggleSessionPinned,+ homeScrollY,]);// 底部边到边:列表填满到物理屏底(内容滚到 home indicator 下方),用 inset 兜底而非靠 SafeAreaView 留白带。@@ -3236,6 +3300,7 @@ function ProjectRow({onToggle,onToggleAutomationGroup,project,+ homeScrollY,showAll = false,suppressTopBorder = false,swipe,@@ -3254,6 +3319,7 @@ function ProjectRow({onToggle(): void;onToggleAutomationGroup(key: string): void;project: MobileHomeProjectGroup;+ homeScrollY?: SharedValue<number>;/** 对话组「查看全部」在原地展开,不跳设备详情。 */showAll?: boolean;/** 前一行也是块(项目组 / 自动化组)时不画顶线:前块底线已是这根分割线。 */@@ -3268,6 +3334,7 @@ function ProjectRow({// PureComponent bail)——以 storeVersion 订阅兜底感知运行态变化,与 AutomationGroup-// Children 同款(否则折叠线以下转入 running 的会话不会被豁免展开,review P1)。useRemoteSessionStoreVersion();+ const storeVersion = remoteSessionStore.getStoreVersion();// 与桌面侧栏项目组同一套折叠策略:前 N 条之外豁免最近 24h 活动 / 需关注 / 运行中的条目// (豁免语义见共享层 getRemoteSessionPreviewCollapse 注释)。// 自动化折叠后 sessions 是"行"(组行代表多条会话):按钮显隐看隐藏行数(hiddenCount),@@ -3279,6 +3346,54 @@ function ProjectRow({isSessionRunning: (sessionId) => remoteSessionStore.isSessionRunning(sessionId),},);+ const projectTop = useSharedValue(0);+ const projectRef = useRef<View>(null);+ const [windowAnchor, setWindowAnchor] = useState(0);+ const [projectLayoutReady, setProjectLayoutReady] = useState(false);+ const estimatedChildHeights = useMemo(+ () => visibleSessions.map(estimateHomeSessionRowHeight),+ [visibleSessions, storeVersion],+ );+ // Windowing is only enabled for genuinely large, uniform child trees. The+ // common project preview (five rows) remains byte-for-byte unchanged, while+ // a large expanded group avoids mounting all rows at once without relying on+ // a nested virtualized list.+ const windowingEligible = !!homeScrollY+ && !collapsed+ && projectLayoutReady+ && visibleSessions.length > PROJECT_CHILD_WINDOW_THRESHOLD+ && estimatedChildHeights.every((height) => height === estimatedChildHeights[0]);+ const scrollY = homeScrollY;+ const estimatedRowHeight = estimatedChildHeights[0] ?? HOME_SESSION_ROW_HEIGHT;+ useAnimatedReaction(+ () => {+ if (!windowingEligible) return -1;+ const relativeY = Math.max(0, scrollY!.value - projectTop.value - HOME_SESSION_ROW_HEIGHT);+ return Math.floor(relativeY / Math.max(1, estimatedRowHeight) / PROJECT_CHILD_WINDOW_SHIFT)+ * PROJECT_CHILD_WINDOW_SHIFT;+ },+ (next, previous) => {+ if (next < 0 || next === previous) return;+ runOnJS(setWindowAnchor)(next);+ },+ [scrollY, windowingEligible, estimatedRowHeight],+ );+ const windowStart = windowingEligible+ ? Math.max(0, Math.min(+ Math.max(0, visibleSessions.length - PROJECT_CHILD_WINDOW_SIZE),+ windowAnchor - PROJECT_CHILD_WINDOW_OVERSCAN,+ ))+ : 0;+ const windowEnd = windowingEligible+ ? Math.min(visibleSessions.length, windowStart + PROJECT_CHILD_WINDOW_SIZE + PROJECT_CHILD_WINDOW_OVERSCAN * 2)+ : visibleSessions.length;+ const renderedSessions = windowingEligible ? visibleSessions.slice(windowStart, windowEnd) : visibleSessions;+ const leadingSpacerHeight = windowingEligible+ ? estimatedChildHeights.slice(0, windowStart).reduce((sum, height) => sum + height, 0)+ : 0;+ const trailingSpacerHeight = windowingEligible+ ? estimatedChildHeights.slice(windowEnd).reduce((sum, height) => sum + height, 0)+ : 0;const groupTestID = kind === 'dialogue' ? 'home.dialogueGroup' : 'home.projectGroup';const rowTestID = kind === 'dialogue' ? 'home.dialogueRow' : 'home.projectRow';const childTestID = kind === 'dialogue' ? 'home.chatRow' : 'home.projectSessionRow';@@ -3344,6 +3459,21 @@ function ProjectRow({);return (<View+ onLayout={(event) => {+ const fallbackY = event.nativeEvent.layout.y;+ projectRef.current?.measureInWindow((_x, screenY) => {+ projectTop.value = screenY + (homeScrollY?.value ?? 0);+ setProjectLayoutReady(true);+ });+ // A native measure can be unavailable in shallow/unit renderers. Keep+ // the local layout as a safe fallback; the real device measurement+ // above is used whenever the row is mounted in a ScrollView.+ if (!projectRef.current) {+ projectTop.value = fallbackY;+ setProjectLayoutReady(true);+ }+ }}+ ref={projectRef}style={[styles.projectGroup, suppressTopBorder && styles.projectGroupNoTop]}testID={groupTestID}>@@ -3351,7 +3481,22 @@ function ProjectRow({{collapsed ? null : (<View style={styles.projectChildren} testID="home.projectChildren">- {visibleSessions.map((item, index) => {+ {leadingSpacerHeight > 0 ? <View pointerEvents="none" style={{ height: leadingSpacerHeight }} /> : null}+ {renderedSessions.map((item, renderedIndex) => {+ const index = windowStart + renderedIndex;+ const itemKey = item.automationGroup?.key ?? item.session.id;+ const swipeable = !!swipe+ && !item.automationGroup+ && conversationSearchAllowsLocalWrites(item);+ // Window shifts used to key rows by session id, so crossing one+ // four-row boundary destroyed and recreated four complete native+ // swipe trees in the same frame. Keep a stable pool of render+ // slots while windowing; the row receives new data without paying+ // the native mount/unmount cost. Preserve identity keys outside the+ // windowed path, and remount a slot when its outer shell changes.+ const reactKey = windowingEligible+ ? `${project.key}:window:${renderedIndex}:${swipeable ? 'swipe' : 'plain'}`+ : itemKey;const row = (<HomeSessionRowexpandedAutomationGroups={expandedAutomationGroups}@@ -3368,12 +3513,12 @@ function ProjectRow({);// 与顶层同一条规则:普通会话子行挂滑动,自动化组行不挂(组行语义含混,// 其展开子行由 AutomationGroupChildren 内的透传包裹)。- if (!swipe || item.automationGroup || !conversationSearchAllowsLocalWrites(item)) {- return <Fragment key={item.automationGroup?.key ?? item.session.id}>{row}</Fragment>;+ if (!swipeable) {+ return <Fragment key={reactKey}>{row}</Fragment>;}return (<SwipeableSessionRow- key={item.session.id}+ key={reactKey}onArchive={swipe.onArchive}onShowOptions={swipe.onShowOptions}onTogglePin={swipe.onTogglePin}@@ -3385,6 +3530,7 @@ function ProjectRow({</SwipeableSessionRow>);})}+ {trailingSpacerHeight > 0 ? <View pointerEvents="none" style={{ height: trailingSpacerHeight }} /> : null}{hiddenRowCount > 0 ? (<PressableaccessibilityLabel={t('devices.list.viewAllConversations', { count: project.sessionCount })}@@ -3444,6 +3590,7 @@ function HomeListRowInner({projectCollapsed,projectDragging,projectHeaderRefs,+ homeScrollY,registry,showAllDialogue,swipe,@@ -3469,6 +3616,7 @@ function HomeListRowInner({projectCollapsed: boolean;projectDragging: boolean;projectHeaderRefs: MutableRefObject<Map<string, View>>;+ homeScrollY?: SharedValue<number>;registry: ReturnType<typeof createSwipeRowRegistry>;showAllDialogue: boolean;swipe: SessionSwipeControls;@@ -3490,6 +3638,7 @@ function HomeListRowInner({onToggle={() => onToggleProject(item.project.key)}onToggleAutomationGroup={onToggleAutomationGroup}project={item.project}+ homeScrollY={homeScrollY}showAll={item.kind === 'dialogue' && showAllDialogue}suppressTopBorder={prevIsBlock}swipe={swipe}diff --git a/apps/mobile/app/listperf.tsx b/apps/mobile/app/listperf.tsxindex f500dad03f..9f4a7d48d6 100644--- a/apps/mobile/app/listperf.tsx+++ b/apps/mobile/app/listperf.tsx@@ -4,7 +4,7 @@* 顶层路由(不在 (auth) 组)→ 已登录用户可直接访问,auth 守卫不拦。** 用法(deeplink):- * lizcn://listperf?turns=300&media=1&auto=1&vel=45+ * lizcn://listperf?turns=300&media=1&auto=1&vel=45&recycle=1* - turns: 轮数(每轮 1 user + 1 assistant),默认 300* - media: 1=含 mermaid/math(WebView),0=纯文本(隔离 WebView 成本),默认 1* - auto: 1=进入后自动做一次「底→顶」匀速滚动扫描并测帧,默认 0@@ -17,24 +17,34 @@ import { SafeAreaView } from 'react-native-safe-area-context';import { buildListPerfRenderItems } from '@/debug/listPerfFixture';import { runScrollSweep, type FrameStats } from '@/debug/scrollProfiler';import { MessageRenderer } from '@/session/MessageRenderer';+import type { MobileMessageWebViewMetrics } from '@/session/mobileMessageWebViewMetrics';+import {+ resetMobileMarkdownRenderMetrics,+ type MobileMarkdownRenderMetrics,+} from '@/session/mobileMarkdownRenderMetrics';type ListApi = {scrollTo: (y: number) => void;getMetrics: () => { contentHeight: number; offsetY: number; viewportHeight: number };+ getWebViewMetrics: () => MobileMessageWebViewMetrics;+ getMarkdownMetrics: () => MobileMarkdownRenderMetrics;};export default function ListPerfHarness() {- const params = useLocalSearchParams<{ turns?: string; media?: string; auto?: string; vel?: string; run?: string }>();+ const params = useLocalSearchParams<{ turns?: string; media?: string; auto?: string; vel?: string; recycle?: string; run?: string }>();const turns = Math.max(1, Math.min(2000, Number(params.turns) || 300));const media = params.media !== '0';const auto = params.auto === '1';+ const recycle = params.recycle === '1';const pxPerFrame = Math.max(5, Math.min(200, Number(params.vel) || 45));const items = useMemo(() => buildListPerfRenderItems(turns, { media }), [turns, media]);- const runKey = `${turns}|${media ? 1 : 0}|${pxPerFrame}|${params.run ?? '0'}`;+ const runKey = `${turns}|${media ? 1 : 0}|${pxPerFrame}|${recycle ? 1 : 0}|${params.run ?? '0'}`;const apiRef = useRef<ListApi | null>(null);const startedKeyRef = useRef<string | null>(null);const [stats, setStats] = useState<FrameStats | null>(null);+ const [webViewMetrics, setWebViewMetrics] = useState<MobileMessageWebViewMetrics | null>(null);+ const [markdownMetrics, setMarkdownMetrics] = useState<MobileMarkdownRenderMetrics | null>(null);const [phase, setPhase] = useState<string>(auto ? 'waiting…' : 'manual');const devExposeList = useCallback((api: ListApi) => {@@ -45,6 +55,11 @@ export default function ListPerfHarness() {if (!auto || startedKeyRef.current === runKey) return undefined;let cancelled = false;setStats(null);+ setWebViewMetrics(null);+ setMarkdownMetrics(null);+ // Counters are process-global so repeated A/B deeplinks must start from a+ // clean window; otherwise B includes all parses performed by A.+ resetMobileMarkdownRenderMetrics();// 轮询等列表布局稳定(contentHeight 被 onContentSizeChange/onScroll 填好),再开扫。const waitAndRun = (attempt: number) => {if (cancelled) return;@@ -63,7 +78,7 @@ export default function ListPerfHarness() {api!.scrollTo(0);setTimeout(() => {runScrollSweep({- label: `list=Legend turns=${turns} media=${media ? 1 : 0} vel=${pxPerFrame}`,+ label: `list=Legend turns=${turns} media=${media ? 1 : 0} recycle=${recycle ? 1 : 0} vel=${pxPerFrame}`,fromY: 0,toY: 1_000_000,pxPerFrame,@@ -72,6 +87,10 @@ export default function ListPerfHarness() {onDone: (s) => {if (cancelled) return;setStats(s);+ const currentWebViewMetrics = apiRef.current?.getWebViewMetrics();+ if (currentWebViewMetrics) setWebViewMetrics(currentWebViewMetrics);+ const currentMarkdownMetrics = apiRef.current?.getMarkdownMetrics();+ if (currentMarkdownMetrics) setMarkdownMetrics(currentMarkdownMetrics);setPhase('done');// 打到 Metro 日志,便于抓取。// eslint-disable-next-line no-console@@ -96,17 +115,28 @@ export default function ListPerfHarness() {<SafeAreaView style={styles.fill} edges={['top']}><View style={styles.bar}><Text style={styles.barText}>- PERF · LegendList · turns={turns} · items={items.length} · media={media ? 1 : 0} · {phase}+ PERF · LegendList · turns={turns} · items={items.length} · media={media ? 1 : 0} · recycle={recycle ? 1 : 0} · {phase}</Text>{stats ? (<Text style={styles.statText}>fps={stats.fps} avg={stats.avgMs}ms p50={stats.p50} p95={stats.p95} p99={stats.p99} max={stats.maxMs} | jank>32={stats.jank32}/{stats.frames} >50={stats.jank50}</Text>) : null}+ {webViewMetrics ? (+ <Text style={styles.statText}>+ webview mounted={webViewMetrics.mounted} mermaid={webViewMetrics.mountedByKind.mermaid} math={webViewMetrics.mountedByKind.math} media={webViewMetrics.mountedByKind.media} composer={webViewMetrics.mountedByKind.composer}+ </Text>+ ) : null}+ {markdownMetrics ? (+ <Text style={styles.statText}>+ markdown full={markdownMetrics.fullParseCount} incremental={markdownMetrics.incrementalParseCount} reusedBlocks={markdownMetrics.reusedBlockCount} parsedUtf16={markdownMetrics.parsedSourceUtf16Length} parseMs={markdownMetrics.parseDurationMsTotal.toFixed(1)} maxMs={markdownMetrics.parseDurationMsMax.toFixed(1)} renderItems={markdownMetrics.renderItemRebuildCount}+ </Text>+ ) : null}</View><View style={styles.fill}><MessageRendereritems={items}+ devRecycleItems={recycle}testID="perf.list"devExposeList={devExposeList}/>diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex 500c06833d..af4220327c 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -1823,6 +1823,8 @@ export default function SessionScreen() {// 退屏后才完成的 in-flight 取件:缓存已被 releaseAll 清空接管不到,这里直接// 补 DELETE,避免「退出时正在取件」的对象漏出退屏统一清理悬到生命周期兜底。onOrphanResolved: (media) => deleteRemoteMediaObject(media),+ }, {+ maxCacheBytes: 16 * 1024 * 1024,}), [deleteRemoteMediaObject]);remoteMediaQueueRef.current ??= createRemoteMediaQueue();const voiceRecordingActiveRef = useRef(false);@@ -4845,15 +4847,41 @@ export default function SessionScreen() {// 变化与 unmount 时都执行:releaseAll + 补删(fire-and-forget;App 被杀等不触发// cleanup 的情况由 OSS 生命周期规则兜底),并换上全新队列实例(released 标志// 一次性,释放过的队列不能复用;unmount 分支多建一个空队列无害)。- useEffect(() => () => {+ const releaseRemoteMediaQueue = useCallback(() => {const released = remoteMediaQueueRef.current?.releaseAll() ?? [];for (const media of released) {// 仍在后台落盘的对象等落盘结束再删,避免 DELETE 抢先把落盘下载打成 404;// 磁盘缓存命中的空 ossKey 条目在 deleteRemoteMediaObject 内跳过。deleteRemoteMediaObject(media);}- remoteMediaQueueRef.current = createRemoteMediaQueue();- }, [sessionId, createRemoteMediaQueue, deleteRemoteMediaObject]);+ remoteMediaQueueRef.current = null;+ }, [deleteRemoteMediaObject]);++ useFocusEffect(+ useCallback(() => () => {+ releaseRemoteMediaQueue();+ }, [releaseRemoteMediaQueue]),+ );++ useEffect(() => () => {+ releaseRemoteMediaQueue();+ }, [releaseRemoteMediaQueue, sessionId]);++ // Navigation focus does not change when Android backgrounds the activity.+ // Release resolved media and queued fetches at the AppState boundary too;+ // the next foreground request lazily creates a fresh queue.+ useEffect(() => {+ const subscription = AppState.addEventListener('change', (nextState) => {+ if (nextState !== 'active') {+ releaseRemoteMediaQueue();+ return;+ }+ if (!remoteMediaQueueRef.current) {+ remoteMediaQueueRef.current = createRemoteMediaQueue();+ }+ });+ return () => subscription.remove();+ }, [createRemoteMediaQueue, releaseRemoteMediaQueue]);/** 单调递增的补齐轮次计数器;`latest` 是本屏最新那一轮的序号(旧轮据此自我作废)。 */const backfillRunSeqRef = useRef(0);diff --git a/apps/mobile/src/__tests__/messageListVirtualization.test.ts b/apps/mobile/src/__tests__/messageListVirtualization.test.tsindex 828b3f48b1..34aae54cae 100644--- a/apps/mobile/src/__tests__/messageListVirtualization.test.ts+++ b/apps/mobile/src/__tests__/messageListVirtualization.test.ts@@ -27,7 +27,8 @@ describe('mobile message list container', () => {expect(listSource).toContain('maintainScrollAtEnd');expect(listSource).toContain('maintainVisibleContentPosition={{ data: true, size: true }}');// cell 含内部 state(展开态 / 手势图 / mermaid·math WebView),关闭回收避免实例错误复用。- expect(listSource).toContain('recycleItems={false}');+ expect(source).toContain('const recycleItems = __DEV__ && devRecycleItems === true;');+ expect(listSource).toContain('recycleItems={recycleItems}');// 上滑加载:LegendList 近顶阈值触发自动预取(替代手搓的滚动 metric 判定)。expect(listSource).toContain('onStartReached={handleStartReached}');// 自动预取必须是电平判定(shouldAutoLoadEarlier + 多时机重评估),不许退回只吃 onStartReacheddiff --git a/apps/mobile/src/__tests__/messageMarkdown.test.ts b/apps/mobile/src/__tests__/messageMarkdown.test.tsindex 0ca1f34716..042a3b4a98 100644--- a/apps/mobile/src/__tests__/messageMarkdown.test.ts+++ b/apps/mobile/src/__tests__/messageMarkdown.test.ts@@ -10,6 +10,8 @@ import {MOBILE_MARKDOWN_IMAGE_ALT_CHIP_MAX_UTF16_LENGTH,mobileMarkdownInlineImageSize,parseMobileMarkdown,+ parseMobileMarkdownDocument,+ parseMobileMarkdownIncremental,parseMobileMarkdownInlines,groupMobileMarkdownSelectableBlocks,} from '@/session/messageMarkdown';@@ -19,6 +21,102 @@ beforeAll(async () => {await i18n.changeLanguage('zh-CN');});+describe('incremental mobile Markdown parsing', () => {+ it('reuses completed blocks after a safe blank-line checkpoint', () => {+ const first = parseMobileMarkdownDocument('# title\n\nfirst paragraph');+ const next = parseMobileMarkdownIncremental(+ '# title\n\nfirst paragraph\n\nsecond paragraph',+ first,+ );+ const full = parseMobileMarkdownDocument(next.source);++ expect(next.incremental).toBe(true);+ expect(next.reusedBlockCount).toBe(1);+ expect(next.blocks).toEqual(full.blocks);+ expect(next.blocks[0]).toBe(first.blocks[0]);+ expect(next.parsedSourceUtf16Length).toBe('first paragraph\n\nsecond paragraph'.length);+ });++ it('falls back to a full parse for an edit in the existing prefix', () => {+ const first = parseMobileMarkdownDocument('# title\n\nfirst paragraph');+ const next = parseMobileMarkdownIncremental(+ '# changed\n\nfirst paragraph\n\nsecond paragraph',+ first,+ );++ expect(next.incremental).toBe(false);+ expect(next.reusedBlockCount).toBe(0);+ expect(next.blocks).toEqual(parseMobileMarkdownDocument(next.source).blocks);+ });++ it('keeps fenced code and display math semantics when appending', () => {+ const codeFirst = parseMobileMarkdownDocument('intro\n\n```ts\nconst x = 1;\n```');+ const codeNext = parseMobileMarkdownIncremental(+ `${codeFirst.source}\n\nend`,+ codeFirst,+ );+ expect(codeNext.blocks).toEqual(parseMobileMarkdownDocument(codeNext.source).blocks);++ const mathFirst = parseMobileMarkdownDocument('intro\n\n$$\nx = 1\n$$');+ const mathNext = parseMobileMarkdownIncremental(+ `${mathFirst.source}\n\nend`,+ mathFirst,+ );+ expect(mathNext.blocks).toEqual(parseMobileMarkdownDocument(mathNext.source).blocks);+ });++ it('falls back when an escaped inline math opener is closed by a later flush', () => {+ const first = parseMobileMarkdownDocument('intro\n\nvalue \\(');+ const next = parseMobileMarkdownIncremental(`${first.source}x\\)`, first);+ const full = parseMobileMarkdownDocument(next.source);++ expect(next.incremental).toBe(false);+ expect(next.reusedBlockCount).toBe(0);+ expect(next.blocks).toEqual(full.blocks);+ });++ it('keeps line offsets when appending after a closed fence without a trailing newline', () => {+ const first = parseMobileMarkdownDocument('intro\n\n```ts\nconst x = 1;\n```');+ const next = parseMobileMarkdownIncremental(`${first.source}\n\nend`, first);+ const full = parseMobileMarkdownDocument(next.source);++ expect(next.blocks).toEqual(full.blocks);+ expect(next.blocks.at(-1)?.key).toBe(full.blocks.at(-1)?.key);+ });++ it('does not reuse an EOF checkpoint when an append mutates its last line', () => {+ const first = parseMobileMarkdownDocument('```ts\nconst x = 1;\n```');+ const next = parseMobileMarkdownIncremental(`${first.source}continued`, first);++ expect(next.incremental).toBe(false);+ expect(next.blocks).toEqual(parseMobileMarkdownDocument(next.source).blocks);+ });++ it('preserves full-parser semantics across character-by-character streaming flushes', () => {+ const fixtures = [+ '# heading\n\nplain text\n\n- item\n\nend',+ 'intro\n\n```ts\nconst x = 1;\n```\n\nresult',+ 'intro\n\n$$\nx = 1\n$$\n\nresult',+ 'prefix \\(x + 1\\) suffix\n\nnext',+ '<!-- hidden\n\ntext -->\n\nvisible',+ ];+ for (const fixture of fixtures) {+ let previous: ReturnType<typeof parseMobileMarkdownDocument> | null = null;+ for (let end = 1; end <= fixture.length; end += 1) {+ const source = fixture.slice(0, end);+ const result = parseMobileMarkdownIncremental(source, previous);+ expect(result.blocks, `prefix length ${end}`).toEqual(+ parseMobileMarkdownDocument(source).blocks,+ );+ expect(result.ranges, `ranges at prefix length ${end}`).toEqual(+ parseMobileMarkdownDocument(source).ranges,+ );+ previous = result;+ }+ }+ });+});+describe('messageMarkdown', () => {it('parses the reported PR-watch long message without creating an oversized inline image', () => {const blocks = parseMobileMarkdown(PR_WATCH_EXPANDED_BLANK_FIXTURE);diff --git a/apps/mobile/src/__tests__/messageWebViewGovernance.test.ts b/apps/mobile/src/__tests__/messageWebViewGovernance.test.tsnew file mode 100644index 0000000000..69e5b70f9e--- /dev/null+++ b/apps/mobile/src/__tests__/messageWebViewGovernance.test.ts@@ -0,0 +1,66 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { beforeEach, describe, expect, it } from 'vitest';+import {+ getMobileMessageWebViewMetrics,+ registerMobileMessageWebView,+ resetMobileMessageWebViewMetrics,+} from '@/session/mobileMessageWebViewMetrics';++describe('mobile message WebView lifecycle accounting', () => {+ beforeEach(() => resetMobileMessageWebViewMetrics());++ it('counts active instances by kind and makes cleanup idempotent', () => {+ const releaseMermaid = registerMobileMessageWebView('mermaid');+ const releaseMath = registerMobileMessageWebView('math');++ expect(getMobileMessageWebViewMetrics()).toMatchObject({+ mounted: 2,+ mountedByKind: { mermaid: 1, math: 1, media: 0, composer: 0 },+ mounts: 2,+ unmounts: 0,+ });++ releaseMermaid();+ releaseMermaid();+ releaseMath();+ expect(getMobileMessageWebViewMetrics()).toMatchObject({+ mounted: 0,+ mountedByKind: { mermaid: 0, math: 0, media: 0, composer: 0 },+ mounts: 2,+ unmounts: 2,+ });+ });+});++describe('message WebView visibility wiring', () => {+ it('gates heavy message blocks without changing the list virtualization contract', () => {+ const renderer = readFileSync(+ resolve(process.cwd(), 'src/session/MessageRenderer.tsx'),+ 'utf8',+ );+ const mermaid = readFileSync(resolve(process.cwd(), 'src/session/mermaidWebView.tsx'), 'utf8');+ const math = readFileSync(resolve(process.cwd(), 'src/session/mathWebView.tsx'), 'utf8');+ 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).toContain('active={heavyContentVisible}');+ expect(renderer).toContain('getWebViewMetrics: getMobileMessageWebViewMetrics');+ expect(renderer).toContain('getMarkdownMetrics: getMobileMarkdownRenderMetrics');+ expect(renderer).toContain('const recycleItems = __DEV__ && devRecycleItems === true;');+ expect(renderer).toContain('recycleItems={recycleItems}');+ expect(mermaid).toContain('active?: boolean;');+ expect(mermaid).toMatch(/active\s*\?\s*<WebView/);+ expect(math).toContain('active?: boolean;');+ expect(math).toMatch(/active\s*\?\s*<WebView/);+ expect(math).toContain('renderGenerationRef.current !== renderGeneration');+ expect(mermaid).toContain('pendingExportsRef.current.clear();');+ expect(mermaid).toContain('}, [active, source]);');+ expect(media).toContain('stopPlaybackAndLoading');+ expect(media).toContain('webViewRef.current?.stopLoading();');+ expect(media).toContain('if (!mountedRef.current) return;');+ expect(composer).toContain('if (disposedRef.current) return;');+ });+});diff --git a/apps/mobile/src/__tests__/mobileMarkdownRenderMetrics.test.ts b/apps/mobile/src/__tests__/mobileMarkdownRenderMetrics.test.tsnew file mode 100644index 0000000000..795a1e1166--- /dev/null+++ b/apps/mobile/src/__tests__/mobileMarkdownRenderMetrics.test.ts@@ -0,0 +1,32 @@+import { beforeEach, describe, expect, it } from 'vitest';+import { parseMobileMarkdownDocument } from '@/session/messageMarkdown';+import {+ getMobileMarkdownRenderMetrics,+ recordMobileMarkdownParse,+ recordMobileMessageRenderItem,+ resetMobileMarkdownRenderMetrics,+} from '@/session/mobileMarkdownRenderMetrics';++describe('mobile Markdown/render metrics', () => {+ beforeEach(() => resetMobileMarkdownRenderMetrics());++ it('separates full and incremental parses and accumulates allocation counters', () => {+ const full = parseMobileMarkdownDocument('one');+ const incremental = { ...full, incremental: true, reusedBlockCount: 1, parsedSourceUtf16Length: 4 };++ recordMobileMarkdownParse(full, 2.5);+ recordMobileMarkdownParse(incremental, 1.25);+ recordMobileMessageRenderItem();+ recordMobileMessageRenderItem();++ expect(getMobileMarkdownRenderMetrics()).toEqual({+ fullParseCount: 1,+ incrementalParseCount: 1,+ reusedBlockCount: 1,+ parsedSourceUtf16Length: 7,+ parseDurationMsTotal: 3.75,+ parseDurationMsMax: 2.5,+ renderItemRebuildCount: 2,+ });+ });+});diff --git a/apps/mobile/src/__tests__/remoteMediaResolveQueue.test.ts b/apps/mobile/src/__tests__/remoteMediaResolveQueue.test.tsindex 895aa591cd..bf097762bb 100644--- a/apps/mobile/src/__tests__/remoteMediaResolveQueue.test.ts+++ b/apps/mobile/src/__tests__/remoteMediaResolveQueue.test.ts@@ -98,6 +98,32 @@ describe('remoteMediaResolveQueue', () => {expect(resolve).toHaveBeenCalledTimes(1);});+ it('bounds resolved cache bytes and evicts the least recently used entry', async () => {+ const { pending, resolve } = manualResolver();+ const orphaned: MobileResolvedRemoteMedia[] = [];+ const queue = createRemoteMediaResolveQueue(+ { resolve, onOrphanResolved: (media) => orphaned.push(media) },+ { maxConcurrent: 1, maxCacheBytes: 2_000 },+ );+ const resolveOne = async (name: string): Promise<MobileResolvedRemoteMedia> => {+ const promise = queue.request(imageRequest(name));+ await flush();+ pending.at(-1)?.resolve(resolvedMedia(name, { size: 1_000 }));+ return promise;+ };++ await resolveOne('a.png');+ await resolveOne('b.png');+ // Refresh A so B becomes the oldest entry.+ expect(queue.peekFresh(imageRequest('a.png').url)).not.toBeNull();+ await resolveOne('c.png');++ expect(queue.peekFresh(imageRequest('a.png').url)).not.toBeNull();+ expect(queue.peekFresh(imageRequest('b.png').url)).toBeNull();+ expect(queue.peekFresh(imageRequest('c.png').url)).not.toBeNull();+ expect(orphaned.map((media) => media.ossKey)).toEqual(['key/b.png']);+ });+it('dedupes concurrent requests for the same url into one resolve call', async () => {const { pending, resolve } = manualResolver();const queue = createRemoteMediaResolveQueue({ resolve });diff --git a/apps/mobile/src/__tests__/sessionMessageMemoryWiring.test.ts b/apps/mobile/src/__tests__/sessionMessageMemoryWiring.test.tsindex 38afb9639c..4d7459a9f5 100644--- a/apps/mobile/src/__tests__/sessionMessageMemoryWiring.test.ts+++ b/apps/mobile/src/__tests__/sessionMessageMemoryWiring.test.ts@@ -97,4 +97,15 @@ describe('任务消息内存治理页面接线', () => {expect(store).toContain('isSessionMessageCacheWriteAuthorityCurrent(cacheAuthority)');expect(store).toContain('remoteSessionStore.isSessionMessageAuthorityCurrent(authority)');});++ it('屏幕失焦时也释放媒体队列,避免栈页面切换后累积内存条目', () => {+ const queueStart = screen.indexOf('const releaseRemoteMediaQueue = useCallback');+ expect(queueStart).toBeGreaterThanOrEqual(0);+ const queueBlock = screen.slice(queueStart, queueStart + 1400);+ expect(queueBlock).toContain('remoteMediaQueueRef.current?.releaseAll()');+ expect(queueBlock).toContain('remoteMediaQueueRef.current = null;');+ expect(queueBlock).toContain('remoteMediaQueueRef.current = createRemoteMediaQueue();');+ expect(queueBlock).toContain('useFocusEffect(');+ expect(queueBlock).toContain('releaseRemoteMediaQueue();');+ });});diff --git a/apps/mobile/src/session/ComposerRichInput.tsx b/apps/mobile/src/session/ComposerRichInput.tsxindex b8c25956ec..af83d01261 100644--- a/apps/mobile/src/session/ComposerRichInput.tsx+++ b/apps/mobile/src/session/ComposerRichInput.tsx@@ -18,6 +18,7 @@ import {type ComposerWebMessage,} from '@/session/composerRichInputProtocol';import { COMPOSER_PASTED_IMAGE_FILE_PREFIX } from '@/session/pastedImageAttachment';+import { registerMobileMessageWebView } from '@/session/mobileMessageWebViewMetrics';export interface ComposerRichInputHandle {applyDocumentAndSetSelectionToEnd(document: ComposerDocument): void;@@ -78,6 +79,7 @@ export const ComposerRichInput = forwardRef<ComposerRichInputHandle, ComposerRictheme,}, forwardedRef) {const webViewRef = useRef<WebView | null>(null);+ useEffect(() => registerMobileMessageWebView('composer'), []);const readyRef = useRef(false);const webSignatureRef = useRef('');const pendingDocumentRef = useRef<{@@ -313,6 +315,7 @@ export const ComposerRichInput = forwardRef<ComposerRichInputHandle, ComposerRic}, [inject, resolveSessionLinkLabel]);const handleMessage = useCallback((event: WebViewMessageEvent) => {+ if (disposedRef.current) return;const message = parseComposerWebMessage(event.nativeEvent.data);if (!message) return;if (message.type === 'ready') {diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsxindex a6994553bf..ed42dd2582 100644--- a/apps/mobile/src/session/MessageRenderer.tsx+++ b/apps/mobile/src/session/MessageRenderer.tsx@@ -1,4 +1,4 @@-import { Fragment, memo, useCallback, useContext, useEffect, useMemo, useRef, useState, type ComponentProps, type ReactNode } from 'react';+import { createContext, Fragment, memo, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, type ComponentProps, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';import {ArrowLeftRight,@@ -172,8 +172,9 @@ import {mobileMarkdownImageTitle,mobileMarkdownImageUrlForWorkdir,mobileMarkdownInlineImageSize,- parseMobileMarkdown,+ parseMobileMarkdownIncremental,parseMobileMarkdownInlines,+ type MobileMarkdownParseResult,type MobileMarkdownBlockGroup,type MobileMarkdownInline,type MobileMarkdownTextRunGroupingOptions,@@ -330,6 +331,12 @@ import {type MermaidDiagramWebViewHandle,} from '@/session/mermaidWebView';import { MathFormulaWebView } from '@/session/mathWebView';+import { getMobileMessageWebViewMetrics } from '@/session/mobileMessageWebViewMetrics';+import {+ getMobileMarkdownRenderMetrics,+ recordMobileMarkdownParse,+ recordMobileMessageRenderItem,+} from '@/session/mobileMarkdownRenderMetrics';import { latexToUnicodeApproximation } from '@cindy/maker-shared/math-markdown';import type { RemoteTextFilePreviewResult } from '@/device-link/mobileMakerTransport';import { fontWeight, lineHeight, radius, spacing, typeScale } from '@/theme/tokens';@@ -342,6 +349,11 @@ 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;+// 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;const STICKY_SHARE_CHECK_THROTTLE_MS = 150;@@ -586,6 +598,7 @@ export function MessageRenderer({syncingWhileEmpty,testID,devExposeList,+ devRecycleItems = false,}: {bottomOverlayHeight?: number;/** 顶部 chrome(绝对定位半透明工具栏)实测高度:内容顶部按此让位,详见 mobileMessageListTopPadding。 */@@ -601,6 +614,8 @@ export function MessageRenderer({/** 空列表且本次打开的首同步未完成:渲染「正在同步」占位(延迟显形防闪)而非「暂无消息」。 */syncingWhileEmpty?: boolean;testID?: string;+ /** DEV-only A/B switch; production keeps row recycling disabled until verified. */+ devRecycleItems?: boolean;/** 全屏图片查看器的分享回调(由会话屏落地本地文件后唤起系统分享单)。 */onShareImage?: (media: Extract<MessagePayload, { kind: 'media' }>['media'],@@ -621,6 +636,8 @@ export function MessageRenderer({devExposeList?: (api: {scrollTo: (y: number) => void;getMetrics: () => { contentHeight: number; offsetY: number; viewportHeight: number };+ getWebViewMetrics: typeof getMobileMessageWebViewMetrics;+ getMarkdownMetrics: typeof getMobileMarkdownRenderMetrics;}) => void;} & MessageActions) {const { colors } = useTheme();@@ -701,6 +718,9 @@ export function MessageRenderer({const followVerifyTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);// settle 遮罩:落底两段式期间列表保持 opacity 0,settle 窗口后揭开(规则 7 防跳动)。const [listRevealed, setListRevealed] = useState(false);+ const [visibleMessageKeys, setVisibleMessageKeys] = useState<ReadonlySet<string>>(+ () => new Set(),+ );// 会话切换(scrollResetKey)的 ref 复位必须在渲染期同步完成,不能只靠下方的 reset effect:// effect 在 paint 后异步执行,而重挂的新列表(key={scrollResetKey})的首批 scroll /// onStartReached 回调、以及先于 reset effect 定义的 eligibility effect,都可能带着上个会话的@@ -911,6 +931,8 @@ export function MessageRenderer({devExposeList?.({scrollTo: (y: number) => scrollToOffsetProgrammatically(y, false),getMetrics: () => scrollMetricsRef.current,+ getWebViewMetrics: getMobileMessageWebViewMetrics,+ getMarkdownMetrics: getMobileMarkdownRenderMetrics,});}, [devExposeList, scrollToOffsetProgrammatically]);@@ -1159,11 +1181,22 @@ export function MessageRenderer({viewableItems: ViewToken<MobileMessageRenderItem>[];}) => {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;+ });});const readActuallyVisibleShareableMessageIds = useCallback(async (viewport: ShareableMessageViewport,@@ -1562,6 +1595,7 @@ export function MessageRenderer({setIsAwayFromBottom(false);setFirstVisibleIndex(0);setHasNewMessages(false);+ setVisibleMessageKeys(new Set());}, [scrollResetKey]);// 卸载时清掉在飞的定时器/rAF(闭包引用 listRef,卸载后触发是无害 no-op,// 但不留悬挂句柄)。@@ -1636,13 +1670,17 @@ export function MessageRenderer({requestLoadEarlier();}, [requestLoadEarlier]);- const renderMessageItem = useCallback(({ item }: { item: MobileMessageRenderItem }) => (- <RenderItemView- actions={actions}- focused={item.key === focusedItemKey}- item={item}- />- ), [actions, focusedItemKey]);+ const renderMessageItem = useCallback(({ item }: { item: MobileMessageRenderItem }) => {+ if (__DEV__) recordMobileMessageRenderItem();+ return (+ <RenderItemView+ actions={actions}+ focused={item.key === focusedItemKey}+ isListItem+ item={item}+ />+ );+ }, [actions, focusedItemKey]);// pending_send 的展开态不改变 listData;LegendList 会复用现有行,单靠 renderItem// 闭包更新不足以保证可见行重绘。把选中项显式纳入 extraData,确保轻点气泡后// 「取消 / 编辑 / 插话」操作行立即出现,不依赖滚动触发回收重渲染。@@ -1653,12 +1691,14 @@ export function MessageRenderer({),[pendingSend?.selectedClientId, shareSelectionActive],);+ const recycleItems = __DEV__ && devRecycleItems === true;return (// chat-text-quote:Provider 恒挂载(值可为 null),避免启用态翻转时整棵消息树// 因 Provider 增删而重挂;value 稳定(useMemo),不触发订阅方重渲。<SelectionQuoteContext.Provider value={selectionQuoteContextValue}><View style={styles.messageFrame}>+ <MessageListVisibleKeysContext.Provider value={visibleMessageKeys}><LegendList// 每会话重挂:alignItemsAtEnd + initialScrollAtEnd 让新会话干净地重新锚到底部// (替代手搓的隐藏+rAF 落底 + open-settle)。@@ -1667,7 +1707,7 @@ export function MessageRenderer({extraData={messageListExtraData}keyExtractor={(item) => item.key}renderItem={renderMessageItem}- recycleItems={false}+ recycleItems={recycleItems}estimatedItemSize={MOBILE_MESSAGE_ESTIMATED_ITEM_SIZE}drawDistance={MOBILE_MESSAGE_DRAW_DISTANCE}// 冷开落底不用 initialScrollAtEnd、贴底跟随不用 maintainScrollAtEnd:两者的内部@@ -1716,6 +1756,7 @@ export function MessageRenderer({viewabilityConfig={viewabilityConfigRef.current}onViewableItemsChanged={handleViewableItemsChangedRef.current}/>+ </MessageListVisibleKeysContext.Provider>{previousUserTarget && previousUserButtonTop !== null ? (<MessageListActionButtonaccessibilityLabel={t('message.renderer.previousQuestionJump', { preview: previousUserTarget.preview || t('message.renderer.noPreview') })}@@ -1787,12 +1828,19 @@ 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 会右对齐成用户气泡并挂上@@ -1882,9 +1930,11 @@ const RenderItemView = memo(function RenderItemView({break;}return (- <View style={focused ? styles.focusedItem : undefined} testID={focused ? 'message.focusedItem' : undefined}>- {node}- </View>+ <MessageHeavyContentVisibilityContext.Provider value={heavyContentVisible}>+ <View style={focused ? styles.focusedItem : undefined} testID={focused ? 'message.focusedItem' : undefined}>+ {node}+ </View>+ </MessageHeavyContentVisibilityContext.Provider>);});@@ -3975,6 +4025,7 @@ 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 回复;点分享会换上确定宽度的容器从而完整显示。@@ -3990,7 +4041,25 @@ function MarkdownBody({const settledTextStyle = pinSettledWidth? [styles.messageText, { width: contentWidth }]: styles.messageText;- const blocks = useMemo(() => parseMobileMarkdown(text), [text]);+ const markdownParseRef = useRef<MobileMarkdownParseResult | null>(null);+ const markdownParse = useMemo(() => {+ const startedAt = typeof performance !== 'undefined' && typeof performance.now === 'function'+ ? performance.now()+ : Date.now();+ const result = parseMobileMarkdownIncremental(text, markdownParseRef.current);+ const finishedAt = typeof performance !== 'undefined' && typeof performance.now === 'function'+ ? performance.now()+ : Date.now();+ return {+ result,+ durationMs: Math.max(0, finishedAt - startedAt),+ };+ }, [text]);+ useLayoutEffect(() => {+ markdownParseRef.current = markdownParse.result;+ if (__DEV__) recordMobileMarkdownParse(markdownParse.result, markdownParse.durationMs);+ }, [markdownParse]);+ const blocks = markdownParse.result.blocks;// Android 的 selectable Text 内嵌 View(直连内联图)行为未定义,含这类 inline 的块不开选中。const inlinesSelectable = useCallback((inlines: readonly MobileMarkdownInline[]) => (selectable === true@@ -4151,7 +4220,7 @@ function MarkdownBody({// 盖住整块——WebView 会吞掉触摸事件,不盖层拿不到点击)。return (<View key={block.key} testID="message.mermaidPreviewButton">- <MermaidDiagramWebView source={block.text} testID="message.mermaidDiagram" />+ <MermaidDiagramWebView active={heavyContentVisible} source={block.text} testID="message.mermaidDiagram" />{onOpenPayload ? (<PressableaccessibilityLabel={t('message.renderer.openDiagramDetail')}@@ -4169,6 +4238,7 @@ function MarkdownBody({// 公式在视觉上是正文的一部分,背景与气泡底色一致)。return (<MathFormulaWebView+ active={heavyContentVisible}key={block.key}source={block.text}testID="message.mathFormula"diff --git a/apps/mobile/src/session/SwipeableSessionRow.tsx b/apps/mobile/src/session/SwipeableSessionRow.tsxindex c28d57348c..0be0656758 100644--- a/apps/mobile/src/session/SwipeableSessionRow.tsx+++ b/apps/mobile/src/session/SwipeableSessionRow.tsx@@ -106,6 +106,19 @@ function SwipeableSessionRowInner({// render*Actions 的回调参数是库内部的 translation SharedValue,渲染期存进 ref,// 供松手回调(handleWillOpen)同步读取当前位移做全滑判定。const translationRef = useRef<SharedValue<number> | null>(null);+ const previousRowKeyRef = useRef(rowKey);++ // Project child windowing reuses a small pool of native swipe rows. When a+ // slot starts representing another session, clear the previous gesture+ // position immediately so an open/partially-open row cannot follow the slot+ // onto the new session. The registry cleanup below separately retires the+ // previous session id.+ useEffect(() => {+ if (previousRowKeyRef.current === rowKey) return;+ methodsRef.current?.reset();+ translationRef.current = null;+ previousRowKeyRef.current = rowKey;+ }, [rowKey]);// 行卸载(归档/删除后随数据消失、列表虚拟化回收)时注销;registry 内部只清// 「当前记录仍是自己」的条目,不会误伤已经接管的新行。diff --git a/apps/mobile/src/session/mathWebView.tsx b/apps/mobile/src/session/mathWebView.tsxindex b611589f01..39be1e09b7 100644--- a/apps/mobile/src/session/mathWebView.tsx+++ b/apps/mobile/src/session/mathWebView.tsx@@ -1,7 +1,8 @@-import { useCallback, useMemo, useRef, useState } from 'react';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { StyleSheet, View } from 'react-native';import { WebView, type WebViewMessageEvent } from 'react-native-webview';import { buildMathWebViewHtml } from '@/session/mathWebViewHtml';+import { registerMobileMessageWebView } from '@/session/mobileMessageWebViewMetrics';import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';import { radius } from '@/theme/tokens';@@ -39,31 +40,57 @@ function rememberMeasuredHeight(source: string, height: number): void {* (稳定性约束见上方常量注释,改动前先理解闪动循环的成因)。*/export function MathFormulaWebView({+ active = true,source,testID,}: {+ active?: boolean;source: string;testID?: string;}) {const styles = useThemedStyles(makeStyles);const { colors } = useTheme();+ const renderIdentityRef = useRef({ active, source });+ const renderGenerationRef = useRef(0);+ if (+ renderIdentityRef.current.active !== active+ || renderIdentityRef.current.source !== source+ ) {+ renderIdentityRef.current = { active, source };+ renderGenerationRef.current += 1;+ }+ const renderGeneration = renderGenerationRef.current;const [height, setHeight] = useState(() => measuredHeightCache.get(source) ?? MATH_WEBVIEW_DEFAULT_HEIGHT,);const heightRef = useRef(height);+ const katexHeightAppliedRef = useRef(false);+ useEffect(() => {+ const cachedHeight = measuredHeightCache.get(source);+ const nextHeight = cachedHeight ?? MATH_WEBVIEW_DEFAULT_HEIGHT;+ katexHeightAppliedRef.current = cachedHeight !== undefined;+ heightRef.current = nextHeight;+ setHeight((current) => current === nextHeight ? current : nextHeight);+ }, [source]);+ useEffect(() => {+ if (!active) return undefined;+ return registerMobileMessageWebView('math');+ }, [active]);const html = useMemo(() =>- buildMathWebViewHtml(source, {- background: colors.surface,- textPrimary: colors.textPrimary,- textSecondary: colors.textSecondary,- }),- [colors.surface, colors.textPrimary, colors.textSecondary, source],+ active+ ? buildMathWebViewHtml(source, {+ background: colors.surface,+ textPrimary: colors.textPrimary,+ textSecondary: colors.textSecondary,+ })+ : '',+ [active, colors.surface, colors.textPrimary, colors.textSecondary, source],);// 本次挂载是否已应用过 KaTeX 最终态高度:应用过之后,迟到的过渡态上报// (乱序消息)不允许再把高度拉回去。- const katexHeightAppliedRef = useRef(false);const onMessage = useCallback((event: WebViewMessageEvent) => {+ if (!active || renderGenerationRef.current !== renderGeneration) return;// 消息门:只认页面脚本上报的 math-height 形态,其它一律忽略// (WebView 消息通道是不可信输入,不做任何超出高度设置的行为)。try {@@ -97,10 +124,10 @@ export function MathFormulaWebView({} catch {// 非 JSON 消息不属于本组件协议,忽略。}- }, [source]);+ }, [active, renderGeneration, source]);return (- <View style={styles.container} testID={testID}>- <WebView+ <View style={[styles.container, { height }]} testID={testID}>+ {active ? <WebViewautomaticallyAdjustContentInsets={false}javaScriptEnablednestedScrollEnabled@@ -115,7 +142,7 @@ export function MathFormulaWebView({// backgroundColor transparent → RNW 关掉 WKWebView 的 opaque,首帧// 提交前透出容器的 surface 底色,消掉默认白底闪一下的空白帧(规则 7)。style={[styles.webView, { height }]}- />+ /> : null}</View>);}diff --git a/apps/mobile/src/session/mediaPlayerWebView.tsx b/apps/mobile/src/session/mediaPlayerWebView.tsxindex 2b5ccc32c1..995fc05232 100644--- a/apps/mobile/src/session/mediaPlayerWebView.tsx+++ b/apps/mobile/src/session/mediaPlayerWebView.tsx@@ -8,6 +8,7 @@ import {type MobileMediaPlayerKind,type MobileMediaPlayerStatus,} from '@/session/mediaPlayerWebViewHtml';+import { registerMobileMessageWebView } from '@/session/mobileMessageWebViewMetrics';import { useTheme } from '@/theme';export function RemoteMediaPlayerWebView({@@ -29,25 +30,40 @@ export function RemoteMediaPlayerWebView({}) {const { colors } = useTheme();const webViewRef = useRef<ComponentRef<typeof WebView>>(null);+ const mountedRef = useRef(true);+ useEffect(() => registerMobileMessageWebView('media'), []);const pausePlayback = useCallback(() => {webViewRef.current?.postMessage(buildMediaPlayerWebViewCommand('pause'));}, []);+ const stopPlaybackAndLoading = useCallback(() => {+ pausePlayback();+ webViewRef.current?.stopLoading();+ }, [pausePlayback]);useEffect(() => {const subscription = AppState.addEventListener('change', state => {- if (state !== 'active') pausePlayback();+ if (state !== 'active') stopPlaybackAndLoading();});- return () => subscription.remove();- }, [pausePlayback]);+ return () => {+ subscription.remove();+ stopPlaybackAndLoading();+ };+ }, [stopPlaybackAndLoading]);useEffect(() => {- return pausePlayback;- }, [kind, pausePlayback, url]);+ return stopPlaybackAndLoading;+ }, [kind, stopPlaybackAndLoading, url]);++ useEffect(() => () => {+ mountedRef.current = false;+ stopPlaybackAndLoading();+ }, [stopPlaybackAndLoading]);- const handleMessage = (event: WebViewMessageEvent) => {+ const handleMessage = useCallback((event: WebViewMessageEvent) => {+ if (!mountedRef.current) return;const status = parseMediaPlayerWebViewMessage(event.nativeEvent.data);if (status) onStatusChange?.(status);- };+ }, [onStatusChange]);return (<View style={style} testID={testID}>diff --git a/apps/mobile/src/session/mermaidWebView.tsx b/apps/mobile/src/session/mermaidWebView.tsxindex fcf52fd3a0..f25d80aaf5 100644--- a/apps/mobile/src/session/mermaidWebView.tsx+++ b/apps/mobile/src/session/mermaidWebView.tsx@@ -3,6 +3,7 @@ import { StyleSheet, View } from 'react-native';import { Directory, File, Paths } from 'expo-file-system';import { WebView, type WebViewMessageEvent } from 'react-native-webview';import { buildMermaidWebViewHtml } from '@/session/mermaidWebViewHtml';+import { registerMobileMessageWebView } from '@/session/mobileMessageWebViewMetrics';import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';import { radius } from '@/theme/tokens';@@ -35,7 +36,9 @@ export const MermaidDiagramWebView = forwardRef<MermaidDiagramWebViewHandle, {testID?: string;/** true 时页面允许双指缩放(详情查看用;内联预览保持锁定)。 */zoomable?: boolean;+ active?: boolean;}>(function MermaidDiagramWebView({+ active = true,bare = false,deferSource = false,fill = false,@@ -51,6 +54,11 @@ export const MermaidDiagramWebView = forwardRef<MermaidDiagramWebViewHandle, {const pendingExportsRef = useRef(new Map<string, PendingExport>());const exportSeqRef = useRef(0);+ useEffect(() => {+ if (!active) return undefined;+ return registerMobileMessageWebView('mermaid');+ }, [active]);+useImperativeHandle(ref, () => ({exportPng() {return new Promise<string>((resolve, reject) => {@@ -80,6 +88,7 @@ export const MermaidDiagramWebView = forwardRef<MermaidDiagramWebViewHandle, {}), []);const handleMessage = useCallback((event: WebViewMessageEvent) => {+ if (!active) return;let message: unknown;try {message = JSON.parse(event.nativeEvent.data);@@ -103,7 +112,7 @@ export const MermaidDiagramWebView = forwardRef<MermaidDiagramWebViewHandle, {} else {pending.reject(new Error(typeof error === 'string' && error ? error : 'mermaid export failed'));}- }, []);+ }, [active]);// 卸载时清空信箱:不兜底的话 exportPng promise 永不 settle。useEffect(() => () => {@@ -112,13 +121,14 @@ export const MermaidDiagramWebView = forwardRef<MermaidDiagramWebViewHandle, {pending.reject(new Error('mermaid webview unmounted'));}pendingExportsRef.current.clear();- }, []);+ }, [active, source]);// 构建完整 HTML 非平凡字符串工作——memo 掉,只有源码或主题变化才重建,// 父级无关重渲染不重付。const html = useMemo(- () =>- buildMermaidWebViewHtml(source, {+ () => {+ if (!active) return '';+ return buildMermaidWebViewHtml(source, {surfaceChip: colors.surfaceChip,textPrimary: colors.textPrimary,textSecondary: colors.textSecondary,@@ -126,8 +136,9 @@ export const MermaidDiagramWebView = forwardRef<MermaidDiagramWebViewHandle, {dark: mode === 'dark',deferSource,zoomable,- }),- [source, colors.surfaceChip, colors.textPrimary, colors.textSecondary, colors.textTertiary, mode, deferSource, zoomable],+ });+ },+ [active, source, colors.surfaceChip, colors.textPrimary, colors.textSecondary, colors.textTertiary, mode, deferSource, zoomable],);return (// 尺寸必须钉在容器上(height 或 flex:1)、WebView 用 flex:1 填满:@@ -142,7 +153,7 @@ export const MermaidDiagramWebView = forwardRef<MermaidDiagramWebViewHandle, {]}testID={testID}>- <WebView+ {active ? <WebViewautomaticallyAdjustContentInsets={false}javaScriptEnablednestedScrollEnabled@@ -156,7 +167,7 @@ export const MermaidDiagramWebView = forwardRef<MermaidDiagramWebViewHandle, {baseUrl: 'https://xdt-maker-mobile.local',}}style={styles.webView}- />+ /> : null}</View>);});diff --git a/apps/mobile/src/session/messageMarkdown.ts b/apps/mobile/src/session/messageMarkdown.tsindex 120dbe9ae2..b06c982d87 100644--- a/apps/mobile/src/session/messageMarkdown.ts+++ b/apps/mobile/src/session/messageMarkdown.ts@@ -65,6 +65,35 @@ export interface ParseMobileMarkdownOptions {* 默认关闭:聊天气泡路径不需要,且既有消费方/测试按无此字段的形状断言。*/srcLines?: boolean;+ /** Internal offsets used when parsing an append-only suffix. */+ lineOffset?: number;+ blockIndexOffset?: number;+ charOffset?: number;+ sourceIsNormalized?: boolean;+}++export interface MobileMarkdownBlockRange {+ startLine: number;+ endLineExclusive: number;+}++export interface MobileMarkdownParseCheckpoint {+ /** UTF-16 offset in the normalized source immediately after a safe boundary. */+ charOffset: number;+ /** Global line index at the beginning of the suffix. */+ lineIndex: number;+ /** Number of blocks already emitted at this boundary. */+ blockCount: number;+}++export interface MobileMarkdownParseResult {+ source: string;+ blocks: MobileMarkdownBlock[];+ ranges: MobileMarkdownBlockRange[];+ checkpoints: MobileMarkdownParseCheckpoint[];+ incremental: boolean;+ reusedBlockCount: number;+ parsedSourceUtf16Length: number;}interface ParsedTableBlock {@@ -93,15 +122,64 @@ export function parseMobileMarkdown(input: string,options?: ParseMobileMarkdownOptions,): MobileMarkdownBlock[] {+ return parseMobileMarkdownDocument(input, options).blocks;+}++/**+ * Parse Markdown while retaining enough source metadata to reuse completed+ * blocks when a streaming message only grows at the end.+ *+ * The incremental path is deliberately conservative: it only starts after a+ * parser-safe blank-line boundary. If the source is edited in the middle, or+ * no safe checkpoint exists, callers get the normal full parse result.+ */+export function parseMobileMarkdownDocument(+ input: string,+ options?: ParseMobileMarkdownOptions,+): MobileMarkdownParseResult {const withSrc = options?.srcLines === true;// LaTeX 定界符归一化(\(...\) / \[...\] → $...$ / $$...$$,desktop/mobile 共用// 实现)。srcLines 模式走保行数变体:单行 inline 照常转换(同行替换,不破坏// 「块 srcLine ↔ 源码行」映射),会插行的 display 保持源码——与桌面端// emitSourceLines 门控同一原则。- const source = input.replace(/\r\n/g, '\n');- const normalized = normalizeMathDelimiters(source, { preserveLineCount: withSrc });+ const lineOffset = options?.lineOffset ?? 0;+ const blockIndexOffset = options?.blockIndexOffset ?? 0;+ const charOffset = options?.charOffset ?? 0;+ const source = options?.sourceIsNormalized === true ? input : input.replace(/\r\n/g, '\n');+ const normalized = options?.sourceIsNormalized === true+ ? source+ : normalizeMathDelimiters(source, { preserveLineCount: withSrc });const lines = normalized.split('\n');const blocks: MobileMarkdownBlock[] = [];+ const ranges: MobileMarkdownBlockRange[] = [];+ const checkpoints: MobileMarkdownParseCheckpoint[] = [{+ charOffset,+ lineIndex: lineOffset,+ blockCount: blockIndexOffset,+ }];+ const lineNumber = (index: number) => lineOffset + index;+ const blockNumber = () => blockIndexOffset + blocks.length;+ const lineEndOffsets: number[] = [];+ let sourceOffset = charOffset;+ for (let index = 0; index < lines.length; index += 1) {+ sourceOffset += lines[index].length;+ if (index < lines.length - 1) sourceOffset += 1;+ lineEndOffsets[index] = sourceOffset;+ }+ const lineEndOffset = (index: number): number => (+ lineEndOffsets[Math.max(0, Math.min(index, lineEndOffsets.length - 1))] ?? charOffset+ );+ const pushBlock = (+ block: MobileMarkdownBlock,+ startLine: number,+ endLineExclusive: number,+ ): void => {+ blocks.push(block);+ ranges.push({+ startLine: lineNumber(startLine),+ endLineExclusive: lineNumber(endLineExclusive),+ });+ };let paragraph: string[] = [];let code: CodeFenceState | null = null;// display math 围栏状态($$ 与 $$ 之间;与 code fence 一样跨行收集)。@@ -117,20 +195,29 @@ export function parseMobileMarkdown(const text = paragraph.join('\n').trim();paragraph = [];if (!text) return;- blocks.push({+ pushBlock({type: 'paragraph',- key: `p:${lineIndex}:${blocks.length}`,- ...(withSrc ? { srcLine: paragraphStart } : {}),+ key: `p:${lineNumber(lineIndex)}:${blockNumber()}`,+ ...(withSrc ? { srcLine: lineNumber(paragraphStart) } : {}),inlines: parseMobileMarkdownInlines(text, paragraphStartsInComment),- });+ }, paragraphStart, lineIndex);};for (let index = 0; index < lines.length; index++) {const line = lines[index];if (code) {if (isClosingCodeFence(line, code)) {- blocks.push(buildCodeBlock(code, blocks.length, withSrc));+ pushBlock(+ buildCodeBlock(code, blockNumber(), withSrc, lineOffset),+ code.start,+ index + 1,+ );code = null;+ checkpoints.push({+ charOffset: lineEndOffset(index),+ lineIndex: lineNumber(index + 1),+ blockCount: blockNumber(),+ });} else {code.lines.push(stripCodeFenceIndent(line, code.indent));}@@ -141,7 +228,16 @@ export function parseMobileMarkdown(if (line.trim() === '$$') {const mathText = math.lines.join('\n').trim();if (mathText) {- blocks.push(buildMathBlock(mathText, math.start, blocks.length, withSrc));+ pushBlock(+ buildMathBlock(mathText, math.start, blockNumber(), withSrc, lineOffset),+ math.start,+ index + 1,+ );+ checkpoints.push({+ charOffset: lineEndOffset(index),+ lineIndex: lineNumber(index + 1),+ blockCount: blockNumber(),+ });} else {// 空围栏($$ 与 $$ 之间无内容):没有可渲染的公式,保持原文段落。// 渲染层(math WebView)因此永远不需要「空公式」占位文案,规避@@ -178,7 +274,11 @@ export function parseMobileMarkdown(const singleLineMath = mathTrimmed.match(/^\$\$(.+)\$\$$/);if (singleLineMath && singleLineMath[1].trim()) {flushParagraph(index);- blocks.push(buildMathBlock(singleLineMath[1], index, blocks.length, withSrc));+ pushBlock(+ buildMathBlock(singleLineMath[1], index, blockNumber(), withSrc, lineOffset),+ index,+ index + 1,+ );continue;}if (mathTrimmed === '$$') {@@ -189,6 +289,16 @@ export function parseMobileMarkdown(if (!line.trim()) {flushParagraph(index);+ // The final empty split segment after a trailing newline is not itself+ // a terminated line yet; retaining a checkpoint for it would advance+ // lineIndex one extra step on the next streaming append.+ if (!inHtmlComment && paragraph.length === 0 && index < lines.length - 1) {+ checkpoints.push({+ charOffset: lineEndOffset(index),+ lineIndex: lineNumber(index + 1),+ blockCount: blockNumber(),+ });+ }continue;}@@ -198,13 +308,13 @@ export function parseMobileMarkdown(const heading = line.match(/^(#{1,6})\s+(.+?)(?:\s+#+)?\s*$/);if (heading) {flushParagraph(index);- blocks.push({+ pushBlock({type: 'heading',- key: `h:${index}:${blocks.length}`,- ...(withSrc ? { srcLine: index } : {}),+ key: `h:${lineNumber(index)}:${blockNumber()}`,+ ...(withSrc ? { srcLine: lineNumber(index) } : {}),level: heading[1].length,inlines: parseMobileMarkdownInlines(heading[2].trim(), lineStartsInComment),- });+ }, index, index + 1);continue;}@@ -218,12 +328,12 @@ export function parseMobileMarkdown(index += 1;}index -= 1;- blocks.push({+ pushBlock({type: 'blockquote',- key: `quote:${quoteStart}:${blocks.length}`,- ...(withSrc ? { srcLine: quoteStart } : {}),+ key: `quote:${lineNumber(quoteStart)}:${blockNumber()}`,+ ...(withSrc ? { srcLine: lineNumber(quoteStart) } : {}),inlines: parseMobileMarkdownInlines(quoteLines.join('\n').trim(), lineStartsInComment),- });+ }, quoteStart, index + 1);continue;}@@ -250,17 +360,17 @@ export function parseMobileMarkdown(}const header = parseCellsWithCommentState(table.header, lineStartsInComment);const rows = table.rows.map((row, rowIndex): MobileMarkdownTableRow => ({- key: `tr:${row.lineIndex}:${rowIndex}`,+ key: `tr:${lineNumber(row.lineIndex)}:${rowIndex}`,cells: parseCellsWithCommentState(row.cells, rowStartsInComment.get(row.lineIndex) ?? lineStartsInComment),}));index = table.endIndex;- blocks.push({+ pushBlock({type: 'table',- key: `table:${tableStart}:${blocks.length}`,- ...(withSrc ? { srcLine: tableStart } : {}),+ key: `table:${lineNumber(tableStart)}:${blockNumber()}`,+ ...(withSrc ? { srcLine: lineNumber(tableStart) } : {}),header,rows,- });+ }, tableStart, table.endIndex + 1);continue;}@@ -269,15 +379,15 @@ export function parseMobileMarkdown(flushParagraph(index);const marker = list[2];const task = list[3].match(/^\[([ xX])\]\s+(.+)$/);- blocks.push({+ pushBlock({type: 'list_item',- key: `li:${index}:${blocks.length}`,- ...(withSrc ? { srcLine: index } : {}),+ key: `li:${lineNumber(index)}:${blockNumber()}`,+ ...(withSrc ? { srcLine: lineNumber(index) } : {}),ordered: /^\d/.test(marker),marker,checked: task ? task[1].toLowerCase() === 'x' : undefined,inlines: parseMobileMarkdownInlines(task ? task[2] : list[3], lineStartsInComment),- });+ }, index, index + 1);continue;}@@ -289,7 +399,11 @@ export function parseMobileMarkdown(}if (code) {- blocks.push(buildCodeBlock(code, blocks.length, withSrc));+ pushBlock(+ buildCodeBlock(code, blockNumber(), withSrc, lineOffset),+ code.start,+ lines.length,+ );}if (math) {// 未闭合的 $$ 围栏(streaming 中途):不升级成 math 块——math 块渲染在@@ -302,7 +416,113 @@ export function parseMobileMarkdown(paragraph = ['$$', ...math.lines];}flushParagraph(lines.length);- return blocks;+ return {+ source: normalized,+ blocks,+ ranges,+ checkpoints,+ incremental: false,+ reusedBlockCount: 0,+ parsedSourceUtf16Length: normalized.length,+ };+}++/**+ * Reparse only the suffix of an append-only Markdown stream when a previously+ * parsed document exposes a safe block boundary. Any non-append edit falls+ * back to the regular parser so callers retain the existing semantics.+ */+export function parseMobileMarkdownIncremental(+ input: string,+ previous?: MobileMarkdownParseResult | null,+): MobileMarkdownParseResult {+ const normalizedInput = normalizeMathDelimiters(input.replace(/\r\n/g, '\n'));++ if (!previous || !normalizedInput.startsWith(previous.source)) {+ return parseMobileMarkdownDocument(input);+ }++ // normalizeMathDelimiters can resolve a delimiter that was incomplete in an+ // earlier streaming flush. In that case the normalized prefix itself changes+ // when new text closes `\\(` / `\\[`, so reusing blocks from the old result+ // would preserve stale inline semantics. Complete escaped math pairs are+ // stable and do not need to disable incremental parsing.+ if (hasUnclosedEscapedMathDelimiter(previous.source)+ || hasUnclosedEscapedMathDelimiter(normalizedInput)) {+ return parseMobileMarkdownDocument(input);+ }++ const checkpoint = [...previous.checkpoints]+ .reverse()+ .find((candidate) => (+ candidate.charOffset > 0+ && candidate.charOffset <= previous.source.length+ && candidate.blockCount <= previous.blocks.length+ // A checkpoint at EOF without a trailing newline points into the last+ // line. An append that does not begin with a newline mutates that line,+ // so this checkpoint is no longer safe to reuse (an earlier checkpoint,+ // if any, may still be selected by the reverse scan).+ && !(+ candidate.charOffset === previous.source.length+ && !previous.source.endsWith('\n')+ && normalizedInput[candidate.charOffset] !== '\n'+ )+ ));++ if (!checkpoint) return parseMobileMarkdownDocument(input);++ let suffixCharOffset = checkpoint.charOffset;+ let suffix = normalizedInput.slice(suffixCharOffset);+ // A checkpoint after a line's final character points at the next logical+ // line. If the old source did not already contain that line terminator, the+ // first appended newline is only the separator and must not create an extra+ // empty line in the suffix parser.+ if (+ checkpoint.charOffset === previous.source.length+ && !previous.source.endsWith('\n')+ && suffix.startsWith('\n')+ ) {+ suffix = suffix.slice(1);+ suffixCharOffset += 1;+ }+ const suffixResult = parseMobileMarkdownDocument(+ suffix,+ {+ sourceIsNormalized: true,+ lineOffset: checkpoint.lineIndex,+ blockIndexOffset: checkpoint.blockCount,+ charOffset: suffixCharOffset,+ },+ );++ return {+ source: normalizedInput,+ blocks: [+ ...previous.blocks.slice(0, checkpoint.blockCount),+ ...suffixResult.blocks,+ ],+ ranges: [+ ...previous.ranges.slice(0, checkpoint.blockCount),+ ...suffixResult.ranges,+ ],+ checkpoints: [+ ...previous.checkpoints.filter(+ (candidate) => candidate.charOffset < checkpoint.charOffset,+ ),+ ...suffixResult.checkpoints,+ ],+ incremental: true,+ reusedBlockCount: checkpoint.blockCount,+ parsedSourceUtf16Length: suffixResult.parsedSourceUtf16Length,+ };+}++function hasUnclosedEscapedMathDelimiter(source: string): boolean {+ const openParen = source.lastIndexOf('\\(');+ const closeParen = source.lastIndexOf('\\)');+ const openBracket = source.lastIndexOf('\\[');+ const closeBracket = source.lastIndexOf('\\]');+ return openParen > closeParen || openBracket > closeBracket;}/** display math 块构造:text 存去围栏后的 LaTeX 源码(trim 掉围栏内缘空白)。 */@@ -311,11 +531,12 @@ function buildMathBlock(startLine: number,blockIndex: number,withSrc: boolean,+ lineOffset = 0,): MobileMarkdownBlock {return {type: 'math',- key: `math:${startLine}:${blockIndex}`,- ...(withSrc ? { srcLine: startLine } : {}),+ key: `math:${startLine + lineOffset}:${blockIndex}`,+ ...(withSrc ? { srcLine: startLine + lineOffset } : {}),text: text.trim(),};}@@ -685,21 +906,22 @@ function buildCodeBlock(code: CodeFenceState,blockIndex: number,withSrc = false,+ lineOffset = 0,): MobileMarkdownBlock {const normalized = normalizeCodeFencePayload(code);const text = normalized.lines.join('\n');if (isMermaidLanguage(normalized.language)) {return {type: 'mermaid',- key: `mermaid:${code.start}:${blockIndex}`,- ...(withSrc ? { srcLine: code.start } : {}),+ key: `mermaid:${code.start + lineOffset}:${blockIndex}`,+ ...(withSrc ? { srcLine: code.start + lineOffset } : {}),text,};}return {type: 'code',- key: `code:${code.start}:${blockIndex}`,- ...(withSrc ? { srcLine: code.start } : {}),+ key: `code:${code.start + lineOffset}:${blockIndex}`,+ ...(withSrc ? { srcLine: code.start + lineOffset } : {}),language: normalized.language,text,};diff --git a/apps/mobile/src/session/mobileMarkdownRenderMetrics.ts b/apps/mobile/src/session/mobileMarkdownRenderMetrics.tsnew file mode 100644index 0000000000..81de8100c7--- /dev/null+++ b/apps/mobile/src/session/mobileMarkdownRenderMetrics.ts@@ -0,0 +1,53 @@+import type { MobileMarkdownParseResult } from '@/session/messageMarkdown';++/** DEV/perf-harness counters for Markdown parsing and list item allocation. */+export interface MobileMarkdownRenderMetrics {+ fullParseCount: number;+ incrementalParseCount: number;+ reusedBlockCount: number;+ parsedSourceUtf16Length: number;+ parseDurationMsTotal: number;+ parseDurationMsMax: number;+ renderItemRebuildCount: number;+}++const metrics: MobileMarkdownRenderMetrics = {+ fullParseCount: 0,+ incrementalParseCount: 0,+ reusedBlockCount: 0,+ parsedSourceUtf16Length: 0,+ parseDurationMsTotal: 0,+ parseDurationMsMax: 0,+ renderItemRebuildCount: 0,+};++export function recordMobileMarkdownParse(+ result: Pick<MobileMarkdownParseResult, 'incremental' | 'reusedBlockCount' | 'parsedSourceUtf16Length'>,+ durationMs: number,+): void {+ if (result.incremental) metrics.incrementalParseCount += 1;+ else metrics.fullParseCount += 1;+ metrics.reusedBlockCount += result.reusedBlockCount;+ metrics.parsedSourceUtf16Length += result.parsedSourceUtf16Length;+ metrics.parseDurationMsTotal += Math.max(0, durationMs);+ metrics.parseDurationMsMax = Math.max(metrics.parseDurationMsMax, Math.max(0, durationMs));+}++export function recordMobileMessageRenderItem(): void {+ metrics.renderItemRebuildCount += 1;+}++export function getMobileMarkdownRenderMetrics(): MobileMarkdownRenderMetrics {+ return { ...metrics };+}++/** Test/perf-harness reset; production behavior does not depend on these counters. */+export function resetMobileMarkdownRenderMetrics(): void {+ metrics.fullParseCount = 0;+ metrics.incrementalParseCount = 0;+ metrics.reusedBlockCount = 0;+ metrics.parsedSourceUtf16Length = 0;+ metrics.parseDurationMsTotal = 0;+ metrics.parseDurationMsMax = 0;+ metrics.renderItemRebuildCount = 0;+}diff --git a/apps/mobile/src/session/mobileMessageWebViewMetrics.ts b/apps/mobile/src/session/mobileMessageWebViewMetrics.tsnew file mode 100644index 0000000000..eb00da583d--- /dev/null+++ b/apps/mobile/src/session/mobileMessageWebViewMetrics.ts@@ -0,0 +1,62 @@+export type MobileMessageWebViewKind = 'mermaid' | 'math' | 'media' | 'composer';++export interface MobileMessageWebViewMetrics {+ mounted: number;+ mountedByKind: Record<MobileMessageWebViewKind, number>;+ mounts: number;+ unmounts: number;+}++const mounted = new Map<string, MobileMessageWebViewKind>();+const mountCounts: Record<MobileMessageWebViewKind, number> = {+ mermaid: 0,+ math: 0,+ media: 0,+ composer: 0,+};+const unmountCounts: Record<MobileMessageWebViewKind, number> = {+ mermaid: 0,+ math: 0,+ media: 0,+ composer: 0,+};+let sequence = 0;++/** Register one native WebView while it is mounted and return its idempotent cleanup. */+export function registerMobileMessageWebView(kind: MobileMessageWebViewKind): () => void {+ const id = `${kind}:${++sequence}`;+ mounted.set(id, kind);+ mountCounts[kind] += 1;+ let released = false;+ return () => {+ if (released) return;+ released = true;+ if (mounted.delete(id)) unmountCounts[kind] += 1;+ };+}++export function getMobileMessageWebViewMetrics(): MobileMessageWebViewMetrics {+ const mountedByKind: Record<MobileMessageWebViewKind, number> = {+ mermaid: 0,+ math: 0,+ media: 0,+ composer: 0,+ };+ for (const kind of mounted.values()) mountedByKind[kind] += 1;+ return {+ mounted: mounted.size,+ mountedByKind,+ mounts: Object.values(mountCounts).reduce((total, count) => total + count, 0),+ unmounts: Object.values(unmountCounts).reduce((total, count) => total + count, 0),+ };+}++/** Test-only reset; production callers should only read the snapshot. */+export function resetMobileMessageWebViewMetrics(): void {+ mounted.clear();+ for (const kind of Object.keys(mountCounts) as MobileMessageWebViewKind[]) {+ mountCounts[kind] = 0;+ unmountCounts[kind] = 0;+ }+ sequence = 0;+}diff --git a/apps/mobile/src/session/remoteMediaResolveQueue.ts b/apps/mobile/src/session/remoteMediaResolveQueue.tsindex f3e45d840f..c3c1213e88 100644--- a/apps/mobile/src/session/remoteMediaResolveQueue.ts+++ b/apps/mobile/src/session/remoteMediaResolveQueue.ts@@ -80,6 +80,8 @@ export interface RemoteMediaResolveQueueOptions {maxConcurrent?: number;/** 失败负缓存时长(ms),默认 20s。 */errorTtlMs?: number;+ /** Approximate byte budget for resolved entries retained by this screen. */+ maxCacheBytes?: number;}export interface RemoteMediaRequestOptions {@@ -110,6 +112,7 @@ export interface RemoteMediaResolveQueue {const DEFAULT_MAX_CONCURRENT = 2;const DEFAULT_ERROR_TTL_MS = 20 * 1000;+const DEFAULT_MAX_CACHE_BYTES = 32 * 1024 * 1024;interface QueueEntry {media: RemoteMediaRequest;@@ -135,11 +138,13 @@ export function createRemoteMediaResolveQueue(): RemoteMediaResolveQueue {const maxConcurrent = Math.max(1, options.maxConcurrent ?? DEFAULT_MAX_CONCURRENT);const errorTtlMs = options.errorTtlMs ?? DEFAULT_ERROR_TTL_MS;+ const maxCacheBytes = Math.max(0, options.maxCacheBytes ?? DEFAULT_MAX_CACHE_BYTES);const isFresh = deps.isFresh ?? ((media, now) => isResolvedRemoteMediaFresh(media, now));const now = deps.now ?? (() => Date.now());// 以下四个容器一律以 requestKeyOf 产出的**缓存键**为键(缩略图带前缀,原图 = 裸 url)。const cache = new Map<string, MobileResolvedRemoteMedia>();+ let cacheBytes = 0;const errorCache = new Map<string, { message: string; until: number }>();/** key → entry;排队与 in-flight 的都在这里,靠 entry.inFlight 区分。 */const entries = new Map<string, QueueEntry>();@@ -149,6 +154,51 @@ export function createRemoteMediaResolveQueue(/** releaseAll 已执行:此后完成的 in-flight 结果改走 onOrphanResolved,不回填缓存。 */let released = false;+ function estimateCacheBytes(media: MobileResolvedRemoteMedia): number {+ const inlineBytes = media.inlineBase64 ? media.inlineBase64.length * 2 : 0;+ const metadataBytes = 256 + media.url.length * 2 + media.ossKey.length * 2;+ const declaredBytes = Number.isFinite(media.size) && media.size > 0+ ? Math.min(media.size, 8 * 1024 * 1024)+ : 0;+ return Math.max(metadataBytes + inlineBytes, declaredBytes);+ }++ function deleteCacheEntry(key: string): MobileResolvedRemoteMedia | null {+ const current = cache.get(key);+ if (!current) return null;+ cache.delete(key);+ cacheBytes = Math.max(0, cacheBytes - estimateCacheBytes(current));+ return current;+ }++ function setCacheEntry(key: string, media: MobileResolvedRemoteMedia): MobileResolvedRemoteMedia[] {+ const evicted: MobileResolvedRemoteMedia[] = [];+ deleteCacheEntry(key);+ cache.set(key, media);+ cacheBytes += estimateCacheBytes(media);+ // Keep the just-resolved item when it alone exceeds the budget: callers+ // are about to receive it, and deleting its OSS object would invalidate the+ // result. The next insertion can evict it normally once another entry exists.+ while (cacheBytes > maxCacheBytes && cache.size > 1) {+ const oldest = cache.keys().next().value as string | undefined;+ if (oldest === undefined) break;+ const removed = deleteCacheEntry(oldest);+ if (removed) evicted.push(removed);+ }+ return evicted;+ }++ function notifyEvicted(entriesToRelease: readonly MobileResolvedRemoteMedia[]): void {+ for (const media of entriesToRelease) {+ deps.onOrphanResolved?.(media);+ }+ }++ function touchCacheEntry(key: string, media: MobileResolvedRemoteMedia): void {+ cache.delete(key);+ cache.set(key, media);+ }+function detachWaiter(entry: QueueEntry, waiter: QueueEntry['waiters'][number]): void {if (waiter.signal && waiter.onAbort) {waiter.signal.removeEventListener('abort', waiter.onAbort);@@ -184,7 +234,7 @@ export function createRemoteMediaResolveQueue(const current = cache.get(key);if (!current) return;if (current.ossKey !== local.ossKey) return;- cache.set(key, local);+ notifyEvicted(setCacheEntry(key, local));}function pump(): void {@@ -217,7 +267,7 @@ export function createRemoteMediaResolveQueue(if (prev && prev.ossKey && prev.ossKey !== resolved.ossKey) {deps.onOrphanResolved?.(prev);}- cache.set(key, resolved);+ notifyEvicted(setCacheEntry(key, resolved));errorCache.delete(key);const followUp = entry.forcedFollowUp;entry.forcedFollowUp = undefined;@@ -248,7 +298,7 @@ export function createRemoteMediaResolveQueue(// 重新走全新取件。const prev = cache.get(key);if (prev) {- cache.delete(key);+ deleteCacheEntry(key);if (prev.ossKey) deps.onOrphanResolved?.(prev);}}@@ -269,7 +319,10 @@ export function createRemoteMediaResolveQueue(// key 是队列/缓存键(缩略图带前缀,原图 = 裸 url),entry.media 才是原始请求。const key = requestKeyOf(media);const cached = cache.get(key);- if (cached && !opts.forceRefresh && isFresh(cached, now())) return Promise.resolve(cached);+ if (cached && !opts.forceRefresh && isFresh(cached, now())) {+ touchCacheEntry(key, cached);+ return Promise.resolve(cached);+ }if (opts.cachedOnly) {// 只读缓存模式:未命中直接拒绝,不入队、不碰负缓存(不污染同键的真实取件)。return Promise.reject(new Error(i18n.t('composer.attachments.mediaCacheMiss')));@@ -346,11 +399,12 @@ export function createRemoteMediaResolveQueue(request,peekFresh(url) {const cached = cache.get(url);- return cached && isFresh(cached, now()) ? cached : null;+ if (!cached || !isFresh(cached, now())) return null;+ touchCacheEntry(url, cached);+ return cached;},evict(url) {- const cached = cache.get(url) ?? null;- cache.delete(url);+ const cached = deleteCacheEntry(url);errorCache.delete(url);return cached;},@@ -366,6 +420,7 @@ export function createRemoteMediaResolveQueue(}const all = [...cache.values()];cache.clear();+ cacheBytes = 0;errorCache.clear();return all;},diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.tsindex 48c210008e..cf78703068 100644--- a/apps/mobile/src/session/remoteSessionStore.ts+++ b/apps/mobile/src/session/remoteSessionStore.ts@@ -578,7 +578,8 @@ const GENERATED_FALLBACK_MIN_PREFIX_LENGTH = 12;const TEXT_DELTA_BATCH_INTERVAL_MS = 32;const DEVICE_LINK_TRUNCATED_FLAG = '__deviceLinkTruncated';const pendingTextDeltaBatches = new Map<string, {- text: string;+ /** Keep deltas as chunks; joining once per flush avoids O(n²) string copies. */+ chunks: string[];persistId?: string;deviceId?: string;agentMeta: Record<string, unknown> | null;@@ -654,14 +655,42 @@ function touchSessionAccess(sessionId: string): void {sessionLastAccessOrder.set(sessionId, ++nextSessionAccessOrder);}+/**+ * Budget accounting runs on every regular-session sweep. Do not serialize the+ * whole payload here: streaming rows replace their object on every flush, so a+ * stringify would allocate a second copy of every large tool result and make+ * the accounting pass itself a noticeable GC source. This intentionally+ * conservative walk counts primitive payloads and container overhead without+ * materializing a large temporary string.+ */+function estimateValueBytes(value: unknown, depth = 0, seen = new Set<object>()): number {+ if (value == null) return 0;+ if (typeof value === 'string') return value.length * 2;+ if (typeof value === 'number' || typeof value === 'boolean') return 16;+ if (typeof value !== 'object') return 8;+ if (seen.has(value)) return 0;+ seen.add(value);+ if (depth >= 3) return 64;+ if (Array.isArray(value)) {+ let bytes = 24;+ for (const item of value) bytes += 8 + estimateValueBytes(item, depth + 1, seen);+ return bytes;+ }+ let bytes = 32;+ for (const [key, item] of Object.entries(value)) {+ bytes += 16 + key.length * 2 + estimateValueBytes(item, depth + 1, seen);+ }+ return bytes;+}+function estimateMessageBytes(message: RemoteMessage): number {const cached = messageBytesEstimates.get(message);if (cached !== undefined) return cached;let bytes = MESSAGE_STRUCTURAL_BYTES_ESTIMATE;if (typeof message.content === 'string') bytes += message.content.length * 2;- else if (message.content != null) bytes += safeStableStringify(message.content).length * 2;- if (message.agentMeta) bytes += safeStableStringify(message.agentMeta).length * 2;- if (message.systemCardData) bytes += safeStableStringify(message.systemCardData).length * 2;+ else if (message.content != null) bytes += estimateValueBytes(message.content);+ if (message.agentMeta) bytes += estimateValueBytes(message.agentMeta);+ if (message.systemCardData) bytes += estimateValueBytes(message.systemCardData);messageBytesEstimates.set(message, bytes);return bytes;}@@ -894,6 +923,10 @@ function releaseSessionDetailProjections(sessionId: string): boolean {let changed = livePlanSnapshots.delete(sessionId);changed = sessionTaskUpdates.delete(sessionId) || changed;changed = sessionParkedTaskUpdates.delete(sessionId) || changed;+ // Goal status is queried when the context sheet opens; retaining a full+ // status payload for every backgrounded task only keeps detail-only data+ // alive and can show stale state after a long absence.+ changed = sessionGoalStatus.delete(sessionId) || changed;changed = inputProjections.delete(sessionId) || changed;// 即使投影已经为空也要抬升 authority:离场/LRU 前启动的慢查询不能在下一次// 打开同一任务后把旧 pending queue 或 continuation owner 写回来。@@ -973,6 +1006,12 @@ function applyMessageWriteRetention(sessionId: string): void {let mergedSessions: RemoteSession[] = [];let messageVersion = 0;let storeVersion = 0;+// A single remote snapshot often updates both the session shard and its+// activity projection. Keep the writes synchronous, but notify subscribers+// once after the snapshot is complete so the home screen does not render the+// same device twice in one turn.+let emitBatchDepth = 0;+let emitBatchPending = false;type LiveRowCreatedAtAnchor = {createdAt: string | undefined;@@ -1059,11 +1098,32 @@ let conversationSearchDeviceModels: readonly {state: string;}[] = [];-function emit(): void {+function emitNow(): void {storeVersion += 1;for (const sub of subs) sub();}+function emit(): void {+ if (emitBatchDepth > 0) {+ emitBatchPending = true;+ return;+ }+ emitNow();+}++function batch<T>(work: () => T): T {+ emitBatchDepth += 1;+ try {+ return work();+ } finally {+ emitBatchDepth -= 1;+ if (emitBatchDepth === 0 && emitBatchPending) {+ emitBatchPending = false;+ emitNow();+ }+ }+}+function bumpInputProjectionAuthorityEpoch(sessionId: string): number {const epoch = ++nextInputProjectionAuthorityEpoch;inputProjectionAuthorityEpochs.set(sessionId, epoch);@@ -2019,7 +2079,11 @@ function streamingClientIdFor(sessionId: string, persistId: string | undefined):function upsertMessage(sessionId: string,message: RemoteMessage,- options: { retirePendingAssistantIdentityOnEqual?: boolean } = {},+ options: {+ retirePendingAssistantIdentityOnEqual?: boolean;+ /** Streaming replacement preserves the already sorted message order. */+ preserveOrderOnReplace?: boolean;+ } = {},): boolean {const existing = messages.get(sessionId) ?? [];const index = existing.findIndex((item) => messageIdentityMatches(item, message));@@ -2076,7 +2140,13 @@ function upsertMessage(}const next = existing.slice();next[index] = replacement;- messages.set(sessionId, normalizeMessages(next));+ // A live delta only changes content/metadata; sorting the whole window on+ // every 32 ms flush needlessly allocates and scans all rows. Callers that+ // replace an authoritative row keep the historical normalization path.+ messages.set(+ sessionId,+ options.preserveOrderOnReplace ? next : normalizeMessages(next),+ );applyMessageWriteRetention(sessionId);if (message.role === 'assistant') {forgetPendingLiveAssistantMessageIdentity(@@ -2283,7 +2353,7 @@ function applyRemoteTextEvent(new Date().toISOString(),hostCreatedAtAnchor?.createdAt,),- });+ }, { preserveOrderOnReplace: true });if (resetsTransportAssembly && !changed) {forgetPendingLiveAssistantMessageIdentity(sessionId,@@ -2347,14 +2417,19 @@ function enqueueRemoteTextDelta(}const current = pendingTextDeltaBatches.get(sessionId);const incomingMeta = isRecord(event.agentMeta) ? event.agentMeta : null;- pendingTextDeltaBatches.set(sessionId, {- text: `${current?.text ?? ''}${text}`,- persistId: current?.persistId ?? persistId,- deviceId: current?.deviceId ?? deviceId,- agentMeta: incomingMeta- ? { ...(current?.agentMeta ?? {}), ...incomingMeta }- : current?.agentMeta ?? null,- });+ if (current) {+ current.chunks.push(text);+ if (incomingMeta) current.agentMeta = { ...(current.agentMeta ?? {}), ...incomingMeta };+ if (!current.persistId) current.persistId = persistId;+ if (current.deviceId === undefined) current.deviceId = deviceId;+ } else {+ pendingTextDeltaBatches.set(sessionId, {+ chunks: [text],+ persistId,+ deviceId,+ agentMeta: incomingMeta,+ });+ }scheduleTextDeltaFlush();return changed;}@@ -2368,7 +2443,7 @@ function flushPendingTextDelta(sessionId: string): boolean {sessionId,{type: 'text',- data: { text: batch.text, isFinal: false },+ data: { text: batch.chunks.join(''), isFinal: false },...(batch.agentMeta ? { agentMeta: batch.agentMeta } : {}),},batch.persistId,@@ -2532,6 +2607,11 @@ function recallParkedTaskUpdates(}export const remoteSessionStore = {+ /** Coalesce notifications for one logically atomic remote snapshot. */+ batch<T>(work: () => T): T {+ return batch(work);+ },+/*** 新建任务第一帧标题预览。只盖哨兵,权威标题一旦离开哨兵就让位。* 失败撤回走 {@link clearPendingTitlePreview}。