Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

perf(mobile): 优化长任务流式渲染与首页订阅

DavidShen9042aceca9a7
diff --git a/apps/mobile/app/devices/index.tsx b/apps/mobile/app/devices/index.tsx
index c32ece8f97..d1ddcfe1e0 100644
--- a/apps/mobile/app/devices/index.tsx
+++ b/apps/mobile/app/devices/index.tsx
@@ -202,9 +202,10 @@ import {
import {
RemoteSessionStoreSubscriptionGate,
remoteSessionStore,
+ useRemoteHomeStatusVersion,
useRemoteMessageVersion,
+ useRemoteSessionMessagePreview,
useRemoteSessions,
- useRemoteSessionStoreVersion,
useSessionRunning,
} from '@/session/remoteSessionStore';
import { dataPropsEqual, mapContentEqual } from '@/utils/valueEquality';
@@ -366,8 +367,6 @@ function HomeScreenContent() {
} = useDeviceLink();
const revokedDevices = useRevokedDevices();
const sessions = useRemoteSessions();
- const messageVersion = useRemoteMessageVersion();
- const storeVersion = useRemoteSessionStoreVersion();
const syncInFlightRef = useRef<Promise<void> | null>(null);
const syncQueuedRef = useRef<{ visible?: boolean } | null>(null);
const loadHomeRef = useRef<(options?: { visible?: boolean }) => Promise<void>>(async () => undefined);
@@ -1557,6 +1556,9 @@ function HomeScreenContent() {
projects: searchProjects,
});
const searchQuery = indexedSearch.query;
+ const normalizedSearchQuery = searchQuery.trim();
+ const messageSearchVersion = useRemoteMessageVersion(normalizedSearchQuery.length > 0);
+ const homeStatusVersion = useRemoteHomeStatusVersion();
const searchFilterA11y = t('devices.list.search.filterAria', {
agent: t(`devices.list.search.filter.agent.${indexedSearch.agentFilter}`),
lastActivity: t(`devices.list.search.filter.lastActivity.${indexedSearch.lastActivityFilter}`),
@@ -1656,11 +1658,11 @@ function HomeScreenContent() {
: null,
[deviceModels, revokedTipDeviceId, t],
);
- // 三个派生索引的依赖挂在全局 messageVersion / storeVersion 上,桌面端活跃期逐 emit
- // 重建出内容相同的新 Map——若不做内容稳定化,home → sections → 全列表行整链每次
- // emit 都重建(2026-07-18 重渲染风暴 trace 实锤)。useStableValue 在内容未变时保留
- // 旧引用,下游 useMemo 依赖即可短路;内容真变(某会话预览/交互数/活动态变化)照常穿透。
+ // 消息预览仅在搜索时构建全局索引;普通首页由行级 selector 消费。pending/live/running
+ // 共用低频 homeStatusVersion,普通文本 token 不再重建这些 Map 或 home → sections 链。
const messagePreviewIndexRaw = useMemo(() => {
+ // 普通首页的预览由可见行按 session 订阅。只有搜索需要跨全部任务建立消息索引。
+ if (!normalizedSearchQuery) return new Map<string, string>();
const next = new Map<string, string>();
const activeIds = new Set<string>();
for (const session of sessions) {
@@ -1679,7 +1681,7 @@ function HomeScreenContent() {
if (!activeIds.has(sessionId)) homePreviewCacheRef.current.delete(sessionId);
}
return next;
- }, [messageVersion, sessions]);
+ }, [messageSearchVersion, normalizedSearchQuery, sessions]);
const messagePreviewIndex = useStableValue(messagePreviewIndexRaw, mapContentEqual);
const pendingInteractionIndexRaw = useMemo(() => {
const next = new Map<string, number>();
@@ -1696,7 +1698,7 @@ function HomeScreenContent() {
if (!activeIds.has(sessionId)) homePendingCacheRef.current.delete(sessionId);
}
return next;
- }, [sessions, storeVersion]);
+ }, [homeStatusVersion, sessions]);
const pendingInteractionIndex = useStableValue(pendingInteractionIndexRaw, mapContentEqual);
const liveActivityIndexRaw = useMemo(() => {
const next = new Map<string, RemoteSessionLiveActivity>();
@@ -1717,7 +1719,7 @@ function HomeScreenContent() {
}
homeLiveActivityIndexRef.current = next;
return next;
- }, [sessions, storeVersion]);
+ }, [homeStatusVersion, sessions]);
const liveActivityIndex = useStableValue(liveActivityIndexRaw, mapContentEqual);
// 列表隐藏 Orca worker 子会话(本期不支持进 worker 聊天);Lead + 普通会话保留。仅 mobile 侧过滤。
const homeSessions = useMemo(() => excludeOrcaWorkerSessions(sessions), [sessions]);
@@ -1745,7 +1747,7 @@ function HomeScreenContent() {
if (scheduleIndex.get(session.id)?.running) ids.add(session.id);
}
return ids;
- }, [homeSessions, liveActivityIndex, scheduleIndex, storeVersion]);
+ }, [homeSessions, homeStatusVersion, liveActivityIndex, scheduleIndex]);
const homePriorityItems = useMemo(
() => [...home.pinned, ...home.chats, ...home.projects.flatMap((project) => project.sessions)],
[home],
@@ -3425,10 +3427,9 @@ function ProjectRow({
const { colors } = useTheme();
const { t } = useTranslation();
// 折叠豁免要命令式读会话运行态,而派生链稳定化后本组件不再逐 emit 重渲染(cell 经
- // PureComponent bail)——以 storeVersion 订阅兜底感知运行态变化,与 AutomationGroup-
+ // PureComponent bail)——以低频首页状态版本兜底感知运行态变化,与 AutomationGroup-
// Children 同款(否则折叠线以下转入 running 的会话不会被豁免展开,review P1)。
- useRemoteSessionStoreVersion();
- const storeVersion = remoteSessionStore.getStoreVersion();
+ const homeStatusVersion = useRemoteHomeStatusVersion();
// 与桌面侧栏项目组同一套折叠策略:前 N 条之外豁免最近 24h 活动 / 需关注 / 运行中的条目
// (豁免语义见共享层 getRemoteSessionPreviewCollapse 注释)。
// 自动化折叠后 sessions 是"行"(组行代表多条会话):按钮显隐看隐藏行数(hiddenCount),
@@ -3448,7 +3449,7 @@ function ProjectRow({
const estimatedChildHeights = useMemo(() => {
const expandedKeys = new Set(expandedAutomationGroups);
return visibleSessions.map((item) => estimateHomeProjectChildHeight(item, expandedKeys));
- }, [expandedAutomationGroups, visibleSessions, storeVersion]);
+ }, [expandedAutomationGroups, homeStatusVersion, visibleSessions]);
const estimatedChildOffsets = useMemo(
() => buildHomeProjectChildOffsets(estimatedChildHeights),
[estimatedChildHeights],
@@ -3891,6 +3892,9 @@ function HomeSessionRowInner({
const { t } = useTranslation();
// 运行态走订阅而非命令式读取:行已 memo 化,父层不再逐 emit 重渲染,命令式读取会 stale。
const sessionIsRunning = useSessionRunning(item.session.id);
+ // 已加载消息的预览按 session 订阅。普通流式 token 只让对应的可见行更新,首页根层、
+ // sections 和其它任务行都保持原引用。
+ const loadedMessagePreview = useRemoteSessionMessagePreview(item.session.id);
const running = sessionIsRunning || !!item.scheduleInfo?.running;
// attention 合并 main 的 #368:liveActivity.attention 也点亮关注态(组行直开 primary 的判定沿用)。
const attention = item.pendingInteractionCount > 0
@@ -3924,7 +3928,12 @@ function HomeSessionRowInner({
// 组行的预览位改为任务态摘要(需关注数 / 执行中 / 共 N 次运行),对齐桌面版组头 meta。
const preview = group
? automationGroupPreview(item, group.sessionCount, t)
- : buildRemoteSessionCardPreview(item, { running });
+ : buildRemoteSessionCardPreview(
+ loadedMessagePreview === undefined || loadedMessagePreview === item.messagePreview
+ ? item
+ : { ...item, messagePreview: loadedMessagePreview },
+ { running },
+ );
// 零消息会话没有摘要。此时不要保留双行列表的空白第二行;但定时任务与置顶
// 标记仍占用右下状态槽,因此继续使用双行布局。
const showPreviewLine = !!preview?.trim() || showSchedule || showPinned;
@@ -4142,8 +4151,8 @@ function AutomationGroupChildren({
const { colors } = useTheme();
const { t } = useTranslation();
// 折叠豁免要命令式读子会话运行态,而父行(HomeSessionRow)已 memo 化、不再逐 emit
- // 重渲染——这里以 storeVersion 订阅兜底感知运行态变化。仅组展开时挂载,量小成本可忽略。
- useRemoteSessionStoreVersion();
+ // 重渲染——只订阅首页状态版本感知运行态变化,普通文本 token 不再惊动整组。
+ useRemoteHomeStatusVersion();
// 与项目组同一套折叠豁免(24h 活动 / 需关注 / 运行中),见共享层注释。
const { visibleItems, hiddenCount } = getRemoteSessionPreviewCollapse(group.items, {
limit: PROJECT_PREVIEW_LIMIT,
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 48ac02a140..15ce5dfc61 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -454,7 +454,8 @@ import {
hasOlderMessagesByServerCount,
listMessagesWithPayloadRetry,
oldestMessageCursor,
- projectLoadedMessageWindow,
+ projectLoadedMessageWindowIncrementally,
+ type LoadedMessageWindowProjection,
shouldRefreshLatestMessageWindowOnReopen,
shouldKeepOlderMessagesAffordance,
} from '@/session/messagePaging';
@@ -983,6 +984,11 @@ export default function SessionScreen() {
const maker = useMobileMakerTransport(deviceId);
const sessions = useRemoteSessions();
const messages = useSessionMessages(sessionId, deviceId);
+ const messageStructureToken = remoteSessionStore.getSessionMessageStructureToken(sessionId);
+ const messageStructureChangedIndexes = remoteSessionStore
+ .getSessionMessageStructureChangedIndexes(sessionId);
+ const latestMessagesRef = useRef(messages);
+ latestMessagesRef.current = messages;
const sessionRetention = useSyncExternalStore(
remoteSessionStore.subscribe,
() => remoteSessionStore.getSessionRetention(sessionId),
@@ -2262,8 +2268,8 @@ export default function SessionScreen() {
&& !inputProjection.queuePaused
&& !inputProjection.queueAbortPending;
const currentTurnStreaming = useMemo(
- () => currentTurnHasStreamingAssistant(messages),
- [messages],
+ () => currentTurnHasStreamingAssistant(latestMessagesRef.current),
+ [messageStructureToken],
);
const canStopCurrentRun = (remoteSessionRunning || currentTurnStreaming)
&& !inputProjection.queueAbortPending;
@@ -4297,11 +4303,12 @@ export default function SessionScreen() {
// shouldKeepOlderMessagesAffordance / hasOlderMessagesAfterReopen 校正(:806/:846)。_count 未知不凭空点亮。
useEffect(() => {
if (isScheduleDetail) return;
- if (lastSyncedAt !== null || hasOlderMessages || messages.length === 0) return;
- if (hasOlderMessagesByServerCount(currentSession?._count?.messages, messages)) {
+ const currentMessages = latestMessagesRef.current;
+ if (lastSyncedAt !== null || hasOlderMessages || currentMessages.length === 0) return;
+ if (hasOlderMessagesByServerCount(currentSession?._count?.messages, currentMessages)) {
setHasOlderMessages(true);
}
- }, [currentSession?._count?.messages, hasOlderMessages, isScheduleDetail, lastSyncedAt, messages]);
+ }, [currentSession?._count?.messages, hasOlderMessages, isScheduleDetail, lastSyncedAt, messageStructureToken]);
// 在线时按 connectionEpoch 去重:每个连接 epoch 只 resync 一次。首开同步由上面的 mount effect 负责
// (此处 epoch == 初值 → skip);仅在 epoch 变化(真正重连 / 回前台 connectNow→online)时再 resync,
@@ -4460,11 +4467,11 @@ export default function SessionScreen() {
// 同帧正式气泡已在流里,视觉上原位变实心,无跳变)。
const queueHiddenClientIds = useMemo(() => {
const ids = new Set<string>();
- for (const message of messages) {
+ for (const message of latestMessagesRef.current) {
if (message.clientId) ids.add(message.clientId);
}
return ids;
- }, [messages]);
+ }, [messageStructureToken]);
// 落定中条目跟踪(见 settlingQueueItems 声明处注释):
// 1) pendingQueue diff——只把「像被派发」的消失当作落定中:drain 恒从队首连续
// 消费,steer 按 steeringQueueClientIds 标记;两者都不沾的中段消失是远端删除
@@ -4612,19 +4619,43 @@ export default function SessionScreen() {
// (worker)会话不渲染 banner,错误卡必须留在消息流(同一 review P2)。
const errorTailClientId = useMemo(() => {
if (collaborationReadOnlyReason) return null;
- const id = findErrorTailClientId(messages);
+ const id = findErrorTailClientId(latestMessagesRef.current);
return id && !dismissedTailErrorClientIds.has(id) ? id : null;
- }, [collaborationReadOnlyReason, messages, dismissedTailErrorClientIds]);
+ }, [collaborationReadOnlyReason, dismissedTailErrorClientIds, messageStructureToken]);
+ const projectedMessageWindowRef = useRef<{
+ projection: LoadedMessageWindowProjection;
+ sessionId: string;
+ } | null>(null);
+ const projectedMessageWindow = useMemo(() => {
+ const projection = projectLoadedMessageWindowIncrementally({
+ changedIndexes: messageStructureChangedIndexes,
+ messages,
+ previous: projectedMessageWindowRef.current?.sessionId === sessionId
+ ? projectedMessageWindowRef.current.projection
+ : null,
+ structureToken: messageStructureToken,
+ });
+ projectedMessageWindowRef.current = { projection, sessionId };
+ return projection;
+ }, [messageStructureChangedIndexes, messageStructureToken, messages, sessionId]);
+ const projectedMessages = projectedMessageWindow.projected;
+ const projectedMessageStructureChangedIndexes = projectedMessageWindow.changedIndexes;
+ const oldestLoadedMessageCursor = useMemo(
+ () => oldestMessageCursor(latestMessagesRef.current),
+ [messageStructureToken],
+ );
const previousRenderItemsRef = useRef<{
sessionId: string;
items: readonly MobileMessageRenderItem[];
} | null>(null);
const streamingRenderPrefixRef = useRef<MobileStreamingRenderPrefixCache | null>(null);
- const renderItems = useMemo(
+ const renderWindow = useMemo(
() => {
const builtWindow = buildMobileStreamingRenderWindow({
cacheKey: i18nInstance.language,
- messages: projectLoadedMessageWindow(messages),
+ messages: projectedMessages,
+ messageStructureChangedIndexes: projectedMessageStructureChangedIndexes,
+ messageStructureToken,
options: {
autoResumePending: inputProjection.autoResumePending,
isSessionStreaming,
@@ -4650,10 +4681,28 @@ export default function SessionScreen() {
const previous = previousRenderItemsRef.current?.sessionId === sessionId
? previousRenderItemsRef.current.items
: [];
- const reconciled = reconcileMobileMessageRenderItems(previous, items);
- return reconciled;
+ const stablePrefixItemCount = forkOrigin || errorTailClientId
+ ? 0
+ : builtWindow.stablePrefixItemCount;
+ const reconciled = reconcileMobileMessageRenderItems(
+ previous,
+ items,
+ stablePrefixItemCount,
+ );
+ return {
+ diffCount: errorTailClientId
+ ? countMobileRenderItemDiffs(reconciled)
+ : builtWindow.diffCount,
+ items: reconciled,
+ stablePrefixItemCount,
+ };
},
- [errorTailClientId, forkOrigin, i18nInstance.language, inputProjection.autoResumePending, isSessionStreaming, makerTurnRunning, messages, sessionId, taskUpdates],
+ [errorTailClientId, forkOrigin, i18nInstance.language, inputProjection.autoResumePending, isSessionStreaming, makerTurnRunning, messageStructureToken, projectedMessages, projectedMessageStructureChangedIndexes, sessionId, taskUpdates],
+ );
+ const renderItems = renderWindow.items;
+ const renderItemsStructureKey = useMemo(
+ () => ({}),
+ [errorTailClientId, forkOrigin, i18nInstance.language, inputProjection.autoResumePending, isSessionStreaming, makerTurnRunning, messageStructureToken, sessionId, taskUpdates],
);
// 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.
@@ -4663,13 +4712,12 @@ export default function SessionScreen() {
// 后台静默刷新:仅在首次加载、还没有任何内容(messages 为空)时显示"正在同步";已有内容
// (重开已看过的会话,messages 还在内存)时后台对账一律静默,不再弹同步提示打扰用户。
const showSyncingIndicator = loading && messages.length === 0;
- const diffCount = useMemo(
- () => countMobileRenderItemDiffs(renderItems),
- [renderItems],
- );
+ const diffCount = renderWindow.diffCount;
const searchHits = useMemo(
- () => findMobileMessageSearchHits(renderItems, searchQuery),
- [renderItems, searchQuery],
+ () => searchOpen && searchQuery.trim()
+ ? findMobileMessageSearchHits(renderItems, searchQuery)
+ : [],
+ [renderItems, searchOpen, searchQuery],
);
const activeSearchHit = activeSearchIndex >= 0 ? searchHits[activeSearchIndex] ?? null : null;
const routeFocusedItemKey = useMemo(
@@ -4900,7 +4948,7 @@ export default function SessionScreen() {
if (!deviceId || !sessionId || loadingEarlier || !hasOlderMessages) return;
const messageAuthority = remoteSessionStore.captureSessionMessageAuthority(sessionId);
if (!remoteSessionStore.isSessionMessageAuthorityCurrent(messageAuthority)) return;
- const before = oldestMessageCursor(messages);
+ const before = oldestLoadedMessageCursor;
if (!before) {
setHasOlderMessages(false);
return;
@@ -4929,7 +4977,7 @@ export default function SessionScreen() {
} finally {
setLoadingEarlier(false);
}
- }, [abandonInFlightBackfill, deviceId, hasOlderMessages, isScheduleDetail, loadingEarlier, maker, messages, sessionId]);
+ }, [abandonInFlightBackfill, deviceId, hasOlderMessages, isScheduleDetail, loadingEarlier, maker, oldestLoadedMessageCursor, sessionId]);
/**
* 历史窗口空洞的自动补齐(见 `historyWindowGap.ts` 的文件头)。
@@ -5021,7 +5069,7 @@ export default function SessionScreen() {
// 发出上百次 limit=1 探测。
if (gapState.backfilled.size >= HISTORY_BACKFILL_MAX_GAPS_PER_VISIT) return;
if (consideredKeys.size >= HISTORY_GAP_MAX_CONSIDERED_PER_VISIT) return;
- const gap = findHistoryWindowGap(messages, consideredKeys);
+ const gap = findHistoryWindowGap(latestMessagesRef.current, consideredKeys);
if (!gap) return;
const gapKey = historyWindowGapKey(gap);
const sessionIdAtStart = sessionId;
@@ -5087,7 +5135,7 @@ export default function SessionScreen() {
loading,
loadingEarlier,
maker,
- messages,
+ messageStructureToken,
readAckSyncedKey,
sessionId,
]);
@@ -6101,6 +6149,10 @@ export default function SessionScreen() {
() => (pendingSendItems.length === 0 ? renderItems : [...renderItems, ...pendingSendItems]),
[pendingSendItems, renderItems],
);
+ const messageListStructureKey = useMemo(
+ () => ({}),
+ [pendingSendItems, renderItemsStructureKey],
+ );
const shareExpandableBlockIds = useMemo(
() => (shareSelectionActive ? collectConversationShareBlockIds(messageListItems) : []),
[messageListItems, shareSelectionActive],
@@ -9357,9 +9409,10 @@ export default function SessionScreen() {
inputProjection.continuationInFlightProjectionCapability
}
items={messageListItems}
+ itemsStructureKey={messageListStructureKey}
pendingSend={pendingSendActions}
loadingEarlier={loadingEarlier}
- loadEarlierProgressKey={oldestMessageCursor(messages)}
+ loadEarlierProgressKey={oldestLoadedMessageCursor}
onCopyMessageLink={copyMessageLink}
onAddMessageToComposer={canUseComposer ? addMessageToComposer : undefined}
onDeleteMessage={collaborationReadOnlyReason ? undefined : deleteMessage}
diff --git a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts b/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
index c6e1935853..d35aa2d833 100644
--- a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
+++ b/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
@@ -283,9 +283,12 @@ describe('mobile home desktop-first surface', () => {
expect(vendorIconSource).toContain('Easing.inOut(Easing.ease)');
// 行运行态经订阅获取(memo 化后命令式读取会 stale,2026-07-18 重渲染风暴修复)
expect(homeSource).toContain('const sessionIsRunning = useSessionRunning(item.session.id);');
- // 保鲜契约:ProjectRow 与 AutomationGroupChildren 内的命令式运行态读取必须各挂一份
- // storeVersion 订阅(裸语句形态);行内相对时间靠分钟心跳订阅保鲜。丢任何一处都是 stale-UI。
- expect((homeSource.match(/^ useRemoteSessionStoreVersion\(\);$/gm) ?? []).length).toBeGreaterThanOrEqual(2);
+ // 保鲜契约:项目/自动化折叠只订阅低频首页状态;消息预览下沉到 session 行。
+ // 普通流式 token 不得再通过全局 storeVersion 唤醒整棵首页列表。
+ expect(homeSource).not.toContain('useRemoteSessionStoreVersion();');
+ expect((homeSource.match(/useRemoteHomeStatusVersion\(\)/g) ?? []).length).toBeGreaterThanOrEqual(3);
+ expect(homeSource).toContain('useRemoteSessionMessagePreview(item.session.id)');
+ expect(homeSource).toContain('useRemoteMessageVersion(normalizedSearchQuery.length > 0)');
expect(homeSource).toContain('useMinuteNow();');
expect(homeSource).toContain('<RadioTower');
expect(homeSource).toContain('<UsersRound');
@@ -432,7 +435,8 @@ describe('mobile home desktop-first surface', () => {
expect(sessionRowSource).toContain('`home.sessionRowTitle.${item.session.id}`');
expect(sessionRowSource).toContain('ellipsizeMode="tail"');
expect(sessionRowSource).toContain('numberOfLines={1}');
- expect(sessionRowSource).toContain('buildRemoteSessionCardPreview(item, { running })');
+ expect(sessionRowSource).toContain('buildRemoteSessionCardPreview(');
+ expect(sessionRowSource).toContain('useRemoteSessionMessagePreview(item.session.id)');
expect(sessionRowSource).toContain('testID={`home.sessionRowPreview.${item.session.id}`}');
expect(sessionRowSource).toContain('const showPreviewLine = !!preview?.trim() || showSchedule || showPinned;');
expect(sessionRowSource).toContain('!showPreviewLine && styles.sessionListRowSingleLine');
diff --git a/apps/mobile/src/__tests__/messagePaging.test.ts b/apps/mobile/src/__tests__/messagePaging.test.ts
index 18c3ed581f..e5b3ae7208 100644
--- a/apps/mobile/src/__tests__/messagePaging.test.ts
+++ b/apps/mobile/src/__tests__/messagePaging.test.ts
@@ -10,6 +10,7 @@ import {
MESSAGE_PAGE_SIZE,
oldestMessageCursor,
projectLoadedMessageWindow,
+ projectLoadedMessageWindowIncrementally,
shouldKeepOlderMessagesAffordance,
shouldRefreshLatestMessageWindowOnReopen,
} from '@/session/messagePaging';
@@ -184,6 +185,53 @@ describe('messagePaging', () => {
'mobile-system-compact:latest',
]);
});
+
+ it('patches a visible streaming row without rescanning a Compact projection', () => {
+ const rows = [
+ message('m1', '2026-01-01T00:00:01.000Z'),
+ compact('replay-1', '2026-01-01T00:00:02.000Z'),
+ compact('replay-2', '2026-01-01T00:00:03.000Z'),
+ message('streaming', '2026-01-01T00:00:04.000Z'),
+ ];
+ const structureToken = {};
+ const first = projectLoadedMessageWindowIncrementally({
+ changedIndexes: new Set(),
+ messages: rows,
+ structureToken,
+ });
+ expect(first.projected.map((row) => row.id)).toEqual([
+ 'm1',
+ 'mobile-system-compact:replay-2',
+ 'streaming',
+ ]);
+
+ const nextRows = [...rows];
+ nextRows[3] = { ...rows[3], content: 'next token' };
+ let unrelatedSourceReads = 0;
+ const observedRows = new Proxy(nextRows, {
+ get(target, property, receiver) {
+ if (typeof property === 'string' && /^\d+$/.test(property) && Number(property) !== 3) {
+ unrelatedSourceReads += 1;
+ }
+ return Reflect.get(target, property, receiver);
+ },
+ });
+ const next = projectLoadedMessageWindowIncrementally({
+ changedIndexes: new Set([3]),
+ messages: observedRows,
+ previous: first,
+ structureToken,
+ });
+
+ expect(unrelatedSourceReads).toBe(0);
+ expect(next.sourceToProjectedIndex).toBe(first.sourceToProjectedIndex);
+ expect(next.changedIndexes).toEqual(new Set([2]));
+ expect(next.projected.map((row) => row.content)).toEqual([
+ 'hello',
+ 'hello',
+ 'next token',
+ ]);
+ });
});
it('keeps the load-earlier affordance only when the remote page is full', () => {
diff --git a/apps/mobile/src/__tests__/messagePerformance.test.ts b/apps/mobile/src/__tests__/messagePerformance.test.ts
index 92b69f2fe9..dec209d121 100644
--- a/apps/mobile/src/__tests__/messagePerformance.test.ts
+++ b/apps/mobile/src/__tests__/messagePerformance.test.ts
@@ -4,6 +4,7 @@ import { describe, expect, it } from 'vitest';
import { buildMobileMessageRenderItems, type MobileMessageRenderItem } from '@/session/messageRenderModel';
import { reconcileMobileMessageRenderItems } from '@/session/messageRenderReconcile';
import { buildMobileStreamingRenderWindow } from '@/session/messageRenderStreamingCache';
+import { countMobileRenderItemDiffs } from '@/session/messagePresentation';
import type { RemoteMessage } from '@/session/types';
const BASE_TIME = Date.UTC(2026, 0, 1, 0, 0, 0);
@@ -169,6 +170,8 @@ describe('message render performance', () => {
it('reuses the normalized historical prefix while only the active turn streams', () => {
const messages = createLargeDesktopMessageFixture(20);
+ const messageStructureToken = {};
+ const messageStructureChangedIndexes = new Set([messages.length + 1]);
const activeUser = message({
id: 'active-user',
role: 'user',
@@ -185,6 +188,8 @@ describe('message render performance', () => {
const first = buildMobileStreamingRenderWindow({
cacheKey: 'en',
messages: [...messages, activeUser, activeAssistant],
+ messageStructureChangedIndexes,
+ messageStructureToken,
options: { isSessionStreaming: true, sessionId: 's1' },
});
expect(first.prefix).not.toBeNull();
@@ -196,15 +201,159 @@ describe('message render performance', () => {
activeUser,
{ ...activeAssistant, content: 'Partial update' },
],
+ messageStructureChangedIndexes,
+ messageStructureToken,
options: { isSessionStreaming: true, sessionId: 's1' },
previousPrefix: first.prefix,
});
expect(next.prefix).toBe(first.prefix);
expect(next.prefix?.items).toBe(first.prefix?.items);
+ expect(next.stablePrefixItemCount).toBe(first.prefix?.items.length);
+ expect(next.diffCount).toBe(countMobileRenderItemDiffs(next.items));
expect(next.items.slice(0, first.prefix!.items.length)).toEqual(first.prefix!.items);
});
+ it('does not read a 2000-message historical prefix again for a trusted text delta', () => {
+ const history = createLargeDesktopMessageFixture(1_000);
+ const activeUser = message({
+ id: 'active-user',
+ role: 'user',
+ content: 'Continue',
+ createdAt: timestamp(2_001),
+ });
+ const activeAssistant = message({
+ id: 'active-assistant',
+ role: 'assistant',
+ content: 'Partial',
+ agentMeta: { isStreaming: true },
+ createdAt: timestamp(2_002),
+ });
+ const messageStructureToken = {};
+ const messageStructureChangedIndexes = new Set([history.length + 1]);
+ const first = buildMobileStreamingRenderWindow({
+ cacheKey: 'en',
+ messages: [...history, activeUser, activeAssistant],
+ messageStructureChangedIndexes,
+ messageStructureToken,
+ options: { isSessionStreaming: true, sessionId: 's1' },
+ });
+ let historicalReads = 0;
+ const nextMessages = new Proxy(
+ [...history, activeUser, { ...activeAssistant, content: 'Partial update' }],
+ {
+ get(target, property, receiver) {
+ if (typeof property === 'string' && /^\d+$/.test(property)) {
+ const index = Number(property);
+ if (index < history.length) historicalReads += 1;
+ }
+ return Reflect.get(target, property, receiver);
+ },
+ },
+ );
+
+ const next = buildMobileStreamingRenderWindow({
+ cacheKey: 'en',
+ messages: nextMessages,
+ messageStructureChangedIndexes,
+ messageStructureToken,
+ options: { isSessionStreaming: true, sessionId: 's1' },
+ previousPrefix: first.prefix,
+ });
+
+ expect(historicalReads).toBe(0);
+ expect(next.stablePrefixItemCount).toBe(first.prefix?.items.length);
+ });
+
+ it('falls back to reference validation when no structure token is supplied', () => {
+ const historicalAssistant = message({
+ id: 'historical-assistant',
+ role: 'assistant',
+ content: 'Original history',
+ createdAt: timestamp(1),
+ });
+ const activeUser = message({
+ id: 'active-user-without-token',
+ role: 'user',
+ content: 'Continue',
+ createdAt: timestamp(2),
+ });
+ const activeAssistant = message({
+ id: 'active-assistant-without-token',
+ role: 'assistant',
+ content: 'Partial',
+ agentMeta: { isStreaming: true },
+ createdAt: timestamp(3),
+ });
+ const options = { isSessionStreaming: true, sessionId: 's1' } as const;
+ const first = buildMobileStreamingRenderWindow({
+ cacheKey: 'en',
+ messages: [historicalAssistant, activeUser, activeAssistant],
+ options,
+ });
+ const changedMessages = [
+ { ...historicalAssistant, content: 'Corrected history' },
+ activeUser,
+ activeAssistant,
+ ];
+ const changed = buildMobileStreamingRenderWindow({
+ cacheKey: 'en',
+ messages: changedMessages,
+ options,
+ previousPrefix: first.prefix,
+ });
+
+ expect(changed.prefix).not.toBe(first.prefix);
+ expect(changed.items).toEqual(buildMobileMessageRenderItems(changedMessages, options));
+ });
+
+ it('invalidates a historical prefix changed under the same structure token', () => {
+ const historicalAssistant = message({
+ id: 'historical-assistant-with-token',
+ role: 'assistant',
+ content: 'Original history',
+ createdAt: timestamp(1),
+ });
+ const activeUser = message({
+ id: 'active-user-with-history-change',
+ role: 'user',
+ content: 'Continue',
+ createdAt: timestamp(2),
+ });
+ const activeAssistant = message({
+ id: 'active-assistant-with-history-change',
+ role: 'assistant',
+ content: 'Partial',
+ agentMeta: { isStreaming: true },
+ createdAt: timestamp(3),
+ });
+ const messageStructureToken = {};
+ const options = { isSessionStreaming: true, sessionId: 's1' } as const;
+ const first = buildMobileStreamingRenderWindow({
+ cacheKey: 'en',
+ messages: [historicalAssistant, activeUser, activeAssistant],
+ messageStructureChangedIndexes: new Set([2]),
+ messageStructureToken,
+ options,
+ });
+ const changedMessages = [
+ { ...historicalAssistant, content: 'Corrected history' },
+ activeUser,
+ activeAssistant,
+ ];
+ const changed = buildMobileStreamingRenderWindow({
+ cacheKey: 'en',
+ messages: changedMessages,
+ messageStructureChangedIndexes: new Set([0, 2]),
+ messageStructureToken,
+ options,
+ previousPrefix: first.prefix,
+ });
+
+ expect(changed.prefix).not.toBe(first.prefix);
+ expect(changed.items).toEqual(buildMobileMessageRenderItems(changedMessages, options));
+ });
+
it('invalidates a historical prefix only when one of its task updates changes', () => {
const prefixTask = message({
id: 'historical-prefix-task',
@@ -419,6 +568,65 @@ describe('message render performance', () => {
expect(retry.items).toEqual(buildMobileMessageRenderItems(updatedMessages, options));
});
+ it('does not rescan a retained 2000-message prefix to rediscover a truncated-turn boundary', () => {
+ const history = Array.from({ length: 2_000 }, (_, index) => message({
+ id: `retained-assistant-${index}`,
+ role: 'assistant',
+ content: `Completed ${index}`,
+ createdAt: timestamp(index),
+ }));
+ const activeThinking = message({
+ id: 'retained-active-thinking',
+ role: 'thinking',
+ content: { kind: 'thinking', text: 'Continuing', isStreaming: true },
+ createdAt: timestamp(2_001),
+ });
+ const activeAssistant = message({
+ id: 'retained-active-assistant',
+ role: 'assistant',
+ content: 'Partial',
+ agentMeta: { isStreaming: true },
+ createdAt: timestamp(2_002),
+ });
+ const messageStructureToken = {};
+ const changedIndexes = new Set([2_001]);
+ const options = { isSessionStreaming: true, sessionId: 's1' } as const;
+ const first = buildMobileStreamingRenderWindow({
+ cacheKey: 'en',
+ messages: [...history, activeThinking, activeAssistant],
+ messageStructureChangedIndexes: changedIndexes,
+ messageStructureToken,
+ options,
+ });
+ expect(first.prefix?.mode).toBe('truncated-turn');
+
+ let historicalReads = 0;
+ const nextMessages = new Proxy(
+ [...history, activeThinking, { ...activeAssistant, content: 'Partial update' }],
+ {
+ get(target, property, receiver) {
+ if (typeof property === 'string' && /^\d+$/.test(property)) {
+ const index = Number(property);
+ if (index < history.length - 1) historicalReads += 1;
+ }
+ return Reflect.get(target, property, receiver);
+ },
+ },
+ );
+ const next = buildMobileStreamingRenderWindow({
+ cacheKey: 'en',
+ messages: nextMessages,
+ messageStructureChangedIndexes: changedIndexes,
+ messageStructureToken,
+ options,
+ previousPrefix: first.prefix,
+ });
+
+ expect(historicalReads).toBe(0);
+ expect(next.prefix).toBe(first.prefix);
+ expect(next.stablePrefixItemCount).toBe(first.prefix?.items.length);
+ });
+
it('advances the reusable prefix into a long visible active turn', () => {
const history = createLargeDesktopMessageFixture(20);
const activeUser = message({
diff --git a/apps/mobile/src/__tests__/remoteSessionStore.test.ts b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
index c972ab4e38..ff7e42f4aa 100644
--- a/apps/mobile/src/__tests__/remoteSessionStore.test.ts
+++ b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
@@ -676,6 +676,251 @@ describe('remoteSessionStore', () => {
}
});
+ it('keeps message structure and home status stable across ordinary text deltas', () => {
+ vi.useFakeTimers();
+ try {
+ remoteSessionStore.enterSessionMessageDetail('s1');
+ remoteSessionStore.setMessages('s1', Array.from({ length: 2_000 }, (_, index) => ({
+ ...message(`history-${index}`, 's1'),
+ createdAt: new Date(Date.UTC(2026, 0, 1, 0, 0, index)).toISOString(),
+ })));
+ pushMakerText('s1', 'live-tail', 'first', false);
+ vi.runOnlyPendingTimers();
+
+ const firstStructure = remoteSessionStore.getSessionMessageStructureToken('s1');
+ const homeStatusBeforeDelta = remoteSessionStore.getHomeStatusVersion();
+ const reduceSpy = vi.spyOn(Array.prototype, 'reduce');
+ const filterSpy = vi.spyOn(Array.prototype, 'filter');
+ try {
+ pushMakerText('s1', 'live-tail', ' second', false);
+ vi.runOnlyPendingTimers();
+
+ expect(reduceSpy).not.toHaveBeenCalled();
+ expect(filterSpy).not.toHaveBeenCalled();
+ } finally {
+ reduceSpy.mockRestore();
+ filterSpy.mockRestore();
+ }
+
+ expect(remoteSessionStore.getMessages('s1').at(-1)?.content).toBe('first second');
+ expect(remoteSessionStore.getSessionMessageStructureToken('s1')).toBe(firstStructure);
+ expect(remoteSessionStore.getSessionMessageStructureChangedIndexes('s1')).toEqual(
+ new Set([2_000]),
+ );
+ expect(remoteSessionStore.getHomeStatusVersion()).toBe(homeStatusBeforeDelta);
+ expect(remoteSessionStore.getSessionMessagePreview('s1')).toBe('first second');
+
+ pushMakerText(
+ 's1',
+ 'live-tail',
+ 'first second',
+ true,
+ { isStreaming: false, streaming: false },
+ );
+ expect(remoteSessionStore.getSessionMessageStructureToken('s1')).not.toBe(firstStructure);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('isolates empty message structure tokens by session', () => {
+ const first = remoteSessionStore.getSessionMessageStructureToken('s1');
+ expect(remoteSessionStore.getSessionMessageStructureToken('s1')).toBe(first);
+ expect(remoteSessionStore.getSessionMessageStructureToken('s2')).not.toBe(first);
+
+ remoteSessionStore.setMessages('s1', [message('m1', 's1')]);
+ expect(remoteSessionStore.getSessionMessageStructureToken('s1')).not.toBe(first);
+ });
+
+ it('notifies only the changed session preview subscription for text deltas', () => {
+ vi.useFakeTimers();
+ const firstPreview = vi.fn();
+ const secondPreview = vi.fn();
+ const homeStatus = vi.fn();
+ const unsubscribeFirst = remoteSessionStore.subscribeSessionMessagePreview('s1', firstPreview);
+ const unsubscribeSecond = remoteSessionStore.subscribeSessionMessagePreview('s2', secondPreview);
+ const unsubscribeHomeStatus = remoteSessionStore.subscribeHomeStatus(homeStatus);
+ try {
+ pushMakerText('s1', 'persist-1', 'first', false);
+ vi.advanceTimersByTime(32);
+
+ expect(firstPreview).toHaveBeenCalledTimes(1);
+ expect(secondPreview).not.toHaveBeenCalled();
+ expect(homeStatus).not.toHaveBeenCalled();
+ } finally {
+ unsubscribeFirst();
+ unsubscribeSecond();
+ unsubscribeHomeStatus();
+ vi.useRealTimers();
+ }
+ });
+
+ it('keeps the first text flush responsive and batches continuation deltas', () => {
+ vi.useFakeTimers();
+ const notify = vi.fn();
+ const unsubscribe = remoteSessionStore.subscribe(notify);
+ try {
+ remoteSessionStore.enterSessionMessageDetail('s1');
+ pushMakerText('s1', 'persist-1', 'first', false);
+ vi.advanceTimersByTime(31);
+ expect(remoteSessionStore.getMessages('s1')).toHaveLength(0);
+ expect(notify).not.toHaveBeenCalled();
+
+ vi.advanceTimersByTime(1);
+ expect(remoteSessionStore.getMessages('s1')[0]?.content).toBe('first');
+ expect(notify).toHaveBeenCalledTimes(1);
+ notify.mockClear();
+
+ pushMakerText('s1', 'persist-1', ' second', false);
+ vi.advanceTimersByTime(40);
+ pushMakerText('s1', 'persist-1', ' third', false);
+ expect(remoteSessionStore.getMessages('s1')[0]?.content).toBe('first');
+ expect(notify).not.toHaveBeenCalled();
+
+ vi.advanceTimersByTime(24);
+ expect(remoteSessionStore.getMessages('s1')[0]?.content).toBe('first second third');
+ expect(notify).toHaveBeenCalledTimes(1);
+ } finally {
+ unsubscribe();
+ vi.useRealTimers();
+ }
+ });
+
+ it('batches background continuation deltas more aggressively than visible detail', () => {
+ vi.useFakeTimers();
+ const notify = vi.fn();
+ const unsubscribe = remoteSessionStore.subscribe(notify);
+ try {
+ pushMakerText('s1', 'persist-1', 'first', false);
+ vi.advanceTimersByTime(32);
+ notify.mockClear();
+
+ pushMakerText('s1', 'persist-1', ' second', false);
+ vi.advanceTimersByTime(64);
+ expect(remoteSessionStore.getMessages('s1')[0]?.content).toBe('first');
+ expect(notify).not.toHaveBeenCalled();
+
+ vi.advanceTimersByTime(32);
+ expect(remoteSessionStore.getMessages('s1')[0]?.content).toBe('first second');
+ expect(notify).toHaveBeenCalledTimes(1);
+ } finally {
+ unsubscribe();
+ vi.useRealTimers();
+ }
+ });
+
+ it('lets a new session first delta accelerate an existing continuation timer', () => {
+ vi.useFakeTimers();
+ try {
+ pushMakerText('s1', 'persist-1', 'first', false);
+ vi.advanceTimersByTime(32);
+ pushMakerText('s1', 'persist-1', ' continuation', false);
+
+ vi.advanceTimersByTime(20);
+ pushMakerText('s2', 'persist-2', 'new session', false);
+ vi.advanceTimersByTime(31);
+ expect(remoteSessionStore.getMessages('s1')[0]?.content).toBe('first');
+ expect(remoteSessionStore.getMessages('s2')).toHaveLength(0);
+
+ vi.advanceTimersByTime(1);
+ expect(remoteSessionStore.getMessages('s1')[0]?.content).toBe('first continuation');
+ expect(remoteSessionStore.getMessages('s2')[0]?.content).toBe('new session');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('reuses the identity index when a streaming assistant is not the tail row', () => {
+ vi.useFakeTimers();
+ try {
+ remoteSessionStore.enterSessionMessageDetail('s1');
+ remoteSessionStore.setMessages('s1', Array.from({ length: 2_000 }, (_, index) => ({
+ ...message(`history-${index}`, 's1'),
+ createdAt: new Date(Date.UTC(2026, 0, 1, 0, 0, index)).toISOString(),
+ })));
+ pushMakerText('s1', 'live-before-system-card', 'first', false);
+ vi.runOnlyPendingTimers();
+ remoteSessionStore.appendLocalSystemCard(
+ 's1',
+ 'context',
+ { context: 'tail card' },
+ new Date('2026-01-02T00:00:00.000Z'),
+ );
+
+ // The first non-tail delta builds the identity index. Its replacement inherits that index.
+ pushMakerText('s1', 'live-before-system-card', ' second', false);
+ vi.runOnlyPendingTimers();
+ const findIndexSpy = vi.spyOn(Array.prototype, 'findIndex');
+ try {
+ pushMakerText('s1', 'live-before-system-card', ' third', false);
+ vi.runOnlyPendingTimers();
+
+ expect(findIndexSpy).not.toHaveBeenCalled();
+ expect(remoteSessionStore.getMessages('s1').find(
+ (item) => item.clientId === 'live-before-system-card',
+ )?.content).toBe('first second third');
+ } finally {
+ findIndexSpy.mockRestore();
+ }
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('clears content-only indexes after append, prepend, final, and reset writes', () => {
+ vi.useFakeTimers();
+ let sequence = 0;
+ const establishContentOnlyDelta = (persistId: string): object => {
+ pushMakerText('s1', persistId, 'first', false);
+ vi.runOnlyPendingTimers();
+ const structureToken = remoteSessionStore.getSessionMessageStructureToken('s1');
+ pushMakerText('s1', persistId, ' second', false);
+ vi.runOnlyPendingTimers();
+ expect(remoteSessionStore.getSessionMessageStructureToken('s1')).toBe(structureToken);
+ expect(remoteSessionStore.getSessionMessageStructureChangedIndexes('s1').size).toBe(1);
+ return structureToken;
+ };
+ const expectStructuralReset = (previousToken: object): void => {
+ expect(remoteSessionStore.getSessionMessageStructureToken('s1')).not.toBe(previousToken);
+ expect(remoteSessionStore.getSessionMessageStructureChangedIndexes('s1').size).toBe(0);
+ };
+ const nextMessage = (prefix: string, createdAt: string): RemoteMessage => {
+ sequence += 1;
+ return messageAt(`${prefix}-${sequence}`, 's1', createdAt);
+ };
+ try {
+ let previousToken = establishContentOnlyDelta('live-before-append');
+ remoteSessionStore.appendMessage(
+ 's1',
+ nextMessage('append', '2026-01-02T00:00:00.000Z'),
+ );
+ expectStructuralReset(previousToken);
+
+ previousToken = establishContentOnlyDelta('live-before-prepend');
+ remoteSessionStore.mergeEarlierMessages(
+ 's1',
+ [nextMessage('prepend', '2025-12-31T00:00:00.000Z')],
+ );
+ expectStructuralReset(previousToken);
+
+ previousToken = establishContentOnlyDelta('live-before-final');
+ pushMakerText('s1', 'live-before-final', 'first second', true, {
+ isStreaming: false,
+ streaming: false,
+ });
+ expectStructuralReset(previousToken);
+
+ previousToken = establishContentOnlyDelta('live-before-reset');
+ remoteSessionStore.setMessages(
+ 's1',
+ [nextMessage('reset', '2026-01-03T00:00:00.000Z')],
+ );
+ expectStructuralReset(previousToken);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('finalizes the previous streaming assistant when the persist id changes', () => {
vi.useFakeTimers();
try {
@@ -4761,6 +5006,28 @@ describe('任务消息内存治理', () => {
expect(sessions.slice(1).some((item) => remoteSessionStore.getMessages(item.id).length === 0)).toBe(true);
});
+ it('notifies an evicted session preview subscriber when another session exceeds the LRU budget', () => {
+ const sessions = Array.from({ length: 9 }, (_, index) => session(`s${index}`));
+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', sessions);
+ const previewChanged = vi.fn();
+ const unsubscribe = remoteSessionStore.subscribeSessionMessagePreview('s0', previewChanged);
+ try {
+ remoteSessionStore.setMessages('s0', manyMessages('s0', 100));
+ expect(remoteSessionStore.getSessionMessagePreview('s0')).toBeDefined();
+ previewChanged.mockClear();
+
+ for (const item of sessions.slice(1)) {
+ remoteSessionStore.setMessages(item.id, manyMessages(item.id, 100));
+ }
+
+ expect(remoteSessionStore.getMessages('s0')).toEqual([]);
+ expect(previewChanged).toHaveBeenCalledTimes(1);
+ expect(remoteSessionStore.getSessionMessagePreview('s0')).toBeUndefined();
+ } finally {
+ unsubscribe();
+ }
+ });
+
it('regular 字节 LRU 会计入深层容器中的大字符串', () => {
remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s0'), session('s1')]);
const currentAuthority = remoteSessionStore.enterSessionMessageDetail('s1');
diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsx
index 2346cc9a32..06a10d874f 100644
--- a/apps/mobile/src/session/MessageRenderer.tsx
+++ b/apps/mobile/src/session/MessageRenderer.tsx
@@ -625,6 +625,7 @@ export function MessageRenderer({
focusedItemKey,
followLatestRequestKey,
items,
+ itemsStructureKey,
onCopyMessageLink,
onAddMessageToComposer,
onForkMessage,
@@ -671,6 +672,8 @@ export function MessageRenderer({
focusedRequestKey?: number | string | null;
followLatestRequestKey?: number | string | null;
items: readonly MobileMessageRenderItem[];
+ /** Stable while streaming only changes row content; structural list derivations key off this. */
+ itemsStructureKey?: unknown;
/** Oldest loaded host cursor; synthetic cards must not mask successful history prepends. */
loadEarlierProgressKey?: string | null;
emptyTestID?: string;
@@ -709,8 +712,17 @@ export function MessageRenderer({
const { colors } = useTheme();
const { t } = useTranslation();
const styles = useThemedStyles(makeStyles);
- const firstUserMessageClientId = findFirstUserMessageClientId(items);
- const lastUserInputClientId = findLastUserInputClientId(items);
+ const itemStructureIdentity = itemsStructureKey ?? items;
+ const itemsForStructureRef = useRef(items);
+ itemsForStructureRef.current = items;
+ const firstUserMessageClientId = useMemo(
+ () => findFirstUserMessageClientId(itemsForStructureRef.current),
+ [itemStructureIdentity],
+ );
+ const lastUserInputClientId = useMemo(
+ () => findLastUserInputClientId(itemsForStructureRef.current),
+ [itemStructureIdentity],
+ );
const focusedItemKeyRef = useRef(focusedItemKey);
focusedItemKeyRef.current = focusedItemKey;
const listRef = useRef<LegendListRef>(null);
@@ -1318,7 +1330,7 @@ export function MessageRenderer({
// 与 main 保持一致:完整历史从首次挂载起就在同一个 LegendList 中,屏外 cell 交给
// LegendList 虚拟化/回收。不能用业务尾窗代替完整数据,否则短尾窗未撑满首屏时
// Android 无法产生有效滚动,运行中任务会重现“上半屏空白且历史不可拖动”。
- const listData = useMemo(() => [...items], [items]);
+ const listData = items;
const listDataRef = useRef(listData);
listDataRef.current = listData;
const prevListLengthRef = useRef(listData.length);
@@ -1334,7 +1346,10 @@ export function MessageRenderer({
}
prevListLengthRef.current = listData.length;
}
- const itemKeys = useMemo(() => listData.map((item) => item.key), [listData]);
+ const itemKeys = useMemo(
+ () => listDataRef.current.map((item) => item.key),
+ [itemStructureIdentity],
+ );
const itemKeysSignature = useMemo(
() => mobileMessageListKeysSignature(itemKeys),
[itemKeys],
diff --git a/apps/mobile/src/session/messagePaging.ts b/apps/mobile/src/session/messagePaging.ts
index 868febc146..07b7993264 100644
--- a/apps/mobile/src/session/messagePaging.ts
+++ b/apps/mobile/src/session/messagePaging.ts
@@ -90,6 +90,90 @@ export function projectLoadedMessageWindow(
return changed ? projected : messages;
}
+export interface LoadedMessageWindowProjection {
+ changedIndexes: ReadonlySet<number>;
+ projected: readonly RemoteMessage[];
+ source: readonly RemoteMessage[];
+ sourceToProjectedIndex: Int32Array | null;
+ structureToken: object;
+}
+
+/**
+ * Reuses Compact-card projection while a stable structure token proves that only row content
+ * changed. The source-to-projected map lets a streaming delta patch its one visible row without
+ * scanning the complete loaded window again.
+ */
+export function projectLoadedMessageWindowIncrementally(input: {
+ changedIndexes: ReadonlySet<number>;
+ messages: readonly RemoteMessage[];
+ previous?: LoadedMessageWindowProjection | null;
+ structureToken: object;
+}): LoadedMessageWindowProjection {
+ const { changedIndexes, messages, previous, structureToken } = input;
+ const sameStructure = previous?.structureToken === structureToken
+ && previous.source.length === messages.length;
+ let projected: readonly RemoteMessage[];
+ let sourceToProjectedIndex: Int32Array | null;
+ if (sameStructure && messages === previous.source) {
+ projected = previous.projected;
+ sourceToProjectedIndex = previous.sourceToProjectedIndex;
+ } else if (sameStructure && previous.projected === previous.source) {
+ projected = messages;
+ sourceToProjectedIndex = null;
+ } else if (
+ sameStructure
+ && previous.sourceToProjectedIndex?.length === messages.length
+ ) {
+ let patched: RemoteMessage[] | null = null;
+ for (const sourceIndex of changedIndexes) {
+ const projectedIndex = previous.sourceToProjectedIndex[sourceIndex] ?? -1;
+ if (projectedIndex < 0) continue;
+ const nextMessage = messages[sourceIndex];
+ if (!nextMessage || previous.projected[projectedIndex] === nextMessage) continue;
+ patched ??= [...previous.projected];
+ patched[projectedIndex] = nextMessage;
+ }
+ projected = patched ?? previous.projected;
+ sourceToProjectedIndex = previous.sourceToProjectedIndex;
+ } else {
+ projected = projectLoadedMessageWindow(messages);
+ if (projected === messages) {
+ sourceToProjectedIndex = null;
+ } else {
+ sourceToProjectedIndex = new Int32Array(messages.length);
+ sourceToProjectedIndex.fill(-1);
+ let projectedIndex = 0;
+ for (let sourceIndex = 0; sourceIndex < messages.length; sourceIndex += 1) {
+ if (messages[sourceIndex] !== projected[projectedIndex]) continue;
+ sourceToProjectedIndex[sourceIndex] = projectedIndex;
+ projectedIndex += 1;
+ }
+ }
+ }
+ const projectedChangedIndexes = sourceToProjectedIndex
+ ? mapChangedIndexesToProjection(changedIndexes, sourceToProjectedIndex)
+ : changedIndexes;
+ return {
+ changedIndexes: projectedChangedIndexes,
+ projected,
+ source: messages,
+ sourceToProjectedIndex,
+ structureToken,
+ };
+}
+
+function mapChangedIndexesToProjection(
+ changedIndexes: ReadonlySet<number>,
+ sourceToProjectedIndex: Int32Array,
+): ReadonlySet<number> {
+ const projectedIndexes = new Set<number>();
+ for (const sourceIndex of changedIndexes) {
+ const projectedIndex = sourceToProjectedIndex[sourceIndex] ?? -1;
+ if (projectedIndex >= 0) projectedIndexes.add(projectedIndex);
+ }
+ return projectedIndexes;
+}
+
export function hasMoreOlderMessages(page: readonly RemoteMessage[], pageSize = MESSAGE_PAGE_SIZE): boolean {
if (page.length >= pageSize) return true;
// 被控端结果帧超限时会静默裁行,并在保留行打 agentMeta.remoteRowsTrimmed 标记
diff --git a/apps/mobile/src/session/messageRenderReconcile.ts b/apps/mobile/src/session/messageRenderReconcile.ts
index f5fe3b815f..cdd383a21f 100644
--- a/apps/mobile/src/session/messageRenderReconcile.ts
+++ b/apps/mobile/src/session/messageRenderReconcile.ts
@@ -23,23 +23,45 @@ type ReconciledRenderItem = MobileMessageRenderItem | MobileWorkChildItem;
export function reconcileMobileMessageRenderItems(
previous: readonly MobileMessageRenderItem[],
next: readonly MobileMessageRenderItem[],
+ stablePrefixItemCount = 0,
): readonly MobileMessageRenderItem[] {
- return reconcileRenderItemList(previous, next) as readonly MobileMessageRenderItem[];
+ return reconcileRenderItemList(
+ previous,
+ next,
+ stablePrefixItemCount,
+ ) as readonly MobileMessageRenderItem[];
}
function reconcileRenderItemList<T extends ReconciledRenderItem>(
previous: readonly T[],
next: readonly T[],
+ stablePrefixItemCount = 0,
): readonly T[] {
if (next.length === 0) return previous.length === 0 ? previous : next;
- const previousByKey = new Map(previous.map((item) => [item.key, item] as const));
- const reconciled = next.map((item) => (
- reconcileRenderItem(previousByKey.get(item.key), item) as T
- ));
- if (
- previous.length === reconciled.length
- && reconciled.every((item, index) => item === previous[index])
+ const trustedPrefixLength = Math.max(
+ 0,
+ Math.min(stablePrefixItemCount, previous.length, next.length),
+ );
+ const previousByKey = new Map<string, T>();
+ for (let index = trustedPrefixLength; index < previous.length; index += 1) {
+ previousByKey.set(previous[index].key, previous[index]);
+ }
+ // Render-model builders hand this reconciler a fresh array. Reconcile its dirty tail in place so
+ // a token update does not allocate another full-history array merely to reuse prior row objects.
+ const reconciled = next as unknown as T[];
+ for (let index = trustedPrefixLength; index < reconciled.length; index += 1) {
+ const item = reconciled[index];
+ reconciled[index] = reconcileRenderItem(previousByKey.get(item.key), item) as T;
+ }
+ let allReconciledItemsUnchanged = previous.length === reconciled.length;
+ for (
+ let index = trustedPrefixLength;
+ allReconciledItemsUnchanged && index < reconciled.length;
+ index += 1
) {
+ if (reconciled[index] !== previous[index]) allReconciledItemsUnchanged = false;
+ }
+ if (allReconciledItemsUnchanged) {
return previous;
}
return reconciled;
diff --git a/apps/mobile/src/session/messageRenderStreamingCache.ts b/apps/mobile/src/session/messageRenderStreamingCache.ts
index 0d1fda786f..5f795eef5f 100644
--- a/apps/mobile/src/session/messageRenderStreamingCache.ts
+++ b/apps/mobile/src/session/messageRenderStreamingCache.ts
@@ -12,6 +12,7 @@ import {
type MobileMessageRenderItem,
} from '@/session/messageRenderModel';
import { collectMobileMarkdownImages } from '@/session/messageMarkdown';
+import { countMobileRenderItemDiffs } from '@/session/messagePresentation';
import type { RemoteMessage } from '@/session/types';
import { contentToPreview } from '@/utils/contentPreview';
@@ -19,12 +20,15 @@ export interface MobileStreamingRenderPrefixCache {
boundaryMessage?: RemoteMessage;
cacheKey: string;
items: readonly MobileMessageRenderItem[];
+ diffCount: number;
markdownImageUrls?: ReadonlySet<string>;
+ messageStructureToken?: object;
messages: readonly RemoteMessage[];
mode: 'history' | 'truncated-turn';
sessionId: string;
tailToolResults?: readonly RemoteMessage[];
taskUpdateDependencies?: readonly MobileStreamingTaskUpdateDependency[];
+ taskUpdates?: ReadonlyMap<string, AgentTaskUpdate>;
toolUseIds?: ReadonlySet<string>;
}
@@ -41,6 +45,8 @@ export interface MobileStreamingRenderPrefixCacheRef {
interface BuildMobileStreamingRenderWindowInput {
cacheKey: string;
messages: readonly RemoteMessage[];
+ messageStructureChangedIndexes?: ReadonlySet<number>;
+ messageStructureToken?: object;
options: MessageRenderOptions & {
autoResumePending?: Record<string, unknown> | null;
sessionId?: string;
@@ -51,8 +57,10 @@ interface BuildMobileStreamingRenderWindowInput {
}
export interface MobileStreamingRenderWindowResult {
+ diffCount: number;
items: MobileMessageRenderItem[];
prefix: MobileStreamingRenderPrefixCache | null;
+ stablePrefixItemCount: number;
}
/**
@@ -70,18 +78,37 @@ export function buildMobileStreamingRenderWindow(
const {
cacheKey,
messages,
+ messageStructureChangedIndexes,
+ messageStructureToken,
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;
+ const trustedPreviousBoundary = trustedStreamingBoundaryPrefix({
+ changedIndexes: messageStructureChangedIndexes,
+ messageStructureToken,
+ previousPrefix,
+ sessionId,
+ });
+ const activeTurnStart = options.isSessionStreaming !== true
+ ? -1
+ : trustedPreviousBoundary?.mode === 'history'
+ ? trustedPreviousBoundary.messages.length
+ : trustedPreviousBoundary?.mode === 'truncated-turn'
+ ? -1
+ : findLastRootUserMessageIndex(messages);
+ const stableAssistantBoundary = options.isSessionStreaming !== true
+ ? -1
+ : trustedPreviousBoundary?.mode === 'truncated-turn'
+ ? trustedPreviousBoundary.messages.length - 1
+ : trustedPreviousBoundary?.mode === 'history'
+ ? -1
+ : findLastStableAssistantBoundaryIndex(
+ messages,
+ activeTurnStart >= 0 ? activeTurnStart + 1 : 1,
+ );
if (
options.isSessionStreaming === true
&& (activeTurnStart < 0 || stableAssistantBoundary > activeTurnStart)
@@ -105,6 +132,8 @@ export function buildMobileStreamingRenderWindow(
boundaryIndex: stableAssistantBoundary,
cacheKey,
messages,
+ messageStructureChangedIndexes,
+ messageStructureToken,
options,
prefixCache,
previousPrefix,
@@ -113,9 +142,12 @@ export function buildMobileStreamingRenderWindow(
});
}
if (activeTurnStart <= 0) {
+ const items = buildMobileMessageRenderItems(messages, options, taskUpdates);
const result = {
- items: buildMobileMessageRenderItems(messages, options, taskUpdates),
+ diffCount: countMobileRenderItemDiffs(items),
+ items,
prefix: null,
+ stablePrefixItemCount: 0,
};
if (prefixCache) prefixCache.current = null;
return result;
@@ -124,8 +156,19 @@ export function buildMobileStreamingRenderWindow(
const canReusePrefix = previousPrefix?.mode === 'history'
&& previousPrefix.sessionId === sessionId
&& previousPrefix.cacheKey === cacheKey
- && sameTaskUpdateDependencies(previousPrefix.taskUpdateDependencies, taskUpdates)
- && sameMessagePrefixReferences(previousPrefix.messages, messages, activeTurnStart);
+ && (
+ previousPrefix.taskUpdates === taskUpdates
+ || sameTaskUpdateDependencies(previousPrefix.taskUpdateDependencies, taskUpdates)
+ )
+ && (
+ structureTokenKeepsPrefixStable({
+ changedIndexes: messageStructureChangedIndexes,
+ messageStructureToken,
+ minimumChangedIndex: activeTurnStart,
+ previousMessageStructureToken: previousPrefix.messageStructureToken,
+ })
+ || sameMessagePrefixReferences(previousPrefix.messages, messages, activeTurnStart)
+ );
const prefixMessages = canReusePrefix
? previousPrefix.messages
: messages.slice(0, activeTurnStart);
@@ -140,15 +183,22 @@ export function buildMobileStreamingRenderWindow(
isSessionStreaming: false,
renderOrphanTaskUpdates: false,
}, taskUpdates);
+ if (canReusePrefix) {
+ previousPrefix.messageStructureToken = messageStructureToken;
+ previousPrefix.taskUpdates = taskUpdates;
+ }
const prefix = canReusePrefix
? previousPrefix
: {
cacheKey,
+ diffCount: countMobileRenderItemDiffs(prefixItems),
items: prefixItems,
+ messageStructureToken,
messages: prefixMessages,
mode: 'history' as const,
sessionId,
taskUpdateDependencies: prefixTaskUpdateDependencies,
+ taskUpdates,
};
const activeItems = buildMobileMessageRenderItems(
messages.slice(activeTurnStart),
@@ -156,8 +206,10 @@ export function buildMobileStreamingRenderWindow(
omitTaskUpdatesConsumedByPrefix(taskUpdates, prefixTaskUpdateDependencies),
);
const result = {
+ diffCount: prefix.diffCount + countMobileRenderItemDiffs(activeItems),
items: [...prefixItems, ...activeItems],
prefix,
+ stablePrefixItemCount: canReusePrefix ? prefixItems.length : 0,
};
// 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.
@@ -177,6 +229,8 @@ function buildTruncatedActiveTurnWindow(
boundaryIndex,
cacheKey,
messages,
+ messageStructureChangedIndexes,
+ messageStructureToken,
options,
prefixCache,
previousPrefix,
@@ -185,25 +239,45 @@ function buildTruncatedActiveTurnWindow(
} = input;
let items: MobileMessageRenderItem[] | null = null;
let reusedPrefix = false;
+ let activeDiffCount = 0;
if (
previousPrefix?.mode === 'truncated-turn'
&& previousPrefix.sessionId === sessionId
&& previousPrefix.cacheKey === cacheKey
- && sameTaskUpdateDependencies(previousPrefix.taskUpdateDependencies, taskUpdates)
+ && (
+ previousPrefix.taskUpdates === taskUpdates
+ || sameTaskUpdateDependencies(previousPrefix.taskUpdateDependencies, taskUpdates)
+ )
&& previousPrefix.boundaryMessage
&& previousPrefix.messages.length === boundaryIndex + 1
&& previousPrefix.boundaryMessage === messages[boundaryIndex]
- && sameMessagePrefixReferences(
- previousPrefix.messages,
- messages,
- previousPrefix.messages.length,
+ && (
+ structureTokenKeepsPrefixStable({
+ changedIndexes: messageStructureChangedIndexes,
+ messageStructureToken,
+ minimumChangedIndex: previousPrefix.messages.length,
+ previousMessageStructureToken: previousPrefix.messageStructureToken,
+ })
+ || sameMessagePrefixReferences(
+ previousPrefix.messages,
+ messages,
+ previousPrefix.messages.length,
+ )
)
- && sameDependentTailToolResults(
- previousPrefix.tailToolResults ?? [],
- messages,
- previousPrefix.messages.length,
- previousPrefix.toolUseIds,
+ && (
+ structureTokenKeepsPrefixStable({
+ changedIndexes: messageStructureChangedIndexes,
+ messageStructureToken,
+ minimumChangedIndex: previousPrefix.messages.length,
+ previousMessageStructureToken: previousPrefix.messageStructureToken,
+ })
+ || sameDependentTailToolResults(
+ previousPrefix.tailToolResults ?? [],
+ messages,
+ previousPrefix.messages.length,
+ previousPrefix.toolUseIds,
+ )
)
) {
const activeItems = buildMobileMessageRenderItems(
@@ -216,23 +290,34 @@ function buildTruncatedActiveTurnWindow(
previousPrefix.boundaryMessage,
);
if (duplicateBoundaryIndex >= 0) {
+ const activeTailItems = activeItems.slice(duplicateBoundaryIndex + 1);
items = [
...previousPrefix.items,
- ...activeItems.slice(duplicateBoundaryIndex + 1),
+ ...activeTailItems,
];
+ activeDiffCount = countMobileRenderItemDiffs(activeTailItems);
reusedPrefix = true;
}
}
if (!items) items = buildMobileMessageRenderItems(messages, options, taskUpdates);
if (reusedPrefix && previousPrefix) {
- if (prefixCache) prefixCache.current = previousPrefix;
- return { items, prefix: previousPrefix };
+ previousPrefix.messageStructureToken = messageStructureToken;
+ previousPrefix.taskUpdates = taskUpdates;
+ const prefix = previousPrefix;
+ if (prefixCache) prefixCache.current = prefix;
+ return {
+ diffCount: prefix.diffCount + activeDiffCount,
+ items,
+ prefix,
+ stablePrefixItemCount: prefix.items.length,
+ };
}
const builtPrefix = buildTruncatedTurnPrefix({
boundaryIndex,
cacheKey,
items,
+ messageStructureToken,
messages,
sessionId,
taskUpdates,
@@ -252,13 +337,57 @@ function buildTruncatedActiveTurnWindow(
? previousPrefix
: builtPrefix;
if (prefixCache) prefixCache.current = prefix;
- return { items, prefix };
+ return {
+ diffCount: countMobileRenderItemDiffs(items),
+ items,
+ prefix,
+ stablePrefixItemCount: 0,
+ };
+}
+
+function structureTokenKeepsPrefixStable(input: {
+ changedIndexes: ReadonlySet<number> | undefined;
+ messageStructureToken: object | undefined;
+ minimumChangedIndex: number;
+ previousMessageStructureToken: object | undefined;
+}): boolean {
+ if (
+ input.messageStructureToken === undefined
+ || input.changedIndexes === undefined
+ || input.previousMessageStructureToken !== input.messageStructureToken
+ ) return false;
+ for (const changedIndex of input.changedIndexes) {
+ if (changedIndex < input.minimumChangedIndex) return false;
+ }
+ return true;
+}
+
+function trustedStreamingBoundaryPrefix(input: {
+ changedIndexes: ReadonlySet<number> | undefined;
+ messageStructureToken: object | undefined;
+ previousPrefix: MobileStreamingRenderPrefixCache | null | undefined;
+ sessionId: string;
+}): MobileStreamingRenderPrefixCache | null {
+ const prefix = input.previousPrefix;
+ if (!prefix || prefix.sessionId !== input.sessionId) return null;
+ const minimumChangedIndex = prefix.mode === 'history'
+ ? prefix.messages.length + 1
+ : prefix.messages.length;
+ return structureTokenKeepsPrefixStable({
+ changedIndexes: input.changedIndexes,
+ messageStructureToken: input.messageStructureToken,
+ minimumChangedIndex,
+ previousMessageStructureToken: prefix.messageStructureToken,
+ })
+ ? prefix
+ : null;
}
function buildTruncatedTurnPrefix(input: {
boundaryIndex: number;
cacheKey: string;
items: readonly MobileMessageRenderItem[];
+ messageStructureToken?: object;
messages: readonly RemoteMessage[];
sessionId: string;
taskUpdates?: ReadonlyMap<string, AgentTaskUpdate>;
@@ -272,13 +401,16 @@ function buildTruncatedTurnPrefix(input: {
return {
boundaryMessage,
cacheKey: input.cacheKey,
+ diffCount: countMobileRenderItemDiffs(input.items.slice(0, boundaryItemIndex + 1)),
items: input.items.slice(0, boundaryItemIndex + 1),
markdownImageUrls: collectAssistantMarkdownImageUrls(prefixMessages, prefixMessages.length),
+ messageStructureToken: input.messageStructureToken,
messages: prefixMessages,
mode: 'truncated-turn',
sessionId: input.sessionId,
tailToolResults: collectDependentTailToolResults(input.messages, prefixMessages.length),
taskUpdateDependencies: collectTaskUpdateDependencies(prefixMessages, input.taskUpdates),
+ taskUpdates: input.taskUpdates,
toolUseIds: collectToolUseIds(prefixMessages, prefixMessages.length),
};
}
@@ -339,8 +471,11 @@ function omitTaskUpdatesConsumedByPrefix(
);
}
-function findLastStableAssistantBoundaryIndex(messages: readonly RemoteMessage[]): number {
- for (let index = messages.length - 2; index > 0; index -= 1) {
+function findLastStableAssistantBoundaryIndex(
+ messages: readonly RemoteMessage[],
+ minimumIndex = 1,
+): number {
+ for (let index = messages.length - 2; index >= minimumIndex; index -= 1) {
const message = messages[index];
const parentUuid = message.agentMeta?.parentUuid;
if (
diff --git a/apps/mobile/src/session/messageSearch.ts b/apps/mobile/src/session/messageSearch.ts
index 2fd983345b..b2f0f1a9ca 100644
--- a/apps/mobile/src/session/messageSearch.ts
+++ b/apps/mobile/src/session/messageSearch.ts
@@ -21,6 +21,7 @@ export function findMobileMessageSearchHits(
items: readonly MobileMessageRenderItem[],
query: string,
): MessageSearchHit[] {
+ if (!query.trim()) return [];
const hits: MessageSearchHit[] = [];
for (const item of items) {
if (item.type === 'fork_origin') {
diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.ts
index 9ea80fa8be..9dbedb8ef0 100644
--- a/apps/mobile/src/session/remoteSessionStore.ts
+++ b/apps/mobile/src/session/remoteSessionStore.ts
@@ -22,7 +22,10 @@ import {
} from '@cindy/maker-shared/agent-task';
import type { MobileGoalStatusPayload } from '@cindy/maker-shared/device-link-contract';
import { applyCodexPlanSnapshotOnDone, markCodexPlanTurnFailed } from '@cindy/maker-shared/message-render';
-import type { RemoteSessionLiveActivity } from '@cindy/maker-shared/session-list';
+import {
+ buildSessionMessagePreviewIndex,
+ type RemoteSessionLiveActivity,
+} from '@cindy/maker-shared/session-list';
import { buildDeviceIdentity, resolveCanonicalDeviceId } from '@cindy/maker-shared/mobile-home';
import {
isProductTurnDoneEvent,
@@ -584,7 +587,9 @@ const activePendingHostAnchorRoundIds = new Map<string, number>();
let nextPendingHostAnchorRoundId = 0;
let streamingFallbackSequence = 0;
const GENERATED_FALLBACK_MIN_PREFIX_LENGTH = 12;
-const TEXT_DELTA_BATCH_INTERVAL_MS = 32;
+const INITIAL_TEXT_DELTA_BATCH_INTERVAL_MS = 32;
+const VISIBLE_DETAIL_TEXT_DELTA_BATCH_INTERVAL_MS = 64;
+const BACKGROUND_TEXT_DELTA_BATCH_INTERVAL_MS = 96;
const DEVICE_LINK_TRUNCATED_FLAG = '__deviceLinkTruncated';
const pendingTextDeltaBatches = new Map<string, {
/** Keep deltas as chunks; joining once per flush avoids O(n²) string copies. */
@@ -594,6 +599,7 @@ const pendingTextDeltaBatches = new Map<string, {
agentMeta: Record<string, unknown> | null;
}>();
let textDeltaFlushTimer: ReturnType<typeof setTimeout> | null = null;
+let textDeltaFlushDeadlineAt: number | null = null;
function streamingAssistantDeviceId(
sessionId: string,
@@ -642,6 +648,11 @@ const sessionDeviceIndex = new Map<string, string>();
const pendingRefreshSessions = new Set<string>();
const reseedHandlers = new Map<string, Set<() => void>>();
const subs = new Set<() => void>();
+const homeStatusSubs = new Set<() => void>();
+const sessionMessagePreviewSubs = new Map<string, Set<() => void>>();
+const pendingMessagePreviewSessionIds = new Set<string>();
+let homeStatusNotifyPending = false;
+let notifyAllMessagePreviewsPending = false;
const emptyMessages: RemoteMessage[] = [];
const emptyPendingInteractions: PendingInteraction[] = [];
const EMPTY_TASK_UPDATES: ReadonlyMap<string, AgentTaskUpdate> = new Map();
@@ -650,8 +661,145 @@ const REGULAR_SESSION_GLOBAL_MESSAGE_BYTES_BUDGET = 64 * 1024 * 1024;
const MESSAGE_STRUCTURAL_BYTES_ESTIMATE = 512;
const MESSAGE_BYTES_ESTIMATE_LIMIT = REGULAR_SESSION_GLOBAL_MESSAGE_BYTES_BUDGET + 1;
const messageBytesEstimates = new WeakMap<RemoteMessage, number>();
+type MessageListBudgetStats = {
+ bytes: number;
+ count: number;
+ hasIntrinsicProtectedRows: boolean;
+};
+const messageListBudgetStatsCache = new WeakMap<
+ readonly RemoteMessage[],
+ MessageListBudgetStats
+>();
const sessionLastAccessOrder = new Map<string, number>();
let nextSessionAccessOrder = 0;
+const messageStructureTokens = new WeakMap<readonly RemoteMessage[], object>();
+const messageStructureChangedIndexes = new WeakMap<
+ readonly RemoteMessage[],
+ ReadonlySet<number>
+>();
+const messageIdentityIndexes = new WeakMap<
+ readonly RemoteMessage[],
+ ReadonlyMap<string, number>
+>();
+const messagePreviewCache = new WeakMap<
+ readonly RemoteMessage[],
+ { preview: string | undefined }
+>();
+const EMPTY_MESSAGE_STRUCTURE_TOKEN = Object.freeze({ kind: 'empty-message-structure' });
+const emptySessionMessageStructureTokens = new Map<string, object>();
+const EMPTY_MESSAGE_STRUCTURE_CHANGED_INDEXES: ReadonlySet<number> = new Set();
+let homeStatusVersion = 0;
+
+function messageStructureToken(list: readonly RemoteMessage[]): object {
+ if (list.length === 0) return EMPTY_MESSAGE_STRUCTURE_TOKEN;
+ return messageStructureTokens.get(list) ?? list;
+}
+
+function inheritMessageStructure(
+ previous: readonly RemoteMessage[],
+ next: readonly RemoteMessage[],
+ changedIndex: number,
+): void {
+ messageStructureTokens.set(next, messageStructureToken(previous));
+ const previousChangedIndexes = messageStructureChangedIndexes.get(previous)
+ ?? EMPTY_MESSAGE_STRUCTURE_CHANGED_INDEXES;
+ if (previousChangedIndexes.has(changedIndex)) {
+ messageStructureChangedIndexes.set(next, previousChangedIndexes);
+ return;
+ }
+ messageStructureChangedIndexes.set(next, new Set([
+ ...previousChangedIndexes,
+ changedIndex,
+ ]));
+}
+
+function messageIdentityIndex(list: readonly RemoteMessage[]): ReadonlyMap<string, number> {
+ const cached = messageIdentityIndexes.get(list);
+ if (cached) return cached;
+ const index = new Map<string, number>();
+ for (let position = 0; position < list.length; position += 1) {
+ const message = list[position];
+ if (message.id && !index.has(message.id)) index.set(message.id, position);
+ if (message.clientId && !index.has(message.clientId)) index.set(message.clientId, position);
+ }
+ messageIdentityIndexes.set(list, index);
+ return index;
+}
+
+function inheritMessageIdentityIndex(
+ previous: readonly RemoteMessage[],
+ next: readonly RemoteMessage[],
+ position: number,
+): void {
+ const cached = messageIdentityIndexes.get(previous);
+ if (!cached) return;
+ const before = previous[position];
+ const after = next[position];
+ if (before?.id !== after?.id || before?.clientId !== after?.clientId) return;
+ messageIdentityIndexes.set(next, cached);
+}
+
+function isIntrinsicMessageWindowProtectedRow(message: RemoteMessage): boolean {
+ return messageKey(message).startsWith('mobile-system-')
+ || (message.role === 'user' && !message.id);
+}
+
+function messageListBudgetStats(list: readonly RemoteMessage[]): MessageListBudgetStats {
+ const cached = messageListBudgetStatsCache.get(list);
+ if (cached) return cached;
+ let bytes = 0;
+ let hasIntrinsicProtectedRows = false;
+ for (const message of list) {
+ bytes += estimateMessageBytes(message);
+ hasIntrinsicProtectedRows ||= isIntrinsicMessageWindowProtectedRow(message);
+ }
+ const stats = { bytes, count: list.length, hasIntrinsicProtectedRows };
+ messageListBudgetStatsCache.set(list, stats);
+ return stats;
+}
+
+function inheritMessageListBudgetStats(
+ previous: readonly RemoteMessage[],
+ next: readonly RemoteMessage[],
+ position: number,
+): void {
+ const cached = messageListBudgetStatsCache.get(previous);
+ if (!cached) return;
+ const before = previous[position];
+ const after = next[position];
+ if (!before || !after) return;
+ const beforeIntrinsic = isIntrinsicMessageWindowProtectedRow(before);
+ const afterIntrinsic = isIntrinsicMessageWindowProtectedRow(after);
+ // Removing the only intrinsic protected row requires a fresh list scan to prove none remain.
+ if (beforeIntrinsic && !afterIntrinsic) return;
+ messageListBudgetStatsCache.set(next, {
+ bytes: cached.bytes - estimateMessageBytes(before) + estimateMessageBytes(after),
+ count: cached.count,
+ hasIntrinsicProtectedRows: cached.hasIntrinsicProtectedRows || afterIntrinsic,
+ });
+}
+
+function bumpHomeStatusVersion(): void {
+ homeStatusVersion += 1;
+ homeStatusNotifyPending = true;
+}
+
+function setPendingInteractionState(sessionId: string, next: PendingInteraction[]): void {
+ pendingInteractions.set(sessionId, next);
+ bumpHomeStatusVersion();
+}
+
+function deletePendingInteractionState(sessionId: string): boolean {
+ const changed = pendingInteractions.delete(sessionId);
+ if (changed) bumpHomeStatusVersion();
+ return changed;
+}
+
+function deleteSessionLiveActivity(sessionId: string): boolean {
+ const changed = sessionLiveActivity.delete(sessionId);
+ if (changed) bumpHomeStatusVersion();
+ return changed;
+}
function sessionById(sessionId: string): RemoteSession | undefined {
return mergedSessions.find((session) => session.id === sessionId);
@@ -874,14 +1022,15 @@ function invalidateSessionMessageWindowState(
function removeSessionRuntimeState(sessionId: string): void {
invalidateSessionMessageWindowState(sessionId, false);
- pendingInteractions.delete(sessionId);
+ emptySessionMessageStructureTokens.delete(sessionId);
+ deletePendingInteractionState(sessionId);
pendingInteractionsAuthoritative.delete(sessionId);
inputProjections.delete(sessionId);
inputProjectionRemoteEpochs.delete(sessionId);
inputProjectionRemoteQueuedEvidence.delete(sessionId);
bumpInputProjectionAuthorityEpoch(sessionId);
- sessionLiveActivity.delete(sessionId);
- sessionRunning.delete(sessionId);
+ deleteSessionLiveActivity(sessionId);
+ if (sessionRunning.delete(sessionId)) bumpHomeStatusVersion();
sessionRunStatus.delete(sessionId);
sessionMakerActivityEpochs.delete(sessionId);
sessionMakerTurnRunning.delete(sessionId);
@@ -1015,22 +1164,21 @@ function enforceRegularMessageBudget(): boolean {
accessOrder: number;
count: number;
bytes: number;
+ hasProtectedRows: boolean;
}> = [];
for (const [sessionId, list] of messages) {
if (retentionForSession(sessionId) !== 'regular') continue;
- const bytes = list.reduce((sum, message) => sum + estimateMessageBytes(message), 0);
- totalCount += list.length;
- totalBytes += bytes;
+ const stats = messageListBudgetStats(list);
+ totalCount += stats.count;
+ totalBytes += stats.bytes;
if (!sessionStoreProtected(sessionId)) {
- const protectedRows = list.filter((message) => isMessageWindowProtectedRow(sessionId, message));
- // LRU 是整窗淘汰;只要含无服务端副本/尚未落库的保护行,就跳过整个会话。
- // 否则保留保护行会被缓存 hook 误当成完整窗口落盘,反而覆盖磁盘上的最新页。
- if (protectedRows.length > 0) continue;
candidates.push({
sessionId,
accessOrder: sessionLastAccessOrder.get(sessionId) ?? 0,
- count: list.length,
- bytes,
+ count: stats.count,
+ bytes: stats.bytes,
+ hasProtectedRows: stats.hasIntrinsicProtectedRows
+ || (pendingLiveAssistantClientIds.get(sessionId)?.size ?? 0) > 0,
});
}
}
@@ -1045,7 +1193,11 @@ function enforceRegularMessageBudget(): boolean {
totalCount <= REGULAR_SESSION_GLOBAL_MESSAGE_BUDGET
&& totalBytes <= REGULAR_SESSION_GLOBAL_MESSAGE_BYTES_BUDGET
) break;
+ // LRU 是整窗淘汰;只要含无服务端副本/尚未落库的保护行,就跳过整个会话。
+ // 标志来自消息数组缓存与 pending identity,不再为每次流式文本重复扫描整窗。
+ if (candidate.hasProtectedRows) continue;
if (!messages.delete(candidate.sessionId)) continue;
+ pendingMessagePreviewSessionIds.add(candidate.sessionId);
forgetWindowCoverage(candidate.sessionId);
sessionLiveStreamAcked.delete(candidate.sessionId);
releaseSessionDetailProjections(candidate.sessionId);
@@ -1166,8 +1318,30 @@ let conversationSearchDeviceModels: readonly {
}[] = [];
function emitNow(): void {
+ const notifyHomeStatus = homeStatusNotifyPending;
+ const notifyAllMessagePreviews = notifyAllMessagePreviewsPending;
+ const changedPreviewSessionIds = [...pendingMessagePreviewSessionIds];
+ homeStatusNotifyPending = false;
+ notifyAllMessagePreviewsPending = false;
+ pendingMessagePreviewSessionIds.clear();
storeVersion += 1;
for (const sub of subs) sub();
+ if (notifyHomeStatus) {
+ for (const sub of homeStatusSubs) sub();
+ }
+ const previewCallbacks = new Set<() => void>();
+ if (notifyAllMessagePreviews) {
+ for (const sessionSubs of sessionMessagePreviewSubs.values()) {
+ for (const sub of sessionSubs) previewCallbacks.add(sub);
+ }
+ } else {
+ for (const sessionId of changedPreviewSessionIds) {
+ for (const sub of sessionMessagePreviewSubs.get(sessionId) ?? []) {
+ previewCallbacks.add(sub);
+ }
+ }
+ }
+ for (const sub of previewCallbacks) sub();
}
function emit(): void {
@@ -1300,7 +1474,7 @@ function recomputeSessions(): void {
sessionDeviceIndex.set(session.id, physicalDeviceId);
}
for (const sessionId of [...sessionLiveActivity.keys()]) {
- if (!sessionDeviceIndex.has(sessionId)) sessionLiveActivity.delete(sessionId);
+ if (!sessionDeviceIndex.has(sessionId)) deleteSessionLiveActivity(sessionId);
}
// 预览不因列表短暂缺席回收:旧 sessions:list 可能在远端建会话前发出、入队成功后才回来。
// 权威标题落地、明确失败撤回、归档/删除、设备移除、clear() 才会丢掉。
@@ -1327,7 +1501,7 @@ function recomputeSessions(): void {
if (!remoteMessageListsEqual(current, trimmed)) {
messages.set(session.id, trimmed);
forgetWindowCoverage(session.id);
- bumpMessageVersion();
+ bumpMessageVersion(session.id);
}
} else {
sessionMessageLifecycle.leave(session.id, 'session-switch');
@@ -1523,7 +1697,7 @@ function applyLivePlanToolUseMessage(
const next = [...existing];
next[targetIndex] = { ...current, content, toolUseId };
messages.set(sessionId, next);
- bumpMessageVersion();
+ bumpMessageVersion(sessionId);
return { handled: true, changed: true };
}
@@ -2119,7 +2293,7 @@ function migrateGeneratedStreamingClientId(sessionId: string, generatedClientId:
if (targetIndex >= 0) next.splice(generatedIndex, 1);
else next[generatedIndex] = migrated;
messages.set(sessionId, normalizeMessages(next));
- bumpMessageVersion();
+ bumpMessageVersion(sessionId);
return true;
}
@@ -2147,13 +2321,22 @@ function upsertMessage(
sessionId: string,
message: RemoteMessage,
options: {
+ /** Caller already resolved this exact identity in the current message array. */
+ knownIndex?: number;
retirePendingAssistantIdentityOnEqual?: boolean;
+ /** A streaming text replacement changes row content but not list structure or identities. */
+ preserveStructureOnReplace?: 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));
+ const candidateIndex = options.knownIndex ?? -1;
+ const index = candidateIndex >= 0
+ && candidateIndex < existing.length
+ && messageIdentityMatches(existing[candidateIndex], message)
+ ? candidateIndex
+ : existing.findIndex((item) => messageIdentityMatches(item, message));
let fallbackIndex = -1;
if (index < 0 && isPersistedAssistantMessage(message)) {
fallbackIndex = findPendingGeneratedStreamingFallbackIndex(sessionId, existing);
@@ -2168,7 +2351,7 @@ function upsertMessage(
messages.set(sessionId, normalizeMessages(next));
applyMessageWriteRetention(sessionId);
retireGeneratedStreamingFallback(sessionId);
- bumpMessageVersion();
+ bumpMessageVersion(sessionId);
return true;
}
}
@@ -2178,7 +2361,7 @@ function upsertMessage(
if (isPersistedAssistantMessage(message) && fallbackIndex < 0) {
retireGeneratedStreamingFallback(sessionId);
}
- bumpMessageVersion();
+ bumpMessageVersion(sessionId);
return true;
}
const replacement = preferCompleteMessage(existing[index], message);
@@ -2210,10 +2393,13 @@ function upsertMessage(
// 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),
- );
+ const committed = options.preserveOrderOnReplace ? next : normalizeMessages(next);
+ if (options.preserveStructureOnReplace) inheritMessageStructure(existing, committed, index);
+ if (options.preserveOrderOnReplace) {
+ inheritMessageIdentityIndex(existing, committed, index);
+ inheritMessageListBudgetStats(existing, committed, index);
+ }
+ messages.set(sessionId, committed);
applyMessageWriteRetention(sessionId);
if (message.role === 'assistant') {
forgetPendingLiveAssistantMessageIdentity(
@@ -2225,10 +2411,20 @@ function upsertMessage(
);
if (isPersistedAssistantMessage(message)) retireGeneratedStreamingFallback(sessionId);
}
- bumpMessageVersion();
+ bumpMessageVersion(sessionId);
return true;
}
+function findMessageIndexByIdentity(
+ list: readonly RemoteMessage[],
+ id: string,
+): number {
+ const tailIndex = list.length - 1;
+ const tail = list[tailIndex];
+ if (tail && (tail.id === id || tail.clientId === id)) return tailIndex;
+ return messageIdentityIndex(list).get(id) ?? -1;
+}
+
function applyRemoteTextEvent(
sessionId: string,
event: Record<string, unknown>,
@@ -2245,9 +2441,8 @@ function applyRemoteTextEvent(
const hasAuthoritativePendingAssembly = authoritativeDeviceId !== undefined
&& [...(streamingAssistantDeviceIds.get(sessionId) ?? [])].some(([ownedClientId, ownerDeviceId]) => {
if (ownerDeviceId !== authoritativeDeviceId) return false;
- const ownedMessage = currentMessages.find((message) => (
- message.id === ownedClientId || message.clientId === ownedClientId
- ));
+ const ownedIndex = findMessageIndexByIdentity(currentMessages, ownedClientId);
+ const ownedMessage = ownedIndex >= 0 ? currentMessages[ownedIndex] : undefined;
if (!ownedMessage || !isPendingLiveAssistantMessage(sessionId, ownedMessage)) return false;
const ownedHostAnchorIdentity = pendingHostAnchorIdentity(
sessionId,
@@ -2277,7 +2472,11 @@ function applyRemoteTextEvent(
const clientIdResolution = streamingClientIdFor(sessionId, persistId);
const { clientId } = clientIdResolution;
const previousStreamingDeviceId = streamingAssistantDeviceId(sessionId, clientId);
- const matchedExisting = messages.get(sessionId)?.find((message) => message.clientId === clientId);
+ const currentAfterClientIdResolution = messages.get(sessionId) ?? [];
+ const matchedExistingIndex = findMessageIndexByIdentity(currentAfterClientIdResolution, clientId);
+ const matchedExisting = matchedExistingIndex >= 0
+ ? currentAfterClientIdResolution[matchedExistingIndex]
+ : undefined;
const matchedHostAnchorIdentity = matchedExisting
? pendingHostAnchorIdentity(
sessionId,
@@ -2420,7 +2619,11 @@ function applyRemoteTextEvent(
new Date().toISOString(),
hostCreatedAtAnchor?.createdAt,
),
- }, { preserveOrderOnReplace: true });
+ }, {
+ knownIndex: matchedExistingIndex,
+ preserveOrderOnReplace: true,
+ preserveStructureOnReplace: !isFinal && existing !== undefined,
+ });
if (resetsTransportAssembly && !changed) {
forgetPendingLiveAssistantMessageIdentity(
sessionId,
@@ -2497,7 +2700,7 @@ function enqueueRemoteTextDelta(
agentMeta: incomingMeta,
});
}
- scheduleTextDeltaFlush();
+ scheduleTextDeltaFlush(sessionId);
return changed;
}
@@ -2551,18 +2754,33 @@ function flushPendingTextDeltas(): void {
if (changed) emit();
}
-function scheduleTextDeltaFlush(): void {
- if (textDeltaFlushTimer !== null) return;
+function scheduleTextDeltaFlush(sessionId: string): void {
+ const hasFlushedLiveAssistant = (pendingLiveAssistantClientIds.get(sessionId)?.size ?? 0) > 0;
+ const delayMs = !hasFlushedLiveAssistant
+ ? INITIAL_TEXT_DELTA_BATCH_INTERVAL_MS
+ : sessionMessageLifecycle.isVisible(sessionId)
+ ? VISIBLE_DETAIL_TEXT_DELTA_BATCH_INTERVAL_MS
+ : BACKGROUND_TEXT_DELTA_BATCH_INTERVAL_MS;
+ const deadlineAt = Date.now() + delayMs;
+ if (
+ textDeltaFlushTimer !== null
+ && textDeltaFlushDeadlineAt !== null
+ && textDeltaFlushDeadlineAt <= deadlineAt
+ ) return;
+ if (textDeltaFlushTimer !== null) clearTimeout(textDeltaFlushTimer);
+ textDeltaFlushDeadlineAt = deadlineAt;
textDeltaFlushTimer = setTimeout(() => {
textDeltaFlushTimer = null;
+ textDeltaFlushDeadlineAt = null;
flushPendingTextDeltas();
- }, TEXT_DELTA_BATCH_INTERVAL_MS);
+ }, Math.max(0, deadlineAt - Date.now()));
}
function clearTextDeltaFlushTimer(): void {
if (textDeltaFlushTimer === null) return;
clearTimeout(textDeltaFlushTimer);
textDeltaFlushTimer = null;
+ textDeltaFlushDeadlineAt = null;
}
function discardPendingTextDelta(sessionId: string): void {
@@ -2588,7 +2806,7 @@ function finalizeRemoteStreamingMessageByClientId(
});
if (!changed) return false;
messages.set(sessionId, next);
- bumpMessageVersion();
+ bumpMessageVersion(sessionId);
return true;
}
@@ -2613,12 +2831,14 @@ function finalizeRemoteStreamingMessages(
});
if (!changed) return false;
messages.set(sessionId, next);
- bumpMessageVersion();
+ bumpMessageVersion(sessionId);
return true;
}
-function bumpMessageVersion(): void {
+function bumpMessageVersion(sessionId?: string): void {
messageVersion += 1;
+ if (sessionId === undefined) notifyAllMessagePreviewsPending = true;
+ else pendingMessagePreviewSessionIds.add(sessionId);
}
// turn start 时暂存的 running codex collab worker 条目:map key → update。核心不变量是
@@ -2767,7 +2987,7 @@ export const remoteSessionStore = {
const changed = invalidateSessionMessageWindowState(sessionId, true);
clearSessionMessageCache(sessionId, deviceId);
if (changed) {
- bumpMessageVersion();
+ bumpMessageVersion(sessionId);
emit();
}
},
@@ -2815,7 +3035,7 @@ export const remoteSessionStore = {
const changed = reclaimScheduleRuntimeMaps(sessionId);
clearSessionMessageCache(sessionId);
if (changed) {
- bumpMessageVersion();
+ bumpMessageVersion(sessionId);
emit();
}
return true;
@@ -2980,13 +3200,13 @@ export const remoteSessionStore = {
let shouldReseedAfterPatch = false;
if (patch.status === 'deleted' || patch.status === 'archived') {
shard.sessions = shard.sessions.filter((s) => s.id !== sessionId);
- sessionLiveActivity.delete(sessionId);
+ deleteSessionLiveActivity(sessionId);
dropPendingTitlePreview(sessionId);
let messageStateChanged = invalidateSessionMessageWindowState(sessionId, false);
messageStateChanged = releaseSessionDetailProjections(sessionId) || messageStateChanged;
sessionMessageLifecycle.forget(sessionId);
if (patch.status === 'deleted') clearSessionMessageCache(sessionId, deviceId);
- if (messageStateChanged) bumpMessageVersion();
+ if (messageStateChanged) bumpMessageVersion(sessionId);
} else {
const wasPinned = shard.sessions[idx].pinnedAt != null;
const unpinned = Object.prototype.hasOwnProperty.call(patch, 'pinnedAt') && patch.pinnedAt == null;
@@ -3022,7 +3242,7 @@ export const remoteSessionStore = {
}
messages.set(sessionId, next);
applyMessageWriteRetention(sessionId);
- bumpMessageVersion();
+ bumpMessageVersion(sessionId);
emit();
},
@@ -3048,7 +3268,7 @@ export const remoteSessionStore = {
}
messages.set(sessionId, next);
applyMessageWriteRetention(sessionId);
- bumpMessageVersion();
+ bumpMessageVersion(sessionId);
emit();
},
@@ -3080,7 +3300,7 @@ export const remoteSessionStore = {
messages.set(sessionId, next);
applyMessageWriteRetention(sessionId);
if (next.length === 0) clearSessionMessageCache(sessionId);
- bumpMessageVersion();
+ bumpMessageVersion(sessionId);
emit();
} else if (textFlushed || projectionSettled) {
emit();
@@ -3236,7 +3456,7 @@ export const remoteSessionStore = {
consumePending: consumeReanchorAfterMerge,
},
);
- if (liveRowsReanchoredBeforeMerge || liveRowsReanchoredAfterMerge) bumpMessageVersion();
+ if (liveRowsReanchoredBeforeMerge || liveRowsReanchoredAfterMerge) bumpMessageVersion(sessionId);
if (textFlushed || liveRowsReanchoredBeforeMerge || liveRowsReanchoredAfterMerge) emit();
return;
}
@@ -3254,7 +3474,7 @@ export const remoteSessionStore = {
);
}
applyMessageWriteRetention(sessionId);
- bumpMessageVersion();
+ bumpMessageVersion(sessionId);
emit();
},
@@ -3317,7 +3537,7 @@ export const remoteSessionStore = {
}
messages.set(sessionId, next);
applyMessageWriteRetention(sessionId);
- bumpMessageVersion();
+ bumpMessageVersion(sessionId);
emit();
},
@@ -3364,7 +3584,7 @@ export const remoteSessionStore = {
{ consumePending: false },
)
) {
- bumpMessageVersion();
+ bumpMessageVersion(sessionId);
changed = true;
}
changed = upsertMessage(
@@ -3384,7 +3604,7 @@ export const remoteSessionStore = {
},
)
) {
- bumpMessageVersion();
+ bumpMessageVersion(sessionId);
changed = true;
}
// 订阅内到达的实时行可以把覆盖区间的上界往后推;断流后收到的不行(见 liveTailTrusted)。
@@ -3483,7 +3703,7 @@ export const remoteSessionStore = {
applyMessageWriteRetention(sessionId);
}
if (!messagesChanged && !tasksChanged && !projectionSettled) return;
- bumpMessageVersion();
+ bumpMessageVersion(sessionId);
emit();
},
@@ -3574,7 +3794,7 @@ export const remoteSessionStore = {
if (streamingChanged || authorityChanged) emit();
return;
}
- pendingInteractions.set(sessionId, next);
+ setPendingInteractionState(sessionId, next);
emit();
},
@@ -3755,7 +3975,7 @@ export const remoteSessionStore = {
if (streamingChanged || reconnectCleared) emit();
return;
}
- pendingInteractions.set(sessionId, next);
+ setPendingInteractionState(sessionId, next);
emit();
},
@@ -3763,7 +3983,7 @@ export const remoteSessionStore = {
const existing = pendingInteractions.get(sessionId) ?? [];
const next = existing.filter((i) => i.request.requestId !== requestId);
if (next.length === existing.length) return;
- pendingInteractions.set(sessionId, next);
+ setPendingInteractionState(sessionId, next);
if (next.length === 0) sessionMessageLifecycle.retryPendingReclaim(sessionId);
emit();
},
@@ -3826,7 +4046,7 @@ export const remoteSessionStore = {
const next = existing.filter((item) => item.request.requestId !== requestId
|| !isInteractionResolveSuppressed(sessionId, item));
if (next.length === existing.length) return;
- pendingInteractions.set(sessionId, next);
+ setPendingInteractionState(sessionId, next);
if (next.length === 0) sessionMessageLifecycle.retryPendingReclaim(sessionId);
emit();
},
@@ -3935,7 +4155,7 @@ export const remoteSessionStore = {
forgetWindowCoverage(sessionId);
pendingRefreshSessions.add(sessionId);
}
- bumpMessageVersion();
+ bumpMessageVersion(sessionId);
emit();
}
return;
@@ -4143,7 +4363,7 @@ export const remoteSessionStore = {
attention: true,
}) || changed;
} else {
- changed = sessionLiveActivity.delete(sessionId) || changed;
+ changed = deleteSessionLiveActivity(sessionId) || changed;
}
// 权威 idle 恢复路径(completed / error 活动推送)同步关闭 maker turn 边界(只关不开):
// 后台/断连错过终态 maker 事件后,边界会卡在 true、孤儿渲染 gate 常开,stale 得以重放。
@@ -4261,7 +4481,7 @@ export const remoteSessionStore = {
isRecord(event.agentMeta) ? event.agentMeta : null,
);
if (terminalPlanChanged) {
- bumpMessageVersion();
+ bumpMessageVersion(sessionId);
emit();
}
return;
@@ -4372,7 +4592,7 @@ export const remoteSessionStore = {
systemCardData: data,
},
]));
- bumpMessageVersion();
+ bumpMessageVersion(sessionId);
emit();
return;
}
@@ -4496,12 +4716,12 @@ export const remoteSessionStore = {
changed = sessionMessageSyncMarkers.delete(sessionId) || changed;
changed = livePlanSnapshots.delete(sessionId) || changed;
changed = pendingRefreshSessions.delete(sessionId) || changed;
- changed = pendingInteractions.delete(sessionId) || changed;
+ changed = deletePendingInteractionState(sessionId) || changed;
// 投影没了,这份(空)列表就不再权威:重连拿到全量快照前不许据此做清理。
changed = pendingInteractionsAuthoritative.delete(sessionId) || changed;
changed = invalidateInputProjectionForOffline(sessionId) || changed;
bumpInputProjectionAuthorityEpoch(sessionId);
- changed = sessionLiveActivity.delete(sessionId) || changed;
+ changed = deleteSessionLiveActivity(sessionId) || changed;
changed = sessionGoalStatus.delete(sessionId) || changed;
changed = sessionTaskUpdates.delete(sessionId) || changed;
changed = sessionParkedTaskUpdates.delete(sessionId) || changed;
@@ -4608,8 +4828,12 @@ export const remoteSessionStore = {
newMakerWorktreePreferences.clear();
newMakerWorktreeBranchPreferences.clear();
messages.clear();
+ emptySessionMessageStructureTokens.clear();
livePlanSnapshots.clear();
- pendingInteractions.clear();
+ if (pendingInteractions.size > 0) {
+ pendingInteractions.clear();
+ bumpHomeStatusVersion();
+ }
pendingInteractionsAuthoritative.clear();
inFlightInteractionResolves.clear();
confirmedInteractionDismissals.clear();
@@ -4622,8 +4846,11 @@ export const remoteSessionStore = {
inputProjectionRemoteQueuedEvidence.clear();
// Keep authority tombstones monotonic across a global store reset so an
// old in-flight query cannot be accepted after the session is recreated.
- sessionLiveActivity.clear();
- sessionRunning.clear();
+ if (sessionLiveActivity.size > 0 || sessionRunning.size > 0) {
+ sessionLiveActivity.clear();
+ sessionRunning.clear();
+ bumpHomeStatusVersion();
+ }
sessionRunStatus.clear();
sessionMakerActivityEpochs.clear();
makerActivityEpoch = 0;
@@ -4687,6 +4914,37 @@ export const remoteSessionStore = {
return messages.get(sessionId) ?? emptyMessages;
},
+ /**
+ * Stable across ordinary streaming text replacements. Consumers use this to keep structural
+ * transcript projections out of the per-token render path. Any append, prepend, reset, final
+ * transition, or authoritative rewrite naturally receives a new token.
+ */
+ getSessionMessageStructureToken(sessionId: string): object {
+ const list = messages.get(sessionId) ?? emptyMessages;
+ if (list.length > 0) return messageStructureToken(list);
+ const existing = emptySessionMessageStructureTokens.get(sessionId);
+ if (existing) return existing;
+ const token = Object.freeze({ kind: 'empty-message-structure', sessionId });
+ emptySessionMessageStructureTokens.set(sessionId, token);
+ return token;
+ },
+
+ /** Distinct content-only replacement positions accumulated under the current structure token. */
+ getSessionMessageStructureChangedIndexes(sessionId: string): ReadonlySet<number> {
+ return messageStructureChangedIndexes.get(messages.get(sessionId) ?? emptyMessages)
+ ?? EMPTY_MESSAGE_STRUCTURE_CHANGED_INDEXES;
+ },
+
+ /** Latest loaded user/assistant preview, cached by the session's message-array identity. */
+ getSessionMessagePreview(sessionId: string): string | undefined {
+ const list = messages.get(sessionId) ?? emptyMessages;
+ const cached = messagePreviewCache.get(list);
+ if (cached) return cached.preview;
+ const preview = buildSessionMessagePreviewIndex([sessionId], () => list).get(sessionId);
+ messagePreviewCache.set(list, { preview });
+ return preview;
+ },
+
getMessageVersion(): number {
return messageVersion;
},
@@ -4695,6 +4953,10 @@ export const remoteSessionStore = {
return storeVersion;
},
+ getHomeStatusVersion(): number {
+ return homeStatusVersion;
+ },
+
setNewMakerWorktreePreference(deviceId: string, enabled: boolean): void {
if (!deviceId) return;
const current = newMakerWorktreePreferences.get(deviceId);
@@ -4822,6 +5084,21 @@ export const remoteSessionStore = {
subs.add(cb);
return () => subs.delete(cb);
},
+
+ subscribeHomeStatus(cb: () => void): () => void {
+ homeStatusSubs.add(cb);
+ return () => homeStatusSubs.delete(cb);
+ },
+
+ subscribeSessionMessagePreview(sessionId: string, cb: () => void): () => void {
+ const listeners = sessionMessagePreviewSubs.get(sessionId) ?? new Set<() => void>();
+ listeners.add(cb);
+ sessionMessagePreviewSubs.set(sessionId, listeners);
+ return () => {
+ listeners.delete(cb);
+ if (listeners.size === 0) sessionMessagePreviewSubs.delete(sessionId);
+ };
+ },
};
sessionMessageLifecycle.setReclaimer((sessionId, reason) =>
@@ -5000,12 +5277,14 @@ function writeSessionRunStatus(sessionId: string, next: RemoteSessionRunStatus):
if (shallowRecordEqual(current as unknown as Record<string, unknown>, next as unknown as Record<string, unknown>)) {
return false;
}
+ const wasRunning = sessionRunning.get(sessionId) === true;
sessionRunStatus.set(sessionId, next);
if (next.isRunning) sessionRunning.set(sessionId, true);
else {
sessionRunning.delete(sessionId);
sessionMessageLifecycle.retryPendingReclaim(sessionId);
}
+ if (wasRunning !== next.isRunning) bumpHomeStatusVersion();
return true;
}
@@ -5035,6 +5314,7 @@ function writeSessionLiveActivity(sessionId: string, next: RemoteSessionLiveActi
return false;
}
sessionLiveActivity.set(sessionId, next);
+ bumpHomeStatusVersion();
return true;
}
@@ -5190,6 +5470,7 @@ export function RemoteSessionStoreSubscriptionGate({
function usePausableRemoteSessionStoreSnapshot<T>(
identity: unknown,
getSnapshot: () => T,
+ subscribe: (cb: () => void) => () => void = remoteSessionStore.subscribe,
): T {
const enabled = useContext(RemoteSessionStoreSubscriptionEnabledContext);
const frozenSnapshotRef = useRef<{ identity: unknown; value: T } | null>(null);
@@ -5203,7 +5484,7 @@ function usePausableRemoteSessionStoreSnapshot<T>(
return frozen.value;
}, [enabled, getSnapshot, identity]);
return useSyncExternalStore(
- enabled ? remoteSessionStore.subscribe : INACTIVE_REMOTE_SESSION_STORE_SUBSCRIBE,
+ enabled ? subscribe : INACTIVE_REMOTE_SESSION_STORE_SUBSCRIBE,
readSnapshot,
);
}
@@ -5220,6 +5501,19 @@ export function useRemoteSessionMessages(sessionId: string): RemoteMessage[] {
);
}
+/** Subscribe to one session's loaded message preview without waking the home-list root. */
+export function useRemoteSessionMessagePreview(sessionId: string): string | undefined {
+ const subscribe = useCallback(
+ (cb: () => void) => remoteSessionStore.subscribeSessionMessagePreview(sessionId, cb),
+ [sessionId],
+ );
+ return usePausableRemoteSessionStoreSnapshot(
+ `message-preview:${sessionId}`,
+ useCallback(() => remoteSessionStore.getSessionMessagePreview(sessionId), [sessionId]),
+ subscribe,
+ );
+}
+
// 本地「最近消息」缓存持久化的去抖间隔:消息流式更新很频繁,只在静默一小段后落盘一次。
const SESSION_MESSAGE_CACHE_PERSIST_DEBOUNCE_MS = 600;
@@ -5325,10 +5619,22 @@ function useSessionMessageCacheSync(
}, []);
}
-export function useRemoteMessageVersion(): number {
+export function useRemoteMessageVersion(enabled = true): number {
+ return usePausableRemoteSessionStoreSnapshot(
+ enabled ? 'message-version' : 'message-version-disabled',
+ useCallback(
+ () => enabled ? remoteSessionStore.getMessageVersion() : 0,
+ [enabled],
+ ),
+ );
+}
+
+/** Home-list invalidation for pending/live/running state; ordinary text deltas do not advance it. */
+export function useRemoteHomeStatusVersion(): number {
return usePausableRemoteSessionStoreSnapshot(
- 'message-version',
- remoteSessionStore.getMessageVersion,
+ 'home-status-version',
+ remoteSessionStore.getHomeStatusVersion,
+ remoteSessionStore.subscribeHomeStatus,
);
}
@@ -5383,6 +5689,7 @@ export function useSessionRunning(sessionId: string): boolean {
return usePausableRemoteSessionStoreSnapshot(
sessionId,
() => remoteSessionStore.isSessionRunning(sessionId),
+ remoteSessionStore.subscribeHomeStatus,
);
}