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): 立即关闭本地窗口并兜底断线锁屏 (#5548)
Dash923a38762cd2
diff --git a/apps/desktop/src/main/remote-desktop-viewer/__tests__/connection.test.ts b/apps/desktop/src/main/remote-desktop-viewer/__tests__/connection.test.tsindex 54f17b5c1d..ca67afd0c9 100644--- a/apps/desktop/src/main/remote-desktop-viewer/__tests__/connection.test.ts+++ b/apps/desktop/src/main/remote-desktop-viewer/__tests__/connection.test.ts@@ -369,6 +369,9 @@ it.each([true, false])(await connection.request(generation, { op: 'capabilities' });await connection.request(generation, { op: 'start', displayId: 'screen' });const closed = connection.close(generation);+ expect(closed).toBeUndefined();+ expect(connection.active).toBe(false);+ expect(() => connection.check(generation)).toThrow('DESKTOP_STOPPED');expect(dispose).toHaveBeenCalledOnce();expect(request.mock.calls.at(-1)?.[1]).toEqual({op: 'stop',@@ -380,6 +383,106 @@ it.each([true, false])(},);+it('keeps explicit exit locking on a start reply that arrives after close and rebind', async () => {+ let finish!: (value: unknown) => void;+ const request = vi.fn(async (_device, message, check) => {+ check();+ if (message.op === 'capabilities') return { lockOnExit: true };+ if (message.op === 'start')+ return new Promise((resolve) => {+ finish = resolve;+ });+ return {};+ });+ const connection = new RemoteViewerConnection({+ owner: () => 'owner',+ request,+ readClipboard: () => '',+ writeClipboard: () => {},+ preferences: () => ({ ...DEFAULT_VIEWER_PREFERENCES, lockOnExit: true }),+ });+ connection.bind({ deviceId: 'old', name: 'Old' });+ connection.setActive(true);+ const generation = connection.generation;+ await connection.request(generation, { op: 'capabilities' });+ const pending = connection.request(generation, { op: 'start', displayId: 'screen' });+ connection.close(generation);+ connection.bind({ deviceId: 'new', name: 'New' });+ connection.setActive(true);+ finish({ lease: 'late-lease' });+ expect(await pending).toEqual({ ok: false, code: 'DESKTOP_STOPPED' });+ expect(request.mock.calls.at(-1)?.slice(0, 2)).toEqual([+ 'old',+ { op: 'stop', lease: 'late-lease', lockScreen: true },+ ]);+ expect(connection.active).toBe(true);+});++it.each([false, true])(+ 'returns the saved preference before a failed remote sync, enabled=%s',+ async (enabled) => {+ let fail!: (error: Error) => void;+ const sync = new Promise<never>((_resolve, reject) => {+ fail = reject;+ });+ const request = vi.fn(async (_target, message, check) => {+ check();+ if (message.op === 'heartbeat') return sync;+ return message.op === 'start' ? { lease: 'lease' } : {};+ });+ const connection = new RemoteViewerConnection({+ owner: () => 'owner',+ request,+ readClipboard: () => '',+ writeClipboard: () => {},+ preferences: () => ({ ...DEFAULT_VIEWER_PREFERENCES, lockOnExit: !enabled }),+ savePreferences: async (_device, patch) => ({ ...DEFAULT_VIEWER_PREFERENCES, ...patch }),+ });+ connection.bind({ deviceId: 'target', name: 'Target' });+ connection.setActive(true);+ const generation = connection.generation;+ await connection.request(generation, { op: 'start', displayId: 'screen' });+ await expect(+ connection.preferences(generation, { lockOnExit: enabled }),+ ).resolves.toMatchObject({ lockOnExit: enabled });+ expect(request.mock.calls.at(-1)?.[1]).toMatchObject({ op: 'heartbeat', lockOnExit: enabled });+ fail(new Error('INVOKE_TIMEOUT'));+ await connection.request(generation, { op: 'heartbeat', lease: 'lease' });+ await expect(connection.preferences(generation)).resolves.toMatchObject({+ lockOnExit: enabled,+ });+ expect(request.mock.calls.at(-1)?.[1]).toMatchObject({ lockOnExit: enabled });+ },+);++it('sends the lock policy before a lease starts and immediately after changing the preference', async () => {+ const request = vi.fn(async (_target, message, check) => {+ check();+ return message.op === 'start' ? { lease: 'lease', controlling: false } : {};+ });+ const connection = new RemoteViewerConnection({+ owner: () => 'owner',+ request,+ readClipboard: () => '',+ writeClipboard: () => {},+ preferences: () => ({ ...DEFAULT_VIEWER_PREFERENCES, lockOnExit: true }),+ savePreferences: async (_device, patch) => ({ ...DEFAULT_VIEWER_PREFERENCES, ...patch }),+ });+ connection.bind({ deviceId: 'target', name: 'Target' });+ connection.setActive(true);+ const generation = connection.generation;+ await connection.request(generation, { op: 'start', displayId: 'screen' });+ expect(request.mock.calls.at(-1)?.[1]).toMatchObject({ op: 'start', lockOnExit: true });+ await connection.preferences(generation, { lockOnExit: false });+ expect(request.mock.calls.at(-1)?.[1]).toEqual({+ op: 'heartbeat',+ lease: 'lease',+ lockOnExit: false,+ });+ await connection.request(generation, { op: 'heartbeat', lease: 'lease' });+ expect(request.mock.calls.at(-1)?.[1]).toMatchObject({ lockOnExit: false });+});+it.each([false, true])('keeps rich clipboard payloads in Main and cancels writes after control release %s',async (release) => {@@ -473,7 +576,9 @@ describe('remembered viewer resolution', () => {await expect(connection.resolution(generation, 'screen', fit)).resolves.toEqual(fit);expect(saveResolution).toHaveBeenCalledWith('computer-a', 'screen', fit);await expect(connection.resolution(generation, 'screen')).resolves.toEqual(fit);- await expect(connection.resolution(generation, 'other', fit)).rejects.toThrow('INVALID_REQUEST');+ await expect(connection.resolution(generation, 'other', fit)).rejects.toThrow(+ 'INVALID_REQUEST',+ );await connection.resolution(generation, 'screen', null);await expect(connection.resolution(generation, 'screen')).resolves.toBeNull();});@@ -504,13 +609,15 @@ describe('remembered viewer resolution', () => {describe('requests carried by the viewer window’s media data channel', () => {function channelFixture(channelRequests = true) {- const relay = vi.fn(async (_target: string, message: RemoteDesktopRequest, check: () => void) => {- check();- if (message.op === 'capabilities') return { channelRequests, clipboardText: true };- if (message.op === 'start') return { lease: 'lease', controlling: false };- if (message.op === 'control') return { controlling: message.enabled };- return { ok: true };- });+ const relay = vi.fn(+ async (_target: string, message: RemoteDesktopRequest, check: () => void) => {+ check();+ if (message.op === 'capabilities') return { channelRequests, clipboardText: true };+ if (message.op === 'start') return { lease: 'lease', controlling: false };+ if (message.op === 'control') return { controlling: message.enabled };+ return { ok: true };+ },+ );const carried: { generation: number; id: string; request: RemoteDesktopRequest }[] = [];let accept = true;const connection = new RemoteViewerConnection({@@ -633,15 +740,17 @@ describe('requests carried by the viewer window’s media data channel', () => {describe('control granted with the lease (autoControl)', () => {it('records a grant from start or a display change like a control reply', async () => {- const relay = vi.fn(async (_target: string, message: RemoteDesktopRequest, check: () => void) => {- check();- if (message.op === 'capabilities') return { autoControl: true, clipboardText: true };- if (message.op === 'start')- return { lease: 'lease', controlling: message.control === true, display: { id: 's' } };- if (message.op === 'viewerDisplay')- return { lease: 'lease', controlling: message.control === true, display: { id: 'v' } };- return { ok: true };- });+ const relay = vi.fn(+ async (_target: string, message: RemoteDesktopRequest, check: () => void) => {+ check();+ if (message.op === 'capabilities') return { autoControl: true, clipboardText: true };+ if (message.op === 'start')+ return { lease: 'lease', controlling: message.control === true, display: { id: 's' } };+ if (message.op === 'viewerDisplay')+ return { lease: 'lease', controlling: message.control === true, display: { id: 'v' } };+ return { ok: true };+ },+ );const connection = new RemoteViewerConnection({owner: () => 'owner',request: relay,diff --git a/apps/desktop/src/main/remote-desktop-viewer/__tests__/windows.test.ts b/apps/desktop/src/main/remote-desktop-viewer/__tests__/windows.test.tsindex 8c51943f55..25ea9c9bd2 100644--- a/apps/desktop/src/main/remote-desktop-viewer/__tests__/windows.test.ts+++ b/apps/desktop/src/main/remote-desktop-viewer/__tests__/windows.test.ts@@ -108,6 +108,7 @@ vi.mock('../../resource-usage-window/window', () => ({}));import { RemoteDesktopViewerWindows } from '../windows';import { REMOTE_VIEWER } from '../../../shared/remoteDesktopViewer';+import { remoteInvoke } from '../../device-link/index';let manager: RemoteDesktopViewerWindows;afterEach(() => {manager?.reset();@@ -119,6 +120,40 @@ afterEach(() => {const event = (win: any) => ({ sender: win.webContents, senderFrame: win.webContents.mainFrame });const call = (channel: string, win: any, ...args: unknown[]) =>fixture.handlers.get(channel)!(event(win), ...args);+it.each(['resolve', 'reject'])(+ 'closes immediately while stop is pending and ignores its late %s',+ async (outcome) => {+ const sender: any = { id: 100 };+ manager = new RemoteDesktopViewerWindows((value) => value === sender);+ manager.register();+ manager.open(sender, { deviceId: 'a', name: 'A' });+ const win = fixture.windows[0];+ call(REMOTE_VIEWER.READY, win);+ call(REMOTE_VIEWER.PRESENTED, win);+ const { generation } = call(REMOTE_VIEWER.STATE, win);+ await call(REMOTE_VIEWER.REQUEST, win, generation, { op: 'start', displayId: 'screen' });+ let settle!: () => void;+ vi.mocked(remoteInvoke).mockImplementationOnce(+ () =>+ new Promise((resolve, reject) => {+ settle = () =>+ outcome === 'resolve'+ ? resolve({ ok: true, result: {} })+ : reject(new Error('INVOKE_TIMEOUT'));+ }),+ );+ call(REMOTE_VIEWER.CLOSE, win, generation);+ expect(win.isVisible()).toBe(false);+ expect(call(REMOTE_VIEWER.STATE, win).active).toBe(false);+ manager.open(sender, { deviceId: 'a', name: 'A' });+ expect(win.isVisible()).toBe(true);+ settle();+ await Promise.resolve();+ await Promise.resolve();+ expect(win.isVisible()).toBe(true);+ expect(call(REMOTE_VIEWER.STATE, win).active).toBe(true);+ },+);it('routes native close and the close shortcut to confirmation without ending the lease', async () => {const sender: any = { id: 100 };manager = new RemoteDesktopViewerWindows((value) => value === sender);diff --git a/apps/desktop/src/main/remote-desktop-viewer/connection.ts b/apps/desktop/src/main/remote-desktop-viewer/connection.tsindex 33224598c3..91a0c50f56 100644--- a/apps/desktop/src/main/remote-desktop-viewer/connection.ts+++ b/apps/desktop/src/main/remote-desktop-viewer/connection.ts@@ -36,7 +36,7 @@ export class RemoteViewerConnection {generation = 0;private owner = '';private lease: string | null = null;- private starting = false;+ private starting: { lockScreen: boolean } | null = null;private pending = 0;private attempted = false;private mediaAttempt: string | null = null;@@ -50,7 +50,6 @@ export class RemoteViewerConnection {private preferencesValue = { ...DEFAULT_VIEWER_PREFERENCES };private safetyState = new ViewerSafety();private clipboardProgress: number | null = null;- private closing = false;private channelRequests = new Map<string, (outcome: RemoteViewerChannelOutcome) => void>();private channelRequestId = 0;constructor(@@ -86,7 +85,6 @@ export class RemoteViewerConnection {this.target = target;this.attempted = false;this.caps = null;- this.closing = false;this.preferencesValue = this.deps.preferences?.(target.deviceId) ?? {...DEFAULT_VIEWER_PREFERENCES,};@@ -146,8 +144,7 @@ export class RemoteViewerConnection {this.lifecycle = tail;return pending;}- deactivate(): void {- this.closing = false;+ deactivate(lockScreen = false): void {this.safetyState.invalidate();this.clipboardProgress = null;this.deps.credentials?.dispose();@@ -163,15 +160,19 @@ export class RemoteViewerConnection {this.controlPending = false;this.controlGeneration++;this.clipboardPending = null;- this.starting = false;+ this.starting = null;// Their media peer belongs to the retired viewer; the outcome is unknown.for (const settle of [...this.channelRequests.values()])settle({ kind: 'error', code: 'INVOKE_TIMEOUT' });if (lease && target && owner === this.deps.owner())void this.serializeLifecycle(() =>- this.deps.request(target.deviceId, { op: 'stop', lease }, () => {- if (owner !== this.deps.owner()) throw new Error('DESKTOP_STOPPED');- }),+ this.deps.request(+ target.deviceId,+ { op: 'stop', lease, ...(lockScreen ? { lockScreen: true } : {}) },+ () => {+ if (owner !== this.deps.owner()) throw new Error('DESKTOP_STOPPED');+ },+ ),).catch(() => {});}async request(@@ -181,7 +182,6 @@ export class RemoteViewerConnection {): Promise<RemoteViewerReply> {try {this.check(generation);- if (this.closing) throw new Error('DESKTOP_STOPPED');const request = parseRemoteDesktopRequest(value);const check = () =>request.op === 'offer' || request.op === 'ice'@@ -218,9 +218,8 @@ export class RemoteViewerConnection {const controlGeneration = this.controlGeneration;const controlPendingAtStart = this.controlPending;if (confirmsControl) this.controlPending = true;- if (isStart) {- this.starting = true;- }+ const starting = isStart ? { lockScreen: false } : null;+ if (isStart) this.starting = starting;this.pending++;try {const execute = async () => {@@ -233,7 +232,9 @@ export class RemoteViewerConnection {const outgoing =request.op === 'offer' && request.settings? { ...request, settings: remoteDesktopVideoSettingsWire(request.settings) }- : request;+ : request.op === 'start' || request.op === 'heartbeat'+ ? { ...request, lockOnExit: this.preferencesValue.lockOnExit }+ : request;const result = await this.send(outgoing, check);if (request.op === 'capabilities') {check();@@ -245,9 +246,17 @@ export class RemoteViewerConnection {if (!this.active || generation !== this.generation || owner !== this.deps.owner()) {if (owner === this.deps.owner())await this.deps- .request(target.deviceId, { op: 'stop', lease: lease.lease }, () => {- if (owner !== this.deps.owner()) throw new Error('DESKTOP_STOPPED');- })+ .request(+ target.deviceId,+ {+ op: 'stop',+ lease: lease.lease,+ ...(starting?.lockScreen ? { lockScreen: true } : {}),+ },+ () => {+ if (owner !== this.deps.owner()) throw new Error('DESKTOP_STOPPED');+ },+ ).catch(() => {});throw new Error('DESKTOP_STOPPED');}@@ -279,7 +288,7 @@ export class RemoteViewerConnection {this.pending--;if (confirmsControl && controlGeneration === this.controlGeneration)this.controlPending = false;- if (generation === this.generation && isStart) this.starting = false;+ if (generation === this.generation && isStart) this.starting = null;}} catch (error) {return viewerFailure(error);@@ -379,6 +388,11 @@ export class RemoteViewerConnection {const reset = value.clipboardSync !== this.preferencesValue.clipboardSync;this.preferencesValue = value;this.safetyState.invalidate(reset);+ if (patch.lockOnExit !== undefined && this.lease) {+ // Saving is local; a slow or failed sync must not leave the switch+ // showing the old value. Regular heartbeats also carry this policy.+ void this.request(generation, { op: 'heartbeat', lease: this.lease });+ }}return { ...this.preferencesValue };}@@ -438,7 +452,8 @@ export class RemoteViewerConnection {!this.caps?.displays.some((display) => display.id === displayId))throw new Error('INVALID_REQUEST');- if (value === undefined) return this.deps.resolution?.(this.target!.deviceId, displayId) ?? null;+ if (value === undefined)+ return this.deps.resolution?.(this.target!.deviceId, displayId) ?? null;const parsed = value === null ? null : parseRememberedViewerResolution(value);if (value !== null && !parsed) throw new Error('INVALID_REQUEST');if (!this.deps.saveResolution) throw new Error('DESKTOP_UNAVAILABLE');@@ -493,7 +508,6 @@ export class RemoteViewerConnection {}async credential(generation: number, action: unknown, enabled: unknown) {this.check(generation);- if (this.closing) throw new Error('DESKTOP_STOPPED');if (!this.deps.credentials) throw new Error('CREDENTIAL_UNAVAILABLE');return this.deps.credentials.run(this.target!.deviceId,@@ -502,37 +516,18 @@ export class RemoteViewerConnection {enabled,() => {this.check(generation);- if (this.closing) throw new Error('DESKTOP_STOPPED');},);}- async close(generation: number): Promise<void> {+ close(generation: number): void {this.check(generation);- if (this.closing) throw new Error('DESKTOP_INPUT_BUSY');- this.closing = true;- this.deps.credentials?.dispose();- const lease = this.lease;- if (!lease) return;const lockScreen = this.preferencesValue.lockOnExit && this.caps?.lockOnExit === true;- this.safetyState.invalidate();- this.controlling = false;- this.controlGeneration++;- try {- await this.serializeLifecycle(async () => {- this.check(generation);- if (this.lease !== lease) return;- await this.deps.request(- this.target!.deviceId,- { op: 'stop', lease, ...(lockScreen ? { lockScreen: true } : {}) },- () => this.check(generation),- );- this.check(generation);- if (this.lease === lease) this.lease = null;- });- } catch (error) {- if (generation === this.generation) this.closing = false;- throw error;- }+ // A start reply may arrive after close. Its own cleanup must retain the+ // explicit exit policy even if this window has already opened a new target.+ if (this.starting) this.starting.lockScreen = lockScreen;+ // Retire local authority now. Cleanup remains serialized with a later+ // start for this peer, but its network outcome never gates window close.+ this.deactivate(lockScreen);}}diff --git a/apps/desktop/src/main/remote-desktop-viewer/windows.ts b/apps/desktop/src/main/remote-desktop-viewer/windows.tsindex f2819b0905..7d89ab12a8 100644--- a/apps/desktop/src/main/remote-desktop-viewer/windows.ts+++ b/apps/desktop/src/main/remote-desktop-viewer/windows.ts@@ -275,15 +275,14 @@ export class RemoteDesktopViewerWindows {ipcMain.handle(REMOTE_VIEWER.PRESENTED, (event) => {this.entry(event).controller.markPresentationReady(event.sender);});- ipcMain.handle(REMOTE_VIEWER.CLOSE, async (event, generation) => {+ ipcMain.handle(REMOTE_VIEWER.CLOSE, (event, generation) => {const entry = this.entry(event);if (generation !== entry.connection.generation) return;try {- await entry.connection.close(generation);+ entry.connection.close(generation);} catch {throwIpcError('PRECONDITION_FAILED', 'DESKTOP_STOP_FAILED');}- if (generation !== entry.connection.generation) return;entry.controller.close(event.sender);});ipcMain.handle(REMOTE_VIEWER.PREFERENCES, async (event, generation, patch) => {diff --git a/apps/desktop/src/main/remote-desktop/__tests__/controller.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/controller.test.tsindex 29d891bebb..3117e33781 100644--- a/apps/desktop/src/main/remote-desktop/__tests__/controller.test.ts+++ b/apps/desktop/src/main/remote-desktop/__tests__/controller.test.ts@@ -296,6 +296,115 @@ describe('remote desktop authority and lifecycle', () => {expect(settled).toHaveBeenCalledOnce();expect(h.deps.restoreResolution).toHaveBeenCalledOnce();});+ it.each([false, true])(+ 'awaits display restoration after a pending shutdown lock, failed=%s',+ async (failed) => {+ const h = harness();+ let finishLock!: () => void;+ h.deps.lockScreen = vi.fn(+ () =>+ new Promise<void>((resolve, reject) => {+ finishLock = () => (failed ? reject(new Error('LOCK_FAILED')) : resolve());+ }),+ );+ h.deps.displayModes = async () => [+ { id: '1', width: 1920, height: 1080, current: true },+ { id: '2', width: 3840, height: 2160, current: false },+ ];+ h.deps.resolution = async (_display, _mode, beforeChange) => beforeChange();+ let finishRestore!: () => void;+ h.deps.restoreResolution = vi.fn(+ () =>+ new Promise<void>((resolve) => {+ finishRestore = resolve;+ }),+ );+ const { lease } = await h.start();+ await h.controller.request('phone', { op: 'heartbeat', lease, lockOnExit: true });+ await h.controller.request('phone', { op: 'control', lease, enabled: true });+ await h.controller.request('phone', {+ op: 'resolution',+ lease,+ modeId: '2',+ temporary: true,+ });+ const settled = vi.fn();+ // The synchronous quit phase may already have started the lock.+ void h.controller.stop().catch(() => {});+ const quitting = h.controller.stopAndRestore().then(settled, settled);+ await vi.waitFor(() => expect(h.deps.lockScreen).toHaveBeenCalledOnce());+ expect(h.deps.restoreResolution).not.toHaveBeenCalled();+ finishLock();+ await vi.waitFor(() => expect(h.deps.restoreResolution).toHaveBeenCalledOnce());+ expect(h.controller.state).toBeNull();+ expect(settled).not.toHaveBeenCalled();+ finishRestore();+ await quitting;+ expect(settled).toHaveBeenCalledWith(+ failed ? expect.objectContaining({ message: 'LOCK_FAILED' }) : undefined,+ );+ expect(h.deps.restoreResolution).toHaveBeenCalledOnce();+ },+ );+ it.each([+ 'temporary-missing',+ 'temporary-failed',+ 'system',+ 'system-failed',+ 'viewer',+ 'restore-viewer',+ 'system-restore-failed',+ ] as const)('does not lock during display cleanup: %s', async (operation) => {+ const h = harness();+ h.deps.lockScreen = vi.fn(async () => {});+ h.deps.displayModes = async () => [{ id: '1', width: 1920, height: 1080, current: true }];+ h.deps.resolution = async (_display, _mode, beforeChange) => {+ beforeChange();+ if (operation !== 'system') throw new Error('MODE_FAILED');+ };+ const handle = {+ resize: vi.fn(async () => ({ id: '1', name: 'Main', width: 1280, height: 720 })),+ restore: vi.fn(async () => {+ throw new Error('MODE_FAILED');+ }),+ dispose: vi.fn(),+ };+ if (operation === 'viewer') handle.resize.mockRejectedValueOnce(new Error('MODE_FAILED'));+ h.deps.createViewerDisplay = vi.fn(async () => handle);+ const { lease } = await h.start();+ await h.controller.request('phone', { op: 'heartbeat', lease, lockOnExit: true });+ await h.controller.request('phone', { op: 'control', lease, enabled: true });+ if (operation === 'restore-viewer' || operation === 'system-restore-failed') {+ await h.controller.request('phone', {+ op: 'viewerDisplay',+ lease,+ width: 1280,+ height: 720,+ control: true,+ });+ }+ const changing = h.controller.request(+ 'phone',+ operation === 'viewer'+ ? { op: 'viewerDisplay', lease, width: 1280, height: 720 }+ : operation === 'restore-viewer'+ ? { op: 'restoreViewerDisplay', lease }+ : {+ op: 'resolution',+ lease,+ modeId: operation === 'temporary-missing' ? '2' : '1',+ temporary: operation.startsWith('temporary'),+ },+ );+ if (operation === 'system') await changing;+ else+ await expect(changing).rejects.toThrow(+ operation === 'temporary-missing' ? 'DESKTOP_DISPLAY_MODE_MISSING' : 'MODE_FAILED',+ );+ await Promise.resolve();+ expect(h.deps.lockScreen).not.toHaveBeenCalled();+ expect(h.controller.state).toBeNull();+ });it('waits for an in-flight mode change before restoring after disconnect', async () => {const h = harness();let finish!: () => void;@@ -603,12 +712,25 @@ describe('remote desktop authority and lifecycle', () => {lease: first.lease,lockScreen: true,});+ await Promise.resolve();h.revoke();finish();await expect(pending).rejects.toThrow('DESKTOP_LOCK_FAILED');expect(h.controller.state).toBeNull();});- it.each(['stop', 'expiry', 'revoke', 'account'])(+ it('keeps plain protocol stop available for recovery without locking', async () => {+ const h = harness();+ h.deps.lockScreen = vi.fn(async () => {});+ const { lease } = (await h.controller.request('phone', {+ op: 'start',+ displayId: '1',+ lockOnExit: true,+ })) as RemoteDesktopLease;+ await h.controller.request('phone', { op: 'stop', lease });+ expect(h.deps.lockScreen).not.toHaveBeenCalled();+ expect(h.controller.state).toBeNull();+ });+ it.each(['revoke', 'account'])('cancels an in-flight lock on %s without cancelling for another peer',async (reason) => {const h = harness();@@ -630,13 +752,9 @@ describe('remote desktop authority and lifecycle', () => {lockScreen: true,});const rejected = expect(pending).rejects.toThrow('cancelled');+ await Promise.resolve();h.controller.stop('other');expect(signal.aborted).toBe(false);- if (reason === 'stop') h.controller.stop('phone');- if (reason === 'expiry') {- h.advance(120000);- h.controller.tick();- }if (reason === 'revoke') {h.revoke();h.controller.tick();@@ -650,6 +768,97 @@ describe('remote desktop authority and lifecycle', () => {expect(h.controller.state).toBeNull();},);+ it.each(['expiry', 'disconnect', 'stop'])(+ 'locks locally after %s and keeps locking through further network loss',+ async (reason) => {+ const h = harness();+ let finish!: () => void;+ let current!: () => boolean;+ let signal!: AbortSignal;+ h.deps.stopPrivacyScreen = vi.fn();+ h.deps.lockScreen = vi.fn((check, cancellation) => {+ current = check;+ signal = cancellation;+ return new Promise<void>((resolve) => {+ finish = resolve;+ });+ });+ const { lease } = (await h.controller.request('phone', {+ op: 'start',+ displayId: '1',+ lockOnExit: true,+ control: true,+ })) as RemoteDesktopLease;+ h.controller.signalingLost('other');+ expect(h.controller.state).toEqual({ peer: 'phone', controlling: true });+ expect(h.deps.lockScreen).not.toHaveBeenCalled();+ if (reason === 'expiry') {+ h.advance(13000);+ h.controller.tick();+ }+ if (reason === 'disconnect') h.controller.signalingLost('phone');+ if (reason === 'stop') void h.controller.stop('phone');+ const stopped = h.controller.stop('phone');+ await Promise.resolve();+ expect(h.deps.stopInput).toHaveBeenCalled();+ expect(h.deps.stopPrivacyScreen).not.toHaveBeenCalled();+ h.advance(60000);+ h.controller.tick();+ h.controller.signalingLost('phone');+ expect(signal.aborted).toBe(false);+ expect(current()).toBe(true);+ expect(h.deps.lockScreen).toHaveBeenCalledOnce();+ expect(() =>+ h.controller.input(lease, 1, [{ kind: 'key', code: 'KeyA', down: true }]),+ ).toThrow('DESKTOP_VIEW_ONLY');+ await expect(+ h.controller.request('other', { op: 'start', displayId: '1', takeover: true }),+ ).rejects.toThrow('DESKTOP_BUSY');+ finish();+ await stopped;+ expect(h.controller.state).toBeNull();+ expect(h.deps.stopPrivacyScreen).toHaveBeenCalledOnce();+ },+ );+ it.each([true, false])(+ 'uses the latest heartbeat lock policy (%s), independent of privacy',+ async (enabled) => {+ const h = harness();+ h.deps.lockScreen = vi.fn(async () => {});+ h.deps.privacyScreen = vi.fn(async () => {});+ const { lease } = (await h.controller.request('phone', {+ op: 'start',+ displayId: '1',+ lockOnExit: !enabled,+ control: true,+ })) as RemoteDesktopLease;+ await h.controller.request('phone', { op: 'heartbeat', lease, lockOnExit: enabled });+ // A delayed privacy update cannot overwrite the independent lease policy.+ await h.controller.request('phone', {+ op: 'privacyScreen',+ lease,+ enabled: false,+ lockOnExit: !enabled,+ });+ await h.controller.stop('phone');+ expect(h.deps.lockScreen).toHaveBeenCalledTimes(enabled ? 1 : 0);+ expect(h.controller.state).toBeNull();+ },+ );+ it.each(['resume', 'takeover'])('does not lock during an authorized %s handoff', async (kind) => {+ const h = harness();+ h.deps.lockScreen = vi.fn(async () => {});+ await h.controller.request('phone', { op: 'start', displayId: '1', lockOnExit: true });+ await h.controller.request(kind === 'resume' ? 'phone' : 'other', {+ op: 'start',+ displayId: '1',+ [kind]: true,+ lockOnExit: true,+ });+ expect(h.deps.lockScreen).not.toHaveBeenCalled();+ await h.controller.stop();+ expect(h.deps.lockScreen).toHaveBeenCalledOnce();+ });it('releases a stalled fallback frame for another peer without stopping its lease', async () => {vi.useFakeTimers();try {diff --git a/apps/desktop/src/main/remote-desktop/controller.ts b/apps/desktop/src/main/remote-desktop/controller.tsindex 4c13bfd07b..cacbc2f3b2 100644--- a/apps/desktop/src/main/remote-desktop/controller.ts+++ b/apps/desktop/src/main/remote-desktop/controller.ts@@ -130,6 +130,7 @@ export class RemoteDesktopController {backgroundViewing?: boolean;clipboardSync?: boolean;hostMute?: boolean;+ lockOnExit?: boolean;privacyLockOnExit?: boolean;})| null = null;@@ -147,6 +148,7 @@ export class RemoteDesktopController {private viewerGeometryManaged = false;private locking = false;private lockAbort: AbortController | null = null;+ private stopping: Promise<void> | null = null;private startingPeer: string | null = null;private framePending = false;private clipboardPending = false;@@ -242,13 +244,17 @@ export class RemoteDesktopController {}}tick(): void {+ const active = this.active;+ if (!active) return;if (- this.active &&- (this.active.expires <= this.now() ||- !this.deps.authorized(this.active.peer) ||- !this.authenticationCurrent(this.active.peer, this.active.authenticationSession))- )- this.stop();+ !this.deps.authorized(active.peer) ||+ !this.authenticationCurrent(active.peer, active.authenticationSession)+ ) {+ this.lockAbort?.abort();+ void this.stop(undefined, false);+ } else if (!this.locking && active.expires <= this.now()) {+ void this.stop();+ }}/** Losing the signaling socket is expected while the phone shows PiP.* Only an authorized, view-only presentation may outlive it, and only while@@ -265,13 +271,46 @@ export class RemoteDesktopController {return;this.stop(peer);}- stop(peer?: string): Promise<void> {+ stop(peer?: string, lockScreen = this.exitLockEnabled()): Promise<void> {if (peer && this.active?.peer !== peer) {// Cancelling a takeover candidate must not revoke the current owner's work.if (this.startingPeer === peer) this.startingPeer = null;return Promise.resolve();}- this.lockAbort?.abort();+ if (this.stopping) return this.stopping;+ const active = this.active;+ if (active && lockScreen && this.deps.lockScreen) {+ this.locking = true;+ const cancellation = new AbortController();+ this.lockAbort = cancellation;+ active.controlling = false;+ this.controlGeneration++;+ this.deps.stopInput();+ // The policy belongs to the host lease. Losing its heartbeat or receiving+ // another stop must not cancel an accepted lock; revocation still can.+ const pending = Promise.resolve()+ .then(() =>+ this.deps.lockScreen!(+ () =>+ this.active === active &&+ !cancellation.signal.aborted &&+ this.deps.authorized(active.peer) &&+ this.authenticationCurrent(active.peer, active.authenticationSession),+ cancellation.signal,+ ),+ )+ .finally(async () => {+ this.stopping = null;+ this.lockAbort = null;+ this.locking = false;+ if (this.active === active) await this.stop(active.peer, false);+ });+ this.stopping = pending;+ // Timer/disconnect callers have no reply channel; explicit callers still+ // receive the rejection. Privacy masks stay up until locking settles.+ void pending.catch(() => log.warn('Screen lock failed while ending remote desktop'));+ return pending;+ }if (this.active) this.lastEnded = { peer: this.active.peer, lease: this.active.lease };this.clipboardTransfer.reset();this.controlGeneration++;@@ -291,6 +330,9 @@ export class RemoteDesktopController {this.deps.changed();return restoring;}+ private exitLockEnabled(): boolean {+ return (this.active?.lockOnExit ?? this.active?.privacyLockOnExit) === true;+ }/** A display change keeps the viewer's video only when it asked and capture can follow. */private holdVideo(keepVideo: boolean | undefined): boolean {if (keepVideo && this.deps.pauseVideo?.()) return true;@@ -378,7 +420,7 @@ export class RemoteDesktopController {};return control ? await this.withControl(peer, active, reply) : reply;} catch (error) {- if (this.active === active) this.stop(peer);+ if (this.active === active) this.stop(peer, false);throw error;} finally {this.resolutionWrite = null;@@ -419,8 +461,13 @@ export class RemoteDesktopController {}/** Join the same restoration used by disconnects before the process exits. */async stopAndRestore(): Promise<void> {- const safety = this.stop();- await Promise.all([safety, this.restoreStoppedDisplay()]);+ try {+ await this.stop();+ } finally {+ // Locking retains the lease until it settles, even on failure. Only then+ // can restoration start; process shutdown must also await that work.+ await this.restoreStoppedDisplay();+ }}/*** Input injection failed while the lease is still valid. Input belongs to the@@ -495,7 +542,7 @@ export class RemoteDesktopController {}async stopPrivacyByUser(): Promise<void> {const active = this.active;- if (!active?.privacyLockOnExit) {+ if (!active || !this.exitLockEnabled()) {this.stopByUser();return;}@@ -635,10 +682,13 @@ export class RemoteDesktopController {if (caps.permissions && !desktopPermissionReady(caps.permissions.screenRecording))throw new Error('DESKTOP_SCREEN_PERMISSION_REQUIRED');if (request.resume && this.userStopped.has(peer)) throw new Error('DESKTOP_STOPPED');- if (request.takeover && this.active) this.stopByUser();+ if (request.takeover && this.active) {+ this.userStopped.set(this.active.peer, this.active.lease);+ void this.stop(this.active.peer, false);+ }// A lost start reply can leave our own lease alive. Rotate it using the// existing cleanup so the new viewer can restart its input sequence at 0.- else if (resumesActive) this.stop(peer);+ else if (resumesActive) this.stop(peer, false);if (this.viewerDisplay || this.originalResolution) {const restorationGeneration = this.controlGeneration;await this.restoreStoppedDisplay();@@ -662,6 +712,7 @@ export class RemoteDesktopController {expires: this.now() + REMOTE_DESKTOP_LEASE_MS,sequence: -1,authenticationSession,+ lockOnExit: request.lockOnExit,};this.deps.changed();return lease;@@ -850,7 +901,7 @@ export class RemoteDesktopController {// Input restarts on the new geometry within the same request.return request.control ? await this.withControl(peer, active, reply) : reply;} catch (error) {- if (this.active === active) this.stop(peer);+ if (this.active === active) this.stop(peer, false);throw error;} finally {this.resolutionWrite = null;@@ -858,30 +909,15 @@ export class RemoteDesktopController {}}case 'stop': {- if (request.lockScreen) {- if (!this.deps.lockScreen) throw new Error('DESKTOP_LOCK_UNAVAILABLE');- if (this.locking || this.starting) throw new Error('DESKTOP_BUSY');- this.locking = true;- const cancellation = new AbortController();- this.lockAbort = cancellation;- active.controlling = false;- this.controlGeneration++;- try {- await this.deps.lockScreen(() => {- this.tick();- return this.active === active && this.deps.authorized(peer);- }, cancellation.signal);- } finally {- this.lockAbort = null;- this.locking = false;- if (this.active === active) this.stop(peer);- }- return { ok: true };- }- this.stop(peer);+ if (request.lockScreen && !this.deps.lockScreen)+ throw new Error('DESKTOP_LOCK_UNAVAILABLE');+ // Plain stop is also used for viewer recovery and display handoff.+ // Explicit exit sends lockScreen; involuntary host stops use the policy.+ await this.stop(peer, request.lockScreen === true);return { ok: true };}case 'heartbeat':+ if (request.lockOnExit !== undefined) active.lockOnExit = request.lockOnExit;active.expires = this.now() + REMOTE_DESKTOP_LEASE_MS;return { controlling: active.controlling };case 'presentation': {@@ -1011,7 +1047,7 @@ export class RemoteDesktopController {if (!current()) throw new Error('DESKTOP_LEASE_EXPIRED');// Release old geometry before the native write can emit display events.// Completion must not inspect or stop a replacement lease.- this.stop(peer);+ this.stop(peer, false);};try {if (this.viewerDisplay) {@@ -1041,7 +1077,7 @@ export class RemoteDesktopController {await this.deps.resolution(active.sourceDisplayId, request.modeId, beforeChange);return { ok: true };} catch (error) {- if (restoringViewer && current()) this.stop(peer);+ if (restoringViewer && current()) this.stop(peer, false);throw error;}}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 985ebb4cc3..e34ca34141 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@@ -136,7 +136,7 @@ it('retries an initial capabilities timeout on a legacy host without inventing aruntime.post?.({ type: 'streaming', epoch: 'lease-one' });expect(snapshot).toMatchObject({ ready: true, controlling: true, error: null });expect(current.requests.filter((request) => request.op === 'start')).toEqual([- { op: 'start', displayId: 'one' },+ { op: 'start', displayId: 'one', lockOnExit: false },]);});@@ -313,8 +313,8 @@ it.each([['two'], ['two', 'three']])(});expect(current.hostLease()).toBe('lease-' + latest);expect(current.requests.filter((request) => request.op === 'start')).toEqual([- { op: 'start', displayId: 'one' },- { op: 'start', displayId: latest },+ { op: 'start', displayId: 'one', lockOnExit: false },+ { op: 'start', displayId: latest, lockOnExit: false },]);},);@@ -330,6 +330,7 @@ it('still requires explicit confirmation to take over another viewer', async ()op: 'start',displayId: 'one',takeover: true,+ lockOnExit: false,});});diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsxindex b7c3ee6573..5e1c618809 100644--- a/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx+++ b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx@@ -407,6 +407,8 @@ export function RemoteDesktopSession({);exitLock.current =lockOnExitLoaded && lockOnExit && caps?.lockOnExit === true;+ const exitLockPolicy = useRef(false);+ exitLockPolicy.current = lockOnExitLoaded && lockOnExit;const [status, setStatus] = useState("connecting");const [appState, setAppState] = useState(AppState.currentState);const [error, setError] = useState<string | null>(null);@@ -631,6 +633,8 @@ export function RemoteDesktopSession({);const request = useCallback(async <T,>(message: RemoteDesktopRequest, preSend?: () => void) => {+ if (message.op === "start" || message.op === "heartbeat")+ message = { ...message, lockOnExit: exitLockPolicy.current };const relay = () =>linkRef.current.invoke<T>(deviceId, REMOTE_DESKTOP_CHANNEL, [message], {preSend,@@ -658,6 +662,17 @@ export function RemoteDesktopSession({() => ({ current: new RemoteDesktopViewerSession(request) }),[request],);+ const updateLockOnExit = (enabled: boolean) => {+ setLockOnExit(enabled);+ // Requests and exit can run before React commits the preference update.+ exitLockPolicy.current = enabled;+ exitLock.current = enabled && caps?.lockOnExit === true;+ const current = active.current;+ if (current)+ void request({ op: "heartbeat", lease: current.lease }).catch(() => {+ // Local preference remains saved; the regular heartbeat retries sync.+ });+ };const authRef = useRef(auth);authRef.current = auth;const loadIceServers = (attemptId: string) =>@@ -1083,6 +1098,7 @@ export function RemoteDesktopSession({linkRef.current.status !== "online" ||!ready.current ||!videoPreferencesLoaded ||+ !lockOnExitLoaded ||!deviceId ||AppState.currentState !== "active")@@ -1239,6 +1255,7 @@ export function RemoteDesktopSession({stop,t,videoPreferencesLoaded,+ lockOnExitLoaded,viewerSession,],);@@ -1606,7 +1623,7 @@ export function RemoteDesktopSession({restoreInlinePresentationRef.current();if (!active.current) void connectRef.current();}- }, [focused, pause, videoPreferencesLoaded]);+ }, [focused, pause, videoPreferencesLoaded, lockOnExitLoaded]);useEffect(() => {send({type: "theme",@@ -3325,7 +3342,7 @@ export function RemoteDesktopSession({lockOnExit,lockOnExitAvailable:lockOnExitLoaded && caps?.lockOnExit === true,- onLockOnExit: setLockOnExit,+ onLockOnExit: updateLockOnExit,}}connected={Boolean(lease) && !connectionPending}controlling={Boolean(lease?.controlling)}diff --git a/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsxindex 686a219334..bb3bd36cb2 100644--- a/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx+++ b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx@@ -68,16 +68,23 @@ vi.mock("../useAutoUnlockSettings", () => ({};},}));-vi.mock("../useLockOnExitPreference", () => ({- useRemoteDesktopPreference: () => [false, vi.fn(), true],- useLockOnExitPreference: () => [- fixture.lockOnExit,- (value: boolean) => {- fixture.lockOnExit = value;- },- true,- ],-}));+vi.mock("../useLockOnExitPreference", async (importOriginal) => {+ const actual =+ await importOriginal<typeof import("../useLockOnExitPreference")>();+ return {+ useRemoteDesktopPreference: () => [false, vi.fn(), true],+ useLockOnExitPreference: (deviceId: string) =>+ fixture.lockPreferenceFromStorage+ ? actual.useLockOnExitPreference(deviceId)+ : [+ fixture.lockOnExit,+ (value: boolean) => {+ fixture.lockOnExit = value;+ },+ true,+ ],+ };+});vi.mock("../usePictureInPicturePreference", () => ({usePictureInPicturePreference: () => {const [enabled, setEnabled] = useState(fixture.pipEnabled);@@ -106,6 +113,7 @@ const fixture = vi.hoisted(() => ({securityBusy: false,themeMode: "light",lockOnExit: false,+ lockPreferenceFromStorage: false,lockSupported: true,alert: vi.fn(),resetUnlockAttempt: vi.fn(),@@ -417,6 +425,7 @@ beforeEach(async () => {fixture.maybeUnlock.mockReset().mockResolvedValue(undefined);fixture.themeMode = "light";fixture.lockOnExit = false;+ fixture.lockPreferenceFromStorage = false;fixture.lockSupported = true;fixture.views = {};fixture.keyboardListeners = {};@@ -1693,7 +1702,7 @@ describe("remote desktop controls", () => {await act(async () => vi.advanceTimersByTimeAsync(6000));expect(host.textContent).not.toContain("remoteDesktop.upgrade");expect(requests().filter((request) => request.op === "start")).toEqual([- { op: "start", displayId: "display" },+ { op: "start", displayId: "display", lockOnExit: false },]);});it("keeps the video when a fallback input is rejected because control was released", async () => {@@ -3107,10 +3116,107 @@ describe("remote desktop controls", () => {});},);+ it.each([false, true])(+ "waits for the saved lock policy before starting, enabled=%s",+ async (enabled) => {+ act(() => root.unmount());+ fixture.lockPreferenceFromStorage = true;+ let finish!: (value: string | null) => void;+ const original = storage.getItem;+ const read = vi.spyOn(storage, "getItem").mockImplementation((key) =>+ key.includes(".lock-on-exit.")+ ? new Promise<string | null>((resolve) => {+ finish = resolve;+ })+ : original(key),+ );+ try {+ root = createRoot(host);+ await act(async () => root.render(<RemoteDesktopScreen />));+ await act(async () =>+ fixture.message!({ nativeEvent: { data: '{"type":"ready"}' } }),+ );+ expect(finish).toBeTypeOf("function");+ expect(requests().filter((r) => r.op === "start")).toHaveLength(0);+ await act(async () => finish(String(enabled)));+ expect(requests().filter((r) => r.op === "start")).toEqual([+ { op: "start", displayId: "display", lockOnExit: enabled },+ ]);+ } finally {+ read.mockRestore();+ }+ },+ );+ it.each([true, false])(+ "syncs a changed lock policy immediately and retries after failure, enabled=%s",+ async (enabled) => {+ act(() => root.unmount());+ fixture.lockPreferenceFromStorage = true;+ const key = "cindy.mobile.remote-desktop.lock-on-exit.v1.computer";+ storage.items.set(key, String(!enabled));+ root = createRoot(host);+ await act(async () => root.render(<RemoteDesktopScreen />));+ await connect();+ act(() => button("operations").click());+ act(() => button("security").click());+ let rejectSync!: (error: Error) => void;+ const original = fixture.invoke.getMockImplementation()!;+ fixture.invoke.mockImplementation((...args) =>+ args[2][0].op === "heartbeat"+ ? new Promise((_, reject) => {+ rejectSync = reject;+ })+ : original(...args),+ );+ const toggle = host.querySelector(+ '[data-testid="remoteDesktop.lockOnExit"]',+ ) as HTMLButtonElement;+ await act(async () => toggle.click());+ // No timer advance: the first heartbeat must already carry the new value.+ expect(requests().filter((r) => r.op === "heartbeat")).toEqual([+ { op: "heartbeat", lease: "lease", lockOnExit: enabled },+ ]);+ expect(toggle.getAttribute("aria-checked")).toBe(String(enabled));+ expect(storage.items.get(key)).toBe(String(enabled));+ await act(async () => rejectSync(new Error("offline")));+ expect(toggle.getAttribute("aria-checked")).toBe(String(enabled));+ let finishRenewal!: (value: unknown) => void;+ fixture.invoke.mockImplementation((...args) =>+ args[2][0].op === "heartbeat"+ ? new Promise((resolve) => {+ finishRenewal = resolve;+ })+ : original(...args),+ );+ await act(async () => vi.advanceTimersByTimeAsync(3000));+ expect(requests().filter((r) => r.op === "heartbeat")).toHaveLength(2);+ expect(+ requests().filter((r) => r.op === "heartbeat").at(-1),+ ).toMatchObject({ lockOnExit: enabled });+ await act(async () => button("disconnect").click());+ expect(requests().filter((r) => r.op === "stop")).toEqual([+ {+ op: "stop",+ lease: "lease",+ ...(enabled ? { lockScreen: true } : {}),+ },+ ]);+ await act(async () => finishRenewal({ controlling: true }));+ expect(requests().filter((r) => r.op === "start")).toHaveLength(1);+ expect(goBackGuarded).toHaveBeenCalledTimes(1);+ },+ );it("requests lock once on explicit exit, independent of automatic unlock", async () => {fixture.lockOnExit = true;await act(async () => root.render(<RemoteDesktopScreen />));await connect();+ expect(requests().find((r) => r.op === "start")).toMatchObject({+ lockOnExit: true,+ });+ await act(async () => vi.advanceTimersByTimeAsync(3000));+ expect(+ requests().filter((r) => r.op === "heartbeat").at(-1),+ ).toMatchObject({ lockOnExit: true });await act(async () => button("back").click());expect(requests().filter((r) => r.op === "stop")).toEqual([{ op: "stop", lease: "lease", lockScreen: true },@@ -4138,8 +4244,8 @@ describe("remote desktop controls", () => {await connect();await act(async () => vi.advanceTimersByTimeAsync(30_000));expect(requests().filter((r) => r.op === "start")).toEqual([- { op: "start", displayId: "display" },- { op: "start", displayId: "display", resume: true },+ { op: "start", displayId: "display", lockOnExit: false },+ { op: "start", displayId: "display", resume: true, lockOnExit: false },]);expect(button("connect")).not.toBeNull();});@@ -4182,7 +4288,7 @@ describe("remote desktop controls", () => {requests().filter((r) => r.op === "start").at(-1),- ).toEqual({ op: "start", displayId: "second" });+ ).toEqual({ op: "start", displayId: "second", lockOnExit: false });expect(host.textContent).not.toContain("remoteDesktop.upgrade");if (native)expect(@@ -4243,6 +4349,7 @@ describe("remote desktop controls", () => {op: "start",displayId: "display",resume: true,+ lockOnExit: false,});await act(async () => vi.advanceTimersByTimeAsync(30_000));expect(requests().filter((r) => r.op === "start")).toHaveLength(2);@@ -4253,7 +4360,7 @@ describe("remote desktop controls", () => {requests().filter((r) => r.op === "start").at(-1),- ).toEqual({ op: "start", displayId: "display" });+ ).toEqual({ op: "start", displayId: "display", lockOnExit: false });});it("reloads a viewer that died while permissions were blocked", async () => {const original = fixture.invoke.getMockImplementation()!;@@ -4814,6 +4921,7 @@ describe("remote desktop controls", () => {op: "start",displayId: "display",takeover: true,+ lockOnExit: false,});});it('resends the upper-pane bounds whenever a folded viewer becomes ready', async () => {diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 6e73f75361..ad37c7abb3 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -195,6 +195,18 @@ relay 类型、allowlist 或持久化 schema,服务端无需改动;Mobile标签的可选 `nameCustomized` 标记区分显式改名与预设本地化。新版更新请求仅在明确改名时提交 `nameCustomized: true`;旧端换色时携带相同原名不会误置标记。缺省字段沿用旧显示规则。+## 远程桌面退出与断线锁屏++远程桌面的 `start` / `heartbeat` 可追加布尔 `lockOnExit`。新版 Desktop 与 Mobile+提前同步退出锁屏策略,被控端在本机断开、信令断开或现有心跳过期时本地执行锁屏;+存活连接的 resume / takeover 和显示器切换不触发。锁屏期间重复断开或心跳过期+不能取消锁屏,撤权与认证身份变化仍可取消。旧请求缺少字段时保留原行为(旧手机的+`privacyScreen.lockOnExit` 继续兼容),新字段优先于该隐私屏幕附带偏好。+旧被控端忽略新字段,主动退出仍发送原 `stop.lockScreen`;断网兜底需要被控端升级。+不带 `lockScreen` 的协议 `stop` 仍用于重连和切显示器的清理,不执行锁屏。+Desktop 本地关窗不等待远端停止回执,后台清理只作用于原 peer / lease,不重置共享链路。+此扩展沿用已有业务通道,不改变 relay、服务端协议或权限范围。+## 远程桌面临时分辨率被控端以可选能力 `resolutionRestore` 声明系统分辨率的连接级恢复支持。diff --git a/docs/remote-desktop-credentials.md b/docs/remote-desktop-credentials.mdindex 932257a585..d454b8e5ba 100644--- a/docs/remote-desktop-credentials.md+++ b/docs/remote-desktop-credentials.md@@ -228,22 +228,27 @@ reject that field; actual modal recovery and user-selection still fail. The onlysubmit action remains LUIBUTTON_GO and recovery buttons are never invoked. Thecurrent Mac preparation probe succeeds with this passive help visible.-### Lock on explicit remote exit+### Lock on remote exit and connection lossThe Security panel includes a separate, default-off lock-on-exit preference. It isa non-secret phone-local boolean override per computer, independent of saved-passwords and Face ID. Explicit Back/disconnect and route unmount send-`stop.lockScreen: true` only when the host advertises `lockOnExit`. Ordinary stop,-media recovery, display changes, background pauses and Face ID inactivity retain-their original behavior. Network loss or force-quitting the phone cannot promise-delivery of an exit command. Old hosts retain normal stop behavior.+passwords and Face ID. Desktop has the same per-computer preference. New viewers+send optional `lockOnExit` on start and heartbeats, so the host owns the policy+before a connection fails. Explicit Back/disconnect and route unmount still send+`stop.lockScreen: true` when supported, including to older hosts. New hosts also+lock on signaling loss or heartbeat expiry (12-second lease, checked every second),+without needing an exit command. Live-lease resume/takeover, display changes and+background viewing with live heartbeats do not trigger locking. Old hosts ignore+the optional policy fields and still need the explicit exit command.The existing authenticated Device Link request is bound to its exact peer andlease. The host blocks replacement starts during the bounded lock operation,releases held input, then the validated native helper sends the fixed macOS lockshortcut and confirms the current console session is locked. No password, Face ID,server endpoint or account-wide setting is involved. Lock failure is visible on-the phone; only macOS currently advertises this optional capability.+the phone; Desktop closes locally without awaiting the remote result. Background+lock failures are logged on the host. macOS and supported Linux hosts advertise+this optional capability.### Stable mobile controlsdiff --git a/docs/remote-desktop.md b/docs/remote-desktop.mdindex f48a163608..858da03e3a 100644--- a/docs/remote-desktop.md+++ b/docs/remote-desktop.md@@ -35,6 +35,9 @@ keyboard focus; without it, Cmd/Ctrl+W requests closing this viewer.Native window close and the close shortcut share a confirmationdialog only after a connection is established; cancelling keeps the connection and control lease. Confirmation belongsto the current window generation and cannot close a later connection.+After confirmation, the local window closes immediately, retires its input and+heartbeat authority, and sends lease cleanup in the background. A missing or+failed remote reply cannot keep the window open or close a replacement window.Desktop uses the local system cursor inside the remote picture, with standardshape hints from the host. Pointer size is independent of remote resolution and zoom.@@ -56,7 +59,10 @@ macOS-to-macOS automatic unlock. Non-secret preferences are scoped to the localaccount and target computer; only explicit overrides are stored. Host effectsare capability-gated and applied after control is confirmed. Privacy failuresremain visible ahead of mute or clipboard notices, with explicit retry. Explicit-exit waits for the requested lock; reconnect and display changes do not lock.+exit does not wait for the requested lock. The host receives the lock-on-exit+policy at start and on heartbeats, then locks locally on stop, signaling loss or+lease expiry. Live-lease resume/takeover and display changes do not lock; recovery+after expiry waits for the already-triggered lock to finish.See [native credential behavior](remote-desktop-credentials.md) for password storage.Video quality changes are coalesced while negotiation is pending. The toolbarshows receive rate and clears stale network samples, while resolution discoverydiff --git a/packages/device-link/src/__tests__/remoteDesktop.test.ts b/packages/device-link/src/__tests__/remoteDesktop.test.tsindex 4f0a276162..97820d7959 100644--- a/packages/device-link/src/__tests__/remoteDesktop.test.ts+++ b/packages/device-link/src/__tests__/remoteDesktop.test.ts@@ -11,6 +11,24 @@ import {} from "../remoteDesktop";import { REMOTE_INVOKE_ALLOWLIST, PUSH_FORWARD_ALLOWLIST } from "../allowlist";describe("remote desktop wire boundary", () => {+ it.each([+ { op: "start", displayId: "1" },+ { op: "heartbeat", lease: "a" },+ ])(+ "accepts an optional boolean lock policy on $op without changing legacy requests",+ (request) => {+ expect(parseRemoteDesktopRequest(request)).toEqual(request);+ for (const lockOnExit of [true, false])+ expect(parseRemoteDesktopRequest({ ...request, lockOnExit })).toEqual({+ ...request,+ lockOnExit,+ });+ for (const lockOnExit of ["true", 1, null, {}])+ expect(() =>+ parseRemoteDesktopRequest({ ...request, lockOnExit }),+ ).toThrow("INVALID_REQUEST");+ },+ );it("preserves legacy stop and accepts only a boolean explicit lock request", () => {expect(parseRemoteDesktopRequest({ op: "stop", lease: "a" })).toEqual({ op: "stop", lease: "a" });expect(parseRemoteDesktopRequest({ op: "stop", lease: "a", lockScreen: true })).toEqual({ op: "stop", lease: "a", lockScreen: true });diff --git a/packages/device-link/src/remoteDesktop.ts b/packages/device-link/src/remoteDesktop.tsindex 53921675d8..23032c8c33 100644--- a/packages/device-link/src/remoteDesktop.ts+++ b/packages/device-link/src/remoteDesktop.ts@@ -153,7 +153,7 @@ export interface RemoteDesktopCapabilities {automaticReconnect?: boolean;/** Explicit same-account replacement of the active viewer. */connectionTakeover?: boolean;- /** Explicit remote exit can lock the host; ordinary stop/recovery is unchanged. */+ /** Can lock the host on exit. New hosts also honor the lease's lockOnExit policy. */lockOnExit?: boolean;videoSettings?: boolean;trickleIce?: boolean;@@ -251,8 +251,9 @@ export type RemoteDesktopRequest =resume?: boolean;takeover?: boolean;control?: boolean;+ lockOnExit?: boolean;}- | { op: "heartbeat"; lease: string }+ | { op: "heartbeat"; lease: string; lockOnExit?: boolean }| { op: "stop"; lease: string; lockScreen?: boolean }| { op: "frame"; lease: string; cursorOverlay?: boolean }| { op: "control" | "presentation"; lease: string; enabled: boolean }@@ -297,6 +298,11 @@ export function parseRemoteDesktopRequest(if (!value || typeof value !== "object" || Array.isArray(value))throw new Error("INVALID_REQUEST");const v = value as Record<string, unknown>;+ const lockOnExit = () => {+ if (v.lockOnExit !== undefined && typeof v.lockOnExit !== "boolean")+ throw new Error("INVALID_REQUEST");+ return typeof v.lockOnExit === "boolean" ? { lockOnExit: v.lockOnExit } : {};+ };// Optional on start and display changes; older hosts drop it and the viewer// asks for control separately.const control = () => {@@ -324,6 +330,7 @@ export function parseRemoteDesktopRequest(...(v.takeover === true ? { takeover: true } : {}),...(typeof v.resume === "boolean" ? { resume: v.resume } : {}),...control(),+ ...lockOnExit(),};}if (typeof v.lease !== "string" || v.lease.length > 128 || !v.lease)@@ -410,7 +417,7 @@ export function parseRemoteDesktopRequest(...(v.lockScreen === true ? { lockScreen: true } : {}),};}- if (v.op === "heartbeat") return { op: v.op, lease };+ if (v.op === "heartbeat") return { op: v.op, lease, ...lockOnExit() };if ((v.op === "control" || v.op === "presentation") &&typeof v.enabled === "boolean"