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): retain lock policy through mobile recovery and PiP exits
zqchris611c5b8c22c9
diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsxindex 0fb32fe143..b31d4fb112 100644--- a/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx+++ b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx@@ -1025,9 +1025,8 @@ export function RemoteDesktopSession({setBusy(false);}const lockScreen = Boolean(- previous &&- ((exiting && exitLock.current) ||- (forceLock && capsRef.current?.value.lockOnExit === true)),+ (exiting && exitLock.current) ||+ (forceLock && capsRef.current?.value.lockOnExit === true),);return viewerSession.current!.stop(lockScreen, preserveLease)@@ -1312,7 +1311,9 @@ export function RemoteDesktopSession({capsRef.current = { deviceId, value: result };setHostCaps({ deviceId, value: result });// A window view never unlocks the computer: it shows a window on an unlocked desktop.- if (!handoff && supportsAutoUnlock(result.platform)) {+ // Automatic recovery must never unlock before the host can reject resume.+ // A deliberate new connection may still use the saved password.+ if (!resuming && !handoff && supportsAutoUnlock(result.platform)) {// Linux capture may be unavailable until its locker releases the session.if (result.platform === "linux") {return securityRef.current.maybeUnlock(async () => {@@ -1498,6 +1499,17 @@ export function RemoteDesktopSession({},[stop],);+ const endBackground = (exiting = false) => {+ if (idleTimeoutPolicy.current > 0 && capsRef.current?.value.idleLock) {+ recovery.current.enabled = false;+ void stopRef.current(false, exiting, true);+ setError("backgroundDisconnected");+ } else pause(exiting);+ };+ const pausePresentation = (exiting = false) => {+ if (AppState.currentState === "background") endBackground(exiting);+ else pause(exiting);+ };const leave = async (returnToSource = navigation.current.onBack) => {if (leaving.current) return;leaving.current = true;@@ -1618,11 +1630,7 @@ export function RemoteDesktopSession({!pipPrepared.current) {securityRef.current.resetConnectionAttempt();- if (idleTimeoutPolicy.current > 0 && capsRef.current?.value.idleLock) {- recovery.current.enabled = false;- void stopRef.current(false, false, true);- setError("backgroundDisconnected");- } else pause();+ endBackground();} else if (state === "active" && active.current) {send({ type: "resume" });restoreInlinePresentationRef.current();@@ -2171,7 +2179,7 @@ export function RemoteDesktopSession({) {// A window closed before its host handoff completed. Retire the lease// so a late ACK cannot leave the host in background-viewing mode.- pause(!focusedRef.current);+ pausePresentation(!focusedRef.current);if (!focusedRef.current) navigation.current.onEnded?.();break;}@@ -2197,7 +2205,8 @@ export function RemoteDesktopSession({!restoringPresentation.current) {recovery.current.enabled = false;- void stop(false, true);+ if (AppState.currentState === "background") endBackground(true);+ else void stop(false, true);navigation.current.onEnded?.();} else if (!presentation.current) {restoreInlinePresentationRef.current();@@ -2207,7 +2216,7 @@ export function RemoteDesktopSession({!NativeRemoteDesktopView &&AppState.currentState === "background")- pause();+ endBackground();}break;case "presentationRestore":@@ -2278,11 +2287,10 @@ export function RemoteDesktopSession({setSettingNotice(t("remoteDesktop.pipUnavailable"));setControlPage("controls");setOperations(true);- if (AppState.currentState === "background") pause();- if (!focusedRef.current) {- void stop(false, true);- navigation.current.onEnded?.();- }+ if (AppState.currentState === "background")+ endBackground(!focusedRef.current);+ else if (!focusedRef.current) void stop(false, true);+ if (!focusedRef.current) navigation.current.onEnded?.();break;case "videoFrameReady":if (mediaAttempt.current === message.attemptId)@@ -2624,7 +2632,7 @@ export function RemoteDesktopSession({) {leaving.current = true;setIsLeaving(true);- pause(true);+ pausePresentation(true);navigation.current.onEnded?.();}return;@@ -2669,7 +2677,7 @@ export function RemoteDesktopSession({setSettingNotice(t("remoteDesktop.pipUnavailable"));setControlPage("controls");setOperations(true);- pause(!focusedRef.current);+ pausePresentation(!focusedRef.current);if (!focusedRef.current) navigation.current.onEnded?.();}, BACKGROUND_TRANSITION_TIMEOUT_MS);try {@@ -2744,7 +2752,7 @@ export function RemoteDesktopSession({if (!NativeRemoteDesktopView && !videoSettingsRef.current.audio)void remotePresentation?.playback(false).catch(() => {});setSettingNotice(t("remoteDesktop.pipUnavailable"));- pause(!focusedRef.current);+ pausePresentation(!focusedRef.current);if (!focusedRef.current) navigation.current.onEnded?.();} finally {finishTransition?.();diff --git a/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsxindex 32388cb506..eea424c90d 100644--- a/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx+++ b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx@@ -1005,6 +1005,49 @@ describe("remote desktop controls", () => {mounted = false;expect(fixture.playback).toHaveBeenLastCalledWith(false);});+ // Unit: a reserved PiP transition skips the initial background handler; all+ // failed exits must still lock and disable recovery when protection is on.+ it.each(["failure", "timeout", "reject", "close"])(+ "locks after protected background PiP preparation ends with %s", async (outcome) => {+ fixture.nativeMedia = true;+ fixture.idleSupported = true;+ act(() => root.render(<RemoteDesktopScreen />));+ await connect();+ await nativePresentation("pipCapability", { supported: true });+ act(() => button("operations").click());+ await act(async () => button("smallWindow").click());+ let grant!: (value: unknown) => void;+ let reject!: (cause: Error) => void;+ const original = fixture.invoke.getMockImplementation()!;+ fixture.invoke.mockImplementation((...args) =>+ args[2][0].op === "presentation" && args[2][0].enabled+ ? new Promise((resolve, fail) => { grant = resolve; reject = fail; })+ : original(...args),+ );+ await nativePresentation("presentationStarting");+ await nativePresentation("presentation", { active: true });+ await act(async () => {+ AppState.currentState = "background";+ fixture.appState!("background");+ });+ expect(requests().filter((r) => r.op === "stop")).toHaveLength(0);+ if (outcome === "failure") await nativePresentation("presentationFailed");+ if (outcome === "timeout") await act(async () => vi.advanceTimersByTimeAsync(4000));+ if (outcome === "reject") await act(async () => reject(new Error("denied")));+ if (outcome === "close") await nativePresentation("presentation", { active: false });+ expect(requests().filter((r) => r.op === "stop")).toEqual([+ { op: "stop", lease: "lease", lockScreen: true },+ ]);+ await act(async () => grant({}));+ await act(async () => {+ AppState.currentState = "active";+ fixture.appState!("active");+ await vi.advanceTimersByTimeAsync(30_000);+ });+ expect(requests().filter((r) => r.op === "start")).toHaveLength(1);+ expect(sent().filter((m) => m.type === "pipPolicy" && m.authorized)).toHaveLength(0);+ },+ );it("prepares native video playback even when the host has no audio", async () => {fixture.nativeMedia = true;fixture.systemAudio = false;@@ -3520,6 +3563,53 @@ describe("remote desktop controls", () => {await act(async () => vi.advanceTimersByTimeAsync(3000));expect(requests().filter((r) => r.op === "start").at(-1)).toMatchObject({ resume: true, idleTimeoutMinutes: 5 });});+ // Unit: backgrounding before start returns must retain the same lock intent+ // as a connected viewer; ordinary late-lease cleanup would disable host expiry.+ it("locks a late start reply after protected background exit without reopening", async () => {+ fixture.idleSupported = true;+ let finish!: (value: unknown) => void;+ const original = fixture.invoke.getMockImplementation()!;+ fixture.invoke.mockImplementation((...args) =>+ args[2][0].op === "start"+ ? new Promise((resolve) => { finish = resolve; })+ : original(...args),+ );+ await act(async () => fixture.message!({ nativeEvent: { data: '{"type":"ready"}' } }));+ expect(requests().filter((r) => r.op === "start")).toHaveLength(1);+ await act(async () => {+ AppState.currentState = "background";+ fixture.appState!("background");+ });+ await act(async () => finish({ lease: "late", display, controlling: true }));+ expect(requests().filter((r) => r.op === "stop")).toEqual([+ { op: "stop", lease: "late", lockScreen: true },+ ]);+ await act(async () => {+ AppState.currentState = "active";+ fixture.appState!("active");+ await vi.advanceTimersByTimeAsync(30_000);+ });+ expect(requests().filter((r) => r.op === "start")).toHaveLength(1);+ });+ // Unit: saved-password preparation previously preceded the host's resume+ // refusal and could unlock a host that had already ended the protected lease.+ it.each(["linux", "darwin"])("does not auto-unlock %s while recovering a protected connection", async (platform) => {+ fixture.hostPlatform = platform;+ fixture.idleSupported = true;+ await connect();+ expect(fixture.maybeUnlock).toHaveBeenCalledOnce();+ const original = fixture.invoke.getMockImplementation()!;+ fixture.invoke.mockImplementation((...args) => {+ if (args[2][0].op === "heartbeat") return Promise.reject(new Error("DESKTOP_LEASE_EXPIRED"));+ if (args[2][0].op === "start" && args[2][0].resume)+ return Promise.reject(new Error("DESKTOP_STOPPED"));+ return original(...args);+ });+ await act(async () => vi.advanceTimersByTimeAsync(6000));+ expect(requests().filter((r) => r.op === "start").at(-1)).toMatchObject({ resume: true });+ expect(fixture.maybeUnlock).toHaveBeenCalledOnce();+ expect(host.textContent).toContain("remoteDesktop.hostDisconnected");+ });it("reads an explicit never override before starting a protected-capable host", async () => {act(() => root.unmount());storage.items.set("cindy.mobile.remote-desktop.idle-timeout.v1.computer", "0");diff --git a/docs/remote-desktop.md b/docs/remote-desktop.mdindex c6744e38fd..7384a5a05a 100644--- a/docs/remote-desktop.md+++ b/docs/remote-desktop.md@@ -20,8 +20,12 @@ Desktop controller lock/suspend retires its viewer immediately and requests a holock. With idle protection enabled, Mobile backgrounding without PiP also ends theconnection and requests a lock; temporary inactive states (such as biometric prompts)do not. PiP keeps the same host idle deadline. Neither path automatically reopens the-remote desktop when the controller returns. If the exit request cannot arrive, the-host's existing 12-second heartbeat expiry locks the protected lease. A transient+remote desktop when the controller returns. The lock request is retained for any+in-flight start reply. Background PiP failure or preparation timeout follows the+same protected exit. Automatic Mobile recovery+does not use a saved password; deliberate reconnects may still auto-unlock.+If the exit request cannot arrive, the host's existing 12-second heartbeat expiry+locks the protected lease. A transientmedia reconnect preserves the live host lease and its idle deadline until resume;failed recovery reaches heartbeat expiry instead of renewing the idle budget.Only this desktop lease ends: other Device Link tasks and channels remain intact.diff --git a/packages/device-link/src/__tests__/remoteDesktopViewerSession.test.ts b/packages/device-link/src/__tests__/remoteDesktopViewerSession.test.tsindex dabd12ae7f..4defc60335 100644--- a/packages/device-link/src/__tests__/remoteDesktopViewerSession.test.ts+++ b/packages/device-link/src/__tests__/remoteDesktopViewerSession.test.ts@@ -72,7 +72,7 @@ it("an uncertain release blocks takeover until a heartbeat reconciles and releasenabled: false,});});-it("stop cancels a pending start and cleans up the returned lease without reopening", async () => {+it.each([false, true])("stop preserves lock=%s when cleaning up a cancelled pending start", async (lockScreen) => {const f = fixture();let finish!: (value: unknown) => void;const started = deferred<void>();@@ -85,13 +85,17 @@ it("stop cancels a pending start and cleans up the returned lease without reopen);const connection = f.session.connect({ isCurrent: () => true });await started.promise;- const stopping = f.session.stop();+ const stopping = f.session.stop(lockScreen);+ // A second ordinary cleanup cannot undo the earlier lock requirement.+ const secondStop = f.session.stop();finish({ lease: "late" });await expect(connection).rejects.toThrow("DESKTOP_VIDEO_STOPPED");await stopping;+ await secondStop;expect(f.request.mock.calls.at(-1)?.[0]).toEqual({op: "stop",lease: "late",+ ...(lockScreen ? { lockScreen: true } : {}),});});diff --git a/packages/device-link/src/remoteDesktopViewerSession.ts b/packages/device-link/src/remoteDesktopViewerSession.tsindex 92e8e2dc7d..0015b0adbf 100644--- a/packages/device-link/src/remoteDesktopViewerSession.ts+++ b/packages/device-link/src/remoteDesktopViewerSession.ts@@ -41,6 +41,7 @@ export class RemoteDesktopViewerSession {private controlGeneration = 0;private releaseUnconfirmed = false;private lifecycle: Promise<void> | null = null;+ private starting: { lockScreen: boolean } | null = null;constructor(private readonly request: DesktopViewerRequest) {}get lease(): RemoteDesktopLease | null {@@ -99,24 +100,35 @@ export class RemoteDesktopViewerSession {caps.displays.find((d) => d.id === options.displayId) ?? caps.displays[0];if (!display) throw new Error("DESKTOP_DISPLAY_MISSING");options.onStart?.();- const lease = await this.request<RemoteDesktopLease>(- {- op: "start",- displayId: display.id,- ...(options.takeover && caps.connectionTakeover- ? { takeover: true }- : options.resume- ? { resume: true }+ const starting = { lockScreen: false };+ this.starting = starting;+ let lease: RemoteDesktopLease;+ try {+ lease = await this.request<RemoteDesktopLease>(+ {+ op: "start",+ displayId: display.id,+ ...(options.takeover && caps.connectionTakeover+ ? { takeover: true }+ : options.resume+ ? { resume: true }+ : {}),+ ...(options.control && caps.autoControl && caps.canControl+ ? { control: true }: {}),- ...(options.control && caps.autoControl && caps.canControl- ? { control: true }- : {}),- ...(options.handoff !== undefined ? { handoff: options.handoff } : {}),- },- check,- );+ ...(options.handoff !== undefined ? { handoff: options.handoff } : {}),+ },+ check,+ );+ } finally {+ if (this.starting === starting) this.starting = null;+ }if (generation !== this.generation || !options.isCurrent()) {- await this.request({ op: "stop", lease: lease.lease }).catch(() => {});+ await this.request({+ op: "stop",+ lease: lease.lease,+ ...(starting.lockScreen && !options.handoff ? { lockScreen: true } : {}),+ }).catch(() => {});throw new Error("DESKTOP_VIDEO_STOPPED");}// A window view that came back as a whole display is not what was asked for.@@ -284,6 +296,7 @@ export class RemoteDesktopViewerSession {* host's heartbeat expiry locks it. Explicit exits always send stop. */stop(lockScreen = false, preserveLease = false): Promise<unknown> {this.generation++;+ if (this.starting && lockScreen) this.starting.lockScreen = true;const lease = this.active;this.active = null;this.controlPending = null;