Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(remote-desktop): 为两端连接增加 60 秒总超时 (#4619)
Dashc7544321d500
diff --git a/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerLifecycle.test.ts b/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerLifecycle.test.tsindex 79f002f4d2..a777ee6f7d 100644--- a/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerLifecycle.test.ts+++ b/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerLifecycle.test.ts@@ -34,7 +34,12 @@ afterEach(() => {});async function fixture(- options: { legacyTimeout?: boolean; delayStart?: boolean; busy?: boolean } = {},+ options: {+ legacyTimeout?: boolean;+ delayStart?: boolean;+ busy?: boolean;+ alwaysTimeout?: boolean;+ } = {},) {const start = deferred();const stop = deferred();@@ -50,6 +55,7 @@ async function fixture(check();requests.push(request);if (request.op === 'capabilities') {+ if (options.alwaysTimeout) throw new Error('INVOKE_TIMEOUT');if (options.legacyTimeout && ++capabilityAttempts === 1) throw new Error('INVOKE_TIMEOUT');return {version: 1,@@ -132,6 +138,114 @@ it('retries an initial capabilities timeout on a legacy host without inventing a]);});+it('stops repeated connection failures at the total deadline and allows manual retry', async () => {+ const options = { alwaysTimeout: true };+ const current = await fixture(options);+ await vi.advanceTimersByTimeAsync(60_000);+ expect(snapshot).toMatchObject({ error: 'connectionTimeout', ready: false });+ const attempts = current.requests.length;+ await vi.advanceTimersByTimeAsync(60_000);+ expect(current.requests).toHaveLength(attempts);+ options.alwaysTimeout = false;+ controller.retry();+ await vi.advanceTimersByTimeAsync(0);+ runtime.post?.({ type: 'framePresented', epoch: 'lease-one' });+ await vi.advanceTimersByTimeAsync(60_000);+ expect(snapshot).toMatchObject({ error: null, ready: true });+});++it('times out a lease that never presents a frame and releases only that lease', async () => {+ const current = await fixture();+ await vi.advanceTimersByTimeAsync(60_000);+ expect(snapshot).toMatchObject({ error: 'connectionTimeout', ready: false });+ expect(current.requests.filter((r) => r.op === 'stop')).toEqual([+ { op: 'stop', lease: 'lease-one' },+ ]);+ runtime.post?.({ type: 'streaming', epoch: 'lease-one' });+ expect(snapshot.error).toBe('connectionTimeout');+});++it('retires a start reply arriving after the connection deadline', async () => {+ const current = await fixture({ delayStart: true });+ await vi.advanceTimersByTimeAsync(60_000);+ expect(snapshot.error).toBe('connectionTimeout');+ current.start.resolve();+ current.stop.resolve();+ await vi.advanceTimersByTimeAsync(0);+ expect(current.hostLease()).toBeNull();+ expect(snapshot).toMatchObject({ error: 'connectionTimeout', ready: false });+});++it('releases the lease and cancels the deadline when the viewer is disposed', async () => {+ const current = await fixture();+ controller.dispose();+ await vi.advanceTimersByTimeAsync(150_000);+ expect(current.hostLease()).toBeNull();+ expect(current.requests.filter((r) => r.op === 'stop')).toEqual([+ { op: 'stop', lease: 'lease-one' },+ ]);+ expect(vi.getTimerCount()).toBe(0);+});++it('keeps a healthy viewer on the same host connected when another viewer times out', async () => {+ const leases = new Set<string>();+ const snapshots = new Map<string, ViewerSnapshot>();+ const createViewer = (peer: string) => {+ const api = {+ state: async () => ({+ target: { deviceId: 'host', name: 'Computer' },+ active: true,+ generation: 1,+ }),+ onActive: () => () => {},+ onLocale: () => () => {},+ onCloseRequested: () => () => {},+ ice: async () => [],+ clipboard: async () => {},+ close: async () => {},+ fullscreen: async () => {},+ rendererReady: async () => {},+ presentationReady: async () => {},+ inputFocus: async () => {},+ request: async (_generation: number, request: RemoteDesktopRequest) => {+ if (request.op === 'capabilities')+ return {+ version: 1,+ enabled: true,+ canControl: false,+ automaticReconnect: true,+ displays: [{ id: 'one', width: 1280, height: 720 }],+ };+ if (request.op === 'start') {+ leases.add(peer);+ return {+ lease: peer,+ controlling: false,+ display: { id: 'one', width: 1280, height: 720 },+ };+ }+ if (request.op === 'stop') leases.delete(request.lease);+ return { controlling: false, jpeg: null };+ },+ } satisfies RemoteDesktopViewerApi;+ return new DesktopViewerController(api, {} as HTMLElement, (value) =>+ snapshots.set(peer, value),+ );+ };+ const stalled = createViewer('stalled');+ try {+ controller = createViewer('healthy');+ await vi.advanceTimersByTimeAsync(0);+ runtime.post?.({ type: 'streaming', epoch: 'healthy' });+ await vi.advanceTimersByTimeAsync(150_000);+ expect(snapshots.get('stalled')?.error).toBe('connectionTimeout');+ expect(snapshots.get('healthy')).toMatchObject({ ready: true, error: null });+ expect([...leases]).toEqual(['healthy']);+ } finally {+ stalled.dispose();+ }+});+it.each([['two'], ['two', 'three']])('connects only the final display after a cancelled start and its stop settle: %j',async (...displays) => {diff --git a/apps/desktop/src/renderer/features/remote-desktop/viewerController.ts b/apps/desktop/src/renderer/features/remote-desktop/viewerController.tsindex e50b8ed419..7b30e5d832 100644--- a/apps/desktop/src/renderer/features/remote-desktop/viewerController.ts+++ b/apps/desktop/src/renderer/features/remote-desktop/viewerController.ts@@ -4,6 +4,7 @@ import {REMOTE_DESKTOP_ICE_SERVERS,REMOTE_DESKTOP_MAX_FRAME_BYTES,RemoteDesktopViewerSession,+ REMOTE_DESKTOP_CONNECTION_TIMEOUT_MS,viewerDisplaySize,RemoteDesktopViewerMedia,remoteDesktopFailureKey,@@ -60,6 +61,7 @@ export class DesktopViewerController {private wantsControl = true;private retryAt = 0;private retryDelay = 1000;+ private connectionTimer: ReturnType<typeof setTimeout> | null = null;private frameBusy: string | null = null;private heartbeatBusy: string | null = null;private streaming = false;@@ -111,6 +113,20 @@ export class DesktopViewerController {}private publish(patch: Partial<ViewerSnapshot>): void {this.state = { ...this.state, ...patch };+ const waiting =+ this.scope.active &&+ !this.disposed &&+ !this.state.error &&+ (!this.state.ready || this.state.status === 'reconnecting');+ if (!waiting) {+ if (this.connectionTimer !== null) clearTimeout(this.connectionTimer);+ this.connectionTimer = null;+ } else if (this.connectionTimer === null) {+ // Transient failures and media fallback must not renew the total budget.+ this.connectionTimer = setTimeout(() => {+ this.fail(new Error('DESKTOP_CONNECTION_TIMEOUT'));+ }, REMOTE_DESKTOP_CONNECTION_TIMEOUT_MS);+ }if (!this.disposed) this.changed(this.state);}private request = async <T>(@@ -134,6 +150,8 @@ export class DesktopViewerController {if (this.disposed || scope.generation < this.scope.generation) return;if (scope.generation === this.scope.generation && scope.active === this.scope.active) return;this.cancel();+ if (this.connectionTimer !== null) clearTimeout(this.connectionTimer);+ this.connectionTimer = null;this.scope = scope;this.resuming = scope.resume === true;this.retryDelay = 1000;@@ -565,6 +583,8 @@ export class DesktopViewerController {dispose(): void {this.cancel();this.disposed = true;+ if (this.connectionTimer !== null) clearTimeout(this.connectionTimer);+ this.connectionTimer = null;for (const t of this.timers) clearInterval(t);for (const off of this.unsubscribers) off();this.runtime.dispose();diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 1cf0663fc4..ab40c12f0b 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -65,6 +65,7 @@"showDesktop": "Desktop","allWindows": "All windows","reconnecting": "Reconnecting…",+ "connectionTimeout": "Connection timed out. Check your network and that the computer is online, then reconnect.","connectionBusy": "Another device is connected to this remote desktop. Exit remote desktop on that device, then try connecting again.","takeoverConnection": "Take over connection","connectionBusyTakeover": "Another device is connected to this desktop. Taking over will disconnect that device.",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 98020266d0..600777d1f4 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -65,6 +65,7 @@"showDesktop": "デスクトップ","allWindows": "すべてのウィンドウ","reconnecting": "再接続中…",+ "connectionTimeout": "接続がタイムアウトしました。ネットワークとコンピューターがオンラインであることを確認してから、再接続してください。","connectionBusy": "別のデバイスがこのリモートデスクトップに接続しています。そのデバイスでリモートデスクトップを終了してから、もう一度接続してください。","takeoverConnection": "接続を引き継ぐ","connectionBusyTakeover": "別のデバイスが接続中です。接続を引き継ぐと、そのデバイスは切断されます。",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 2b348c9b0b..9ab45b1247 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -65,6 +65,7 @@"showDesktop": "데스크톱","allWindows": "모든 창","reconnecting": "다시 연결 중…",+ "connectionTimeout": "연결 시간이 초과되었습니다. 네트워크와 컴퓨터의 온라인 상태를 확인한 후 다시 연결하세요.","connectionBusy": "다른 기기가 이 원격 데스크톱에 연결되어 있습니다. 해당 기기에서 원격 데스크톱을 종료한 후 다시 연결하세요.","takeoverConnection": "연결 넘겨받기","connectionBusyTakeover": "다른 기기가 연결되어 있습니다. 연결을 넘겨받으면 해당 기기의 연결이 끊어집니다.",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex acb9ca7cd5..ddf7593b4c 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -65,6 +65,7 @@"showDesktop": "桌面","allWindows": "所有窗口","reconnecting": "正在重新连接…",+ "connectionTimeout": "连接超时。请检查网络和电脑是否在线,然后重新连接。","connectionBusy": "已有其他设备连接此远程桌面。请先在那台设备上退出远程桌面,再尝试连接。","takeoverConnection": "接管连接","connectionBusyTakeover": "已有其他设备连接此远程桌面。接管连接后,上一台设备会断开。",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 7c543ecfe1..dbeb21b75e 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -65,6 +65,7 @@"showDesktop": "桌面","allWindows": "所有視窗","reconnecting": "正在重新連線…",+ "connectionTimeout": "連線逾時。請檢查網路及電腦是否在線,然後重新連線。","connectionBusy": "已有其他裝置連線至此遠端桌面。請先在該裝置上退出遠端桌面,再嘗試連線。","takeoverConnection": "接管連線","connectionBusyTakeover": "已有其他裝置連線至此遠端桌面。接管連線後,上一台裝置會中斷。",diff --git a/apps/mobile/src/i18n/locales/en/remoteDesktop.json b/apps/mobile/src/i18n/locales/en/remoteDesktop.jsonindex 0b64c4b3e1..b4f6d7cbc0 100644--- a/apps/mobile/src/i18n/locales/en/remoteDesktop.json+++ b/apps/mobile/src/i18n/locales/en/remoteDesktop.json@@ -56,6 +56,7 @@"connect": "Connect","connecting": "Connecting…","reconnecting": "Reconnecting…",+ "connectionTimeout": "Connection timed out. Check your network and that the computer is online, then reconnect.","lockingOnExit": "Locking computer…","disconnected": "Disconnected","compatibility": "Compatibility mode · lower frame rate",diff --git a/apps/mobile/src/i18n/locales/ja/remoteDesktop.json b/apps/mobile/src/i18n/locales/ja/remoteDesktop.jsonindex 66d79f12d4..2057af49e3 100644--- a/apps/mobile/src/i18n/locales/ja/remoteDesktop.json+++ b/apps/mobile/src/i18n/locales/ja/remoteDesktop.json@@ -56,6 +56,7 @@"connect": "接続","connecting": "接続中…","reconnecting": "再接続中…",+ "connectionTimeout": "接続がタイムアウトしました。ネットワークとコンピューターがオンラインであることを確認してから、再接続してください。","lockingOnExit": "コンピューターをロック中…","disconnected": "切断済み","compatibility": "互換モード · 低フレームレート",diff --git a/apps/mobile/src/i18n/locales/ko/remoteDesktop.json b/apps/mobile/src/i18n/locales/ko/remoteDesktop.jsonindex cbb04d3e93..80a7ee7767 100644--- a/apps/mobile/src/i18n/locales/ko/remoteDesktop.json+++ b/apps/mobile/src/i18n/locales/ko/remoteDesktop.json@@ -56,6 +56,7 @@"connect": "연결","connecting": "연결 중…","reconnecting": "다시 연결 중…",+ "connectionTimeout": "연결 시간이 초과되었습니다. 네트워크와 컴퓨터의 온라인 상태를 확인한 후 다시 연결하세요.","lockingOnExit": "컴퓨터를 잠그는 중…","disconnected": "연결 끊김","compatibility": "호환 모드 · 낮은 프레임 속도",diff --git a/apps/mobile/src/i18n/locales/zh-CN/remoteDesktop.json b/apps/mobile/src/i18n/locales/zh-CN/remoteDesktop.jsonindex 4f571c56cc..c67515fc25 100644--- a/apps/mobile/src/i18n/locales/zh-CN/remoteDesktop.json+++ b/apps/mobile/src/i18n/locales/zh-CN/remoteDesktop.json@@ -56,6 +56,7 @@"connect": "连接","connecting": "连接中…","reconnecting": "正在重新连接…",+ "connectionTimeout": "连接超时。请检查网络和电脑是否在线,然后重新连接。","lockingOnExit": "正在锁定电脑…","disconnected": "已断开","compatibility": "兼容模式 · 帧率较低",diff --git a/apps/mobile/src/i18n/locales/zh-TW/remoteDesktop.json b/apps/mobile/src/i18n/locales/zh-TW/remoteDesktop.jsonindex aaac3ee36e..be304e8698 100644--- a/apps/mobile/src/i18n/locales/zh-TW/remoteDesktop.json+++ b/apps/mobile/src/i18n/locales/zh-TW/remoteDesktop.json@@ -56,6 +56,7 @@"connect": "連線","connecting": "連線中…","reconnecting": "正在重新連線…",+ "connectionTimeout": "連線逾時。請檢查網路及電腦是否在線,然後重新連線。","lockingOnExit": "正在鎖定電腦…","disconnected": "已中斷","compatibility": "相容模式 · 畫格率較低",diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsxindex 2d356d3f54..be04cf9504 100644--- a/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx+++ b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx@@ -41,6 +41,7 @@ import { useTranslation } from "react-i18next";import SegmentedControl from "@expo/ui/community/segmented-control";import {RemoteDesktopViewerSession,+ REMOTE_DESKTOP_CONNECTION_TIMEOUT_MS,viewerDisplaySize,RemoteDesktopViewerMedia,remoteDesktopFailureKey,@@ -263,6 +264,7 @@ export default function RemoteDesktopScreen() {exitLock.current =lockOnExitLoaded && lockOnExit && caps?.lockOnExit === true;const [status, setStatus] = useState("connecting");+ const [appState, setAppState] = useState(AppState.currentState);const [error, setError] = useState<string | null>(null);const takeoverPromptOpen = useRef(false);const takeoverAction = useRef<() => void>(() => {});@@ -817,6 +819,20 @@ export default function RemoteDesktopScreen() {);const connectRef = useRef(connect);connectRef.current = connect;+ useEffect(() => {+ if (!focused || appState !== "active" || !showConnectionStatus) return;+ // One deadline spans link setup, automatic retries and first presentation.+ // Background/navigation pauses it; a manual retry starts a fresh budget.+ const timer = setTimeout(() => {+ if (+ alive.current &&+ focusedRef.current &&+ AppState.currentState === "active"+ )+ fail(new Error("DESKTOP_CONNECTION_TIMEOUT"));+ }, REMOTE_DESKTOP_CONNECTION_TIMEOUT_MS);+ return () => clearTimeout(timer);+ }, [focused, appState, showConnectionStatus, fail]);useEffect(() => {// Authentication preparation is already running; only the native prompt// waits for a frame from this lease. stop() releases cancelled waiters.@@ -888,6 +904,7 @@ export default function RemoteDesktopScreen() {useEffect(() => {alive.current = true;const subscription = AppState.addEventListener("change", (state) => {+ setAppState(state);// iOS enters inactive during an interrupted Home gesture or a system// overlay. Release held input, but keep this viewer's lease and stream.if (state === "inactive") {diff --git a/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsxindex 28da7889ee..6e518c691c 100644--- a/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx+++ b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx@@ -385,6 +385,68 @@ const connect = async () => {};describe("remote desktop controls", () => {+ it("bounds repeated failures without renewing the deadline on each retry", async () => {+ fixture.openLink.mockRejectedValue(new Error("INVOKE_TIMEOUT"));+ await act(async () => {+ fixture.message!({ nativeEvent: { data: '{"type":"ready"}' } });+ });+ await act(async () => vi.advanceTimersByTimeAsync(60_000));+ expect(host.textContent).toContain("remoteDesktop.connectionTimeout");+ const attempts = fixture.openLink.mock.calls.length;+ await act(async () => vi.advanceTimersByTimeAsync(60_000));+ expect(fixture.openLink).toHaveBeenCalledTimes(attempts);+ fixture.openLink.mockResolvedValue({});+ await act(async () => button("connect").click());+ act(() =>+ fixture.message!({+ nativeEvent: {+ data: '{"type":"framePresented","epoch":"lease"}',+ },+ }),+ );+ await act(async () => vi.advanceTimersByTimeAsync(60_000));+ expect(host.textContent).not.toContain("remoteDesktop.connectionTimeout");+ });++ it("times out while waiting for the first frame and ignores late presentation", async () => {+ await act(async () => {+ fixture.message!({ nativeEvent: { data: '{"type":"ready"}' } });+ });+ await act(async () => vi.advanceTimersByTimeAsync(60_000));+ expect(host.textContent).toContain("remoteDesktop.connectionTimeout");+ expect(requests().filter((r) => r.op === "stop")).toEqual([+ { op: "stop", lease: "lease" },+ ]);+ act(() =>+ fixture.message!({+ nativeEvent: {+ data: '{"type":"framePresented","epoch":"lease"}',+ },+ }),+ );+ expect(host.textContent).toContain("remoteDesktop.connectionTimeout");+ });++ it("cancels the deadline after a frame and gives background resume a fresh budget", async () => {+ await connect();+ await act(async () => vi.advanceTimersByTimeAsync(150_000));+ expect(host.textContent).not.toContain("remoteDesktop.connectionTimeout");+ await act(async () => {+ AppState.currentState = "background";+ fixture.appState!("background");+ });+ await act(async () => vi.advanceTimersByTimeAsync(150_000));+ expect(host.textContent).not.toContain("remoteDesktop.connectionTimeout");+ await act(async () => {+ AppState.currentState = "active";+ fixture.appState!("active");+ });+ await act(async () => vi.advanceTimersByTimeAsync(59_000));+ expect(host.textContent).not.toContain("remoteDesktop.connectionTimeout");+ await act(async () => vi.advanceTimersByTimeAsync(1000));+ expect(host.textContent).toContain("remoteDesktop.connectionTimeout");+ });+it("retries an initial capabilities timeout normally on a legacy host", async () => {const original = fixture.invoke.getMockImplementation()!;let attempts = 0;diff --git a/packages/device-link/src/remoteDesktopViewerSession.ts b/packages/device-link/src/remoteDesktopViewerSession.tsindex c0b32a5110..f53dfd4705 100644--- a/packages/device-link/src/remoteDesktopViewerSession.ts+++ b/packages/device-link/src/remoteDesktopViewerSession.ts@@ -4,6 +4,9 @@ import type {RemoteDesktopRequest,} from "./remoteDesktop.js";+// Whole foreground connection/recovery budget, including retries and first frame.+export const REMOTE_DESKTOP_CONNECTION_TIMEOUT_MS = 60_000;+export type DesktopViewerRequest = <T>(request: RemoteDesktopRequest,beforeSend?: () => void,@@ -247,6 +250,7 @@ export function viewerDisplaySize(/** Only transient connection errors may restart a viewer. Explicit stop wins. */export function remoteDesktopFailureKey(code: string): string | null {+ if (/DESKTOP_CONNECTION_TIMEOUT/.test(code)) return "connectionTimeout";if (/ACCESS_REVOKED/.test(code)) return "accessRevoked";if (/REMOTE_DISABLED/.test(code)) return "remoteDisabled";if (/DESKTOP_BUSY/.test(code)) return "connectionBusy";