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): 被控提示条不再阻塞主进程,并改为仅本机可用的断开确认
Dash5a838a253671
diff --git a/apps/desktop/src/main/remote-desktop/__tests__/backgroundActivity.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/backgroundActivity.test.tsindex 8dc1bb1696..54553c0bc7 100644--- a/apps/desktop/src/main/remote-desktop/__tests__/backgroundActivity.test.ts+++ b/apps/desktop/src/main/remote-desktop/__tests__/backgroundActivity.test.ts@@ -44,6 +44,7 @@ describe('remote desktop state polling', () => {assertTrustedAppRendererEvent,readDeviceLinkSettings: () => ({ remoteDesktopEnabled: false }),remoteDesktop: { state: null },+ controlledOverlay: { visible: false },permissions: { guideOpen: false },readWindowsDesktopSupport,throwIpcError: (code: string) => {diff --git a/apps/desktop/src/main/remote-desktop/__tests__/controlledOverlay.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/controlledOverlay.test.tsindex 40131a0516..7159e0d469 100644--- a/apps/desktop/src/main/remote-desktop/__tests__/controlledOverlay.test.ts+++ b/apps/desktop/src/main/remote-desktop/__tests__/controlledOverlay.test.ts@@ -16,6 +16,9 @@ interface FakeWindow extends EventEmitter {webContents: EventEmitter & { executeJavaScript: Mock };setContentProtection: Mock;setAlwaysOnTop: Mock;+ setIgnoreMouseEvents: Mock;+ focus: Mock;+ moveTop: Mock;getBounds(): Bounds;setBounds(bounds: Bounds): void;isVisible(): boolean;@@ -57,9 +60,16 @@ vi.mock('electron', () => ({bounds: Bounds;webContents = Object.assign(new EventEmitter(), {setWindowOpenHandler: vi.fn(),- // The page width follows the label that was actually loaded.+ // The overlay width follows the label that was actually loaded; the+ // confirmation reports its height.executeJavaScript: vi.fn(async () =>- this.html.includes('ByDevice') ? 240 : this.html.includes('beingControlled') ? 180 : 160,+ this.html.includes('disconnectChoiceDetail')+ ? 150+ : this.html.includes('ByDevice')+ ? 240+ : this.html.includes('beingControlled')+ ? 180+ : 160,),});constructor(options: Options) {@@ -76,6 +86,7 @@ vi.mock('electron', () => ({setContentProtection = vi.fn();setVisibleOnAllWorkspaces = vi.fn();setAlwaysOnTop = vi.fn();+ setIgnoreMouseEvents = vi.fn();getMediaSourceId() {return `window:${100 + this.id}:0`;}@@ -89,6 +100,11 @@ vi.mock('electron', () => ({state.events.push(`show:${100 + this.id}`);this.visible = true;}+ show() {+ this.visible = true;+ }+ focus = vi.fn();+ moveTop = vi.fn();isVisible() {return this.visible;}@@ -134,15 +150,29 @@ const settle = async () => {function fixture() {const excluded = vi.fn((ids: number[]) => state.events.push(`exclude:${ids.join(',')}`));const revoke = vi.fn<(peer: string) => Promise<void>>(async () => {});- return { overlay: new ControlledOverlay(excluded, revoke), excluded, revoke };+ const disconnect = vi.fn<(peer: string) => void>();+ return {+ overlay: new ControlledOverlay(excluded, revoke, disconnect),+ excluded,+ revoke,+ disconnect,+ };}const navigate = (window: FakeWindow, url: string) => {const event = { url, preventDefault: vi.fn() };window.webContents.emit('will-navigate', event);return event;};-/** Clicks the revoke link of the page the window currently shows. */-const clickRevoke = (window: FakeWindow) => {+/** Answers the disconnect confirmation as its form / Cancel link would navigate. */+const answer = (window: FakeWindow, choice: 'disconnect' | 'revoke' | 'cancel') =>+ navigate(+ window,+ choice === 'cancel'+ ? 'https://cindy-overlay.invalid/choose/cancel'+ : `https://cindy-overlay.invalid/choose/disconnect?${choice === 'revoke' ? 'revoke=1' : ''}`,+ );+/** Clicks the Disconnect link of the page the window currently shows. */+const clickDisconnect = (window: FakeWindow) => {const href = /<a href="([^"]+)"/.exec(window.html)?.[1].replaceAll('&', '&');return navigate(window, href!);};@@ -153,7 +183,7 @@ beforeEach(() => {state.events.length = 0;state.displays = [primary, secondary];state.load = null;- state.confirm.mockReset().mockResolvedValue({ response: 1 });+ state.confirm.mockReset();state.themeMode = 'system';});@@ -176,7 +206,7 @@ it('filters the overlay from capture before its first visible frame', async () =expect(state.events).toEqual(['exclude:101', 'show:101']);expect(window.html).toContain('remoteDesktop.beingViewed');// Measured pill width, centred under the top of the shared display's work area.- expect(window.getBounds()).toEqual({ x: 640, y: 37, width: 160, height: 28 });+ expect(window.getBounds()).toEqual({ x: 640, y: 37, width: 160, height: 36 });});it('reloads the label in place when control is granted', async () => {@@ -197,24 +227,26 @@ it('keeps a dragged overlay on the shared display and remembers it for the run',overlay.update(target);await settle();const window = state.windows[0];- window.setBounds({ x: 1400, y: 500, width: 180, height: 28 });+ window.setBounds({ x: 1400, y: 500, width: 180, height: 36 });window.emit('moved');- expect(window.getBounds()).toEqual({ x: 1260, y: 500, width: 180, height: 28 });+ expect(window.getBounds()).toEqual({ x: 1260, y: 500, width: 180, height: 36 });overlay.update(null);overlay.update(target);await settle();- expect(state.windows[1].getBounds()).toEqual({ x: 1260, y: 500, width: 180, height: 28 });+ expect(state.windows[1].getBounds()).toEqual({ x: 1260, y: 500, width: 180, height: 36 });// A lease on another display starts from that display's default spot.overlay.update({ ...target, displayId: '2' });await settle();- expect(state.windows[1].getBounds()).toEqual({ x: 2310, y: 12, width: 180, height: 28 });+ expect(state.windows[1].getBounds()).toEqual({ x: 2310, y: 12, width: 180, height: 36 });});it('removes the window and its capture filter when the lease or privacy ends it', async () => {const { overlay, excluded } = fixture();overlay.update(phone);await settle();+ expect(overlay.visible).toBe(true);overlay.update(null);+ expect(overlay.visible).toBe(false);expect(state.windows[0].destroyed).toBe(true);expect(excluded).toHaveBeenLastCalledWith([]);expect(screen.listenerCount('display-metrics-changed')).toBe(0);@@ -254,7 +286,7 @@ it('renders the viewing device name as escaped markup and skips unchanged targetconst window = state.windows[0];expect(window.html).toContain('remoteDesktop.controlledByDevice:x</span><b>y');expect(window.html).not.toContain('<b>');- expect(window.html).toContain('remoteDevice.revokeAccess');+ expect(window.html).toContain('remoteDesktop.disconnect');expect(window.getBounds()).toMatchObject({ x: 600, width: 240 });// Only constant code is ever executed in the page.expect(new Set(window.webContents.executeJavaScript.mock.calls.map(([code]) => code)).size).toBe(@@ -263,56 +295,148 @@ it('renders the viewing device name as escaped markup and skips unchanged targetoverlay.update({ ...target });await settle();expect(window.loadURL).toHaveBeenCalledTimes(1);- clickRevoke(window);+ clickDisconnect(window);+ await settle();+ answer(state.windows[1], 'revoke');await settle();expect(revoke).toHaveBeenCalledExactlyOnceWith('p&1');});-it('revokes the device named on the clicked page, only after confirmation', async () => {- const { overlay, revoke } = fixture();+it('disconnects the device named on the clicked page, revoking it only when ticked', async () => {+ const { overlay, revoke, disconnect } = fixture();overlay.update(phone);await settle();const window = state.windows[0];- state.confirm.mockResolvedValueOnce({ response: 0 });- expect(clickRevoke(window).preventDefault).toHaveBeenCalled();+ expect(clickDisconnect(window).preventDefault).toHaveBeenCalled();await settle();+ answer(state.windows[1], 'cancel');+ await settle();+ expect(state.windows[1].destroyed).toBe(true);+ expect(disconnect).not.toHaveBeenCalled();expect(revoke).not.toHaveBeenCalled();// The lease moves to another viewer, but its page is still loading.let finishLoad!: () => void;- state.load = () => new Promise<void>((resolve) => (finishLoad = resolve));+ state.load = (loading) =>+ loading === window ? new Promise<void>((resolve) => (finishLoad = resolve)) : undefined;overlay.update(laptop);// The periodic sync repeats the same target while it loads.overlay.update(laptop);await settle();expect(window.loadURL).toHaveBeenCalledTimes(2);- let answer!: (value: { response: number }) => void;- state.confirm.mockReturnValueOnce(new Promise((resolve) => (answer = resolve)));- clickRevoke(window);- // A second click while the dialog is open does not stack another dialog.- clickRevoke(window);- answer({ response: 1 });- await settle();- expect(state.confirm).toHaveBeenCalledTimes(2);+ clickDisconnect(window);+ await settle();+ // A second click while the choice is open raises it instead of stacking another.+ clickDisconnect(window);+ await settle();+ expect(state.windows).toHaveLength(3);+ expect(state.windows[2].moveTop).toHaveBeenCalledOnce();+ answer(state.windows[2], 'revoke');+ await settle();+ // Revoking ends the session too.+ expect(disconnect).toHaveBeenCalledExactlyOnceWith('phone');expect(revoke).toHaveBeenCalledExactlyOnceWith('phone');finishLoad();await settle();- clickRevoke(window);+ clickDisconnect(window);+ await settle();+ answer(state.windows[3], 'disconnect');await settle();- expect(revoke).toHaveBeenLastCalledWith('laptop');+ // Left unticked, the session ends without revoking.+ expect(disconnect).toHaveBeenLastCalledWith('laptop');+ expect(revoke).toHaveBeenCalledTimes(1);+});++// 2026-10-18 incident: a parentless native alert runs app-modally on macOS, so+// Main stopped serving heartbeats and injected input until the lease expired.+it('asks only the local user: hidden from capture, passed through, never focused', async () => {+ vi.useFakeTimers();+ try {+ const { overlay, revoke, excluded } = fixture();+ overlay.update(phone);+ await settle();+ clickDisconnect(state.windows[0]);+ await settle();+ const confirmation = state.windows[1];+ expect(state.confirm).not.toHaveBeenCalled();+ // Filtered like the overlay before its first visible frame, and shown without focus,+ // so injected keys cannot answer it.+ expect(confirmation.setContentProtection).toHaveBeenCalledWith(true);+ expect(state.events.slice(-2)).toEqual(['exclude:101,102', 'show:102']);+ expect(confirmation.options).toMatchObject({ focusable: false, acceptFirstMouse: true });+ expect(confirmation.focus).not.toHaveBeenCalled();+ expect(confirmation.setAlwaysOnTop).toHaveBeenCalledWith(true, 'screen-saver', 1);+ // Revoking is opt-in: the checkbox starts unticked.+ expect(confirmation.html).toContain('<input type="checkbox" name="revoke" value="1">');+ // Centred on the shared display's work area.+ expect(confirmation.getBounds()).toEqual({ x: 520, y: 388, width: 400, height: 150 });++ // The viewer's pointer passes through it as through the overlay.+ overlay.viewerPointer({ x: 700, y: 450 });+ expect(confirmation.setIgnoreMouseEvents).toHaveBeenLastCalledWith(true);+ expect(state.windows[0].setIgnoreMouseEvents).toHaveBeenLastCalledWith(true);+ vi.advanceTimersByTime(1000);+ expect(confirmation.setIgnoreMouseEvents).toHaveBeenLastCalledWith(false);++ answer(confirmation, 'cancel');+ await settle();+ expect(confirmation.destroyed).toBe(true);+ expect(excluded).toHaveBeenLastCalledWith([101]);++ clickDisconnect(state.windows[0]);+ await settle();+ overlay.update(null);+ await settle();+ expect(state.windows[2].destroyed).toBe(true);+ expect(excluded).toHaveBeenLastCalledWith([]);+ expect(revoke).not.toHaveBeenCalled();+ } finally {+ vi.useRealTimers();+ }+});++it("lets the viewer's pointer pass through, handing it back when it leaves or rests", async () => {+ vi.useFakeTimers();+ try {+ const { overlay } = fixture();+ overlay.update(phone);+ await settle();+ // Centred pill: x 600–839, y 37–72.+ const window = state.windows[0];+ overlay.viewerPointer({ x: 700, y: 50 });+ overlay.viewerPointer({ x: 710, y: 50 });+ expect(window.setIgnoreMouseEvents.mock.calls).toEqual([[true]]);+ overlay.viewerPointer({ x: 700, y: 200 });+ expect(window.setIgnoreMouseEvents).toHaveBeenLastCalledWith(false);+ // Resting over it returns it to local clicks; the viewer's next click re-arms it first.+ overlay.viewerPointer({ x: 700, y: 50 });+ vi.advanceTimersByTime(999);+ expect(window.setIgnoreMouseEvents).toHaveBeenLastCalledWith(true);+ vi.advanceTimersByTime(1);+ expect(window.setIgnoreMouseEvents).toHaveBeenLastCalledWith(false);+ overlay.viewerPointer({ x: 700, y: 50 });+ expect(window.setIgnoreMouseEvents).toHaveBeenLastCalledWith(true);+ // A lease that ends mid-rest leaves nothing behind for the next overlay.+ overlay.update(null);+ vi.runAllTimers();+ expect(window.setIgnoreMouseEvents).toHaveBeenCalledTimes(5);+ } finally {+ vi.useRealTimers();+ }});it('cancels every other navigation without acting', async () => {- const { overlay, revoke } = fixture();+ const { overlay, revoke, disconnect } = fixture();overlay.update(phone);await settle();expect(navigate(state.windows[0], 'https://example.com/').preventDefault).toHaveBeenCalled();expect(- navigate(state.windows[0], 'https://cindy-overlay.invalid/revoke?peer=').preventDefault,+ navigate(state.windows[0], 'https://cindy-overlay.invalid/disconnect?peer=').preventDefault,).toHaveBeenCalled();await settle();- expect(state.confirm).not.toHaveBeenCalled();+ expect(state.windows).toHaveLength(1);+ expect(disconnect).not.toHaveBeenCalled();expect(revoke).not.toHaveBeenCalled();});diff --git a/apps/desktop/src/main/remote-desktop/__tests__/inputHost.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/inputHost.test.tsindex 3174bc83a3..397291e3af 100644--- a/apps/desktop/src/main/remote-desktop/__tests__/inputHost.test.ts+++ b/apps/desktop/src/main/remote-desktop/__tests__/inputHost.test.ts@@ -354,6 +354,37 @@ describe('native input lifecycle', () => {expect(c.child.stdin.write).not.toHaveBeenCalled();c.exit();});+ // The controlled overlay needs each viewer pointer before it lands to let it pass through.+ it('reports each whole-display pointer position before injecting it', async () => {+ const c = childProcess();+ const pointer = vi.fn();+ const host = new DesktopInputHost(+ vi.fn(),+ {+ platform: 'darwin',+ resolveBinary: async () => '/test/helper',+ spawn: () => {+ queueMicrotask(() => c.child.stdout.emit('data', Buffer.from('ready\n')));+ return c.typed;+ },+ },+ (point) => pointer(point, c.child.stdin.write.mock.calls.length),+ );+ await host.start('1');+ host.input([+ { kind: 'move', x: 0.25, y: 0.75 },+ { kind: 'key', code: 'KeyA', down: true },+ { kind: 'button', button: 0, down: true, x: 0.5, y: 0.5 },+ ]);+ await flush();+ expect(pointer.mock.calls).toEqual([+ [{ x: 25, y: 74 }, 0],+ [{ x: 50, y: 50 }, 0],+ ]);+ expect(c.child.stdin.write).toHaveBeenCalledOnce();+ host.stop();+ c.exit();+ });});it('keeps Linux whole-desktop coordinates normalized and releases input before returning ownership', async () => {@@ -450,7 +481,11 @@ describe('代输入 window input', () => {['darwin', { windowId: 0, pid: 2 }],['darwin', { windowId: 1, pid: -1 }],] as const) {- const host = new DesktopInputHost(vi.fn(), { platform, resolveBinary: async () => '/x', spawn });+ const host = new DesktopInputHost(vi.fn(), {+ platform,+ resolveBinary: async () => '/x',+ spawn,+ });await expect(host.start('1', window)).rejects.toThrow('DESKTOP_INPUT_UNSUPPORTED');}expect(spawn).not.toHaveBeenCalled();diff --git a/apps/desktop/src/main/remote-desktop/controlledOverlay.ts b/apps/desktop/src/main/remote-desktop/controlledOverlay.tsindex 10cdf6bee1..ec4b8330bc 100644--- a/apps/desktop/src/main/remote-desktop/controlledOverlay.ts+++ b/apps/desktop/src/main/remote-desktop/controlledOverlay.ts@@ -1,7 +1,5 @@import {- app,BrowserWindow,- dialog,nativeTheme,screen,session,@@ -16,16 +14,29 @@ import { escapeHtml } from './privacyScreenHtml';const log = createLogger('remote-desktop:overlay');-const HEIGHT = 28;+const HEIGHT = 36;const INITIAL_WIDTH = 220;const TOP_MARGIN = 12;// Renderer crashes / load failures tolerated per lease before giving up.const MAX_FAILURES = 3;// Never loaded: the page has no script, so its only way to talk to Main is-// its revoke link, which will-navigate cancels and recognizes by this prefix.-const REVOKE_URL = 'https://cindy-overlay.invalid/revoke?peer=';+// its Disconnect link, which will-navigate cancels and recognizes by this prefix.+const DISCONNECT_URL = 'https://cindy-overlay.invalid/disconnect?peer=';// Constant code only: every label is rendered into the page markup itself.const MEASURE_SCRIPT = "Math.ceil(document.querySelector('main').getBoundingClientRect().width)";+// After the viewer's pointer rests this long, the shared cursor is handed back to local clicks.+const VIEWER_POINTER_REST_MS = 1000;+const CONFIRM_WIDTH = 400;+const CONFIRM_MEASURE_SCRIPT =+ "Math.ceil(document.querySelector('main').getBoundingClientRect().height)";+// The confirmation's answers, recognized by will-navigate like the Disconnect link:+// its script-free form submits the revoke checkbox as `?revoke=1` when ticked.+const CHOICE_URL = {+ disconnect: 'https://cindy-overlay.invalid/choose/disconnect',+ cancel: 'https://cindy-overlay.invalid/choose/cancel',+} as const;+/** Ending only this session, or also blocking the device until restored in Settings. */+type DisconnectChoice = 'disconnect' | 'revoke';export interface ControlledOverlayTarget {displayId: string;@@ -44,21 +55,62 @@ function overlayHtml(text: string, label: string, dark: boolean, peer: string)::root.dark{color-scheme:dark;--surface:#2c2c2a;--border:#3c3c3a;--text-primary:#d4d4d4;--chip:#3c3c3a}html,body{margin:0;height:100%;overflow:hidden;background:transparent}body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;user-select:none;cursor:default;-webkit-app-region:drag}-main{display:inline-flex;align-items:center;gap:8px;box-sizing:border-box;height:${HEIGHT}px;padding:0 4px 0 12px;border:1px solid var(--border);border-radius:9999px;background:var(--surface);color:var(--text-primary);font-size:12px;white-space:nowrap}-i{flex:none;width:6px;height:6px;border-radius:50%;background:var(--accent);animation:breathe 1.5s ease-in-out infinite}-span{max-width:260px;overflow:hidden;text-overflow:ellipsis}-a{flex:none;-webkit-app-region:no-drag;display:inline-flex;align-items:center;height:20px;padding:0 8px;border-radius:9999px;background:var(--chip);color:var(--text-primary);text-decoration:none;-webkit-user-drag:none}+main{display:inline-flex;align-items:center;gap:10px;box-sizing:border-box;height:${HEIGHT}px;padding:0 4px 0 16px;border:1px solid var(--border);border-radius:9999px;background:var(--surface);color:var(--text-primary);font-size:14px;font-weight:500;white-space:nowrap}+i{flex:none;width:8px;height:8px;border-radius:50%;background:var(--accent);animation:breathe 1.5s ease-in-out infinite}+span{max-width:320px;overflow:hidden;text-overflow:ellipsis}+a{flex:none;-webkit-app-region:no-drag;display:inline-flex;align-items:center;height:28px;padding:0 12px;border-radius:9999px;background:var(--chip);color:var(--text-primary);font-size:13px;text-decoration:none;-webkit-user-drag:none}a:hover{opacity:.8}@keyframes breathe{0%,100%{opacity:.3}50%{opacity:1}}@media(prefers-reduced-motion:reduce){i{animation:none}}-</style></head><body><main><i></i><span>${escapeHtml(text)}</span><a href="${escapeHtml(REVOKE_URL + encodeURIComponent(peer))}" draggable="false">${escapeHtml(label)}</a></main></body></html>`;+</style></head><body><main><i></i><span>${escapeHtml(text)}</span><a href="${escapeHtml(DISCONNECT_URL + encodeURIComponent(peer))}" draggable="false">${escapeHtml(label)}</a></main></body></html>`;}-/** The device named on the page whose revoke link was clicked. */-function revokedPeer(url: string): string | null {- if (!url.startsWith(REVOKE_URL)) return null;+/** Isolated disconnect confirmation: mirrors the shared ConfirmDialog's standard presentation+ * (DESIGN.md §4 Dialog & Modal, §2 ConfirmDialog Danger) — an unticked revoke checkbox,+ * Cancel first, Disconnect as the inverse neutral primary that turns danger while revoke+ * is ticked. Pointer-only: the window never takes keyboard focus (see askDisconnect). */+function confirmHtml(+ copy: {+ title: string;+ detail: string;+ revoke: string;+ revokeHint: string;+ cancel: string;+ disconnect: string;+ },+ dark: boolean,+): string {+ return `<!doctype html><html${dark ? ' class="dark"' : ''}><head><meta charset="utf-8">+<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'">+<style>+:root{color-scheme:light;--surface:#ffffff;--border:#d7d7d4;--text-primary:#262626;--text-secondary:#737373;--focus:#417cdd}+:root.dark{color-scheme:dark;--surface:#2c2c2a;--border:#3c3c3a;--text-primary:#d4d4d4;--text-secondary:#a3a3a3}+html,body{margin:0;overflow:hidden;background:transparent}+body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;user-select:none;cursor:default;-webkit-app-region:drag}+main{box-sizing:border-box;width:${CONFIRM_WIDTH}px;padding:16px;border:1px solid var(--border);border-radius:12px;background:var(--surface);color:var(--text-primary)}+h1{margin:0;font-size:16px;font-weight:500;line-height:1.5}+p{margin:8px 0 0;font-size:13px;line-height:1.5;color:var(--text-secondary)}+label{display:flex;align-items:flex-start;gap:8px;margin-top:16px;-webkit-app-region:no-drag}+input{flex:none;width:16px;height:16px;margin:2px 0 0;accent-color:var(--text-primary)}+b{display:block;font-size:13px;font-weight:500;line-height:1.5}+small{display:block;font-size:12px;line-height:1.5;color:var(--text-secondary)}+nav{display:flex;flex-wrap:wrap;justify-content:flex-end;gap:10px;margin-top:24px}+a,button{-webkit-app-region:no-drag;-webkit-user-drag:none;display:inline-flex;align-items:center;justify-content:center;box-sizing:border-box;min-width:96px;min-height:36px;margin:0;padding:6px 16px;border:0;border-radius:9999px;font:inherit;font-size:14px;font-weight:500;text-decoration:none;cursor:default;outline:none}+a:focus-visible,button:focus-visible,input:focus-visible{box-shadow:0 0 0 2px var(--focus)}+a:hover,button:hover{opacity:.85}+.cancel{border:1px solid var(--border);color:var(--text-primary)}+.primary{background:var(--text-primary);color:var(--surface)}+form:has(input:checked) .primary{background:#ef4444;color:#ffffff}+</style></head><body><main><h1>${escapeHtml(copy.title)}</h1><p>${escapeHtml(copy.detail)}</p>+<form action="${CHOICE_URL.disconnect}" method="get"><label><input type="checkbox" name="revoke" value="1"><span><b>${escapeHtml(copy.revoke)}</b><small>${escapeHtml(copy.revokeHint)}</small></span></label>+<nav><a class="cancel" href="${CHOICE_URL.cancel}" draggable="false">${escapeHtml(copy.cancel)}</a><button class="primary" type="submit">${escapeHtml(copy.disconnect)}</button></nav></form></main></body></html>`;+}++/** The device named on the page whose Disconnect link was clicked. */+function linkedPeer(url: string): string | null {+ if (!url.startsWith(DISCONNECT_URL)) return null;try {- return decodeURIComponent(url.slice(REVOKE_URL.length)) || null;+ return decodeURIComponent(url.slice(DISCONNECT_URL.length)) || null;} catch {return null;}@@ -80,10 +132,12 @@ function clamp(bounds: Rectangle, area: Rectangle): Rectangle {* and excluded from what the viewer receives. Frameless and never focused, it* has no close affordance; the lease alone decides its lifetime.*- * Every label change loads a fresh static page whose revoke link carries the- * device it names, so a click always revokes exactly the device on screen.- * The revoke button first asks in a visible system dialog, so a blind click- * from the viewer (who cannot see the overlay) cannot revoke anything itself.+ * Every label change loads a fresh static page whose Disconnect link carries the+ * device it names, so a click always acts on exactly the device on screen. It+ * asks first, with an unticked checkbox to also revoke the device's access.+ * Both are local-only: the viewer cannot see them, its pointer passes through+ * them to what it does see beneath, and the confirmation never takes keyboard+ * focus, so the viewer can neither open nor answer it.* (`closable: false` is avoided: on macOS it cancels window-list closes.)*/export class ControlledOverlay {@@ -98,15 +152,27 @@ export class ControlledOverlay {private placedDisplay: string | null = null;private generation = 0;private partitionConfigured = false;- private confirming = false;+ private confirmWindow: BrowserWindow | null = null;+ /** Capture-filter ids of the shown overlay and confirmation (macOS filters them explicitly). */+ private overlayId: number | null = null;+ private confirmId: number | null = null;+ /** Whether the local-only windows currently let clicks through, and when they take them back. */+ private passThrough = false;+ private restTimer: ReturnType<typeof setTimeout> | null = null;/** Last dragged origin, kept for this app run only. */private position: { x: number; y: number } | null = null;constructor(private readonly excluded: (ids: number[]) => void,private readonly revoke: (peer: string) => Promise<void>,+ private readonly disconnect: (peer: string) => void,) {}+ /** Shown on screen: while it is, the main window's own session notice stays hidden. */+ get visible(): boolean {+ return this.shown && this.window !== null && !this.window.isDestroyed();+ }+/** Idempotent; `null` removes the overlay. */update(target: ControlledOverlayTarget | null): void {if (!target) {@@ -128,9 +194,52 @@ export class ControlledOverlay {}}+ /** The viewer's pointer, in global DIP, just before it is injected. While it is+ * over the overlay or its confirmation, clicks pass through both; local clicks (on+ * the same system cursor) get them back once the viewer's pointer leaves or rests.+ * Each viewer button event re-arms pass-through before it is injected. */+ viewerPointer(point: { x: number; y: number }): void {+ const windows = this.localOnlyWindows();+ if (!windows.length) return;+ const over = windows.some((window) => {+ const { x, y, width, height } = window.getBounds();+ return point.x >= x && point.x < x + width && point.y >= y && point.y < y + height;+ });+ if (this.restTimer) clearTimeout(this.restTimer);+ this.restTimer = over+ ? setTimeout(() => this.setPassThrough(false), VIEWER_POINTER_REST_MS)+ : null;+ this.setPassThrough(over);+ }++ /** What the viewer must never reach: the shown overlay and the shown confirmation. */+ private localOnlyWindows(): BrowserWindow[] {+ const confirmation = this.confirmWindow;+ return [+ this.shown ? this.window : null,+ confirmation?.isVisible() ? confirmation : null,+ ].filter((window): window is BrowserWindow => window !== null && !window.isDestroyed());+ }++ private setPassThrough(on: boolean): void {+ if (this.passThrough === on) return;+ this.passThrough = on;+ for (const window of this.localOnlyWindows()) window.setIgnoreMouseEvents(on);+ }++ private publishExcluded(): void {+ this.excluded([this.overlayId, this.confirmId].filter((id): id is number => id !== null));+ }+stop(): void {this.generation++;this.target = null;+ if (this.restTimer) clearTimeout(this.restTimer);+ this.restTimer = null;+ this.passThrough = false;+ // An unanswered confirmation never outlives its lease: closing it cancels.+ const confirmation = this.confirmWindow;+ if (confirmation && !confirmation.isDestroyed()) confirmation.destroy();const window = this.window;if (!window) return;this.window = null;@@ -139,7 +248,8 @@ export class ControlledOverlay {this.loadingKey = '';this.placedDisplay = null;if (!window.isDestroyed()) window.destroy();- this.excluded([]);+ this.overlayId = null;+ this.publishExcluded();}/** The only failure path: counts against the lease that owns this window. */@@ -198,7 +308,7 @@ export class ControlledOverlay {target.controlling ? 'remoteDesktop.controlledByDevice' : 'remoteDesktop.viewedByDevice',).replaceAll('{{name}}', target.name): t(target.controlling ? 'remoteDesktop.beingControlled' : 'remoteDesktop.beingViewed');- const label = t('remoteDevice.revokeAccess');+ const label = t('remoteDesktop.disconnect');const dark = overlayIsDark();const key = JSON.stringify([text, label, dark, target.peer]);if (key === this.loadedKey) {@@ -230,30 +340,137 @@ export class ControlledOverlay {this.layout(window, width);}- private async confirmRevoke(peer: string): Promise<void> {- if (this.confirming) return;- this.confirming = true;+ private async confirmDisconnect(peer: string): Promise<void> {+ const open = this.confirmWindow;+ if (open && !open.isDestroyed()) {+ open.moveTop();+ return;+ }try {- app.focus({ steal: true });- const { response } = await dialog.showMessageBox({- type: 'warning',- message: t('settings.remoteControl.revokeConfirm.title'),- detail: t('settings.remoteControl.revokeConfirm.description'),- buttons: [t('privacyExit.cancel'), t('settings.remoteControl.revokeConfirm.confirm')],- defaultId: 0,- cancelId: 0,- noLink: true,- });- if (response === 1) await this.revoke(peer);+ const choice = await this.askDisconnect();+ if (!choice) return;+ // Either way this session ends now; revoking also blocks the device.+ this.disconnect(peer);+ if (choice === 'revoke') await this.revoke(peer);} catch (error) {- log.warn('overlay revoke failed', error);- } finally {- this.confirming = false;+ log.warn('overlay disconnect failed', error);}}- private async create(generation: number): Promise<void> {- this.generation = generation;+ /** Cindy's own confirmation instead of `dialog.showMessageBox`: without a visible+ * parent, macOS runs that alert app-modally, so Main stops serving the lease+ * (heartbeats, injected input) the viewer needs to answer it, and the lease+ * expires. A one-off, top-level, transparent float like the overlay itself,+ * so it is not one of the reusable auxiliary windows (electron-security §3.1).+ * Local-only like the overlay: filtered from capture, passed through by the+ * viewer's pointer, and never focusable, so injected keys cannot answer it+ * either; the local user answers by pointer (no Esc).+ * Resolves `null` for Cancel, closing, lease end and any failure. */+ private askDisconnect(): Promise<DisconnectChoice | null> {+ return new Promise((resolve) => {+ let window: BrowserWindow;+ try {+ window = new BrowserWindow({+ width: CONFIRM_WIDTH,+ height: 160,+ show: false,+ ...(process.platform === 'darwin' ? { type: 'panel' } : {}),+ frame: false,+ transparent: true,+ backgroundColor: '#00000000',+ acceptFirstMouse: true,+ focusable: false,+ resizable: false,+ minimizable: false,+ maximizable: false,+ fullscreenable: false,+ skipTaskbar: true,+ webPreferences: this.webPreferences(),+ });+ } catch (error) {+ log.warn('disconnect choice unavailable', error);+ resolve(null);+ return;+ }+ this.confirmWindow = window;+ let settled = false;+ const finish = (choice: DisconnectChoice | null) => {+ if (settled) return;+ settled = true;+ if (this.confirmWindow === window) {+ this.confirmWindow = null;+ if (this.confirmId !== null) {+ this.confirmId = null;+ this.publishExcluded();+ }+ }+ if (!window.isDestroyed()) window.destroy();+ resolve(choice);+ };+ window.on('closed', () => finish(null));+ window.webContents.setWindowOpenHandler(() => ({ action: 'deny' }));+ window.webContents.on('will-navigate', (event) => {+ event.preventDefault();+ if (event.url === CHOICE_URL.cancel) return finish(null);+ const [base, query = ''] = event.url.split('?', 2);+ if (base !== CHOICE_URL.disconnect) return;+ finish(new URLSearchParams(query).get('revoke') === '1' ? 'revoke' : 'disconnect');+ });+ window.webContents.on('render-process-gone', () => finish(null));+ void (async () => {+ const copy = {+ title: t('privacyExit.title'),+ detail: t('remoteDesktop.disconnectChoiceDetail'),+ revoke: t('remoteDesktop.disconnectRevoke'),+ revokeHint: t('remoteDesktop.disconnectRevokeHint'),+ cancel: t('privacyExit.cancel'),+ disconnect: t('remoteDesktop.disconnect'),+ };+ window.setMenuBarVisibility(false);+ window.setContentProtection(true);+ window.setVisibleOnAllWorkspaces(true, {+ visibleOnFullScreen: true,+ skipTransformProcessType: true,+ });+ // Above the overlay, which sits at the same level.+ window.setAlwaysOnTop(true, 'screen-saver', 1);+ await window.loadURL(+ `data:text/html;charset=utf-8,${encodeURIComponent(confirmHtml(copy, overlayIsDark()))}`,+ );+ if (settled) return;+ const height: unknown = await window.webContents.executeJavaScript(CONFIRM_MEASURE_SCRIPT);+ if (settled) return;+ if (typeof height !== 'number' || !Number.isFinite(height) || height <= 0)+ throw new Error('disconnect choice unavailable');+ const { workArea } = this.display();+ window.setBounds(+ clamp(+ {+ x: workArea.x + Math.round((workArea.width - CONFIRM_WIDTH) / 2),+ y: workArea.y + Math.round((workArea.height - height) / 2),+ width: CONFIRM_WIDTH,+ height,+ },+ workArea,+ ),+ false,+ );+ const id = Number(window.getMediaSourceId().split(':')[1]);+ if (!Number.isSafeInteger(id) || id <= 0) throw new Error('disconnect choice unavailable');+ // Install the capture filter before the first visible frame.+ this.confirmId = id;+ this.publishExcluded();+ if (this.passThrough) window.setIgnoreMouseEvents(true);+ window.showInactive();+ })().catch((error) => {+ log.warn('disconnect choice unavailable', error);+ finish(null);+ });+ });+ }++ /** The isolated, script-free partition shared by the overlay and its confirmation. */+ private webPreferences(): Electron.WebPreferences {const partition = session.fromPartition('cindy-desktop-overlay', { cache: false });if (!this.partitionConfigured) {partition.setPermissionCheckHandler(() => false);@@ -265,6 +482,24 @@ export class ControlledOverlay {);this.partitionConfigured = true;}+ return {+ session: partition,+ sandbox: true,+ contextIsolation: true,+ nodeIntegration: false,+ nodeIntegrationInSubFrames: false,+ nodeIntegrationInWorker: false,+ webSecurity: true,+ allowRunningInsecureContent: false,+ experimentalFeatures: false,+ plugins: false,+ navigateOnDragDrop: false,+ devTools: false,+ };+ }++ private async create(generation: number): Promise<void> {+ this.generation = generation;let window: BrowserWindow;try {window = new BrowserWindow({@@ -286,20 +521,7 @@ export class ControlledOverlay {maximizable: false,fullscreenable: false,skipTaskbar: true,- webPreferences: {- session: partition,- sandbox: true,- contextIsolation: true,- nodeIntegration: false,- nodeIntegrationInSubFrames: false,- nodeIntegrationInWorker: false,- webSecurity: true,- allowRunningInsecureContent: false,- experimentalFeatures: false,- plugins: false,- navigateOnDragDrop: false,- devTools: false,- },+ webPreferences: this.webPreferences(),});} catch (error) {log.warn('overlay unavailable', error);@@ -307,6 +529,7 @@ export class ControlledOverlay {return;}this.window = window;+ this.passThrough = false;const relayout = () => {if (this.window === window && this.shown && !window.isDestroyed()) this.layout(window);};@@ -325,13 +548,14 @@ export class ControlledOverlay {this.loadedKey = '';this.loadingKey = '';this.placedDisplay = null;- this.excluded([]);+ this.overlayId = null;+ this.publishExcluded();});window.webContents.setWindowOpenHandler(() => ({ action: 'deny' }));window.webContents.on('will-navigate', (event) => {event.preventDefault();- const peer = revokedPeer(event.url);- if (peer && this.window === window) void this.confirmRevoke(peer);+ const peer = linkedPeer(event.url);+ if (peer && this.window === window) void this.confirmDisconnect(peer);});window.webContents.on('render-process-gone', () =>this.fail(window, generation, new Error('overlay renderer gone')),@@ -351,7 +575,8 @@ export class ControlledOverlay {const id = Number(window.getMediaSourceId().split(':')[1]);if (!Number.isSafeInteger(id) || id <= 0) throw new Error('overlay window id unavailable');// Install the capture filter before the first visible frame.- this.excluded([id]);+ this.overlayId = id;+ this.publishExcluded();window.showInactive();this.shown = true;} catch (error) {diff --git a/apps/desktop/src/main/remote-desktop/index.ts b/apps/desktop/src/main/remote-desktop/index.tsindex ce742384a9..19312aa409 100644--- a/apps/desktop/src/main/remote-desktop/index.ts+++ b/apps/desktop/src/main/remote-desktop/index.ts@@ -209,6 +209,10 @@ const controlledOverlay = new ControlledOverlay(if (!controllerDirectory) throw new Error('controller directory unavailable');await controllerDirectory.revoke(peer);},+ // Same as the main window's Disconnect, for the session the overlay names only.+ (peer) => {+ if (remoteDesktop.state?.peer === peer) remoteDesktop.stopByUser();+ },);/** Device-link owns names and revocation; injected at registration (no import cycle). */export interface RemoteDesktopControllerDirectory {@@ -269,9 +273,13 @@ let pending: {} | null = null;// A dead input helper or a refused injection is an input failure, not a session// failure: repair input once while keeping the lease, capture and media running.-const input = new DesktopInputHost(() => {- void remoteDesktop.releaseControl(true);-});+const input = new DesktopInputHost(+ () => {+ void remoteDesktop.releaseControl(true);+ },+ undefined,+ (point) => controlledOverlay.viewerPointer(point),+);const clipboardCounter = new ClipboardCounter(resolveDesktopInputBinary);// A display change holds native capture instead of stopping it: frames pause// until the changed display is known, then the same stream follows it. The@@ -1142,6 +1150,7 @@ export function registerRemoteDesktopIpc(return {enabled: readDeviceLinkSettings().remoteDesktopEnabled,active: remoteDesktop.state,+ overlay: controlledOverlay.visible,permissionGuide: permissions.guideOpen,...(checkWindowsSupport === true? { windowsSupport: await readWindowsDesktopSupport() }diff --git a/apps/desktop/src/main/remote-desktop/inputHost.ts b/apps/desktop/src/main/remote-desktop/inputHost.tsindex 33b70b3201..528a9b5438 100644--- a/apps/desktop/src/main/remote-desktop/inputHost.ts+++ b/apps/desktop/src/main/remote-desktop/inputHost.ts@@ -227,6 +227,8 @@ export class DesktopInputHost {spawn: (binary: string, args: string[] = []) =>spawn(binary, args, { stdio: 'pipe', windowsHide: true }),},+ /** Each whole-display pointer position (global DIP), reported just before it is injected. */+ private readonly onPointer?: (point: { x: number; y: number }) => void,) {}async start(displayId: string, window?: { windowId: number; pid: number }): Promise<void> {this.stop();@@ -386,6 +388,7 @@ export class DesktopInputHost {x: Math.round(display.bounds.x + event.x * (display.bounds.width - 1)),y: Math.round(display.bounds.y + event.y * (display.bounds.height - 1)),};+ this.onPointer?.(point);const native = process.platform === 'win32' ? screen.dipToScreenPoint(point) : point;return { ...event, ...native };}),diff --git a/apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopHost.tsx b/apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopHost.tsxindex 8ac955adcf..eb4d1c0a5e 100644--- a/apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopHost.tsx+++ b/apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopHost.tsx@@ -62,7 +62,8 @@ export function RemoteDesktopHost() {showCancel={false}maxWidth={460}/>- {state.active && (+ {/* The on-screen overlay, where supported, carries the same notice and Disconnect. */}+ {state.active && !state.overlay && (<divrole="status"className="fixed bottom-4 left-1/2 z-50 flex -translate-x-1/2 items-center gap-3 rounded-full border border-[var(--border-default)] bg-[var(--settings-theme-card-bg)] px-4 py-2 text-13 text-[var(--text-primary)]"diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex e3103fb8b6..65d70946a8 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -723,6 +723,9 @@"controlledByDevice": "{{name}} is controlling your desktop","viewedByDevice": "{{name}} is viewing your desktop","disconnect": "Disconnect",+ "disconnectChoiceDetail": "Disconnecting ends this remote desktop session; the device can connect again later.",+ "disconnectRevoke": "Also revoke this device's access",+ "disconnectRevokeHint": "It can no longer connect to this machine until you restore it under Settings → Remote Connection.","back": "Back","connect": "Connect","connecting": "Connecting…",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex f8b047e9d0..2700bb1463 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -711,6 +711,9 @@"controlledByDevice": "{{name}} がデスクトップを操作しています","viewedByDevice": "{{name}} がデスクトップを表示しています","disconnect": "切断",+ "disconnectChoiceDetail": "切断すると今回のリモートデスクトップが終了し、相手は後で再接続できます。",+ "disconnectRevoke": "このデバイスのアクセス権も撤回する",+ "disconnectRevokeHint": "撤回すると本機に接続できなくなります。「設定 → リモート接続」で復元できます。","back": "戻る","connect": "接続","connecting": "接続中…",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 9caaedc382..21f058f2ea 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -711,6 +711,9 @@"controlledByDevice": "{{name}}에서 데스크톱을 원격으로 제어 중","viewedByDevice": "{{name}}에서 데스크톱을 원격으로 보는 중","disconnect": "연결 끊기",+ "disconnectChoiceDetail": "연결을 끊으면 이번 원격 데스크톱이 종료되며, 상대 기기는 나중에 다시 연결할 수 있습니다.",+ "disconnectRevoke": "이 기기의 액세스 권한도 철회",+ "disconnectRevokeHint": "철회하면 이 컴퓨터에 더 이상 연결할 수 없으며, 설정 → 원격 연결에서 복원할 수 있습니다.","back": "뒤로","connect": "연결","connecting": "연결 중…",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 85e339b0bf..693b312ae8 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -711,6 +711,9 @@"controlledByDevice": "{{name}} 正在远程控制桌面","viewedByDevice": "{{name}} 正在远程查看桌面","disconnect": "断开连接",+ "disconnectChoiceDetail": "断开后本次远程桌面结束,对方之后仍可重新连接。",+ "disconnectRevoke": "同时撤销这台设备的访问权限",+ "disconnectRevokeHint": "撤销后对方无法再远程连接本机,需在「设置 → 远程连接」中恢复。","back": "返回","connect": "连接","connecting": "连接中…",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 5243b8fe48..6920d20132 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -711,6 +711,9 @@"controlledByDevice": "{{name}} 正在遠端控制桌面","viewedByDevice": "{{name}} 正在遠端檢視桌面","disconnect": "中斷連線",+ "disconnectChoiceDetail": "中斷後本次遠端桌面結束,對方之後仍可重新連線。",+ "disconnectRevoke": "同時撤銷這台裝置的訪問權限",+ "disconnectRevokeHint": "撤銷後對方無法再遠端連線本機,需在「設定 → 遠端連線」中恢復。","back": "返回","connect": "連線","connecting": "連線中…",diff --git a/apps/desktop/src/shared/remoteDesktop.ts b/apps/desktop/src/shared/remoteDesktop.tsindex 515cb479c4..61574f881f 100644--- a/apps/desktop/src/shared/remoteDesktop.ts+++ b/apps/desktop/src/shared/remoteDesktop.ts@@ -66,6 +66,8 @@ export interface DesktopHostCommand {export interface DesktopLocalState {enabled: boolean;active: { peer: string; controlling: boolean } | null;+ /** The on-screen controlled overlay is showing; it then replaces the main window's notice. */+ overlay?: boolean;permissionGuide?: boolean;windowsSupport?: WindowsDesktopSupport;}