Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): coalesce session sync triggers (#1130)
hushaowu-rhe3e5445f54c2
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex 221618800b..bb04af6faf 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -75,7 +75,7 @@ import {} from '@/device-link/remoteStatus';import { agentAuthGateHint, agentAuthGateVerdict } from '@/session/agentAuthGate';import { isTransientRemoteError, withTransientRemoteRetry } from '@/device-link/remoteRetry';-import { useRemoteSyncTask } from '@/device-link/remoteSyncTask';+import { useRemoteSyncCoordinator, type RemoteSyncRun } from '@/device-link/remoteSyncTask';import { useMobileMakerTransport } from '@/device-link/useMobileMakerTransport';import { createMobileMakerTransport } from '@/device-link/mobileMakerTransport';import { startFocusedTopicSubscription } from '@/device-link/focusedTopicSubscription';@@ -1057,7 +1057,7 @@ export default function SessionScreen() {const [controlBusy, setControlBusy] = useState(false);const [messageActionBusy, setMessageActionBusy] = useState<string | null>(null);const [rewindState, setRewindState] = useState<RewindPreviewState>({ kind: 'idle' });- // 切 session 时同步(render 阶段)重置回撤确认框 / busy 态并递增「请求代际」。SessionScreen 切+ // 切 session 时同步(render 阶段)重置回撤确认框 / busy / loading 态并递增「请求代际」。SessionScreen 切// session 复用实例、不 remount,这些本地 UI state 不会自动重置,残留会让确认框跨 session 出现且// 无法自愈(messageActionBusy 残留还会置灰目标 session 的消息操作栏)。用 React 官方「prop 变化时// 调整 state」的 render 阶段模式而非 useEffect:同步生效,既无切换首帧的残留闪帧,也不留「路由已切、@@ -1068,6 +1068,7 @@ export default function SessionScreen() {setPrevRewindSessionId(sessionId);setRewindState({ kind: 'idle' });setMessageActionBusy(null);+ setLoading(false);rewindRequestSeqRef.current += 1;}const [contextLoading, setContextLoading] = useState(false);@@ -2816,12 +2817,16 @@ export default function SessionScreen() {};}, [connectionEpoch, deviceId, lastSyncedAt, maker, openLink, sessionAgentSwitchSupported, sessionId]);- const syncSession = useCallback(async (options: { replaceMessages?: boolean } = {}) => {- if (!deviceId || !sessionId) return;+ const syncSession = useCallback(async (syncRun: Pick<RemoteSyncRun, 'isStale' | 'replaceMessages'>) => {+ const options = { replaceMessages: syncRun.replaceMessages };+ if (!deviceId || !sessionId || syncRun.isStale()) return;// 新建会话乐观管线在途(running / create-failed):被控端可能还没有这个会话,// getSession 会 NOT_FOUND 报错横幅。统一在这里挡掉全部 load 触发点;管线完成// (task 移除)后由下方 effect 触发一轮真正的同步。- if (shouldBlockSessionSync(sessionId)) return;+ if (shouldBlockSessionSync(sessionId)) {+ if (!syncRun.isStale()) setLoading(false);+ return;+ }// 已读回执门槛的 epoch 必须在 sync **开始**时捕获:重连时 connectionEpoch 先行推进,// 旧连接代的 in-flight load 若在尾部读 ref 的最新值,会把旧窗口数据标成新代已同步,// 抢在排队的 resync 之前放行回执。开始时捕获则旧 load 落的是旧代 key,门槛不放行。@@ -2849,6 +2854,7 @@ export default function SessionScreen() {const activeSessions = await maker.listActiveSessions().catch(() => []);return { activeSessions, activityEpochAtFetchStart };};+ if (syncRun.isStale()) return;setLoading(true);setError(null);try {@@ -2864,6 +2870,7 @@ export default function SessionScreen() {fetchActiveSessionSnapshot(),]);});+ if (syncRun.isStale()) return;remoteSessionStore.upsertDeviceSession(deviceId, deviceName, sessionMeta);remoteSessionStore.setActiveSessionSnapshots(deviceId,@@ -2903,6 +2910,7 @@ export default function SessionScreen() {messageWindowSynced: remoteSessionStore.isSessionMessageWindowSynced(sessionId, sessionMeta),storedSession: storedSessionAtStart,});+ if (syncRun.isStale()) return;remoteSessionStore.upsertDeviceSession(deviceId, deviceName, sessionMeta);remoteSessionStore.setActiveSessionSnapshots(deviceId,@@ -2918,6 +2926,7 @@ export default function SessionScreen() {REOPEN_MESSAGE_WINDOW_LIMITS,),);+ if (syncRun.isStale()) return;const historyPage: RemoteMessage[] = Array.isArray(history.messages) ? history.messages : [];remoteSessionStore.setLatestMessageWindow(sessionId, historyPage);remoteSessionStore.markSessionMessagesSynced(sessionId, sessionMeta);@@ -2934,6 +2943,7 @@ export default function SessionScreen() {// 不变量:上面 setHasOlderMessages 的校正(:806/:841/:846)与这里的 setLastSyncedAt 之间必须保持// 同步尾、无 await —— 否则乐观点亮 effect(依赖 lastSyncedAt===null)会在 await 间隙把刚校正成 false// 的「加载更早」入口重新点亮。将来切勿在两者之间插入 await。+ if (syncRun.isStale()) return;setLastSyncedAt(Date.now());// 已读回执门槛:本会话在当前连接代完成过整窗同步。sessionId / epoch / 门槛代号// 都取 sync 开始时的快照——原地切 session、重连、attention 上升沿之后,启动更早@@ -2942,12 +2952,19 @@ export default function SessionScreen() {setReadAckSyncedKey(`${sessionId}:${readAckEpochAtStart}`);}} catch (err) {- setError(formatRemoteError(err));+ if (!syncRun.isStale()) setError(formatRemoteError(err));} finally {- setLoading(false);+ if (!syncRun.isStale()) setLoading(false);}}, [deviceId, deviceName, maker, openLink, sessionId, subscribe]);- const load = useRemoteSyncTask(() => syncSession());+ const requestSync = useRemoteSyncCoordinator(+ (run) => syncSession(run),+ `${deviceId}:${sessionId}`,+ );+ const load = useCallback(+ () => requestSync({ reason: 'passive-refresh' }),+ [requestSync],+ );/** 恢复路径里装不下的附件:中转对象回收,不留无人认领的已上传对象。 */const discardRecoveredAttachments = (attachments: readonly RemoteSerializedAttachment[]) => {@@ -7155,7 +7172,7 @@ export default function SessionScreen() {));clearQuotes(sessionId);setRewindState({ kind: 'idle' });- await syncSession({ replaceMessages: true });+ await requestSync({ reason: 'rewind-commit', replaceMessages: true });} catch (err) {if (rewindRequestSeqRef.current !== seq) return;setError(formatRemoteError(err));@@ -7171,7 +7188,7 @@ export default function SessionScreen() {} finally {if (rewindRequestSeqRef.current === seq) setMessageActionBusy(null);}- }, [applyComposerDocument, deviceId, maker, messageActionBusy, rewindState, sessionId, syncSession]);+ }, [applyComposerDocument, deviceId, maker, messageActionBusy, requestSync, rewindState, sessionId]);return (<View style={styles.safeArea} testID="session.screen">@@ -7226,7 +7243,7 @@ export default function SessionScreen() {issue={connectionIssue}lastSyncedAt={lastSyncedAt}loading={loading}- onSync={() => void load()}+ onSync={() => void requestSync({ reason: 'manual', replaceMessages: false })}status={status}variant="inline"/>@@ -7487,7 +7504,7 @@ export default function SessionScreen() {// 设备真不可用(离线/被撤销):消息区保留阻塞占位和重试入口;底部 composer 仍可编辑草稿。<SessionSyncPlaceholderloading={loading}- onSync={() => void load()}+ onSync={() => void requestSync({ reason: 'manual', replaceMessages: false })}/>) : (<>diff --git a/apps/mobile/src/__tests__/remoteSyncTask.test.ts b/apps/mobile/src/__tests__/remoteSyncTask.test.tsindex 5335020aed..fa53126980 100644--- a/apps/mobile/src/__tests__/remoteSyncTask.test.ts+++ b/apps/mobile/src/__tests__/remoteSyncTask.test.ts@@ -1,5 +1,7 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';import { describe, expect, it } from 'vitest';-import { createRemoteSyncRunner } from '@/device-link/remoteSyncTask';+import { createRemoteSyncCoordinator, createRemoteSyncRunner } from '@/device-link/remoteSyncTask';function deferred() {let resolve!: () => void;@@ -13,6 +15,10 @@ function nextTick(): Promise<void> {return new Promise((resolve) => setTimeout(resolve, 0));}+function readSessionScreenSource(): string {+ return readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8').replace(/\r\n/g, '\n');+}+describe('remote sync task runner', () => {it('coalesces repeated triggers into one in-flight run and one follow-up run', async () => {const gates = [deferred(), deferred()];@@ -55,3 +61,135 @@ describe('remote sync task runner', () => {expect(count).toBe(2);});});++describe('remote sync coordinator', () => {+ it('merges repeated passive requests into one follow-up run', async () => {+ const gates = [deferred(), deferred()];+ const runs: Array<{ reasons: readonly string[]; replaceMessages: boolean }> = [];+ const coordinator = createRemoteSyncCoordinator(async (run) => {+ const index = runs.length;+ runs.push({ reasons: run.reasons, replaceMessages: run.replaceMessages });+ await gates[index].promise;+ });+ coordinator.setContext('dev-1:session-1');++ const first = coordinator.request({ reason: 'mount' });+ const second = coordinator.request({ reason: 'presence' });+ const third = coordinator.request({ reason: 'breaker' });++ expect(second).toBe(first);+ expect(third).toBe(first);+ expect(runs).toEqual([{ reasons: ['mount'], replaceMessages: false }]);++ gates[0].resolve();+ await nextTick();+ expect(runs).toEqual([+ { reasons: ['mount'], replaceMessages: false },+ { reasons: ['presence', 'breaker'], replaceMessages: false },+ ]);++ gates[1].resolve();+ await first;+ expect(coordinator.isRunning()).toBe(false);+ });++ it('lets an authoritative replacement invalidate an in-flight passive run', async () => {+ const gates = [deferred(), deferred()];+ const staleChecks: Array<() => boolean> = [];+ const replaceModes: boolean[] = [];+ const coordinator = createRemoteSyncCoordinator(async (run) => {+ const index = replaceModes.length;+ replaceModes.push(run.replaceMessages);+ staleChecks.push(run.isStale);+ await gates[index].promise;+ });+ coordinator.setContext('dev-1:session-1');++ const task = coordinator.request({ reason: 'mount' });+ expect(staleChecks[0]()).toBe(false);+ void coordinator.request({ reason: 'rewind', replaceMessages: true });+ expect(staleChecks[0]()).toBe(true);++ gates[0].resolve();+ await nextTick();+ expect(replaceModes).toEqual([false, true]);+ expect(staleChecks[1]()).toBe(false);++ gates[1].resolve();+ await task;+ });++ it('invalidates old identity runs and drops their queued follow-up', async () => {+ const gates = [deferred(), deferred()];+ const runs: Array<{ reasons: readonly string[]; isStale: () => boolean }> = [];+ const coordinator = createRemoteSyncCoordinator(async (run) => {+ const index = runs.length;+ runs.push({ reasons: run.reasons, isStale: run.isStale });+ await gates[index].promise;+ });+ coordinator.setContext('dev-1:session-a');++ const task = coordinator.request({ reason: 'mount-a' });+ void coordinator.request({ reason: 'retry-a' });+ coordinator.setContext('dev-1:session-b');+ void coordinator.request({ reason: 'mount-b' });++ expect(runs[0].isStale()).toBe(true);+ gates[0].resolve();+ await nextTick();+ expect(runs.map((run) => run.reasons)).toEqual([['mount-a'], ['mount-b']]);+ expect(runs[1].isStale()).toBe(false);++ gates[1].resolve();+ await task;+ });++ it('continues with a queued follow-up after a failed run', async () => {+ const runs: string[][] = [];+ const firstStarted = deferred();+ const coordinator = createRemoteSyncCoordinator(async (run) => {+ runs.push([...run.reasons]);+ if (runs.length === 1) {+ firstStarted.resolve();+ await nextTick();+ throw new Error('first failed');+ }+ });+ coordinator.setContext('dev-1:session-1');++ const task = coordinator.request({ reason: 'first' });+ await firstStarted.promise;+ void coordinator.request({ reason: 'follow-up' });++ await expect(task).rejects.toThrow('first failed');+ expect(runs).toEqual([['first'], ['follow-up']]);+ });++ it('clears loading when a queued sync is blocked for a newly-created session', () => {+ const source = readSessionScreenSource();+ expect(source).toContain(+ 'if (shouldBlockSessionSync(sessionId)) {\n if (!syncRun.isStale()) setLoading(false);\n return;\n }',+ );+ });++ it('resets loading when the reused screen switches sessions', () => {+ const source = readSessionScreenSource();+ expect(source).toContain(+ 'setRewindState({ kind: \'idle\' });\n setMessageActionBusy(null);\n setLoading(false);',+ );+ });++ it('applies coordinator context and task changes after render commits', () => {+ const source = readFileSync(+ resolve(process.cwd(), 'src/device-link/remoteSyncTask.ts'),+ 'utf8',+ ).replace(/\r\n/g, '\n');+ expect(source).toContain(+ 'useLayoutEffect(() => {\n taskRef.current = task;\n coordinatorRef.current?.setContext(contextKey);\n }, [contextKey, task]);',+ );+ expect(source).not.toContain(+ ' taskRef.current = task;\n const coordinatorRef =',+ );+ expect(source).not.toContain('coordinatorRef.current.setContext(contextKey);');+ });+});diff --git a/apps/mobile/src/device-link/remoteSyncTask.ts b/apps/mobile/src/device-link/remoteSyncTask.tsindex 13b0c74ba7..e1157625a2 100644--- a/apps/mobile/src/device-link/remoteSyncTask.ts+++ b/apps/mobile/src/device-link/remoteSyncTask.ts@@ -1,4 +1,4 @@-import { useCallback, useEffect, useRef } from 'react';+import { useCallback, useEffect, useLayoutEffect, useRef } from 'react';export interface RemoteSyncRunner {run(): Promise<void>;@@ -52,3 +52,114 @@ export function useRemoteSyncTask(task: () => Promise<void>): () => Promise<voidreturn useCallback(() => runnerRef.current?.run() ?? Promise.resolve(), []);}++export interface RemoteSyncRequest {+ reason: string;+ /** 权威整窗替换(如 rewind commit):使当前在途普通读取失效,并在后续轮次胜出。 */+ replaceMessages?: boolean;+}++export interface RemoteSyncRun {+ reasons: readonly string[];+ replaceMessages: boolean;+ /** 请求发起后 sync identity / 权威替换发生变化时,旧结果不得再提交。 */+ isStale(): boolean;+}++export interface RemoteSyncCoordinator {+ setContext(contextKey: string): void;+ request(request: RemoteSyncRequest): Promise<void>;+ isRunning(): boolean;+}++interface PendingRemoteSync {+ reasons: Set<string>;+ replaceMessages: boolean;+}++function mergeRemoteSyncRequest(+ current: PendingRemoteSync | null,+ request: RemoteSyncRequest,+): PendingRemoteSync {+ const next = current ?? { reasons: new Set<string>(), replaceMessages: false };+ next.reasons.add(request.reason);+ next.replaceMessages = next.replaceMessages || request.replaceMessages === true;+ return next;+}++/**+ * Session sync coordinator:同一时刻最多一轮网络读取,被动触发合并成至多一轮 follow-up。+ * context 变化会使旧轮次失效;权威整窗替换还会立即废弃同 context 的旧普通读取,+ * 防止 rewind 后迟到的 reopen 结果把已删除消息重新写回。+ */+export function createRemoteSyncCoordinator(+ task: (run: RemoteSyncRun) => Promise<void>,+): RemoteSyncCoordinator {+ let contextKey: string | null = null;+ let generation = 0;+ let inFlight: Promise<void> | null = null;+ let pending: PendingRemoteSync | null = null;++ const drain = async (): Promise<void> => {+ let firstError: unknown = null;+ while (pending) {+ const next = pending;+ pending = null;+ const capturedGeneration = generation;+ try {+ await task({+ reasons: [...next.reasons],+ replaceMessages: next.replaceMessages,+ isStale: () => generation !== capturedGeneration,+ });+ } catch (error) {+ firstError ??= error;+ }+ }+ if (firstError !== null) throw firstError;+ };++ return {+ setContext(nextContextKey: string): void {+ if (contextKey === nextContextKey) return;+ contextKey = nextContextKey;+ generation += 1;+ // 旧 identity 尚未执行的 follow-up 没有提交资格;新 identity 的调用方会立即 request。+ pending = null;+ },+ request(request: RemoteSyncRequest): Promise<void> {+ if (request.replaceMessages === true) {+ // 权威替换必须让已经发出的普通窗口读取失效,并独占下一轮 pending options。+ generation += 1;+ pending = null;+ }+ pending = mergeRemoteSyncRequest(pending, request);+ if (inFlight) return inFlight;+ inFlight = drain().finally(() => {+ inFlight = null;+ });+ return inFlight;+ },+ isRunning(): boolean {+ return inFlight !== null;+ },+ };+}++export function useRemoteSyncCoordinator(+ task: (run: RemoteSyncRun) => Promise<void>,+ contextKey: string,+): (request: RemoteSyncRequest) => Promise<void> {+ const taskRef = useRef(task);+ const coordinatorRef = useRef<RemoteSyncCoordinator | null>(null);+ coordinatorRef.current ??= createRemoteSyncCoordinator((run) => taskRef.current(run));+ useLayoutEffect(() => {+ taskRef.current = task;+ coordinatorRef.current?.setContext(contextKey);+ }, [contextKey, task]);++ return useCallback(+ (request: RemoteSyncRequest) => coordinatorRef.current?.request(request) ?? Promise.resolve(),+ [],+ );+}