Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(sync): 修复手机弱网同步恢复、运行中历史加载与正文缺失 (#3994)
DavidShenXDd36a78ddc583
diff --git a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.tsindex 3379da312f..e6f05cc178 100644--- a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts+++ b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts@@ -82,6 +82,7 @@ import {onToolResultFullEvent,prepareSyntheticToolEventForBroadcast,onAssistantTextEvent,+ getSessionTextSnapshot,onInteractionMessage,onInteractionResolved,onThinkingEvent,@@ -1750,6 +1751,25 @@ describe('thinking persistence', () => {});describe('event timestamp persistence', () => {+ it('reads current text with its stable identity without persisting or sealing it', async () => {+ const persistId = onAssistantTextEvent(SESSION, { text: 'prefix', isFinal: false }, null);+ const snapshot = getSessionTextSnapshot(SESSION);+ expect(Number.isFinite(Date.parse(snapshot!.event.data.createdAt))).toBe(true);+ onAssistantTextEvent(SESSION, { text: ' suffix', isFinal: false }, null);+ expect(snapshot?.event.data.text).toBe('prefix');+ expect(getSessionTextSnapshot(SESSION)).toMatchObject({+ persistId, event: { data: { text: 'prefix suffix', isFullText: true, isFinal: false } },+ });+ await flushWrites();+ expect(createMessage).not.toHaveBeenCalled();+ flushAssistantBlock(SESSION);+ expect(getSessionTextSnapshot(SESSION)).toBeNull();+ await flushWrites();+ expect(createMessage).toHaveBeenCalledWith(SESSION,+ expect.objectContaining({+ clientId: persistId, content: 'prefix suffix', createdAt: Date.parse(snapshot!.event.data.createdAt),+ }), broadcastGuard());+ });it('uses the first assistant delta timestamp when the block is flushed later', async () => {const startedAt = Date.parse('2026-06-20T10:00:00.000Z');const delayedWriteTime = Date.parse('2026-06-20T10:00:05.000Z');diff --git a/apps/desktop/src/main/device-link/__tests__/dispatchMakerEventBatch.test.ts b/apps/desktop/src/main/device-link/__tests__/dispatchMakerEventBatch.test.tsindex b1c948df72..c58c0d1727 100644--- a/apps/desktop/src/main/device-link/__tests__/dispatchMakerEventBatch.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/dispatchMakerEventBatch.test.ts@@ -13,6 +13,8 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import {DeviceLinkError,CONTROLLER_CAPABILITY_MAKER_EVENT_BATCH_V1,+ CONTROLLER_CAPABILITY_SESSION_TEXT_SNAPSHOT_V1,+ SESSION_SYNC_CHANNEL,DL_SUBSCRIBE_CHANNEL,DL_UNSUBSCRIBE_CHANNEL,MAKER_EVENT_BATCH_CHANNEL,@@ -61,6 +63,7 @@ import {__testing,flushMakerEventBatchesOnReconnect,handleControllerOffline,+ setSessionTextSnapshotReader,} from '../dispatch';import * as subscriptions from '../subscriptions';@@ -634,6 +637,151 @@ describe('[9] 字节估算按 UTF-8(review 首轮)', () => {});});+describe('running session recovery on slow links', () => {+ const capabilities = [CONTROLLER_CAPABILITY_MAKER_EVENT_BATCH_V1, CONTROLLER_CAPABILITY_SESSION_TEXT_SNAPSHOT_V1];+ const delta = (text: string, persistId = 'p1') => ({+ sessionId: 's1', persistId,+ event: { type: 'text', source: 'codex', data: { text, isFinal: false } },+ });+ const snapshot = { ...delta('whole prefix'), event: {+ type: 'text', data: { text: 'whole prefix', isFinal: false, isFullText: true },+ } };++ it('replays only the requested current block after old deltas and before new deltas', () => {+ const h = mkClient();+ __testing.setActiveClient(h.client as never);+ setSessionTextSnapshotReader((sid) => sid === 's1' ? snapshot : null);+ subscriptions.subscribe('phone', ['session:s1'], 'phone', capabilities);+ subscribeBatchController('old', ['session:s1']);+ __testing.forwardPush('maker:event', delta('old suffix'));+ const result = __testing.handleSubscriptionFrame('phone', {+ channel: DL_SUBSCRIBE_CHANNEL, args: [{ topics: ['session:s1'], capabilities }],+ });+ expect(result.ok).toBe(true);+ __testing.forwardPush('maker:event', delta('new suffix'));+ vi.advanceTimersByTime(WINDOW_MS);+ const phone = h.sent.filter(p => p.dst === 'phone');+ expect(phone.map(p => p.channel)).toEqual([MAKER_EVENT_BATCH_CHANNEL, SESSION_SYNC_CHANNEL, MAKER_EVENT_BATCH_CHANNEL]);+ expect(phone[1].payload).toEqual(snapshot);+ expect(h.sent.filter(p => p.dst === 'old').every(p => p.channel === MAKER_EVENT_BATCH_CHANNEL)).toBe(true);+ });++ it('fails subscription when the snapshot cannot enter the reliable window', () => {+ const h = mkClient({ sendPush: vi.fn(() => { throw new DeviceLinkError('BACKPRESSURE', 'full'); }) });+ __testing.setActiveClient(h.client as never);+ setSessionTextSnapshotReader(() => snapshot);+ expect(__testing.handleSubscriptionFrame('phone', {+ channel: DL_SUBSCRIBE_CHANNEL, args: [{ topics: ['session:s1'], capabilities }],+ })).toMatchObject({ ok: false, error: { code: 'BACKPRESSURE' } });+ });++ it('coalesces only adjacent same-identity deltas without crossing a tool or final boundary', () => {+ const h = mkClient();+ __testing.setActiveClient(h.client as never);+ subscribeBatchController('phone', ['session:s1']);+ for (const p of [delta('a'), delta('b'), delta('c', 'p2'),+ { sessionId: 's1', event: { type: 'tool_use', data: { toolUseId: 't1' } } }, delta('d')]) {+ __testing.forwardPush('maker:event', p);+ }+ vi.advanceTimersByTime(WINDOW_MS);+ expect(batchesIn(h.sent)[0].events).toEqual([+ delta('ab'), delta('c', 'p2'),+ { sessionId: 's1', event: { type: 'tool_use', data: { toolUseId: 't1' } } }, delta('d'),+ ]);+ });++ it('bounds one congested peer, repairs its dropped final row, and leaves a healthy peer flowing', () => {+ const h = mkClient();+ let congested = true;+ h.client.getReliableSendQueueDepth = vi.fn((dst: string) => dst === 'slow' && congested ? 16 : 0) as never;+ __testing.setActiveClient(h.client as never);+ for (const dst of ['slow', 'healthy']) subscriptions.subscribe(dst, ['session:s1'], dst, capabilities);+ setSessionTextSnapshotReader(() => snapshot);+ for (let i = 0; i < 10; i++) {+ __testing.forwardPush('maker:event', delta(`part-${i}`));+ vi.advanceTimersByTime(WINDOW_MS);+ }+ expect(h.sent.filter(p => p.dst === 'slow')).toHaveLength(0);+ expect(h.sent.filter(p => p.dst === 'healthy')).toHaveLength(10);+ // A durable final row can fail admission too; it must leave a repair signal.+ h.sendPush.mockImplementationOnce(() => { throw new DeviceLinkError('BACKPRESSURE', 'full'); });+ __testing.forwardPush('local-db:messages:created', { sessionId: 's1', message: { id: 'final' } });+ setSessionTextSnapshotReader(() => null);+ congested = false;+ vi.advanceTimersByTime(2_000);+ expect(h.sent.filter(p => p.dst === 'slow')).toEqual([+ { dst: 'slow', channel: SESSION_SYNC_CHANNEL, payload: { sessionId: 's1', resyncRequired: true }, ownerStamp: undefined },+ ]);+ expect(h.sent.filter(p => p.dst === 'healthy' && p.channel === SESSION_SYNC_CHANNEL)).toHaveLength(0);+ });++ it('does not deliver a pending repair after the session is unsubscribed', () => {+ const h = mkClient();+ h.client.getReliableSendQueueDepth.mockReturnValue(16);+ __testing.setActiveClient(h.client as never);+ subscriptions.subscribe('phone', ['session:s1'], 'phone', capabilities);+ __testing.forwardPush('maker:event', delta('text'));+ vi.advanceTimersByTime(WINDOW_MS);+ __testing.handleSubscriptionFrame('phone', { channel: DL_UNSUBSCRIBE_CHANNEL, args: [{ topics: ['session:s1'] }] });+ h.client.getReliableSendQueueDepth.mockReturnValue(0);+ vi.advanceTimersByTime(4_000);+ expect(h.sent).toHaveLength(0);+ });++ it('repairs text-only loss without repeatedly requesting a large unchanged history page', () => {+ const h = mkClient();+ h.client.getReliableSendQueueDepth.mockReturnValue(16);+ __testing.setActiveClient(h.client as never);+ subscriptions.subscribe('phone', ['session:s1'], 'phone', capabilities);+ setSessionTextSnapshotReader(() => snapshot);+ __testing.forwardPush('maker:event', delta('missed'));+ vi.advanceTimersByTime(WINDOW_MS);+ h.client.getReliableSendQueueDepth.mockReturnValue(0);+ vi.advanceTimersByTime(2_000);+ expect(h.sent).toEqual([+ { dst: 'phone', channel: SESSION_SYNC_CHANNEL, payload: { ...snapshot, resyncRequired: false }, ownerStamp: undefined },+ ]);+ });++ it('holds later deltas after the window drains until the missing prefix is repaired', () => {+ const h = mkClient();+ h.client.getReliableSendQueueDepth.mockReturnValue(16);+ __testing.setActiveClient(h.client as never);+ subscriptions.subscribe('phone', ['session:s1'], 'phone', capabilities);+ setSessionTextSnapshotReader(() => snapshot);+ __testing.forwardPush('maker:event', delta('missed prefix'));+ vi.advanceTimersByTime(WINDOW_MS);+ h.client.getReliableSendQueueDepth.mockReturnValue(0);+ __testing.forwardPush('maker:event', delta('later suffix'));+ vi.advanceTimersByTime(WINDOW_MS);+ __testing.forwardPush('maker:event', delta('x'.repeat(300_000)));+ expect(h.sent).toHaveLength(0);+ vi.advanceTimersByTime(2_000);+ expect(h.sent.map(p => p.channel)).toEqual([SESSION_SYNC_CHANNEL]);+ expect(h.sent[0].payload).toEqual({ ...snapshot, resyncRequired: false });+ __testing.forwardPush('maker:event', delta('after snapshot'));+ vi.advanceTimersByTime(WINDOW_MS);+ expect(h.sent.map(p => p.channel)).toEqual([SESSION_SYNC_CHANNEL, MAKER_EVENT_BATCH_CHANNEL]);+ expect(batchesIn(h.sent)[0].events).toEqual([delta('after snapshot')]);+ });++ it('repairs an oversized event when its compact retry also fails admission', () => {+ const h = mkClient();+ __testing.setActiveClient(h.client as never);+ subscriptions.subscribe('phone', ['session:s1'], 'phone', capabilities);+ setSessionTextSnapshotReader(() => snapshot);+ h.sendPush.mockImplementationOnce(() => { throw new DeviceLinkError('PAYLOAD_TOO_LARGE', 'large'); });+ h.sendPush.mockImplementationOnce(() => { throw new DeviceLinkError('BACKPRESSURE', 'full'); });+ __testing.forwardPush('maker:event', {+ sessionId: 's1', event: { type: 'tool_result', data: { text: 'x'.repeat(300_000) } },+ });+ vi.advanceTimersByTime(2_000);+ expect(h.sent).toEqual([+ { dst: 'phone', channel: SESSION_SYNC_CHANNEL, payload: { ...snapshot, resyncRequired: true }, ownerStamp: undefined },+ ]);+ });+});+describe('[6] 帧数削减度量', () => {it('长思考洪峰:100 条事件从 100 帧压到 2 帧(条数上限 + 窗口各一次)', () => {const h = mkClient();diff --git a/apps/desktop/src/main/device-link/__tests__/providerListProjection.test.ts b/apps/desktop/src/main/device-link/__tests__/providerListProjection.test.tsindex bbe5885ad9..606b7a915f 100644--- a/apps/desktop/src/main/device-link/__tests__/providerListProjection.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/providerListProjection.test.ts@@ -310,3 +310,30 @@ describe('projectInvokeResultForTunnel — maker:provider:list 投影', () => {expect(__testing.projectInvokeResultForTunnel('maker:provider:list', weird)).toBe(weird);});});+++describe('active runtime summary projection', () => {+ const rows = [true, false].map((isTurnRunning, i) => ({+ sessionId: `session-${i}`, isTurnRunning, agentKind: 'codex', workDir: '/work',+ capabilities: { availableModels: [{ id: 'model', description: 'x'.repeat(120_000) }] },+ }));++ it('omits repeated model catalogs only for an explicit summary request', () => {+ const projected = __testing.projectInvokeResultForTunnel(+ 'maker:list-active', rows, false, [{ summary: true }],+ );+ expect(projected).toEqual([+ { sessionId: 'session-0', isTurnRunning: true },+ { sessionId: 'session-1', isTurnRunning: false },+ ]);+ expect(JSON.stringify(projected).length).toBeLessThan(150);+ expect(rows[0].capabilities.availableModels[0].description).toHaveLength(120_000);+ });++ it.each([[], [null], [{ summary: false }], [{ summary: 'true' }]])(+ 'preserves the complete response for legacy or non-opt-in callers (%j)', (...args) => {+ expect(__testing.projectInvokeResultForTunnel('maker:list-active', rows, false, args))+ .toBe(rows);+ },+ );+});diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.tsindex a3d0cd6e71..bd975c1f25 100644--- a/apps/desktop/src/main/device-link/dispatch.ts+++ b/apps/desktop/src/main/device-link/dispatch.ts@@ -38,8 +38,10 @@ import {DL_TELEGRAM_STATUS_CHANNEL,DL_TELEGRAM_SET_ONLINE_CHANNEL,SESSION_ACTIVITY_CHANNEL,+ SESSION_SYNC_CHANNEL,MAKER_EVENT_BATCH_CHANNEL,CONTROLLER_CAPABILITY_MAKER_EVENT_BATCH_V1,+ CONTROLLER_CAPABILITY_SESSION_TEXT_SNAPSHOT_V1,byteLength,DeviceLinkError,parseFsWatchTopic,@@ -411,7 +413,20 @@ function projectInvokeResultForTunnel(channel: string,result: unknown,supportsFullLogoKinds = false,+ args: readonly unknown[] = [],): unknown {+ // Opt-in only: legacy/desktop controllers still receive complete runtime capabilities.+ // Home only needs run state; repeating the model catalog per runtime blocks slow links.+ const options = args[0];+ if (channel === 'maker:list-active' && options && typeof options === 'object'+ && !Array.isArray(options) && 'summary' in options && options.summary === true+ && Array.isArray(result)) {+ return result.map((item: unknown) => {+ if (!item || typeof item !== 'object' || Array.isArray(item)) return item;+ const row = item as Record<string, unknown>;+ return { sessionId: row.sessionId, isTurnRunning: row.isTurnRunning };+ });+ }if (channel !== 'maker:provider:list') return result;const r = result as { providers?: unknown; modelVisibilityOverrides?: unknown };if (!Array.isArray(r.providers)) return result;@@ -617,6 +632,11 @@ const reportedControllerNameByDevice = new Map<string, string>();/** `sessions` 订阅出现时通知 host replay 当前列表级轻量状态。 */type SessionsSubscribedListener = (controllerDeviceId: string) => void;let onSessionsSubscribed: SessionsSubscribedListener | null = null;+let readSessionTextSnapshot: ((sessionId: string) => unknown | null) | null = null;++export function setSessionTextSnapshotReader(reader: typeof readSessionTextSnapshot): void {+ readSessionTextSnapshot = reader;+}export function setControllersChangedListener(cb: ControllersChangedListener | null): void {onControllersChanged = cb;@@ -865,6 +885,76 @@ interface MakerEventBatchStage {const makerEventBatchStages = new Map<string, MakerEventBatchStage>();+// Bound live traffic before it enters the shared socket FIFO. Only opt-in+// controllers can repair skipped deltas from the authoritative in-flight block.+const MAKER_EVENT_WINDOW_SOFT_CAP = 16;+function isNonFinalTextPush(payload: unknown): boolean {+ const event = (payload as { event?: { type?: unknown; data?: { isFinal?: unknown } } } | null)?.event;+ return event?.type === 'text' && event.data?.isFinal === false;+}++const sessionSyncStages = new Map<string, {+ sessions: Map<string, boolean>;+ timer: ReturnType<typeof setTimeout> | null;+ ownerStamp?: PushOwnerStamp;+}>();++function clearSessionSyncStage(dst: string): void {+ const stage = sessionSyncStages.get(dst);+ if (stage?.timer) clearTimeout(stage.timer);+ sessionSyncStages.delete(dst);+}++function stageSessionSync(dst: string, sessionId: string, historyRequired = true): void {+ if (!subscriptions.controllerSupports(dst, CONTROLLER_CAPABILITY_SESSION_TEXT_SNAPSHOT_V1)) return;+ let stage = sessionSyncStages.get(dst);+ if (!stage) {+ stage = { sessions: new Map(), timer: null, ownerStamp: broadcastTap.getSafeDataOwnerPushStamp?.() };+ sessionSyncStages.set(dst, stage);+ }+ stage.sessions.set(sessionId, historyRequired || stage.sessions.get(sessionId) === true);+ if (stage.sessions.size > SESSION_ACTIVITY_STAGE_MAX_KEYS) {+ stage.sessions.delete(stage.sessions.keys().next().value!);+ }+ if (stage.timer) return;+ stage.timer = setTimeout(() => {+ stage.timer = null;+ if (!activeClient || activeClient.getStatus() !== 'online'+ || !makerEventBatchOwnerStampEquals(stage.ownerStamp, broadcastTap.getSafeDataOwnerPushStamp?.())) {+ clearSessionSyncStage(dst);+ return;+ }+ for (const sid of stage.sessions.keys()) {+ if (!subscriptions.controllerHasTopic(dst, `session:${sid}`)) {+ stage.sessions.delete(sid);+ continue;+ }+ if ((activeClient.getReliableSendQueueDepth?.(dst) ?? 0) >= MAKER_EVENT_WINDOW_SOFT_CAP) break;+ // Flush older staged deltas before the snapshot. No await may split this+ // boundary: newer deltas must be sequenced after the full-text replacement.+ flushMakerEventBatchesForSession(dst, sid);+ try {+ const snapshot = readSessionTextSnapshot?.(sid);+ activeClient.sendPush(dst, SESSION_SYNC_CHANNEL, {+ ...(snapshot && typeof snapshot === 'object' ? snapshot : {}),+ sessionId: sid,+ // Text-only loss is repaired by this snapshot. Re-reading the same+ // large DB page on every dropped delta would recreate the congestion.+ // Once the block is sealed, history becomes the recovery authority.+ resyncRequired: stage.sessions.get(sid) === true || !snapshot,+ }, broadcastTap.getSafeDataOwnerPushStamp?.());+ stage.sessions.delete(sid);+ } catch {+ break;+ }+ }+ const next = stage.sessions.entries().next().value;+ if (next) stageSessionSync(dst, next[0], next[1]);+ else clearSessionSyncStage(dst);+ }, 2_000);+ (stage.timer as unknown as { unref?: () => void }).unref?.();+}+function makerEventBatchOwnerStampEquals(a: PushOwnerStamp | undefined,b: PushOwnerStamp | undefined,@@ -874,6 +964,33 @@ function makerEventBatchOwnerStampEquals(return a.dataOwnerId === b.dataOwnerId && a.ownerGeneration === b.ownerGeneration;}+/** Merge only adjacent deltas whose complete non-text payload is identical. */+function coalesceMakerTextDelta(previous: unknown, incoming: unknown): unknown | null {+ const read = (value: unknown) => {+ if (!value || typeof value !== 'object') return null;+ const p = value as Record<string, unknown>;+ if (typeof p.persistId !== 'string' || !p.persistId) return null;+ const event = p.event as Record<string, unknown> | undefined;+ const data = event?.data as Record<string, unknown> | undefined;+ if (event?.type !== 'text' || data?.isFinal !== false || data.isFullText === true+ || typeof data.text !== 'string') return null;+ return { p, event, data, text: data.text };+ };+ const a = read(previous);+ const b = read(incoming);+ if (!a || !b) return null;+ const signature = (item: typeof a) => JSON.stringify({+ ...item.p, event: { ...item.event, data: { ...item.data, text: '' } },+ });+ try {+ if (signature(a) !== signature(b)) return null;+ } catch {+ // Serialization failures remain isolated by the existing send boundary.+ return null;+ }+ return { ...b.p, event: { ...b.event, data: { ...b.data, text: a.text + b.text } } };+}+/*** 把一条 maker:event 收进目标控制端的批。到量(条数/字节)立即 flush,否则等* 窗口定时器统一 flush。@@ -915,8 +1032,15 @@ function stageMakerEventPush(tail = { events: [], bytes: 0, ...(ownerStamp ? { ownerStamp } : {}) };segments.push(tail);}- tail.events.push(payload);- tail.bytes += payloadBytes;+ const previous = tail.events.at(-1);+ const coalesced = coalesceMakerTextDelta(previous, payload);+ if (coalesced) {+ tail.events[tail.events.length - 1] = coalesced;+ tail.bytes += estimateMakerEventBytes(coalesced) - estimateMakerEventBytes(previous);+ } else {+ tail.events.push(payload);+ tail.bytes += payloadBytes;+ }if (tail.events.length >= MAKER_EVENT_BATCH_MAX_EVENTS|| tail.bytes >= MAKER_EVENT_BATCH_MAX_BYTES@@ -1107,16 +1231,28 @@ function flushMakerEventBatchSession(continue;}const payload: MakerEventBatchPayload = { sessionId, events: slice };+ const historyRequired = !slice.every(isNonFinalTextPush);try {if (!activeClient || activeClient.getStatus() !== 'online') {throw new DeviceLinkError('NOT_CONNECTED', 'relay offline');}+ if (+ subscriptions.controllerSupports(dst, CONTROLLER_CAPABILITY_SESSION_TEXT_SNAPSHOT_V1)+ && (sessionSyncStages.get(dst)?.sessions.has(sessionId)+ || (activeClient.getReliableSendQueueDepth?.(dst) ?? 0) >= MAKER_EVENT_WINDOW_SOFT_CAP)+ ) {+ // Once any part is skipped, subsequent deltas no longer have a valid+ // prefix at the receiver. Resume only after the full snapshot is queued.+ stageSessionSync(dst, sessionId, historyRequired);+ continue;+ }if (segment.ownerStamp === undefined) {activeClient.sendPush(dst, MAKER_EVENT_BATCH_CHANNEL, payload);} else {activeClient.sendPush(dst, MAKER_EVENT_BATCH_CHANNEL, payload, segment.ownerStamp);}} catch (err) {+ stageSessionSync(dst, sessionId, historyRequired);// 发不出去就丢这一片(不降级、不重试、不滞留):理由与四轮 review 的推导见// MakerEventBatchFlushOutcome 注释。relay 离线时后续切片连尝试都省掉。if (err instanceof DeviceLinkError && err.code === 'NOT_CONNECTED') {@@ -1443,18 +1579,36 @@ function sendPushBestEffort(ownerStamp?: PushOwnerStamp,): void {if (!activeClient) return;+ const sessionId = readPushSessionId(payload);+ const markForRecovery = () => {+ if (sessionId && channel !== SESSION_SYNC_CHANNEL+ && topicForPush(channel, payload) === `session:${sessionId}`) {+ stageSessionSync(dst, sessionId, channel !== 'maker:event' || !isNonFinalTextPush(payload));+ }+ };+ // Oversized maker events and offline replay can bypass the batching path.+ // They must obey the same missing-prefix boundary as ordinary deltas.+ if (channel === 'maker:event' && sessionId+ && subscriptions.controllerSupports(dst, CONTROLLER_CAPABILITY_SESSION_TEXT_SNAPSHOT_V1)+ && (sessionSyncStages.get(dst)?.sessions.has(sessionId)+ || (activeClient.getReliableSendQueueDepth?.(dst) ?? 0) >= MAKER_EVENT_WINDOW_SOFT_CAP)) {+ markForRecovery();+ return;+ }try {if (ownerStamp === undefined) activeClient.sendPush(dst, channel, payload);else activeClient.sendPush(dst, channel, payload, ownerStamp);return;} catch (err) {if (!isPayloadTooLargeError(err)) {+ markForRecovery();log.warn(`forwardPush to ${shortId(dst)} failed (${channel}): ${String(err)}`);return;}const compactPayload = compactOversizedPushPayload(channel, payload);if (!compactPayload) {+ markForRecovery();log.warn(`forwardPush to ${shortId(dst)} failed (${channel}): ${String(err)}`);return;}@@ -1464,6 +1618,7 @@ function sendPushBestEffort(else activeClient.sendPush(dst, channel, compactPayload, ownerStamp);log.warn(`forwardPush to ${shortId(dst)} sent compact payload after oversized ${channel} frame`);} catch (retryErr) {+ markForRecovery();log.warn(`forwardPush to ${shortId(dst)} failed after compact retry (${channel}): ${String(retryErr)}`,);@@ -1632,6 +1787,7 @@ function deactivateControllerState(changed = subscriptions.getControllerIds().includes(deviceId) || changed;clearReportedControllerName(deviceId);clearSessionActivityStage(deviceId);+ clearSessionSyncStage(deviceId);clearMakerEventBatchStage(deviceId);cancelLinkAcceptRetry(deviceId);return subscriptions.clearController(deviceId) || changed;@@ -2833,6 +2989,7 @@ function handleSubscriptionFrame(src: string, payload: InvokePayload): InvokeResfor (const topic of topics) {const sessionId = topic.startsWith('session:') ? topic.slice('session:'.length) : null;if (sessionId) dropMakerEventBatch(src, sessionId);+ if (sessionId) sessionSyncStages.get(src)?.sessions.delete(sessionId);}}syncForwarding();@@ -2845,6 +3002,25 @@ function handleSubscriptionFrame(src: string, payload: InvokePayload): InvokeRes// 不先收口就会让新帧先于断线前的文本送达,重现「终态后冒出文本」。flushMakerEventBatchesFor(src);drainOfflinePushQueueTo(src, topics);+ if (subscriptions.controllerSupports(src, CONTROLLER_CAPABILITY_SESSION_TEXT_SNAPSHOT_V1)) {+ // Synchronous with subscription registration: old batches/backlog precede+ // this snapshot, and subsequent live deltas follow it on the same stream.+ // Admission failure must fail subscribe so its existing retry repairs it.+ for (const topic of topics) {+ if (!topic.startsWith('session:')) continue;+ const snapshot = readSessionTextSnapshot?.(topic.slice('session:'.length));+ if (snapshot) {+ try {+ activeClient?.sendPush(src, SESSION_SYNC_CHANNEL, snapshot, broadcastTap.getSafeDataOwnerPushStamp?.());+ } catch (error) {+ return { ok: false, error: {+ code: error instanceof DeviceLinkError ? error.code : 'INTERNAL',+ message: 'session text snapshot could not be queued',+ } };+ }+ }+ }+ }}return { ok: true, result: { ok: true } };}@@ -3043,6 +3219,7 @@ export async function runInvoke(CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2,)|| listingCapabilities.includes(CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2),+ args,),};} catch (err) {@@ -3136,9 +3313,11 @@ export const __testing = {controllerDisplayNameByDevice.clear();reportedControllerNameByDevice.clear();onSessionsSubscribed = null;+ readSessionTextSnapshot = null;activeClient = null;offlinePushQueue.clear();clearAllSessionActivityStages();+ for (const dst of sessionSyncStages.keys()) clearSessionSyncStage(dst);clearAllMakerEventBatchStages();cancelAllLinkAcceptRetries();revokedLinkOpenRejectAt.clear();diff --git a/apps/desktop/src/main/maker-host/__tests__/codexAuthIsolatedSandbox.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexAuthIsolatedSandbox.test.tsindex b99c45eb8e..0ebe401ca4 100644--- a/apps/desktop/src/main/maker-host/__tests__/codexAuthIsolatedSandbox.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codexAuthIsolatedSandbox.test.ts@@ -381,6 +381,7 @@ describe('dev 沙箱凭证隔离(XDT_ISOLATED_AUTH)', () => {tokens: { access_token: 'invalidated-release-token', account_id: 'acct-invalidated' },}),);+ const releaseBytes = fs.readFileSync(releaseAuth);bindReleaseOpenAi(releaseAuth);expect(writeInvalidatedSystemCodexAuthMarker(@@ -402,8 +403,12 @@ describe('dev 沙箱凭证隔离(XDT_ISOLATED_AUTH)', () => {oauthWritesBlocked: true,});await expect(adapter.getAccessToken()).resolves.toBe('system-token');- expect(fs.statSync(localAuth).ino).toBe(fs.statSync(systemAuth).ino);- expect(fs.statSync(localAuth).ino).not.toBe(fs.statSync(releaseAuth).ino);+ // Inode values are not stable across all supported filesystems. Verify the+ // isolation contract by comparing the selected credential bytes instead:+ // local auth must contain the system credential and remain distinct from+ // the invalidated Release credential.+ expect(fs.readFileSync(localAuth)).toEqual(fs.readFileSync(systemAuth));+ expect(fs.readFileSync(localAuth)).not.toEqual(releaseBytes);});it('dev 默认只读共享:登录和登出不可改,失效只阻断当前进程', async () => {diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 329accef49..cb5d756bcd 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -439,6 +439,7 @@ import {flushOrphanToolResults,getLastAssistantTranscriptUuid,getSessionDbAgentKind,+ getSessionTextSnapshot,markAssistantTurnFailed,noteSessionAgentKind,noteSessionClearBoundary,@@ -912,6 +913,7 @@ import { emitSessionCreated } from '../localDb/ipc/sessionCreatedBroadcast.js';import { setBusyProbe as setDeviceLinkBusyProbe } from '../device-link/index.js';import {markRemoteSettingPersistedInsideHandler,+ setSessionTextSnapshotReader,setRemoteReviewInputGuard as setDeviceLinkRemoteReviewInputGuard,setRemoteWorkingDirGuard as setDeviceLinkRemoteWorkingDirGuard,setRemoteSettingsPersist as setDeviceLinkRemoteSettingsPersist,@@ -4411,6 +4413,7 @@ export function registerModelVisibilitySyncIpc(): void {}export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions): void {+ setSessionTextSnapshotReader(getSessionTextSnapshot);log.info('registering maker:* IPC handlers');const broadcastSessionRuntimeProjection = async (sessionId: string,diff --git a/apps/desktop/src/main/messagePersistBroadcaster.ts b/apps/desktop/src/main/messagePersistBroadcaster.tsindex 84c856c1c4..68c3f192ce 100644--- a/apps/desktop/src/main/messagePersistBroadcaster.ts+++ b/apps/desktop/src/main/messagePersistBroadcaster.ts@@ -82,6 +82,24 @@ interface AssistantBlock {}const assistantBlocks = new Map<string, AssistantBlock>();++/** Read the in-flight block without flushing or changing its persistence identity. */+export function getSessionTextSnapshot(sessionId: string) {+ const block = assistantBlocks.get(sessionId);+ if (!block?.text) return null;+ return {+ sessionId,+ persistId: block.persistId,+ event: {+ type: 'text',+ data: {+ text: block.text, isFinal: false, isFullText: true,+ createdAt: new Date(block.createdAt).toISOString(),+ },+ agentMeta: block.agentMeta,+ },+ };+}interface SealedAssistantLateFinalCandidate {persistId: string;text: string;diff --git a/apps/mobile/app/devices/index.tsx b/apps/mobile/app/devices/index.tsxindex d483ef75e9..0fd729a0cf 100644--- a/apps/mobile/app/devices/index.tsx+++ b/apps/mobile/app/devices/index.tsx@@ -104,6 +104,7 @@ import {formatRemoteError,} from '@/device-link/remoteStatus';import { withTransientRemoteRetry } from '@/device-link/remoteRetry';+import { runIndependentSnapshotReads } from '@/device-link/sessionSnapshotSingleFlight';import { revokedDevicesStore, useRevokedDevices } from '@/device-link/revokedDevicesStore';import { useUnresponsiveDevices } from '@/device-link/unresponsiveDevicesStore';import {@@ -684,55 +685,45 @@ function HomeScreenContent() {}updateDeviceConnectionState(device.deviceId, 'syncing');try {- const [- list,- activeSessions,- activeSessionSnapshotEpoch,- sessionListMutationEpoch,- ] = await withTransientRemoteRetry(async () => {+ const assertCurrentScope = () => {if (homeAccountGenerationRef.current !== expectedAccountGeneration|| !isCurrentHomeSyncTarget(device.deviceId, expectedHomeSyncGeneration)- ) {- throw new HomeSyncScopeSupersededError();- }+ ) throw new HomeSyncScopeSupersededError();+ };+ await withTransientRemoteRetry(async () => {+ assertCurrentScope();homeListOwnedDeviceIdsRef.current.add(device.deviceId);await subscribe(HOME_LIST_SUBSCRIPTION_OWNER, device.deviceId, ['sessions']);- if (- homeAccountGenerationRef.current !== expectedAccountGeneration- || !isCurrentHomeSyncTarget(device.deviceId, expectedHomeSyncGeneration)- ) {- throw new HomeSyncScopeSupersededError();- }- // Capture inside the retry callback so every maker:list-active attempt gets its own- // fence. A newer retry push received while this request is in flight must survive- // the older snapshot, while progress predating this attempt can be cleared.- const activeSessionSnapshotEpoch = remoteSessionStore.captureActiveSessionSnapshotEpoch();- const sessionListMutationEpoch = remoteSessionStore.captureDeviceSessionListMutationEpoch(- device.deviceId,- );- const [list, activeSessions] = await Promise.all([- invoke<RemoteSession[]>(device.deviceId, 'local-db:sessions:list', [- LIST_LIMIT,- remoteListStatusFilter(statusFilter),- // hydrate / 重连是权威重拉,绕开被控端写前的同参数 in-flight list。- { includePinned: true, fresh: true },- ]),- // `sessions` topic replay covers list-level Agent Island activity, but the authoritative- // "turn currently running" snapshot is maker:list-active. Pull it with the list so Home- // does not need a session-detail round trip before showing running rows.- invoke<unknown[]>(device.deviceId, 'maker:list-active', []).catch((err) => {- if (isOptionalActiveSessionSnapshotError(err)) return null;- throw err;- }),- ]);- return [- list,- activeSessions,- activeSessionSnapshotEpoch,- sessionListMutationEpoch,- ] as const;+ assertCurrentScope();});+ // A slow activity snapshot must not replay an already successful whole list.+ // Each read captures its own authority fence again on every retry.+ const [[list, sessionListMutationEpoch], [activeSessions, activeSessionSnapshotEpoch]] =+ await runIndependentSnapshotReads([+ async () => {+ assertCurrentScope();+ const epoch = remoteSessionStore.captureDeviceSessionListMutationEpoch(device.deviceId);+ const list = await invoke<RemoteSession[]>(device.deviceId, 'local-db:sessions:list', [+ LIST_LIMIT,+ remoteListStatusFilter(statusFilter),+ { includePinned: true, fresh: true },+ ]);+ return [list, epoch] as const;+ },+ async () => {+ assertCurrentScope();+ const epoch = remoteSessionStore.captureActiveSessionSnapshotEpoch();+ // Old hosts ignore this optional projection and still return the full snapshot.+ const active = await invoke<unknown[]>(device.deviceId, 'maker:list-active', [+ { summary: true },+ ]).catch((err) => {+ if (isOptionalActiveSessionSnapshotError(err)) return null;+ throw err;+ });+ return [active, epoch] as const;+ },+ ] as const, withTransientRemoteRetry);if (homeAccountGenerationRef.current !== expectedAccountGeneration|| !isCurrentHomeSyncTarget(device.deviceId, expectedHomeSyncGeneration)diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex ebd27b5a49..9116c076f0 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -99,11 +99,13 @@ import {} from '@/device-link/remoteSyncTask';import {runConnectionScopedSessionMetadataRead,- readProgressiveMessageWindow,+ waitForIndependentSnapshotReads,runSessionMessagesSnapshotSingleFlight,runSessionPendingInteractionsSnapshotSingleFlight,runSessionProjectionSnapshotSingleFlight,} from '@/device-link/sessionSnapshotSingleFlight';+import { syncSessionMessageWindow } from '@/session/sessionMessageWindowSync';+import { shouldClearOperationErrorAfterSync, type SessionOperationError } from '@/session/sessionSyncErrorRecovery';import { createTransientTopicSubscriptionCoordinator } from '@/device-link/transientTopicSubscription';import { useMobileMakerTransport } from '@/device-link/useMobileMakerTransport';import { createMobileMakerTransport } from '@/device-link/mobileMakerTransport';@@ -464,7 +466,6 @@ import {oldestMessageCursor,projectLoadedMessageWindowIncrementally,type LoadedMessageWindowProjection,- shouldRefreshLatestMessageWindowOnReopen,shouldKeepOlderMessagesAffordance,} from '@/session/messagePaging';import {@@ -1641,7 +1642,32 @@ export default function SessionScreen() {const [extraDirBrowseEntries, setExtraDirBrowseEntries] = useState<RemoteDirectoryEntry[]>([]);const [extraDirBrowseLoading, setExtraDirBrowseLoading] = useState(false);const [extraDirBrowseError, setExtraDirBrowseError] = useState<string | null>(null);- const [error, setError] = useState<string | null>(null);+ const [operationError, setOperationError] = useState<SessionOperationError | null>(null);+ const operationErrorRef = useRef<SessionOperationError | null>(null);+ const setError = useCallback((message: string | null) => {+ const next = message === null ? null : { message };+ operationErrorRef.current = next;+ setOperationError(next);+ }, []);+ const error = operationError?.message ?? null;+ const [syncError, setSyncError] = useState<string | null>(null);+ const [historyError, setHistoryError] = useState<string | null>(null);+ const historyRequestSeqRef = useRef(0);+ const historyRequestInFlightRef = useRef<number | null>(null);+ const messageWindowReconciledRef = useRef(false);+ const errorScopeKey = JSON.stringify([deviceId, sessionId]);+ const [errorScope, setErrorScope] = useState(errorScopeKey);+ if (errorScope !== errorScopeKey) {+ setErrorScope(errorScopeKey);+ setError(null);+ setSyncError(null);+ setHistoryError(null);+ setLoadingEarlier(false);+ historyRequestSeqRef.current += 1;+ historyRequestInFlightRef.current = null;+ messageWindowReconciledRef.current = false;+ }+ useEffect(() => () => { historyRequestSeqRef.current += 1; }, []);// UI 错误可被任意操作清掉;transport hold 独立锁存所有连接恢复来源,直到当前// 设备完成一次权威同步。error 可空:纯 relay / presence 断线未必产生请求错误。const [outboxTransportHold, setOutboxTransportHold] = useState<{@@ -1918,7 +1944,7 @@ export default function SessionScreen() {// 用它——否则恢复后横幅消失了,composer 却仍被 stale 快照锁在不可用态,// 直到手动同步才解开。const connectionError = resolveEffectiveConnectionError(- isDeviceAccessRevoked ? '[ACCESS_REVOKED] access revoked by target device' : error,+ isDeviceAccessRevoked ? '[ACCESS_REVOKED] access revoked by target device' : syncError ?? error,isDeviceUnresponsive,);// dispatch / Stop 与恢复 edge 共用 Context 内随 connection epoch 重置的三态 verdict,@@ -1999,6 +2025,8 @@ export default function SessionScreen() {);// 弱网普通断线也要有可见信号(消息流静默停更没有任何提示),经防闪延迟后显示const connectionRecoveryError = activeOutboxTransportError ?? connectionError;+ const bannerError = connectionRecoveryError ?? historyError;+ const bannerRetriesHistory = connectionRecoveryError === null && historyError !== null;const contentRecoveryState = contentRecoveryKey !== null&& contentSyncedKey === contentRecoveryKey&& readAckSyncedKey === `${sessionId}:${connectionEpoch}`@@ -2011,7 +2039,7 @@ export default function SessionScreen() {}, [contentRecoveryState]);const showConnectionBanner = useShowConnectionBanner(status,- connectionRecoveryError,+ bannerError,connectionIssue,isDeviceUnresponsive,contentRecoveryState,@@ -3247,8 +3275,8 @@ export default function SessionScreen() {() => maker.getPendingInteractions(sessionId),);if (syncRun.isStale()) return;+ const operationErrorAtSyncStart = operationErrorRef.current;setLoading(true);- setError(null);try {await prepareLinkAndSubscription();if (syncRun.isStale() || !messageAuthorityCurrent()) return;@@ -3261,15 +3289,13 @@ export default function SessionScreen() {const isCurrent = () => !syncRun.isStale() && messageAuthorityCurrent();const pushRefresh = notificationResponse !== null&& syncedNotificationResponseRef.current !== notificationResponse;- const messageRead = readProgressiveMessageWindow({+ const messageRead = syncSessionMessageWindow({readMetadata: () => retryRead(fetchSessionMetadata),+ isReopen,+ storedSession: storedSessionAtStart,eager: !isReopen || pushRefresh,- shouldReadMessages: (sessionMeta) => shouldRefreshLatestMessageWindowOnReopen({- freshSession: sessionMeta,- messageWindowSynced: remoteSessionStore.isSessionMessageWindowSynced(sessionId, sessionMeta),- storedSession: storedSessionAtStart,- }),- readMessages: () => retryRead(() => listMessagesWithPayloadRetry(+ isWindowSynced: (sessionMeta) => remoteSessionStore.isSessionMessageWindowSynced(sessionId, sessionMeta),+ readLatest: () => retryRead(() => listMessagesWithPayloadRetry((limit) => runSessionMessagesSnapshotSingleFlight(snapshotScope,limit,@@ -3290,6 +3316,21 @@ export default function SessionScreen() {moreBeyondWindow,});}+ // Even failed metadata must not hide pagination for a successful page.+ messageWindowReconciledRef.current = true;+ setHasOlderMessages(moreBeyondWindow);+ },+ commit: (sessionMeta, history) => {+ if (history !== null) {+ remoteSessionStore.markSessionMessagesSynced(sessionId, sessionMeta);+ if (pushRefresh) syncedNotificationResponseRef.current = notificationResponse;+ }+ if (history === null) {+ messageWindowReconciledRef.current = true;+ setHasOlderMessages(hasOlderMessagesAfterReopen(+ sessionMeta._count?.messages, remoteSessionStore.getMessages(sessionId),+ ));+ }},});const commitRead = <T,>(read: () => Promise<T>, commit: (value: T) => void) =>@@ -3297,7 +3338,7 @@ export default function SessionScreen() {// Only the control/read-receipt barrier waits for all resources. Each response// is applied independently, and a changed metadata response starts history// immediately rather than waiting for pending/projection/active.- const [{ metadata: sessionMeta, history }] = await Promise.all([+ await waitForIndependentSnapshotReads([messageRead,commitRead(fetchPendingInteractions, (pendingInteractions) => {remoteSessionStore.setPendingInteractions(sessionId, Array.isArray(pendingInteractions) ? pendingInteractions : []);@@ -3316,17 +3357,11 @@ export default function SessionScreen() {}),]);if (!isCurrent()) return;- if (history !== null) {- remoteSessionStore.markSessionMessagesSynced(sessionId, sessionMeta);- if (pushRefresh) syncedNotificationResponseRef.current = notificationResponse;- }- setHasOlderMessages(history !== null- ? shouldKeepOlderMessagesAffordance(history)- : hasOlderMessagesAfterReopen(sessionMeta._count?.messages, remoteSessionStore.getMessages(sessionId)));- // 不变量:上面 setHasOlderMessages 的校正与这里的 setLastSyncedAt 之间必须保持- // 同步尾、无 await —— 否则乐观点亮 effect(依赖 lastSyncedAt===null)会在 await 间隙把刚校正成 false- // 的「加载更早」入口重新点亮。将来切勿在两者之间插入 await。if (syncRun.isStale() || !messageAuthorityCurrent()) return;+ setSyncError(null);+ if (shouldClearOperationErrorAfterSync(operationErrorRef.current, operationErrorAtSyncStart)) {+ setError(null);+ }// 当前设备的权威 session + projection 同步已完整落定,才解除独立 transport hold。// 不在 connectionEpoch 刚推进时提前清,避免同一 commit 的 outbox effect 抢在 resync 前派发。setOutboxTransportHold((current) => current?.deviceId === deviceId ? null : current);@@ -3345,18 +3380,17 @@ export default function SessionScreen() {} catch (err) {if (!syncRun.isStale() && messageAuthorityCurrent()) {const formatted = formatRemoteError(err);- setError(formatted);+ setSyncError(formatted);// 两类失败都写入 hold 且不能清门:瞬态错误继续自动重试,确定性错误保留// 手动同步入口;共享 UI error 被其它操作清掉时也不会变成不可见的永久自锁。latchOutboxTransportHold(formatted);- // The coordinator owns sibling cancellation and preserves this failure- // for rewind/navigation callers. Supersession remains a separate outcome.+ // Useful siblings have settled; preserve full-sync failure for callers.throw err;}} finally {if (!syncRun.isStale() && messageAuthorityCurrent()) setLoading(false);}- }, [deviceId, deviceName, getSubscriptionIdentity, latchOutboxTransportHold, maker, notificationResponse, openLink, reopenLink, sessionId, subscribe]);+ }, [deviceId, deviceName, getSubscriptionIdentity, latchOutboxTransportHold, maker, notificationResponse, openLink, reopenLink, sessionId, setError, subscribe]);// 任一连接恢复身份变化都会让旧读取失去提交资格。否则断线前启动的同步可能在// 新 hold 锁存后迟到,并从成功尾误清恢复屏障。const remoteSyncContextKey = JSON.stringify([@@ -3707,13 +3741,13 @@ export default function SessionScreen() {// 乐观点亮「加载更早」入口:缓存消息 hydrate 后(messages 已有内容),不等首开那次慢 listMessages(A1,// device-link 往返可能数秒)回来,就用已存 session 的 _count.messages 与 in-store 已加载真实条数比较,- // 立即让入口可见,避免"先拉没反应、慢拉取回来才出现入口、再拉才加载"。仅在本次打开尚未同步过- // (lastSyncedAt 为空)、入口当前不可见、且 _count 已知且 > 已加载时乐观置 true;A1 / reopen 回来后仍按+ // 立即让入口可见,避免"先拉没反应、慢拉取回来才出现入口、再拉才加载"。仅在历史尚未校正且未完整同步、+ // 入口当前不可见、且 _count 已知且 > 已加载时乐观置 true;A1 / reopen 回来后仍按// shouldKeepOlderMessagesAffordance / hasOlderMessagesAfterReopen 校正(:806/:846)。_count 未知不凭空点亮。useEffect(() => {if (isScheduleDetail) return;const currentMessages = latestMessagesRef.current;- if (lastSyncedAt !== null || hasOlderMessages || currentMessages.length === 0) return;+ if (messageWindowReconciledRef.current || lastSyncedAt !== null || hasOlderMessages || currentMessages.length === 0) return;if (hasOlderMessagesByServerCount(currentSession?._count?.messages, currentMessages)) {setHasOlderMessages(true);}@@ -4377,7 +4411,7 @@ export default function SessionScreen() {const loadEarlierMessages = useCallback(async () => {if (isScheduleDetail) return;- if (!deviceId || !sessionId || loadingEarlier || !hasOlderMessages) return;+ if (!deviceId || !sessionId || loadingEarlier || historyRequestInFlightRef.current !== null || !hasOlderMessages) return;const messageAuthority = remoteSessionStore.captureSessionMessageAuthority(sessionId);if (!remoteSessionStore.isSessionMessageAuthorityCurrent(messageAuthority)) return;const before = oldestLoadedMessageCursor;@@ -4389,25 +4423,35 @@ export default function SessionScreen() {// 发请求**之前**同步做掉,不能只靠依赖 loadingEarlier 的 effect —— 那是被动的,自动补齐可能// 在它执行前就返回并继续下一页(#1210 review)。abandonInFlightBackfill();+ const requestSeq = ++historyRequestSeqRef.current;+ historyRequestInFlightRef.current = requestSeq;+ const isCurrentHistoryRequest = () => historyRequestSeqRef.current === requestSeq+ && remoteSessionStore.isSessionMessageAuthorityCurrent(messageAuthority);setLoadingEarlier(true);- setError(null);try {const page = await withTransientRemoteRetry(() =>listMessagesWithPayloadRetry((limit) => maker.listMessages(sessionId, { limit, before })),);- if (!remoteSessionStore.isSessionMessageAuthorityCurrent(messageAuthority)) return;+ if (!isCurrentHistoryRequest()) return;const pageList = Array.isArray(page.messages) ? page.messages : [];// 用 mergeEarlierMessages 而不是 mergeMessages:这一页是沿 before 从窗口最旧端**连续**取的,// 登记进「已验证连续」区间后,后续满页的最新窗口同步才不会把用户一路翻出来的历史当成来源// 不明的缓存丢掉(#1210 review)。- remoteSessionStore.mergeEarlierMessages(sessionId, pageList, { authority: messageAuthority });+ if (!remoteSessionStore.mergeEarlierMessages(sessionId, pageList, {+ authority: messageAuthority,+ before,+ })) return;+ setHistoryError(null);setHasOlderMessages(shouldKeepOlderMessagesAffordance(page));} catch (err) {- if (remoteSessionStore.isSessionMessageAuthorityCurrent(messageAuthority)) {- setError(formatRemoteError(err));+ if (isCurrentHistoryRequest()) {+ setHistoryError(formatRemoteError(err));}} finally {- setLoadingEarlier(false);+ if (historyRequestSeqRef.current === requestSeq) {+ historyRequestInFlightRef.current = null;+ setLoadingEarlier(false);+ }}}, [abandonInFlightBackfill, deviceId, hasOlderMessages, isScheduleDetail, loadingEarlier, maker, oldestLoadedMessageCursor, sessionId]);@@ -8677,11 +8721,14 @@ export default function SessionScreen() {<ConnectionBannerdensity="compact"deviceUnresponsive={isDeviceUnresponsive}- error={connectionRecoveryError}+ error={bannerError}+ requestErrorAutoRecovering={bannerRetriesHistory ? false : undefined}issue={connectionIssue}lastSyncedAt={lastSyncedAt}- loading={loading}- onSync={() => void requestSync({ reason: 'manual', replaceMessages: false })}+ loading={loading || loadingEarlier}+ onSync={() => bannerRetriesHistory+ ? void loadEarlierMessages()+ : void requestSync({ reason: 'manual', replaceMessages: false })}status={status}recovery={contentRecoveryState}variant="inline"diff --git a/apps/mobile/src/__tests__/historyWindowGap.test.ts b/apps/mobile/src/__tests__/historyWindowGap.test.tsindex 9d9fce8311..6bad203506 100644--- a/apps/mobile/src/__tests__/historyWindowGap.test.ts+++ b/apps/mobile/src/__tests__/historyWindowGap.test.ts@@ -138,6 +138,24 @@ describe('backfillHistoryWindowGap', () => {expect(merge).not.toHaveBeenCalled();});+ it('fills a 400-row gap using small network pages within the bounded request budget', async () => {+ const history = Array.from({ length: 400 }, (_, i) => row(`m${399 - i}`, 399 - i));+ const merged: string[] = [];+ const listPage = vi.fn(async (before: string, limit: number) => {+ const start = before === 'tail' ? 0 : history.findIndex((r) => r.id === before) + 1;+ return history.slice(start, start + limit);+ });+ const outcome = await backfillHistoryWindowGap({+ newerId: 'tail', olderId: 'm0', newerMs: BASE_MS + 401 * 60_000,+ olderMs: BASE_MS, gapMs: 401 * 60_000,+ }, { listPage, merge: (rows) => merged.push(...rows.map((r) => r.id)), isCancelled: () => false });+ expect(outcome).toBe('covered');+ expect(merged).toEqual(history.map((r) => r.id));+ expect(listPage.mock.calls[0][1]).toBe(1);+ expect(listPage.mock.calls.slice(1).every(([, limit]) => limit === 20)).toBe(true);+ expect(listPage.mock.calls.length).toBeLessThanOrEqual(HISTORY_BACKFILL_MAX_REQUESTS);+ });+it('探测发现别的行 → 继续翻页直到取回目标行', async () => {const merged: string[] = [];// 每页按服务端契约排列:最新在前、页尾最旧(见 nextPageCursor)。diff --git a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts b/apps/mobile/src/__tests__/homeDesktopFirst.test.tsindex 10ca485225..4466d7c95f 100644--- a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts+++ b/apps/mobile/src/__tests__/homeDesktopFirst.test.ts@@ -315,15 +315,16 @@ describe('mobile home desktop-first surface', () => {expect(source).toContain('saveDeviceIdentityCache(result.cache)');expect(source).toContain('loadDeviceSessionScheduleIndex(deviceId, invoke)');expect(source).toContain('replaceSessionScheduleIndexEntries(');- expect(source).toContain("invoke<unknown[]>(device.deviceId, 'maker:list-active', [])");+ expect(source).toContain("invoke<unknown[]>(device.deviceId, 'maker:list-active', [");+ expect(source).toContain("{ summary: true }");expect(source).toContain('if (isOptionalActiveSessionSnapshotError(err)) return null;');expect(source).toContain('function isOptionalActiveSessionSnapshotError(error: unknown): boolean');expect(source).toContain('if (isAccessRevokedError(error) || isDeviceOfflineError(error)) return false;');expect(source).toContain("if (text.includes('REMOTE_DISABLED')) return false;");expect(source).toContain('return true;');- expect(source).toMatch(/const \[\s*list,\s*activeSessions,\s*activeSessionSnapshotEpoch,/);+ expect(source).toContain('await runIndependentSnapshotReads([');expect(source).toContain('remoteSessionStore.captureActiveSessionSnapshotEpoch()');- expect(source).toMatch(/return \[\s*list,\s*activeSessions,\s*activeSessionSnapshotEpoch,/);+ expect(source).toContain('return [active, epoch] as const;');expect(source).toContain('activeSessionSnapshotEpoch,');expect(source).toContain('remoteScheduleEventStore.subscribe(() => {');expect(source).toContain('const snapshot = remoteScheduleEventStore.getSnapshot(deviceId)');diff --git a/apps/mobile/src/__tests__/invokeTimeouts.test.ts b/apps/mobile/src/__tests__/invokeTimeouts.test.tsindex b1fc195849..b1311ab02a 100644--- a/apps/mobile/src/__tests__/invokeTimeouts.test.ts+++ b/apps/mobile/src/__tests__/invokeTimeouts.test.ts@@ -7,6 +7,10 @@ import {} from '@/device-link/invokeTimeouts';describe('resolveMobileInvokeTimeoutMs', () => {+ it('allows a large history row to finish on a slow link without widening small status reads', () => {+ expect(resolveMobileInvokeTimeoutMs('local-db:messages:list')).toBe(30_000);+ expect(resolveMobileInvokeTimeoutMs('maker:list-active')).toBeUndefined();+ });it('mobile 精确表优先:media / 文件搜索 / 词典学习保住收紧前的 30s 窗口', () => {expect(resolveMobileInvokeTimeoutMs('device-link:media:fetch')).toBe(30_000);expect(resolveMobileInvokeTimeoutMs('file-browser:remote-op')).toBe(30_000);diff --git a/apps/mobile/src/__tests__/messagePaging.test.ts b/apps/mobile/src/__tests__/messagePaging.test.tsindex e5b3ae7208..e4b4dfafcc 100644--- a/apps/mobile/src/__tests__/messagePaging.test.ts+++ b/apps/mobile/src/__tests__/messagePaging.test.ts@@ -38,6 +38,28 @@ function sessionVersion(patch: Partial<Pick<RemoteSession, '_count' | 'updatedAt}describe('messagePaging', () => {+ it('never sends temporary stream identities as host pagination cursors', () => {+ const rows = [+ message('mobile-stream-old', '2026-01-01T00:00:01.000Z'),+ message('host-row', '2026-01-01T00:00:02.000Z'),+ message('mobile-stream-new', '2026-01-01T00:00:03.000Z'),+ ];+ expect(oldestMessageCursor(rows)).toBe('host-row');+ expect(latestMessageCursor(rows)).toBe('host-row');+ expect(oldestMessageCursor([rows[0], rows[2]])).toBeNull();+ expect(latestMessageCursor([rows[0], rows[2]])).toBeNull();+ });++ it('does not let running stream rows consume the remaining host history count', () => {+ const rows = [+ message('host-row', '2026-01-01T00:00:01.000Z'),+ message('mobile-stream-new', '2026-01-01T00:00:02.000Z'),+ ];+ expect(hasOlderMessagesAfterReopen(2, rows)).toBe(true);+ expect(hasOlderMessagesByServerCount(2, rows)).toBe(true);+ expect(hasOlderMessagesAfterReopen(undefined, [rows[1]], 1)).toBe(false);+ });+it('finds the oldest message id without relying on current array order', () => {expect(oldestMessageCursor([message('m3', '2026-01-01T00:00:03.000Z'),@@ -273,6 +295,17 @@ describe('messagePaging', () => {expect(shouldKeepOlderMessagesAffordance(result)).toBe(true);});+ it('uses small network pages without reducing the cached history window', async () => {+ const calls: number[] = [];+ const result = await listMessagesWithPayloadRetry(async (limit) => {+ calls.push(limit);+ return Array.from({ length: limit }, (_, i) => message(`m${i}`, '2026-01-01T00:00:01.000Z'));+ });+ expect(calls).toEqual([20]);+ expect(MESSAGE_PAGE_SIZE).toBe(80);+ expect(shouldKeepOlderMessagesAffordance(result)).toBe(true);+ });+it('does not retry non-payload pagination errors', async () => {const calls: number[] = [];await expect(listMessagesWithPayloadRetry(async (limit) => {diff --git a/apps/mobile/src/__tests__/mobileMakerTransport.test.ts b/apps/mobile/src/__tests__/mobileMakerTransport.test.tsindex c8a67d396e..e870b6fc25 100644--- a/apps/mobile/src/__tests__/mobileMakerTransport.test.ts+++ b/apps/mobile/src/__tests__/mobileMakerTransport.test.ts@@ -183,7 +183,7 @@ describe('mobile maker transport', () => {{deviceId: 'dev-1',channel: 'maker:list-active',- args: [],+ args: [{ summary: true }],},]);});diff --git a/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts b/apps/mobile/src/__tests__/optimisticSessionComposer.test.tsindex a65ef759a2..dd43884a2b 100644--- a/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts+++ b/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts@@ -274,7 +274,9 @@ describe('mobile optimistic composer while session is not ready', () => {expect(retry).toContain('|| isDeviceUnresponsive');expect(syncCatch).toContain('latchOutboxTransportHold(formatted);');expect(syncCatch).not.toContain('? null : current');- expect(source).toContain('error={connectionRecoveryError}');+ expect(source).toContain('error={bannerError}');+ expect(source).toContain('const bannerError = connectionRecoveryError ?? historyError;');+ expect(source).toContain('requestErrorAutoRecovering={bannerRetriesHistory ? false : undefined}');});it('separates the interrupted metadata fence from the full read-ack sync gate', () => {diff --git a/apps/mobile/src/__tests__/remoteSessionStore.test.ts b/apps/mobile/src/__tests__/remoteSessionStore.test.tsindex 6ccb27028c..b2be40cbe1 100644--- a/apps/mobile/src/__tests__/remoteSessionStore.test.ts+++ b/apps/mobile/src/__tests__/remoteSessionStore.test.ts@@ -1,5 +1,5 @@import { beforeEach, describe, expect, it, vi } from 'vitest';-import { MAKER_EVENT_BATCH_CHANNEL } from '@cindy/device-link';+import { MAKER_EVENT_BATCH_CHANNEL, SESSION_SYNC_CHANNEL } from '@cindy/device-link';import { clampLiveRowCreatedAt } from '@/session/messagePaging';import { MOBILE_TOOL_INPUT_PROJECTION_THRESHOLD_BYTES } from '@/session/messageToolPayloadProjection';import { remoteSessionStore, sessionPendingWrites } from '@/session/remoteSessionStore';@@ -679,6 +679,109 @@ describe('remoteSessionStore', () => {expect(remoteSessionStore.getSessionTaskUpdates('s1').size).toBe(0);});+ it('repairs a missing streaming prefix on reopen and keeps subsequent deltas exactly once', () => {+ vi.useFakeTimers();+ try {+ pushMakerText('s1', 'live-id', ' suffix', false);+ const snapshot = {+ sessionId: 's1', persistId: 'live-id',+ event: { type: 'text', data: { text: 'prefix suffix', isFinal: false, isFullText: true } },+ };+ remoteSessionStore.applyRemotePush('dev-1', SESSION_SYNC_CHANNEL, snapshot);+ remoteSessionStore.applyRemotePush('dev-1', SESSION_SYNC_CHANNEL, snapshot);+ pushMakerText('s1', 'live-id', ' tail', false);+ vi.runOnlyPendingTimers();+ expect(remoteSessionStore.getMessages('s1')).toHaveLength(1);+ expect(remoteSessionStore.getMessages('s1')[0]).toMatchObject({+ content: 'prefix suffix tail', agentMeta: { isStreaming: true },+ });+ remoteSessionStore.applyRemotePush('dev-1', 'local-db:messages:created', {+ sessionId: 's1', message: { ...message('host-id', 's1'), clientId: 'live-id', content: 'prefix suffix tail final' },+ });+ remoteSessionStore.applyRemotePush('dev-1', SESSION_SYNC_CHANNEL, snapshot);+ expect(remoteSessionStore.getMessages('s1')).toHaveLength(1);+ expect(remoteSessionStore.getMessages('s1')[0].content).toBe('prefix suffix tail final');+ } finally { vi.useRealTimers(); }+ });++ it('still accepts a legacy final full-text event after its partial row was persisted', () => {+ remoteSessionStore.setMessages('s1', [{+ ...message('host-id', 's1'), clientId: 'legacy-id', content: 'partial',+ }]);+ remoteSessionStore.applyRemotePush('dev-1', 'maker:event', {+ sessionId: 's1', persistId: 'legacy-id', event: {+ type: 'text', data: { text: 'partial completed', isFinal: true, isFullText: true },+ },+ });+ expect(remoteSessionStore.getMessages('s1')).toHaveLength(1);+ expect(remoteSessionStore.getMessages('s1')[0]).toMatchObject({+ id: 'host-id', content: 'partial completed',+ });+ });++ it.each([false, true])('orders the live snapshot by host time when history arrives later (existing=%s)', (existing) => {+ vi.useFakeTimers();+ try {+ const oldTime = '2026-09-05T10:00:00.000Z';+ const userTime = '2026-09-05T11:00:00.000Z';+ const blockTime = '2026-09-05T11:00:01.000Z';+ remoteSessionStore.setMessages('s1', [{ ...message('old', 's1'), createdAt: oldTime }]);+ if (existing) {+ pushMakerText('s1', 'live-id', 'suffix', false);+ vi.runOnlyPendingTimers();+ remoteSessionStore.mergeMessages('s1', [{ ...message('user', 's1'), role: 'user', createdAt: userTime }]);+ }+ remoteSessionStore.applyRemotePush('dev-1', SESSION_SYNC_CHANNEL, {+ sessionId: 's1', persistId: 'live-id', event: {+ type: 'text', data: { text: 'whole suffix', isFinal: false, isFullText: true, createdAt: blockTime },+ },+ });+ remoteSessionStore.mergeMessages('s1', [{ ...message('user', 's1'), role: 'user', createdAt: userTime }]);+ pushMakerText('s1', 'live-id', ' tail', false);+ vi.runOnlyPendingTimers();+ expect(remoteSessionStore.getMessages('s1').map(m => m.id)).toEqual(['old', 'user', 'live-id']);+ expect(remoteSessionStore.getMessages('s1').at(-1)).toMatchObject({+ content: 'whole suffix tail', createdAt: blockTime, agentMeta: { isStreaming: true },+ });+ } finally { vi.useRealTimers(); }+ });++ it('requests history reconciliation after a dropped push without clearing cached messages', () => {+ const meta = session('s1', { _count: { messages: 1 } });+ remoteSessionStore.setMessages('s1', [message('m1', 's1')]);+ remoteSessionStore.markSessionMessagesSynced('s1', meta);+ remoteSessionStore.applyRemotePush('dev-1', SESSION_SYNC_CHANNEL, { sessionId: 's1', resyncRequired: true });+ expect(remoteSessionStore.getMessages('s1')).toHaveLength(1);+ expect(remoteSessionStore.isSessionMessageWindowSynced('s1', meta)).toBe(false);+ expect(remoteSessionStore.hasPendingRefresh('s1')).toBe(true);+ // An older in-flight history response commits after the dirty notification.+ remoteSessionStore.markSessionMessagesSynced('s1', meta);+ expect(remoteSessionStore.consumePendingRefresh('s1')).toBe(true);+ expect(remoteSessionStore.isSessionMessageWindowSynced('s1', meta)).toBe(false);+ });++ it('retires a provisional time anchor even when the authoritative snapshot is identical', () => {+ vi.useFakeTimers();+ try {+ const blockTime = '2026-09-05T11:00:01.000Z';+ vi.setSystemTime(new Date(blockTime));+ pushMakerText('s1', 'live-id', 'whole text', false);+ vi.runOnlyPendingTimers();+ const createdAt = remoteSessionStore.getMessages('s1')[0].createdAt;+ remoteSessionStore.applyRemotePush('dev-1', SESSION_SYNC_CHANNEL, {+ sessionId: 's1', persistId: 'live-id', event: {+ type: 'text', data: { text: 'whole text', isFinal: false, isFullText: true, createdAt },+ },+ });+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', {+ updatedAt: '2026-09-05T10:00:00.000Z', userSendAt: '2026-09-05T10:00:00.000Z',+ })]);+ expect(remoteSessionStore.getMessages('s1')[0]).toMatchObject({+ createdAt, content: 'whole text', agentMeta: { isStreaming: true },+ });+ } finally { vi.useRealTimers(); }+ });+it('batches maker text deltas into one streaming assistant row', () => {vi.useFakeTimers();const notify = vi.fn();@@ -2114,6 +2217,47 @@ describe('remoteSessionStore', () => {]);});+ it('rejects late paging whose anchor was removed by a concurrent latest-window refresh', () => {+ const old = messageAt('old-anchor', 's1', '2026-01-01T09:00:00.000Z');+ const latest = messageAt('new-anchor', 's1', '2026-01-01T10:00:00.000Z');+ remoteSessionStore.setMessages('s1', [old]);+ remoteSessionStore.setLatestMessageWindow('s1', [latest], { moreBeyondWindow: true });+ expect(remoteSessionStore.mergeEarlierMessages('s1', [+ messageAt('late-old-page', 's1', '2026-01-01T08:00:00.000Z'),+ ], { before: old.id })).toBe(false);+ expect(remoteSessionStore.mergeEarlierMessages('s1', [], { before: old.id })).toBe(false);+ expect(remoteSessionStore.getMessages('s1').map(row => row.id)).toEqual(['new-anchor']);+ // Paging again from the surviving anchor fills the actual gap and may extend coverage.+ expect(remoteSessionStore.mergeEarlierMessages('s1', [old], { before: latest.id })).toBe(true);+ remoteSessionStore.setLatestMessageWindow('s1', [latest], { moreBeyondWindow: true });+ expect(remoteSessionStore.getMessages('s1').map(row => row.id)).toEqual(['old-anchor', 'new-anchor']);+ });++ it('does not join a late disjoint latest response to a newer verified window', () => {+ const latest = messageAt('new-anchor', 's1', '2026-01-01T10:00:00.000Z');+ remoteSessionStore.noteLiveStreamAcked('s1');+ remoteSessionStore.setLatestMessageWindow('s1', [latest], { moreBeyondWindow: true });+ remoteSessionStore.setLatestMessageWindow('s1', [+ messageAt('stale-latest', 's1', '2026-01-01T08:00:00.000Z'),+ ], { moreBeyondWindow: true });+ const tail = messageAt('live-tail', 's1', '2026-01-01T11:00:00.000Z');+ remoteSessionStore.appendMessage('s1', tail);+ remoteSessionStore.setLatestMessageWindow('s1', [tail], { moreBeyondWindow: true });+ expect(remoteSessionStore.getMessages('s1').map(row => row.id)).toEqual(['new-anchor', 'live-tail']);+ });++ it('does not certify a gap when paging before an unverified older island', () => {+ const latest = messageAt('new-anchor', 's1', '2026-01-01T10:00:00.000Z');+ const island = messageAt('island', 's1', '2026-01-01T09:00:00.000Z');+ remoteSessionStore.setMessages('s1', [latest]);+ remoteSessionStore.mergeMessages('s1', [island]);+ remoteSessionStore.mergeEarlierMessages('s1', [+ messageAt('old-page', 's1', '2026-01-01T08:00:00.000Z'),+ ], { before: island.id });+ remoteSessionStore.setLatestMessageWindow('s1', [latest], { moreBeyondWindow: true });+ expect(remoteSessionStore.getMessages('s1').map(row => row.id)).toEqual(['new-anchor']);+ });+it('用户「加载更早」翻出来的历史在满页重连时保留(已验证连续)', () => {// 回归(#1210 review):只凭"最新页满页"就清空更早的行,会把用户一路翻出来的历史与滚动锚点// 一起丢掉,而且补齐也不会拉回(裁完窗口里已没有内部跳变可发现)。「加载更早」是沿 before 从diff --git a/apps/mobile/src/__tests__/scrollWindowModel.test.ts b/apps/mobile/src/__tests__/scrollWindowModel.test.tsindex 6041157b2b..af03251899 100644--- a/apps/mobile/src/__tests__/scrollWindowModel.test.ts+++ b/apps/mobile/src/__tests__/scrollWindowModel.test.ts@@ -100,12 +100,13 @@ describe('scrollWindowModel', () => {it.each(['\n', '\r\n'])('restores the load-earlier affordance after unchanged reopen with %j line endings', (lineEnding) => {const source = readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8').replace(/\r?\n/g, lineEnding);// 重开"无新内容"分支(metaChanged=false)也补设 hasOlderMessages,用服务端总数 vs in-store 推断。- expect(source).toContain('hasOlderMessagesAfterReopen(sessionMeta._count?.messages, remoteSessionStore.getMessages(sessionId))');+ expect(source).toMatch(/hasOlderMessagesAfterReopen\(\s*sessionMeta\._count\?\.messages, remoteSessionStore\.getMessages\(sessionId\),?\s*\)/);// 仍保留有新内容时的精确(page-based)判定。这个值现在同时喂给 store 的窗口连续性判据// (moreBeyondWindow,见 #1222):两者本就该同源 —— 「本页上沿之外还有历史」既决定是否点亮// 「加载更早」,也决定能不能信任早于本页的缓存段。expect(source).toContain('const moreBeyondWindow = shouldKeepOlderMessagesAffordance(history);');- expect(source).toMatch(/setHasOlderMessages\(history !== null\s+\? shouldKeepOlderMessagesAffordance\(history\)/);+ expect(source).toContain('setHasOlderMessages(moreBeyondWindow);');+ expect(source).toMatch(/if \(history === null\) \{\s*messageWindowReconciledRef\.current = true;\s*setHasOlderMessages\(hasOlderMessagesAfterReopen\(/);expect(source).toMatch(/setLatestMessageWindow\(sessionId, historyPage, \{\s*authority: messageAuthority,\s*moreBeyondWindow,\s*\}\)/,);diff --git a/apps/mobile/src/__tests__/sessionMainLayerDesktopFirst.test.ts b/apps/mobile/src/__tests__/sessionMainLayerDesktopFirst.test.tsindex 312ab4dfd0..4510cc8182 100644--- a/apps/mobile/src/__tests__/sessionMainLayerDesktopFirst.test.ts+++ b/apps/mobile/src/__tests__/sessionMainLayerDesktopFirst.test.ts@@ -46,7 +46,7 @@ describe('mobile session main layer desktop-first noise budget', () => {// 目标设备熔断 open(电脑端未响应)立即显示;普通弱网断线经防闪窗口后也显示,不再彻底静默。expect(routeSource).toContain('{showConnectionBanner ? (');expect(source.replace(/\r\n/g, '\n'))- .toContain('useShowConnectionBanner(\n status,\n connectionRecoveryError,');+ .toContain('useShowConnectionBanner(\n status,\n bannerError,');expect(routeSource).not.toContain('connectionError || (loading && !currentSession)');expect(syncSource).toContain("t('session.screen.awaitingSync')");expect(syncSource).toContain("t('session.screen.resync')");diff --git a/apps/mobile/src/__tests__/sessionMessageMemoryWiring.test.ts b/apps/mobile/src/__tests__/sessionMessageMemoryWiring.test.tsindex 22de008131..45fc9d8bfb 100644--- a/apps/mobile/src/__tests__/sessionMessageMemoryWiring.test.ts+++ b/apps/mobile/src/__tests__/sessionMessageMemoryWiring.test.ts@@ -74,10 +74,10 @@ describe('任务消息内存治理页面接线', () => {expect(screen).toContain('remoteSessionStore.setMessages(sessionId, historyPage, { authority: messageAuthority });');expect(screen).toMatch(/authority: messageAuthority,\s+moreBeyondWindow,/);expect(screen).toContain('{ authority: messageAuthority },\n );');- expect(screen).toContain('remoteSessionStore.mergeEarlierMessages(sessionId, pageList, { authority: messageAuthority });');+ expect(screen).toMatch(/remoteSessionStore\.mergeEarlierMessages\(sessionId, pageList, \{\s*authority: messageAuthority,\s*before,\s*\}\)/);expect(screen).toContain('remoteSessionStore.mergeMessages(sessionIdAtStart, rows, { authority: messageAuthority });');// First open and reopen now share the same authority-fenced history read.- expect(screen).toContain('readProgressiveMessageWindow({');+ expect(screen).toContain('syncSessionMessageWindow({');expect(screen.match(/maker\.listMessages\(/g)).toHaveLength(3);});diff --git a/apps/mobile/src/__tests__/sessionMessageWindowSync.test.ts b/apps/mobile/src/__tests__/sessionMessageWindowSync.test.tsnew file mode 100644index 0000000000..01ec1de1db--- /dev/null+++ b/apps/mobile/src/__tests__/sessionMessageWindowSync.test.ts@@ -0,0 +1,107 @@+import { describe, expect, it, vi } from 'vitest';+import { syncSessionMessageWindow } from '@/session/sessionMessageWindowSync';+import { shouldKeepOlderMessagesAffordance, type MessagePageRetryResult } from '@/session/messagePaging';+import type { RemoteMessage, RemoteSession } from '@/session/types';++function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((done) => { resolve = done; });+ return { promise, resolve };+}++const session = { id: 's1', updatedAt: '2026-09-05T00:00:00Z', _count: { messages: 100 } } as RemoteSession;+const page: MessagePageRetryResult = {+ messages: [{ id: 'host-row', clientId: 'host-row', sessionId: 's1' } as RemoteMessage],+ limit: 1,+ reducedByPayloadTooLarge: true,+};++function fixture(isReopen = false) {+ return {+ isReopen,+ storedSession: session,+ readMetadata: vi.fn(async () => session),+ readLatest: vi.fn(async () => page),+ isCurrent: vi.fn(() => true),+ isWindowSynced: vi.fn(() => false),+ commit: vi.fn(),+ };+}++describe('independent session history sync', () => {+ it.each([false, true])('commits history and preserves pagination when projection fails (reopen=%s)', async (isReopen) => {+ const input = fixture(isReopen);+ const history = deferred<MessagePageRetryResult>();+ input.readLatest.mockReturnValue(history.promise);+ const projectionError = new Error('[INVOKE_TIMEOUT] projection');+ const result = Promise.allSettled([+ syncSessionMessageWindow(input),+ Promise.reject(projectionError),+ ]);+ await Promise.resolve();+ expect(input.commit).not.toHaveBeenCalled();+ history.resolve(page);+ const outcomes = await result;+ expect(input.commit).toHaveBeenCalledWith(session, page);+ expect(shouldKeepOlderMessagesAffordance(input.commit.mock.calls[0][1])).toBe(true);+ expect(outcomes[0].status).toBe('fulfilled');+ expect(outcomes[1]).toEqual({ status: 'rejected', reason: projectionError });+ });++ it('starts cold metadata and history concurrently', async () => {+ const input = fixture();+ const metadata = deferred<RemoteSession>();+ input.readMetadata.mockReturnValue(metadata.promise);+ const result = syncSessionMessageWindow(input);+ expect(input.readLatest).toHaveBeenCalledOnce();+ expect(input.commit).not.toHaveBeenCalled();+ metadata.resolve(session);+ await result;+ expect(input.commit).toHaveBeenCalledWith(session, page);+ });++ it('reconciles cached pagination without refetching unchanged, synced history', async () => {+ const input = fixture(true);+ input.isWindowSynced.mockReturnValue(true);+ await syncSessionMessageWindow(input);+ expect(input.readLatest).not.toHaveBeenCalled();+ expect(input.commit).toHaveBeenCalledWith(session, null);+ });++ it('refreshes running history when the host metadata changes', async () => {+ const input = fixture(true);+ const updated = { ...session, updatedAt: '2026-09-05T00:01:00Z' };+ input.isWindowSynced.mockReturnValue(true);+ input.readMetadata.mockResolvedValue(updated);+ await syncSessionMessageWindow(input);+ expect(input.commit).toHaveBeenCalledWith(updated, page);+ });++ it.each([false, true])('does not commit a late page after authority or page identity changes (reopen=%s)', async (isReopen) => {+ const input = fixture(isReopen);+ const history = deferred<MessagePageRetryResult>();+ input.readLatest.mockReturnValue(history.promise);+ const result = syncSessionMessageWindow(input);+ await Promise.resolve();+ input.isCurrent.mockReturnValue(false);+ history.resolve(page);+ await result;+ expect(input.commit).not.toHaveBeenCalled();+ });++ it('does not start a reopened history request after metadata loses authority', async () => {+ const input = fixture(true);+ input.isCurrent.mockReturnValue(false);+ await syncSessionMessageWindow(input);+ expect(input.readLatest).not.toHaveBeenCalled();+ expect(input.commit).not.toHaveBeenCalled();+ });++ it('keeps a real history failure visible without marking the window synced', async () => {+ const input = fixture();+ const error = new Error('[INVOKE_TIMEOUT] history');+ input.readLatest.mockRejectedValue(error);+ await expect(syncSessionMessageWindow(input)).rejects.toBe(error);+ expect(input.commit).not.toHaveBeenCalled();+ });+});diff --git a/apps/mobile/src/__tests__/sessionSyncErrorRecovery.test.ts b/apps/mobile/src/__tests__/sessionSyncErrorRecovery.test.tsnew file mode 100644index 0000000000..632b068c3e--- /dev/null+++ b/apps/mobile/src/__tests__/sessionSyncErrorRecovery.test.ts@@ -0,0 +1,29 @@+import { describe, expect, it } from 'vitest';+import { shouldClearOperationErrorAfterSync } from '@/session/sessionSyncErrorRecovery';++describe('operation error cleanup after successful authoritative sync', () => {+ it.each(['INVOKE_TIMEOUT', 'NOT_CONNECTED', 'DEVICE_UNRESPONSIVE'])(+ 'clears the %s occurrence that initiated recovery', (code) => {+ const error = { message: `[${code}] failed` };+ expect(shouldClearOperationErrorAfterSync(error, error)).toBe(true);+ },+ );++ it('preserves a newer timeout even when the text is identical', () => {+ const startedWith = { message: '[INVOKE_TIMEOUT] failed' };+ expect(shouldClearOperationErrorAfterSync({ ...startedWith }, startedWith)).toBe(false);+ });++ it('preserves an error raised during an initially healthy sync', () => {+ expect(shouldClearOperationErrorAfterSync({ message: '[INVOKE_TIMEOUT] failed' }, null)).toBe(false);+ });++ it('preserves deterministic operation failures', () => {+ const error = { message: '[NOT_FOUND] message not found' };+ expect(shouldClearOperationErrorAfterSync(error, error)).toBe(false);+ });++ it('does nothing when another operation already cleared the error', () => {+ expect(shouldClearOperationErrorAfterSync(null, { message: '[INVOKE_TIMEOUT] failed' })).toBe(false);+ });+});diff --git a/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.ts b/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.tsnew file mode 100644index 0000000000..5830095558--- /dev/null+++ b/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.ts@@ -0,0 +1,275 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import ts from 'typescript';+import { describe, expect, it, vi } from 'vitest';+import { createRemoteSyncCoordinator } from '@/device-link/remoteSyncTask';+import { runConnectionScopedSessionMetadataRead, waitForIndependentSnapshotReads } from '@/device-link/sessionSnapshotSingleFlight';+import { syncSessionMessageWindow } from '@/session/sessionMessageWindowSync';+import { shouldClearOperationErrorAfterSync } from '@/session/sessionSyncErrorRecovery';+import { hasOlderMessagesAfterReopen, shouldKeepOlderMessagesAffordance } from '@/session/messagePaging';++// Execute the actual page callbacks, not a duplicate orchestration written for tests.+// This catches a helper becoming disconnected from the screen during integration.+const source = ts.createSourceFile('screen.tsx', readFileSync(+ resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8',+), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+function pageCallback(name: string, bindings: Record<string, unknown>): (...args: any[]) => Promise<void> {+ let expression: ts.Expression | undefined;+ const visit = (node: ts.Node) => {+ if (ts.isVariableDeclaration(node) && node.name.getText(source) === name+ && node.initializer && ts.isCallExpression(node.initializer)) {+ expression = node.initializer.arguments[0];+ }+ ts.forEachChild(node, visit);+ };+ visit(source);+ if (!expression) throw new Error(`Missing production callback ${name}`);+ const compiled = ts.transpileModule(`const callback = ${expression.getText(source)};`, {+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS },+ }).outputText;+ return new Function(...Object.keys(bindings), `${compiled}\nreturn callback;`)(...Object.values(bindings));+}+function deferred<T>() {+ let resolve!: (value: T) => void;+ let reject!: (reason: unknown) => void;+ const promise = new Promise<T>((yes, no) => { resolve = yes; reject = no; });+ return { promise, resolve, reject };+}+const tick = () => new Promise((done) => setTimeout(done, 0));+const session = { id: 's1', updatedAt: '2026-09-06T00:00:00Z', _count: { messages: 100 } };+const page = { messages: [{ id: 'm1' }], limit: 1, reducedByPayloadTooLarge: false };++function fixture(reopen = false) {+ const state = {+ rows: reopen ? [{ id: 'cached', clientId: 'cached' }] : [] as { id: string; clientId?: string }[],+ older: false, loading: false, historyLoading: false,+ syncError: null as string | null, historyError: null as string | null,+ operation: null as { message: string } | null,+ hold: { deviceId: 'd1', error: null } as { deviceId: string; error: string | null } | null,+ synced: null as number | null, readAck: null as string | null,+ };+ const operationErrorRef = { current: state.operation };+ const setError = vi.fn((message: string | null) => {+ state.operation = message === null ? null : { message };+ operationErrorRef.current = state.operation;+ });+ const store = {+ captureSessionMessageAuthority: () => ({ generation: 1 }),+ isSessionMessageAuthorityCurrent: () => true,+ upsertDeviceSession: vi.fn(),+ getMessages: () => state.rows,+ getSessions: () => reopen ? [session] : [],+ captureActiveSessionSnapshotEpoch: () => 0,+ captureInputProjectionAuthorityEpoch: () => 0,+ getPendingInteractions: () => [],+ isSessionMessageWindowSynced: vi.fn(() => false),+ setMessages: vi.fn((_id, rows) => { state.rows = rows; }),+ setLatestMessageWindow: vi.fn((_id, rows) => { state.rows = rows; }),+ markSessionMessagesSynced: vi.fn(),+ setPendingInteractions: vi.fn(), setInputProjectionIfCurrent: vi.fn(),+ setActiveSessionSnapshots: vi.fn(),+ mergeEarlierMessages: vi.fn((_id, rows) => { state.rows = [...rows, ...state.rows]; return true; }),+ };+ const maker = {+ getSession: vi.fn(async () => session),+ listMessages: vi.fn(async () => page),+ input: { getProjection: vi.fn(async () => ({})) },+ getPendingInteractions: vi.fn(async () => []),+ listActiveSessions: vi.fn(async () => []),+ };+ const bindings = {+ deviceId: 'd1', deviceName: 'test', sessionId: 's1',+ remoteSessionStore: store, maker, shouldBlockSessionSync: () => false,+ readAckEpochRef: { current: 1 }, readAckGateGenRef: { current: 1 },+ sessionSubscriptionIdentityRef: { current: JSON.stringify(['d1', 's1', 1]) },+ createRemoteSyncReopenCoordinator: () => ({ captureVersion: () => 0 }),+ reopenLink: async () => undefined, openLink: async () => undefined,+ subscribe: async () => undefined, sessionsSubscriptionCoordinatorRef: { current: null },+ // Retry delays / transport single-flight are tested separately; preserve callbacks and fences here.+ retryRemoteSyncRead: (_run: unknown, read: () => unknown) => read(),+ runConnectionScopedSessionMetadataRead, waitForIndependentSnapshotReads, syncSessionMessageWindow,+ runSessionProjectionSnapshotSingleFlight: (_scope: unknown, _epoch: unknown, read: () => unknown) => read(),+ runSessionPendingInteractionsSnapshotSingleFlight: (_scope: unknown, _pending: unknown, read: () => unknown) => read(),+ runSessionMessagesSnapshotSingleFlight: (_scope: unknown, _limit: unknown, _fence: unknown, read: () => unknown) => read(),+ listMessagesWithPayloadRetry: (read: (limit: number) => unknown) => read(20),+ withTransientRemoteRetry: (read: () => unknown) => read(),+ REOPEN_MESSAGE_WINDOW_LIMITS: [20],+ getSubscriptionIdentity: () => null, notificationResponse: null,+ syncedNotificationResponseRef: { current: null },+ shouldKeepOlderMessagesAffordance, hasOlderMessagesAfterReopen,+ messageWindowReconciledRef: { current: false },+ setHasOlderMessages: (value: boolean) => { state.older = value; },+ setLoading: (value: boolean) => { state.loading = value; },+ setSyncError: (value: string | null) => { state.syncError = value; },+ setError, operationErrorRef, shouldClearOperationErrorAfterSync,+ setOutboxTransportHold: (update: (value: typeof state.hold) => typeof state.hold) => { state.hold = update(state.hold); },+ latchOutboxTransportHold: (error: string) => { state.hold = { deviceId: 'd1', error }; },+ setLastSyncedAt: (value: number) => { state.synced = value; },+ setContentSyncedKey: vi.fn(), contentRecoveryKeyRef: { current: null },+ setSessionMetadataSyncedKey: vi.fn(),+ setReadAckSyncedKey: (value: string) => { state.readAck = value; },+ formatRemoteError: (error: Error) => error.message,+ isScheduleDetail: false, loadingEarlier: false, hasOlderMessages: true,+ oldestLoadedMessageCursor: 'before-m1', abandonInFlightBackfill: vi.fn(),+ historyRequestSeqRef: { current: 0 }, historyRequestInFlightRef: { current: null as number | null },+ setLoadingEarlier: (value: boolean) => { state.historyLoading = value; },+ setHistoryError: (value: string | null) => { state.historyError = value; },+ };+ const coordinator = createRemoteSyncCoordinator(pageCallback('syncSession', bindings));+ coordinator.setContext('d1:s1:1');+ return { state, maker, store, bindings, coordinator, setError,+ sync: () => coordinator.request({ reason: 'manual' }),+ earlier: pageCallback('loadEarlierMessages', bindings),+ };+}++describe('production session recovery callbacks', () => {+ it('routes the visible history retry to pagination rather than full sync', () => {+ const screen = source.getFullText().replace(/\r\n/g, '\n');+ expect(screen).toContain('const bannerError = connectionRecoveryError ?? historyError;');+ expect(screen).toContain('const bannerRetriesHistory = connectionRecoveryError === null && historyError !== null;');+ expect(screen).toContain('requestErrorAutoRecovering={bannerRetriesHistory ? false : undefined}');+ expect(screen).toContain('loading={loading || loadingEarlier}');+ expect(screen).toMatch(/onSync=\{\(\) => bannerRetriesHistory\s+\? void loadEarlierMessages\(\)\s+: void requestSync\(/);+ const errorSources = screen.slice(screen.indexOf('const connectionError ='), screen.indexOf('const bannerError ='));+ expect(errorSources).not.toContain('historyError');+ });++ it.each([false, true])('keeps late history and pagination after projection rejects (reopen=%s)', async (reopen) => {+ const f = fixture(reopen);+ const history = deferred<typeof page>();+ f.maker.listMessages.mockReturnValue(history.promise);+ f.maker.input.getProjection.mockRejectedValue(new Error('[INVOKE_TIMEOUT] projection'));+ const result = f.sync();+ const rejected = expect(result).rejects.toThrow('projection');+ await tick();+ expect(f.state.loading).toBe(true);+ history.resolve(page);+ await rejected;+ expect(f.state.rows).toEqual(page.messages);+ expect(f.state.older).toBe(true);+ expect(f.state.syncError).toContain('projection');+ expect(f.state.readAck).toBeNull();+ expect(f.state.hold).not.toBeNull();+ f.maker.input.getProjection.mockResolvedValue({});+ await f.sync();+ expect(f.state.syncError).toBeNull();+ expect(f.state.hold).toBeNull();+ expect(f.state.readAck).toBe('s1:1');+ });++ it('shows a fetched cold page and its pagination even if metadata fails first', async () => {+ const f = fixture();+ const history = deferred<typeof page>();+ f.maker.listMessages.mockReturnValue(history.promise);+ f.maker.getSession.mockRejectedValue(new Error('[INVOKE_TIMEOUT] metadata'));+ const rejected = expect(f.sync()).rejects.toThrow('metadata');+ await tick();+ history.resolve(page);+ await rejected;+ expect(f.state.rows).toEqual(page.messages);+ expect(f.state.older).toBe(true);+ expect(f.store.markSessionMessagesSynced).not.toHaveBeenCalled();+ });++ it('restores pagination on unchanged reopen without waiting for a failed projection', async () => {+ const f = fixture(true);+ f.store.isSessionMessageWindowSynced.mockReturnValue(true);+ f.maker.input.getProjection.mockRejectedValue(new Error('[INVOKE_TIMEOUT] projection'));+ await expect(f.sync()).rejects.toThrow('projection');+ expect(f.state.older).toBe(true);+ expect(f.maker.listMessages).not.toHaveBeenCalled();+ expect(f.state.rows).toEqual([{ id: 'cached', clientId: 'cached' }]);+ expect(f.state.hold).not.toBeNull();+ });++ it('retains early progressive display while control state is pending', async () => {+ const f = fixture();+ const projection = deferred<object>();+ f.maker.input.getProjection.mockReturnValue(projection.promise);+ const result = f.sync();+ await tick();+ expect(f.state.rows).toEqual(page.messages);+ expect(f.state.older).toBe(true);+ expect(f.state.hold).not.toBeNull();+ expect(f.state.readAck).toBeNull();+ projection.resolve({});+ await result;+ expect(f.state.hold).toBeNull();+ });++ it.each(['clear-old', 'keep-new-identical', 'keep-deterministic'])('clears operation errors by occurrence: %s', async (scenario) => {+ const f = fixture();+ const message = scenario === 'keep-deterministic' ? '[NOT_FOUND] item' : '[INVOKE_TIMEOUT] send';+ f.setError(message);+ const projection = deferred<object>();+ f.maker.input.getProjection.mockReturnValue(projection.promise);+ const result = f.sync();+ await tick();+ expect(f.state.operation?.message).toBe(message);+ if (scenario === 'keep-new-identical') f.setError(message);+ projection.resolve({});+ await result;+ expect(f.state.operation?.message ?? null).toBe(scenario === 'clear-old' ? null : message);+ });++ it('does not commit a late page after coordinator context changes', async () => {+ const f = fixture();+ const history = deferred<typeof page>();+ f.maker.listMessages.mockReturnValue(history.promise);+ const result = f.sync();+ await tick();+ f.coordinator.setContext('d1:s2:1');+ history.resolve(page);+ await result;+ await tick();+ expect(f.state.rows).toEqual([]);+ expect(f.state.readAck).toBeNull();+ });++ it('retries a failed page locally without changing sync/operation errors or the hold', async () => {+ const f = fixture();+ f.state.hold = null;+ f.setError('[NOT_FOUND] unrelated operation');+ f.maker.listMessages.mockRejectedValueOnce(new Error('[INVOKE_TIMEOUT] history'));+ await f.earlier();+ expect(f.state.historyError).toContain('history');+ expect(f.state.operation?.message).toContain('unrelated');+ expect(f.state.syncError).toBeNull();+ expect(f.state.hold).toBeNull();+ const retry = deferred<typeof page>();+ f.maker.listMessages.mockReturnValue(retry.promise);+ const result = f.earlier();+ await f.earlier(); // Same-tick duplicate must not send a second page request.+ expect(f.state.historyLoading).toBe(true);+ expect(f.state.historyError).toContain('history');+ expect(f.maker.listMessages).toHaveBeenCalledTimes(2);+ retry.resolve(page);+ await result;+ expect(f.state.historyError).toBeNull();+ expect(f.state.historyLoading).toBe(false);+ expect(f.maker.getSession).not.toHaveBeenCalled();+ expect(f.maker.input.getProjection).not.toHaveBeenCalled();+ expect(f.maker.listMessages).toHaveBeenLastCalledWith('s1', { limit: 20, before: 'before-m1' });+ });++ it('does not let an old page failure clear a new request loading state', async () => {+ const f = fixture();+ const old = deferred<typeof page>();+ f.maker.listMessages.mockReturnValue(old.promise);+ const result = f.earlier();+ f.bindings.historyRequestSeqRef.current += 1; // The screen invalidates this synchronously on task switch.+ f.bindings.historyRequestInFlightRef.current = null;+ const next = deferred<typeof page>();+ f.maker.listMessages.mockReturnValue(next.promise);+ const newer = f.earlier();+ old.reject(new Error('[INVOKE_TIMEOUT] old page'));+ await result;+ expect(f.state.historyLoading).toBe(true);+ expect(f.state.historyError).toBeNull();+ next.resolve(page);+ await newer;+ expect(f.state.historyLoading).toBe(false);+ expect(f.store.mergeEarlierMessages).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/mobile/src/components/ConnectionBanner.tsx b/apps/mobile/src/components/ConnectionBanner.tsxindex 0aa12a9491..15ac3e048a 100644--- a/apps/mobile/src/components/ConnectionBanner.tsx+++ b/apps/mobile/src/components/ConnectionBanner.tsx@@ -69,6 +69,7 @@ export function ConnectionBanner({density = 'default',deviceUnresponsive = false,error,+ requestErrorAutoRecovering,issue = null,lastSyncedAt,onSync,@@ -81,6 +82,8 @@ export function ConnectionBanner({/** 当前关联设备熔断 open(电脑端未响应);relay 可能仍 online,单独入参 */deviceUnresponsive?: boolean;error: string | null;+ /** Request owners with local retry (e.g. history pagination) can opt out of connection recovery. */+ requestErrorAutoRecovering?: boolean;/** 连接层失败原因(useDeviceLink().connectionIssue);比请求级 error 更根因,优先展示 */issue?: DeviceLinkConnectionIssue | null;lastSyncedAt: number | null;@@ -105,7 +108,7 @@ export function ConnectionBanner({hasActiveIssue: activeIssue !== null,deviceUnresponsive: showUnresponsive,hasRequestError: friendlyError !== null,- requestErrorAutoRecovering: isAutoRecoveringRemoteError(effectiveError),+ requestErrorAutoRecovering: requestErrorAutoRecovering ?? isAutoRecoveringRemoteError(effectiveError),});const tone = activeIssue? 'off'diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsxindex 2495b6e1ee..400f0215d3 100644--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx@@ -6,6 +6,7 @@ import {DeviceLinkClient,DeviceLinkError,CONTROLLER_CAPABILITY_MAKER_EVENT_BATCH_V1,+ CONTROLLER_CAPABILITY_SESSION_TEXT_SNAPSHOT_V1,CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2,DL_SUBSCRIBE_CHANNEL,DL_UNSUBSCRIBE_CHANNEL,@@ -182,6 +183,7 @@ const DeviceLinkContext = createContext<DeviceLinkContextValue | null>(null);* 被控端按能力缺失降级)。被控端只在看到对应能力后才发送新 wire 形状。*/const CONTROLLER_CAPABILITIES = [+ CONTROLLER_CAPABILITY_SESSION_TEXT_SNAPSHOT_V1,CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2,// maker:event 微批:被控端把同一会话的连续事件合并成一帧,本端拆包后逐条消费// (见 remoteSessionStore 的 MAKER_EVENT_BATCH_CHANNEL 分支)。diff --git a/apps/mobile/src/device-link/invokeTimeouts.ts b/apps/mobile/src/device-link/invokeTimeouts.tsindex 5f06e2ab29..75d3bb0132 100644--- a/apps/mobile/src/device-link/invokeTimeouts.ts+++ b/apps/mobile/src/device-link/invokeTimeouts.ts@@ -47,6 +47,9 @@ import { INVOKE_TIMEOUT_OVERRIDES_MS } from '@cindy/device-link';* 新增合法慢通道优先登记协议契约表(桌面控制端共用),仅 mobile 特有差异放这里。*/export const MOBILE_INVOKE_TIMEOUT_OVERRIDES_MS: Record<string, number> = {+ // Even a small row count can contain one large message: the Android weak-link+ // regression took ~18s to deliver 200KB. Do not enqueue another copy at 15s.+ 'local-db:messages:list': 30_000,'device-link:media:fetch': 30_000,'device-link:voice:dictionary-learning': 30_000,'device-link:voice:transcribe': 30_000,diff --git a/apps/mobile/src/device-link/mobileMakerTransport.ts b/apps/mobile/src/device-link/mobileMakerTransport.tsindex 67447f47e2..5668ed6e9f 100644--- a/apps/mobile/src/device-link/mobileMakerTransport.ts+++ b/apps/mobile/src/device-link/mobileMakerTransport.ts@@ -687,7 +687,7 @@ export function createMobileMakerTransport({call('local-db:messages:around-client-id', [sessionId, clientId, opts]),send: (sessionId, message, createOpts, sendOpts) =>call('maker:send', [sessionId, message, createOpts, sendOpts]),- listActiveSessions: () => call('maker:list-active'),+ listActiveSessions: () => call('maker:list-active', [{ summary: true }]),setModel: async (sessionId, model, providerId, selection) => {const wireArgs = selection? [sessionId, model, providerId ?? null, null, selection]diff --git a/apps/mobile/src/device-link/sessionSnapshotSingleFlight.ts b/apps/mobile/src/device-link/sessionSnapshotSingleFlight.tsindex 70c893aee6..eb7dd9a8ff 100644--- a/apps/mobile/src/device-link/sessionSnapshotSingleFlight.ts+++ b/apps/mobile/src/device-link/sessionSnapshotSingleFlight.ts@@ -220,10 +220,20 @@ export async function readProgressiveMessageWindow<Metadata, History>(options: {const history = options.eager? messages(): metadata.then((value) => options.isCurrent() && options.shouldReadMessages(value) ? messages() : null);- const [metadataValue, historyValue] = await Promise.all([metadata, history]);+ const [metadataValue, historyValue] = await waitForIndependentSnapshotReads([metadata, history] as const);return { metadata: metadataValue, history: historyValue };}+/** Do not let one rejected read cancel still-useful siblings at the coordinator boundary. */+export async function waitForIndependentSnapshotReads<T extends readonly unknown[]>(+ reads: { [K in keyof T]: Promise<T[K]> },+): Promise<T> {+ const results = await Promise.allSettled(reads);+ const failure = results.find((result) => result.status === 'rejected');+ if (failure?.status === 'rejected') throw failure.reason;+ return results.map((result) => (result as PromiseFulfilledResult<unknown>).value) as unknown as T;+}+/** Apply each successful response immediately while retaining allSettled failure classification. */export async function settleProgressiveSnapshot<T>(read: Promise<T>,diff --git a/apps/mobile/src/session/historyWindowGap.ts b/apps/mobile/src/session/historyWindowGap.tsindex 115932f37c..167bf7bbd7 100644--- a/apps/mobile/src/session/historyWindowGap.ts+++ b/apps/mobile/src/session/historyWindowGap.ts@@ -39,7 +39,7 @@*/import { HISTORY_GAP_SPLIT_MS } from '@cindy/maker-shared/history-gap';-import { MESSAGE_PAGE_SIZE } from '@/session/messagePaging';+import { MESSAGE_FETCH_PAGE_SIZE } from '@/session/messagePaging';import type { RemoteMessage } from '@/session/types';/**@@ -87,10 +87,10 @@ export const HISTORY_GAP_MAX_CONSIDERED_PER_VISIT = 6;** 不能只按行数算预算:被控端结果帧超限时 `listMessagesWithPayloadRetry` 会一路降 limit,* device-link 侧还会静默裁行(`remoteRowsTrimmed`),那种分片每次只带回几行。若与行数共用一个- * 计数器,这类会话会在远未取到 400 行时就发出几十个请求。12 次是"5 个满页 + 若干降级页"的- * 保守上界,也兼作防死循环兜底。+ * 计数器,这类会话会在远未取到 400 行时就发出几十个请求。上限容纳 400 行的小网络页,+ * 再留 7 次探测/降级余量,仍有独立请求数边界兜底。*/-export const HISTORY_BACKFILL_MAX_REQUESTS = 12;+export const HISTORY_BACKFILL_MAX_REQUESTS = Math.ceil(HISTORY_BACKFILL_MAX_ROWS / MESSAGE_FETCH_PAGE_SIZE) + 7;/** 探测两行在服务端是否真的相邻时的页大小(只要一行就够,payload 最小)。 */export const HISTORY_GAP_PROBE_LIMIT = 1;@@ -252,7 +252,7 @@ export async function backfillHistoryWindowGap(let rows = probeRows;let requests = probeRequests;while (rows < HISTORY_BACKFILL_MAX_ROWS && requests < HISTORY_BACKFILL_MAX_REQUESTS) {- const page = await deps.listPage(before, MESSAGE_PAGE_SIZE);+ const page = await deps.listPage(before, MESSAGE_FETCH_PAGE_SIZE);if (deps.isCancelled()) return 'cancelled';requests += 1;if (page.length === 0) return 'exhausted';diff --git a/apps/mobile/src/session/messagePaging.ts b/apps/mobile/src/session/messagePaging.tsindex 07b7993264..55f014cb7b 100644--- a/apps/mobile/src/session/messagePaging.ts+++ b/apps/mobile/src/session/messagePaging.ts@@ -1,12 +1,15 @@import type { RemoteMessage, RemoteSession } from '@/session/types';export const MESSAGE_PAGE_SIZE = 80;-export const MESSAGE_PAGE_RETRY_LIMITS = [80, 40, 20, 10, 5, 1] as const;+// Keep the cache window independent of the wire page. On a slow mobile link an+// 80-row page can occupy the reliable stream past the request deadline.+export const MESSAGE_FETCH_PAGE_SIZE = 20;+export const MESSAGE_PAGE_RETRY_LIMITS = [MESSAGE_FETCH_PAGE_SIZE, 10, 5, 1] as const;export function latestMessageCursor(messages: readonly RemoteMessage[]): string | null {let latest: RemoteMessage | null = null;for (const message of messages) {- if (!message.id || message.id.startsWith('mobile-system-')) continue;+ if (!isHostMessageRow(message)) continue;if (!latest || compareMessageOrder(message, latest) > 0) latest = message;}return latest?.id ?? null;@@ -15,10 +18,9 @@ export function latestMessageCursor(messages: readonly RemoteMessage[]): stringexport function oldestMessageCursor(messages: readonly RemoteMessage[]): string | null {let oldest: RemoteMessage | null = null;for (const message of messages) {- // Skip locally-appended system cards (synthetic `mobile-system-…` id, see- // remoteSessionStore.appendLocalSystemCard): they aren't real host rows, so handing one to- // the host as a `before` cursor matches nothing and re-fetches the latest page (no progress).- if (!message.id || message.id.startsWith('mobile-system-')) continue;+ // Local system cards and in-flight stream rows have no persisted host ID.+ // Sending either as `before` can fetch the latest page again without progress.+ if (!isHostMessageRow(message)) continue;if (!oldest || compareMessageOrder(message, oldest) < 0) {oldest = message;}@@ -237,7 +239,7 @@ export function shouldRefreshLatestMessageWindowOnReopen(input: {* `hasOlderMessages` state 重置为 false,不补设就会丢失「加载更早」入口 —— 这是回归)。* 优先用服务端总数 `_count.messages` 与 in-store 已加载真实消息数比较(总数 > 已加载 → 还有更早);* 服务端没给总数时退化为窗口启发式(已加载到整页边界 → 推断还有更早)。- * 计数排除本地合成的 system 卡(`mobile-system-` 前缀,非真实 host 行)。+ * 计数排除本地 system 卡与尚未落盘的流式行,与服务端持久消息总数保持同一口径。*/export function hasOlderMessagesAfterReopen(totalCount: number | undefined,@@ -268,7 +270,7 @@ export function hasOlderMessagesByServerCount(function countRealMessages(messages: readonly RemoteMessage[]): number {let count = 0;for (const message of messages) {- if (!message.id || message.id.startsWith('mobile-system-')) continue;+ if (!isHostMessageRow(message)) continue;count += 1;}return count;diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.tsindex a1815b2d54..45dfba018c 100644--- a/apps/mobile/src/session/remoteSessionStore.ts+++ b/apps/mobile/src/session/remoteSessionStore.ts@@ -11,6 +11,7 @@ import {import {MAKER_EVENT_BATCH_CHANNEL,SESSION_ACTIVITY_CHANNEL,+ SESSION_SYNC_CHANNEL,expandMakerEventBatchPayload,type SessionActivityPayload,} from '@cindy/device-link';@@ -484,6 +485,10 @@ function coverLatestPage(function coverEarlierPage(sessionId: string, pageOldest: string, joinsAt: string | undefined): void {const current = sessionWindowCoverage.get(sessionId);if (current) {+ // A page before an unverified cache island cannot bridge that island to a+ // newer verified window. Only extend coverage through an anchor inside it.+ if (!joinsAt || joinsAt.localeCompare(current.since) < 0+ || joinsAt.localeCompare(current.until) > 0) return;if (pageOldest.localeCompare(current.since) < 0) {sessionWindowCoverage.set(sessionId, { ...current, since: pageOldest });}@@ -2436,6 +2441,13 @@ function applyRemoteTextEvent(const data = isRecord(event.data) ? event.data : null;const text = typeof data?.text === 'string' ? data.text : '';const isFinal = data?.isFinal === true;+ // Legacy hosts already send isFullText on final events. Keep their existing+ // reconciliation semantics; only the new in-flight snapshot replaces text.+ const isFullText = data?.isFullText === true && !isFinal;+ const snapshotCreatedAt = isFullText && !isFinal && typeof data?.createdAt === 'string'+ && Number.isFinite(Date.parse(data.createdAt))+ ? new Date(data.createdAt).toISOString()+ : undefined;if (!text) return false;const authoritativeDeviceId = authoritativeSessionDeviceId(sessionId);@@ -2495,6 +2507,8 @@ function applyRemoteTextEvent(const matchedExistingIsPersisted = matchedExisting !== undefined&& !matchedExistingIsPending&& isPersistedAssistantMessage(matchedExisting);+ // A DB row is stronger than an earlier subscription snapshot still in flight.+ if (isFullText && matchedExistingIsPersisted) return clientIdResolution.changed;const rejectsNonAuthoritativeTransportReplay = deviceId !== undefined&& authoritativeDeviceId !== undefined&& deviceId !== authoritativeDeviceId@@ -2579,7 +2593,9 @@ function applyRemoteTextEvent(}const currentText = existing ? contentToPreview(existing.content) : '';- const nextText = isFinal+ const nextText = isFullText && !hasDeviceLinkTruncationMarker(event) && !hasDeviceLinkTruncationMarker(data)+ ? text+ : isFinal? (finalTextWasTruncated && existing? currentText: existing && currentText@@ -2598,7 +2614,7 @@ function applyRemoteTextEvent(? { ...(existing?.agentMeta ?? {}), ...event.agentMeta }: existing?.agentMeta);const hostCreatedAtAnchor = existing ? undefined : liveRowCreatedAtAnchor(sessionId);- const needsHostAnchor = existing+ const needsHostAnchor = snapshotCreatedAt ? false : existing? [existing.id, existing.clientId, clientId].some((id) => (Boolean(id) && pendingHostAnchorLiveAssistantClientIds.get(sessionId)?.has(id) === true))@@ -2606,6 +2622,9 @@ function applyRemoteTextEvent(const hostAnchorIdentity = existing? pendingHostAnchorIdentity(sessionId, existing.id, existing.clientId, clientId): resetHostAnchorIdentity;+ // A subscription snapshot knows the block's real host time. An earlier+ // provisional row may be anchored to old history, so repair its position too.+ const changesCreatedAt = snapshotCreatedAt !== undefined && snapshotCreatedAt !== existing?.createdAt;const changed = upsertMessage(sessionId, {id: existing?.id ?? clientId,clientId,@@ -2617,14 +2636,14 @@ function applyRemoteTextEvent(// 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(+ createdAt: snapshotCreatedAt ?? existing?.createdAt ?? clampLiveRowCreatedAt(new Date().toISOString(),hostCreatedAtAnchor?.createdAt,),}, {knownIndex: matchedExistingIndex,- preserveOrderOnReplace: true,- preserveStructureOnReplace: !isFinal && existing !== undefined,+ preserveOrderOnReplace: !changesCreatedAt,+ preserveStructureOnReplace: !isFinal && existing !== undefined && !changesCreatedAt,});if (resetsTransportAssembly && !changed) {forgetPendingLiveAssistantMessageIdentity(@@ -2637,6 +2656,15 @@ function applyRemoteTextEvent(if (changed || resetsTransportAssembly) {rememberPendingLiveAssistantClientId(sessionId, clientId);}+ if (snapshotCreatedAt) {+ // An identical snapshot can make upsert a no-op. Its authoritative time+ // still retires any provisional anchor, without retiring the live identity.+ const anchors = pendingHostAnchorLiveAssistantClientIds.get(sessionId);+ for (const id of [existing?.id, existing?.clientId, clientId]) {+ if (id) anchors?.delete(id);+ }+ if (anchors?.size === 0) pendingHostAnchorLiveAssistantClientIds.delete(sessionId);+ }// 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.@@ -2663,7 +2691,8 @@ function applyRemoteTextEvent(function isRemoteTextDeltaEvent(event: Record<string, unknown>): boolean {if (readString(event, 'type') !== 'text') return false;const data = isRecord(event.data) ? event.data : null;- return typeof data?.text === 'string' && data.text.length > 0 && data.isFinal === false;+ return typeof data?.text === 'string' && data.text.length > 0 && data.isFinal === false+ && data.isFullText !== true;}function enqueueRemoteTextDelta(@@ -3312,6 +3341,15 @@ export const remoteSessionStore = {const latestOldestCreatedAt = latestWindow[0].createdAt;const latestNewestCreatedAt = latestWindow[latestWindow.length - 1].createdAt;+ const currentCoverage = sessionWindowCoverage.get(sessionId);+ if (currentCoverage && latestNewestCreatedAt.localeCompare(currentCoverage.since) < 0) {+ // Concurrent latest reads (detail + reconnect) can finish in reverse order.+ // An entirely older page cannot describe the current tail. Joining it to+ // retained newer rows, then trusting live pushes, would certify the gap.+ // Rewind/clear invalidates coverage explicitly, so it does not use this path.+ if (textFlushed || projectionSettled) emit();+ return;+ }// 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.@@ -3500,6 +3538,9 @@ export const remoteSessionStore = {consumePendingRefresh(sessionId: string): boolean {if (!pendingRefreshSessions.has(sessionId)) return false;pendingRefreshSessions.delete(sessionId);+ // A history read already in flight when the dirty push arrived may have+ // reinstalled its older marker. The queued repair must still read history.+ sessionMessageSyncMarkers.delete(sessionId);return true;},@@ -3555,15 +3596,23 @@ export const remoteSessionStore = {mergeEarlierMessages(sessionId: string,list: readonly RemoteMessage[],- options: SessionMessageWriteOptions = {},- ): void {- if (retentionForSession(sessionId) === 'schedule') return;- if (!messageWriteAllowed(sessionId, options.authority)) return;+ options: SessionMessageWriteOptions & { before?: string } = {},+ ): boolean {+ if (retentionForSession(sessionId) === 'schedule') return false;+ if (!messageWriteAllowed(sessionId, options.authority)) return false;+ const current = messages.get(sessionId) ?? emptyMessages;+ const anchor = options.before ? current.find((row) => row.id === options.before) : undefined;+ // A latest-window refresh can remove the request's anchor without changing+ // detail authority. Joining that old page to the NEW oldest row invents a+ // contiguous interval across missing history. Let the caller retry from the+ // current window instead, and do not let a stale empty page close pagination.+ if (options.before && !anchor) return false;// 合并前窗口的最旧行 = 这一页接上的那一行,尚无结论时它就是区间上界(见 coverEarlierPage)。- const joinsAt = oldestCreatedAt(messages.get(sessionId) ?? emptyMessages);+ const joinsAt = anchor?.createdAt ?? oldestCreatedAt(current);this.mergeMessages(sessionId, list, options);const pageOldest = oldestCreatedAt(list);if (pageOldest) coverEarlierPage(sessionId, pageOldest, joinsAt);+ return true;},appendMessage(@@ -4065,6 +4114,19 @@ export const remoteSessionStore = {},applyRemotePush(deviceId: string, channel: string, payload: unknown): void {+ if (channel === SESSION_SYNC_CHANNEL && isRecord(payload)) {+ const sessionId = readString(payload, 'sessionId');+ if (!sessionId) return;+ if (isRecord(payload.event)) this.applyRemotePush(deviceId, 'maker:event', payload);+ if (payload.resyncRequired === true) {+ sessionMessageSyncMarkers.delete(sessionId);+ forgetWindowCoverage(sessionId);+ pendingRefreshSessions.add(sessionId);+ bumpMessageVersion(sessionId);+ emit();+ }+ return;+ }if (channel === SESSION_ACTIVITY_CHANNEL) {this.applySessionActivity(deviceId, payload);return;diff --git a/apps/mobile/src/session/sessionMessageWindowSync.ts b/apps/mobile/src/session/sessionMessageWindowSync.tsnew file mode 100644index 0000000000..ec09a1c6e6--- /dev/null+++ b/apps/mobile/src/session/sessionMessageWindowSync.ts@@ -0,0 +1,40 @@+import {+ shouldRefreshLatestMessageWindowOnReopen,+ type MessagePageRetryResult,+} from '@/session/messagePaging';+import type { RemoteSession } from '@/session/types';+import { readProgressiveMessageWindow } from '@/device-link/sessionSnapshotSingleFlight';++interface SessionMessageWindowSync {+ isReopen: boolean;+ eager?: boolean;+ storedSession: RemoteSession | null;+ readMetadata(): Promise<RemoteSession>;+ readLatest(): Promise<MessagePageRetryResult>;+ isCurrent(): boolean;+ isWindowSynced(session: RemoteSession): boolean;+ commitMessages?(page: MessagePageRetryResult): void;+ commit(session: RemoteSession, page: MessagePageRetryResult | null): void;+}++/**+ * History owns its read/commit independently of pending-interaction and input+ * snapshots. A failed projection must not discard a fetched page or prevent a+ * reopened task from checking its history. Full sync/dispatch readiness is+ * still decided by the caller after all resources succeed.+ */+export async function syncSessionMessageWindow(input: SessionMessageWindowSync): Promise<void> {+ const { metadata: session, history: page } = await readProgressiveMessageWindow({+ readMetadata: input.readMetadata,+ readMessages: input.readLatest,+ eager: input.eager ?? !input.isReopen,+ isCurrent: input.isCurrent,+ shouldReadMessages: (metadata) => shouldRefreshLatestMessageWindowOnReopen({+ freshSession: metadata,+ storedSession: input.storedSession,+ messageWindowSynced: input.isWindowSynced(metadata),+ }),+ commitMessages: (history) => input.commitMessages?.(history),+ });+ if (input.isCurrent()) input.commit(session, page);+}diff --git a/apps/mobile/src/session/sessionSyncErrorRecovery.ts b/apps/mobile/src/session/sessionSyncErrorRecovery.tsnew file mode 100644index 0000000000..ee427cd323--- /dev/null+++ b/apps/mobile/src/session/sessionSyncErrorRecovery.ts@@ -0,0 +1,15 @@+import { isAutoRecoveringRemoteError } from '@/device-link/remoteStatus';++/** A new object for every error occurrence, even when the text repeats. */+export interface SessionOperationError {+ message: string;+}++export function shouldClearOperationErrorAfterSync(+ current: SessionOperationError | null,+ atSyncStart: SessionOperationError | null,+): boolean {+ return current !== null+ && current === atSyncStart+ && isAutoRecoveringRemoteError(current.message);+}diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.tsindex 9625455d73..bcc86819bc 100644--- a/packages/device-link/src/__tests__/client.test.ts+++ b/packages/device-link/src/__tests__/client.test.ts@@ -378,6 +378,77 @@ function makeRelayClient(}describe('DeviceLinkClient', () => {+ it('gives hello/ack a full window after a slow but successful socket upgrade', async () => {+ vi.useFakeTimers();+ const h = makeHarness({ timing: { handshakeTimeoutMs: 15, pingIntervalMs: 60_000 } });+ try {+ h.client.start();+ await vi.advanceTimersByTimeAsync(0);+ const socket = h.current();+ await vi.advanceTimersByTimeAsync(12);+ socket.emit('open');+ await vi.advanceTimersByTimeAsync(12);+ expect(socket.terminated).toBe(false);+ socket.push({ v: PROTOCOL_VERSION, kind: 'hello-ack', payload: {+ serverProtocolVersion: PROTOCOL_VERSION, deviceId: 'dev-self', userId: 'u1',+ } });+ await vi.advanceTimersByTimeAsync(20);+ expect(h.client.getStatus()).toBe('online');+ expect(h.sockets).toHaveLength(1);+ } finally {+ h.client.stop();+ vi.useRealTimers();+ }+ });++ it('backs off large response copies for a slow controller without blocking a healthy controller', async () => {+ vi.useFakeTimers();+ const h = makeHarness({ timing: { pingIntervalMs: 60_000, requestTimeoutMs: 60_000 } });+ try {+ h.client.start();+ await vi.advanceTimersByTimeAsync(0);+ const socket = h.current();+ socket.ack();+ for (const peer of ['ctrl-slow', 'ctrl-healthy']) {+ const opening = establishInboundReliableLink(h, `${peer}-stream`, 1, peer);+ await vi.advanceTimersByTimeAsync(0);+ await opening;+ }+ const acknowledge = (peer: string, id: string) => {+ const frame = socket.sent.find(e => e.kind === 'invoke-result' && e.id === id)!;+ const meta = parseTransportPayload(frame.payload)!.meta;+ socket.push({ v: PROTOCOL_VERSION, kind: 'push', src: peer, payload: {+ channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL,+ payload: { streamId: meta.streamId, ackSeq: meta.seq },+ } });+ };+ h.client.sendInvokeResult('ctrl-slow', 'large', { ok: true, result: 'x'.repeat(240_000) });+ const copies = () => socket.sent.filter(e => e.kind === 'invoke-result' && e.id === 'large');+ const firstBytes = copies().reduce((sum, e) => sum + JSON.stringify(e).length, 0);+ expect(copies()).toHaveLength(2);+ // The local socket is drained, but the downstream controller needs ten seconds.+ expect(socket.bufferedAmount).toBe(0);+ await vi.advanceTimersByTimeAsync(9_999);+ expect(copies()).toHaveLength(2); // The first two segments are still in transit.+ h.client.sendInvokeResult('ctrl-healthy', 'healthy', { ok: true, result: 'ok' });+ acknowledge('ctrl-healthy', 'healthy');+ expect(h.client.getReliableSendQueueDepth('ctrl-healthy')).toBe(0);+ expect(h.client.isLinkReady('ctrl-healthy')).toBe(true);+ await vi.advanceTimersByTimeAsync(1);+ acknowledge('ctrl-slow', 'large');+ await vi.advanceTimersByTimeAsync(30_000);+ expect(copies()).toHaveLength(2);+ expect(copies().reduce((sum, e) => sum + JSON.stringify(e).length, 0)).toBe(firstBytes);+ expect(h.client.getReliableSendQueueDepth('ctrl-slow')).toBe(0);+ expect(h.client.isLinkReady('ctrl-slow')).toBe(true);+ expect(h.sockets).toHaveLength(1);+ expect(socket.terminated).toBe(false);+ } finally {+ h.client.stop();+ vi.useRealTimers();+ }+ });+it('start → open 后第一帧是 hello,hello-ack 后 online', async () => {const h = makeHarness();const statuses: string[] = [];@@ -1002,7 +1073,7 @@ describe('DeviceLinkClient', () => {h.client.stop();});- it('≥2 控制端共享同一被控端:一个停止 ACK 只复位该 peer,邻居 link 与在途请求零感知', async () => {+ it.each([16, 300 * 1024])('≥2 控制端共享同一被控端:停止 ACK 的 %i 字节响应只复位该 peer,邻居零感知', async (bytes) => {// 故障半径要求的拓扑是「多个控制端共用一台被控桌面」,不是「一个控制端连两台桌面」。// 本用例站在被控 Desktop:ctrl-silent 永不 ACK,ctrl-healthy 的在途 invoke 必须仍能完成,// 且共享 WSS 不得被拆掉。@@ -1029,7 +1100,7 @@ describe('DeviceLinkClient', () => {const socket = h.current();const socketCount = h.sockets.length;- h.client.sendInvokeResult('ctrl-silent', 'silent-req', { ok: true, result: ['silent'] });+ h.client.sendInvokeResult('ctrl-silent', 'silent-req', { ok: true, result: 's'.repeat(bytes) });h.client.sendInvokeResult('ctrl-healthy', 'healthy-inflight', { ok: true, result: ['healthy'] });const healthyFrame = socket.sent.filter((env) => env.kind === 'invoke-result' && env.dst === 'ctrl-healthy')@@ -4365,6 +4436,28 @@ describe('DeviceLinkClient', () => {h.client.stop();});+ it.each([1, 9, 11, 19])('last valid frame at %sms receives the full heartbeat idle budget', async (offset) => {+ vi.useFakeTimers();+ const h = makeHarness({ timing: { pingIntervalMs: 10, pongMissLimit: 1 } });+ try {+ h.client.start();+ await vi.advanceTimersByTimeAsync(1);+ const ws = h.current();+ ws.ack();+ await vi.advanceTimersByTimeAsync(offset);+ ws.push({ v: PROTOCOL_VERSION, kind: 'pong' });+ await vi.advanceTimersByTimeAsync(19);+ expect(ws.terminated).toBe(false);+ expect(h.client.getStatus()).toBe('online');+ // Still bounded: the first heartbeat tick after two full idle periods closes it.+ await vi.advanceTimersByTimeAsync(11);+ expect(ws.terminated).toBe(true);+ } finally {+ h.client.stop();+ vi.useRealTimers();+ }+ });+it('pong 持续回应则不判僵死', async () => {const h = makeHarness({ timing: { pingIntervalMs: 8, pongMissLimit: 1 } });h.client.start();@@ -6621,7 +6714,148 @@ describe('定时重发的单趟预算(TRANSPORT_RETRY_PASS_BUDGET)', () => {}}- it('对端停止 ACK 时,一趟定时重发只发预算内的最旧几条(而不是整个窗口)', async () => {+ it('a large response delivered after 18s is not duplicated while waiting for its first ACK', async () => {+ await withFakeTimers(async (h, advance) => {+ h.client.sendInvokeResult('dev-b', 'slow-page', { ok: true, result: 'x'.repeat(200 * 1024) });+ const ws = h.current();+ const first = ws.sent.find((env) => env.kind === 'invoke-result')!;+ const meta = parseTransportPayload(first.payload)!.meta;+ await advance(18_000);+ expect([...sendsBySeq(ws).values()]).toEqual([1]);+ ws.push({+ v: PROTOCOL_VERSION,+ kind: 'push',+ src: 'dev-b',+ payload: {+ channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL,+ payload: { streamId: meta.streamId, ackSeq: meta.seq },+ },+ });+ await advance(40_000);+ expect([...sendsBySeq(ws).values()]).toEqual([1]);+ expect(h.client.getReliableSendQueueDepth('dev-b')).toBe(0);+ expect(ws.closed).toBeNull();+ }, { pingIntervalMs: 600_000, transportRetryIntervalMs: 2_000 });+ });++ it('retries an eligible small request while a large head frame is cooling down', async () => {+ await withFakeTimers(async (h, advance) => {+ h.client.sendInvokeResult('dev-b', 'slow-page', { ok: true, result: 'x'.repeat(200 * 1024) });+ h.client.sendInvokeResult('dev-b', 'small-request', { ok: true, result: 'ok' });+ const ws = h.current();+ const seqs = [...sendsBySeq(ws).keys()].sort((a, b) => a - b);+ expect(seqs).toHaveLength(2);++ // The large head waits for its byte-based interval (~26s), but the+ // small tail is eligible on the first retry tick and must not be starved.+ await advance(2_000);+ expect(retriedSeqs(sendsBySeq(ws))).toEqual([seqs[1]]);+ }, { pingIntervalMs: 600_000, transportRetryIntervalMs: 2_000 });+ }, 10_000);++ it('a small tail cannot reset a slow large head after 35s without ACK or disturb another peer', async () => {+ await withFakeTimers(async (h, advance) => {+ const resets = vi.fn();+ h.client.onPeerTransportReset(resets);+ const healthyLink = establishInboundReliableLink(h, 'healthy-stream', 1, 'dev-healthy');+ await advance(1);+ await healthyLink;+ const ws = h.current();+ h.client.sendInvokeResult('dev-b', 'slow-page', { ok: true, result: 'x'.repeat(200 * 1024) });+ h.client.sendInvokeResult('dev-b', 'small-request', { ok: true, result: 'ok' });+ const seqs = [...sendsBySeq(ws).keys()].sort((a, b) => a - b);+ const healthyRequest = h.client.invoke('dev-healthy', { channel: 'maker:healthy', args: [] }, 60_000);+ void healthyRequest.catch(() => {});+ const healthyFrame = ws.sent.find((env) => env.kind === 'invoke' && env.dst === 'dev-healthy')!;+ const healthyMeta = parseTransportPayload(healthyFrame.payload)!.meta;+ ws.push({+ v: PROTOCOL_VERSION, kind: 'push', src: 'dev-healthy',+ payload: { channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL, payload: {+ streamId: healthyMeta.streamId, ackSeq: healthyMeta.seq,+ } },+ });++ await advance(25_999);+ expect(sendsBySeq(ws).get(seqs[0])).toBe(1);+ await advance(9_001);+ // The existing 26s size budget permits one head retry, not an early+ // reset/replay. The tail's cumulative ACK is still blocked by that head.+ expect(resets).not.toHaveBeenCalled();+ expect(h.client.isLinkReady('dev-b')).toBe(true);+ expect(h.client.isLinkReady('dev-healthy')).toBe(true);+ expect(ws.sent.filter((env) => env.kind === 'link-close')).toHaveLength(0);+ expect(sendsBySeq(ws).get(seqs[0])).toBe(2);+ expect(sendsBySeq(ws).get(seqs[1])).toBe(2);+ ws.push({ v: PROTOCOL_VERSION, kind: 'invoke-result', src: 'dev-healthy',+ id: healthyFrame.id, payload: { ok: true, result: 'healthy' } });+ await expect(healthyRequest).resolves.toEqual({ ok: true, result: 'healthy' });++ // A genuinely silent head must still exhaust its own bounded budget.+ await advance(100_000);+ expect(resets).toHaveBeenCalledTimes(1);+ expect(resets.mock.calls[0][0]).toMatchObject({ deviceId: 'dev-b', seq: seqs[0] });+ expect(h.client.isLinkReady('dev-healthy')).toBe(true);+ expect(ws.closed).toBeNull();+ expect(h.sockets).toHaveLength(1);+ }, { pingIntervalMs: 600_000, transportRetryIntervalMs: 2_000 });+ });++ it.each([true, false])('a small tail resumes bounded retries after its large head is acknowledged (tail ACK=%s)', async (ackTail) => {+ await withFakeTimers(async (h, advance) => {+ const resets = vi.fn();+ h.client.onPeerTransportReset(resets);+ h.client.sendInvokeResult('dev-b', 'slow-page', { ok: true, result: 'x'.repeat(200 * 1024) });+ h.client.sendInvokeResult('dev-b', 'small-request', { ok: true, result: 'ok' });+ const ws = h.current();+ const first = ws.sent.find((env) => env.kind === 'invoke-result')!;+ const meta = parseTransportPayload(first.payload)!.meta;+ const seqs = [...sendsBySeq(ws).keys()].sort((a, b) => a - b);+ await advance(35_000);+ expect(resets).not.toHaveBeenCalled();+ ws.push({ v: PROTOCOL_VERSION, kind: 'push', src: 'dev-b',+ payload: { channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL, payload: {+ streamId: meta.streamId, ackSeq: seqs[0],+ } } });+ await advance(2_000);+ expect(sendsBySeq(ws).get(seqs[1])).toBe(3);+ if (ackTail) {+ ws.push({ v: PROTOCOL_VERSION, kind: 'push', src: 'dev-b',+ payload: { channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL, payload: {+ streamId: meta.streamId, ackSeq: seqs[1],+ } } });+ }+ await advance(35_000);+ if (ackTail) {+ expect(h.client.getReliableSendQueueDepth('dev-b')).toBe(0);+ expect(resets).not.toHaveBeenCalled();+ } else {+ expect(resets).toHaveBeenCalledTimes(1);+ expect(resets.mock.calls[0][0]).toMatchObject({ deviceId: 'dev-b', seq: seqs[1] });+ }+ expect(ws.closed).toBeNull();+ }, { pingIntervalMs: 600_000, transportRetryIntervalMs: 2_000 });+ });++ it.each([1, 2])('a small tail respects a retry limit of %s behind a large head', async (transportMaxRetryAttempts) => {+ await withFakeTimers(async (h, advance) => {+ const resets = vi.fn();+ h.client.onPeerTransportReset(resets);+ h.client.sendInvokeResult('dev-b', 'slow-page', { ok: true, result: 'x'.repeat(200 * 1024) });+ h.client.sendInvokeResult('dev-b', 'small-request', { ok: true, result: 'ok' });+ const ws = h.current();+ const seqs = [...sendsBySeq(ws).keys()].sort((a, b) => a - b);+ await advance(25_999);+ expect(resets).not.toHaveBeenCalled();+ expect(sendsBySeq(ws).get(seqs[0])).toBe(1);+ expect(sendsBySeq(ws).get(seqs[1])).toBe(transportMaxRetryAttempts);+ await advance(30_001);+ expect(resets).toHaveBeenCalledTimes(1);+ expect(resets.mock.calls[0][0]).toMatchObject({ deviceId: 'dev-b', seq: seqs[0] });+ expect(ws.closed).toBeNull();+ }, { pingIntervalMs: 600_000, transportRetryIntervalMs: 2_000, transportMaxRetryAttempts });+ });++ it('队头冷却时仍允许后续小请求重传', async () => {// 2026-08-08 线上:一趟重发遍历整个 pending 窗口(上限 64 条)、同步全部写进 ws,// 对端 relay 路由已失效时逐帧弹回 DEVICE_OFFLINE —— 单簇 213 条就是这个形状。// 既有两道刹车都拦不住本趟:per-peer 制动要等 relay-error 回来(异步),ws 容量@@ -6639,9 +6873,12 @@ describe('定时重发的单趟预算(TRANSPORT_RETRY_PASS_BUDGET)', () => {await advance(200);expect(retriedSeqs(sendsBySeq(ws))).toEqual(seqs.slice(0, 3));- // 再一趟:对端仍未 ACK,预算继续压在同样的队头 3 条上(不铺满窗口)+ // 后续小帧不再被队头冷却冻结;本趟预算继续限制单趟发送量。+ await advance(200);+ expect(retriedSeqs(sendsBySeq(ws))).toEqual(seqs.slice(0, 6));+ expect(seqs.slice(0, 3).map((seq) => sendsBySeq(ws).get(seq))).toEqual([2, 2, 2]);+ // 队头继续按退避间隔重发,后续序号则可独立获得重试机会。await advance(200);- expect(retriedSeqs(sendsBySeq(ws))).toEqual(seqs.slice(0, 3));const headCounts = seqs.slice(0, 3).map((seq) => sendsBySeq(ws).get(seq));expect(headCounts).toEqual([3, 3, 3]); // 首发 + 两趟重发}, {@@ -6708,7 +6945,8 @@ describe('定时重发的单趟预算(TRANSPORT_RETRY_PASS_BUDGET)', () => {// 预算 4 帧、每条 3 片:队头那条发完(3 帧)后,第二条会超预算 → 发送前就被拦下,// 留到下一趟。所以本趟只重发队头 1 条、只写出 3 帧。const framesBefore = framesSent(ws);- await advance(200);+ // Large messages first receive a bounded transmission budget (15 ticks).+ await advance(3_000);const retried = retriedSeqs(sendsBySeq(ws));expect(retried).toEqual([seqs[0]]);// 本趟真实写出的帧数不超过 max(预算, 队头分片数) —— 这才是「上限」的准确表述@@ -6733,14 +6971,9 @@ describe('定时重发的单趟预算(TRANSPORT_RETRY_PASS_BUDGET)', () => {}const ws = h.current();const seqs = [...sendsBySeq(ws).keys()].sort((a, b) => a - b);- const framesBefore = framesSent(ws);-- await advance(200);- // 只有队头那条大消息被重发,5 条小消息一条都没被带出去- expect(retriedSeqs(sendsBySeq(ws))).toEqual([seqs[0]]);- // 溢出被限制在「队头这一条的分片数」内,而不是预算 + 队头- const passFrames = framesSent(ws) - framesBefore;- expect(passFrames).toBeLessThanOrEqual(6);+ await advance(3_000);+ // 队头仍受分片预算约束;小消息不会因队头冷却而饥饿。+ expect(retriedSeqs(sendsBySeq(ws))).toEqual(seqs);}, {pingIntervalMs: 600_000,transportRetryIntervalMs: 200,diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.tsindex ec05c046b1..7d25c77ddf 100644--- a/packages/device-link/src/allowlist.ts+++ b/packages/device-link/src/allowlist.ts@@ -18,7 +18,7 @@* 双层校验:控制端发送前(快速失败)+ 被控端执行前(权威)。* 新增 channel 不进表即天然不可远程调用(代码保证确定性)。*/-import { SESSION_ACTIVITY_CHANNEL } from './topics.js';+import { SESSION_ACTIVITY_CHANNEL, SESSION_SYNC_CHANNEL } from './topics.js';/*** 订阅控制帧 channel(控制端 → 被控端,push 驱动):注册 / 注销对某 topic 的变更推送。@@ -583,6 +583,7 @@ export const PUSH_FORWARD_ALLOWLIST: ReadonlySet<string> = new Set(['local-db:sessions:created','local-db:sessions:patched',SESSION_ACTIVITY_CHANNEL,+ SESSION_SYNC_CHANNEL,'local-db:messages:created','local-db:messages:deleted',// 被控端 terminal error 落库脏信号:控制端据此把已加载历史的远程会话标脏,下次打开重拉。diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.tsindex 3a9ed5516d..910ac6b299 100644--- a/packages/device-link/src/client.ts+++ b/packages/device-link/src/client.ts@@ -108,6 +108,11 @@ const HANDSHAKE_TIMEOUT_WIDEN_AFTER = 2;/** 「link 未就绪收到可靠帧」通知的 per-peer 节流(见 onReliableFrameBeforeLink)。 */const STALE_LINK_NOTIFY_THROTTLE_MS = 30_000;const SLOW_REQUEST_WARN_MS = 1_000;+// Allow slow relay -> controller delivery before duplicating an entire message.+// With the default 2s tick this allows 8KiB/s, capped at 30s per attempt. Small+// messages retain their existing retry cadence; dead peers still exhaust retries.+const RELIABLE_RETRY_BYTES_PER_INTERVAL = 16 * 1024;+const RELIABLE_RETRY_MAX_SIZE_INTERVALS = 15;/** 连续三次握手成功后仍没撑过稳定期,才把普通抖动升级为可见问题。 */const SHORT_LIVED_STREAK_LIMIT = 3;const MAX_LEGACY_INBOUND_FRAMES = 128;@@ -1615,6 +1620,9 @@ export class DeviceLinkClient {ws.on('open', () => {if (epoch !== this.connEpoch) return;+ // TCP/TLS upgrade made progress. Give hello/ack its own bounded RTT window;+ // a slow upgrade must not consume almost all of the application handshake budget.+ this.armHandshakeTimeout(epoch);// 进站第一帧必须是 hellothis.sendEnvelope({ v: PROTOCOL_VERSION, kind: 'hello', payload: this.opts.getHello() });});@@ -1787,7 +1795,11 @@ export class DeviceLinkClient {this.pongMisses = 0;}this.pongMisses++;- if (this.pongMisses > this.timing.pongMissLimit) {+ // Timer phase must not shorten the idle budget after a valid frame.+ // Keep the missed-ping gate too: a delayed JS timer alone is not evidence+ // that multiple probes actually went unanswered.+ const idleBudgetMs = this.timing.pingIntervalMs * (this.timing.pongMissLimit + 1);+ if (this.pongMisses > this.timing.pongMissLimit && now - this.lastInboundAt >= idleBudgetMs) {this.log.warn(`heartbeat lost, forcing reconnect (misses=${this.pongMisses}, idleForMs=${now - this.lastInboundAt})`,);@@ -3621,8 +3633,38 @@ export class DeviceLinkClient {// 引发事故的量级。真出现这种负载时日志会给出真实形状,届时按证据设计,不先建机制。const budget = this.recoveryPassBudget();let framesSpent = 0;+ const head = peer.pending.values().next().value;for (const pending of peer.pending.values()) {- if (!opts.ignoreInterval && now - pending.lastSentAt < this.timing.transportRetryIntervalMs) {+ // Cumulative ACK cannot confirm a tail while a byte-paced head is still+ // missing. Allow one early tail retry to fill the receiver's buffer, but+ // do not burn its whole retry budget (and reset this healthy slow link)+ // before the head has finished. ACK removal naturally releases this hold;+ // genuine link recovery still replays immediately via ignoreInterval.+ if (+ !opts.ignoreInterval+ && head+ && pending !== head+ && head.bytes > RELIABLE_RETRY_BYTES_PER_INTERVAL+ && pending.attempts >= Math.min(2, this.timing.transportMaxRetryAttempts)+ ) continue;+ // A local ws write is not a delivery receipt: relay -> mobile can still be+ // transmitting a large response even with bufferedAmount=0. A 200KB page+ // took ~18s on Android's 256Kbit/s high-latency link; 2/4/8s backoff still+ // queued several full copies before its first ACK. Include a bounded byte+ // budget, retaining immediate replay when a new connection/link resumes.+ const sizeIntervals = Math.min(+ RELIABLE_RETRY_MAX_SIZE_INTERVALS,+ Math.ceil(pending.bytes / RELIABLE_RETRY_BYTES_PER_INTERVAL),+ );+ const retryDelayMs = this.timing.transportRetryIntervalMs * Math.max(+ sizeIntervals,+ Math.min(4, 2 ** Math.max(0, pending.attempts - 1)),+ );+ if (!opts.ignoreInterval && now - pending.lastSentAt < retryDelayMs) {+ // A large head frame may still be inside its byte-based cooldown while+ // a later small request is already eligible. Cumulative ACK cannot+ // advance past the head, but one early retry lets the receiver buffer+ // the later frame without exhausting its budget behind that head.continue;}if (pending.attempts >= this.timing.transportMaxRetryAttempts) {diff --git a/packages/device-link/src/protocol.ts b/packages/device-link/src/protocol.tsindex 84958443b7..f4da269228 100644--- a/packages/device-link/src/protocol.ts+++ b/packages/device-link/src/protocol.ts@@ -129,6 +129,9 @@ export const CONTROLLER_CAPABILITY_MODEL_WINDOW_CONFIRMATION_V1 =*/export const CONTROLLER_CAPABILITY_MAKER_EVENT_BATCH_V1 = 'maker-event-batch-v1';+/** Accepts ordered current-text snapshots and history repair hints, including after backpressure. */+export const CONTROLLER_CAPABILITY_SESSION_TEXT_SNAPSHOT_V1 = 'session-text-snapshot-v1';+export interface LinkAcceptPayload {appVersion: string;/** 被控端 allowlist 的指纹,便于控制端探测版本差异 */diff --git a/packages/device-link/src/topics.ts b/packages/device-link/src/topics.tsindex 21982460c7..6607f1ec04 100644--- a/packages/device-link/src/topics.ts+++ b/packages/device-link/src/topics.ts@@ -62,6 +62,18 @@ export interface SessionActivityPayload {/** 会话列表级实时活动摘要 channel。归 `sessions` topic,不触发 active-control 横幅。 */export const SESSION_ACTIVITY_CHANNEL = 'local-db:sessions:activity';+/**+ * Opt-in recovery for session-text-snapshot-v1 controllers. Payload has sessionId,+ * optional persistId/event (text, isFullText:true, isFinal:false, data.createdAt+ * is the block's ISO host timestamp), and optional+ * resyncRequired. The event replaces that in-flight block; the flag invalidates+ * history independently. Host flushes older batches before sending, then sends+ * newer deltas on the same reliable stream. Not coalescible/evictable: dropping+ * the repair itself would leave the controller silently incomplete again.+ * Old hosts ignore the capability; old controllers never receive this channel.+ */+export const SESSION_SYNC_CHANNEL = 'maker:session-sync';+/*** `maker:event` 的**微批**转发 channel(同一会话的连续事件合并成一帧)。*