Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 中继离线时释放独立文件连接
Dashd78b10c117fe
diff --git a/apps/mobile/src/__tests__/fileWebViewTermination.test.tsx b/apps/mobile/src/__tests__/fileWebViewTermination.test.tsxindex 65ad6c7a6f..b376fb9336 100644--- a/apps/mobile/src/__tests__/fileWebViewTermination.test.tsx+++ b/apps/mobile/src/__tests__/fileWebViewTermination.test.tsx@@ -39,7 +39,7 @@ vi.mock('react-native-webview', async () => {vi.mock('expo-file-system', () => ({ Directory: class { exists = false; }, File: class {}, Paths: { cache: '/cache' } }));vi.mock('expo-crypto', () => ({ randomUUID: () => 'id' }));vi.mock('@/auth/AuthContext', () => ({ useAuth: () => ({ isAuthenticated: true, user: { id: 'a' }, accountGeneration: 1 }) }));-vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => ({ connectionEpoch: 1, invoke: vi.fn() }) }));+vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => ({ connectionEpoch: 1, status: 'online', invoke: vi.fn() }) }));vi.mock('@/config/env', () => ({ DEVICE_LINK_API_BASE_URL: 'https://example.test', getActiveMobileSessionRealm: () => 'global' }));vi.mock('@/device-link/peerFileRegistry', () => ({installPeerFileDownload: (...args: unknown[]) => { state.install(...args); return state.unregister; },diff --git a/apps/mobile/src/__tests__/peerFileLifecycle.test.tsx b/apps/mobile/src/__tests__/peerFileLifecycle.test.tsxindex a2e0666c1b..f8437ff66c 100644--- a/apps/mobile/src/__tests__/peerFileLifecycle.test.tsx+++ b/apps/mobile/src/__tests__/peerFileLifecycle.test.tsx@@ -8,6 +8,9 @@ const state = vi.hoisted(() => ({props: {} as any,sequence: 0,sessionBound: true,+ status: "online",+ connectionEpoch: 1,+ mounted: false,app: "active",change: (_state: string) => {},upload: undefined as any,@@ -41,10 +44,14 @@ vi.mock("react-native", () => ({},}));vi.mock("react-native-webview", async () => {- const { forwardRef, useImperativeHandle } = await import("react");+ const { forwardRef, useImperativeHandle, useEffect } = await import("react");return {WebView: forwardRef((props: any, ref) => {state.props = props;+ useEffect(() => {+ state.mounted = true;+ return () => { state.mounted = false; };+ }, []);useImperativeHandle(ref, () => ({injectJavaScript(script: string) {const match = /^window.filePeerMessage\((.*)\);true;$/.exec(script);@@ -102,7 +109,8 @@ vi.mock("@/auth/AuthContext", () => ({}));vi.mock("@/device-link/DeviceLinkContext", () => ({useDeviceLink: () => ({- connectionEpoch: 1,+ connectionEpoch: state.connectionEpoch,+ status: state.status,invoke: state.rpc,openLink: state.open,}),@@ -158,6 +166,9 @@ beforeEach(() => {vi.useFakeTimers();state.sequence = 0;state.sessionBound = true;+ state.status = "online";+ state.connectionEpoch = 1;+ state.mounted = false;state.app = "active";state.commands = [];state.holdReceive = false;@@ -229,6 +240,48 @@ it("keeps legacy idle expiry when the host has not advertised sessionBound", asyexpect(await read()).toBeNull();});+it.each(["idle", "offer", "receive"])("disposes on relay loss during %s and reconnects only on demand", async (phase) => {+ let answer!: (value: unknown) => void;+ const normal = state.rpc.getMockImplementation()!;+ if (phase === "offer") state.rpc.mockImplementation((...args) =>+ args[2][0].action === "offer" ? new Promise(resolve => { answer = resolve; }) : normal(...args));+ state.holdReceive = phase === "receive";+ const operation = phase === "receive" ? state.download("device", "url") : connect();+ // Observe rejection immediately, including the intentionally failing old implementation.+ const result = operation.then(() => "completed", (error: Error) => error.message);+ await vi.advanceTimersByTimeAsync(0);+ const oldProps = state.props;+ const queued = phase === "idle" ? undefined : state.download("device", "queued-url");+ const queuedResult = queued?.then(() => "completed", (error: Error) => error.message);+ act(() => {+ state.status = "reconnecting";+ root.render(createElement(PeerFileTransport));+ });+ expect(state.mounted).toBe(false);+ expect(state.download).toBeUndefined();+ expect(state.read).toBeUndefined();+ if (phase === "offer") answer({ connection: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", sdp: "v=0" });+ expect(await result).toBe(phase === "idle" ? "completed" : "FILE_PEER_CANCELLED");+ if (queuedResult) expect(await queuedResult).toBe("FILE_PEER_CANCELLED");+ const count = offers().length;+ act(() => oldProps.onMessage({ nativeEvent: { data: JSON.stringify({ type: "ready" }) } }));+ await vi.advanceTimersByTimeAsync(30 * 60_000);+ expect(state.download).toBeUndefined();+ expect(offers()).toHaveLength(count);+ act(() => {+ state.status = "online";+ state.connectionEpoch++;+ root.render(createElement(PeerFileTransport));+ });+ expect(state.download).toBeUndefined();+ act(() => message({ type: "ready" }));+ expect(await read()).toBeNull();+ expect(offers()).toHaveLength(count);+ state.rpc.mockImplementation(normal);+ await connect();+ expect(offers()).toHaveLength(count + 1);+});+it("releases a late host answer after backgrounding during setup", async () => {const normal = state.rpc.getMockImplementation()!;let answer!: (value: unknown) => void;@@ -268,6 +321,7 @@ it("rebuilds only on demand after failure and ignores delayed closure of the oldit.each([["background", false], ["reset", false], ["abort", false],["background", true], ["reset", true], ["abort", true],+ ["offline", false], ["offline", true],] as const)("rejects and releases a file cancelled during cache store: %s, store fails=%s", async (cause, fails) => {let resume!: () => void;state.cache.store.mockImplementation(() => new Promise<void>((resolve, reject) => {@@ -282,6 +336,9 @@ it.each([if (cause === "background") {state.app = "background";state.change("background");+ } else if (cause === "offline") {+ state.status = "reconnecting";+ root.render(createElement(PeerFileTransport));} else if (cause === "reset") state.reset("device");else controller.abort();});diff --git a/apps/mobile/src/device-link/peerFileTransport.tsx b/apps/mobile/src/device-link/peerFileTransport.tsxindex 5d8dfb5cee..c2ab474a87 100644--- a/apps/mobile/src/device-link/peerFileTransport.tsx+++ b/apps/mobile/src/device-link/peerFileTransport.tsx@@ -116,7 +116,9 @@ export function PeerFileTransport() {const cacheOwner = JSON.stringify([getActiveMobileSessionRealm(), auth.user?.id]);const fileCache = useMemo(() => createPeerFileCache(cacheOwner).catch(() => null), [cacheOwner]);const account = `${auth.user?.id ?? ""}:${getActiveMobileSessionRealm()}:${auth.isAuthenticated}:${auth.accountGeneration}`;- const owner = `${account}:${link.connectionEpoch}`;+ // Epoch advances on reconnect; status also invalidates work at disconnect.+ const owner = `${account}:${link.connectionEpoch}:${link.status}`;+ const enabled = foreground && auth.isAuthenticated && link.status === "online";const viewKey = `${owner}:${crashes}`;const liveView = useRef(viewKey);liveView.current = viewKey;@@ -186,7 +188,7 @@ export function PeerFileTransport() {[account],);useEffect(() => {- if (!foreground || ready !== viewKey || !auth.isAuthenticated) return;+ if (!enabled || ready !== viewKey) return;if (!swept) {swept = true;const dir = new Directory(Paths.cache, "remote-media-share", "file-peer");@@ -785,7 +787,7 @@ export function PeerFileTransport() {"if (typeof runtime !== 'undefined') runtime.dispose();true;",);};- }, [foreground, ready, auth.isAuthenticated, viewKey]);+ }, [enabled, ready, viewKey]);const handleProcessTerminated = () => {if (liveView.current !== viewKey) return;mobileDebugLog("warn", "files", "direct transfer runtime terminated", {@@ -794,7 +796,7 @@ export function PeerFileTransport() {setReady(null);setCrashes((n) => Math.min(2, n + 1));};- if (!foreground || !auth.isAuthenticated) return null;+ if (!enabled) return null;return (<ViewpointerEvents="none"diff --git a/docs/dev-rules/remote-and-mobile-adaptation.md b/docs/dev-rules/remote-and-mobile-adaptation.mdindex 54c6de2326..614c5fed72 100644--- a/docs/dev-rules/remote-and-mobile-adaptation.md+++ b/docs/dev-rules/remote-and-mobile-adaptation.md@@ -66,7 +66,9 @@ Desktop 与 Mobile 的整文件 peer 下载共用 `fileTransferPolicy.ts`。数沿用已有存储预算,不作为文件有效期或“最佳网络速度”的依据。双方协商支持后,文件连接跟随远程会话生命周期,首次传文件时才建立,不用任意空闲时长决定关闭;旧端继续按已有空闲预算兼容。手机退后台释放原文件 WebView 和电脑端-连接,回前台不立即重建。断链取消排队与建连中的请求,防止迟到结果恢复已关闭的会话。+连接,回前台不立即重建。手机 relay 离开 online 时同样立即卸载文件 WebView,+不等重新上线后的 connectionEpoch 才清理;取消在途、排队及建连中的请求,+迟到消息不得恢复旧会话。重新在线且新 WebView 就绪后按需建连,不主动重放文件请求。连续一个命令预算(15 秒)没有写入进展(含等待 EOF)时回退。只要仍有写入进展,不按预计剩余时间、文件大小或速度放弃传输:接收超时约束的是无进度等待,不是整个