Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): keep message list anchored after send (#3192)
hushaowu-rh816a35a59f72
diff --git a/apps/mobile/src/__tests__/messageListVirtualization.test.ts b/apps/mobile/src/__tests__/messageListVirtualization.test.tsindex 0e36114a05..7020047d50 100644--- a/apps/mobile/src/__tests__/messageListVirtualization.test.ts+++ b/apps/mobile/src/__tests__/messageListVirtualization.test.ts@@ -56,6 +56,86 @@ describe('mobile message list container', () => {expect(source).toContain('evaluateMobileAnchorVerify({');expect(source).toContain('initialAnchorVerifyFrameRef');expect(source).toContain('scrollToEndProgrammatically(false)');+ // mVCP 对 data / size 都常开;普通尾部追加与流式 resize 必须先记 settle 安静窗,+ // 两套 verifier 都不能再只依赖 readingOlderRef 判断是否等待。+ expect(source).toContain('mvcpSettleAtRef.current = mobileMvcpSettleDeadline(');+ expect(source).toContain('markMobileMvcpSettle();');+ expect(source.match(/isMobileMvcpSettling\(Date\.now\(\), mvcpSettleAtRef\.current\)/g))+ .toHaveLength(2);+ });++ it('clears stale history intent before verifying an explicit follow-latest request', () => {+ const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');+ const effectStart = source.indexOf('// 「跳到最新」请求');+ const effectEnd = source.indexOf('// 自动加载更早', effectStart);+ const effectSource = source.slice(effectStart, effectEnd);+ const clearHistoryIntentAt = effectSource.indexOf('userScrollForOlderRef.current = false');+ const verifyAt = effectSource.indexOf('runStickToLatestVerify();');++ expect(effectStart).toBeGreaterThan(-1);+ expect(effectEnd).toBeGreaterThan(effectStart);+ expect(clearHistoryIntentAt).toBeGreaterThan(-1);+ expect(verifyAt).toBeGreaterThan(clearHistoryIntentAt);+ });++ it('verifies a manual jump-to-latest after issuing the animated scroll', () => {+ const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');+ const callbackStart = source.indexOf('const scrollToBottom = useCallback');+ const callbackEnd = source.indexOf('const jumpToPreviousUserMessage', callbackStart);+ const callbackSource = source.slice(callbackStart, callbackEnd);+ const scrollAt = callbackSource.indexOf('scrollToEndProgrammatically(true);');+ const verifyAt = callbackSource.indexOf('runStickToLatestVerify();');++ expect(callbackStart).toBeGreaterThan(-1);+ expect(callbackEnd).toBeGreaterThan(callbackStart);+ expect(scrollAt).toBeGreaterThan(-1);+ expect(verifyAt).toBeGreaterThan(scrollAt);+ expect(callbackSource).toContain(+ '}, [runStickToLatestVerify, scrollToEndProgrammatically]);',+ );+ });++ it('waits for an animated follow scroll to settle before issuing non-animated verification retries', () => {+ const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');+ const verifyStart = source.indexOf('const runStickToLatestVerify = useCallback');+ const verifyEnd = source.indexOf('// DEV-only:', verifyStart);+ const verifySource = source.slice(verifyStart, verifyEnd);+ const contentSizeStart = source.indexOf('const handleContentSize = useCallback');+ const contentSizeEnd = source.indexOf('// 冷开落底', contentSizeStart);+ const contentSizeSource = source.slice(contentSizeStart, contentSizeEnd);++ expect(verifySource).toContain('mobileFollowVerifyStartDelayMs({');+ expect(verifySource).toContain('followVerifyTimerRef.current = setTimeout');+ expect(contentSizeSource).toContain('if (programmaticAnimatedScrollInFlightRef.current)');+ expect(contentSizeSource.indexOf('if (programmaticAnimatedScrollInFlightRef.current)'))+ .toBeLessThan(contentSizeSource.indexOf('scrollToEndProgrammatically(false)'));+ });++ it('clears stale history intent when a manual downward scroll re-pins at the bottom', () => {+ const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');+ const scrollStart = source.indexOf('// 近底/跟随态迁移');+ const scrollEnd = source.indexOf('// 用户开始拖动', scrollStart);+ const scrollSource = source.slice(scrollStart, scrollEnd);++ expect(scrollStart).toBeGreaterThan(-1);+ expect(scrollEnd).toBeGreaterThan(scrollStart);+ expect(scrollSource).toContain('const wasNearBottom = nearBottomRef.current');+ expect(scrollSource).toContain('if (!wasNearBottom && nearBottom && scrollDelta > 0)');+ expect(scrollSource).toContain('userScrollForOlderRef.current = false');+ });++ it('keeps follow verification enabled for a dead-zone drag that never actually unpins', () => {+ const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');+ const verifyStart = source.indexOf('const runStickToLatestVerify');+ const verifyEnd = source.indexOf('// DEV-only:', verifyStart);+ const verifySource = source.slice(verifyStart, verifyEnd);++ expect(verifyStart).toBeGreaterThan(-1);+ expect(verifyEnd).toBeGreaterThan(verifyStart);+ expect(verifySource).toContain('stickToLatest: nearBottomRef.current');+ expect(verifySource).not.toContain(+ 'stickToLatest: nearBottomRef.current && !userScrollForOlderRef.current',+ );});it('measures every mounted shareable message, including expanded group children', () => {diff --git a/apps/mobile/src/__tests__/messageScroll.test.ts b/apps/mobile/src/__tests__/messageScroll.test.tsindex 1a0a58f6ed..7feb13dfe9 100644--- a/apps/mobile/src/__tests__/messageScroll.test.ts+++ b/apps/mobile/src/__tests__/messageScroll.test.ts@@ -9,12 +9,19 @@ import {buildSearchLoadEarlierAction,createMobileFollowEndPinState,DEFAULT_NEAR_BOTTOM_THRESHOLD,+ evaluateMobileAnchorVerify,evaluateMobileFollowEndContentSizePin,findMobileRenderItemKeyByClientId,firstNonEmptyMessageLine,isNearMessageListBottom,isNearMobileMessageListBottom,isNearMessageListTop,+ isMobileMvcpSettling,+ mobileFollowVerifyStartDelayMs,+ mobileMvcpSettleDeadline,+ MOBILE_ANCHOR_VERIFY_MAX_ATTEMPTS,+ MOBILE_ANCHOR_VERIFY_MAX_WAIT_ROUNDS,+ MOBILE_ANCHOR_VERIFY_TOLERANCE,MOBILE_FOLLOW_END_PIN_HEIGHT_DEAD_ZONE,MOBILE_FOLLOW_END_PIN_MAX_REVERSALS_PER_WINDOW,MOBILE_FOLLOW_END_PIN_SUPPRESS_MS,@@ -33,6 +40,7 @@ import {mobileTopPaddingCompensationOffset,MOBILE_FOLLOW_REPIN_DIRECTION_DEAD_ZONE,MOBILE_FOLLOW_UNPIN_DRAG_DEAD_ZONE,+ MOBILE_MVCP_SETTLE_QUIET_MS,resolveMobileNearBottomOnScroll,shouldUnpinMobileFollowOnDrag,} from '@/session/messageScroll';@@ -641,3 +649,130 @@ describe('evaluateMobileFollowEndContentSizePin (贴底补滚振荡断路器)',expect(state.reversalTimestamps).toEqual([3000]);});});++describe('evaluateMobileAnchorVerify (落底校验/补滚有界重试环——冷开锚定与贴底跟随共用同一判定)', () => {+ // 视口 800,内容 2000 → endOffset = 1200。+ const metricsAt = (offsetY: number) => ({ contentHeight: 2000, offsetY, viewportHeight: 800 });+ const baseInput = {+ attempts: 0,+ listVisible: true,+ preserveVisibleContentPosition: false,+ stickToLatest: true,+ waitRounds: 0,+ };++ it('未处于贴底跟随意图(用户已解除/翻到旧消息)→ 直接 settled,不发起补滚', () => {+ expect(evaluateMobileAnchorVerify({+ ...baseInput, stickToLatest: false, metrics: metricsAt(0),+ })).toBe('settled');+ });++ it('列表尚未可见(如切换会话中)→ 直接 settled', () => {+ expect(evaluateMobileAnchorVerify({+ ...baseInput, listVisible: false, metrics: metricsAt(0),+ })).toBe('settled');+ });++ it('已落在容差带内 → settled(容差边界 offsetY === endOffset - TOLERANCE 视为已达)', () => {+ expect(evaluateMobileAnchorVerify({+ ...baseInput, metrics: metricsAt(1200),+ })).toBe('settled');+ expect(evaluateMobileAnchorVerify({+ ...baseInput, metrics: metricsAt(1200 - MOBILE_ANCHOR_VERIFY_TOLERANCE),+ })).toBe('settled');+ });++ it('偏移仍差着容差带 → retry(容差边界外 1px 即触发重试)', () => {+ expect(evaluateMobileAnchorVerify({+ ...baseInput, metrics: metricsAt(1200 - MOBILE_ANCHOR_VERIFY_TOLERANCE - 1),+ })).toBe('retry');+ expect(evaluateMobileAnchorVerify({+ ...baseInput, metrics: metricsAt(0),+ })).toBe('retry');+ });++ it('重试次数达到上限后仍未落底 → give-up(不无限重试)', () => {+ expect(evaluateMobileAnchorVerify({+ ...baseInput, attempts: MOBILE_ANCHOR_VERIFY_MAX_ATTEMPTS, metrics: metricsAt(0),+ })).toBe('give-up');+ // 上限前一次仍是 retry。+ expect(evaluateMobileAnchorVerify({+ ...baseInput, attempts: MOBILE_ANCHOR_VERIFY_MAX_ATTEMPTS - 1, metrics: metricsAt(0),+ })).toBe('retry');+ });++ it('mVCP 仍开着(preserveVisibleContentPosition)→ wait,不在其吸收滚动的窗口内瞎重试', () => {+ expect(evaluateMobileAnchorVerify({+ ...baseInput, preserveVisibleContentPosition: true, metrics: metricsAt(0),+ })).toBe('wait');+ });++ it('原生 metrics 尚未结算(contentHeight/viewportHeight <= 0)→ wait,而非误判为已落空', () => {+ expect(evaluateMobileAnchorVerify({+ ...baseInput, metrics: { contentHeight: 0, offsetY: 0, viewportHeight: 800 },+ })).toBe('wait');+ expect(evaluateMobileAnchorVerify({+ ...baseInput, metrics: { contentHeight: 2000, offsetY: 0, viewportHeight: 0 },+ })).toBe('wait');+ });++ it('等待轮数达到上限仍无有效 metrics/仍在 mVCP 中 → give-up(不无限期挂着)', () => {+ expect(evaluateMobileAnchorVerify({+ ...baseInput,+ preserveVisibleContentPosition: true,+ waitRounds: MOBILE_ANCHOR_VERIFY_MAX_WAIT_ROUNDS,+ metrics: metricsAt(0),+ })).toBe('give-up');+ // 上限前一轮仍是 wait。+ expect(evaluateMobileAnchorVerify({+ ...baseInput,+ preserveVisibleContentPosition: true,+ waitRounds: MOBILE_ANCHOR_VERIFY_MAX_WAIT_ROUNDS - 1,+ metrics: metricsAt(0),+ })).toBe('wait');+ });+});++describe('mobile mVCP settle quiet window', () => {+ it('keeps verification waiting through the quiet window after a data or size change', () => {+ const settleAt = mobileMvcpSettleDeadline(0, 1_000);+ expect(settleAt).toBe(1_000 + MOBILE_MVCP_SETTLE_QUIET_MS);+ expect(isMobileMvcpSettling(1_000, settleAt)).toBe(true);+ expect(isMobileMvcpSettling(settleAt - 1, settleAt)).toBe(true);+ expect(isMobileMvcpSettling(settleAt, settleAt)).toBe(false);+ });++ it('extends an in-flight settle window when streaming content changes again', () => {+ const firstDeadline = mobileMvcpSettleDeadline(0, 1_000);+ const extendedDeadline = mobileMvcpSettleDeadline(firstDeadline, 1_080);+ expect(extendedDeadline).toBe(1_080 + MOBILE_MVCP_SETTLE_QUIET_MS);+ });+});++describe('mobileFollowVerifyStartDelayMs (动画贴底完成后再启动 verifier)', () => {+ it('动画仍在 settle 窗口内时返回剩余等待时间', () => {+ expect(mobileFollowVerifyStartDelayMs({+ animatedScrollInFlight: true,+ now: 600,+ settleAt: 1400,+ })).toBe(800);+ });++ it('非动画、已结束或时钟已越过 settle 时立即校验', () => {+ expect(mobileFollowVerifyStartDelayMs({+ animatedScrollInFlight: false,+ now: 600,+ settleAt: 1400,+ })).toBe(0);+ expect(mobileFollowVerifyStartDelayMs({+ animatedScrollInFlight: true,+ now: 1400,+ settleAt: 1400,+ })).toBe(0);+ expect(mobileFollowVerifyStartDelayMs({+ animatedScrollInFlight: true,+ now: 1500,+ settleAt: 1400,+ })).toBe(0);+ });+});diff --git a/apps/mobile/src/__tests__/remoteSessionStore.test.ts b/apps/mobile/src/__tests__/remoteSessionStore.test.tsindex 996df7ef54..82d80745ea 100644--- a/apps/mobile/src/__tests__/remoteSessionStore.test.ts+++ b/apps/mobile/src/__tests__/remoteSessionStore.test.ts@@ -1,5 +1,6 @@import { beforeEach, describe, expect, it, vi } from 'vitest';import { MAKER_EVENT_BATCH_CHANNEL } from '@cindy/device-link';+import { clampLiveRowCreatedAt } from '@/session/messagePaging';import { remoteSessionStore, sessionPendingWrites } from '@/session/remoteSessionStore';import type { InputProjection, PendingInteraction, RemoteMessage, RemoteSession } from '@/session/types';@@ -596,6 +597,122 @@ describe('remoteSessionStore', () => {}});+ it.each([+ ['without persistId', undefined],+ ['with the same persistId', 'shared-live-assistant'],+ ] as const)('flushes a text delta batch when the transport changes %s', (_label, persistId) => {+ vi.useFakeTimers();+ try {+ remoteSessionStore.applyRemotePush('stale-mac', 'maker:event', {+ sessionId: 's1',+ ...(persistId ? { persistId } : {}),+ event: {+ type: 'text',+ data: { text: 'Stale reply', isFinal: false },+ },+ });+ remoteSessionStore.applyRemotePush('current-mac', 'maker:event', {+ sessionId: 's1',+ ...(persistId ? { persistId } : {}),+ event: {+ type: 'text',+ data: { text: 'Current reply', isFinal: false },+ },+ });++ remoteSessionStore.removeDevice('stale-mac');+ vi.runOnlyPendingTimers();++ expect(remoteSessionStore.getMessages('s1')).toMatchObject([{+ content: 'Current reply',+ role: 'assistant',+ }]);+ } finally {+ vi.useRealTimers();+ }+ });++ it('resets a shared-persist streaming row after both transport batches flush', () => {+ vi.useFakeTimers();+ try {+ remoteSessionStore.applyRemotePush('stale-mac', 'maker:event', {+ sessionId: 's1',+ persistId: 'shared-live-assistant',+ event: {+ type: 'text',+ data: { text: 'Stale reply', isFinal: false },+ },+ });+ vi.runOnlyPendingTimers();++ remoteSessionStore.applyRemotePush('current-mac', 'maker:event', {+ sessionId: 's1',+ persistId: 'shared-live-assistant',+ event: {+ type: 'text',+ data: { text: 'Current reply', isFinal: false },+ },+ });+ vi.runOnlyPendingTimers();++ expect(remoteSessionStore.getMessages('s1')).toMatchObject([{+ clientId: 'shared-live-assistant',+ content: 'Current reply',+ role: 'assistant',+ }]);++ remoteSessionStore.removeDevice('stale-mac');++ expect(remoteSessionStore.getMessages('s1')).toMatchObject([{+ clientId: 'shared-live-assistant',+ content: 'Current reply',+ role: 'assistant',+ }]);+ } finally {+ vi.useRealTimers();+ }+ });++ it('tracks transport stream assembly independently for interleaved persist ids', () => {+ vi.useFakeTimers();+ try {+ for (const [deviceId, persistId, text] of [+ ['stale-mac', 'assistant-a', 'Stale A'],+ ['stale-mac', 'assistant-b', 'Stale B'],+ ['current-mac', 'assistant-a', 'Current A'],+ ] as const) {+ remoteSessionStore.applyRemotePush(deviceId, 'maker:event', {+ sessionId: 's1',+ persistId,+ event: {+ type: 'text',+ data: { text, isFinal: false },+ },+ });+ vi.runOnlyPendingTimers();+ }++ expect(remoteSessionStore.getMessages('s1').map((item) => ({+ clientId: item.clientId,+ content: item.content,+ })).sort((left, right) => left.clientId.localeCompare(right.clientId))).toEqual([+ { clientId: 'assistant-a', content: 'Current A' },+ { clientId: 'assistant-b', content: 'Stale B' },+ ]);++ remoteSessionStore.removeDevice('stale-mac');++ expect(remoteSessionStore.getMessages('s1').map((item) => ({+ clientId: item.clientId,+ content: item.content,+ }))).toEqual([+ { clientId: 'assistant-a', content: 'Current A' },+ ]);+ } finally {+ vi.useRealTimers();+ }+ });+it('treats final text as a complete block and clears streaming at done', () => {pushMakerText('s1', 'persist-1', 'hello', false);pushMakerText('s1', 'persist-1', 'hello world', true, { model: 'claude' });@@ -1907,7 +2024,7 @@ describe('remoteSessionStore', () => {content: '完整的长内容',};const truncated = {- ...messageAt('m1', 's1', '2026-01-01T10:00:01.000Z'),+ ...messageAt('m1', 's1', '2026-01-01T10:00:01.500Z'),content: '[remote content truncated: payload too large]',agentMeta: { remoteContentTruncated: true, agentTaskStatus: 'failed' as const },};@@ -1921,6 +2038,7 @@ describe('remoteSessionStore', () => {const rows = remoteSessionStore.getMessages('s1');expect(rows.map((item) => item.id)).toEqual(['m1', 'm2']);expect(rows[0].content).toBe('完整的长内容');+ expect(rows[0].createdAt).toBe('2026-01-01T10:00:01.500Z');expect(rows[0].agentMeta?.agentTaskStatus).toBe('failed');expect(rows[0].agentMeta?.remoteContentTruncated).not.toBe(true);});@@ -2968,669 +3086,2514 @@ describe('remoteSessionStore', () => {expect(remoteSessionStore.getMessages('s1')).toHaveLength(2);});- it('emits when soft offline only clears pending-refresh metadata', () => {- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);- remoteSessionStore.applyRemotePush('dev-1', 'local-db:session:error-persisted', {- sessionId: 's1',- });- expect(remoteSessionStore.hasPendingRefresh('s1')).toBe(true);-- const notify = vi.fn();- const unsubscribe = remoteSessionStore.subscribe(notify);+ it('preserves a provisional live reply anchor across transient device offline', () => {+ vi.useFakeTimers();try {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', {+ userSendAt: '2026-01-01T00:00:01.000Z',+ updatedAt: '2026-01-01T00:00:01.000Z',+ })]);+ vi.setSystemTime(new Date('2026-01-01T00:10:00.000Z'));+ pushMakerText('s1', 'current-live-assistant', 'Current reply', true);+remoteSessionStore.markDeviceOffline('dev-1');- expect(remoteSessionStore.hasPendingRefresh('s1')).toBe(false);- expect(notify).toHaveBeenCalledTimes(1);+ remoteSessionStore.setLatestMessageWindow('s1', [{+ ...messageAt('current-user', 's1', '2026-01-01T00:00:02.000Z'),+ role: 'user',+ content: 'Current question',+ }]);++ expect(remoteSessionStore.getMessages('s1').map((item) => item.clientId)).toEqual([+ 'current-user',+ 'current-live-assistant',+ ]);} finally {- unsubscribe();+ vi.useRealTimers();}});- it('removes a device shard with its messages and pending interactions', () => {- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);- remoteSessionStore.setDeviceSessions('dev-2', 'Windows', [session('s2')]);- remoteSessionStore.setMessages('s1', [message('m1', 's1')]);- remoteSessionStore.setMessages('s2', [message('m2', 's2')]);- remoteSessionStore.setPendingInteractions('s1', [{ request: { requestId: 'req-1' } }]);- remoteSessionStore.setInputProjection('s1', projection('s1'));+ it('does not let a reconnecting newer send claim an older offline provisional reply', () => {+ vi.useFakeTimers();+ try {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', {+ userSendAt: '2026-01-01T00:00:01.000Z',+ updatedAt: '2026-01-01T00:00:01.000Z',+ })]);+ vi.setSystemTime(new Date('2026-01-01T00:10:00.000Z'));+ pushMakerText('s1', 'previous-live-assistant', 'Previous reply', true);- remoteSessionStore.removeDevice('dev-1');+ remoteSessionStore.markDeviceOffline('dev-1');+ remoteSessionStore.upsertDeviceSession('dev-1', 'Mac', session('s1', {+ userSendAt: '2026-01-01T00:00:02.000Z',+ updatedAt: '2026-01-01T00:00:02.000Z',+ }));+ remoteSessionStore.setLatestMessageWindow('s1', [+ {+ ...messageAt('previous-user', 's1', '2026-01-01T00:00:01.000Z'),+ role: 'user',+ content: 'Previous question',+ },+ {+ ...messageAt('current-user', 's1', '2026-01-01T00:00:02.000Z'),+ role: 'user',+ content: 'Current question',+ },+ ]);- expect(remoteSessionStore.getSessions().map((item) => item.id)).toEqual(['s2']);- expect(remoteSessionStore.getMessages('s1')).toEqual([]);- expect(remoteSessionStore.getPendingInteractions('s1')).toEqual([]);- expect(remoteSessionStore.getInputProjection('s1').pendingQueue).toEqual([]);- expect(remoteSessionStore.getMessages('s2')).toHaveLength(1);+ const rows = remoteSessionStore.getMessages('s1');+ expect(rows.map((item) => item.clientId)).toEqual([+ 'previous-user',+ 'previous-live-assistant',+ 'current-user',+ ]);+ expect(rows.find((item) => item.clientId === 'previous-live-assistant')?.createdAt)+ .toBe('2026-01-01T00:00:01.000Z');+ } finally {+ vi.useRealTimers();+ }});- it('writes canonicalDeviceId for a stale shard uniquely matching a current device, keeping deviceLinkDeviceId physical', () => {- remoteSessionStore.setDeviceIdentity([{ deviceId: 'current-mac', name: 'Lizi Mac' }]);- remoteSessionStore.setDeviceSessions('current-mac', 'Lizi Mac', [session('s-current')]);- remoteSessionStore.setDeviceSessions('stale-mac', 'Lizi Mac', [session('s-stale')]);-- const byId = new Map(remoteSessionStore.getSessions().map((s) => [s.id, s]));- // 展示维度:两条都认领到 current-mac(详情页按 canonicalDeviceId 过滤时同时可见)。- expect(byId.get('s-current')?.canonicalDeviceId).toBe('current-mac');- expect(byId.get('s-stale')?.canonicalDeviceId).toBe('current-mac');- // 路由维度:deviceLinkDeviceId 保持物理 shard id,sessionDeviceIndex 指向物理 shard(patch 不丢)。- expect(byId.get('s-stale')?.deviceLinkDeviceId).toBe('stale-mac');- expect(remoteSessionStore.getSessionDeviceId('s-stale')).toBe('stale-mac');- });+ it('keeps per-identity transport ownership across soft offline finalization', () => {+ vi.useFakeTimers();+ try {+ remoteSessionStore.setDeviceSessions('stale-mac', 'Mac', [session('s1')]);+ remoteSessionStore.applyRemotePush('stale-mac', 'maker:event', {+ sessionId: 's1',+ persistId: 'shared-live-assistant',+ event: {+ type: 'text',+ data: { text: 'Stale reply', isFinal: false },+ },+ });+ vi.runOnlyPendingTimers();- it('dedupes the same session id across stale/current shards, keeping the current shard copy', () => {- remoteSessionStore.setDeviceIdentity([{ deviceId: 'current-mac', name: 'Lizi Mac' }]);- // 同一 session id 同时出现在 stale 与 current 两个 shard(re-link 后旧 shard 残留)。- remoteSessionStore.setDeviceSessions('stale-mac', 'Lizi Mac', [session('dup')]);- remoteSessionStore.setDeviceSessions('current-mac', 'Lizi Mac', [session('dup')]);+ remoteSessionStore.markDeviceOffline('stale-mac');+ remoteSessionStore.applyRemotePush('current-mac', 'maker:event', {+ sessionId: 's1',+ persistId: 'shared-live-assistant',+ event: {+ type: 'text',+ data: { text: 'Current reply', isFinal: false },+ },+ });+ vi.runOnlyPendingTimers();- const rows = remoteSessionStore.getSessions().filter((s) => s.id === 'dup');- expect(rows).toHaveLength(1); // 去重,不重复渲染- expect(rows[0]?.deviceLinkDeviceId).toBe('current-mac'); // 保留 current shard 的真身- expect(remoteSessionStore.getSessionDeviceId('dup')).toBe('current-mac');+ expect(remoteSessionStore.getMessages('s1')).toMatchObject([{+ clientId: 'shared-live-assistant',+ content: 'Current reply',+ }]);+ } finally {+ vi.useRealTimers();+ }});- it('does not merge two unknown same-name shards (canonicalDeviceId stays the original id)', () => {- remoteSessionStore.setDeviceIdentity([]);- remoteSessionStore.setDeviceSessions('ghost-1', 'MacBook Pro', [session('g1')]);- remoteSessionStore.setDeviceSessions('ghost-2', 'MacBook Pro', [session('g2')]);+ it('keeps a pre-metadata offline reply unbound until its older user row arrives', () => {+ vi.useFakeTimers();+ try {+ vi.setSystemTime(new Date('2026-01-01T00:10:00.000Z'));+ pushMakerText('s1', 'previous-live-assistant', 'Previous reply', true);- const byId = new Map(remoteSessionStore.getSessions().map((s) => [s.id, s.canonicalDeviceId]));- expect(byId.get('g1')).toBe('ghost-1');- expect(byId.get('g2')).toBe('ghost-2');- });+ // No session list row exists yet, so the offline transition must use the+ // maker event's transport device rather than sessionDeviceIndex.+ remoteSessionStore.markDeviceOffline('dev-1');+ remoteSessionStore.upsertDeviceSession('dev-1', 'Mac', session('s1', {+ userSendAt: '2026-01-01T00:00:02.000Z',+ updatedAt: '2026-01-01T00:00:02.000Z',+ }));+ remoteSessionStore.setLatestMessageWindow('s1', [{+ ...messageAt('current-user', 's1', '2026-01-01T00:00:02.000Z'),+ role: 'user',+ content: 'Current question',+ }]);- it('leaves canonicalDeviceId equal to the physical shard id before any device identity is injected', () => {- remoteSessionStore.setDeviceSessions('stale-mac', 'Lizi Mac', [session('s1')]);- const s = remoteSessionStore.getSessions()[0];- expect(s?.deviceLinkDeviceId).toBe('stale-mac');- expect(s?.canonicalDeviceId).toBe('stale-mac');- });+ expect(remoteSessionStore.getMessages('s1')+ .find((item) => item.clientId === 'previous-live-assistant')?.createdAt)+ .toBe('2026-01-01T00:10:00.000Z');- it('does not claim when two stale shards share a name matching one current device', () => {- remoteSessionStore.setDeviceIdentity([{ deviceId: 'current-mbp', name: 'MacBook Pro' }]);- remoteSessionStore.setDeviceSessions('stale-1', 'MacBook Pro', [session('a')]);- remoteSessionStore.setDeviceSessions('stale-2', 'MacBook Pro', [session('b')]);+ remoteSessionStore.appendMessage('s1', {+ ...messageAt('previous-user', 's1', '2026-01-01T00:00:01.000Z'),+ role: 'user',+ content: 'Previous question',+ });- const byId = new Map(remoteSessionStore.getSessions().map((s) => [s.id, s.canonicalDeviceId]));- // stale 侧同名歧义 → 不认领,保留各自物理 id,不并到 current-mbp。- expect(byId.get('a')).toBe('stale-1');- expect(byId.get('b')).toBe('stale-2');+ const rows = remoteSessionStore.getMessages('s1');+ expect(rows.map((item) => item.clientId)).toEqual([+ 'previous-user',+ 'previous-live-assistant',+ 'current-user',+ ]);+ expect(rows.find((item) => item.clientId === 'previous-live-assistant')?.createdAt)+ .toBe('2026-01-01T00:00:01.000Z');+ } finally {+ vi.useRealTimers();+ }});- it('ignores placeholder device names when claiming stale shards', () => {- remoteSessionStore.setDeviceIdentity([{ deviceId: 'current-x', name: 'unknown' }]);- remoteSessionStore.setDeviceSessions('stale-x', 'unknown', [session('p')]);- // placeholder 名(unknown)不参与认领,stale-x 保留物理 id。- expect(remoteSessionStore.getSessions().find((s) => s.id === 'p')?.canonicalDeviceId).toBe('stale-x');- });-});+ it('flushes and freezes a pre-metadata text delta when its transport goes offline', () => {+ vi.useFakeTimers();+ try {+ vi.setSystemTime(new Date('2026-01-01T00:10:00.000Z'));+ pushMakerText('s1', 'previous-live-assistant', 'Previous reply', false);-describe('maker:session-model-pref:changed push 路由', () => {- it('路由进 sessionModelMirror(镜像可读),非法 payload 静默忽略', async () => {- const { makeSessionMirrorAccessors, clearSessionMirror } = await import('@/session/sessionModelMirror');- const acc = makeSessionMirrorAccessors('s-pref', vi.fn());- remoteSessionStore.applyRemotePush('dev-1', 'maker:session-model-pref:changed', {- sessionId: 's-pref',- agent: 'codex',- providerId: 'xd',- model: 'gpt-5.5',- effort: 'xhigh',- fast: true,- });- expect(acc.getEffort('codex', 'xd', 'gpt-5.5')).toBe('xhigh');- expect(acc.getFast('codex', 'xd', 'gpt-5.5')).toBe(true);+ remoteSessionStore.markDeviceOffline('dev-1');+ remoteSessionStore.upsertDeviceSession('dev-1', 'Mac', session('s1', {+ userSendAt: '2026-01-01T00:00:02.000Z',+ updatedAt: '2026-01-01T00:00:02.000Z',+ }));+ remoteSessionStore.setLatestMessageWindow('s1', [{+ ...messageAt('current-user', 's1', '2026-01-01T00:00:02.000Z'),+ role: 'user',+ content: 'Current question',+ }]);- remoteSessionStore.applyRemotePush('dev-1', 'maker:session-model-pref:changed', { nope: 1 });- expect(acc.getEffort('codex', 'xd', 'nope')).toBeUndefined();- clearSessionMirror('s-pref');+ expect(remoteSessionStore.getMessages('s1')+ .find((item) => item.clientId === 'previous-live-assistant')?.createdAt)+ .toBe('2026-01-01T00:10:00.000Z');++ remoteSessionStore.appendMessage('s1', {+ ...messageAt('previous-user', 's1', '2026-01-01T00:00:01.000Z'),+ role: 'user',+ content: 'Previous question',+ });+ expect(remoteSessionStore.getMessages('s1').map((item) => item.clientId)).toEqual([+ 'previous-user',+ 'previous-live-assistant',+ 'current-user',+ ]);+ } finally {+ vi.useRealTimers();+ }});-});-describe('setDeviceSessions 对在途乐观创建行(pendingLocalCreation)的保护', () => {- beforeEach(() => remoteSessionStore.clear());+ it('pairs an older delayed user with the offline-unbound reply before the new round reply', () => {+ vi.useFakeTimers();+ try {+ vi.setSystemTime(new Date('2026-01-01T00:10:00.000Z'));+ pushMakerText('s1', 'previous-live-assistant', 'Previous reply', true);+ remoteSessionStore.markDeviceOffline('dev-1');- it('比建成更早发出的旧列表不含该 id:合成行保留,不从列表消失', () => {- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s-old')]);- remoteSessionStore.upsertDeviceSession('dev-1', 'Mac', session('s-new', { pendingLocalCreation: true }));+ remoteSessionStore.upsertDeviceSession('dev-1', 'Mac', session('s1', {+ userSendAt: '2026-01-01T00:00:02.000Z',+ updatedAt: '2026-01-01T00:00:02.000Z',+ }));+ vi.setSystemTime(new Date('2026-01-01T00:11:00.000Z'));+ pushMakerText('s1', 'current-live-assistant', 'Current reply', true);- // 首页 in-flight 的 sessions:list 响应此刻返回(发出时被控端还没建这个任务)。- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s-old')]);- const rows = remoteSessionStore.getSessions();- expect(rows.map((s) => s.id)).toContain('s-new');- expect(rows.find((s) => s.id === 's-new')?.pendingLocalCreation).toBe(true);- });+ remoteSessionStore.appendMessage('s1', {+ ...messageAt('previous-user', 's1', '2026-01-01T00:00:01.000Z'),+ role: 'user',+ content: 'Previous question',+ });+ expect(remoteSessionStore.getMessages('s1').map((item) => item.clientId)).toEqual([+ 'previous-user',+ 'previous-live-assistant',+ 'current-live-assistant',+ ]);+ remoteSessionStore.appendMessage('s1', {+ ...messageAt('current-user', 's1', '2026-01-01T00:00:02.000Z'),+ role: 'user',+ content: 'Current question',+ });- it('建成后 enqueue 落定前的新列表含该 id 但无标:合并权威字段并保留禁发标', () => {- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', []);- remoteSessionStore.upsertDeviceSession('dev-1', 'Mac', session('s-new', { pendingLocalCreation: true, title: '本地草稿标题' }));+ expect(remoteSessionStore.getMessages('s1').map((item) => item.clientId)).toEqual([+ 'previous-user',+ 'previous-live-assistant',+ 'current-user',+ 'current-live-assistant',+ ]);+ } finally {+ vi.useRealTimers();+ }+ });- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s-new', { title: '权威标题' })]);- const row = remoteSessionStore.getSessions().find((s) => s.id === 's-new');- expect(row?.title).toBe('权威标题');+ it('pairs multiple offline-unbound reply cohorts with realtime users in arrival order', () => {+ vi.useFakeTimers();+ try {+ remoteSessionStore.applyMakerEvent('s1', {+ type: 'status',+ data: { isRunning: true },+ });+ vi.setSystemTime(new Date('2026-01-01T00:10:00.000Z'));+ pushMakerText('s1', 'live-assistant-1', 'First reply', true);+ remoteSessionStore.applyMakerEvent('s1', {+ type: 'status',+ data: { isRunning: false },+ });+ remoteSessionStore.applyMakerEvent('s1', {+ type: 'status',+ data: { isRunning: true },+ });+ vi.setSystemTime(new Date('2026-01-01T00:11:00.000Z'));+ pushMakerText('s1', 'live-assistant-2', 'Second reply', true);++ remoteSessionStore.markDeviceOffline('dev-1');+ remoteSessionStore.upsertDeviceSession('dev-1', 'Mac', session('s1', {+ userSendAt: '2026-01-01T00:00:02.000Z',+ updatedAt: '2026-01-01T00:00:02.000Z',+ }));+ remoteSessionStore.appendMessage('s1', {+ ...messageAt('user-1', 's1', '2026-01-01T00:00:01.000Z'),+ role: 'user',+ content: 'First question',+ });+ remoteSessionStore.appendMessage('s1', {+ ...messageAt('user-2', 's1', '2026-01-01T00:00:02.000Z'),+ role: 'user',+ content: 'Second question',+ });++ expect(remoteSessionStore.getMessages('s1').map((item) => item.clientId)).toEqual([+ 'user-1',+ 'live-assistant-1',+ 'user-2',+ 'live-assistant-2',+ ]);+ } finally {+ vi.useRealTimers();+ }+ });++ it('pairs multiple offline-unbound reply cohorts with a reconnect window in arrival order', () => {+ vi.useFakeTimers();+ try {+ remoteSessionStore.applyMakerEvent('s1', {+ type: 'status',+ data: { isRunning: true },+ });+ vi.setSystemTime(new Date('2026-01-01T00:10:00.000Z'));+ pushMakerText('s1', 'live-assistant-1', 'First reply', true);+ remoteSessionStore.applyMakerEvent('s1', {+ type: 'status',+ data: { isRunning: false },+ });+ remoteSessionStore.applyMakerEvent('s1', {+ type: 'status',+ data: { isRunning: true },+ });+ vi.setSystemTime(new Date('2026-01-01T00:11:00.000Z'));+ pushMakerText('s1', 'live-assistant-2', 'Second reply', true);++ remoteSessionStore.markDeviceOffline('dev-1');+ remoteSessionStore.upsertDeviceSession('dev-1', 'Mac', session('s1', {+ userSendAt: '2026-01-01T00:00:02.000Z',+ updatedAt: '2026-01-01T00:00:02.000Z',+ }));+ remoteSessionStore.setLatestMessageWindow('s1', [+ {+ ...messageAt('user-1', 's1', '2026-01-01T00:00:01.000Z'),+ role: 'user',+ content: 'First question',+ },+ {+ ...messageAt('user-2', 's1', '2026-01-01T00:00:02.000Z'),+ role: 'user',+ content: 'Second question',+ },+ ], { moreBeyondWindow: false });++ expect(remoteSessionStore.getMessages('s1').map((item) => item.clientId)).toEqual([+ 'user-1',+ 'live-assistant-1',+ 'user-2',+ 'live-assistant-2',+ ]);+ } finally {+ vi.useRealTimers();+ }+ });++ it('leaves offline-unbound cohorts pending when the reconnect window is truncated', () => {+ vi.useFakeTimers();+ try {+ for (const [index, createdAt] of [+ ['1', '2026-01-01T00:10:00.000Z'],+ ['2', '2026-01-01T00:11:00.000Z'],+ ['3', '2026-01-01T00:12:00.000Z'],+ ] as const) {+ remoteSessionStore.applyMakerEvent('s1', {+ type: 'status',+ data: { isRunning: true },+ });+ vi.setSystemTime(new Date(createdAt));+ pushMakerText('s1', `live-assistant-${index}`, `Reply ${index}`, true);+ remoteSessionStore.applyMakerEvent('s1', {+ type: 'status',+ data: { isRunning: false },+ });+ }++ remoteSessionStore.markDeviceOffline('dev-1');+ remoteSessionStore.upsertDeviceSession('dev-1', 'Mac', session('s1', {+ userSendAt: '2026-01-01T00:00:03.000Z',+ updatedAt: '2026-01-01T00:00:03.000Z',+ }));+ remoteSessionStore.setLatestMessageWindow('s1', [+ {+ ...messageAt('user-2', 's1', '2026-01-01T00:00:02.000Z'),+ role: 'user',+ content: 'Second question',+ },+ {+ ...messageAt('user-3', 's1', '2026-01-01T00:00:03.000Z'),+ role: 'user',+ content: 'Third question',+ },+ ], { moreBeyondWindow: true });++ expect(remoteSessionStore.getMessages('s1').map((item) => item.clientId)).toEqual([+ 'user-2',+ 'user-3',+ 'live-assistant-1',+ 'live-assistant-2',+ 'live-assistant-3',+ ]);+ } finally {+ vi.useRealTimers();+ }+ });++ it('leaves offline-unbound cohorts pending when the reconnect window has extra users', () => {+ vi.useFakeTimers();+ try {+ for (const [index, createdAt] of [+ ['1', '2026-01-01T00:10:00.000Z'],+ ['2', '2026-01-01T00:11:00.000Z'],+ ] as const) {+ remoteSessionStore.applyMakerEvent('s1', {+ type: 'status',+ data: { isRunning: true },+ });+ vi.setSystemTime(new Date(createdAt));+ pushMakerText('s1', `live-assistant-${index}`, `Reply ${index}`, true);+ remoteSessionStore.applyMakerEvent('s1', {+ type: 'status',+ data: { isRunning: false },+ });+ }++ remoteSessionStore.markDeviceOffline('dev-1');+ remoteSessionStore.upsertDeviceSession('dev-1', 'Mac', session('s1', {+ userSendAt: '2026-01-01T00:00:03.000Z',+ updatedAt: '2026-01-01T00:00:03.000Z',+ }));+ remoteSessionStore.setLatestMessageWindow('s1', [+ {+ ...messageAt('user-1', 's1', '2026-01-01T00:00:01.000Z'),+ role: 'user',+ content: 'First question',+ },+ {+ ...messageAt('user-2', 's1', '2026-01-01T00:00:02.000Z'),+ role: 'user',+ content: 'Second question',+ },+ {+ ...messageAt('user-3', 's1', '2026-01-01T00:00:03.000Z'),+ role: 'user',+ content: 'Third question',+ },+ ], { moreBeyondWindow: false });++ expect(remoteSessionStore.getMessages('s1').map((item) => item.clientId)).toEqual([+ 'user-1',+ 'user-2',+ 'user-3',+ 'live-assistant-1',+ 'live-assistant-2',+ ]);+ } finally {+ vi.useRealTimers();+ }+ });++ it('leaves offline-unbound cohorts pending when an equal-sized reconnect window is truncated', () => {+ vi.useFakeTimers();+ try {+ for (const [index, createdAt] of [+ ['1', '2026-01-01T00:10:00.000Z'],+ ['2', '2026-01-01T00:11:00.000Z'],+ ] as const) {+ remoteSessionStore.applyMakerEvent('s1', {+ type: 'status',+ data: { isRunning: true },+ });+ vi.setSystemTime(new Date(createdAt));+ pushMakerText('s1', `live-assistant-${index}`, `Reply ${index}`, true);+ remoteSessionStore.applyMakerEvent('s1', {+ type: 'status',+ data: { isRunning: false },+ });+ }++ remoteSessionStore.markDeviceOffline('dev-1');+ remoteSessionStore.upsertDeviceSession('dev-1', 'Mac', session('s1', {+ userSendAt: '2026-01-01T00:00:03.000Z',+ updatedAt: '2026-01-01T00:00:03.000Z',+ }));+ remoteSessionStore.setLatestMessageWindow('s1', [+ {+ ...messageAt('user-2', 's1', '2026-01-01T00:00:02.000Z'),+ role: 'user',+ content: 'Second question',+ },+ {+ ...messageAt('user-3', 's1', '2026-01-01T00:00:03.000Z'),+ role: 'user',+ content: 'Third question',+ },+ ], { moreBeyondWindow: true });++ expect(remoteSessionStore.getMessages('s1').map((item) => item.clientId)).toEqual([+ 'user-2',+ 'user-3',+ 'live-assistant-1',+ 'live-assistant-2',+ ]);+ } finally {+ vi.useRealTimers();+ }+ });++ it('emits when soft offline only clears pending-refresh metadata', () => {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);+ remoteSessionStore.applyRemotePush('dev-1', 'local-db:session:error-persisted', {+ sessionId: 's1',+ });+ expect(remoteSessionStore.hasPendingRefresh('s1')).toBe(true);++ const notify = vi.fn();+ const unsubscribe = remoteSessionStore.subscribe(notify);+ try {+ remoteSessionStore.markDeviceOffline('dev-1');+ expect(remoteSessionStore.hasPendingRefresh('s1')).toBe(false);+ expect(notify).toHaveBeenCalledTimes(1);+ } finally {+ unsubscribe();+ }+ });++ it('removes a device shard with its messages and pending interactions', () => {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);+ remoteSessionStore.setDeviceSessions('dev-2', 'Windows', [session('s2')]);+ remoteSessionStore.setMessages('s1', [message('m1', 's1')]);+ remoteSessionStore.setMessages('s2', [message('m2', 's2')]);+ remoteSessionStore.setPendingInteractions('s1', [{ request: { requestId: 'req-1' } }]);+ remoteSessionStore.setInputProjection('s1', projection('s1'));++ remoteSessionStore.removeDevice('dev-1');++ expect(remoteSessionStore.getSessions().map((item) => item.id)).toEqual(['s2']);+ expect(remoteSessionStore.getMessages('s1')).toEqual([]);+ expect(remoteSessionStore.getPendingInteractions('s1')).toEqual([]);+ expect(remoteSessionStore.getInputProjection('s1').pendingQueue).toEqual([]);+ expect(remoteSessionStore.getMessages('s2')).toHaveLength(1);+ });++ it('discards a pre-metadata text batch when its transport is hard removed', () => {+ vi.useFakeTimers();+ try {+ pushMakerText('s1', 'live-assistant', 'Stale reply', false);++ remoteSessionStore.removeDevice('dev-1');+ vi.runOnlyPendingTimers();++ expect(remoteSessionStore.getMessages('s1')).toEqual([]);+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);+ expect(remoteSessionStore.getMessages('s1')).toEqual([]);+ } finally {+ vi.useRealTimers();+ }+ });++ it('removes a flushed pre-metadata reply with its transport-owned anchor', () => {+ vi.useFakeTimers();+ try {+ vi.setSystemTime(new Date('2026-01-01T00:10:00.000Z'));+ pushMakerText('s1', 'live-assistant', 'Stale reply', true);+ remoteSessionStore.setSessionRunning('s1', true);+ expect(remoteSessionStore.getMessages('s1')).toHaveLength(1);+ expect(remoteSessionStore.getSessionRunStatus('s1').isRunning).toBe(true);++ remoteSessionStore.removeDevice('dev-1');+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', {+ userSendAt: '2026-01-01T00:00:01.000Z',+ updatedAt: '2026-01-01T00:00:01.000Z',+ })]);+ expect(remoteSessionStore.getMessages('s1')).toEqual([]);+ expect(remoteSessionStore.getSessionRunStatus('s1').isRunning).toBe(false);+ } finally {+ vi.useRealTimers();+ }+ });++ it('keeps a current shard window when removing a stale transport for the same session id', () => {+ vi.useFakeTimers();+ try {+ vi.setSystemTime(new Date('2026-01-01T00:10:00.000Z'));+ remoteSessionStore.applyRemotePush('stale-mac', 'maker:event', {+ sessionId: 's1',+ persistId: 'stale-live-assistant',+ event: {+ type: 'text',+ data: { text: 'Stale reply', isFinal: true },+ },+ });+ remoteSessionStore.setDeviceSessions('current-mac', 'Mac', [session('s1')]);+ remoteSessionStore.setMessages('s1', [messageAt(+ 'current-assistant',+ 's1',+ '2026-01-01T00:00:01.000Z',+ )]);++ remoteSessionStore.removeDevice('stale-mac');++ expect(remoteSessionStore.getSessionDeviceId('s1')).toBe('current-mac');+ expect(remoteSessionStore.getMessages('s1').map((item) => item.clientId)).toEqual([+ 'current-assistant',+ ]);+ } finally {+ vi.useRealTimers();+ }+ });++ it('does not let an identical transport replay claim a persisted assistant row', () => {+ remoteSessionStore.setDeviceSessions('current-mac', 'Mac', [session('s1')]);+ remoteSessionStore.setMessages('s1', [message('persisted-assistant', 's1')]);++ remoteSessionStore.applyRemotePush('stale-mac', 'maker:event', {+ sessionId: 's1',+ persistId: 'persisted-assistant',+ event: {+ type: 'text',+ data: { text: 'hello', isFinal: true },+ },+ });+ remoteSessionStore.removeDevice('stale-mac');++ expect(remoteSessionStore.getSessionDeviceId('s1')).toBe('current-mac');+ expect(remoteSessionStore.getMessages('s1')).toEqual([+ message('persisted-assistant', 's1'),+ ]);+ });++ it('retires pending identity when an identical persisted assistant echo arrives', () => {+ vi.useFakeTimers();+ try {+ vi.setSystemTime(new Date('2026-01-01T00:00:00.000Z'));+ pushMakerText('s1', 'persisted-assistant', 'hello', true);+ remoteSessionStore.appendMessage('s1', message('persisted-assistant', 's1'));++ remoteSessionStore.appendMessage('s1', {+ ...messageAt('next-user', 's1', '2026-01-01T00:00:01.000Z'),+ role: 'user',+ content: 'Next question',+ });++ expect(remoteSessionStore.getMessages('s1').map((item) => item.clientId)).toEqual([+ 'persisted-assistant',+ 'next-user',+ ]);+ } finally {+ vi.useRealTimers();+ }+ });++ it('keeps pending identity for an identical live transport replay', () => {+ vi.useFakeTimers();+ try {+ vi.setSystemTime(new Date('2026-01-01T00:00:00.000Z'));+ pushMakerText('s1', 'live-assistant', 'hello', true);+ pushMakerText('s1', 'live-assistant', 'hello', true);++ remoteSessionStore.appendMessage('s1', {+ ...messageAt('trigger-user', 's1', '2026-01-01T00:00:01.000Z'),+ role: 'user',+ content: 'Question',+ });++ expect(remoteSessionStore.getMessages('s1').map((item) => item.clientId)).toEqual([+ 'trigger-user',+ 'live-assistant',+ ]);+ } finally {+ vi.useRealTimers();+ }+ });++ it('does not let a stale transport mutate or claim a persisted assistant row', () => {+ remoteSessionStore.setDeviceIdentity([{ deviceId: 'current-mac', name: 'Mac' }]);+ remoteSessionStore.setDeviceSessions('current-mac', 'Mac', [session('s1')]);+ remoteSessionStore.setMessages('s1', [message('persisted-assistant', 's1')]);++ remoteSessionStore.applyRemotePush('stale-mac', 'maker:event', {+ sessionId: 's1',+ persistId: 'persisted-assistant',+ event: {+ type: 'text',+ data: { text: 'Stale replay', isFinal: true },+ },+ });+ remoteSessionStore.removeDevice('stale-mac');++ expect(remoteSessionStore.getSessionDeviceId('s1')).toBe('current-mac');+ expect(remoteSessionStore.getMessages('s1')).toEqual([+ message('persisted-assistant', 's1'),+ ]);+ });++ it.each([+ ['before the current transport batch flushes', false],+ ['after the current transport batch flushes', true],+ ] as const)('keeps replacement transport state %s when removing an indexed stale shard', (+ _label,+ flushBeforeRemoval,+ ) => {+ vi.useFakeTimers();+ try {+ remoteSessionStore.setDeviceSessions('stale-mac', 'Mac', [session('s1')]);+ remoteSessionStore.applyRemotePush('current-mac', 'maker:event', {+ sessionId: 's1',+ persistId: 'current-live-assistant',+ event: {+ type: 'text',+ data: { text: 'Current reply', isFinal: false },+ },+ });+ if (flushBeforeRemoval) vi.runOnlyPendingTimers();++ remoteSessionStore.removeDevice('stale-mac');+ vi.runOnlyPendingTimers();++ expect(remoteSessionStore.getMessages('s1')).toMatchObject([{+ clientId: 'current-live-assistant',+ content: 'Current reply',+ }]);++ remoteSessionStore.setDeviceSessions('current-mac', 'Mac', [session('s1')]);+ expect(remoteSessionStore.getSessionDeviceId('s1')).toBe('current-mac');+ expect(remoteSessionStore.getMessages('s1')).toHaveLength(1);+ } finally {+ vi.useRealTimers();+ }+ });++ it.each([+ ['stale transport writes first', ['stale-mac', 'current-mac']],+ ['stale transport writes last', ['current-mac', 'stale-mac']],+ ] as const)('removes only the stale transport provisional reply when %s', (_label, deviceOrder) => {+ vi.useFakeTimers();+ try {+ remoteSessionStore.setDeviceSessions('current-mac', 'Mac', [session('s1')]);+ vi.setSystemTime(new Date('2026-01-01T00:10:00.000Z'));+ for (const deviceId of deviceOrder) {+ const isStale = deviceId === 'stale-mac';+ remoteSessionStore.applyRemotePush(deviceId, 'maker:event', {+ sessionId: 's1',+ persistId: isStale ? 'stale-live-assistant' : 'current-live-assistant',+ event: {+ type: 'text',+ data: {+ text: isStale ? 'Stale reply' : 'Current reply',+ isFinal: true,+ },+ },+ });+ }++ expect(remoteSessionStore.getMessages('s1').map((item) => item.clientId).sort()).toEqual([+ 'current-live-assistant',+ 'stale-live-assistant',+ ]);+ remoteSessionStore.removeDevice('stale-mac');++ expect(remoteSessionStore.getSessionDeviceId('s1')).toBe('current-mac');+ expect(remoteSessionStore.getMessages('s1').map((item) => item.clientId)).toEqual([+ 'current-live-assistant',+ ]);+ } finally {+ vi.useRealTimers();+ }+ });++ it('keeps a provisional reply that is also owned by the current transport', () => {+ vi.useFakeTimers();+ try {+ remoteSessionStore.setDeviceSessions('current-mac', 'Mac', [session('s1')]);+ vi.setSystemTime(new Date('2026-01-01T00:10:00.000Z'));+ for (const deviceId of ['stale-mac', 'current-mac']) {+ remoteSessionStore.applyRemotePush(deviceId, 'maker:event', {+ sessionId: 's1',+ persistId: 'shared-live-assistant',+ event: {+ type: 'text',+ data: { text: 'Shared reply', isFinal: true },+ },+ });+ }++ remoteSessionStore.removeDevice('stale-mac');++ expect(remoteSessionStore.getMessages('s1').map((item) => item.clientId)).toEqual([+ 'shared-live-assistant',+ ]);+ } finally {+ vi.useRealTimers();+ }+ });++ it('does not let a stale replay replace the current transport assembly', () => {+ vi.useFakeTimers();+ try {+ remoteSessionStore.setDeviceIdentity([{ deviceId: 'current-mac', name: 'Mac' }]);+ remoteSessionStore.setDeviceSessions('current-mac', 'Mac', [session('s1')]);+ remoteSessionStore.applyRemotePush('current-mac', 'maker:event', {+ sessionId: 's1',+ persistId: 'shared-live-assistant',+ event: {+ type: 'text',+ data: { text: 'Current reply', isFinal: true },+ },+ });+ remoteSessionStore.applyRemotePush('stale-mac', 'maker:event', {+ sessionId: 's1',+ persistId: 'shared-live-assistant',+ event: {+ type: 'text',+ data: { text: 'Stale replay', isFinal: true },+ },+ });++ expect(remoteSessionStore.getMessages('s1')).toMatchObject([{+ clientId: 'shared-live-assistant',+ content: 'Current reply',+ }]);+ remoteSessionStore.removeDevice('stale-mac');+ expect(remoteSessionStore.getMessages('s1')).toMatchObject([{+ clientId: 'shared-live-assistant',+ content: 'Current reply',+ }]);+ } finally {+ vi.useRealTimers();+ }+ });++ it('does not let a stale transport migrate the current generated assembly', () => {+ vi.useFakeTimers();+ try {+ remoteSessionStore.setDeviceIdentity([{ deviceId: 'current-mac', name: 'Mac' }]);+ remoteSessionStore.setDeviceSessions('current-mac', 'Mac', [session('s1')]);+ remoteSessionStore.applyRemotePush('current-mac', 'maker:event', {+ sessionId: 's1',+ event: {+ type: 'text',+ data: { text: 'Current reply', isFinal: true },+ },+ });+ const currentClientId = remoteSessionStore.getMessages('s1')[0]?.clientId;++ remoteSessionStore.applyRemotePush('stale-mac', 'maker:event', {+ sessionId: 's1',+ persistId: 'stale-persisted-assistant',+ event: {+ type: 'text',+ data: { text: 'Stale replay', isFinal: true },+ },+ });++ expect(currentClientId).toMatch(/^mobile-stream-/);+ expect(remoteSessionStore.getMessages('s1')).toMatchObject([{+ clientId: currentClientId,+ content: 'Current reply',+ }]);+ } finally {+ vi.useRealTimers();+ }+ });++ it('keeps current generated ownership across a done boundary before stale replay', () => {+ vi.useFakeTimers();+ try {+ remoteSessionStore.setDeviceIdentity([{ deviceId: 'current-mac', name: 'Mac' }]);+ remoteSessionStore.setDeviceSessions('current-mac', 'Mac', [session('s1')]);+ remoteSessionStore.applyRemotePush('current-mac', 'maker:event', {+ sessionId: 's1',+ event: {+ type: 'text',+ data: { text: 'Current reply', isFinal: true },+ },+ });+ const currentClientId = remoteSessionStore.getMessages('s1')[0]?.clientId;+ remoteSessionStore.applyRemotePush('current-mac', 'maker:event', {+ sessionId: 's1',+ event: { type: 'done', data: {} },+ });++ remoteSessionStore.applyRemotePush('stale-mac', 'maker:event', {+ sessionId: 's1',+ persistId: 'stale-persisted-assistant',+ event: {+ type: 'text',+ data: { text: 'Stale replay', isFinal: true },+ },+ });++ expect(currentClientId).toMatch(/^mobile-stream-/);+ expect(remoteSessionStore.getMessages('s1')).toMatchObject([{+ clientId: currentClientId,+ content: 'Current reply',+ }]);+ } finally {+ vi.useRealTimers();+ }+ });++ it('allows a replacement transport when no authoritative device identity is available', () => {+ vi.useFakeTimers();+ try {+ remoteSessionStore.setDeviceSessions('stale-mac', 'Mac', [session('s1')]);+ remoteSessionStore.applyRemotePush('stale-mac', 'maker:event', {+ sessionId: 's1',+ persistId: 'shared-live-assistant',+ event: {+ type: 'text',+ data: { text: 'Stale reply', isFinal: true },+ },+ });+ remoteSessionStore.applyRemotePush('current-mac', 'maker:event', {+ sessionId: 's1',+ persistId: 'shared-live-assistant',+ event: {+ type: 'text',+ data: { text: 'Current reply', isFinal: true },+ },+ });++ remoteSessionStore.removeDevice('stale-mac');+ expect(remoteSessionStore.getMessages('s1')).toMatchObject([{+ clientId: 'shared-live-assistant',+ content: 'Current reply',+ }]);+ } finally {+ vi.useRealTimers();+ }+ });++ it('lets the canonical current transport replace an indexed stale assembly', () => {+ vi.useFakeTimers();+ try {+ remoteSessionStore.setDeviceIdentity([{ deviceId: 'current-mac', name: 'Mac' }]);+ remoteSessionStore.setDeviceSessions('stale-mac', 'Mac', [session('s1')]);+ remoteSessionStore.applyRemotePush('stale-mac', 'maker:event', {+ sessionId: 's1',+ persistId: 'shared-live-assistant',+ event: {+ type: 'text',+ data: { text: 'Stale reply', isFinal: true },+ },+ });+ remoteSessionStore.applyRemotePush('current-mac', 'maker:event', {+ sessionId: 's1',+ persistId: 'shared-live-assistant',+ event: {+ type: 'text',+ data: { text: 'Current reply', isFinal: true },+ },+ });++ remoteSessionStore.removeDevice('stale-mac');+ expect(remoteSessionStore.getMessages('s1')).toMatchObject([{+ clientId: 'shared-live-assistant',+ content: 'Current reply',+ }]);+ } finally {+ vi.useRealTimers();+ }+ });++ it('writes canonicalDeviceId for a stale shard uniquely matching a current device, keeping deviceLinkDeviceId physical', () => {+ remoteSessionStore.setDeviceIdentity([{ deviceId: 'current-mac', name: 'Lizi Mac' }]);+ remoteSessionStore.setDeviceSessions('current-mac', 'Lizi Mac', [session('s-current')]);+ remoteSessionStore.setDeviceSessions('stale-mac', 'Lizi Mac', [session('s-stale')]);++ const byId = new Map(remoteSessionStore.getSessions().map((s) => [s.id, s]));+ // 展示维度:两条都认领到 current-mac(详情页按 canonicalDeviceId 过滤时同时可见)。+ expect(byId.get('s-current')?.canonicalDeviceId).toBe('current-mac');+ expect(byId.get('s-stale')?.canonicalDeviceId).toBe('current-mac');+ // 路由维度:deviceLinkDeviceId 保持物理 shard id,sessionDeviceIndex 指向物理 shard(patch 不丢)。+ expect(byId.get('s-stale')?.deviceLinkDeviceId).toBe('stale-mac');+ expect(remoteSessionStore.getSessionDeviceId('s-stale')).toBe('stale-mac');+ });++ it('dedupes the same session id across stale/current shards, keeping the current shard copy', () => {+ remoteSessionStore.setDeviceIdentity([{ deviceId: 'current-mac', name: 'Lizi Mac' }]);+ // 同一 session id 同时出现在 stale 与 current 两个 shard(re-link 后旧 shard 残留)。+ remoteSessionStore.setDeviceSessions('stale-mac', 'Lizi Mac', [session('dup')]);+ remoteSessionStore.setDeviceSessions('current-mac', 'Lizi Mac', [session('dup')]);++ const rows = remoteSessionStore.getSessions().filter((s) => s.id === 'dup');+ expect(rows).toHaveLength(1); // 去重,不重复渲染+ expect(rows[0]?.deviceLinkDeviceId).toBe('current-mac'); // 保留 current shard 的真身+ expect(remoteSessionStore.getSessionDeviceId('dup')).toBe('current-mac');+ });++ it('does not merge two unknown same-name shards (canonicalDeviceId stays the original id)', () => {+ remoteSessionStore.setDeviceIdentity([]);+ remoteSessionStore.setDeviceSessions('ghost-1', 'MacBook Pro', [session('g1')]);+ remoteSessionStore.setDeviceSessions('ghost-2', 'MacBook Pro', [session('g2')]);++ const byId = new Map(remoteSessionStore.getSessions().map((s) => [s.id, s.canonicalDeviceId]));+ expect(byId.get('g1')).toBe('ghost-1');+ expect(byId.get('g2')).toBe('ghost-2');+ });++ it('leaves canonicalDeviceId equal to the physical shard id before any device identity is injected', () => {+ remoteSessionStore.setDeviceSessions('stale-mac', 'Lizi Mac', [session('s1')]);+ const s = remoteSessionStore.getSessions()[0];+ expect(s?.deviceLinkDeviceId).toBe('stale-mac');+ expect(s?.canonicalDeviceId).toBe('stale-mac');+ });++ it('does not claim when two stale shards share a name matching one current device', () => {+ remoteSessionStore.setDeviceIdentity([{ deviceId: 'current-mbp', name: 'MacBook Pro' }]);+ remoteSessionStore.setDeviceSessions('stale-1', 'MacBook Pro', [session('a')]);+ remoteSessionStore.setDeviceSessions('stale-2', 'MacBook Pro', [session('b')]);++ const byId = new Map(remoteSessionStore.getSessions().map((s) => [s.id, s.canonicalDeviceId]));+ // stale 侧同名歧义 → 不认领,保留各自物理 id,不并到 current-mbp。+ expect(byId.get('a')).toBe('stale-1');+ expect(byId.get('b')).toBe('stale-2');+ });++ it('ignores placeholder device names when claiming stale shards', () => {+ remoteSessionStore.setDeviceIdentity([{ deviceId: 'current-x', name: 'unknown' }]);+ remoteSessionStore.setDeviceSessions('stale-x', 'unknown', [session('p')]);+ // placeholder 名(unknown)不参与认领,stale-x 保留物理 id。+ expect(remoteSessionStore.getSessions().find((s) => s.id === 'p')?.canonicalDeviceId).toBe('stale-x');+ });+});++describe('maker:session-model-pref:changed push 路由', () => {+ it('路由进 sessionModelMirror(镜像可读),非法 payload 静默忽略', async () => {+ const { makeSessionMirrorAccessors, clearSessionMirror } = await import('@/session/sessionModelMirror');+ const acc = makeSessionMirrorAccessors('s-pref', vi.fn());+ remoteSessionStore.applyRemotePush('dev-1', 'maker:session-model-pref:changed', {+ sessionId: 's-pref',+ agent: 'codex',+ providerId: 'xd',+ model: 'gpt-5.5',+ effort: 'xhigh',+ fast: true,+ });+ expect(acc.getEffort('codex', 'xd', 'gpt-5.5')).toBe('xhigh');+ expect(acc.getFast('codex', 'xd', 'gpt-5.5')).toBe(true);++ remoteSessionStore.applyRemotePush('dev-1', 'maker:session-model-pref:changed', { nope: 1 });+ expect(acc.getEffort('codex', 'xd', 'nope')).toBeUndefined();+ clearSessionMirror('s-pref');+ });+});++describe('setDeviceSessions 对在途乐观创建行(pendingLocalCreation)的保护', () => {+ beforeEach(() => remoteSessionStore.clear());++ it('比建成更早发出的旧列表不含该 id:合成行保留,不从列表消失', () => {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s-old')]);+ remoteSessionStore.upsertDeviceSession('dev-1', 'Mac', session('s-new', { pendingLocalCreation: true }));++ // 首页 in-flight 的 sessions:list 响应此刻返回(发出时被控端还没建这个任务)。+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s-old')]);+ const rows = remoteSessionStore.getSessions();+ expect(rows.map((s) => s.id)).toContain('s-new');+ expect(rows.find((s) => s.id === 's-new')?.pendingLocalCreation).toBe(true);+ });++ it('建成后 enqueue 落定前的新列表含该 id 但无标:合并权威字段并保留禁发标', () => {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', []);+ remoteSessionStore.upsertDeviceSession('dev-1', 'Mac', session('s-new', { pendingLocalCreation: true, title: '本地草稿标题' }));++ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s-new', { title: '权威标题' })]);+ const row = remoteSessionStore.getSessions().find((s) => s.id === 's-new');+ expect(row?.title).toBe('权威标题');expect(row?.pendingLocalCreation).toBe(true);});- it('管线清标(pendingLocalCreation: false)后,列表对账恢复正常替换语义', () => {- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', []);- remoteSessionStore.upsertDeviceSession('dev-1', 'Mac', session('s-new', { pendingLocalCreation: true }));- remoteSessionStore.applySessionPatch('dev-1', 's-new', { pendingLocalCreation: false });+ it('管线清标(pendingLocalCreation: false)后,列表对账恢复正常替换语义', () => {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', []);+ remoteSessionStore.upsertDeviceSession('dev-1', 'Mac', session('s-new', { pendingLocalCreation: true }));+ remoteSessionStore.applySessionPatch('dev-1', 's-new', { pendingLocalCreation: false });++ // 不含该 id 的列表到达:行不再受保护(正常对账,如会话被其它控制端删除)。+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s-old')]);+ expect(remoteSessionStore.getSessions().map((s) => s.id)).toEqual(['s-old']);+ });+});++describe('setDeviceSessions 在途元数据写保护(sessionPendingWrites)', () => {+ beforeEach(() => remoteSessionStore.clear());++ it('在途字段不被旧快照冲掉,其余字段照常吃快照(review P1:重连全量对账)', () => {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', { title: '旧名' })]);+ const release = sessionPendingWrites.track('s1', ['title']);+ remoteSessionStore.applySessionPatch('dev-1', 's1', { title: '新名' });+ // 重连全量拉到旧快照:title 仍是旧名,但 updatedAt 已推进+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [+ session('s1', { title: '旧名', updatedAt: '2026-01-02T00:00:00.000Z' }),+ ]);+ const row = remoteSessionStore.getSessions().find((s) => s.id === 's1');+ expect(row?.title).toBe('新名');+ expect(row?.updatedAt).toBe('2026-01-02T00:00:00.000Z');+ // overlay 藏掉了与本地不同的权威快照值 → 留差异痕,由写的结局 consume 触发 reseed+ expect(sessionPendingWrites.consumeMaskedPush('s1', ['title'])).toBe(true);+ release();+ });++ it('乐观移出的行(删除/归档在途)不随旧快照复活;release 后恢复正常对账', () => {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1'), session('s2')]);+ const release = sessionPendingWrites.track('s1', ['status']);+ remoteSessionStore.applySessionPatch('dev-1', 's1', { status: 'deleted' });+ expect(remoteSessionStore.getSessions().map((s) => s.id)).toEqual(['s2']);+ // 重连全量拉到旧快照(被控端还没处理删除,s1 仍在):不得复活+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1'), session('s2')]);+ expect(remoteSessionStore.getSessions().map((s) => s.id)).toEqual(['s2']);+ // 写 settle 后,后续快照按正常语义对账(若被控端确认删除,新快照不含 s1)+ release();+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s2')]);+ expect(remoteSessionStore.getSessions().map((s) => s.id)).toEqual(['s2']);+ });++ it('restore 在途把行加回列表:旧快照缺失该行时不抹掉,写 settle 后恢复正常对账(review P2)', () => {+ // 归档会话 s1 不在活跃列表;详情页 restore:乐观 status=active 把行加回+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s2')]);+ remoteSessionStore.upsertDeviceSession('dev-1', 'Mac', session('s1', { status: 'active' }));+ const release = sessionPendingWrites.track('s1', ['status']);+ // 重连全量拉到旧快照(被控端未处理 restore,s1 仍归档不在列表):不得抹掉乐观行+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s2')]);+ expect(remoteSessionStore.getSessions().map((s) => s.id).sort()).toEqual(['s1', 's2']);+ // 写 settle 后正常对账:后续快照不含 s1(如 restore 失败回滚)则移除+ release();+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s2')]);+ expect(remoteSessionStore.getSessions().map((s) => s.id)).toEqual(['s2']);+ });++ it('无在途写时全量对账语义不变', () => {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', { title: 'A' })]);+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', { title: 'B' })]);+ expect(remoteSessionStore.getSessions().find((s) => s.id === 's1')?.title).toBe('B');+ });+});++describe('引用调和(2026-07-18 首页重渲染风暴修复)', () => {+ beforeEach(() => remoteSessionStore.clear());++ it('setDeviceSessions:单会话变化时,其余会话保留旧对象引用', () => {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1'), session('s2'), session('s3')]);+ const before = remoteSessionStore.getSessions();+ const s1Before = before.find((s) => s.id === 's1');+ const s3Before = before.find((s) => s.id === 's3');+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [+ session('s1'),+ session('s2', { updatedAt: '2026-01-02T00:00:00.000Z' }),+ session('s3'),+ ]);+ const after = remoteSessionStore.getSessions();+ expect(after).not.toBe(before);+ expect(after.find((s) => s.id === 's1')).toBe(s1Before);+ expect(after.find((s) => s.id === 's3')).toBe(s3Before);+ expect(after.find((s) => s.id === 's2')).not.toBe(before.find((s) => s.id === 's2'));+ });++ it('upsert 置顶重排:数组换新但内容未变的会话对象引用保留', () => {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1'), session('s2')]);+ const before = remoteSessionStore.getSessions();+ const s1Before = before.find((s) => s.id === 's1');+ const s2Before = before.find((s) => s.id === 's2');+ remoteSessionStore.upsertDeviceSession('dev-1', 'Mac', session('s2'));+ const after = remoteSessionStore.getSessions();+ expect(after[0]).toBe(s2Before);+ expect(after.find((s) => s.id === 's1')).toBe(s1Before);+ });++ it('设备身份归一化下,与会话内容无关的重算保留 mergedSessions 数组引用', () => {+ // 归一化分支每轮都会 {...session, canonicalDeviceId} 重铸对象,调和必须能吸收它,+ // 否则 useSyncExternalStore 快照逐 emit 换新引用,消费屏全量重渲染(风暴根因)。+ remoteSessionStore.setDeviceIdentity([{ deviceId: 'dev-1', name: 'Mac' }]);+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1'), session('s2')]);+ const before = remoteSessionStore.getSessions();+ remoteSessionStore.setDeviceIdentity([+ { deviceId: 'dev-1', name: 'Mac' },+ { deviceId: 'dev-9', name: 'Other' },+ ]);+ expect(remoteSessionStore.getSessions()).toBe(before);+ });++ it('跨设备:另一设备 shard 变化不换本设备会话的对象引用', () => {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);+ const s1Before = remoteSessionStore.getSessions().find((s) => s.id === 's1');+ remoteSessionStore.setDeviceSessions('dev-2', 'Win', [session('w1')]);+ expect(remoteSessionStore.getSessions().find((s) => s.id === 's1')).toBe(s1Before);+ remoteSessionStore.removeDevice('dev-2');+ expect(remoteSessionStore.getSessions().find((s) => s.id === 's1')).toBe(s1Before);+ });++ it('风暴不变量:消息/运行态/活动高频 churn + 内容等价重算下,会话列表快照引用零漂移', () => {+ // 桌面端流式输出 = appendMessage / status / activity 事件以每秒多条的频率灌入,+ // 其间还夹杂设备表更新等触发 recomputeSessions 的内容等价重算(归一化分支每轮+ // 都会重铸对象,必须被引用调和吸收)。这些都不改变会话列表内容,getSessions()+ // 快照必须保持同一引用——它是 useRemoteSessions 消费屏(首页/设备详情)不被+ // 无关 emit 惊动的结构保证,重构后回归验证的核心断言(2026-07-18 风暴修复;+ // 每轮 setDeviceIdentity 在修复前的 store 上会真实打红本用例)。+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1'), session('s2')]);+ const snapshot = remoteSessionStore.getSessions();+ for (let i = 0; i < 50; i += 1) {+ remoteSessionStore.appendMessage('s1', {+ id: `m${i}`,+ clientId: `m${i}`,+ sessionId: 's1',+ role: 'assistant',+ content: `chunk ${i}`,+ toolUseId: null,+ agentMeta: null,+ createdAt: `2026-01-01T00:00:${String(i).padStart(2, '0')}.000Z`,+ });+ remoteSessionStore.applyMakerEvent('s1', { type: 'status', data: { isRunning: true, tokenUsage: i + 1 } });+ remoteSessionStore.applySessionActivity('dev-1', {+ sessionId: 's1',+ phase: 'running',+ compactDetail: `step ${i}`,+ });+ // 每轮设备表变化(无关设备增补)强制走一次 recomputeSessions:会话内容等价,+ // 归一化重铸的对象必须被调和吸收,快照引用不许漂移。+ remoteSessionStore.setDeviceIdentity([+ { deviceId: 'dev-1', name: 'Mac' },+ { deviceId: `ghost-${i}`, name: `G${i}` },+ ]);+ }+ expect(remoteSessionStore.getSessions()).toBe(snapshot);+ });+});++describe('maker:event 微批拆包(CONTROLLER_CAPABILITY_MAKER_EVENT_BATCH_V1)', () => {+ it('批内事件按序走与逐帧完全相同的路径:流式增量拼接结果一致', () => {+ vi.useFakeTimers();+ try {+ // 逐帧基线+ pushMakerText('s-single', 'p-1', 'hello', false);+ pushMakerText('s-single', 'p-1', ' world', false);+ vi.runOnlyPendingTimers();+ const single = remoteSessionStore.getMessages('s-single');++ // 同样两条事件,这次由被控端合并成一帧微批下发+ remoteSessionStore.applyRemotePush('dev-1', MAKER_EVENT_BATCH_CHANNEL, {+ sessionId: 's-batch',+ events: [+ { sessionId: 's-batch', persistId: 'p-1', event: { type: 'text', data: { text: 'hello', isFinal: false } } },+ { sessionId: 's-batch', persistId: 'p-1', event: { type: 'text', data: { text: ' world', isFinal: false } } },+ ],+ });+ vi.runOnlyPendingTimers();+ const batched = remoteSessionStore.getMessages('s-batch');++ expect(batched).toHaveLength(1);+ expect(batched[0]).toMatchObject({ id: 'p-1', role: 'assistant', content: 'hello world' });+ // 与逐帧结果逐字段一致(仅 sessionId 不同)+ expect(batched[0]!.content).toBe(single[0]!.content);+ } finally {+ vi.useRealTimers();+ }+ });++ it('形状不符的批帧整体忽略;批内单条坏事件只跳过该条', () => {+ vi.useFakeTimers();+ try {+ // 缺 events / events 为空 / 非数组:整帧忽略,不抛+ for (const bad of [+ { sessionId: 's-bad' },+ { sessionId: 's-bad', events: [] },+ { sessionId: 's-bad', events: 'nope' },+ { events: [{}] },+ null,+ ]) {+ expect(() =>+ remoteSessionStore.applyRemotePush('dev-1', MAKER_EVENT_BATCH_CHANNEL, bad),+ ).not.toThrow();+ }+ vi.runOnlyPendingTimers();+ expect(remoteSessionStore.getMessages('s-bad')).toHaveLength(0);++ // 批内混入坏条目:好的照常生效+ remoteSessionStore.applyRemotePush('dev-1', MAKER_EVENT_BATCH_CHANNEL, {+ sessionId: 's-mixed',+ events: [+ 'not-an-object',+ { sessionId: 's-mixed', persistId: 'p-9', event: { type: 'text', data: { text: 'ok', isFinal: true } } },+ ],+ });+ vi.runOnlyPendingTimers();+ expect(remoteSessionStore.getMessages('s-mixed')).toHaveLength(1);+ expect(remoteSessionStore.getMessages('s-mixed')[0]).toMatchObject({ content: 'ok' });+ } finally {+ vi.useRealTimers();+ }+ });++ it('批内 sessionId 与顶层不一致的条目被丢弃:不绕过 topic 隔离', () => {+ // topic 路由只按**顶层** sessionId,批内混入其它会话的事件会把本端未订阅的+ // 会话数据投进来(坏帧/恶意帧场景)。fail-closed 跳过该条,不整批丢。+ vi.useFakeTimers();+ try {+ remoteSessionStore.applyRemotePush('dev-1', MAKER_EVENT_BATCH_CHANNEL, {+ sessionId: 's-own',+ events: [+ { sessionId: 's-other', persistId: 'p-x', event: { type: 'text', data: { text: 'leak', isFinal: true } } },+ { sessionId: 's-own', persistId: 'p-y', event: { type: 'text', data: { text: 'mine', isFinal: true } } },+ ],+ });+ vi.runOnlyPendingTimers();+ expect(remoteSessionStore.getMessages('s-other')).toHaveLength(0);+ expect(remoteSessionStore.getMessages('s-own')).toHaveLength(1);+ expect(remoteSessionStore.getMessages('s-own')[0]).toMatchObject({ content: 'mine' });+ } finally {+ vi.useRealTimers();+ }+ });+});++describe('任务消息内存治理', () => {+ beforeEach(() => remoteSessionStore.clear());++ const manyMessages = (sessionId: string, count: number): RemoteMessage[] =>+ Array.from({ length: count }, (_, index) => messageAt(+ `${sessionId}-m-${index}`,+ sessionId,+ new Date(Date.UTC(2026, 0, 1, 0, 0, index)).toISOString(),+ ));++ const flushReclaim = async (): Promise<void> => {+ await Promise.resolve();+ await Promise.resolve();+ };++ it('只按 source=scheduler 分类,标题与 source 缺失均保守按 regular', () => {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [+ session('schedule', { source: 'scheduler', title: '普通标题' }),+ session('legacy-title', { title: '[Schedule] 旧标题' }),+ session('bound', { source: 'user', title: '被定时器绑定' }),+ ]);++ expect(remoteSessionStore.getSessionRetention('schedule')).toBe('schedule');+ expect(remoteSessionStore.getSessionRetention('legacy-title')).toBe('regular');+ expect(remoteSessionStore.getSessionRetention('bound')).toBe('regular');+ });++ it('旧详情代际的读取在 blur→refocus 后不能覆盖新窗口', () => {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', { source: 'scheduler' })]);+ const first = remoteSessionStore.enterSessionMessageDetail('s1');+ remoteSessionStore.setMessages('s1', [message('first', 's1')], { authority: first });+ remoteSessionStore.leaveSessionMessageDetail('s1', 'detail-blur', first);+ const second = remoteSessionStore.enterSessionMessageDetail('s1');++ remoteSessionStore.setMessages('s1', [message('stale', 's1')], { authority: first });+ expect(remoteSessionStore.getMessages('s1').map((row) => row.id)).toEqual(['first']);++ remoteSessionStore.setMessages('s1', [message('fresh', 's1')], { authority: second });+ expect(remoteSessionStore.getMessages('s1').map((row) => row.id)).toEqual(['fresh']);+ });++ it('从未打开的 regular 可更新全局镜像,首次进入或离场后不再接受无 authority 补读', () => {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);+ const unenteredAuthority = remoteSessionStore.captureUnenteredSessionMessageAuthority('s1');+ expect(remoteSessionStore.hasSessionMessageDetailEntered('s1')).toBe(false);+ expect(remoteSessionStore.canCommitUnenteredSessionMessageWindow(unenteredAuthority, 'dev-1')).toBe(true);+ expect(remoteSessionStore.canCommitUnenteredSessionMessageWindow(unenteredAuthority, 'dev-2')).toBe(false);++ remoteSessionStore.setLatestMessageWindow('s1', [message('global-mirror', 's1')]);+ expect(remoteSessionStore.getMessages('s1').map((row) => row.id)).toEqual(['global-mirror']);++ const authority = remoteSessionStore.enterSessionMessageDetail('s1');+ expect(remoteSessionStore.hasSessionMessageDetailEntered('s1')).toBe(true);+ expect(remoteSessionStore.canCommitUnenteredSessionMessageWindow(unenteredAuthority, 'dev-1')).toBe(false);+ remoteSessionStore.leaveSessionMessageDetail('s1', 'detail-blur', authority);+ remoteSessionStore.setLatestMessageWindow('s1', [message('stale-reconnect', 's1')]);++ expect(remoteSessionStore.getMessages('s1').some((row) => row.id === 'stale-reconnect')).toBe(false);+ });++ it('从未打开的 schedule 不接受无 authority 的重连补读', () => {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [+ session('s1', { source: 'scheduler' }),+ ]);++ const unenteredAuthority = remoteSessionStore.captureUnenteredSessionMessageAuthority('s1');+ expect(remoteSessionStore.hasSessionMessageDetailEntered('s1')).toBe(false);+ expect(remoteSessionStore.canCommitUnenteredSessionMessageWindow(unenteredAuthority, 'dev-1')).toBe(false);+ remoteSessionStore.setLatestMessageWindow('s1', [message('schedule-reconnect', 's1')]);+ expect(remoteSessionStore.getMessages('s1')).toEqual([]);+ });++ it('clear 后同设备同任务重建也拒绝 reset 前的未进入详情读取', () => {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);+ const beforeReset = remoteSessionStore.captureUnenteredSessionMessageAuthority('s1');++ remoteSessionStore.clear();+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);++ expect(remoteSessionStore.canCommitUnenteredSessionMessageWindow(beforeReset, 'dev-1')).toBe(false);+ const afterReset = remoteSessionStore.captureUnenteredSessionMessageAuthority('s1');+ expect(remoteSessionStore.canCommitUnenteredSessionMessageWindow(afterReset, 'dev-1')).toBe(true);+ });++ it('schedule 失焦后回收到 0,后续 push 不会复活完整正文', async () => {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', { source: 'scheduler' })]);+ const authority = remoteSessionStore.enterSessionMessageDetail('s1');+ remoteSessionStore.setMessages('s1', [message('m1', 's1')], { authority });++ remoteSessionStore.leaveSessionMessageDetail('s1', 'detail-blur', authority);+ await flushReclaim();+ expect(remoteSessionStore.getMessages('s1')).toEqual([]);++ remoteSessionStore.applyRemotePush('dev-1', 'local-db:messages:created', {+ sessionId: 's1',+ message: message('late-push', 's1'),+ });+ expect(remoteSessionStore.getMessages('s1')).toEqual([]);+ });++ it('regular 离场后旧订阅 push 与尚未 flush 的流式批次都不能复活窗口', async () => {+ vi.useFakeTimers();+ try {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);+ const authority = remoteSessionStore.enterSessionMessageDetail('s1');+ remoteSessionStore.setMessages('s1', manyMessages('s1', 2), { authority });+ pushMakerText('s1', 'stream-1', 'queued delta', false);++ remoteSessionStore.leaveSessionMessageDetail('s1', 'detail-blur', authority);+ const nextAuthority = remoteSessionStore.enterSessionMessageDetail('s1');+ vi.runOnlyPendingTimers();+ remoteSessionStore.applyRemotePush('dev-1', 'local-db:messages:created', {+ sessionId: 's1',+ message: message('late-subscription-push', 's1'),+ });++ expect(remoteSessionStore.isSessionMessageAuthorityCurrent(nextAuthority)).toBe(true);+ expect(remoteSessionStore.getMessages('s1').map((row) => row.id)).toEqual([+ 's1-m-0',+ 'late-subscription-push',+ 's1-m-1',+ ]);+ // 上面的 push 是在新代际可见期间到达,应该保留;旧代际排队的 delta 不得出现。+ expect(remoteSessionStore.getMessages('s1').some((row) => row.id === 'stream-1')).toBe(false);++ remoteSessionStore.leaveSessionMessageDetail('s1', 'detail-blur', nextAuthority);+ await flushReclaim();+ remoteSessionStore.applyRemotePush('dev-1', 'local-db:messages:created', {+ sessionId: 's1',+ message: message('push-after-leave', 's1'),+ });+ expect(remoteSessionStore.getMessages('s1').some((row) => row.id === 'push-after-leave')).toBe(false);+ } finally {+ vi.useRealTimers();+ }+ });++ it('页面卸载后本地工作排空仍会完成 deferred reclaim', async () => {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', { source: 'scheduler' })]);+ const work = remoteSessionStore.acquireSessionMessageWork('s1', true);+ const authority = remoteSessionStore.enterSessionMessageDetail('s1');+ remoteSessionStore.setMessages('s1', [message('m1', 's1')], { authority });+ remoteSessionStore.leaveSessionMessageDetail('s1', 'session-switch', authority);++ await flushReclaim();+ expect(remoteSessionStore.getMessages('s1')).toHaveLength(1);+ work.release();+ await flushReclaim();+ expect(remoteSessionStore.getMessages('s1')).toEqual([]);+ });++ it('pending queue 暂缓 schedule 回收,queue 排空后由 store 主动补回收', async () => {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', { source: 'scheduler' })]);+ const authority = remoteSessionStore.enterSessionMessageDetail('s1');+ remoteSessionStore.setMessages('s1', [message('m1', 's1')], { authority });+ remoteSessionStore.setInputProjection('s1', projection('s1'));+ remoteSessionStore.leaveSessionMessageDetail('s1', 'app-background', authority);++ await flushReclaim();+ expect(remoteSessionStore.getMessages('s1')).toHaveLength(1);+ remoteSessionStore.setInputProjection('s1', {+ ...projection('s1'),+ pendingQueue: [],+ });+ await flushReclaim();+ expect(remoteSessionStore.getMessages('s1')).toEqual([]);+ });++ it('regular 失焦压回单窗,同时保留窗口外的本地系统卡', async () => {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);+ const authority = remoteSessionStore.enterSessionMessageDetail('s1');+ const localCard = {+ ...messageAt('mobile-system-pwd-old', 's1', '2025-12-31T23:59:59.000Z'),+ role: 'system' as const,+ };+ remoteSessionStore.setMessages('s1', [localCard, ...manyMessages('s1', 100)], { authority });+ remoteSessionStore.leaveSessionMessageDetail('s1', 'detail-blur', authority);+ await flushReclaim();++ const rows = remoteSessionStore.getMessages('s1');+ expect(rows).toHaveLength(80);+ expect(rows.some((row) => row.id === localCard.id)).toBe(true);+ expect(rows.at(-1)?.id).toBe('s1-m-99');+ });++ it('regular 全局 LRU 不淘汰当前详情,且总量压回约 800 条', () => {+ const sessions = Array.from({ length: 9 }, (_, index) => session(`s${index}`));+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', sessions);+ remoteSessionStore.enterSessionMessageDetail('s0');+ for (const item of sessions) {+ remoteSessionStore.setMessages(item.id, manyMessages(item.id, 100));+ }++ const total = sessions.reduce(+ (sum, item) => sum + remoteSessionStore.getMessages(item.id).length,+ 0,+ );+ expect(total).toBeLessThanOrEqual(800);+ expect(remoteSessionStore.getMessages('s0')).toHaveLength(100);+ expect(sessions.slice(1).some((item) => remoteSessionStore.getMessages(item.id).length === 0)).toBe(true);+ });++ it('regular LRU 只淘汰可重取正文,不丢尚未落盘的本地系统卡', () => {+ const sessions = Array.from({ length: 9 }, (_, index) => session(`s${index}`));+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', sessions);+ const localCard = {+ ...messageAt('mobile-system-local-only', 's0', '2025-12-31T23:59:59.000Z'),+ role: 'system' as const,+ };+ remoteSessionStore.setMessages('s0', [localCard, ...manyMessages('s0', 99)]);+ for (const item of sessions.slice(1)) {+ remoteSessionStore.setMessages(item.id, manyMessages(item.id, 100));+ }++ expect(remoteSessionStore.getMessages('s0')).toHaveLength(100);+ expect(remoteSessionStore.getMessages('s0').some((row) => row.id === localCard.id)).toBe(true);+ });++ it('regular 离场释放详情投影并拒绝离场前启动的旧投影查询', async () => {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);+ const authority = remoteSessionStore.enterSessionMessageDetail('s1');+ remoteSessionStore.setMessages('s1', [message('m1', 's1')], { authority });+ remoteSessionStore.setInputProjection('s1', {+ ...projection('s1'),+ pendingQueue: [],+ });+ const queryEpoch = remoteSessionStore.captureInputProjectionAuthorityEpoch('s1');++ remoteSessionStore.leaveSessionMessageDetail('s1', 'detail-blur', authority);+ await flushReclaim();++ expect(remoteSessionStore.getInputProjection('s1').pendingQueue).toEqual([]);+ expect(remoteSessionStore.setInputProjectionIfCurrent(+ 's1',+ projection('s1'),+ queryEpoch,+ )).toBe(false);+ });++ it('source 晚到改判 schedule:当前详情立即压窗,失焦后归零', async () => {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);+ const authority = remoteSessionStore.enterSessionMessageDetail('s1');+ remoteSessionStore.setMessages('s1', manyMessages('s1', 100), { authority });++ remoteSessionStore.upsertDeviceSession('dev-1', 'Mac', session('s1', { source: 'scheduler' }));+ expect(remoteSessionStore.getSessionRetention('s1')).toBe('schedule');+ expect(remoteSessionStore.getMessages('s1')).toHaveLength(80);++ remoteSessionStore.leaveSessionMessageDetail('s1', 'detail-blur');+ await flushReclaim();+ expect(remoteSessionStore.getMessages('s1')).toEqual([]);+ });++ it('归档会话会撤销旧 authority,并拒绝迟到 push 复活正文', () => {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);+ const authority = remoteSessionStore.enterSessionMessageDetail('s1');+ remoteSessionStore.setMessages('s1', [message('before-archive', 's1')], { authority });- // 不含该 id 的列表到达:行不再受保护(正常对账,如会话被其它控制端删除)。- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s-old')]);- expect(remoteSessionStore.getSessions().map((s) => s.id)).toEqual(['s-old']);+ remoteSessionStore.applySessionPatch('dev-1', 's1', { status: 'archived' });+ remoteSessionStore.applyRemotePush('dev-1', 'local-db:messages:created', {+ sessionId: 's1',+ message: message('late-after-archive', 's1'),+ });++ expect(remoteSessionStore.isSessionMessageAuthorityCurrent(authority)).toBe(false);+ expect(remoteSessionStore.getMessages('s1')).toEqual([]);+ });++ it('显式失效 rewind 窗口会清正文、sync marker 并登记刷新', () => {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);+ const authority = remoteSessionStore.enterSessionMessageDetail('s1');+ remoteSessionStore.setMessages('s1', [message('before-rewind', 's1')], { authority });+ const row = remoteSessionStore.getSessions().find((item) => item.id === 's1')!;+ remoteSessionStore.markSessionMessagesSynced('s1', row);++ remoteSessionStore.invalidateSessionMessageWindow('s1', 'dev-1');++ expect(remoteSessionStore.getMessages('s1')).toEqual([]);+ expect(remoteSessionStore.isSessionMessageWindowSynced('s1', row)).toBe(false);+ expect(remoteSessionStore.hasPendingRefresh('s1')).toBe(true);+ expect(remoteSessionStore.isSessionMessageAuthorityCurrent(authority)).toBe(true);});});-describe('setDeviceSessions 在途元数据写保护(sessionPendingWrites)', () => {+describe('device-clock live row clamp (applyRemoteTextEvent createdAt, cross-clock-domain sort fix)', () => {beforeEach(() => remoteSessionStore.clear());- it('在途字段不被旧快照冲掉,其余字段照常吃快照(review P1:重连全量对账)', () => {- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', { title: '旧名' })]);- const release = sessionPendingWrites.track('s1', ['title']);- remoteSessionStore.applySessionPatch('dev-1', 's1', { title: '新名' });- // 重连全量拉到旧快照:title 仍是旧名,但 updatedAt 已推进- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [- session('s1', { title: '旧名', updatedAt: '2026-01-02T00:00:00.000Z' }),- ]);- const row = remoteSessionStore.getSessions().find((s) => s.id === 's1');- expect(row?.title).toBe('新名');- expect(row?.updatedAt).toBe('2026-01-02T00:00:00.000Z');- // overlay 藏掉了与本地不同的权威快照值 → 留差异痕,由写的结局 consume 触发 reseed- expect(sessionPendingWrites.consumeMaskedPush('s1', ['title'])).toBe(true);- release();+ it('clampLiveRowCreatedAt: 无既有基准时原样返回设备时间', () => {+ expect(clampLiveRowCreatedAt('2026-01-01T00:00:05.000Z', undefined))+ .toBe('2026-01-01T00:00:05.000Z');});- it('乐观移出的行(删除/归档在途)不随旧快照复活;release 后恢复正常对账', () => {- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1'), session('s2')]);- const release = sessionPendingWrites.track('s1', ['status']);- remoteSessionStore.applySessionPatch('dev-1', 's1', { status: 'deleted' });- expect(remoteSessionStore.getSessions().map((s) => s.id)).toEqual(['s2']);- // 重连全量拉到旧快照(被控端还没处理删除,s1 仍在):不得复活- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1'), session('s2')]);- expect(remoteSessionStore.getSessions().map((s) => s.id)).toEqual(['s2']);- // 写 settle 后,后续快照按正常语义对账(若被控端确认删除,新快照不含 s1)- release();- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s2')]);- expect(remoteSessionStore.getSessions().map((s) => s.id)).toEqual(['s2']);+ it('clampLiveRowCreatedAt: 设备时间领先于既有基准 → 锚定既有基准,不让快设备时钟支配后续主机行', () => {+ expect(clampLiveRowCreatedAt('2026-01-01T00:00:05.000Z', '2026-01-01T00:00:01.000Z'))+ .toBe('2026-01-01T00:00:01.000Z');});- it('restore 在途把行加回列表:旧快照缺失该行时不抹掉,写 settle 后恢复正常对账(review P2)', () => {- // 归档会话 s1 不在活跃列表;详情页 restore:乐观 status=active 把行加回- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s2')]);- remoteSessionStore.upsertDeviceSession('dev-1', 'Mac', session('s1', { status: 'active' }));- const release = sessionPendingWrites.track('s1', ['status']);- // 重连全量拉到旧快照(被控端未处理 restore,s1 仍归档不在列表):不得抹掉乐观行- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s2')]);- expect(remoteSessionStore.getSessions().map((s) => s.id).sort()).toEqual(['s1', 's2']);- // 写 settle 后正常对账:后续快照不含 s1(如 restore 失败回滚)则移除- release();- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s2')]);- expect(remoteSessionStore.getSessions().map((s) => s.id)).toEqual(['s2']);+ it('clampLiveRowCreatedAt: 设备时间与既有基准相同 → 原样返回(打平,交给 compareMessageOrder 的 rowid/到达序兜底)', () => {+ expect(clampLiveRowCreatedAt('2026-01-01T00:00:05.000Z', '2026-01-01T00:00:05.000Z'))+ .toBe('2026-01-01T00:00:05.000Z');});- it('无在途写时全量对账语义不变', () => {- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', { title: 'A' })]);- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', { title: 'B' })]);- expect(remoteSessionStore.getSessions().find((s) => s.id === 's1')?.title).toBe('B');+ it('clampLiveRowCreatedAt: 设备时间落后于既有基准 → 钳制为既有基准本身,不发明 +1ms', () => {+ expect(clampLiveRowCreatedAt('2026-01-01T00:00:01.000Z', '2026-01-01T00:00:05.000Z'))+ .toBe('2026-01-01T00:00:05.000Z');});-});-describe('引用调和(2026-07-18 首页重渲染风暴修复)', () => {- beforeEach(() => remoteSessionStore.clear());+ it('设备时钟落后会话已知最新行时,新建的 live 行不再被排到该行之前(跨时钟域错位的修复现场)', () => {+ vi.useFakeTimers();+ try {+ // 会话里已有一条 createdAt 更新的行(可能是刚持久化的用户消息,也可能是更早一次+ // 已经落定的 live 行),随后设备本地时钟给出的「现在」比它更旧 —— 这正是本 bug 的+ // 跨时钟域场景(不论具体是设备落后还是设备超前,症状同源:新行的设备戳不保证+ // ≥ 会话已知最新行,可能被排到它前面,`getMessages` 尾部就不是最新内容)。+ remoteSessionStore.setLatestMessageWindow('s1', [+ messageAt('user-sent', 's1', '2026-01-01T00:10:00.000Z'),+ ]);+ vi.setSystemTime(new Date('2026-01-01T00:05:00.000Z'));+ pushMakerText('s1', 'live-assistant', 'streaming reply', true);- it('setDeviceSessions:单会话变化时,其余会话保留旧对象引用', () => {- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1'), session('s2'), session('s3')]);- const before = remoteSessionStore.getSessions();- const s1Before = before.find((s) => s.id === 's1');- const s3Before = before.find((s) => s.id === 's3');- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [- session('s1'),- session('s2', { updatedAt: '2026-01-02T00:00:00.000Z' }),- session('s3'),- ]);- const after = remoteSessionStore.getSessions();- expect(after).not.toBe(before);- expect(after.find((s) => s.id === 's1')).toBe(s1Before);- expect(after.find((s) => s.id === 's3')).toBe(s3Before);- expect(after.find((s) => s.id === 's2')).not.toBe(before.find((s) => s.id === 's2'));+ const rows = remoteSessionStore.getMessages('s1');+ // 钳制后,新 live 行的 createdAt 被拉到「已知最新行」自身(打平),稳定排序下+ // 仍落在其后 —— 不再被排到 user-sent 前面(修复前会因为设备戳更早而插到它前面,+ // 尾部就会显示旧内容而不是刚发生的这条)。+ expect(rows.map((item) => item.clientId)).toEqual(['user-sent', 'live-assistant']);+ expect(rows.find((item) => item.clientId === 'live-assistant')?.createdAt)+ .toBe('2026-01-01T00:10:00.000Z');+ } finally {+ vi.useRealTimers();+ }});- it('upsert 置顶重排:数组换新但内容未变的会话对象引用保留', () => {- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1'), session('s2')]);- const before = remoteSessionStore.getSessions();- const s1Before = before.find((s) => s.id === 's1');- const s2Before = before.find((s) => s.id === 's2');- remoteSessionStore.upsertDeviceSession('dev-1', 'Mac', session('s2'));- const after = remoteSessionStore.getSessions();- expect(after[0]).toBe(s2Before);- expect(after.find((s) => s.id === 's1')).toBe(s1Before);+ it('设备时钟快于主机时,后续主机持久化消息仍能排到旧 live 行之后', () => {+ vi.useFakeTimers();+ try {+ remoteSessionStore.setLatestMessageWindow('s1', [+ {+ ...messageAt('previous-user', 's1', '2026-01-01T00:00:00.000Z'),+ role: 'user',+ },+ ]);+ vi.setSystemTime(new Date('2026-01-01T00:10:00.000Z'));+ pushMakerText('s1', 'stale-live-assistant', 'previous streaming reply', true);++ remoteSessionStore.appendMessage('s1', {+ ...messageAt('new-user', 's1', '2026-01-01T00:05:00.000Z'),+ role: 'user',+ });++ const rows = remoteSessionStore.getMessages('s1');+ expect(rows.map((item) => item.clientId)).toEqual([+ 'previous-user',+ 'stale-live-assistant',+ 'new-user',+ ]);+ expect(rows.find((item) => item.clientId === 'stale-live-assistant')?.createdAt)+ .toBe('2026-01-01T00:00:00.000Z');+ } finally {+ vi.useRealTimers();+ }});- it('设备身份归一化下,与会话内容无关的重算保留 mergedSessions 数组引用', () => {- // 归一化分支每轮都会 {...session, canonicalDeviceId} 重铸对象,调和必须能吸收它,- // 否则 useSyncExternalStore 快照逐 emit 换新引用,消费屏全量重渲染(风暴根因)。- remoteSessionStore.setDeviceIdentity([{ deviceId: 'dev-1', name: 'Mac' }]);- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1'), session('s2')]);- const before = remoteSessionStore.getSessions();- remoteSessionStore.setDeviceIdentity([- { deviceId: 'dev-1', name: 'Mac' },- { deviceId: 'dev-9', name: 'Other' },- ]);- expect(remoteSessionStore.getSessions()).toBe(before);+ it('会话 userSendAt 已越过旧 user 尾行时,当前 live 回复仍等待本轮 user push 重锚', () => {+ vi.useFakeTimers();+ try {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', {+ userSendAt: '2026-01-01T00:00:02.000Z',+ updatedAt: '2026-01-01T00:00:02.000Z',+ })]);+ remoteSessionStore.setLatestMessageWindow('s1', [{+ ...messageAt('previous-user', 's1', '2026-01-01T00:00:01.000Z'),+ role: 'user',+ content: 'Previous question',+ }]);+ vi.setSystemTime(new Date('2026-01-01T00:10:00.000Z'));+ pushMakerText('s1', 'current-live-assistant', 'Current reply', true);++ expect(remoteSessionStore.getMessages('s1')+ .find((item) => item.clientId === 'current-live-assistant')?.createdAt)+ .toBe('2026-01-01T00:00:02.000Z');++ remoteSessionStore.appendMessage('s1', {+ ...messageAt('current-user', 's1', '2026-01-01T00:00:02.000Z'),+ role: 'user',+ content: 'Current question',+ });++ const rows = remoteSessionStore.getMessages('s1');+ expect(rows.map((item) => item.clientId)).toEqual([+ 'previous-user',+ 'current-user',+ 'current-live-assistant',+ ]);+ expect(rows.slice(1).map((item) => item.createdAt)).toEqual([+ '2026-01-01T00:00:02.000Z',+ '2026-01-01T00:00:02.000Z',+ ]);+ } finally {+ vi.useRealTimers();+ }+ });++ it('空消息窗先用会话 userSendAt 临时锚定短 live 行,再由权威消息完成重锚', () => {+ vi.useFakeTimers();+ try {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', {+ userSendAt: '2026-01-01T00:00:00.000Z',+ updatedAt: '2026-01-01T00:00:00.000Z',+ })]);+ vi.setSystemTime(new Date('2026-01-01T00:10:00.000Z'));+ pushMakerText('s1', undefined, 'OK', true);++ expect(remoteSessionStore.getMessages('s1')[0]?.createdAt)+ .toBe('2026-01-01T00:00:00.000Z');++ remoteSessionStore.appendMessage('s1', {+ ...messageAt('persisted-short', 's1', '2026-01-01T00:00:01.000Z'),+ content: 'OK',+ });++ const rows = remoteSessionStore.getMessages('s1');+ expect(rows).toHaveLength(2);+ expect(rows[0]?.clientId).toMatch(/^mobile-stream-/);+ expect(rows[0]?.createdAt).toBe('2026-01-01T00:00:01.000Z');+ expect(rows[1]?.clientId).toBe('persisted-short');+ } finally {+ vi.useRealTimers();+ }+ });++ it('首个短 live 行早于会话元数据时,元数据到达后把设备时间重锚到主机时间域', () => {+ vi.useFakeTimers();+ try {+ vi.setSystemTime(new Date('2026-01-01T00:10:00.000Z'));+ pushMakerText('s1', undefined, 'OK', true);++ expect(remoteSessionStore.getMessages('s1')[0]?.createdAt)+ .toBe('2026-01-01T00:10:00.000Z');++ remoteSessionStore.upsertDeviceSession('dev-1', 'Mac', session('s1', {+ userSendAt: '2026-01-01T00:00:00.000Z',+ updatedAt: '2026-01-01T00:00:00.000Z',+ }));++ expect(remoteSessionStore.getMessages('s1')[0]?.createdAt)+ .toBe('2026-01-01T00:00:00.000Z');++ remoteSessionStore.appendMessage('s1', {+ ...messageAt('persisted-short', 's1', '2026-01-01T00:00:01.000Z'),+ content: 'OK',+ });++ const rows = remoteSessionStore.getMessages('s1');+ expect(rows).toHaveLength(2);+ expect(rows[0]?.clientId).toMatch(/^mobile-stream-/);+ expect(rows[0]?.createdAt).toBe('2026-01-01T00:00:01.000Z');+ expect(rows[1]?.clientId).toBe('persisted-short');+ } finally {+ vi.useRealTimers();+ }+ });++ it('旧会话快照只做临时重锚,后续权威 user push 仍会恢复问题先于 live 回复', () => {+ vi.useFakeTimers();+ try {+ vi.setSystemTime(new Date('2026-01-01T00:10:00.000Z'));+ pushMakerText('s1', 'live-assistant', 'OK', true);++ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', {+ userSendAt: '2026-01-01T00:00:00.000Z',+ updatedAt: '2026-01-01T00:00:00.000Z',+ })]);++ expect(remoteSessionStore.getMessages('s1')[0]?.createdAt)+ .toBe('2026-01-01T00:00:00.000Z');++ remoteSessionStore.appendMessage('s1', {+ ...messageAt('persisted-user', 's1', '2026-01-01T00:00:01.000Z'),+ role: 'user',+ content: 'Question',+ });++ const rows = remoteSessionStore.getMessages('s1');+ expect(rows.map((item) => item.clientId)).toEqual([+ 'persisted-user',+ 'live-assistant',+ ]);+ expect(rows.map((item) => item.createdAt)).toEqual([+ '2026-01-01T00:00:01.000Z',+ '2026-01-01T00:00:01.000Z',+ ]);+ } finally {+ vi.useRealTimers();+ }+ });++ it('只有旧会话快照水位时,随后创建的 live 行也会等待权威消息重锚', () => {+ vi.useFakeTimers();+ try {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', {+ userSendAt: '2026-01-01T00:00:00.000Z',+ updatedAt: '2026-01-01T00:00:00.000Z',+ })]);+ vi.setSystemTime(new Date('2026-01-01T00:10:00.000Z'));+ pushMakerText('s1', 'live-assistant', 'OK', true);++ remoteSessionStore.appendMessage('s1', {+ ...messageAt('persisted-user', 's1', '2026-01-01T00:00:01.000Z'),+ role: 'user',+ content: 'Question',+ });++ const rows = remoteSessionStore.getMessages('s1');+ expect(rows.map((item) => item.clientId)).toEqual([+ 'persisted-user',+ 'live-assistant',+ ]);+ expect(rows.map((item) => item.createdAt)).toEqual([+ '2026-01-01T00:00:01.000Z',+ '2026-01-01T00:00:01.000Z',+ ]);+ } finally {+ vi.useRealTimers();+ }+ });++ it('发送前发起的旧消息窗口迟到时不消费 live 行待重锚身份', () => {+ vi.useFakeTimers();+ try {+ // 此时发送前的 history 请求已经发出,但本地窗口尚未拿到任何主机时间水位。+ vi.setSystemTime(new Date('2026-01-01T00:10:00.000Z'));+ pushMakerText('s1', 'live-assistant', 'Current reply', true);++ // 这份窗口在发送前已经开始读取,返回时不含本轮 user 行。它可以临时把 live+ // 行拉回主机时间域,但不能消费待重锚身份;否则后续权威 user push 无法恢复顺序。+ remoteSessionStore.setLatestMessageWindow('s1', [+ messageAt('previous-assistant', 's1', '2026-01-01T00:00:00.000Z'),+ ]);++ remoteSessionStore.appendMessage('s1', {+ ...messageAt('current-user', 's1', '2026-01-01T00:00:01.000Z'),+ role: 'user',+ content: 'Current question',+ });++ const rows = remoteSessionStore.getMessages('s1');+ expect(rows.map((item) => item.clientId)).toEqual([+ 'previous-assistant',+ 'current-user',+ 'live-assistant',+ ]);+ expect(rows.slice(1).map((item) => item.createdAt)).toEqual([+ '2026-01-01T00:00:01.000Z',+ '2026-01-01T00:00:01.000Z',+ ]);+ } finally {+ vi.useRealTimers();+ }+ });++ it('非空会话的旧 assistant 尾行不能让当前 live 回复失去待重锚资格', () => {+ vi.useFakeTimers();+ try {+ remoteSessionStore.setLatestMessageWindow('s1', [+ messageAt('previous-assistant', 's1', '2026-01-01T00:00:00.000Z'),+ ]);+ vi.setSystemTime(new Date('2026-01-01T00:10:00.000Z'));+ pushMakerText('s1', 'current-live-assistant', 'Current reply', true);++ remoteSessionStore.appendMessage('s1', {+ ...messageAt('current-user', 's1', '2026-01-01T00:00:01.000Z'),+ role: 'user',+ content: 'Current question',+ });++ const rows = remoteSessionStore.getMessages('s1');+ expect(rows.map((item) => item.clientId)).toEqual([+ 'previous-assistant',+ 'current-user',+ 'current-live-assistant',+ ]);+ expect(rows.slice(1).map((item) => item.createdAt)).toEqual([+ '2026-01-01T00:00:01.000Z',+ '2026-01-01T00:00:01.000Z',+ ]);+ } finally {+ vi.useRealTimers();+ }});- it('跨设备:另一设备 shard 变化不换本设备会话的对象引用', () => {- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);- const s1Before = remoteSessionStore.getSessions().find((s) => s.id === 's1');- remoteSessionStore.setDeviceSessions('dev-2', 'Win', [session('w1')]);- expect(remoteSessionStore.getSessions().find((s) => s.id === 's1')).toBe(s1Before);- remoteSessionStore.removeDevice('dev-2');- expect(remoteSessionStore.getSessions().find((s) => s.id === 's1')).toBe(s1Before);- });+ it('连续两轮 provisional live 回复按 user push 顺序逐条完成重锚', () => {+ vi.useFakeTimers();+ try {+ vi.setSystemTime(new Date('2026-01-01T00:10:00.000Z'));+ pushMakerText('s1', 'live-assistant-1', 'First reply', true);+ vi.setSystemTime(new Date('2026-01-01T00:11:00.000Z'));+ pushMakerText('s1', 'live-assistant-2', 'Second reply', true);- it('风暴不变量:消息/运行态/活动高频 churn + 内容等价重算下,会话列表快照引用零漂移', () => {- // 桌面端流式输出 = appendMessage / status / activity 事件以每秒多条的频率灌入,- // 其间还夹杂设备表更新等触发 recomputeSessions 的内容等价重算(归一化分支每轮- // 都会重铸对象,必须被引用调和吸收)。这些都不改变会话列表内容,getSessions()- // 快照必须保持同一引用——它是 useRemoteSessions 消费屏(首页/设备详情)不被- // 无关 emit 惊动的结构保证,重构后回归验证的核心断言(2026-07-18 风暴修复;- // 每轮 setDeviceIdentity 在修复前的 store 上会真实打红本用例)。- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1'), session('s2')]);- const snapshot = remoteSessionStore.getSessions();- for (let i = 0; i < 50; i += 1) {remoteSessionStore.appendMessage('s1', {- id: `m${i}`,- clientId: `m${i}`,- sessionId: 's1',- role: 'assistant',- content: `chunk ${i}`,- toolUseId: null,- agentMeta: null,- createdAt: `2026-01-01T00:00:${String(i).padStart(2, '0')}.000Z`,+ ...messageAt('user-1', 's1', '2026-01-01T00:00:01.000Z'),+ role: 'user',+ content: 'First question',});- remoteSessionStore.applyMakerEvent('s1', { type: 'status', data: { isRunning: true, tokenUsage: i + 1 } });- remoteSessionStore.applySessionActivity('dev-1', {- sessionId: 's1',- phase: 'running',- compactDetail: `step ${i}`,+ remoteSessionStore.appendMessage('s1', {+ ...messageAt('user-2', 's1', '2026-01-01T00:00:02.000Z'),+ role: 'user',+ content: 'Second question',});- // 每轮设备表变化(无关设备增补)强制走一次 recomputeSessions:会话内容等价,- // 归一化重铸的对象必须被调和吸收,快照引用不许漂移。- remoteSessionStore.setDeviceIdentity([- { deviceId: 'dev-1', name: 'Mac' },- { deviceId: `ghost-${i}`, name: `G${i}` },++ const rows = remoteSessionStore.getMessages('s1');+ expect(rows.map((item) => item.clientId)).toEqual([+ 'user-1',+ 'live-assistant-1',+ 'user-2',+ 'live-assistant-2',+ ]);+ expect(rows.map((item) => item.createdAt)).toEqual([+ '2026-01-01T00:00:01.000Z',+ '2026-01-01T00:00:01.000Z',+ '2026-01-01T00:00:02.000Z',+ '2026-01-01T00:00:02.000Z',]);+ } finally {+ vi.useRealTimers();}- expect(remoteSessionStore.getSessions()).toBe(snapshot);});-});-describe('maker:event 微批拆包(CONTROLLER_CAPABILITY_MAKER_EVENT_BATCH_V1)', () => {- it('批内事件按序走与逐帧完全相同的路径:流式增量拼接结果一致', () => {+ it('同一发送轮次的多条 live 回复按原顺序整体移到 user 行之后', () => {vi.useFakeTimers();try {- // 逐帧基线- pushMakerText('s-single', 'p-1', 'hello', false);- pushMakerText('s-single', 'p-1', ' world', false);- vi.runOnlyPendingTimers();- const single = remoteSessionStore.getMessages('s-single');+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', {+ userSendAt: '2026-01-01T00:00:01.000Z',+ updatedAt: '2026-01-01T00:00:01.000Z',+ })]);+ vi.setSystemTime(new Date('2026-01-01T00:10:00.000Z'));+ pushMakerText('s1', 'live-assistant-1', 'First reply block', true);+ pushMakerText('s1', 'live-assistant-2', 'Second reply block', true);- // 同样两条事件,这次由被控端合并成一帧微批下发- remoteSessionStore.applyRemotePush('dev-1', MAKER_EVENT_BATCH_CHANNEL, {- sessionId: 's-batch',- events: [- { sessionId: 's-batch', persistId: 'p-1', event: { type: 'text', data: { text: 'hello', isFinal: false } } },- { sessionId: 's-batch', persistId: 'p-1', event: { type: 'text', data: { text: ' world', isFinal: false } } },- ],+ remoteSessionStore.appendMessage('s1', {+ ...messageAt('user-1', 's1', '2026-01-01T00:00:01.000Z'),+ role: 'user',+ content: 'Question',});- vi.runOnlyPendingTimers();- const batched = remoteSessionStore.getMessages('s-batch');- expect(batched).toHaveLength(1);- expect(batched[0]).toMatchObject({ id: 'p-1', role: 'assistant', content: 'hello world' });- // 与逐帧结果逐字段一致(仅 sessionId 不同)- expect(batched[0]!.content).toBe(single[0]!.content);+ expect(remoteSessionStore.getMessages('s1').map((item) => item.clientId)).toEqual([+ 'user-1',+ 'live-assistant-1',+ 'live-assistant-2',+ ]);+ remoteSessionStore.appendMessage('s1', {+ ...messageAt('user-2', 's1', '2026-01-01T00:00:02.000Z'),+ role: 'user',+ content: 'Next question',+ });+ expect(remoteSessionStore.getMessages('s1').map((item) => item.clientId)).toEqual([+ 'user-1',+ 'live-assistant-1',+ 'live-assistant-2',+ 'user-2',+ ]);} finally {vi.useRealTimers();}});- it('形状不符的批帧整体忽略;批内单条坏事件只跳过该条', () => {+ it('元数据前同一 maker turn 的多条 live 回复由首个 user 行整体消费', () => {vi.useFakeTimers();try {- // 缺 events / events 为空 / 非数组:整帧忽略,不抛- for (const bad of [- { sessionId: 's-bad' },- { sessionId: 's-bad', events: [] },- { sessionId: 's-bad', events: 'nope' },- { events: [{}] },- null,- ]) {- expect(() =>- remoteSessionStore.applyRemotePush('dev-1', MAKER_EVENT_BATCH_CHANNEL, bad),- ).not.toThrow();- }- vi.runOnlyPendingTimers();- expect(remoteSessionStore.getMessages('s-bad')).toHaveLength(0);+ remoteSessionStore.applyMakerEvent('s1', {+ type: 'status',+ data: { isRunning: true },+ });+ vi.setSystemTime(new Date('2026-01-01T00:10:00.000Z'));+ pushMakerText('s1', 'live-assistant-1', 'First reply block', true);+ pushMakerText('s1', 'live-assistant-2', 'Second reply block', true);- // 批内混入坏条目:好的照常生效- remoteSessionStore.applyRemotePush('dev-1', MAKER_EVENT_BATCH_CHANNEL, {- sessionId: 's-mixed',- events: [- 'not-an-object',- { sessionId: 's-mixed', persistId: 'p-9', event: { type: 'text', data: { text: 'ok', isFinal: true } } },- ],+ remoteSessionStore.appendMessage('s1', {+ ...messageAt('user-1', 's1', '2026-01-01T00:00:01.000Z'),+ role: 'user',+ content: 'Question',});- vi.runOnlyPendingTimers();- expect(remoteSessionStore.getMessages('s-mixed')).toHaveLength(1);- expect(remoteSessionStore.getMessages('s-mixed')[0]).toMatchObject({ content: 'ok' });+ expect(remoteSessionStore.getMessages('s1').map((item) => item.clientId)).toEqual([+ 'user-1',+ 'live-assistant-1',+ 'live-assistant-2',+ ]);++ remoteSessionStore.applyMakerEvent('s1', {+ type: 'status',+ data: { isRunning: false },+ });+ remoteSessionStore.appendMessage('s1', {+ ...messageAt('user-2', 's1', '2026-01-01T00:00:02.000Z'),+ role: 'user',+ content: 'Next question',+ });+ expect(remoteSessionStore.getMessages('s1').map((item) => item.clientId)).toEqual([+ 'user-1',+ 'live-assistant-1',+ 'live-assistant-2',+ 'user-2',+ ]);} finally {vi.useRealTimers();}});- it('批内 sessionId 与顶层不一致的条目被丢弃:不绕过 topic 隔离', () => {- // topic 路由只按**顶层** sessionId,批内混入其它会话的事件会把本端未订阅的- // 会话数据投进来(坏帧/恶意帧场景)。fail-closed 跳过该条,不整批丢。+ it('延迟的非 user push 不会消费当前轮 live 回复的待重锚身份', () => {vi.useFakeTimers();try {- remoteSessionStore.applyRemotePush('dev-1', MAKER_EVENT_BATCH_CHANNEL, {- sessionId: 's-own',- events: [- { sessionId: 's-other', persistId: 'p-x', event: { type: 'text', data: { text: 'leak', isFinal: true } } },- { sessionId: 's-own', persistId: 'p-y', event: { type: 'text', data: { text: 'mine', isFinal: true } } },- ],+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', {+ userSendAt: '2026-01-01T00:00:02.000Z',+ updatedAt: '2026-01-01T00:00:02.000Z',+ })]);+ vi.setSystemTime(new Date('2026-01-01T00:10:00.000Z'));+ pushMakerText('s1', 'current-live-assistant', 'Current reply', true);++ remoteSessionStore.appendMessage('s1', {+ ...messageAt('delayed-previous-assistant', 's1', '2026-01-01T00:00:01.000Z'),+ content: 'Delayed previous reply',});- vi.runOnlyPendingTimers();- expect(remoteSessionStore.getMessages('s-other')).toHaveLength(0);- expect(remoteSessionStore.getMessages('s-own')).toHaveLength(1);- expect(remoteSessionStore.getMessages('s-own')[0]).toMatchObject({ content: 'mine' });+ remoteSessionStore.appendMessage('s1', {+ ...messageAt('current-user', 's1', '2026-01-01T00:00:02.000Z'),+ role: 'user',+ content: 'Current question',+ });++ const rows = remoteSessionStore.getMessages('s1');+ expect(rows.map((item) => item.clientId)).toEqual([+ 'delayed-previous-assistant',+ 'current-user',+ 'current-live-assistant',+ ]);+ expect(rows.slice(1).map((item) => item.createdAt)).toEqual([+ '2026-01-01T00:00:02.000Z',+ '2026-01-01T00:00:02.000Z',+ ]);} finally {vi.useRealTimers();}});-});--describe('任务消息内存治理', () => {- beforeEach(() => remoteSessionStore.clear());-- const manyMessages = (sessionId: string, count: number): RemoteMessage[] =>- Array.from({ length: count }, (_, index) => messageAt(- `${sessionId}-m-${index}`,- sessionId,- new Date(Date.UTC(2026, 0, 1, 0, 0, index)).toISOString(),- ));- const flushReclaim = async (): Promise<void> => {- await Promise.resolve();- await Promise.resolve();- };+ it('早于本轮发送时间的 user push 不会消费当前轮 live 回复的待重锚身份', () => {+ vi.useFakeTimers();+ try {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', {+ userSendAt: '2026-01-01T00:00:02.000Z',+ updatedAt: '2026-01-01T00:00:02.000Z',+ })]);+ vi.setSystemTime(new Date('2026-01-01T00:10:00.000Z'));+ pushMakerText('s1', 'current-live-assistant', 'Current reply', true);- it('只按 source=scheduler 分类,标题与 source 缺失均保守按 regular', () => {- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [- session('schedule', { source: 'scheduler', title: '普通标题' }),- session('legacy-title', { title: '[Schedule] 旧标题' }),- session('bound', { source: 'user', title: '被定时器绑定' }),- ]);+ remoteSessionStore.appendMessage('s1', {+ ...messageAt('delayed-previous-user', 's1', '2026-01-01T00:00:01.000Z'),+ role: 'user',+ content: 'Previous question',+ });+ expect(remoteSessionStore.getMessages('s1')+ .find((item) => item.clientId === 'current-live-assistant')?.createdAt)+ .toBe('2026-01-01T00:00:02.000Z');+ remoteSessionStore.appendMessage('s1', {+ ...messageAt('current-user', 's1', '2026-01-01T00:00:02.000Z'),+ role: 'user',+ content: 'Current question',+ });- expect(remoteSessionStore.getSessionRetention('schedule')).toBe('schedule');- expect(remoteSessionStore.getSessionRetention('legacy-title')).toBe('regular');- expect(remoteSessionStore.getSessionRetention('bound')).toBe('regular');+ const rows = remoteSessionStore.getMessages('s1');+ expect(rows.map((item) => item.clientId)).toEqual([+ 'delayed-previous-user',+ 'current-user',+ 'current-live-assistant',+ ]);+ expect(rows.slice(1).map((item) => item.createdAt)).toEqual([+ '2026-01-01T00:00:02.000Z',+ '2026-01-01T00:00:02.000Z',+ ]);+ } finally {+ vi.useRealTimers();+ }});- it('旧详情代际的读取在 blur→refocus 后不能覆盖新窗口', () => {- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', { source: 'scheduler' })]);- const first = remoteSessionStore.enterSessionMessageDetail('s1');- remoteSessionStore.setMessages('s1', [message('first', 's1')], { authority: first });- remoteSessionStore.leaveSessionMessageDetail('s1', 'detail-blur', first);- const second = remoteSessionStore.enterSessionMessageDetail('s1');+ it('匹配本轮发送时间的 user 最新窗口会完成配对,下一轮 user 不再认领旧回复', () => {+ vi.useFakeTimers();+ try {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', {+ userSendAt: '2026-01-01T00:00:01.000Z',+ updatedAt: '2026-01-01T00:00:01.000Z',+ })]);+ vi.setSystemTime(new Date('2026-01-01T00:10:00.000Z'));+ pushMakerText('s1', 'live-assistant-1', 'First reply', true);- remoteSessionStore.setMessages('s1', [message('stale', 's1')], { authority: first });- expect(remoteSessionStore.getMessages('s1').map((row) => row.id)).toEqual(['first']);+ remoteSessionStore.setLatestMessageWindow('s1', [{+ ...messageAt('user-1', 's1', '2026-01-01T00:00:01.000Z'),+ role: 'user',+ content: 'First question',+ }]);+ remoteSessionStore.appendMessage('s1', {+ ...messageAt('user-2', 's1', '2026-01-01T00:00:02.000Z'),+ role: 'user',+ content: 'Second question',+ });- remoteSessionStore.setMessages('s1', [message('fresh', 's1')], { authority: second });- expect(remoteSessionStore.getMessages('s1').map((row) => row.id)).toEqual(['fresh']);+ expect(remoteSessionStore.getMessages('s1').map((item) => item.clientId)).toEqual([+ 'user-1',+ 'live-assistant-1',+ 'user-2',+ ]);+ } finally {+ vi.useRealTimers();+ }});- it('从未打开的 regular 可更新全局镜像,首次进入或离场后不再接受无 authority 补读', () => {- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);- const unenteredAuthority = remoteSessionStore.captureUnenteredSessionMessageAuthority('s1');- expect(remoteSessionStore.hasSessionMessageDetailEntered('s1')).toBe(false);- expect(remoteSessionStore.canCommitUnenteredSessionMessageWindow(unenteredAuthority, 'dev-1')).toBe(true);- expect(remoteSessionStore.canCommitUnenteredSessionMessageWindow(unenteredAuthority, 'dev-2')).toBe(false);+ it('一次权威窗口带回多轮 user 时,按窗口顺序逐条配对 provisional 回复', () => {+ vi.useFakeTimers();+ try {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', {+ userSendAt: '2026-01-01T00:00:02.000Z',+ updatedAt: '2026-01-01T00:00:02.000Z',+ })]);+ vi.setSystemTime(new Date('2026-01-01T00:10:00.000Z'));+ pushMakerText('s1', 'live-assistant-1', 'First reply', true);+ vi.setSystemTime(new Date('2026-01-01T00:11:00.000Z'));+ pushMakerText('s1', 'live-assistant-2', 'Second reply', true);- remoteSessionStore.setLatestMessageWindow('s1', [message('global-mirror', 's1')]);- expect(remoteSessionStore.getMessages('s1').map((row) => row.id)).toEqual(['global-mirror']);+ remoteSessionStore.setLatestMessageWindow('s1', [+ {+ ...messageAt('user-1', 's1', '2026-01-01T00:00:01.000Z'),+ role: 'user',+ content: 'First question',+ },+ {+ ...messageAt('user-2', 's1', '2026-01-01T00:00:02.000Z'),+ role: 'user',+ content: 'Second question',+ },+ ]);- const authority = remoteSessionStore.enterSessionMessageDetail('s1');- expect(remoteSessionStore.hasSessionMessageDetailEntered('s1')).toBe(true);- expect(remoteSessionStore.canCommitUnenteredSessionMessageWindow(unenteredAuthority, 'dev-1')).toBe(false);- remoteSessionStore.leaveSessionMessageDetail('s1', 'detail-blur', authority);- remoteSessionStore.setLatestMessageWindow('s1', [message('stale-reconnect', 's1')]);+ const rows = remoteSessionStore.getMessages('s1');+ expect(rows.map((item) => item.clientId)).toEqual([+ 'user-1',+ 'live-assistant-1',+ 'user-2',+ 'live-assistant-2',+ ]);+ expect(rows.map((item) => item.createdAt)).toEqual([+ '2026-01-01T00:00:01.000Z',+ '2026-01-01T00:00:01.000Z',+ '2026-01-01T00:00:02.000Z',+ '2026-01-01T00:00:02.000Z',+ ]);- expect(remoteSessionStore.getMessages('s1').some((row) => row.id === 'stale-reconnect')).toBe(false);+ remoteSessionStore.appendMessage('s1', {+ ...messageAt('user-3', 's1', '2026-01-01T00:00:03.000Z'),+ role: 'user',+ content: 'Third question',+ });+ expect(remoteSessionStore.getMessages('s1').map((item) => item.clientId)).toEqual([+ 'user-1',+ 'live-assistant-1',+ 'user-2',+ 'live-assistant-2',+ 'user-3',+ ]);+ } finally {+ vi.useRealTimers();+ }});- it('从未打开的 schedule 不接受无 authority 的重连补读', () => {- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [- session('s1', { source: 'scheduler' }),- ]);+ it('截断权威窗口只配对窗口内对应的最新 provisional 回复', () => {+ vi.useFakeTimers();+ try {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', {+ userSendAt: '2026-01-01T00:00:03.000Z',+ updatedAt: '2026-01-01T00:00:03.000Z',+ })]);+ vi.setSystemTime(new Date('2026-01-01T00:10:00.000Z'));+ pushMakerText('s1', 'live-assistant-1', 'First reply', true);+ pushMakerText('s1', 'live-assistant-2', 'Second reply', true);+ pushMakerText('s1', 'live-assistant-3', 'Third reply', true);- const unenteredAuthority = remoteSessionStore.captureUnenteredSessionMessageAuthority('s1');- expect(remoteSessionStore.hasSessionMessageDetailEntered('s1')).toBe(false);- expect(remoteSessionStore.canCommitUnenteredSessionMessageWindow(unenteredAuthority, 'dev-1')).toBe(false);- remoteSessionStore.setLatestMessageWindow('s1', [message('schedule-reconnect', 's1')]);- expect(remoteSessionStore.getMessages('s1')).toEqual([]);+ remoteSessionStore.setLatestMessageWindow('s1', [+ {+ ...messageAt('user-2', 's1', '2026-01-01T00:00:02.000Z'),+ role: 'user',+ content: 'Second question',+ },+ {+ ...messageAt('user-3', 's1', '2026-01-01T00:00:03.000Z'),+ role: 'user',+ content: 'Third question',+ },+ ]);++ remoteSessionStore.upsertDeviceSession('dev-1', 'Mac', session('s1', {+ userSendAt: '2026-01-01T00:00:04.000Z',+ updatedAt: '2026-01-01T00:00:04.000Z',+ }));+ pushMakerText('s1', 'live-assistant-4', 'Fourth reply', true);+ remoteSessionStore.appendMessage('s1', {+ ...messageAt('user-4', 's1', '2026-01-01T00:00:04.000Z'),+ role: 'user',+ content: 'Fourth question',+ });++ const rows = remoteSessionStore.getMessages('s1');+ const rowIds = rows.map((item) => item.clientId);+ expect(rowIds.indexOf('live-assistant-2')).toBe(rowIds.indexOf('user-2') + 1);+ expect(rowIds.indexOf('live-assistant-3')).toBe(rowIds.indexOf('user-3') + 1);+ expect(rowIds.indexOf('live-assistant-4')).toBe(rowIds.indexOf('user-4') + 1);+ expect(rowIds.indexOf('live-assistant-1')).toBeLessThan(rowIds.indexOf('user-4'));+ expect(rows.find((item) => item.clientId === 'live-assistant-2')?.createdAt)+ .toBe('2026-01-01T00:00:02.000Z');+ expect(rows.find((item) => item.clientId === 'live-assistant-3')?.createdAt)+ .toBe('2026-01-01T00:00:03.000Z');+ expect(rows.find((item) => item.clientId === 'live-assistant-4')?.createdAt)+ .toBe('2026-01-01T00:00:04.000Z');+ } finally {+ vi.useRealTimers();+ }});- it('clear 后同设备同任务重建也拒绝 reset 前的未进入详情读取', () => {- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);- const beforeReset = remoteSessionStore.captureUnenteredSessionMessageAuthority('s1');+ it('截断窗口中的中间 user 边界不会认领更旧轮次的 pending 回复', () => {+ vi.useFakeTimers();+ try {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', {+ userSendAt: '2026-01-01T00:00:01.000Z',+ updatedAt: '2026-01-01T00:00:01.000Z',+ })]);+ vi.setSystemTime(new Date('2026-01-01T00:10:00.000Z'));+ pushMakerText('s1', 'live-assistant-1', 'First reply', true);++ remoteSessionStore.upsertDeviceSession('dev-1', 'Mac', session('s1', {+ userSendAt: '2026-01-01T00:00:02.000Z',+ updatedAt: '2026-01-01T00:00:02.000Z',+ }));+ pushMakerText('s1', 'live-assistant-2', 'Second reply', true);+ remoteSessionStore.appendMessage('s1', {+ ...messageAt('user-2', 's1', '2026-01-01T00:00:02.000Z'),+ role: 'user',+ content: 'Second question',+ });++ remoteSessionStore.upsertDeviceSession('dev-1', 'Mac', session('s1', {+ userSendAt: '2026-01-01T00:00:03.000Z',+ updatedAt: '2026-01-01T00:00:03.000Z',+ }));+ pushMakerText('s1', 'live-assistant-3', 'Third reply', true);+ remoteSessionStore.setLatestMessageWindow('s1', [+ {+ ...messageAt('user-2', 's1', '2026-01-01T00:00:02.000Z'),+ role: 'user',+ content: 'Second question',+ },+ {+ ...messageAt('user-3', 's1', '2026-01-01T00:00:03.000Z'),+ role: 'user',+ content: 'Third question',+ },+ ]);- remoteSessionStore.clear();- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);+ const truncatedRows = remoteSessionStore.getMessages('s1');+ expect(truncatedRows.find((item) => item.clientId === 'live-assistant-1')?.createdAt)+ .toBe('2026-01-01T00:00:01.000Z');+ expect(truncatedRows.map((item) => item.clientId).indexOf('live-assistant-1'))+ .toBeLessThan(truncatedRows.map((item) => item.clientId).indexOf('user-2'));- expect(remoteSessionStore.canCommitUnenteredSessionMessageWindow(beforeReset, 'dev-1')).toBe(false);- const afterReset = remoteSessionStore.captureUnenteredSessionMessageAuthority('s1');- expect(remoteSessionStore.canCommitUnenteredSessionMessageWindow(afterReset, 'dev-1')).toBe(true);+ remoteSessionStore.setLatestMessageWindow('s1', [+ {+ ...messageAt('user-1', 's1', '2026-01-01T00:00:01.000Z'),+ role: 'user',+ content: 'First question',+ },+ {+ ...messageAt('user-2', 's1', '2026-01-01T00:00:02.000Z'),+ role: 'user',+ content: 'Second question',+ },+ {+ ...messageAt('user-3', 's1', '2026-01-01T00:00:03.000Z'),+ role: 'user',+ content: 'Third question',+ },+ ]);+ const completeRowIds = remoteSessionStore.getMessages('s1').map((item) => item.clientId);+ expect(completeRowIds.indexOf('live-assistant-1'))+ .toBe(completeRowIds.indexOf('user-1') + 1);+ expect(remoteSessionStore.getMessages('s1')+ .find((item) => item.clientId === 'live-assistant-1')?.createdAt)+ .toBe('2026-01-01T00:00:01.000Z');+ } finally {+ vi.useRealTimers();+ }});- it('schedule 失焦后回收到 0,后续 push 不会复活完整正文', async () => {- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', { source: 'scheduler' })]);- const authority = remoteSessionStore.enterSessionMessageDetail('s1');- remoteSessionStore.setMessages('s1', [message('m1', 's1')], { authority });+ it('早于本轮发送时间的 user 最新窗口不改写当前 live 锚点,仍等待当前 user push 完成配对', () => {+ vi.useFakeTimers();+ try {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', {+ userSendAt: '2026-01-01T00:00:02.000Z',+ updatedAt: '2026-01-01T00:00:02.000Z',+ })]);+ vi.setSystemTime(new Date('2026-01-01T00:10:00.000Z'));+ pushMakerText('s1', 'current-live-assistant', 'Current reply', true);- remoteSessionStore.leaveSessionMessageDetail('s1', 'detail-blur', authority);- await flushReclaim();- expect(remoteSessionStore.getMessages('s1')).toEqual([]);+ remoteSessionStore.setLatestMessageWindow('s1', [{+ ...messageAt('previous-user', 's1', '2026-01-01T00:00:01.000Z'),+ role: 'user',+ content: 'Previous question',+ }]);+ expect(remoteSessionStore.getMessages('s1')+ .find((item) => item.clientId === 'current-live-assistant')?.createdAt)+ .toBe('2026-01-01T00:00:02.000Z');+ remoteSessionStore.appendMessage('s1', {+ ...messageAt('current-user', 's1', '2026-01-01T00:00:02.000Z'),+ role: 'user',+ content: 'Current question',+ });- remoteSessionStore.applyRemotePush('dev-1', 'local-db:messages:created', {- sessionId: 's1',- message: message('late-push', 's1'),- });- expect(remoteSessionStore.getMessages('s1')).toEqual([]);+ expect(remoteSessionStore.getMessages('s1').map((item) => item.clientId)).toEqual([+ 'previous-user',+ 'current-user',+ 'current-live-assistant',+ ]);+ } finally {+ vi.useRealTimers();+ }});- it('regular 离场后旧订阅 push 与尚未 flush 的流式批次都不能复活窗口', async () => {+ it('多帧 live 行在会话元数据到达前持续保留待重锚标记', () => {vi.useFakeTimers();try {- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);- const authority = remoteSessionStore.enterSessionMessageDetail('s1');- remoteSessionStore.setMessages('s1', manyMessages('s1', 2), { authority });- pushMakerText('s1', 'stream-1', 'queued delta', false);-- remoteSessionStore.leaveSessionMessageDetail('s1', 'detail-blur', authority);- const nextAuthority = remoteSessionStore.enterSessionMessageDetail('s1');+ vi.setSystemTime(new Date('2026-01-01T00:10:00.000Z'));+ pushMakerText('s1', undefined, 'O', false);vi.runOnlyPendingTimers();- remoteSessionStore.applyRemotePush('dev-1', 'local-db:messages:created', {- sessionId: 's1',- message: message('late-subscription-push', 's1'),+ const provisionalCreatedAt = remoteSessionStore.getMessages('s1')[0]?.createdAt;+ pushMakerText('s1', undefined, 'K', true);++ expect(remoteSessionStore.getMessages('s1')[0]).toMatchObject({+ content: 'OK',+ createdAt: provisionalCreatedAt,});- expect(remoteSessionStore.isSessionMessageAuthorityCurrent(nextAuthority)).toBe(true);- expect(remoteSessionStore.getMessages('s1').map((row) => row.id)).toEqual([- 's1-m-0',- 'late-subscription-push',- 's1-m-1',- ]);- // 上面的 push 是在新代际可见期间到达,应该保留;旧代际排队的 delta 不得出现。- expect(remoteSessionStore.getMessages('s1').some((row) => row.id === 'stream-1')).toBe(false);+ remoteSessionStore.upsertDeviceSession('dev-1', 'Mac', session('s1', {+ userSendAt: '2026-01-01T00:00:00.000Z',+ updatedAt: '2026-01-01T00:00:00.000Z',+ }));- remoteSessionStore.leaveSessionMessageDetail('s1', 'detail-blur', nextAuthority);- await flushReclaim();- remoteSessionStore.applyRemotePush('dev-1', 'local-db:messages:created', {- sessionId: 's1',- message: message('push-after-leave', 's1'),+ expect(remoteSessionStore.getMessages('s1')[0]).toMatchObject({+ content: 'OK',+ createdAt: '2026-01-01T00:00:00.000Z',});- expect(remoteSessionStore.getMessages('s1').some((row) => row.id === 'push-after-leave')).toBe(false);} finally {vi.useRealTimers();}});- it('页面卸载后本地工作排空仍会完成 deferred reclaim', async () => {- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', { source: 'scheduler' })]);- const work = remoteSessionStore.acquireSessionMessageWork('s1', true);- const authority = remoteSessionStore.enterSessionMessageDetail('s1');- remoteSessionStore.setMessages('s1', [message('m1', 's1')], { authority });- remoteSessionStore.leaveSessionMessageDetail('s1', 'session-switch', authority);+ it('多条 distinct live 行在首个主机水位到达前都保持待重锚', () => {+ vi.useFakeTimers();+ try {+ vi.setSystemTime(new Date('2026-01-01T00:10:00.000Z'));+ pushMakerText('s1', 'live-assistant-1', 'First reply', true);+ vi.setSystemTime(new Date('2026-01-01T00:11:00.000Z'));+ pushMakerText('s1', 'live-assistant-2', 'Second reply', true);++ expect(remoteSessionStore.getMessages('s1').map((item) => item.createdAt)).toEqual([+ '2026-01-01T00:10:00.000Z',+ '2026-01-01T00:11:00.000Z',+ ]);- await flushReclaim();- expect(remoteSessionStore.getMessages('s1')).toHaveLength(1);- work.release();- await flushReclaim();- expect(remoteSessionStore.getMessages('s1')).toEqual([]);+ remoteSessionStore.upsertDeviceSession('dev-1', 'Mac', session('s1', {+ userSendAt: '2026-01-01T00:00:00.000Z',+ updatedAt: '2026-01-01T00:00:00.000Z',+ }));++ expect(remoteSessionStore.getMessages('s1').map((item) => item.createdAt)).toEqual([+ '2026-01-01T00:00:00.000Z',+ '2026-01-01T00:00:00.000Z',+ ]);+ } finally {+ vi.useRealTimers();+ }});- it('pending queue 暂缓 schedule 回收,queue 排空后由 store 主动补回收', async () => {- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', { source: 'scheduler' })]);- const authority = remoteSessionStore.enterSessionMessageDetail('s1');- remoteSessionStore.setMessages('s1', [message('m1', 's1')], { authority });- remoteSessionStore.setInputProjection('s1', projection('s1'));- remoteSessionStore.leaveSessionMessageDetail('s1', 'app-background', authority);+ it('本地 system card 不会被当成首条 live 行的主机时间水位', () => {+ vi.useFakeTimers();+ try {+ const localCardId = remoteSessionStore.appendLocalSystemCard(+ 's1',+ 'status',+ {},+ new Date('2026-01-01T00:10:00.000Z'),+ );+ vi.setSystemTime(new Date('2026-01-01T00:11:00.000Z'));+ pushMakerText('s1', 'live-assistant', 'Reply after local card', true);- await flushReclaim();- expect(remoteSessionStore.getMessages('s1')).toHaveLength(1);- remoteSessionStore.setInputProjection('s1', {- ...projection('s1'),- pendingQueue: [],- });- await flushReclaim();- expect(remoteSessionStore.getMessages('s1')).toEqual([]);- });+ expect(remoteSessionStore.getMessages('s1')+ .find((item) => item.clientId === 'live-assistant')?.createdAt)+ .toBe('2026-01-01T00:11:00.000Z');- it('regular 失焦压回单窗,同时保留窗口外的本地系统卡', async () => {- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);- const authority = remoteSessionStore.enterSessionMessageDetail('s1');- const localCard = {- ...messageAt('mobile-system-pwd-old', 's1', '2025-12-31T23:59:59.000Z'),- role: 'system' as const,- };- remoteSessionStore.setMessages('s1', [localCard, ...manyMessages('s1', 100)], { authority });- remoteSessionStore.leaveSessionMessageDetail('s1', 'detail-blur', authority);- await flushReclaim();+ remoteSessionStore.upsertDeviceSession('dev-1', 'Mac', session('s1', {+ userSendAt: '2026-01-01T00:00:00.000Z',+ updatedAt: '2026-01-01T00:00:00.000Z',+ }));- const rows = remoteSessionStore.getMessages('s1');- expect(rows).toHaveLength(80);- expect(rows.some((row) => row.id === localCard.id)).toBe(true);- expect(rows.at(-1)?.id).toBe('s1-m-99');+ const rows = remoteSessionStore.getMessages('s1');+ expect(rows.find((item) => item.id === localCardId)?.createdAt)+ .toBe('2026-01-01T00:10:00.000Z');+ expect(rows.find((item) => item.clientId === 'live-assistant')?.createdAt)+ .toBe('2026-01-01T00:00:00.000Z');+ } finally {+ vi.useRealTimers();+ }});- it('regular 全局 LRU 不淘汰当前详情,且总量压回约 800 条', () => {- const sessions = Array.from({ length: 9 }, (_, index) => session(`s${index}`));- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', sessions);- remoteSessionStore.enterSessionMessageDetail('s0');- for (const item of sessions) {- remoteSessionStore.setMessages(item.id, manyMessages(item.id, 100));- }+ it('主机持久化消息早于会话元数据时,也会收口临时 live 行的设备时间', () => {+ vi.useFakeTimers();+ try {+ vi.setSystemTime(new Date('2026-01-01T00:10:00.000Z'));+ pushMakerText('s1', undefined, 'OK', true);- const total = sessions.reduce(- (sum, item) => sum + remoteSessionStore.getMessages(item.id).length,- 0,- );- expect(total).toBeLessThanOrEqual(800);- expect(remoteSessionStore.getMessages('s0')).toHaveLength(100);- expect(sessions.slice(1).some((item) => remoteSessionStore.getMessages(item.id).length === 0)).toBe(true);- });+ remoteSessionStore.appendMessage('s1', {+ ...messageAt('persisted-short', 's1', '2026-01-01T00:00:01.000Z'),+ content: 'OK',+ });- it('regular LRU 只淘汰可重取正文,不丢尚未落盘的本地系统卡', () => {- const sessions = Array.from({ length: 9 }, (_, index) => session(`s${index}`));- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', sessions);- const localCard = {- ...messageAt('mobile-system-local-only', 's0', '2025-12-31T23:59:59.000Z'),- role: 'system' as const,- };- remoteSessionStore.setMessages('s0', [localCard, ...manyMessages('s0', 99)]);- for (const item of sessions.slice(1)) {- remoteSessionStore.setMessages(item.id, manyMessages(item.id, 100));+ const rows = remoteSessionStore.getMessages('s1');+ expect(rows).toHaveLength(2);+ expect(rows[0]?.clientId).toMatch(/^mobile-stream-/);+ expect(rows[0]?.createdAt).toBe('2026-01-01T00:00:01.000Z');+ expect(rows[1]?.clientId).toBe('persisted-short');+ } finally {+ vi.useRealTimers();}-- expect(remoteSessionStore.getMessages('s0')).toHaveLength(100);- expect(remoteSessionStore.getMessages('s0').some((row) => row.id === localCard.id)).toBe(true);});- it('regular 离场释放详情投影并拒绝离场前启动的旧投影查询', async () => {- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);- const authority = remoteSessionStore.enterSessionMessageDetail('s1');- remoteSessionStore.setMessages('s1', [message('m1', 's1')], { authority });- remoteSessionStore.setInputProjection('s1', {- ...projection('s1'),- pendingQueue: [],- });- const queryEpoch = remoteSessionStore.captureInputProjectionAuthorityEpoch('s1');+ it('首个主机 user push 在插入后再重锚,保持问题先于 live 回复', () => {+ vi.useFakeTimers();+ try {+ vi.setSystemTime(new Date('2026-01-01T00:10:00.000Z'));+ pushMakerText('s1', undefined, 'OK', true);- remoteSessionStore.leaveSessionMessageDetail('s1', 'detail-blur', authority);- await flushReclaim();+ remoteSessionStore.appendMessage('s1', {+ ...messageAt('persisted-user', 's1', '2026-01-01T00:00:01.000Z'),+ role: 'user',+ content: 'Question',+ });- expect(remoteSessionStore.getInputProjection('s1').pendingQueue).toEqual([]);- expect(remoteSessionStore.setInputProjectionIfCurrent(- 's1',- projection('s1'),- queryEpoch,- )).toBe(false);+ const rows = remoteSessionStore.getMessages('s1');+ expect(rows.map((item) => item.clientId)).toEqual([+ 'persisted-user',+ expect.stringMatching(/^mobile-stream-/),+ ]);+ expect(rows.map((item) => item.createdAt)).toEqual([+ '2026-01-01T00:00:01.000Z',+ '2026-01-01T00:00:01.000Z',+ ]);+ } finally {+ vi.useRealTimers();+ }});- it('source 晚到改判 schedule:当前详情立即压窗,失焦后归零', async () => {- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);- const authority = remoteSessionStore.enterSessionMessageDetail('s1');- remoteSessionStore.setMessages('s1', manyMessages('s1', 100), { authority });+ it('权威最新消息窗口先于会话元数据到达时也会重锚临时 live 行', () => {+ vi.useFakeTimers();+ try {+ vi.setSystemTime(new Date('2026-01-01T00:10:00.000Z'));+ pushMakerText('s1', undefined, 'OK', true);- remoteSessionStore.upsertDeviceSession('dev-1', 'Mac', session('s1', { source: 'scheduler' }));- expect(remoteSessionStore.getSessionRetention('s1')).toBe('schedule');- expect(remoteSessionStore.getMessages('s1')).toHaveLength(80);+ remoteSessionStore.setLatestMessageWindow('s1', [{+ ...messageAt('persisted-user', 's1', '2026-01-01T00:00:01.000Z'),+ role: 'user',+ content: 'Question',+ }]);- remoteSessionStore.leaveSessionMessageDetail('s1', 'detail-blur');- await flushReclaim();- expect(remoteSessionStore.getMessages('s1')).toEqual([]);+ const rows = remoteSessionStore.getMessages('s1');+ expect(rows.map((item) => item.clientId)).toEqual([+ 'persisted-user',+ expect.stringMatching(/^mobile-stream-/),+ ]);+ expect(rows.map((item) => item.createdAt)).toEqual([+ '2026-01-01T00:00:01.000Z',+ '2026-01-01T00:00:01.000Z',+ ]);+ } finally {+ vi.useRealTimers();+ }});- it('归档会话会撤销旧 authority,并拒绝迟到 push 复活正文', () => {- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);- const authority = remoteSessionStore.enterSessionMessageDetail('s1');- remoteSessionStore.setMessages('s1', [message('before-archive', 's1')], { authority });+ it('权威 assistant 最新窗口重锚后仍让持久化行占据尾部', () => {+ vi.useFakeTimers();+ try {+ vi.setSystemTime(new Date('2026-01-01T00:10:00.000Z'));+ pushMakerText('s1', undefined, 'OK', true);- remoteSessionStore.applySessionPatch('dev-1', 's1', { status: 'archived' });- remoteSessionStore.applyRemotePush('dev-1', 'local-db:messages:created', {- sessionId: 's1',- message: message('late-after-archive', 's1'),- });+ remoteSessionStore.setLatestMessageWindow('s1', [{+ ...messageAt('persisted-short', 's1', '2026-01-01T00:00:01.000Z'),+ content: 'OK',+ }]);- expect(remoteSessionStore.isSessionMessageAuthorityCurrent(authority)).toBe(false);- expect(remoteSessionStore.getMessages('s1')).toEqual([]);+ const rows = remoteSessionStore.getMessages('s1');+ expect(rows).toHaveLength(2);+ expect(rows[0]?.clientId).toMatch(/^mobile-stream-/);+ expect(rows[1]?.clientId).toBe('persisted-short');+ expect(rows.map((item) => item.createdAt)).toEqual([+ '2026-01-01T00:00:01.000Z',+ '2026-01-01T00:00:01.000Z',+ ]);+ } finally {+ vi.useRealTimers();+ }});- it('显式失效 rewind 窗口会清正文、sync marker 并登记刷新', () => {- remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);- const authority = remoteSessionStore.enterSessionMessageDetail('s1');- remoteSessionStore.setMessages('s1', [message('before-rewind', 's1')], { authority });- const row = remoteSessionStore.getSessions().find((item) => item.id === 's1')!;- remoteSessionStore.markSessionMessagesSynced('s1', row);-- remoteSessionStore.invalidateSessionMessageWindow('s1', 'dev-1');+ it('流式增量的首个 delta 落定 createdAt 后,后续 delta 沿用同一戳(不重复取设备时间/不重新钳制)', () => {+ vi.useFakeTimers();+ try {+ remoteSessionStore.setLatestMessageWindow('s1', [+ messageAt('user-sent', 's1', '2026-01-01T00:10:00.000Z'),+ ]);+ vi.setSystemTime(new Date('2026-01-01T00:05:00.000Z'));+ pushMakerText('s1', 'live-assistant', 'partial ', false);+ // 非 final 的增量先进 pendingTextDeltaBatches,由防抖定时器统一落定+ // (见 remoteSessionStore.ts scheduleTextDeltaFlush/flushPendingTextDeltas)。+ vi.runOnlyPendingTimers();+ const firstStamp = remoteSessionStore.getMessages('s1')+ .find((item) => item.clientId === 'live-assistant')?.createdAt;+ expect(firstStamp).toBe('2026-01-01T00:10:00.000Z');- expect(remoteSessionStore.getMessages('s1')).toEqual([]);- expect(remoteSessionStore.isSessionMessageWindowSynced('s1', row)).toBe(false);- expect(remoteSessionStore.hasPendingRefresh('s1')).toBe(true);- expect(remoteSessionStore.isSessionMessageAuthorityCurrent(authority)).toBe(true);+ vi.setSystemTime(new Date('2026-01-01T00:20:00.000Z'));+ pushMakerText('s1', 'live-assistant', 'and more', false);+ vi.runOnlyPendingTimers();+ const secondStamp = remoteSessionStore.getMessages('s1')+ .find((item) => item.clientId === 'live-assistant')?.createdAt;+ // 已存在行的 createdAt 保持不变(见 remoteSessionStore.ts applyRemoteTextEvent+ // 对应分支的注释),不会因为设备时间继续前进而被重新戳一次。+ expect(secondStamp).toBe(firstStamp);+ } finally {+ vi.useRealTimers();+ }});});diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsxindex 138e5d17c7..1479787b6b 100644--- a/apps/mobile/src/session/MessageRenderer.tsx+++ b/apps/mobile/src/session/MessageRenderer.tsx@@ -302,6 +302,9 @@ import {evaluateMessageWindowUpdate,evaluateMobileAnchorVerify,evaluateMobileFollowEndContentSizePin,+ isMobileMvcpSettling,+ mobileFollowVerifyStartDelayMs,+ mobileMvcpSettleDeadline,mobileMessageListTopPadding,MOBILE_FOLLOW_END_PIN_SUPPRESS_MS,MOBILE_MESSAGE_LIST_BOTTOM_PADDING,@@ -650,9 +653,15 @@ export function MessageRenderer({const readingOlderRef = useRef(false);// 每次补页分配 generation:旧会话 / 旧请求的异步 settle 不得清掉新请求的抑制态。const readingOlderRequestGenerationRef = useRef(0);+ // LegendList mVCP 始终开启;普通尾部 append / 流式 resize 同样会触发 native 锚点+ // 调整,不能只拿 readingOlderRef 代表 settle 状态。每次 data / size 变化延长一个短+ // 安静窗,verifier 在窗内只等待,不消耗 6 次补滚预算。+ const mvcpSettleAtRef = useRef(0);const programmaticScrollGenerationRef = useRef(0);const programmaticScrollTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);const programmaticScrollInFlightRef = useRef(false);+ const programmaticAnimatedScrollInFlightRef = useRef(false);+ const programmaticScrollSettleAtRef = useRef(0);const previousFollowLatestRequestKeyRef = useRef(followLatestRequestKey);const previousItemKeysRef = useRef<readonly string[]>([]);const scrollMetricsRef = useRef<MessageScrollMetrics>({@@ -675,6 +684,11 @@ export function MessageRenderer({// 落底 rAF / verify loop / 揭开 timer 的句柄(生命周期 = 每个 scrollResetKey 一轮)。const initialAnchorFrameRef = useRef<number | null>(null);const initialRevealTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ // 贴底跟随的落底校验/补滚环(runStickToLatestVerify,独立于冷开锚定的 generation/frame——+ // 两条校验环可能各自独立触发,互不打断/互不清对方的句柄)。+ const followVerifyGenerationRef = useRef(0);+ const followVerifyFrameRef = useRef<number | null>(null);+ const followVerifyTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);// settle 遮罩:落底两段式期间列表保持 opacity 0,settle 窗口后揭开(规则 7 防跳动)。const [listRevealed, setListRevealed] = useState(false);// 会话切换(scrollResetKey)的 ref 复位必须在渲染期同步完成,不能只靠下方的 reset effect:@@ -693,8 +707,11 @@ export function MessageRenderer({lastAutoLoadEarlierKeyRef.current = null;readingOlderRef.current = false;readingOlderRequestGenerationRef.current += 1;+ mvcpSettleAtRef.current = 0;programmaticScrollGenerationRef.current += 1;programmaticScrollInFlightRef.current = false;+ programmaticAnimatedScrollInFlightRef.current = false;+ programmaticScrollSettleAtRef.current = 0;if (programmaticScrollTimerRef.current !== null) {clearTimeout(programmaticScrollTimerRef.current);programmaticScrollTimerRef.current = null;@@ -712,6 +729,15 @@ export function MessageRenderer({cancelAnimationFrame(initialAnchorVerifyFrameRef.current);initialAnchorVerifyFrameRef.current = null;}+ followVerifyGenerationRef.current += 1;+ if (followVerifyTimerRef.current !== null) {+ clearTimeout(followVerifyTimerRef.current);+ followVerifyTimerRef.current = null;+ }+ if (followVerifyFrameRef.current !== null) {+ cancelAnimationFrame(followVerifyFrameRef.current);+ followVerifyFrameRef.current = null;+ }// settle 遮罩复位必须与列表重挂同帧(渲染期 setState,React 官方 prop-change 模式):// 走 effect 会晚一帧,新列表以旧 revealed=true 裸挂一帧,未锚定内容闪现。setListRevealed(false);@@ -743,8 +769,13 @@ export function MessageRenderer({const closePayload = useCallback(() => setPayload(null), []);const markProgrammaticScroll = useCallback((animated: boolean) => {const generation = programmaticScrollGenerationRef.current + 1;+ const settleMs = animated+ ? MOBILE_PROGRAMMATIC_ANIMATED_SCROLL_SETTLE_MS+ : MOBILE_PROGRAMMATIC_SCROLL_SETTLE_MS;programmaticScrollGenerationRef.current = generation;programmaticScrollInFlightRef.current = true;+ programmaticAnimatedScrollInFlightRef.current = animated;+ programmaticScrollSettleAtRef.current = Date.now() + settleMs;if (programmaticScrollTimerRef.current !== null) {clearTimeout(programmaticScrollTimerRef.current);}@@ -752,20 +783,29 @@ export function MessageRenderer({if (programmaticScrollGenerationRef.current !== generation) return;programmaticScrollTimerRef.current = null;programmaticScrollInFlightRef.current = false;- }, animated- ? MOBILE_PROGRAMMATIC_ANIMATED_SCROLL_SETTLE_MS- : MOBILE_PROGRAMMATIC_SCROLL_SETTLE_MS);+ programmaticAnimatedScrollInFlightRef.current = false;+ programmaticScrollSettleAtRef.current = 0;+ }, settleMs);}, []);const clearProgrammaticScroll = useCallback(() => {programmaticScrollGenerationRef.current += 1;programmaticScrollInFlightRef.current = false;+ programmaticAnimatedScrollInFlightRef.current = false;+ programmaticScrollSettleAtRef.current = 0;if (programmaticScrollTimerRef.current !== null) {clearTimeout(programmaticScrollTimerRef.current);programmaticScrollTimerRef.current = null;}}, []);+ const markMobileMvcpSettle = useCallback(() => {+ mvcpSettleAtRef.current = mobileMvcpSettleDeadline(+ mvcpSettleAtRef.current,+ Date.now(),+ );+ }, []);+const scrollToEndProgrammatically = useCallback((animated: boolean) => {markProgrammaticScroll(animated);void listRef.current?.scrollToEnd({ animated });@@ -781,6 +821,80 @@ export function MessageRenderer({void listRef.current?.scrollToIndex({ animated: true, index, viewPosition });}, [markProgrammaticScroll]);+ // 贴底跟随的落底校验/补滚环:两条手动补滚路径——「跳到最新」(followLatestRequestKey)+ // 与 handleContentSize 的贴底追赶——都只发一次命令式 scrollToEnd,不校验是否真的到达内容+ // 末端。落地一刻的 native metrics 可能仍是陈旧值(测量结算未完成),或 mVCP 尚未真正关闭+ // 吸收了这次滚动:两者都会让最新消息静默停在 composer 浮层后面(bug 现场)。复用冷开锚定+ // 同一判定(evaluateMobileAnchorVerify)、同样的双帧节奏 + 有界重试,命中 settled/give-up+ // 就收手——不吃冷开锚定的 generation/frame ref,两条校验环各自独立生命周期,互不打断。+ const runStickToLatestVerify = useCallback(() => {+ const generation = followVerifyGenerationRef.current + 1;+ followVerifyGenerationRef.current = generation;+ if (followVerifyFrameRef.current !== null) {+ cancelAnimationFrame(followVerifyFrameRef.current);+ followVerifyFrameRef.current = null;+ }+ if (followVerifyTimerRef.current !== null) {+ clearTimeout(followVerifyTimerRef.current);+ followVerifyTimerRef.current = null;+ }+ const step = (attempts: number, waitRounds: number) => {+ if (followVerifyGenerationRef.current !== generation) return;+ // 贴底跟随意图只认 nearBottomRef:死区内轻触 / 小幅拖动并没有真实解除贴底,+ // 不能让 userScrollForOlderRef 这根“允许加载历史”的手势记录把校验永久关掉。+ // 真正上移超过死区时 shouldUnpinMobileFollowOnDrag 会把 nearBottomRef 翻 false,+ // 下一轮判定自然 settle。+ const action = evaluateMobileAnchorVerify({+ attempts,+ listVisible: true,+ metrics: scrollMetricsRef.current,+ preserveVisibleContentPosition: readingOlderRef.current+ || isMobileMvcpSettling(Date.now(), mvcpSettleAtRef.current),+ stickToLatest: nearBottomRef.current,+ waitRounds,+ });+ if (action === 'settled' || action === 'give-up') {+ followVerifyFrameRef.current = null;+ return;+ }+ if (action === 'retry') scrollToEndProgrammatically(false);+ followVerifyFrameRef.current = requestAnimationFrame(() => {+ followVerifyFrameRef.current = requestAnimationFrame(() => {+ followVerifyFrameRef.current = null;+ step(+ attempts + (action === 'retry' ? 1 : 0),+ waitRounds + (action === 'wait' ? 1 : 0),+ );+ });+ });+ };+ const start = () => {+ if (followVerifyGenerationRef.current !== generation) return;+ // 双帧等待:与冷开锚定环同源——命令式 scrollToEnd 已由调用方发出,这里只负责校验,+ // 给原生布局至少一帧结算再读 metrics,不把「刚发出去还没生效」误判成落空。+ followVerifyFrameRef.current = requestAnimationFrame(() => {+ followVerifyFrameRef.current = requestAnimationFrame(() => {+ followVerifyFrameRef.current = null;+ step(0, 0);+ });+ });+ };+ const startDelayMs = mobileFollowVerifyStartDelayMs({+ animatedScrollInFlight: programmaticAnimatedScrollInFlightRef.current,+ now: Date.now(),+ settleAt: programmaticScrollSettleAtRef.current,+ });+ if (startDelayMs > 0) {+ followVerifyTimerRef.current = setTimeout(() => {+ if (followVerifyGenerationRef.current !== generation) return;+ followVerifyTimerRef.current = null;+ start();+ }, startDelayMs);+ } else {+ start();+ }+ }, [scrollToEndProgrammatically]);+// DEV-only:把列表控制器 + 滚动 metrics 暴露给性能 harness(临时,profiling/回归测量用)。useEffect(() => {if (!__DEV__) return;@@ -804,6 +918,9 @@ export function MessageRenderer({prevListLengthRef.current = listData.length;}const itemKeys = useMemo(() => listData.map((item) => item.key), [listData]);+ useEffect(() => {+ markMobileMvcpSettle();+ }, [itemKeys, markMobileMvcpSettle]);const firstItemKey = itemKeys[0] ?? null;// 本地缩略兜底映射版本:collect 内部对 cindy-oss-attach:// 附件读全局 store 做 overlay,// hydrate / 新注册后 gallery 需要重建,否则点开气泡本地图时 initialUrl 对不上图集条目。@@ -1072,10 +1189,11 @@ export function MessageRenderer({}, [onVisibleShareableMessageIdsReaderChange, readActuallyVisibleShareableMessageIds]);// 贴底跟随由 handleContentSize 的手动补滚承担(nearBottomRef 是跟随意图的唯一真相);- // 跳底直接命令式 scrollToEnd。+ // 跳底先命令式 scrollToEnd,随后复用同一轮有界落底校验。const scrollToBottom = useCallback(() => {nearBottomRef.current = true;readingOlderRef.current = false;+ userScrollForOlderRef.current = false;// 用户主动跳底是明确的重锚意图:重建补滚护栏(清掉可能仍开着的断路窗,// 让跳底后的贴底跟随立即恢复;振荡若还在会重新跳闸,review P2)。在飞的// 断路清账 timer 一并作废——本次显式跳底就是清账。@@ -1087,7 +1205,8 @@ export function MessageRenderer({setIsAwayFromBottom(false);setHasNewMessages(false);scrollToEndProgrammatically(true);- }, [scrollToEndProgrammatically]);+ runStickToLatestVerify();+ }, [runStickToLatestVerify, scrollToEndProgrammatically]);const jumpToPreviousUserMessage = useCallback(() => {if (!previousUserTarget) return;@@ -1101,13 +1220,20 @@ export function MessageRenderer({scrollToIndexProgrammatically(previousUserTarget.index, 0.12);}, [previousUserTarget, scrollToIndexProgrammatically]);- // 「跳到最新」请求(会话外部触发):命令式滚到底,之后由 handleContentSize 补滚维持贴底。+ // 「跳到最新」请求(会话外部触发,含发送消息后的跟随):命令式滚到底,随后跑一轮有界+ // 校验/补滚(runStickToLatestVerify)——单发的 scrollToEnd 落地一刻的 metrics 可能仍陈旧,+ // 或被仍开着的 mVCP 吸收掉,不校验就会静默停在旧消息上(bug 现场,与冷开锚定同一根因)。+ // 之后的贴底由 handleContentSize 补滚维持。useEffect(() => {if (previousFollowLatestRequestKeyRef.current === followLatestRequestKey) return;previousFollowLatestRequestKeyRef.current = followLatestRequestKey;if (followLatestRequestKey === null || followLatestRequestKey === undefined) return;nearBottomRef.current = true;readingOlderRef.current = false;+ // 发送后的显式贴底已经取代旧的历史浏览意图。先清掉该标记,否则 verifier 的+ // stickToLatest 会被一次更早的拖动永久压成 false,退化回不可靠的单次 scrollToEnd。+ // 用户若在校验期间再次拖动,onScrollBeginDrag 会重新置 true 并自然中止补滚。+ userScrollForOlderRef.current = false;// 与 scrollToBottom 同语义:显式重锚清掉补滚护栏的断路窗与在飞清账 timer。followEndPinStateRef.current = createMobileFollowEndPinState();if (followEndPinRecoveryTimerRef.current) {@@ -1117,7 +1243,8 @@ export function MessageRenderer({setHasNewMessages(false);setIsAwayFromBottom(false);scrollToEndProgrammatically(true);- }, [followLatestRequestKey, scrollToEndProgrammatically]);+ runStickToLatestVerify();+ }, [followLatestRequestKey, runStickToLatestVerify, scrollToEndProgrammatically]);// 自动加载更早:电平触发判定(shouldAutoLoadEarlier),在所有可能改变判定结果的时机重评估// (scroll 事件 / LegendList onStartReached 边沿 / eligibility 变化 effect)。@@ -1193,6 +1320,8 @@ export function MessageRenderer({viewportHeight: event.nativeEvent.layoutMeasurement.height,};const previousOffsetY = scrollMetricsRef.current.offsetY;+ const wasNearBottom = nearBottomRef.current;+ const scrollDelta = readingOlderRef.current ? 0 : metrics.offsetY - previousOffsetY;scrollMetricsRef.current = metrics;if (nearBottomRef.current@@ -1209,10 +1338,16 @@ export function MessageRenderer({wasNearBottom: nearBottomRef.current,metrics,programmaticScrollInFlight: programmaticScrollInFlightRef.current,- scrollDelta: readingOlderRef.current ? 0 : metrics.offsetY - previousOffsetY,+ scrollDelta,bottomOverlayHeight,});nearBottomRef.current = nearBottom;+ // A genuine downward false→true transition means the user manually returned to the+ // latest edge. The old history-browsing intent no longer owns follow verification;+ // a later drag will set it again before any new upward browse.+ if (!wasNearBottom && nearBottom && scrollDelta > 0) {+ userScrollForOlderRef.current = false;+ }setIsAwayFromBottom(!nearBottom);if (nearBottom) setHasNewMessages(false);}@@ -1272,11 +1407,19 @@ export function MessageRenderer({// 上翻历史时 nearBottomRef=false,不打断。animated:false → 即时跟随、不排队动画。// LegendList 内置 maintainScrollAtEnd 已弃用(见 LegendList props 注释),不存在双机制叠加。const handleContentSize = useCallback((_width: number, height: number) => {+ markMobileMvcpSettle();const { viewportHeight } = scrollMetricsRef.current;scrollMetricsRef.current = { ...scrollMetricsRef.current, contentHeight: height };// readingOlderRef:load-earlier 的 prepend 也会撑高 contentHeight,但那是顶部增长、不该贴底(review P1)。if (readingOlderRef.current) return;if (nearBottomRef.current && viewportHeight > 0 && height > viewportHeight) {+ // Animated jump/send follow owns the viewport until its settle window closes. Content+ // growth during that animation only reschedules the verifier; a false-animated pin here+ // would visibly cut the smooth scroll short and jump straight to the end.+ if (programmaticAnimatedScrollInFlightRef.current) {+ runStickToLatestVerify();+ return;+ }// 补滚护栏:死区去噪 + 振荡断路,掐断「scrollToEnd → 重测 → onContentSizeChange」// 洪泛环(JS 忙死、冷开消息区空白;语义与参数见 messageScroll.ts 护栏段)。// 单调增长(流式/冷开/回填)不限流,每次跟进;只有高度往返振荡才跳闸。@@ -1300,14 +1443,19 @@ export function MessageRenderer({followEndPinRecoveryTimerRef.current = null;if (nearBottomRef.current && !readingOlderRef.current) {scrollToEndProgrammatically(false);+ // 清账补滚同样不保证真的落底(measurement 结算 / mVCP 吸收的静默落空同源风险),+ // 跑一轮校验/补滚兜底。+ runStickToLatestVerify();}}, MOBILE_FOLLOW_END_PIN_SUPPRESS_MS + 50);}if (decision.shouldScroll) {scrollToEndProgrammatically(false);+ // 贴底追赶的落底一样不校验就可能落空(陈旧 metrics / mVCP 吸收),补一轮有界校验。+ runStickToLatestVerify();}}- }, []);+ }, [markMobileMvcpSettle, runStickToLatestVerify, scrollToEndProgrammatically]);// 冷开落底(替代 initialScrollAtEnd,弃用原因见 LegendList props 注释):首批 items// commit 后先命令式落底,随后双帧校验 native metrics 是否真的到达 content end。@@ -1342,7 +1490,8 @@ export function MessageRenderer({const startedAt = Date.now();const verify = (attempts: number, waitRounds: number) => {if (initialAnchorGenerationRef.current !== generation) return;- const preserveVisibleContentPosition = readingOlderRef.current;+ const preserveVisibleContentPosition = readingOlderRef.current+ || isMobileMvcpSettling(Date.now(), mvcpSettleAtRef.current);const action = evaluateMobileAnchorVerify({attempts,listVisible: true,@@ -1403,10 +1552,13 @@ export function MessageRenderer({// 但不留悬挂句柄)。useEffect(() => () => {initialAnchorGenerationRef.current += 1;+ followVerifyGenerationRef.current += 1;if (followEndPinRecoveryTimerRef.current) clearTimeout(followEndPinRecoveryTimerRef.current);clearProgrammaticScroll();if (initialAnchorFrameRef.current !== null) cancelAnimationFrame(initialAnchorFrameRef.current);if (initialAnchorVerifyFrameRef.current !== null) cancelAnimationFrame(initialAnchorVerifyFrameRef.current);+ if (followVerifyFrameRef.current !== null) cancelAnimationFrame(followVerifyFrameRef.current);+ if (followVerifyTimerRef.current !== null) clearTimeout(followVerifyTimerRef.current);if (initialRevealTimerRef.current) clearTimeout(initialRevealTimerRef.current);}, [clearProgrammaticScroll]);diff --git a/apps/mobile/src/session/messagePaging.ts b/apps/mobile/src/session/messagePaging.tsindex f118b56bbb..00dfbb6d2c 100644--- a/apps/mobile/src/session/messagePaging.ts+++ b/apps/mobile/src/session/messagePaging.ts@@ -278,3 +278,33 @@ export function compareMessageOrder(a: RemoteMessage, b: RemoteMessage): number// arrival order is meaningful; message ids are not insertion ordered.return 0;}++/**+ * Cross-clock-domain sort fix (called by remoteSessionStore.applyRemoteTextEvent when it+ * stamps a live streaming/finalized assistant row with the *device* clock).+ *+ * Persisted rows carry the *host* clock's createdAt; live rows created before the host+ * persists them are stamped with the device's local clock. When the device clock runs+ * ahead of the host clock, a brand-new persisted row (host time) can sort *before* the+ * stale device-stamped live row under compareMessageOrder's plain createdAt comparison —+ * the message list's tail then keeps showing the old live row instead of the just-sent+ * message, even though the live row is about to be reconciled away.+ *+ * Fix: when the session already has a newest createdAt, anchor the temporary live row to+ * that watermark verbatim. A stable tie records the only trustworthy ordering fact we have:+ * this live row was observed after all currently known rows. It also avoids letting a device+ * clock that is ahead of the host dominate future host-persisted rows, which must still be+ * able to sort after this temporary row. The later authoritative persisted-row reconciliation+ * overwrites the temporary row with the real host time. Without a watermark, fall back to the+ * device timestamp because there is no host-domain anchor yet; remoteSessionStore marks that row+ * as provisional and reanchors it when the first session metadata or created-message push supplies+ * a host timestamp. Do not fabricate a `+1ms` value: that would invent an ordering fact no clock+ * actually observed.+ */+export function clampLiveRowCreatedAt(+ deviceNowIso: string,+ latestExistingCreatedAt: string | undefined,+): string {+ if (!latestExistingCreatedAt) return deviceNowIso;+ return latestExistingCreatedAt;+}diff --git a/apps/mobile/src/session/messageScroll.ts b/apps/mobile/src/session/messageScroll.tsindex 8112b153ee..e0a3c5846a 100644--- a/apps/mobile/src/session/messageScroll.ts+++ b/apps/mobile/src/session/messageScroll.ts@@ -287,14 +287,46 @@ export const MOBILE_ANCHOR_VERIFY_TOLERANCE = 2;export const MOBILE_ANCHOR_VERIFY_MAX_ATTEMPTS = 6;/**- * 校验等待上限(独立于补滚预算):mVCP 还开着 / metrics 未就绪时环只等不滚,等待- * 不消耗补滚额度——否则 mVCP 长开(open-settle cap 2s)会把预算烧光,窗口关闭后- * 反而没额度补滚,遮挡残留(review P1)。上限按最长 mVCP 窗口取:双帧一轮 ≈ 33ms,- * 75 轮 ≈ 2.5s > OPEN_SETTLE_CAP_MS(2000ms),窗口自然关闭后环仍活着;再长说明- * 状态异常(如列表空置),结束环交给常规事件跟随,每轮只是一次纯函数比较,无副作用。+ * 校验等待上限(独立于补滚预算):mVCP 还在结算 / metrics 未就绪时环只等不滚,等待+ * 不消耗补滚额度——否则连续的 data / size 调整会先把 6 次补滚预算烧光,布局安静后+ * 反而没额度补滚,遮挡残留(review P1)。双帧一轮约 33ms,75 轮约 2.5s;超过该+ * 上限说明布局持续变化或状态异常,结束环交给后续 contentSize 事件继续跟随。*/export const MOBILE_ANCHOR_VERIFY_MAX_WAIT_ROUNDS = 75;+/**+ * LegendList 的 mVCP 没有公开“本轮 native 调整已完成”信号。data / size 变化后保留+ * 一个短安静窗:期间 verifier 只等待;连续流式测量会延长窗口,但仍受上面的 2.5s+ * 总等待预算约束。120ms 约 7 帧,覆盖 JS commit、native layout 与滚动回传的常见链路。+ */+export const MOBILE_MVCP_SETTLE_QUIET_MS = 120;++export function mobileMvcpSettleDeadline(previousDeadline: number, now: number): number {+ return Math.max(previousDeadline, now + MOBILE_MVCP_SETTLE_QUIET_MS);+}++export function isMobileMvcpSettling(now: number, settleAt: number): boolean {+ return now < settleAt;+}++export interface MobileFollowVerifyStartDelayInput {+ animatedScrollInFlight: boolean;+ now: number;+ settleAt: number;+}++/**+ * Animated `scrollToEnd` must own the viewport until its bounded settle window closes.+ * Starting the verifier earlier would read an expected in-flight offset and replace the+ * smooth animation with an immediate non-animated retry.+ */+export function mobileFollowVerifyStartDelayMs(+ input: MobileFollowVerifyStartDelayInput,+): number {+ if (!input.animatedScrollInFlight) return 0;+ return Math.max(0, input.settleAt - input.now);+}+export interface MobileAnchorVerifyInput {attempts: number;listVisible: boolean;diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.tsindex 9156712ebb..ace7b8179e 100644--- a/apps/mobile/src/session/remoteSessionStore.ts+++ b/apps/mobile/src/session/remoteSessionStore.ts@@ -49,7 +49,7 @@ import { classifySessionRetention, type SessionRetentionKind } from '@/session/simport { contentToPreview } from '@/utils/contentPreview';import type { MobileSystemCardType } from '@/session/systemCard';import type { InputProjection, PendingInteraction, RemoteMessage, RemoteSession } from '@/session/types';-import { compareMessageOrder, MESSAGE_PAGE_SIZE } from '@/session/messagePaging';+import { clampLiveRowCreatedAt, compareMessageOrder, MESSAGE_PAGE_SIZE } from '@/session/messagePaging';import { normalizeRemoteMoney } from '@/session/remoteMoney';interface DeviceShard {@@ -143,6 +143,8 @@ export interface SetLatestMessageWindowOptions {export interface SessionMessageWriteOptions {authority?: SessionMessageAuthority;+ /** 本行是否携带主机时间域的 createdAt;本地临时卡必须显式关闭。 */+ hostTimeAuthoritative?: boolean;}interface LivePlanSnapshot {@@ -520,7 +522,37 @@ const sessionTaskUpdates = new Map<string, ReadonlyMap<string, AgentTaskUpdate>>// Keep one temporary assistant row per session and reconcile it with the persisted row by// clientId/persistId when the database push arrives.const streamingAssistantClientIds = new Map<string, string>();+// The same persisted streaming identity can be replayed by a stale transport after+// re-link. Track the transport currently assembling that identity so a device switch+// replaces the stale live text instead of concatenating two transports into one row.+const streamingAssistantDeviceIds = new Map<string, Map<string, string>>();const pendingLiveAssistantClientIds = new Map<string, Set<string>>();+// 首个 live 行可能早于 getSession / listMessages 到达。此时只能暂用手机时间,待第一份+// 主机时间水位到达后重锚;否则快手机时钟会让短且无 persistId 的旧 live 行长期占据尾部。+// value 记录这条 provisional 回复首次关联到的 userSendAt;重连期间 desktop 若已推进到+// 下一轮,旧回复不能被新轮 user 行认领。null 表示 live 行早于任何 session 元数据到达,+// 首份 userSendAt 会在 recomputeSessions 中完成一次性绑定,之后不再随新轮次前移;若+// null 身份先经历软离线,则禁止用重连后的“首份”元数据绑定,因为它可能已经是下一轮。+type PendingHostAnchorIdentity = {+ bindOnMetadata: boolean;+ /** Transports that have produced this provisional identity. */+ deviceIds: ReadonlySet<string>;+ /**+ * Local maker-turn cohort used only while host session metadata is unavailable.+ * Distinct assistant rows emitted by one running turn share this id, so the first+ * authoritative user row can consume the whole reply block without claiming rows+ * from a later turn. Once sendAt is known it remains as the stronger pre-metadata+ * grouping key; identities created with host metadata use sendAt directly.+ */+ unboundRoundId: number | null;+ sendAt: string | null;+};+const pendingHostAnchorLiveAssistantClientIds = new Map<+ string,+ Map<string, PendingHostAnchorIdentity>+>();+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;@@ -528,9 +560,45 @@ const DEVICE_LINK_TRUNCATED_FLAG = '__deviceLinkTruncated';const pendingTextDeltaBatches = new Map<string, {text: string;persistId?: string;+ deviceId?: string;agentMeta: Record<string, unknown> | null;}>();let textDeltaFlushTimer: ReturnType<typeof setTimeout> | null = null;++function streamingAssistantDeviceId(+ sessionId: string,+ clientId: string,+): string | undefined {+ return streamingAssistantDeviceIds.get(sessionId)?.get(clientId);+}++function rememberStreamingAssistantDeviceId(+ sessionId: string,+ clientId: string,+ deviceId: string,+): void {+ const existing = streamingAssistantDeviceIds.get(sessionId) ?? new Map<string, string>();+ existing.set(clientId, deviceId);+ streamingAssistantDeviceIds.set(sessionId, existing);+}++function forgetStreamingAssistantDeviceId(sessionId: string, clientId: string): boolean {+ const existing = streamingAssistantDeviceIds.get(sessionId);+ if (!existing || !existing.delete(clientId)) return false;+ if (existing.size === 0) streamingAssistantDeviceIds.delete(sessionId);+ return true;+}++function clearStreamingAssistantPointer(sessionId: string): boolean {+ return streamingAssistantClientIds.delete(sessionId);+}++function clearStreamingAssistantState(sessionId: string): boolean {+ const clientIdChanged = clearStreamingAssistantPointer(sessionId);+ const deviceIdChanged = streamingAssistantDeviceIds.delete(sessionId);+ return clientIdChanged || deviceIdChanged;+}+// 目标模式状态镜像:null = 已确认无 goal(get-status 拉过 / push 清除);缺项 = 尚未拉取。const sessionGoalStatus = new Map<string, MobileGoalStatusPayload | null>();// maker `status` 事件驱动的权威 turn 边界(与 sessionRunning 分开):sessionRunning 还会被@@ -668,8 +736,10 @@ function invalidateSessionMessageWindowState(changed = sessionTaskUpdates.delete(sessionId) || changed;changed = sessionParkedTaskUpdates.delete(sessionId) || changed;changed = sessionMessageSyncMarkers.delete(sessionId) || changed;- changed = streamingAssistantClientIds.delete(sessionId) || changed;+ changed = clearStreamingAssistantState(sessionId) || changed;changed = pendingLiveAssistantClientIds.delete(sessionId) || changed;+ changed = pendingHostAnchorLiveAssistantClientIds.delete(sessionId) || changed;+ changed = activePendingHostAnchorRoundIds.delete(sessionId) || changed;if (pendingTextDeltaBatches.has(sessionId)) {discardPendingTextDelta(sessionId);changed = true;@@ -687,6 +757,118 @@ function invalidateSessionMessageWindowState(return changed;}+function removeSessionRuntimeState(sessionId: string): void {+ invalidateSessionMessageWindowState(sessionId, false);+ pendingInteractions.delete(sessionId);+ pendingInteractionsAuthoritative.delete(sessionId);+ inputProjections.delete(sessionId);+ bumpInputProjectionAuthorityEpoch(sessionId);+ sessionLiveActivity.delete(sessionId);+ sessionRunning.delete(sessionId);+ sessionRunStatus.delete(sessionId);+ sessionMakerActivityEpochs.delete(sessionId);+ sessionMakerTurnRunning.delete(sessionId);+ sessionMessageLifecycle.forget(sessionId);+ sessionDeviceIndex.delete(sessionId);+ dropPendingTitlePreview(sessionId);+ // revision 下限按会话回收:它不参与单轮快照回收(那会把覆盖权还给晚到的+ // 旧快照),所以只能在会话本身消失时清,保持有界。+ const sessionPrefix = interactionResolveKey(sessionId, '');+ for (const key of interactionRevisionFloors.keys()) {+ if (key.startsWith(sessionPrefix)) interactionRevisionFloors.delete(key);+ }+}++function discardTransportOwnedPendingSessionState(+ sessionId: string,+ deviceId: string,+): boolean {+ let changed = false;+ const batch = pendingTextDeltaBatches.get(sessionId);+ if (batch?.deviceId === deviceId) {+ discardPendingTextDelta(sessionId);+ changed = true;+ }+ const pendingAnchors = pendingHostAnchorLiveAssistantClientIds.get(sessionId);+ const pendingAnchorIds = new Set<string>();+ if (pendingAnchors) {+ for (const [id, identity] of pendingAnchors) {+ if (!identity.deviceIds.has(deviceId)) continue;+ if (identity.deviceIds.size > 1) {+ pendingAnchors.set(id, {+ ...identity,+ deviceIds: new Set([...identity.deviceIds].filter((candidate) => candidate !== deviceId)),+ });+ changed = true;+ } else {+ pendingAnchorIds.add(id);+ }+ }+ }+ const streamingDeviceIds = streamingAssistantDeviceIds.get(sessionId);+ if (streamingDeviceIds) {+ for (const [id, ownerDeviceId] of streamingDeviceIds) {+ if (ownerDeviceId === deviceId) pendingAnchorIds.add(id);+ }+ }+ if (pendingAnchorIds.size === 0) return changed;+ const existingMessages = messages.get(sessionId);+ if (existingMessages && pendingAnchorIds.size > 0) {+ const nextMessages = existingMessages.filter((message) => (+ !pendingAnchorIds.has(message.id) && !pendingAnchorIds.has(message.clientId)+ ));+ if (nextMessages.length !== existingMessages.length) {+ if (nextMessages.length > 0) messages.set(sessionId, nextMessages);+ else messages.delete(sessionId);+ changed = true;+ }+ }+ const pendingLiveIds = pendingLiveAssistantClientIds.get(sessionId);+ if (pendingLiveIds) {+ for (const id of pendingAnchorIds) pendingLiveIds.delete(id);+ if (pendingLiveIds.size === 0) pendingLiveAssistantClientIds.delete(sessionId);+ }+ const streamingClientId = streamingAssistantClientIds.get(sessionId);+ if (streamingClientId && pendingAnchorIds.has(streamingClientId)) {+ streamingAssistantClientIds.delete(sessionId);+ }+ for (const id of pendingAnchorIds) forgetStreamingAssistantDeviceId(sessionId, id);+ if (pendingAnchors) {+ for (const id of pendingAnchorIds) pendingAnchors.delete(id);+ if (pendingAnchors.size === 0) {+ pendingHostAnchorLiveAssistantClientIds.delete(sessionId);+ activePendingHostAnchorRoundIds.delete(sessionId);+ } else {+ const activeRoundId = activePendingHostAnchorRoundIds.get(sessionId);+ if (+ activeRoundId !== undefined+ && ![...pendingAnchors.values()].some((identity) => (+ identity.unboundRoundId === activeRoundId+ ))+ ) {+ activePendingHostAnchorRoundIds.delete(sessionId);+ }+ }+ }+ return true;+}++function hasTransportOwnedSessionStateFromOtherDevice(+ sessionId: string,+ deviceId: string,+): boolean {+ const batchDeviceId = pendingTextDeltaBatches.get(sessionId)?.deviceId;+ if (batchDeviceId !== undefined && batchDeviceId !== deviceId) return true;+ const pendingAnchors = pendingHostAnchorLiveAssistantClientIds.get(sessionId);+ if (pendingAnchors && [...pendingAnchors.values()].some((identity) => (+ [...identity.deviceIds].some((ownerDeviceId) => ownerDeviceId !== deviceId)+ ))) return true;+ const streamingDeviceIds = streamingAssistantDeviceIds.get(sessionId);+ return streamingDeviceIds+ ? [...streamingDeviceIds.values()].some((ownerDeviceId) => ownerDeviceId !== deviceId)+ : false;+}+function releaseSessionDetailProjections(sessionId: string): boolean {let changed = livePlanSnapshots.delete(sessionId);changed = sessionTaskUpdates.delete(sessionId) || changed;@@ -770,6 +952,81 @@ function applyMessageWriteRetention(sessionId: string): void {let mergedSessions: RemoteSession[] = [];let messageVersion = 0;let storeVersion = 0;++type LiveRowCreatedAtAnchor = {+ createdAt: string | undefined;+ /** 会话列表快照可能早于本次发送,只能临时钳制;消息水位才可完成重锚。 */+ provisional: boolean;+};++function liveRowCreatedAtAnchor(sessionId: string): LiveRowCreatedAtAnchor {+ const pendingHostAnchorIds = pendingHostAnchorLiveAssistantClientIds.get(sessionId);+ const session = mergedSessions.find((item) => item.id === sessionId);+ const authoritativeMessages = (messages.get(sessionId) ?? []).filter((message) => {+ const isPendingHostAnchor = pendingHostAnchorIds?.has(message.id) === true+ || pendingHostAnchorIds?.has(message.clientId) === true;+ const isLocalSystemCard = message.systemCardType !== undefined+ && (message.id.startsWith('mobile-system-') || message.clientId.startsWith('mobile-system-'));+ return !isPendingHostAnchor && !isLocalSystemCard;+ });+ const messageWatermark = newestCreatedAt(authoritativeMessages);+ if (messageWatermark) {+ const latestAuthoritativeMessage = authoritativeMessages[authoritativeMessages.length - 1];+ const newerUserSendAt = session?.userSendAt+ && session.userSendAt.localeCompare(messageWatermark) > 0+ ? session.userSendAt+ : undefined;+ return {+ createdAt: newerUserSendAt ?? messageWatermark,+ // user 尾行只有在没有更晚的 session.userSendAt 时才可认作本轮问题;否则它+ // 属于旧轮次,当前 user push 仍在途。assistant / tool 尾行同样只能提供临时时间锚。+ provisional: newerUserSendAt !== undefined || latestAuthoritativeMessage?.role !== 'user',+ };+ }+ return {+ createdAt: session?.userSendAt ?? session?.updatedAt ?? session?.createdAt,+ provisional: true,+ };+}++function latestUserSendAt(sessionId: string): string | undefined {+ return mergedSessions.find((item) => item.id === sessionId)?.userSendAt ?? undefined;+}++function authoritativeSessionDeviceId(sessionId: string): string | undefined {+ if (!deviceList) return undefined;+ const session = mergedSessions.find((item) => item.id === sessionId);+ const canonicalDeviceId = session?.canonicalDeviceId;+ if (canonicalDeviceId && deviceList.some((device) => device.deviceId === canonicalDeviceId)) {+ return canonicalDeviceId;+ }+ const indexedDeviceId = sessionDeviceIndex.get(sessionId);+ return indexedDeviceId && deviceList.some((device) => device.deviceId === indexedDeviceId)+ ? indexedDeviceId+ : undefined;+}++function userMessageMatchesLatestSend(sessionId: string, message: RemoteMessage): boolean {+ if (message.role !== 'user') return false;+ const userSendAt = latestUserSendAt(sessionId);+ return Boolean(userSendAt && message.createdAt.localeCompare(userSendAt) >= 0);+}++function userMessageCanConsumePendingLiveReply(+ sessionId: string,+ message: RemoteMessage,+): boolean {+ if (message.role !== 'user') return false;+ const userSendAt = latestUserSendAt(sessionId);+ // Before session metadata arrives, preserve the existing realtime ordering semantics.+ // Once a send marker exists, an older delayed push normally belongs to a previous round.+ // The exception is an unbound reply frozen by an offline transition: only an older user+ // row can identify that reply's original round after reconnect metadata has moved ahead.+ return !userSendAt+ || message.createdAt.localeCompare(userSendAt) >= 0+ || hasOfflineUnboundPendingHostAnchor(sessionId);+}+// 当前权威设备列表(由首页从设备列表 API reconcile 后注入)。每次重算会话时基于它 + 当前 shards(stale 侧)// 重建身份索引,用于给会话算展示用 canonicalDeviceId(把 re-link 后残留 stale shard 认领回当前设备);// 为 null 时不归一,安全退化。@@ -856,7 +1113,14 @@ function recomputeSessions(): void {// 数组级同样调和:全部元素引用与序都未变时保留旧数组引用——useRemoteSessions 的// useSyncExternalStore 快照经 Object.is 即可短路,消费屏对无关 emit 零重渲染。mergedSessions = sameElementRefs(mergedSessions, next) ? mergedSessions : next;+ let liveRowsReanchored = false;for (const session of mergedSessions) {+ bindPendingHostAnchorSendAt(session.id, session.userSendAt);+ liveRowsReanchored = reanchorPendingLiveAssistantRows(+ session.id,+ session.userSendAt ?? session.updatedAt ?? session.createdAt,+ { consumePending: false },+ ) || liveRowsReanchored;const nextRetention = classifySessionRetention(session);if (nextRetention !== 'schedule' || previousRetention.get(session.id) === 'schedule') continue;// source 晚到后立即切断旧缓存路径。旧 hydrate / debounce 回调还会在提交前@@ -875,6 +1139,7 @@ function recomputeSessions(): void {sessionMessageLifecycle.leave(session.id, 'session-switch');}}+ if (liveRowsReanchored) bumpMessageVersion();emit();}@@ -1074,6 +1339,7 @@ function preferCompleteMessage(existing: RemoteMessage | undefined, incoming: Re// (for example an Agent/Task terminal state patched after the original push).return {...existing,+ createdAt: incoming.createdAt,agentMeta: {...(existing.agentMeta ?? {}),...(incoming.agentMeta ?? {}),@@ -1159,12 +1425,115 @@ function rememberPendingLiveAssistantClientId(sessionId: string, clientId: strinpendingLiveAssistantClientIds.set(sessionId, existing);}+function rememberPendingHostAnchorLiveAssistantClientId(+ sessionId: string,+ clientId: string | null | undefined,+ sendAt: string | null = latestUserSendAt(sessionId) ?? null,+ bindOnMetadata = true,+ deviceIds?: string | readonly string[],+ unboundRoundId?: number | null,+): void {+ if (!clientId) return;+ const existing = pendingHostAnchorLiveAssistantClientIds.get(sessionId)+ ?? new Map<string, PendingHostAnchorIdentity>();+ const nextDeviceIds = typeof deviceIds === 'string'+ ? [deviceIds]+ : deviceIds ?? [];+ if (!existing.has(clientId)) {+ let resolvedRoundId = unboundRoundId;+ if (resolvedRoundId === undefined) {+ if (sendAt !== null) {+ resolvedRoundId = null;+ } else if (sessionMakerTurnRunning.get(sessionId) === true) {+ resolvedRoundId = activePendingHostAnchorRoundIds.get(sessionId);+ if (resolvedRoundId === undefined) {+ resolvedRoundId = ++nextPendingHostAnchorRoundId;+ activePendingHostAnchorRoundIds.set(sessionId, resolvedRoundId);+ }+ } else {+ // Older producers may omit maker status boundaries. Preserve their historical+ // one-row-per-user fallback instead of grouping unrelated unbound replies.+ resolvedRoundId = ++nextPendingHostAnchorRoundId;+ }+ }+ existing.set(clientId, {+ bindOnMetadata,+ deviceIds: new Set(nextDeviceIds),+ sendAt,+ unboundRoundId: resolvedRoundId,+ });+ } else if (nextDeviceIds.length > 0) {+ const identity = existing.get(clientId);+ if (identity && nextDeviceIds.some((deviceId) => !identity.deviceIds.has(deviceId))) {+ existing.set(clientId, {+ ...identity,+ deviceIds: new Set([...identity.deviceIds, ...nextDeviceIds]),+ });+ }+ }+ pendingHostAnchorLiveAssistantClientIds.set(sessionId, existing);+}++function pendingHostAnchorIdentity(+ sessionId: string,+ ...ids: Array<string | null | undefined>+): PendingHostAnchorIdentity | undefined {+ const existing = pendingHostAnchorLiveAssistantClientIds.get(sessionId);+ if (!existing) return undefined;+ for (const id of ids) {+ if (id && existing.has(id)) return existing.get(id);+ }+ return undefined;+}++function bindPendingHostAnchorSendAt(sessionId: string, sendAt: string | null | undefined): void {+ if (!sendAt) return;+ const existing = pendingHostAnchorLiveAssistantClientIds.get(sessionId);+ if (!existing) return;+ for (const [id, identity] of existing) {+ if (identity.sendAt === null && identity.bindOnMetadata) {+ existing.set(id, { ...identity, sendAt });+ }+ }+}++function freezeUnboundPendingHostAnchorsForOffline(sessionId: string, deviceId: string): boolean {+ const existing = pendingHostAnchorLiveAssistantClientIds.get(sessionId);+ if (!existing) return false;+ let changed = false;+ for (const [id, identity] of existing) {+ if (!identity.deviceIds.has(deviceId)) continue;+ if (identity.sendAt !== null || !identity.bindOnMetadata) continue;+ existing.set(id, { ...identity, bindOnMetadata: false });+ changed = true;+ }+ return changed;+}++function hasOfflineUnboundPendingHostAnchor(sessionId: string): boolean {+ const existing = pendingHostAnchorLiveAssistantClientIds.get(sessionId);+ return existing+ ? [...existing.values()].some((identity) => (+ identity.sendAt === null && !identity.bindOnMetadata+ ))+ : false;+}+function forgetPendingLiveAssistantClientId(sessionId: string, clientId: string | null | undefined): void {if (!clientId) return;const existing = pendingLiveAssistantClientIds.get(sessionId);- if (!existing) return;- existing.delete(clientId);- if (existing.size === 0) pendingLiveAssistantClientIds.delete(sessionId);+ if (existing) {+ existing.delete(clientId);+ if (existing.size === 0) pendingLiveAssistantClientIds.delete(sessionId);+ }+ const pendingHostAnchorIds = pendingHostAnchorLiveAssistantClientIds.get(sessionId);+ if (pendingHostAnchorIds) {+ pendingHostAnchorIds.delete(clientId);+ if (pendingHostAnchorIds.size === 0) {+ pendingHostAnchorLiveAssistantClientIds.delete(sessionId);+ }+ }+ forgetStreamingAssistantDeviceId(sessionId, clientId);}function forgetPendingLiveAssistantMessageIdentity(@@ -1178,9 +1547,268 @@ function forgetGeneratedPendingLiveAssistantClientIds(sessionId: string): void {const existing = pendingLiveAssistantClientIds.get(sessionId);if (!existing) return;for (const id of [...existing]) {- if (isGeneratedStreamingClientId(id)) existing.delete(id);+ if (isGeneratedStreamingClientId(id)) forgetPendingLiveAssistantClientId(sessionId, id);+ }+}++function reanchorPendingLiveAssistantRows(+ sessionId: string,+ hostCreatedAtWatermark: string | undefined,+ options: {+ /** 快照默认只临时重锚;实时消息或已匹配最新 userSendAt 的窗口才可消费身份。 */+ consumePending?: boolean;+ /** user 行与 live 回复同戳时,明确把回复放在触发它的 user 行之后。 */+ afterMessage?: RemoteMessage;+ /** 权威窗口可一次带回多轮 user;从窗口尾部向前与 pending 回复按序一对一配对。 */+ afterMessages?: readonly RemoteMessage[];+ /** 权威窗口已覆盖到会话起点;否则最旧 user 可能已被窗口上沿截断。 */+ afterMessagesStartIsComplete?: boolean;+ /** 已知本轮发送标记时,实时 user push 也只认领最新的 pending 回复。 */+ pairPendingFromEnd?: boolean;+ } = {},+): boolean {+ if (!hostCreatedAtWatermark) return false;+ const pendingIds = pendingHostAnchorLiveAssistantClientIds.get(sessionId);+ if (!pendingIds || pendingIds.size === 0) return false;+ const existing = messages.get(sessionId);+ if (!existing) return false;+ const pendingRows: Array<{+ identity: PendingHostAnchorIdentity;+ message: RemoteMessage;+ }> = [];+ for (const [pendingId, identity] of pendingIds) {+ const match = existing.find((message) => (+ message.role === 'assistant'+ && (message.id === pendingId || message.clientId === pendingId)+ ));+ if (match && !pendingRows.some((row) => row.message === match)) {+ pendingRows.push({ message: match, identity });+ }+ }+ const afterMessages = options.afterMessages+ ?? (options.afterMessage ? [options.afterMessage] : []);+ const pairsPendingFromEnd = options.afterMessages !== undefined+ || options.pairPendingFromEnd === true;+ const latestSendAt = latestUserSendAt(sessionId);+ const knownSendAts = [...new Set([+ ...pendingRows+ .map((row) => row.identity.sendAt)+ .filter((sendAt): sendAt is string => sendAt !== null),+ ...afterMessages+ .filter((message) => message.role === 'user')+ .map((message) => message.createdAt),+ ...(latestSendAt ? [latestSendAt] : []),+ ])].sort((left, right) => left.localeCompare(right));+ const hasOfflineUnboundPendingRow = pendingRows.some((row) => (+ row.identity.sendAt === null && !row.identity.bindOnMetadata+ ));+ const pendingRowCanPairMessage = (+ row: (typeof pendingRows)[number],+ message: RemoteMessage,+ ): boolean => {+ const rowSendAt = row.identity.sendAt;+ if (+ hasOfflineUnboundPendingRow+ && latestSendAt+ && message.createdAt.localeCompare(latestSendAt) < 0+ ) {+ return rowSendAt === null && !row.identity.bindOnMetadata;+ }+ if (rowSendAt === null && !row.identity.bindOnMetadata) {+ return Boolean(latestSendAt && message.createdAt.localeCompare(latestSendAt) < 0);+ }+ if (!rowSendAt || !latestSendAt || rowSendAt.localeCompare(latestSendAt) >= 0) return true;+ const nextSendAt = knownSendAts.find((sendAt) => sendAt.localeCompare(rowSendAt) > 0);+ return message.createdAt.localeCompare(rowSendAt) >= 0+ && (!nextSendAt || message.createdAt.localeCompare(nextSendAt) < 0);+ };+ const pairs: Array<{+ pendingRow: (typeof pendingRows)[number];+ afterMessage: RemoteMessage;+ }> = [];+ const pairsOfflineUnboundFromStart = options.afterMessages === undefined+ && afterMessages.length === 1+ && afterMessages[0].role === 'user'+ && hasOfflineUnboundPendingRow+ && Boolean(latestSendAt)+ && afterMessages[0].createdAt.localeCompare(latestSendAt ?? '') < 0;+ const offlineUnboundRoundGroups = new Map<+ number,+ Array<(typeof pendingRows)[number]>+ >();+ for (const row of pendingRows) {+ if (+ row.identity.sendAt !== null+ || row.identity.bindOnMetadata+ || row.identity.unboundRoundId === null+ ) continue;+ const group = offlineUnboundRoundGroups.get(row.identity.unboundRoundId) ?? [];+ group.push(row);+ offlineUnboundRoundGroups.set(row.identity.unboundRoundId, group);+ }+ const orderedOfflineUnboundRoundGroups = [...offlineUnboundRoundGroups]+ .sort(([leftRoundId], [rightRoundId]) => leftRoundId - rightRoundId)+ .map(([, rows]) => rows);+ const reconnectWindowUsers = afterMessages.filter((message) => (+ message.role === 'user'+ && (!latestSendAt || message.createdAt.localeCompare(latestSendAt) <= 0)+ ));+ const pairsOfflineUnboundWindowInOrder = options.afterMessages !== undefined+ && orderedOfflineUnboundRoundGroups.length > 1+ && orderedOfflineUnboundRoundGroups.reduce((count, rows) => count + rows.length, 0)+ === pendingRows.length+ && reconnectWindowUsers.length > 0;+ // A bounded latest window represents the newest user rows, so pair it with the+ // newest pending replies. Realtime pushes do the same once the latest send marker+ // is known, except delayed users restoring multiple offline-unbound rounds: those+ // must consume the oldest eligible cohort first to preserve arrival order.+ if (pairsPendingFromEnd && pairsOfflineUnboundWindowInOrder) {+ // A reconnect window can deliver several delayed users in one authoritative page.+ // Pair only when that page accounts for every offline cohort; a truncated latest+ // suffix cannot prove whether its first user belongs to the oldest pending round.+ if (+ options.afterMessagesStartIsComplete === true+ && reconnectWindowUsers.length === orderedOfflineUnboundRoundGroups.length+ ) {+ const pairedUsers = reconnectWindowUsers;+ for (let index = 0; index < orderedOfflineUnboundRoundGroups.length; index += 1) {+ for (const pendingRow of orderedOfflineUnboundRoundGroups[index]) {+ pairs.push({ pendingRow, afterMessage: pairedUsers[index] });+ }+ }+ }+ } else if (pairsPendingFromEnd && pairsOfflineUnboundFromStart) {+ const afterMessage = afterMessages[0];+ const pendingRow = pendingRows+ .filter((row) => pendingRowCanPairMessage(row, afterMessage))+ .reduce<(typeof pendingRows)[number] | undefined>((oldest, row) => {+ if (!oldest) return row;+ const oldestRoundId = oldest.identity.unboundRoundId ?? Number.MAX_SAFE_INTEGER;+ const rowRoundId = row.identity.unboundRoundId ?? Number.MAX_SAFE_INTEGER;+ return rowRoundId < oldestRoundId ? row : oldest;+ }, undefined);+ if (pendingRow) pairs.push({ pendingRow, afterMessage });+ } else if (pairsPendingFromEnd) {+ let maxRowIndex = pendingRows.length - 1;+ for (let afterIndex = afterMessages.length - 1; afterIndex >= 0 && maxRowIndex >= 0; afterIndex -= 1) {+ let matchedRowIndex = -1;+ for (let rowIndex = maxRowIndex; rowIndex >= 0; rowIndex -= 1) {+ if (pendingRowCanPairMessage(pendingRows[rowIndex], afterMessages[afterIndex])) {+ matchedRowIndex = rowIndex;+ break;+ }+ }+ if (matchedRowIndex < 0) continue;+ pairs.unshift({+ pendingRow: pendingRows[matchedRowIndex],+ afterMessage: afterMessages[afterIndex],+ });+ maxRowIndex = matchedRowIndex - 1;+ }+ } else {+ const pairCount = Math.min(pendingRows.length, afterMessages.length);+ for (let index = 0; index < pairCount; index += 1) {+ pairs.push({ pendingRow: pendingRows[index], afterMessage: afterMessages[index] });+ }+ }+ // A single realtime/latest-window user row identifies one send round. All live+ // assistant blocks carrying that non-null send marker belong after the same user;+ // move them as one ordered block instead of consuming only the last block.+ if (afterMessages.length === 1 && pairs.length === 1) {+ const groupedIdentity = pairs[0].pendingRow.identity;+ if (groupedIdentity.unboundRoundId !== null || groupedIdentity.sendAt !== null) {+ const afterMessage = afterMessages[0];+ const groupedRows = pendingRows.filter((row) => (+ (groupedIdentity.unboundRoundId !== null+ ? row.identity.unboundRoundId === groupedIdentity.unboundRoundId+ : row.identity.sendAt === groupedIdentity.sendAt)+ && pendingRowCanPairMessage(row, afterMessage)+ ));+ pairs.splice(0, pairs.length, ...groupedRows.map((pendingRow) => ({+ pendingRow,+ afterMessage,+ })));+ }}- if (existing.size === 0) pendingLiveAssistantClientIds.delete(sessionId);+ const pairedCreatedAtById = new Map<string, string>();+ for (const pair of pairs) {+ const pendingRow = pair.pendingRow.message;+ const createdAt = pair.afterMessage.createdAt;+ pairedCreatedAtById.set(pendingRow.id, createdAt);+ pairedCreatedAtById.set(pendingRow.clientId, createdAt);+ }+ const reanchored = existing.map((message) => {+ if (+ message.role !== 'assistant'+ || (!pendingIds.has(message.id) && !pendingIds.has(message.clientId))+ ) return message;+ const pairedCreatedAt = pairedCreatedAtById.get(message.id)+ ?? pairedCreatedAtById.get(message.clientId);+ if (pairsPendingFromEnd && pairedCreatedAt === undefined) return message;+ const pendingIdentity = pendingHostAnchorIdentity(sessionId, message.id, message.clientId);+ if (+ pairedCreatedAt === undefined+ && pendingIdentity?.sendAt === null+ && !pendingIdentity.bindOnMetadata+ ) return message;+ if (+ pairedCreatedAt === undefined+ && pendingIdentity?.sendAt+ && latestSendAt+ && pendingIdentity.sendAt.localeCompare(latestSendAt) < 0+ && hostCreatedAtWatermark.localeCompare(latestSendAt) >= 0+ ) return message;+ const createdAt = pairedCreatedAt ?? hostCreatedAtWatermark;+ return message.createdAt === createdAt ? message : { ...message, createdAt };+ });+ let next = normalizeMessages(reanchored);+ const pairGroups: Array<{+ afterMessage: RemoteMessage;+ pendingRows: Array<(typeof pendingRows)[number]>;+ }> = [];+ for (const pair of pairs) {+ const group = pairGroups.find((candidate) => (+ messageIdentityMatches(candidate.afterMessage, pair.afterMessage)+ ));+ if (group) group.pendingRows.push(pair.pendingRow);+ else pairGroups.push({ afterMessage: pair.afterMessage, pendingRows: [pair.pendingRow] });+ }+ const consumedPendingRows: RemoteMessage[] = [];+ for (const group of pairGroups) {+ const groupedRows = next.filter((message) => group.pendingRows.some((row) => (+ messageIdentityMatches(message, row.message)+ )));+ if (groupedRows.length === 0) continue;+ const withoutPending = next.filter((message) => !group.pendingRows.some((row) => (+ messageIdentityMatches(message, row.message)+ )));+ const anchorIndex = withoutPending.findIndex((message) => (+ messageIdentityMatches(message, group.afterMessage)+ ));+ if (anchorIndex < 0) continue;+ next = [+ ...withoutPending.slice(0, anchorIndex + 1),+ ...groupedRows,+ ...withoutPending.slice(anchorIndex + 1),+ ];+ consumedPendingRows.push(...groupedRows);+ }+ if (options.consumePending !== false) {+ if (afterMessages.length > 0) {+ for (const pendingRow of consumedPendingRows) {+ pendingIds.delete(pendingRow.id);+ pendingIds.delete(pendingRow.clientId);+ }+ if (pendingIds.size === 0) {+ pendingHostAnchorLiveAssistantClientIds.delete(sessionId);+ }+ } else {+ pendingHostAnchorLiveAssistantClientIds.delete(sessionId);+ }+ }+ if (remoteMessageListsEqual(existing, next)) return false;+ messages.set(sessionId, next);+ return true;}function retireGeneratedStreamingFallback(sessionId: string): void {@@ -1248,8 +1876,26 @@ function migrateGeneratedStreamingClientId(sessionId: string, generatedClientId:streamingAssistantClientIds.set(sessionId, persistId);const hadPendingLiveId = pendingLiveAssistantClientIds.get(sessionId)?.has(generatedClientId) === true;+ const streamingDeviceId = streamingAssistantDeviceId(sessionId, generatedClientId);+ const neededHostAnchor = pendingHostAnchorLiveAssistantClientIds+ .get(sessionId)+ ?.has(generatedClientId) === true;+ const hostAnchorIdentity = pendingHostAnchorIdentity(sessionId, generatedClientId);forgetPendingLiveAssistantClientId(sessionId, generatedClientId);if (hadPendingLiveId) rememberPendingLiveAssistantClientId(sessionId, persistId);+ if (streamingDeviceId) {+ rememberStreamingAssistantDeviceId(sessionId, persistId, streamingDeviceId);+ }+ if (neededHostAnchor && hostAnchorIdentity) {+ rememberPendingHostAnchorLiveAssistantClientId(+ sessionId,+ persistId,+ hostAnchorIdentity.sendAt,+ hostAnchorIdentity.bindOnMetadata,+ [...hostAnchorIdentity.deviceIds],+ hostAnchorIdentity.unboundRoundId,+ );+ }const existing = messages.get(sessionId);if (!existing) return false;@@ -1295,7 +1941,11 @@ function streamingClientIdFor(sessionId: string, persistId: string | undefined):return { clientId: generated, changed: false };}-function upsertMessage(sessionId: string, message: RemoteMessage): boolean {+function upsertMessage(+ sessionId: string,+ message: RemoteMessage,+ options: { retirePendingAssistantIdentityOnEqual?: boolean } = {},+): boolean {const existing = messages.get(sessionId) ?? [];const index = existing.findIndex((item) => messageIdentityMatches(item, message));let fallbackIndex = -1;@@ -1326,7 +1976,29 @@ function upsertMessage(sessionId: string, message: RemoteMessage): boolean {return true;}const replacement = preferCompleteMessage(existing[index], message);- if (remoteMessageEqual(existing[index], replacement)) return false;+ if (remoteMessageEqual(existing[index], replacement)) {+ if (+ message.role !== 'assistant'+ || options.retirePendingAssistantIdentityOnEqual !== true+ ) return false;+ const hadPendingIdentity = isPendingLiveAssistantMessage(sessionId, existing[index])+ || pendingHostAnchorIdentity(+ sessionId,+ existing[index].id,+ existing[index].clientId,+ message.id,+ message.clientId,+ ) !== undefined;+ forgetPendingLiveAssistantMessageIdentity(+ sessionId,+ existing[index].id,+ existing[index].clientId,+ message.id,+ message.clientId,+ );+ if (isPersistedAssistantMessage(message)) retireGeneratedStreamingFallback(sessionId);+ return hadPendingIdentity;+ }const next = existing.slice();next[index] = replacement;messages.set(sessionId, normalizeMessages(next));@@ -1349,19 +2021,99 @@ function applyRemoteTextEvent(sessionId: string,event: Record<string, unknown>,persistId?: string,+ deviceId?: string,): boolean {const data = isRecord(event.data) ? event.data : null;const text = typeof data?.text === 'string' ? data.text : '';const isFinal = data?.isFinal === true;if (!text) return false;+ const authoritativeDeviceId = authoritativeSessionDeviceId(sessionId);+ const currentMessages = messages.get(sessionId) ?? [];+ 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+ ));+ if (!ownedMessage || !isPendingLiveAssistantMessage(sessionId, ownedMessage)) return false;+ const ownedHostAnchorIdentity = pendingHostAnchorIdentity(+ sessionId,+ ownedMessage.id,+ ownedMessage.clientId,+ ownedClientId,+ );+ return !(+ ownedHostAnchorIdentity?.bindOnMetadata === false+ && ownedHostAnchorIdentity.deviceIds.has(ownerDeviceId)+ );+ });+ const rejectsBeforeClientIdMutation = deviceId !== undefined+ && authoritativeDeviceId !== undefined+ && deviceId !== authoritativeDeviceId+ && hasAuthoritativePendingAssembly;+ if (rejectsBeforeClientIdMutation) return false;+const clientIdResolution = streamingClientIdFor(sessionId, persistId);const { clientId } = clientIdResolution;- const existing = messages.get(sessionId)?.find((message) => message.clientId === clientId);+ const previousStreamingDeviceId = streamingAssistantDeviceId(sessionId, clientId);+ const matchedExisting = messages.get(sessionId)?.find((message) => message.clientId === clientId);+ const matchedHostAnchorIdentity = matchedExisting+ ? pendingHostAnchorIdentity(+ sessionId,+ matchedExisting.id,+ matchedExisting.clientId,+ clientId,+ )+ : undefined;+ const previousTransportWasSoftOffline = previousStreamingDeviceId !== undefined+ && matchedHostAnchorIdentity?.bindOnMetadata === false+ && matchedHostAnchorIdentity.deviceIds.has(previousStreamingDeviceId);+ const matchedExistingIsPending = matchedExisting !== undefined+ && isPendingLiveAssistantMessage(sessionId, matchedExisting);+ const matchedExistingIsPersisted = matchedExisting !== undefined+ && !matchedExistingIsPending+ && isPersistedAssistantMessage(matchedExisting);+ const rejectsNonAuthoritativeTransportReplay = deviceId !== undefined+ && authoritativeDeviceId !== undefined+ && deviceId !== authoritativeDeviceId+ && (+ matchedExistingIsPersisted+ || (+ previousStreamingDeviceId !== undefined+ && previousStreamingDeviceId !== deviceId+ && previousStreamingDeviceId === authoritativeDeviceId+ && !previousTransportWasSoftOffline+ && matchedExistingIsPending+ )+ );+ if (rejectsNonAuthoritativeTransportReplay) return clientIdResolution.changed;+ const resetsTransportAssembly = previousStreamingDeviceId !== undefined+ && deviceId !== undefined+ && previousStreamingDeviceId !== deviceId+ && matchedExisting !== undefined+ && isPendingLiveAssistantMessage(sessionId, matchedExisting);+ const resetHostAnchorIdentity = resetsTransportAssembly+ ? pendingHostAnchorIdentity(+ sessionId,+ matchedExisting.id,+ matchedExisting.clientId,+ clientId,+ )+ : undefined;+ const existing = resetsTransportAssembly ? undefined : matchedExisting;const finalTextWasTruncated = isFinal && (hasDeviceLinkTruncationMarker(event) || hasDeviceLinkTruncationMarker(data));if (isFinal && !existing) {+ // Device-clock stamp on a brand-new live row: anchor it to the newest known message,+ // or to host-domain session activity when the message window is still empty. Otherwise+ // an ahead device clock can dominate the first later host-persisted row.+ const hostCreatedAtAnchor = liveRowCreatedAtAnchor(sessionId);+ const createdAt = clampLiveRowCreatedAt(+ new Date().toISOString(),+ hostCreatedAtAnchor.createdAt,+ );const changed = upsertMessage(sessionId, {id: clientId,clientId,@@ -1370,9 +2122,35 @@ function applyRemoteTextEvent(content: text,toolUseId: null,agentMeta: isRecord(event.agentMeta) ? event.agentMeta : null,- createdAt: new Date().toISOString(),+ createdAt,});- if (changed) rememberPendingLiveAssistantClientId(sessionId, clientId);+ if (resetsTransportAssembly && !changed) {+ forgetPendingLiveAssistantMessageIdentity(+ sessionId,+ matchedExisting.id,+ matchedExisting.clientId,+ clientId,+ );+ }+ if (changed || resetsTransportAssembly) {+ rememberPendingLiveAssistantClientId(sessionId, clientId);+ if (hostCreatedAtAnchor.provisional || resetHostAnchorIdentity) {+ rememberPendingHostAnchorLiveAssistantClientId(+ sessionId,+ clientId,+ resetHostAnchorIdentity?.sendAt,+ resetHostAnchorIdentity?.bindOnMetadata ?? true,+ deviceId,+ resetHostAnchorIdentity?.unboundRoundId,+ );+ }+ }+ if (+ deviceId !== undefined+ && pendingLiveAssistantClientIds.get(sessionId)?.has(clientId) === true+ ) {+ rememberStreamingAssistantDeviceId(sessionId, clientId, deviceId);+ }return changed || clientIdResolution.changed;}@@ -1395,6 +2173,15 @@ function applyRemoteTextEvent(: streamingMeta(isRecord(event.agentMeta)? { ...(existing?.agentMeta ?? {}), ...event.agentMeta }: existing?.agentMeta);+ const hostCreatedAtAnchor = existing ? undefined : liveRowCreatedAtAnchor(sessionId);+ const needsHostAnchor = existing+ ? [existing.id, existing.clientId, clientId].some((id) => (+ Boolean(id) && pendingHostAnchorLiveAssistantClientIds.get(sessionId)?.has(id) === true+ ))+ : hostCreatedAtAnchor?.provisional === true || resetHostAnchorIdentity !== undefined;+ const hostAnchorIdentity = existing+ ? pendingHostAnchorIdentity(sessionId, existing.id, existing.clientId, clientId)+ : resetHostAnchorIdentity;const changed = upsertMessage(sessionId, {id: existing?.id ?? clientId,clientId,@@ -1403,9 +2190,45 @@ function applyRemoteTextEvent(content: nextText,toolUseId: null,agentMeta: nextMeta,- createdAt: existing?.createdAt ?? new Date().toISOString(),+ // Existing rows keep their already-stamped createdAt unchanged (it may already be a+ // clamped value from the first delta). Only a brand-new row's fresh device-clock stamp+ // needs the clamp — see clampLiveRowCreatedAt doc comment in messagePaging.ts.+ createdAt: existing?.createdAt ?? clampLiveRowCreatedAt(+ new Date().toISOString(),+ hostCreatedAtAnchor?.createdAt,+ ),});- if (changed) rememberPendingLiveAssistantClientId(sessionId, clientId);+ if (resetsTransportAssembly && !changed) {+ forgetPendingLiveAssistantMessageIdentity(+ sessionId,+ matchedExisting.id,+ matchedExisting.clientId,+ clientId,+ );+ }+ if (changed || resetsTransportAssembly) {+ rememberPendingLiveAssistantClientId(sessionId, clientId);+ }+ // upsertMessage intentionally clears pending reconciliation identities when it+ // replaces an assistant row. A live delta/final is not host-authoritative, so+ // carry the provisional anchor forward until metadata or a persisted row lands.+ // Even an unchanged replay can add a second transport owner for the same identity.+ if (needsHostAnchor) {+ rememberPendingHostAnchorLiveAssistantClientId(+ sessionId,+ clientId,+ hostAnchorIdentity?.sendAt ?? latestUserSendAt(sessionId) ?? null,+ hostAnchorIdentity?.bindOnMetadata ?? true,+ deviceId,+ hostAnchorIdentity?.unboundRoundId,+ );+ }+ if (+ deviceId !== undefined+ && pendingLiveAssistantClientIds.get(sessionId)?.has(clientId) === true+ ) {+ rememberStreamingAssistantDeviceId(sessionId, clientId, deviceId);+ }return changed || clientIdResolution.changed;}@@ -1419,6 +2242,7 @@ function enqueueRemoteTextDelta(sessionId: string,event: Record<string, unknown>,persistId?: string,+ deviceId?: string,): boolean {const data = isRecord(event.data) ? event.data : null;const text = typeof data?.text === 'string' ? data.text : '';@@ -1426,7 +2250,13 @@ function enqueueRemoteTextDelta(let changed = false;const existing = pendingTextDeltaBatches.get(sessionId);- if (existing?.persistId && persistId && existing.persistId !== persistId) {+ if (+ existing+ && (+ (existing.persistId && persistId && existing.persistId !== persistId)+ || existing.deviceId !== deviceId+ )+ ) {changed = flushPendingTextDelta(sessionId);}const current = pendingTextDeltaBatches.get(sessionId);@@ -1434,6 +2264,7 @@ function enqueueRemoteTextDelta(pendingTextDeltaBatches.set(sessionId, {text: `${current?.text ?? ''}${text}`,persistId: current?.persistId ?? persistId,+ deviceId: current?.deviceId ?? deviceId,agentMeta: incomingMeta? { ...(current?.agentMeta ?? {}), ...incomingMeta }: current?.agentMeta ?? null,@@ -1455,6 +2286,7 @@ function flushPendingTextDelta(sessionId: string): boolean {...(batch.agentMeta ? { agentMeta: batch.agentMeta } : {}),},batch.persistId,+ batch.deviceId,);}@@ -1514,7 +2346,7 @@ function finalizeRemoteStreamingMessages(sessionId: string,boundaryAgentMeta?: Record<string, unknown> | null,): boolean {- streamingAssistantClientIds.delete(sessionId);+ clearStreamingAssistantPointer(sessionId);const existing = messages.get(sessionId);if (!existing) return false;let changed = false;@@ -1999,9 +2831,34 @@ export const remoteSessionStore = {return;}- const existing = messages.get(sessionId) ?? [];const latestOldestCreatedAt = latestWindow[0].createdAt;const latestNewestCreatedAt = latestWindow[latestWindow.length - 1].createdAt;+ // A triggering user row must be inserted before its live assistant reply is+ // tied to the same host timestamp. Other authoritative tail rows keep the+ // existing live-before-persisted arrival order when their timestamps tie.+ const latestTailMessage = latestWindow[latestWindow.length - 1];+ const latestTailIsUser = latestTailMessage.role === 'user';+ const latestSendAt = latestUserSendAt(sessionId);+ const latestTailMatchesSend = userMessageMatchesLatestSend(sessionId, latestTailMessage);+ const latestTailIsKnownStaleUser = latestTailIsUser+ && latestSendAt !== undefined+ && !latestTailMatchesSend;+ const reanchorAfterMerge = latestTailIsUser && !latestTailIsKnownStaleUser;+ // A latest-window request may have started before the current send. Only a user tail+ // at/after the session's send marker may move or finish this pending identity; an older+ // user tail belongs to a previous round and leaves the current reply untouched.+ const consumeReanchorAfterMerge = reanchorAfterMerge && latestTailMatchesSend;+ const reanchorAfterMessages = consumeReanchorAfterMerge+ ? latestWindow.filter((message) => message.role === 'user')+ : undefined;+ const liveRowsReanchoredBeforeMerge = !reanchorAfterMerge+ && !latestTailIsKnownStaleUser+ && reanchorPendingLiveAssistantRows(+ sessionId,+ latestNewestCreatedAt,+ { consumePending: false },+ );+ const existing = messages.get(sessionId) ?? [];const existingIdentityIndex = buildMessageIdentityIndex(existing);const hasOverlap = latestWindow.some((item) => messageIdentityIndexHas(existingIdentityIndex, item));const byKey = new Map<string, RemoteMessage>();@@ -2111,10 +2968,34 @@ export const remoteSessionStore = {// "窗口内容有没有变"无关。被早退跳过时这次权威响应就白来了(#1210 review)。coverLatestPage(sessionId, latestOldestCreatedAt, latestNewestCreatedAt, joinedCoverage);if (remoteMessageListsEqual(existing, next)) {- if (textFlushed) emit();+ const liveRowsReanchoredAfterMerge = reanchorAfterMerge+ && reanchorPendingLiveAssistantRows(+ sessionId,+ latestNewestCreatedAt,+ {+ afterMessage: consumeReanchorAfterMerge ? undefined : latestTailMessage,+ afterMessages: reanchorAfterMessages,+ afterMessagesStartIsComplete: options.moreBeyondWindow !== true,+ consumePending: consumeReanchorAfterMerge,+ },+ );+ if (liveRowsReanchoredBeforeMerge || liveRowsReanchoredAfterMerge) bumpMessageVersion();+ if (textFlushed || liveRowsReanchoredBeforeMerge || liveRowsReanchoredAfterMerge) emit();return;}messages.set(sessionId, next);+ if (reanchorAfterMerge) {+ reanchorPendingLiveAssistantRows(+ sessionId,+ latestNewestCreatedAt,+ {+ afterMessage: consumeReanchorAfterMerge ? undefined : latestTailMessage,+ afterMessages: reanchorAfterMessages,+ afterMessagesStartIsComplete: options.moreBeyondWindow !== true,+ consumePending: consumeReanchorAfterMerge,+ },+ );+ }applyMessageWriteRetention(sessionId);bumpMessageVersion();emit();@@ -2212,7 +3093,41 @@ export const remoteSessionStore = {): void {if (!messageWriteAllowed(sessionId, options.authority)) return;let changed = flushPendingTextDelta(sessionId);- changed = upsertMessage(sessionId, overlayLivePlanSnapshot(sessionId, message)) || changed;+ const reanchorAfterMessage = options.hostTimeAuthoritative !== false && message.role === 'user';+ const userCanReanchorPendingLiveReply = reanchorAfterMessage+ && userMessageCanConsumePendingLiveReply(sessionId, message);+ if (+ options.hostTimeAuthoritative !== false+ && !reanchorAfterMessage+ && reanchorPendingLiveAssistantRows(+ sessionId,+ message.createdAt,+ { consumePending: false },+ )+ ) {+ bumpMessageVersion();+ changed = true;+ }+ changed = upsertMessage(+ sessionId,+ overlayLivePlanSnapshot(sessionId, message),+ { retirePendingAssistantIdentityOnEqual: options.hostTimeAuthoritative !== false },+ ) || changed;+ if (+ userCanReanchorPendingLiveReply+ && reanchorPendingLiveAssistantRows(+ sessionId,+ message.createdAt,+ {+ afterMessage: message,+ consumePending: true,+ pairPendingFromEnd: latestUserSendAt(sessionId) !== undefined,+ },+ )+ ) {+ bumpMessageVersion();+ changed = true;+ }// 订阅内到达的实时行可以把覆盖区间的上界往后推;断流后收到的不行(见 liveTailTrusted)。coverLiveRow(sessionId, message);if (changed) {@@ -2332,7 +3247,7 @@ export const remoteSessionStore = {createdAt: createdAt.toISOString(),systemCardType: cardType,systemCardData: data,- });+ }, { hostTimeAuthoritative: false });return clientId;},@@ -2620,11 +3535,11 @@ export const remoteSessionStore = {* 单条 maker:event push payload 的消费(逐帧与微批拆包**共用**唯一实现——* 两条路径若各自解析,批的语义就会随逐帧演进而漂移)。*/- applyMakerEventPush(payload: Record<string, unknown>): void {+ applyMakerEventPush(payload: Record<string, unknown>, deviceId?: string): void {const sessionId = readString(payload, 'sessionId');const event = isRecord(payload.event) ? payload.event : null;const persistId = readString(payload, 'persistId') ?? undefined;- if (sessionId && event) this.applyMakerEvent(sessionId, event, persistId);+ if (sessionId && event) this.applyMakerEvent(sessionId, event, persistId, deviceId);},applyRemotePush(deviceId: string, channel: string, payload: unknown): void {@@ -2724,7 +3639,7 @@ export const remoteSessionStore = {return;}if (channel === 'maker:event' && isRecord(payload)) {- this.applyMakerEventPush(payload);+ this.applyMakerEventPush(payload, deviceId);return;}// 微批帧:被控端把同一会话的连续 maker:event 合并成一帧(能力协商见@@ -2736,7 +3651,7 @@ export const remoteSessionStore = {// 同一份,见 expandMakerEventBatchPayload 注释)。for (const event of expandMakerEventBatchPayload(payload)) {if (!isRecord(event)) continue;- this.applyMakerEventPush(event);+ this.applyMakerEventPush(event, deviceId);}return;}@@ -2941,7 +3856,12 @@ export const remoteSessionStore = {if (changed) emit();},- applyMakerEvent(sessionId: string, event: Record<string, unknown>, persistId?: string): void {+ applyMakerEvent(+ sessionId: string,+ event: Record<string, unknown>,+ persistId?: string,+ deviceId?: string,+ ): void {markSessionMakerActivity(sessionId);const type = readString(event, 'type');const reconnectCleared = type !== null && type !== 'error' && type !== 'done'@@ -2954,11 +3874,11 @@ export const remoteSessionStore = {return;}if (isRemoteTextDeltaEvent(event)) {- if (enqueueRemoteTextDelta(sessionId, event, persistId) || reconnectCleared) emit();+ if (enqueueRemoteTextDelta(sessionId, event, persistId, deviceId) || reconnectCleared) emit();return;}let changed = flushPendingTextDelta(sessionId);- changed = applyRemoteTextEvent(sessionId, event, persistId) || changed;+ changed = applyRemoteTextEvent(sessionId, event, persistId, deviceId) || changed;changed = reconnectCleared || changed;if (changed) emit();return;@@ -3126,7 +4046,7 @@ export const remoteSessionStore = {// Background compact belongs to the previous idle cycle. Finalizing here// would seal a product turn that started after compaction_start.if (!backgroundCompact) {- streamingAssistantClientIds.delete(sessionId);+ clearStreamingAssistantPointer(sessionId);}const nextMessages = backgroundCompact? existing@@ -3256,6 +4176,16 @@ export const remoteSessionStore = {*/markDeviceOffline(deviceId: string): void {let changed = false;+ // A first text delta can still be waiting in the 32ms batch before any session+ // metadata/index exists. Flush batches from this transport first so they create a+ // device-owned host anchor, then freeze that identity before reconnect metadata can+ // bind it to a newer send round.+ for (const [sessionId, batch] of [...pendingTextDeltaBatches]) {+ if (batch.deviceId !== deviceId) continue;+ changed = flushAndFinalizeRemoteStreamingMessages(sessionId) || changed;+ changed = clearStreamingAssistantPointer(sessionId) || changed;+ changed = freezeUnboundPendingHostAnchorsForOffline(sessionId, deviceId) || changed;+ }for (const [sessionId, indexedDeviceId] of sessionDeviceIndex) {if (indexedDeviceId !== deviceId) continue;changed = sessionMessageSyncMarkers.delete(sessionId) || changed;@@ -3272,11 +4202,20 @@ export const remoteSessionStore = {changed = sessionParkedTaskUpdates.delete(sessionId) || changed;changed = sessionMakerActivityEpochs.delete(sessionId) || changed;changed = flushAndFinalizeRemoteStreamingMessages(sessionId) || changed;- changed = streamingAssistantClientIds.delete(sessionId) || changed;- changed = pendingLiveAssistantClientIds.delete(sessionId) || changed;+ changed = clearStreamingAssistantPointer(sessionId) || changed;+ // The message window survives a soft offline transition, so both pending+ // identities must survive too: one protects the live row during latest-window+ // reconciliation, and the other lets a reconnecting authoritative user row+ // restore question → reply order. Persisted reconciliation, explicit window+ // invalidation, or actual device removal will retire them.+ changed = freezeUnboundPendingHostAnchorsForOffline(sessionId, deviceId) || changed;changed = writeMakerTurnRunning(sessionId, false) || changed;changed = writeSessionRunStatus(sessionId, EMPTY_SESSION_RUN_STATUS) || changed;}+ for (const [sessionId, pendingAnchors] of pendingHostAnchorLiveAssistantClientIds) {+ if (![...pendingAnchors.values()].some((identity) => identity.deviceIds.has(deviceId))) continue;+ changed = freezeUnboundPendingHostAnchorsForOffline(sessionId, deviceId) || changed;+ }if (changed) emit();},@@ -3284,47 +4223,68 @@ export const remoteSessionStore = {const hadShard = shards.delete(deviceId);const hadWorktreePreference = newMakerWorktreePreferences.delete(deviceId);const hadWorktreeBranchPreferences = newMakerWorktreeBranchPreferences.delete(deviceId);- // Sweep per-session maps for this device regardless of whether the shard still exists, and- // drop the index entries too — otherwise sessionDeviceIndex (and any maps it points at)- // leak orphans when the shard was already pruned.- let removedSession = false;+ // A maker event may precede the session list, so transport-owned batches, host anchors,+ // and streaming identities are also authoritative ownership evidence. Sweep their sessions+ // even when no shard or sessionDeviceIndex entry exists yet; otherwise the 32ms timer can+ // recreate messages after hard removal, or an already-flushed live row can survive.+ const indexedDeviceSessionIds = new Set<string>();+ const transportOwnedSessionIds = new Set<string>();for (const [sessionId, indexedDeviceId] of sessionDeviceIndex) {- if (indexedDeviceId === deviceId) {- messages.delete(sessionId);- livePlanSnapshots.delete(sessionId);- pendingInteractions.delete(sessionId);- pendingInteractionsAuthoritative.delete(sessionId);- inputProjections.delete(sessionId);- bumpInputProjectionAuthorityEpoch(sessionId);- sessionLiveActivity.delete(sessionId);- sessionRunning.delete(sessionId);- sessionRunStatus.delete(sessionId);- sessionMakerActivityEpochs.delete(sessionId);- sessionMessageSyncMarkers.delete(sessionId);- // 连续性结论随窗口一起失效:rewind 可能删掉中间的行,清空/回收更是整窗重来。- // 重置为未知,下一次最新窗口同步会重建(见 sessionWindowCoverage)。- forgetWindowCoverage(sessionId);- // 会话镜像整体回收:它的 `session:<id>` 订阅也随之消失,ACK 记录不能留着给后面的页背书。- sessionLiveStreamAcked.delete(sessionId);- sessionTaskUpdates.delete(sessionId);- streamingAssistantClientIds.delete(sessionId);- discardPendingTextDelta(sessionId);- pendingLiveAssistantClientIds.delete(sessionId);- sessionMakerTurnRunning.delete(sessionId);- sessionParkedTaskUpdates.delete(sessionId);- sessionMessageLifecycle.forget(sessionId);- sessionLastAccessOrder.delete(sessionId);+ if (indexedDeviceId === deviceId) indexedDeviceSessionIds.add(sessionId);+ }+ for (const [sessionId, batch] of pendingTextDeltaBatches) {+ if (batch.deviceId === deviceId) transportOwnedSessionIds.add(sessionId);+ }+ for (const [sessionId, pendingAnchors] of pendingHostAnchorLiveAssistantClientIds) {+ if ([...pendingAnchors.values()].some((identity) => identity.deviceIds.has(deviceId))) {+ transportOwnedSessionIds.add(sessionId);+ }+ }+ for (const [sessionId, streamingDeviceIds] of streamingAssistantDeviceIds) {+ if ([...streamingDeviceIds.values()].some((ownerDeviceId) => ownerDeviceId === deviceId)) {+ transportOwnedSessionIds.add(sessionId);+ }+ }+ let removedTransportState = false;+ for (const sessionId of indexedDeviceSessionIds) {+ // Keep the authority reset explicit in this hard-remove boundary: consumers must+ // never interpret the now-empty interaction list as an authoritative snapshot.+ pendingInteractionsAuthoritative.delete(sessionId);+ if (hasTransportOwnedSessionStateFromOtherDevice(sessionId, deviceId)) {+ // The stale shard may still own sessionDeviceIndex while a re-linked transport has+ // already started streaming before its own session list arrives. Preserve that+ // replacement batch/row and remove only state owned by the stale transport.sessionDeviceIndex.delete(sessionId);- dropPendingTitlePreview(sessionId);- // revision 下限按会话回收:它不参与单轮快照回收(那会把覆盖权还给晚到的- // 旧快照),所以只能在会话本身消失时清,保持有界。- const sessionPrefix = interactionResolveKey(sessionId, '');- for (const key of interactionRevisionFloors.keys()) {- if (key.startsWith(sessionPrefix)) interactionRevisionFloors.delete(key);- }- removedSession = true;+ removedTransportState = discardTransportOwnedPendingSessionState(+ sessionId,+ deviceId,+ ) || removedTransportState;+ continue;+ }+ removeSessionRuntimeState(sessionId);+ }+ for (const sessionId of transportOwnedSessionIds) {+ if (indexedDeviceSessionIds.has(sessionId)) continue;+ // A re-linked current shard may already own the same session id. In that case+ // remove only the stale transport's provisional rows/batch and keep the current+ // device's authoritative window and runtime projections intact. The same precise+ // cleanup also preserves a second pre-metadata transport when no shard exists yet.+ removedTransportState = discardTransportOwnedPendingSessionState(+ sessionId,+ deviceId,+ ) || removedTransportState;+ if (+ !sessionDeviceIndex.has(sessionId)+ && !pendingTextDeltaBatches.has(sessionId)+ && !pendingHostAnchorLiveAssistantClientIds.has(sessionId)+ && !streamingAssistantDeviceIds.has(sessionId)+ ) {+ pendingInteractionsAuthoritative.delete(sessionId);+ removeSessionRuntimeState(sessionId);+ removedTransportState = true;}}+ const removedSession = indexedDeviceSessionIds.size > 0 || removedTransportState;if (!hadShard&& !removedSession@@ -3361,7 +4321,11 @@ export const remoteSessionStore = {sessionLiveStreamAcked.clear();sessionTaskUpdates.clear();streamingAssistantClientIds.clear();+ streamingAssistantDeviceIds.clear();pendingLiveAssistantClientIds.clear();+ pendingHostAnchorLiveAssistantClientIds.clear();+ activePendingHostAnchorRoundIds.clear();+ nextPendingHostAnchorRoundId = 0;pendingTextDeltaBatches.clear();clearTextDeltaFlushTimer();sessionMakerTurnRunning.clear();@@ -3710,6 +4674,7 @@ function clearLiveGenerationOnWideRunStart(function writeMakerTurnRunning(sessionId: string, running: boolean): boolean {const prev = sessionMakerTurnRunning.get(sessionId) === true;+ if (!running) activePendingHostAnchorRoundIds.delete(sessionId);if (running === prev) return false;if (running) sessionMakerTurnRunning.set(sessionId, true);else {