Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
perf(mobile): 加速点击推送后的任务同步恢复 (#3968)
Dash8d67dfcb5123
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex 82e8ea2197..7bbe80b656 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -92,12 +92,13 @@ import { agentAuthGateHint, agentAuthGateVerdict } from '@/session/agentAuthGateimport { isTransientRemoteError, withTransientRemoteRetry } from '@/device-link/remoteRetry';import {createRemoteSyncReopenCoordinator,+ retryRemoteSyncRead,useRemoteSyncCoordinator,type RemoteSyncRun,} from '@/device-link/remoteSyncTask';import {runConnectionScopedSessionMetadataRead,- runIndependentSnapshotReads,+ readProgressiveMessageWindow,runSessionMessagesSnapshotSingleFlight,runSessionPendingInteractionsSnapshotSingleFlight,runSessionProjectionSnapshotSingleFlight,@@ -896,6 +897,7 @@ export default function SessionScreen() {const { t, i18n: i18nInstance } = useTranslation();const params = useLocalSearchParams<{sessionId: string;+ notificationResponse?: string;deviceId?: string;deviceName?: string;draft?: string;@@ -910,6 +912,8 @@ export default function SessionScreen() {visualSearchQuery?: string;}>();const sessionId = readRouteParam(params.sessionId) ?? '';+ const notificationResponse = readRouteParam(params.notificationResponse);+ const syncedNotificationResponseRef = useRef<string | null>(null);const shareSelectionActive = useShareSelectionActive(sessionId);const shareSelectionCount = useShareSelectionCount();const shareSelectionRevision = useShareSelectionRevision();@@ -957,7 +961,7 @@ export default function SessionScreen() {remoteSessionStore.leaveSessionMessageDetail(sessionId, 'detail-blur', authority);}};- }, [deviceId, sessionId]),+ }, [deviceId, notificationResponse, sessionId]),);useEffect(() => {const subscription = AppState.addEventListener('change', (nextState) => {@@ -1691,11 +1695,14 @@ export default function SessionScreen() {// A 上次访问落的 key 仍等于 `${sessionId}:${connectionEpoch}`,若不清,回到 A 会在// 新一轮 load() 拉到最新窗口前就凭缓存消息放行回执(离开期间只有轻 topic 在走,// 缓存未必含新完成 turn 的内容)。每次切换都强制等本次访问的 sync 重新落 key。- const [prevReadAckSessionId, setPrevReadAckSessionId] = useState(sessionId);- if (prevReadAckSessionId !== sessionId) {- setPrevReadAckSessionId(sessionId);+ // A new push visit to the same route must also wait for its new message window.+ const readAckVisitKey = JSON.stringify([deviceId, sessionId, notificationResponse]);+ const [prevReadAckVisitKey, setPrevReadAckVisitKey] = useState(readAckVisitKey);+ if (prevReadAckVisitKey !== readAckVisitKey) {+ setPrevReadAckVisitKey(readAckVisitKey);setReadAckSyncedKey(null);setSessionMetadataSyncedKey(null);+ setContentSyncedKey(null);readAckGateGenRef.current += 1;}// 远程媒体取件队列:屏实例级缓存 + 同 url 去重 + 并发上限(每次取件都让桌面端@@ -3120,8 +3127,7 @@ export default function SessionScreen() {};}, [connectionEpoch, deviceId, lastSyncedAt, maker, openLink, sessionAgentSwitchSupported, sessionId]);- const syncSession = useCallback(async (syncRun: Pick<RemoteSyncRun, 'isStale' | 'replaceMessages'>) => {- const contentKeyAtStart = contentRecoveryKeyRef.current;+ const syncSession = useCallback(async (syncRun: RemoteSyncRun) => {const snapshotStartedAt = Date.now();const options = { replaceMessages: syncRun.replaceMessages };if (!deviceId || !sessionId || syncRun.isStale()) return;@@ -3176,7 +3182,7 @@ export default function SessionScreen() {&& storedMessagesAtStart.length > 0&& storedSessionAtStart !== null;const prepareLinkAndSubscription = async () => {- await withTransientRemoteRetry(() => openLink(deviceId));+ await retryRemoteSyncRead(syncRun, () => openLink(deviceId));if (subscriptionRetryIsStale()) return;let subscriptionAttemptVersion = syncReopenCoordinator.captureVersion();// sessions topic 只负责之后的实时推送,不挡快照读。自己在后台@@ -3193,13 +3199,14 @@ export default function SessionScreen() {};const retryRead = <T,>(read: () => Promise<T>): Promise<T> => {let failedAtVersion: number | null = null;- return withTransientRemoteRetry(async () => {+ return retryRemoteSyncRead(syncRun, async () => {// 首轮复用上面统一完成的 link-open。只有本项真的因瞬态错误重试时才// 按失败请求开始时的恢复版本重开:同一旧代的错峰失败会合并;重开后// 发出的请求若再次断链,则以新版本触发下一次真正 reopen。if (failedAtVersion !== null) {await syncReopenCoordinator.reopenAfter(failedAtVersion);}+ if (syncRun.isStale()) throw new Error('Remote sync superseded');const attemptVersion = syncReopenCoordinator.captureVersion();return read().catch((err) => {failedAtVersion = attemptVersion;@@ -3207,10 +3214,17 @@ export default function SessionScreen() {});});};- const snapshotScope = {+ const snapshotScope: {+ deviceId: string;+ sessionId: string;+ connectionEpoch: number;+ subscriptionIdentity?: number | null;+ signal: AbortSignal;+ } = {deviceId,sessionId,connectionEpoch: readAckEpochAtStart,+ signal: syncRun.signal,};const fetchActiveSessionSnapshot = async () => {// Capture immediately before every request. Because this helper is invoked inside@@ -3241,112 +3255,79 @@ export default function SessionScreen() {setError(null);try {await prepareLinkAndSubscription();- if (!isReopen) {- // 首开 / 强制替换:A1 仍保持并行,但每一项独立重试。一个 ACK timeout- // 不再把已经成功的 meta / history / pending / projection / active 全部重发。- const [sessionMeta, history, pendingInteractions, projectionResult, activeSessionSnapshot] = await runIndependentSnapshotReads([- fetchSessionMetadata,- () => listMessagesWithPayloadRetry((limit) => runSessionMessagesSnapshotSingleFlight(+ if (syncRun.isStale() || !messageAuthorityCurrent()) return;+ // Capture at the first snapshot read, after link-open. An ACK received while+ // opening the link is already covered; it must not force another full batch.+ const ackAtReadStart = getSubscriptionIdentity?.(deviceId, ['sessions', `session:${sessionId}`]) ?? null;+ snapshotScope.subscriptionIdentity = ackAtReadStart;+ const contentKeyAtStart = ackAtReadStart === null ? null+ : JSON.stringify([deviceId, sessionId, readAckEpochAtStart, ackAtReadStart]);+ const isCurrent = () => !syncRun.isStale() && messageAuthorityCurrent();+ const pushRefresh = notificationResponse !== null+ && syncedNotificationResponseRef.current !== notificationResponse;+ const messageRead = readProgressiveMessageWindow({+ readMetadata: () => retryRead(fetchSessionMetadata),+ eager: !isReopen || pushRefresh,+ shouldReadMessages: (sessionMeta) => shouldRefreshLatestMessageWindowOnReopen({+ freshSession: sessionMeta,+ messageWindowSynced: remoteSessionStore.isSessionMessageWindowSynced(sessionId, sessionMeta),+ storedSession: storedSessionAtStart,+ }),+ readMessages: () => retryRead(() => listMessagesWithPayloadRetry(+ (limit) => runSessionMessagesSnapshotSingleFlight(snapshotScope,limit,{ kind: 'detail', generation: messageAuthority.generation },() => maker.listMessages(sessionId, { limit }),- )),- fetchPendingInteractions,- fetchProjection,- () => fetchActiveSessionSnapshot(),- ] as const, retryRead);- if (syncRun.isStale() || !messageAuthorityCurrent()) return;- remoteSessionStore.setActiveSessionSnapshots(- deviceId,- Array.isArray(activeSessionSnapshot.activeSessions)- ? activeSessionSnapshot.activeSessions- : [],- activeSessionSnapshot.activityEpochAtFetchStart,- );- const historyPage: RemoteMessage[] = Array.isArray(history.messages) ? history.messages : [];- // moreBeyondWindow:本页上沿之外服务端还有历史(满页 / 被裁行)。为真时 store 不保留早于- // 本页的缓存段 —— 它与本页之间可能隔着从未加载的行,保留就是孤岛(#1222)。判据与- // 「加载更早」入口同源,两者本就该一致。- const moreBeyondWindow = shouldKeepOlderMessagesAffordance(history);- if (options.replaceMessages) {- remoteSessionStore.setMessages(sessionId, historyPage, { authority: messageAuthority });- } else {- remoteSessionStore.setLatestMessageWindow(sessionId, historyPage, {- authority: messageAuthority,- moreBeyondWindow,- });- }- remoteSessionStore.markSessionMessagesSynced(sessionId, sessionMeta);- setHasOlderMessages(moreBeyondWindow);- remoteSessionStore.setPendingInteractions(sessionId, Array.isArray(pendingInteractions) ? pendingInteractions : []);- remoteSessionStore.setInputProjectionIfCurrent(- sessionId,- projectionResult.projection,- projectionResult.authorityEpochAtStart,- );- } else {- // 重开:便宜并行(不含整窗 listMessages)拿 meta + pending + projection + active。- const [sessionMeta, pendingInteractions, projectionResult, activeSessionSnapshot] = await runIndependentSnapshotReads([- fetchSessionMetadata,- fetchPendingInteractions,- fetchProjection,- () => fetchActiveSessionSnapshot(),- ] as const, retryRead);- // 廉价对账:updatedAt 主信号(任何消息变化都会 bump),_count 仅在两侧都有时作辅助;- // 另外要求消息窗口已被详情页同步到当前 meta,避免首页先刷新 session preview 后,- // 详情页把旧消息缓存误判成最新。任一变化 → 拉取权威最新窗口并对账;- // 都没变 → 跳过整窗重拉(内容已是最新,新消息由 live subscribe 推送)。- const freshCount = sessionMeta._count?.messages;- const metaChanged = shouldRefreshLatestMessageWindowOnReopen({- freshSession: sessionMeta,- messageWindowSynced: remoteSessionStore.isSessionMessageWindowSynced(sessionId, sessionMeta),- storedSession: storedSessionAtStart,- });- if (syncRun.isStale() || !messageAuthorityCurrent()) return;- remoteSessionStore.setActiveSessionSnapshots(- deviceId,- Array.isArray(activeSessionSnapshot.activeSessions)- ? activeSessionSnapshot.activeSessions- : [],- activeSessionSnapshot.activityEpochAtFetchStart,- );- if (metaChanged) {- const history = await retryRead(() =>- listMessagesWithPayloadRetry(- (limit) => runSessionMessagesSnapshotSingleFlight(- snapshotScope,- limit,- { kind: 'detail', generation: messageAuthority.generation },- () => maker.listMessages(sessionId, { limit }),- ),- REOPEN_MESSAGE_WINDOW_LIMITS,- ),- );- if (syncRun.isStale() || !messageAuthorityCurrent()) return;+ ),+ isReopen ? REOPEN_MESSAGE_WINDOW_LIMITS : undefined,+ )),+ isCurrent,+ commitMessages: (history) => {const historyPage: RemoteMessage[] = Array.isArray(history.messages) ? history.messages : [];- // 同首开路径:上沿之外还有历史时不保留更早的缓存段(#1222)。const moreBeyondWindow = shouldKeepOlderMessagesAffordance(history);- remoteSessionStore.setLatestMessageWindow(sessionId, historyPage, {- authority: messageAuthority,- moreBeyondWindow,- });- remoteSessionStore.markSessionMessagesSynced(sessionId, sessionMeta);- setHasOlderMessages(moreBeyondWindow);- } else {- // 回归修复:没新内容也要补设 hasOlderMessages —— 屏幕重开把该 state 重置为 false,跳过整窗- // 重拉时若不补设,「加载更早」入口会消失、往上拖刷不出老消息。用服务端总数 vs in-store 已加载- // 真实消息数推断(getSession 没给总数时退化为窗口启发式)。- setHasOlderMessages(hasOlderMessagesAfterReopen(freshCount, remoteSessionStore.getMessages(sessionId)));- }- remoteSessionStore.setPendingInteractions(sessionId, Array.isArray(pendingInteractions) ? pendingInteractions : []);- remoteSessionStore.setInputProjectionIfCurrent(- sessionId,- projectionResult.projection,- projectionResult.authorityEpochAtStart,- );+ if (options.replaceMessages) {+ remoteSessionStore.setMessages(sessionId, historyPage, { authority: messageAuthority });+ } else {+ remoteSessionStore.setLatestMessageWindow(sessionId, historyPage, {+ authority: messageAuthority,+ moreBeyondWindow,+ });+ }+ },+ });+ const commitRead = <T,>(read: () => Promise<T>, commit: (value: T) => void) =>+ runConnectionScopedSessionMetadataRead(() => retryRead(read), isCurrent, commit);+ // 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([+ messageRead,+ commitRead(fetchPendingInteractions, (pendingInteractions) => {+ remoteSessionStore.setPendingInteractions(sessionId, Array.isArray(pendingInteractions) ? pendingInteractions : []);+ }),+ commitRead(fetchProjection, (projectionResult) => {+ remoteSessionStore.setInputProjectionIfCurrent(+ sessionId, projectionResult.projection, projectionResult.authorityEpochAtStart,+ );+ }),+ commitRead(fetchActiveSessionSnapshot, (activeSessionSnapshot) => {+ remoteSessionStore.setActiveSessionSnapshots(+ deviceId,+ Array.isArray(activeSessionSnapshot.activeSessions) ? activeSessionSnapshot.activeSessions : [],+ activeSessionSnapshot.activityEpochAtFetchStart,+ );+ }),+ ]);+ if (!isCurrent()) return;+ if (history !== null) {+ remoteSessionStore.markSessionMessagesSynced(sessionId, sessionMeta);+ if (pushRefresh) syncedNotificationResponseRef.current = notificationResponse;}- // 不变量:上面 setHasOlderMessages 的校正(:806/:841/:846)与这里的 setLastSyncedAt 之间必须保持+ 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;@@ -3356,6 +3337,7 @@ export default function SessionScreen() {setLastSyncedAt(Date.now());setContentSyncedKey(contentKeyAtStart);if (contentKeyAtStart !== null && contentRecoveryKeyRef.current === contentKeyAtStart) {+ syncRun.satisfy('subscription-acked');console.debug('[device-link] recovery snapshot applied', { elapsedMs: Date.now() - snapshotStartedAt });}// 已读回执门槛:本会话在当前连接代完成过整窗同步。sessionId / epoch / 门槛代号@@ -3371,16 +3353,22 @@ export default function SessionScreen() {// 两类失败都写入 hold 且不能清门:瞬态错误继续自动重试,确定性错误保留// 手动同步入口;共享 UI error 被其它操作清掉时也不会变成不可见的永久自锁。latchOutboxTransportHold(formatted);+ // The coordinator owns sibling cancellation and preserves this failure+ // for rewind/navigation callers. Supersession remains a separate outcome.+ throw err;}} finally {if (!syncRun.isStale() && messageAuthorityCurrent()) setLoading(false);}- }, [deviceId, deviceName, latchOutboxTransportHold, maker, openLink, reopenLink, sessionId, subscribe]);+ }, [deviceId, deviceName, getSubscriptionIdentity, latchOutboxTransportHold, maker, notificationResponse, openLink, reopenLink, sessionId, subscribe]);// 任一连接恢复身份变化都会让旧读取失去提交资格。否则断线前启动的同步可能在// 新 hold 锁存后迟到,并从成功尾误清恢复屏障。const remoteSyncContextKey = JSON.stringify([deviceId,sessionId,+ notificationResponse,+ appStateActive,+ messageReloadRevision,connectionEpoch,status,targetAvailableForDispatch,@@ -3394,9 +3382,10 @@ export default function SessionScreen() {// the two. Reuse the existing coordinator to reconcile after this exact ACK.useEffect(() => {if (!contentRecoveryKey || status !== 'online') return;+ if (contentSyncedKey === contentRecoveryKey) return;if (!messageScreenFocusedRef.current || !messageAppActiveRef.current) return;void requestSync({ reason: 'subscription-acked', replaceMessages: false });- }, [contentRecoveryKey, requestSync, status]);+ }, [contentRecoveryKey, contentSyncedKey, requestSync, status]);const load = useCallback(() => requestSync({ reason: 'passive-refresh' }),[requestSync],diff --git a/apps/mobile/src/__tests__/mobilePushRecovery.test.ts b/apps/mobile/src/__tests__/mobilePushRecovery.test.tsnew file mode 100644index 0000000000..220edf8f8e--- /dev/null+++ b/apps/mobile/src/__tests__/mobilePushRecovery.test.ts@@ -0,0 +1,346 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { createBackgroundConnection } from '@/device-link/backgroundConnection';+import { createRemoteSyncCoordinator, retryRemoteSyncRead } from '@/device-link/remoteSyncTask';+import { readProgressiveMessageWindow, settleProgressiveSnapshot, runSessionMessagesSnapshotSingleFlight } from '@/device-link/sessionSnapshotSingleFlight';+import { notificationRecoveryRoute } from '@/notifications/pushRegistrationModel';+import { remoteSessionStore } from '@/session/remoteSessionStore';+import { classifySnapshotBatchFailure, rehydrateDeviceLinkPeer } from '@/device-link/rehydrate';+import type { RemoteMessage } from '@/session/types';++function deferred<T>() {+ let resolve!: (value: T) => void;+ let reject!: (reason: unknown) => void;+ const promise = new Promise<T>((done, fail) => { resolve = done; reject = fail; });+ return { promise, resolve, reject };+}++describe('background push recovery', () => {+ beforeEach(() => { vi.useFakeTimers(); vi.setSystemTime(100_000); });+ afterEach(() => vi.useRealTimers());++ function fixture() {+ let background = true;+ const release = deferred<void>();+ const stop = vi.fn();+ const connect = vi.fn();+ const releaseTopics = vi.fn(() => [release.promise]);+ const lifecycle = createBackgroundConnection({+ isBackground: () => background,+ releaseTopics, stop, connect,+ graceMs: 2500, releaseWaitMs: 1000, suspendMs: 10_000,+ });+ return { lifecycle, release, stop, connect, releaseTopics, active: () => { background = false; lifecycle.active(); } };+ }++ it('replaces a half-open socket immediately when JS was suspended during the final unsubscribe', async () => {+ const f = fixture();+ f.lifecycle.background();+ await vi.advanceTimersByTimeAsync(2500);+ expect(f.releaseTopics).toHaveBeenCalledTimes(2);+ expect(f.stop).not.toHaveBeenCalled();+ // Wall time passes without running timers: iOS suspended the JS runtime.+ vi.setSystemTime(Date.now() + 60_000);+ f.active();+ expect(f.stop).toHaveBeenCalledTimes(1);+ expect(f.connect).toHaveBeenCalledTimes(1);+ expect(f.stop.mock.invocationCallOrder[0]).toBeLessThan(f.connect.mock.invocationCallOrder[0]);+ f.release.resolve();+ await vi.runAllTimersAsync();+ expect(f.stop).toHaveBeenCalledTimes(1);+ f.lifecycle.dispose();+ });++ it('keeps the healthy socket for a quick app switch and releases heavy topics immediately', async () => {+ const f = fixture();+ f.lifecycle.background();+ expect(f.releaseTopics).toHaveBeenCalledTimes(1);+ await vi.advanceTimersByTimeAsync(500);+ f.active();+ f.release.resolve();+ await vi.runAllTimersAsync();+ expect(f.stop).not.toHaveBeenCalled();+ expect(f.connect).toHaveBeenCalledTimes(1);+ });++ it('bounds final unsubscribe and prevents an old tail from stopping a later background generation', async () => {+ const f = fixture();+ f.lifecycle.background();+ await vi.advanceTimersByTimeAsync(2500);+ f.active();+ f.lifecycle.background();+ f.release.resolve();+ await vi.advanceTimersByTimeAsync(0);+ expect(f.stop).not.toHaveBeenCalled();+ f.lifecycle.dispose();+ await vi.runAllTimersAsync();+ expect(f.stop).not.toHaveBeenCalled();+ const g = fixture();+ g.lifecycle.background();+ await vi.advanceTimersByTimeAsync(3500);+ expect(g.stop).toHaveBeenCalledTimes(1);+ g.lifecycle.dispose();+ });+});++describe('progressive push snapshots', () => {+ beforeEach(() => { vi.useFakeTimers(); vi.setSystemTime(0); remoteSessionStore.clear(); });+ afterEach(() => { remoteSessionStore.clear(); vi.useRealTimers(); });++ const message: RemoteMessage = {+ id: 'latest', sessionId: 'session-1', role: 'assistant', content: 'latest response',+ clientId: 'latest', toolUseId: null, agentMeta: null, createdAt: '2026-09-05T00:00:00Z',+ };++ it('shows push messages at 100ms while metadata and control state are still pending', async () => {+ const metadata = deferred<number>();+ const history = deferred<RemoteMessage[]>();+ const projection = deferred<void>();+ let recovered = false;+ const timeline: number[] = [];+ const result = readProgressiveMessageWindow({+ readMetadata: () => metadata.promise,+ readMessages: () => history.promise,+ eager: true, shouldReadMessages: () => true, isCurrent: () => true,+ commitMessages: (value) => { remoteSessionStore.setMessages('session-1', value); timeline.push(Date.now()); },+ });+ const complete = Promise.all([result, projection.promise]).then(() => { recovered = true; });+ await vi.advanceTimersByTimeAsync(100);+ history.resolve([message]);+ await vi.advanceTimersByTimeAsync(0);+ expect(remoteSessionStore.getMessages('session-1')).toEqual([message]);+ expect(timeline).toEqual([100]);+ expect(recovered).toBe(false);+ metadata.resolve(1);+ await vi.advanceTimersByTimeAsync(14_900);+ expect(recovered).toBe(false);+ projection.resolve();+ await complete;+ expect(recovered).toBe(true);+ });++ it('starts history on changed metadata without waiting for any auxiliary read', async () => {+ const metadata = deferred<number>();+ const readMessages = vi.fn(async () => [message]);+ const result = readProgressiveMessageWindow({+ readMetadata: () => metadata.promise, readMessages,+ eager: false, shouldReadMessages: (version) => version === 2,+ isCurrent: () => true, commitMessages: () => undefined,+ });+ expect(readMessages).not.toHaveBeenCalled();+ metadata.resolve(2);+ await result;+ expect(readMessages).toHaveBeenCalledTimes(1);+ await readProgressiveMessageWindow({+ readMetadata: async () => 1, readMessages,+ eager: false, shouldReadMessages: () => false,+ isCurrent: () => true, commitMessages: () => undefined,+ });+ expect(readMessages).toHaveBeenCalledTimes(1);+ });++ it('commits a recovery response before a sibling times out and retains the failure classification', async () => {+ const goal = deferred<void>();+ const result = Promise.all([+ settleProgressiveSnapshot(Promise.resolve([message]), (value) => remoteSessionStore.setMessages('session-1', value)),+ settleProgressiveSnapshot(goal.promise, () => undefined),+ ]);+ await vi.advanceTimersByTimeAsync(0);+ expect(remoteSessionStore.getMessages('session-1')).toEqual([message]);+ goal.reject(new Error('INVOKE_TIMEOUT'));+ const settled = await result;+ expect(settled.map((item) => item.status)).toEqual(['fulfilled', 'rejected']);+ });++ it('does not reuse a pre-ACK message request for the post-ACK gap reconciliation', async () => {+ const old = deferred<string>();+ const scope = { deviceId: 'device', sessionId: 'session', connectionEpoch: 1 };+ const fence = { kind: 'detail' as const, generation: 1 };+ const before = runSessionMessagesSnapshotSingleFlight({ ...scope, subscriptionIdentity: null }, 20, fence, () => old.promise);+ const read = vi.fn(async () => 'after-ack');+ expect(await runSessionMessagesSnapshotSingleFlight({ ...scope, subscriptionIdentity: 7 }, 20, fence, read)).toBe('after-ack');+ expect(read).toHaveBeenCalledTimes(1);+ old.resolve('before-ack');+ await before;+ });++ it('cancels shared stale snapshots without touching another peer and fetches a fresh replacement', async () => {+ const old = deferred<string>();+ const other = deferred<string>();+ const scope = { deviceId: 'device-a', sessionId: 'session', connectionEpoch: 1 };+ const fence = { kind: 'detail' as const, generation: 1 };+ // Rehydrate starts first; detail joins it and can subsequently invalidate it.+ const rehydrate = runSessionMessagesSnapshotSingleFlight(scope, 20, fence, () => old.promise);+ const controller = new AbortController();+ const detail = runSessionMessagesSnapshotSingleFlight({ ...scope, signal: controller.signal }, 20, fence, async () => 'unused');+ expect(detail).toBe(rehydrate);+ const peerB = runSessionMessagesSnapshotSingleFlight({ ...scope, deviceId: 'device-b' }, 20, fence, () => other.promise);+ const cancelled = expect(detail).rejects.toThrow('superseded');+ controller.abort();+ await cancelled;+ expect(await runSessionMessagesSnapshotSingleFlight(scope, 20, fence, async () => 'fresh')).toBe('fresh');+ old.reject(new Error('late transport failure'));+ other.resolve('peer-b');+ expect(await peerB).toBe('peer-b');+ });++ it('rejects a late progressive window after its detail authority has been revoked', async () => {+ const history = deferred<RemoteMessage[]>();+ const authority = remoteSessionStore.enterSessionMessageDetail('session-1');+ const result = readProgressiveMessageWindow({+ readMetadata: async () => 1, readMessages: () => history.promise,+ eager: true, shouldReadMessages: () => true,+ isCurrent: () => remoteSessionStore.isSessionMessageAuthorityCurrent(authority),+ commitMessages: (value) => remoteSessionStore.setMessages('session-1', value, { authority }),+ });+ remoteSessionStore.clear();+ history.resolve([message]);+ await result;+ expect(remoteSessionStore.getMessages('session-1')).toEqual([]);+ });++ it('retries still-current rehydrate after a sharing detail is cancelled, fencing the late old reply', async () => {+ const old = deferred<RemoteMessage[]>();+ const scope = { deviceId: 'device-a', sessionId: 'session-1', connectionEpoch: 1 };+ const fence = { kind: 'detail' as const, generation: 1 };+ const read = vi.fn<() => Promise<RemoteMessage[]>>().mockImplementationOnce(() => old.promise).mockResolvedValue([message]);+ const deps = {+ createDeviceSendCohort: () => 1,+ capturePresenceEpoch: () => 1,+ captureResponseEvidenceEpoch: () => 1,+ isPresenceEpochCurrent: () => true,+ isResponseEvidenceEpochCurrent: () => true,+ openLink: () => ({ capturedPresenceEpoch: 1, capturedResponseEvidenceEpoch: 1, request: Promise.resolve() }),+ subscribe: async () => undefined,+ requestSessionsReseed: () => undefined,+ rebuildSessionSnapshot: async () => {+ const settled = await settleProgressiveSnapshot(+ runSessionMessagesSnapshotSingleFlight(scope, 20, fence, read),+ (value) => remoteSessionStore.setMessages('session-1', value),+ );+ // Same batch boundary as Provider: local invalidation is retried by the+ // existing peer recovery path, not treated as a permanent missing resource.+ const failure = classifySnapshotBatchFailure([settled]);+ if (failure.kind === 'partial-transient') throw Object.assign(new Error('partial snapshot needs retry'), { code: 'INVOKE_TIMEOUT' });+ if (failure.kind === 'reject') throw failure.error;+ },+ };+ const plan = { deviceId: 'device-a', openLink: false, topics: ['session:session-1' as const] };+ const recovery = rehydrateDeviceLinkPeer(plan, deps);+ await vi.advanceTimersByTimeAsync(0);+ expect(read).toHaveBeenCalledTimes(1);+ const controller = new AbortController();+ const detail = runSessionMessagesSnapshotSingleFlight({ ...scope, signal: controller.signal }, 20, fence, read);+ const cancelled = expect(detail).rejects.toThrow('superseded');+ controller.abort();+ await cancelled;+ expect((await recovery).transientFailures).toBe(1);+ expect(remoteSessionStore.getMessages('session-1')).toEqual([]);+ expect((await rehydrateDeviceLinkPeer(plan, deps)).transientFailures).toBe(0);+ expect(read).toHaveBeenCalledTimes(2);+ expect(remoteSessionStore.getMessages('session-1')).toEqual([message]);+ old.resolve([{ ...message, content: 'obsolete' }]);+ await vi.advanceTimersByTimeAsync(0);+ expect(remoteSessionStore.getMessages('session-1')).toEqual([message]);+ });++ it('preserves the device query and fragment while replacing an untrusted duplicate navigation hint', () => {+ const route = notificationRecoveryRoute('/sessions/a?deviceId=d¬ificationResponse=old#tail', 'id:push&2');+ expect(route).toBe('/sessions/a?deviceId=d¬ificationResponse=id%3Apush%262#tail');+ expect(notificationRecoveryRoute('/sessions/a', '1')).toBe('/sessions/a?notificationResponse=1');+ });+});++describe('superseded recovery reads', () => {+ beforeEach(() => vi.useFakeTimers());+ afterEach(() => vi.useRealTimers());++ it('starts the new connection without waiting for the old transport timeout and ignores its late reply', async () => {+ const old = deferred<string>();+ const committed: string[] = [];+ const coordinator = createRemoteSyncCoordinator(async (run) => {+ const value = await retryRemoteSyncRead(run, () => run.reasons.includes('old') ? old.promise : Promise.resolve('new'));+ if (!run.isStale()) committed.push(value);+ });+ coordinator.setContext('connection-1');+ const task = coordinator.request({ reason: 'old' });+ coordinator.setContext('connection-2');+ void coordinator.request({ reason: 'new' });+ await vi.advanceTimersByTimeAsync(0);+ await task;+ expect(committed).toEqual(['new']);+ old.resolve('obsolete');+ await vi.advanceTimersByTimeAsync(0);+ expect(committed).toEqual(['new']);+ });++ it('does not retry or reopen after invalidation during backoff', async () => {+ const read = vi.fn(async () => { throw new Error('INVOKE_TIMEOUT'); });+ const coordinator = createRemoteSyncCoordinator((run) => retryRemoteSyncRead(run, read));+ coordinator.setContext('old');+ const task = coordinator.request({ reason: 'start' });+ await vi.advanceTimersByTimeAsync(0);+ expect(read).toHaveBeenCalledTimes(1);+ coordinator.setContext('new');+ await task;+ await vi.advanceTimersByTimeAsync(10_000);+ expect(read).toHaveBeenCalledTimes(1);+ });++ it('drops only a covered ACK follow-up and preserves manual refresh', async () => {+ const gate = deferred<void>();+ const runs: string[][] = [];+ const coordinator = createRemoteSyncCoordinator(async (run) => {+ runs.push([...run.reasons]);+ if (runs.length === 1) { await gate.promise; run.satisfy('subscription-acked'); }+ });+ const result = coordinator.request({ reason: 'mount' });+ void coordinator.request({ reason: 'subscription-acked' });+ void coordinator.request({ reason: 'manual' });+ gate.resolve();+ await result;+ expect(runs).toEqual([['mount'], ['manual']]);+ });++ it('invalidates late siblings of a failed batch when the same-context retry starts', async () => {+ const oldHistory = deferred<void>();+ const committed: string[] = [];+ let late!: Promise<void>;+ const coordinator = createRemoteSyncCoordinator(async (run) => {+ if (run.reasons.includes('old')) {+ late = oldHistory.promise.then(() => { if (!run.isStale()) committed.push('old'); });+ throw new Error('projection failed');+ }+ committed.push('new');+ });+ await expect(coordinator.request({ reason: 'old' })).rejects.toThrow('projection failed');+ await coordinator.request({ reason: 'retry' });+ oldHistory.resolve();+ await late;+ expect(committed).toEqual(['new']);+ });++ it('rejects an awaited authoritative refresh with its real error while cancelling sibling reads', async () => {+ const failed = deferred<void>();+ const history = deferred<void>();+ const error = new Error('projection failed');+ const committed = vi.fn();+ let signal!: AbortSignal;+ const coordinator = createRemoteSyncCoordinator(async (run) => {+ signal = run.signal;+ await Promise.all([+ failed.promise,+ retryRemoteSyncRead(run, () => history.promise).then(() => { if (!run.isStale()) committed(); }),+ ]);+ });+ // A passive caller may ignore the same promise; the awaited rewind caller+ // still receives the original failure, not a successful cancellation result.+ const refresh = coordinator.request({ reason: 'rewind-commit', replaceMessages: true });+ const rejected = expect(refresh).rejects.toBe(error);+ failed.reject(error);+ await rejected;+ expect(signal.aborted).toBe(true);+ history.resolve();+ await vi.advanceTimersByTimeAsync(0);+ expect(committed).not.toHaveBeenCalled();+ });+});diff --git a/apps/mobile/src/__tests__/scrollWindowModel.test.ts b/apps/mobile/src/__tests__/scrollWindowModel.test.tsindex 554ae53449..6041157b2b 100644--- a/apps/mobile/src/__tests__/scrollWindowModel.test.ts+++ b/apps/mobile/src/__tests__/scrollWindowModel.test.ts@@ -97,15 +97,15 @@ describe('scrollWindowModel', () => {});});- it('restores the load-earlier affordance after reopen even when no new content was fetched', () => {- const source = readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');+ 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(freshCount, remoteSessionStore.getMessages(sessionId))');+ expect(source).toContain('hasOlderMessagesAfterReopen(sessionMeta._count?.messages, remoteSessionStore.getMessages(sessionId))');// 仍保留有新内容时的精确(page-based)判定。这个值现在同时喂给 store 的窗口连续性判据// (moreBeyondWindow,见 #1222):两者本就该同源 —— 「本页上沿之外还有历史」既决定是否点亮// 「加载更早」,也决定能不能信任早于本页的缓存段。expect(source).toContain('const moreBeyondWindow = shouldKeepOlderMessagesAffordance(history);');- expect(source).toContain('setHasOlderMessages(moreBeyondWindow);');+ expect(source).toMatch(/setHasOlderMessages\(history !== null\s+\? shouldKeepOlderMessagesAffordance\(history\)/);expect(source).toMatch(/setLatestMessageWindow\(sessionId, historyPage, \{\s*authority: messageAuthority,\s*moreBeyondWindow,\s*\}\)/,);diff --git a/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts b/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.tsindex bb5ec9eca1..d958d5184c 100644--- a/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts+++ b/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts@@ -56,8 +56,9 @@ describe('mobile session composer desktop-first surface', () => {expect(source).toContain('const activityEpochAtFetchStart = remoteSessionStore.captureActiveSessionSnapshotEpoch();',);- expect((source.match(/fetchActiveSessionSnapshot\(\),/g) ?? []).length).toBe(2);- expect((source.match(/activeSessionSnapshot\.activityEpochAtFetchStart/g) ?? []).length).toBe(2);+ // First open and reopen share one progressive, independently retried reader.+ expect(source).toContain('commitRead(fetchActiveSessionSnapshot,');+ expect((source.match(/activeSessionSnapshot\.activityEpochAtFetchStart/g) ?? []).length).toBe(1);expect((source.match(/maker\.listActiveSessions\(\)/g) ?? []).length).toBe(1);});diff --git a/apps/mobile/src/__tests__/sessionMessageMemoryWiring.test.ts b/apps/mobile/src/__tests__/sessionMessageMemoryWiring.test.tsindex 063563b497..22de008131 100644--- a/apps/mobile/src/__tests__/sessionMessageMemoryWiring.test.ts+++ b/apps/mobile/src/__tests__/sessionMessageMemoryWiring.test.ts@@ -40,7 +40,7 @@ describe('任务消息内存治理页面接线', () => {expect(firstReload).toBeGreaterThan(firstEnter);expect(authorityBlock).not.toContain('shouldReload');expect(authorityBlock).not.toContain('lastEnteredMessageSessionRef');- expect(authorityBlock).toContain('}, [deviceId, sessionId]),');+ expect(authorityBlock).toContain('}, [deviceId, notificationResponse, sessionId]),');const subscriptionStart = screen.indexOf('return startFocusedTopicSubscription({');const optimisticOlderStart = screen.indexOf('// 乐观点亮「加载更早」入口', subscriptionStart);@@ -48,15 +48,37 @@ describe('任务消息内存治理页面接线', () => {expect(subscriptionBlock).not.toContain('void load();');});+ it('同任务的新通知撤销上次同步与已读资格', () => {+ expect(screen).toContain('JSON.stringify([deviceId, sessionId, notificationResponse])');+ const resetStart = screen.indexOf('if (prevReadAckVisitKey !== readAckVisitKey) {');+ expect(resetStart).toBeGreaterThanOrEqual(0);+ const reset = screen.slice(resetStart, screen.indexOf('\n }', resetStart));+ expect(reset).toContain('setReadAckSyncedKey(null)');+ expect(reset).toContain('setSessionMetadataSyncedKey(null)');+ expect(reset).toContain('setContentSyncedKey(null)');+ expect(reset).toContain('readAckGateGenRef.current += 1');+ });++ it('同步失败保留页面错误并交给协调器向权威重读调用方传播', () => {+ const syncStart = screen.indexOf('const syncSession = useCallback');+ const syncEnd = screen.indexOf('const remoteSyncContextKey', syncStart);+ const sync = screen.slice(syncStart, syncEnd);+ expect(sync).toMatch(/latchOutboxTransportHold\(formatted\);[\s\S]*?throw err;/);+ expect(sync).not.toContain('syncRun.cancel()');+ expect(screen).toContain("await requestSync({ reason: 'rewind-commit', replaceMessages: true })");+ });+it('详情读取在请求开始捕获 authority,并在所有消息写入口提交', () => {expect(screen).toContain('const messageAuthority = remoteSessionStore.captureSessionMessageAuthority(sessionId);');expect(screen).toContain('remoteSessionStore.isSessionMessageAuthorityCurrent(messageAuthority)');expect(screen).toContain('remoteSessionStore.setMessages(sessionId, historyPage, { authority: messageAuthority });');- expect(screen).toContain('authority: messageAuthority,\n moreBeyondWindow,');+ expect(screen).toMatch(/authority: messageAuthority,\s+moreBeyondWindow,/);expect(screen).toContain('{ authority: messageAuthority },\n );');expect(screen).toContain('remoteSessionStore.mergeEarlierMessages(sessionId, pageList, { authority: messageAuthority });');expect(screen).toContain('remoteSessionStore.mergeMessages(sessionIdAtStart, rows, { authority: messageAuthority });');- expect(screen.match(/maker\.listMessages\(/g)).toHaveLength(4);+ // First open and reopen now share the same authority-fenced history read.+ expect(screen).toContain('readProgressiveMessageWindow({');+ expect(screen.match(/maker\.listMessages\(/g)).toHaveLength(3);});it('schedule 关闭翻历史入口,页面工作租约覆盖发送与附件状态', () => {@@ -85,8 +107,8 @@ describe('任务消息内存治理页面接线', () => {expect(deviceLink).toContain('? remoteSessionStore.captureSessionMessageAuthority(sessionId)');expect(deviceLink).toContain('remoteSessionStore.captureUnenteredSessionMessageAuthority(sessionId)');expect(deviceLink).toContain('authority: messageAuthorityAtRequestStart');- expect(deviceLink).toContain('remoteSessionStore.canCommitUnenteredSessionMessageWindow(\n unenteredMessageAuthorityAtRequestStart,');- expect(deviceLink).toContain('remoteSessionStore.setLatestMessageWindow(sessionId, history.value, windowOptions);');+ expect(deviceLink).toMatch(/remoteSessionStore.canCommitUnenteredSessionMessageWindow\(\s+unenteredMessageAuthorityAtRequestStart,/);+ expect(deviceLink).toContain('remoteSessionStore.setLatestMessageWindow(sessionId, value, windowOptions);');expect(screen).toContain('remoteSessionStore.invalidateSessionMessageWindow(sessionId, deviceId);');expect(screen).not.toContain('remoteSessionStore.setMessages(sessionId, Array.isArray(history.messages)');});diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsxindex 877bc4a3b1..2495b6e1ee 100644--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx@@ -1,4 +1,5 @@import Constants from 'expo-constants';+import { createBackgroundConnection } from './backgroundConnection';import { confirmTrackedSubscription, SubscriptionAcknowledgements } from './subscriptionAcknowledgements';import { AppState, Platform } from 'react-native';import {@@ -71,6 +72,7 @@ import {import { isTransientRemoteError } from '@/device-link/remoteRetry';import {runSessionMessagesSnapshotSingleFlight,+ settleProgressiveSnapshot,runSessionPendingInteractionsSnapshotSingleFlight,runSessionProjectionSnapshotSingleFlight,} from '@/device-link/sessionSnapshotSingleFlight';@@ -606,13 +608,20 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {presenceWipeTimerDeps,);},- rebuildSessionSnapshot: (deviceId, sessionId, opts) => rebuildSessionSnapshot(- client,- deviceId,- sessionId,- connectionEpochRef.current,- opts,- ),+ rebuildSessionSnapshot: (deviceId, sessionId, opts) => {+ const epoch = connectionEpochRef.current;+ const releaseGeneration = backgroundReleaseGenerationRef.current;+ return rebuildSessionSnapshot(client, deviceId, sessionId, epoch, {+ ...opts,+ subscriptionIdentity: remoteSubscribedTopicsRef.current.identity(deviceId, ['sessions', `session:${sessionId}`]),+ }, () => client === clientRef.current+ && client.getStatus() === 'online'+ && connectionEpochRef.current === epoch+ && backgroundReleaseGenerationRef.current === releaseGeneration+ && !backgroundReleaseInFlightRef.current+ && !revokedDevicesStore.has(deviceId)+ && !client.isOutboundExplicitlyClosed(deviceId));+ },});if (@@ -1053,18 +1062,6 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {}});- // 退后台的断连宽限状态:stopTimer 挂着表示还没真正 stop;backgroundAt 用于- // 回前台时判断 JS 是否在计时器触发前就被挂起(见 BACKGROUND_SUSPEND_SUSPECT_MS)。- const backgroundState: { stopTimer: ReturnType<typeof setTimeout> | null; backgroundAt: number } = {- stopTimer: null,- backgroundAt: 0,- };- const clearBackgroundStopTimer = () => {- if (backgroundState.stopTimer) {- clearTimeout(backgroundState.stopTimer);- backgroundState.stopTimer = null;- }- };const releaseHeavyTopics = (): Promise<void>[] => {const releases: Promise<void>[] = [];for (const plan of registryRef.current.snapshot()) {@@ -1078,23 +1075,23 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {}return releases;};+ const backgroundConnection = createBackgroundConnection({+ isBackground: () => AppState.currentState === 'background',+ releaseTopics: releaseHeavyTopics,+ stop: () => client.stop(),+ connect: () => client.connectNow('appstate-active', { overrideCongestionCooldown: true }),+ graceMs: BACKGROUND_STOP_GRACE_MS,+ releaseWaitMs: BACKGROUND_FINAL_UNSUBSCRIBE_WAIT_MS,+ suspendMs: BACKGROUND_SUSPEND_SUSPECT_MS,+ });const sub = AppState.addEventListener('change', (next) => {if (next === 'active') {backgroundReleaseInFlightRef.current = false;- const heldConnection = backgroundState.stopTimer !== null;- clearBackgroundStopTimer();- const backgroundedForMs = backgroundState.backgroundAt > 0 ? Date.now() - backgroundState.backgroundAt : 0;- backgroundState.backgroundAt = 0;- if (heldConnection && backgroundedForMs > BACKGROUND_SUSPEND_SUSPECT_MS) {- // 宽限计时器没来得及触发但后台已超阈值:JS 被挂起过,socket 大概率- // 已被系统回收而状态机仍认为 online——主动换新连接,别等心跳才发现假活。- client.stop();- }// 回前台立刻重连:绕开断线后遗留的指数退避计时器(可能 park 到 30s),// 让"打开 App → 打开会话"路径快速恢复在线,而不是干等退避。// overrideCongestionCooldown:用户显式回前台是拥塞冷却的合法豁免——// 冷却默认只拦请求路径的 un-park(waitUntilOnline),不拦真人操作。- client.connectNow('appstate-active', { overrideCongestionCooldown: true });+ backgroundConnection.active();// 快速切换(连接被宽限保住、始终 online)不会有 online 状态转换,这条显式// 补齐就是断档回填的唯一触发点;其余路径下它因 status 未 online 而空转。void rehydrateWithClient(client);@@ -1110,26 +1107,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {// 后若订阅残留(宽限窗、挂起延迟最长可拖到 server 60s 空闲清扫),恰好在// 用户离开的瞬间完成的任务就永远收不到通知。只动远端订阅与 ack 簿记,// registry 所有权保留 —— 回前台的 rehydrate 会因 ack 已清而重新订阅。- for (const release of releaseHeavyTopics()) {- void release.catch(() => undefined);- }- // 短暂宽限再断:几秒内切回的快速 App 切换不触发整套断连/重连/补齐。- // iOS 挂起后计时器不再运行,恢复时由上面的 active 分支收拾残局。- backgroundState.backgroundAt = Date.now();- clearBackgroundStopTimer();- backgroundState.stopTimer = setTimeout(() => {- backgroundState.stopTimer = null;- if (AppState.currentState !== 'background') return;- // 已发出的 stale subscribe 无法撤回;断开前再幂等释放一次并等待已发出的- // unsubscribe 收尾,确保最后落到桌面端的 session topic 状态仍是释放。- const finalRelease = Promise.allSettled(releaseHeavyTopics());- const boundedWait = new Promise<void>((resolve) => {- setTimeout(resolve, BACKGROUND_FINAL_UNSUBSCRIBE_WAIT_MS);- });- void Promise.race([finalRelease, boundedWait]).finally(() => {- if (AppState.currentState === 'background') client.stop();- });- }, BACKGROUND_STOP_GRACE_MS);+ backgroundConnection.background();}});@@ -1151,7 +1129,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {disposed = true;networkSubscription?.remove();sub.remove();- clearBackgroundStopTimer();+ backgroundConnection.dispose();offUnresponsive();offResponseEvidence();offBeforeLink();@@ -1382,7 +1360,8 @@ async function rebuildSessionSnapshot(deviceId: string,sessionId: string,connectionEpoch: number,- opts?: DeviceLinkRehydrateSendOptions,+ opts: DeviceLinkRehydrateSendOptions | undefined,+ isCurrent: () => boolean,): Promise<void> {// 这四个并发请求是同一轮补齐:一次路由抖动可能让它们同时等满超时,但这只// 代表一个独立故障观测。共享显式 cohort,避免单轮 fan-out 直接凑满 3 次阈值。@@ -1400,14 +1379,67 @@ async function rebuildSessionSnapshot(const unenteredMessageAuthorityAtRequestStart = messageDetailEnteredAtRequestStart? null: remoteSessionStore.captureUnenteredSessionMessageAuthority(sessionId);- const snapshotScope = { deviceId, sessionId, connectionEpoch };+ const snapshotScope = { deviceId, sessionId, connectionEpoch, subscriptionIdentity: opts?.subscriptionIdentity };const pendingSnapshotAtRequestStart = remoteSessionStore.getPendingInteractions(sessionId);// 四路快照独立拉取、独立落库:断连补齐窗口本就脆弱,一个子请求失败不应拖垮// 其余(旧实现共用一个 catch,任一失败三份快照全丢)。goal 覆盖断连窗口内// 丢失的 maker:goal:status-changed push;model-pref / turn-cost 无对应查询通道,// 暂不在补齐范围(需扩桌面端 invoke 白名单)。- const [history, pending, projection, goal] = await Promise.allSettled([- runSessionMessagesSnapshotSingleFlight(+ const applyHistory = (value: RemoteMessage[]) => {+ if (!isCurrent()) return;+ if (Array.isArray(value)) {+ // moreBeyondWindow:这一页上沿之外服务端还有历史(满 80 条,或被 device-link 裁过行)。为真时+ // store 不保留早于本页的缓存段 —— 断连期间漏收的 push 可能正落在两段之间,保留就在窗口里+ // 留下孤岛,而漏收的量不大时两侧时间差很小、时间阈值的空洞检测发现不了(#1222)。+ const windowOptions = {+ moreBeyondWindow: hasMoreOlderMessages(value, RECONNECT_MESSAGE_WINDOW_LIMIT),+ };+ if (messageAuthorityAtRequestStart) {+ remoteSessionStore.setLatestMessageWindow(sessionId, value, {+ ...windowOptions,+ authority: messageAuthorityAtRequestStart,+ });+ } else if (+ unenteredMessageAuthorityAtRequestStart+ && remoteSessionStore.canCommitUnenteredSessionMessageWindow(+ unenteredMessageAuthorityAtRequestStart,+ deviceId,+ )+ ) {+ // 从未打开过的 regular 仍承担首页/全局消息镜像;但请求飞行期间只要发生过+ // enter / leave / forget / clear,生命周期 fence 就会失效,旧重连响应不得越过+ // 新生命周期。Store 同时校验 regular retention 与物理设备归属,避免旧设备响应+ // 写回新 shard。+ remoteSessionStore.setLatestMessageWindow(sessionId, value, windowOptions);+ }+ }+ };+ const applyPending = (value: PendingInteraction[]) => {+ if (!isCurrent()) return;+ if (Array.isArray(value)) {+ remoteSessionStore.setPendingInteractions(sessionId, value, { finalizeStreaming: true });+ }+ };+ const applyProjection = (value: InputProjection) => {+ if (!isCurrent()) return;+ if (value) {+ remoteSessionStore.setInputProjectionIfCurrent(+ sessionId,+ value,+ projectionEpochAtRequestStart,+ );+ }+ };+ const applyGoal = (value: MobileGoalStatusPayload | null | undefined) => {+ if (!isCurrent()) return;+ // undefined = 未拿到/未知(兼容形态的空返回),不能当作权威「无 goal」落库——+ // 那会把在世的 goal 卡清掉直到下一条 push;只有显式 null 才代表确认无 goal。+ if (value !== undefined) {+ remoteSessionStore.setGoalStatus(sessionId, value);+ }+ };+ const [history, pending, projection, goal] = await Promise.all([+ settleProgressiveSnapshot(runSessionMessagesSnapshotSingleFlight(snapshotScope,RECONNECT_MESSAGE_WINDOW_LIMIT,messageAuthorityAtRequestStart@@ -1424,8 +1456,8 @@ async function rebuildSessionSnapshot([sessionId, { limit: RECONNECT_MESSAGE_WINDOW_LIMIT }],sendOpts,),- ),- runSessionPendingInteractionsSnapshotSingleFlight(+ ), applyHistory),+ settleProgressiveSnapshot(runSessionPendingInteractionsSnapshotSingleFlight(snapshotScope,pendingSnapshotAtRequestStart,() => sendInvokeWithAccessHandling<PendingInteraction[]>(@@ -1435,8 +1467,8 @@ async function rebuildSessionSnapshot([sessionId],sendOpts,),- ),- runSessionProjectionSnapshotSingleFlight(+ ), applyPending),+ settleProgressiveSnapshot(runSessionProjectionSnapshotSingleFlight(snapshotScope,projectionEpochAtRequestStart,() => sendInvokeWithAccessHandling<InputProjection>(@@ -1446,56 +1478,15 @@ async function rebuildSessionSnapshot([sessionId],sendOpts,),- ),- sendInvokeWithAccessHandling<MobileGoalStatusPayload | null | undefined>(+ ), applyProjection),+ settleProgressiveSnapshot(sendInvokeWithAccessHandling<MobileGoalStatusPayload | null | undefined>(client,deviceId,'maker:goal:get-status',[sessionId],sendOpts,- ),+ ), applyGoal),]);- if (history.status === 'fulfilled' && Array.isArray(history.value)) {- // moreBeyondWindow:这一页上沿之外服务端还有历史(满 80 条,或被 device-link 裁过行)。为真时- // store 不保留早于本页的缓存段 —— 断连期间漏收的 push 可能正落在两段之间,保留就在窗口里- // 留下孤岛,而漏收的量不大时两侧时间差很小、时间阈值的空洞检测发现不了(#1222)。- const windowOptions = {- moreBeyondWindow: hasMoreOlderMessages(history.value, RECONNECT_MESSAGE_WINDOW_LIMIT),- };- if (messageAuthorityAtRequestStart) {- remoteSessionStore.setLatestMessageWindow(sessionId, history.value, {- ...windowOptions,- authority: messageAuthorityAtRequestStart,- });- } else if (- unenteredMessageAuthorityAtRequestStart- && remoteSessionStore.canCommitUnenteredSessionMessageWindow(- unenteredMessageAuthorityAtRequestStart,- deviceId,- )- ) {- // 从未打开过的 regular 仍承担首页/全局消息镜像;但请求飞行期间只要发生过- // enter / leave / forget / clear,生命周期 fence 就会失效,旧重连响应不得越过- // 新生命周期。Store 同时校验 regular retention 与物理设备归属,避免旧设备响应- // 写回新 shard。- remoteSessionStore.setLatestMessageWindow(sessionId, history.value, windowOptions);- }- }- if (pending.status === 'fulfilled' && Array.isArray(pending.value)) {- remoteSessionStore.setPendingInteractions(sessionId, pending.value, { finalizeStreaming: true });- }- if (projection.status === 'fulfilled' && projection.value) {- remoteSessionStore.setInputProjectionIfCurrent(- sessionId,- projection.value,- projectionEpochAtRequestStart,- );- }- // undefined = 未拿到/未知(兼容形态的空返回),不能当作权威「无 goal」落库——- // 那会把在世的 goal 卡清掉直到下一条 push;只有显式 null 才代表确认无 goal。- if (goal.status === 'fulfilled' && goal.value !== undefined) {- remoteSessionStore.setGoalStatus(sessionId, goal.value);- }// 任一子快照瞬时失败 → 上抛让 rehydrate 计入重试;永久失败(老被控端无 goal// 通道的 CHANNEL_NOT_ALLOWED、权限撤销等)吞掉,重试没有意义。同批若已有// fulfilled 目标应答,兄弟 unavailable 只能算局部瞬态,不能升级为整机 verdict。diff --git a/apps/mobile/src/device-link/backgroundConnection.ts b/apps/mobile/src/device-link/backgroundConnection.tsnew file mode 100644index 0000000000..9051ee2b5c--- /dev/null+++ b/apps/mobile/src/device-link/backgroundConnection.ts@@ -0,0 +1,58 @@+interface BackgroundConnectionOptions {+ isBackground(): boolean;+ releaseTopics(): Promise<void>[];+ stop(): void;+ connect(): void;+ graceMs: number;+ releaseWaitMs: number;+ suspendMs: number;+}++/** Owns the background grace period, including the async unsubscribe tail after its timer fires. */+export function createBackgroundConnection(options: BackgroundConnectionOptions) {+ let backgroundAt: number | null = null;+ let generation = 0;+ let stopTimer: ReturnType<typeof setTimeout> | null = null;+ let releaseTimer: ReturnType<typeof setTimeout> | null = null;+ const clearTimers = () => {+ if (stopTimer !== null) clearTimeout(stopTimer);+ if (releaseTimer !== null) clearTimeout(releaseTimer);+ stopTimer = releaseTimer = null;+ };+ return {+ background() {+ clearTimers();+ const captured = ++generation;+ backgroundAt = Date.now();+ for (const release of options.releaseTopics()) void release.catch(() => undefined);+ stopTimer = setTimeout(() => {+ stopTimer = null;+ if (!options.isBackground() || generation !== captured) return;+ const releases = Promise.allSettled(options.releaseTopics());+ const boundedWait = new Promise<void>((resolve) => {+ releaseTimer = setTimeout(resolve, options.releaseWaitMs);+ });+ void Promise.race([releases, boundedWait]).finally(() => {+ if (generation !== captured) return;+ clearTimers();+ if (options.isBackground()) options.stop();+ });+ }, options.graceMs);+ },+ active() {+ const elapsed = backgroundAt === null ? 0 : Date.now() - backgroundAt;+ backgroundAt = null;+ generation += 1;+ clearTimers();+ // A timer reference cannot tell whether the socket was actually stopped:+ // JS can be suspended while the final unsubscribe is still awaiting ACK.+ if (elapsed > options.suspendMs) options.stop();+ options.connect();+ },+ dispose() {+ generation += 1;+ backgroundAt = null;+ clearTimers();+ },+ };+}diff --git a/apps/mobile/src/device-link/rehydrate.ts b/apps/mobile/src/device-link/rehydrate.tsindex 2d02370112..d389c496d8 100644--- a/apps/mobile/src/device-link/rehydrate.ts+++ b/apps/mobile/src/device-link/rehydrate.ts@@ -1,8 +1,10 @@import type { Topic } from '@cindy/device-link';import type { RehydratePlan } from '@/device-link/topicRegistry';import { isTransientRemoteError } from '@/device-link/remoteRetry';+import { SnapshotReadSupersededError } from '@/device-link/sessionSnapshotSingleFlight';export interface DeviceLinkRehydrateSendOptions {+ subscriptionIdentity?: number | null;/** 同一设备的一轮快照 fan-out 共享一个响应性观测 cohort。 */responsivenessCohort?: number;}@@ -233,6 +235,12 @@ export function classifySnapshotBatchFailure(&& !isRemoteDisabledError(result.reason),);if (availabilityRejections.length === 0) {+ // A detail caller may invalidate a shared physical response while this peer's+ // recovery is still current. Reuse the existing retry path rather than mark+ // recovery complete or allow that old response to overwrite a fresh window.+ if (rejections.some((result) => result.reason instanceof SnapshotReadSupersededError)) {+ return { kind: 'partial-transient' };+ }return otherTransient? { kind: 'reject', error: otherTransient.reason }: { kind: 'none' };diff --git a/apps/mobile/src/device-link/remoteSyncTask.ts b/apps/mobile/src/device-link/remoteSyncTask.tsindex 3c1cc85d83..6545c62961 100644--- a/apps/mobile/src/device-link/remoteSyncTask.ts+++ b/apps/mobile/src/device-link/remoteSyncTask.ts@@ -1,4 +1,5 @@import { useCallback, useEffect, useLayoutEffect, useRef } from 'react';+import { withTransientRemoteRetry } from './remoteRetry';export interface RemoteSyncRunner {run(): Promise<void>;@@ -103,6 +104,32 @@ export interface RemoteSyncRun {replaceMessages: boolean;/** 请求发起后 sync identity / 权威替换发生变化时,旧结果不得再提交。 */isStale(): boolean;+ signal: AbortSignal;+ /** A successful snapshot may cover a notification queued while it was starting. */+ satisfy(reason: string): void;+}++/** Cancels the local wait; late transport replies remain fenced by isStale/authority. */+export function waitForRemoteSync<T>(signal: AbortSignal, operation: () => Promise<T>): Promise<T> {+ if (signal.aborted) return Promise.reject(new Error('Remote sync superseded'));+ return new Promise<T>((resolve, reject) => {+ const abort = () => reject(new Error('Remote sync superseded'));+ signal.addEventListener('abort', abort, { once: true });+ try {+ operation().then(resolve, reject).finally(() => signal.removeEventListener('abort', abort));+ } catch (error) {+ signal.removeEventListener('abort', abort);+ reject(error);+ }+ });+}++/** Invalidation interrupts both an in-flight read and retry backoff, without reopening a stale peer. */+export function retryRemoteSyncRead<T>(run: Pick<RemoteSyncRun, 'signal' | 'isStale'>, read: () => Promise<T>): Promise<T> {+ return waitForRemoteSync(run.signal, () => withTransientRemoteRetry(() => {+ if (run.isStale()) throw new Error('Remote sync superseded');+ return waitForRemoteSync(run.signal, read);+ }));}export interface RemoteSyncCoordinator {@@ -127,7 +154,7 @@ function mergeRemoteSyncRequest(}/**- * Session sync coordinator:同一时刻最多一轮网络读取,被动触发合并成至多一轮 follow-up。+ * Session sync coordinator:同一时刻最多一轮有效读取,被动触发合并成至多一轮 follow-up。* context 变化会使旧轮次失效;权威整窗替换还会立即废弃同 context 的旧普通读取,* 防止 rewind 后迟到的 reopen 结果把已删除消息重新写回。*/@@ -138,21 +165,40 @@ export function createRemoteSyncCoordinator(let generation = 0;let inFlight: Promise<void> | null = null;let pending: PendingRemoteSync | null = null;+ let controller: AbortController | null = null;const drain = async (): Promise<void> => {let firstError: unknown = null;while (pending) {const next = pending;pending = null;- const capturedGeneration = generation;+ // A sibling of a failed Promise.all may still be settling when the next+ // run starts, even without a connection change. It cannot commit over it.+ const capturedGeneration = ++generation;+ const runController = new AbortController();+ controller = runController;try {- await task({+ const run: RemoteSyncRun = {reasons: [...next.reasons],replaceMessages: next.replaceMessages,- isStale: () => generation !== capturedGeneration,- });+ isStale: () => generation !== capturedGeneration || runController.signal.aborted,+ signal: runController.signal,+ satisfy(reason) {+ if (generation !== capturedGeneration || !pending) return;+ pending.reasons.delete(reason);+ if (pending.reasons.size === 0 && !pending.replaceMessages) pending = null;+ },+ };+ // Start synchronously so callers can enqueue a follow-up in this same turn.+ const result = task(run);+ void result.catch(() => undefined);+ await waitForRemoteSync(runController.signal, () => result);} catch (error) {- firstError ??= error;+ const cancelled = runController.signal.aborted;+ runController.abort();+ if (!cancelled && generation === capturedGeneration) firstError ??= error;+ } finally {+ if (controller === runController) controller = null;}}if (firstError !== null) throw firstError;@@ -163,6 +209,7 @@ export function createRemoteSyncCoordinator(if (contextKey === nextContextKey) return;contextKey = nextContextKey;generation += 1;+ controller?.abort();// 旧 identity 尚未执行的 follow-up 没有提交资格;新 identity 的调用方会立即 request。pending = null;},@@ -170,6 +217,7 @@ export function createRemoteSyncCoordinator(if (request.replaceMessages === true) {// 权威替换必须让已经发出的普通窗口读取失效,并独占下一轮 pending options。generation += 1;+ controller?.abort();pending = null;}pending = mergeRemoteSyncRequest(pending, request);@@ -177,6 +225,9 @@ export function createRemoteSyncCoordinator(inFlight = drain().finally(() => {inFlight = null;});+ // Passive refresh callers intentionally do not await. Observe the rejection+ // without changing the promise returned to rewind/navigation callers.+ void inFlight.catch(() => undefined);return inFlight;},isRunning(): boolean {@@ -196,6 +247,7 @@ export function useRemoteSyncCoordinator(taskRef.current = task;coordinatorRef.current?.setContext(contextKey);}, [contextKey, task]);+ useEffect(() => () => coordinatorRef.current?.setContext('unmounted'), []);return useCallback((request: RemoteSyncRequest) => coordinatorRef.current?.request(request) ?? Promise.resolve(),diff --git a/apps/mobile/src/device-link/sessionSnapshotSingleFlight.ts b/apps/mobile/src/device-link/sessionSnapshotSingleFlight.tsindex 716c15a187..70c893aee6 100644--- a/apps/mobile/src/device-link/sessionSnapshotSingleFlight.ts+++ b/apps/mobile/src/device-link/sessionSnapshotSingleFlight.ts@@ -5,6 +5,8 @@ export interface SessionSnapshotRequestIdentity {deviceId: string;sessionId: string;connectionEpoch: number;+ subscriptionIdentity?: number | null;+ signal?: AbortSignal;resource: SessionSnapshotResource;/*** Exact request semantics and local authority fence. Requests only share a@@ -16,7 +18,7 @@ export interface SessionSnapshotRequestIdentity {export type SessionSnapshotScope = Pick<SessionSnapshotRequestIdentity,- 'deviceId' | 'sessionId' | 'connectionEpoch'+ 'deviceId' | 'sessionId' | 'connectionEpoch' | 'subscriptionIdentity' | 'signal'>;export type SessionMessageSnapshotFence =@@ -58,13 +60,25 @@ export function sessionPendingInteractionsSnapshotVariant(return `snapshot=${id}`;}-const inFlightSessionSnapshotRequests = new Map<string, Promise<unknown>>();+interface SnapshotRead {+ promise: Promise<unknown>;+ cancel(): void;+}+/** Local invalidation, not a transport failure or a permanent missing resource. */+export class SnapshotReadSupersededError extends Error {+ constructor() {+ super('Remote sync superseded');+ this.name = 'SnapshotReadSupersededError';+ }+}+const inFlightSessionSnapshotRequests = new Map<string, SnapshotRead>();function requestKey(identity: SessionSnapshotRequestIdentity): string {return JSON.stringify([identity.deviceId,identity.sessionId,identity.connectionEpoch,+ identity.subscriptionIdentity ?? null,identity.resource,identity.variant,]);@@ -78,9 +92,13 @@ export function runSessionSnapshotSingleFlight<T>(identity: SessionSnapshotRequestIdentity,read: () => Promise<T>,): Promise<T> {+ if (identity.signal?.aborted) return Promise.reject(new SnapshotReadSupersededError());const key = requestKey(identity);const current = inFlightSessionSnapshotRequests.get(key);- if (current) return current as Promise<T>;+ if (current) {+ invalidateOnCancellation(key, current, identity.signal);+ return current.promise as Promise<T>;+ }let request: Promise<T>;try {@@ -88,14 +106,37 @@ export function runSessionSnapshotSingleFlight<T>(} catch (error) {request = Promise.reject(error);}- inFlightSessionSnapshotRequests.set(key, request);+ let cancel!: () => void;+ const shared = new Promise<T>((resolve, reject) => {+ cancel = () => reject(new SnapshotReadSupersededError());+ // Always observe the physical response, including rejection after cancellation.+ void request.then(resolve, reject);+ });+ const entry: SnapshotRead = { promise: shared, cancel };+ inFlightSessionSnapshotRequests.set(key, entry);+ invalidateOnCancellation(key, entry, identity.signal);const clear = () => {- if (inFlightSessionSnapshotRequests.get(key) === request) {+ if (inFlightSessionSnapshotRequests.get(key) === entry) {inFlightSessionSnapshotRequests.delete(key);}};- void request.then(clear, clear);- return request;+ void shared.then(clear, clear);+ return shared;+}++/** Cancelled callers must not lend a pre-recovery physical response to a newer run. */+function invalidateOnCancellation(key: string, entry: SnapshotRead, signal?: AbortSignal): void {+ if (!signal) return;+ const invalidate = () => {+ if (inFlightSessionSnapshotRequests.get(key) === entry) inFlightSessionSnapshotRequests.delete(key);+ // All consumers of this exact stale response lose commit eligibility, including+ // a rehydrate caller sharing it with the detail page. Rehydrate classifies this+ // local invalidation as needing a fresh snapshot. Other peers are untouched.+ entry.cancel();+ };+ signal.addEventListener('abort', invalidate, { once: true });+ const clear = () => signal.removeEventListener('abort', invalidate);+ void entry.promise.then(clear, clear);}export function runSessionMessagesSnapshotSingleFlight<T>(@@ -163,6 +204,40 @@ export async function runConnectionScopedSessionMetadataRead<T>(return value;}+/** The visible message window never waits for unrelated control-state snapshots. */+export async function readProgressiveMessageWindow<Metadata, History>(options: {+ readMetadata(): Promise<Metadata>;+ readMessages(): Promise<History>;+ eager: boolean;+ shouldReadMessages(metadata: Metadata): boolean;+ isCurrent(): boolean;+ commitMessages(history: History): void;+}): Promise<{ metadata: Metadata; history: History | null }> {+ const messages = () => runConnectionScopedSessionMetadataRead(+ options.readMessages, options.isCurrent, options.commitMessages,+ );+ const metadata = options.readMetadata();+ const history = options.eager+ ? messages()+ : metadata.then((value) => options.isCurrent() && options.shouldReadMessages(value) ? messages() : null);+ const [metadataValue, historyValue] = await Promise.all([metadata, history]);+ return { metadata: metadataValue, history: historyValue };+}++/** Apply each successful response immediately while retaining allSettled failure classification. */+export async function settleProgressiveSnapshot<T>(+ read: Promise<T>,+ commit: (value: T) => void,+): Promise<PromiseSettledResult<T>> {+ try {+ const value = await read;+ commit(value);+ return { status: 'fulfilled', value };+ } catch (reason) {+ return { status: 'rejected', reason };+ }+}+/*** Applies retry to each read independently. One timeout therefore retries only* that item instead of replaying every sibling request in the opening batch.diff --git a/apps/mobile/src/notifications/PushNotificationsBridge.tsx b/apps/mobile/src/notifications/PushNotificationsBridge.tsxindex 5dd442b5a8..f5fae3891f 100644--- a/apps/mobile/src/notifications/PushNotificationsBridge.tsx+++ b/apps/mobile/src/notifications/PushNotificationsBridge.tsx@@ -3,7 +3,7 @@ import { useCallback, useEffect, useRef } from 'react';import { AppState } from 'react-native';import { useAuth } from '@/auth/AuthContext';import Notifications from './nativeNotifications';-import { parseNotificationResponseDeepLink } from './pushRegistrationModel';+import { notificationRecoveryRoute, parseNotificationResponseDeepLink } from './pushRegistrationModel';import {configureForegroundNotificationBehavior,isPushSupported,@@ -103,7 +103,7 @@ export function PushNotificationsBridge() {if (consumedNotificationResponseKeys.has(dedupeKey)) return;consumedNotificationResponseKeys.add(dedupeKey);void Notifications.clearLastNotificationResponseAsync?.()?.catch(() => undefined);- pendingDeepLinkRef.current = deepLink;+ pendingDeepLinkRef.current = notificationRecoveryRoute(deepLink, dedupeKey);flushPendingDeepLink();};diff --git a/apps/mobile/src/notifications/pushRegistrationModel.ts b/apps/mobile/src/notifications/pushRegistrationModel.tsindex 61af31d0cd..1da568fcb5 100644--- a/apps/mobile/src/notifications/pushRegistrationModel.ts+++ b/apps/mobile/src/notifications/pushRegistrationModel.ts@@ -70,6 +70,18 @@ function parseNotificationPayloadDeepLink(data: unknown): string | null {return parseNotificationDeepLink(record.body) ?? parseNotificationDeepLink(record.data);}+/** Local navigation hint only; neither the push payload nor the device-link protocol changes. */+export function notificationRecoveryRoute(deepLink: string, responseKey: string): string {+ const hashIndex = deepLink.indexOf('#');+ const path = hashIndex < 0 ? deepLink : deepLink.slice(0, hashIndex);+ const fragment = hashIndex < 0 ? '' : deepLink.slice(hashIndex);+ const queryIndex = path.indexOf('?');+ const pathname = queryIndex < 0 ? path : path.slice(0, queryIndex);+ const query = new URLSearchParams(queryIndex < 0 ? '' : path.slice(queryIndex + 1));+ query.set('notificationResponse', responseKey);+ return `${pathname}?${query.toString()}${fragment}`;+}+/*** 从 expo-notifications 的点击响应中解析任务深链。*