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): restore Windows input and localized viewer controls
MagicLizif2c042d3e60c
diff --git a/apps/desktop/native/remote-desktop/README.md b/apps/desktop/native/remote-desktop/README.mdindex dc6c24ea88..ec897f6b29 100644--- a/apps/desktop/native/remote-desktop/README.md+++ b/apps/desktop/native/remote-desktop/README.md@@ -1,4 +1,28 @@-# macOS input helper trust boundary+# Remote desktop native helpers++## Windows input desktop access++The Windows helper explicitly attaches its input thread to `OpenInputDesktop`.+The handle requests `DESKTOP_JOURNALPLAYBACK` together with its existing+read/write/switch rights: Windows requires this access for `SendInput` on the+attached desktop, even though Cindy installs no journaling hooks. Without the+right, attachment succeeds and the helper prints `ready`, but its first input+is rejected with Win32 `ERROR_ACCESS_DENIED` (5). This affects controllers on+any OS; it is a Windows host issue, not a Mac-to-Windows wire-format difference.++The desktop ACL, process token, UIPI and secure-desktop service boundary still+apply. This does not elevate the helper or bypass UAC. An input failure releases+control while keeping the viewer lease and video; viewers observe the resulting+`controlling:false` on the existing heartbeat.++`desktop::tests::binding_and_rechecking_preserve_input_access` is an explicit+native integration check for an unlocked, interactive Windows session. It uses+zero relative movement (no clicks, typing or pointer displacement) to verify+binding, rechecking and restoration. Run the Windows crate's `cargo test` with a+task-specific `--target-dir` outside the checkout. It is separate from Node unit+tests and does not prove lock/UAC or physical cross-device behavior.++## macOS input helper trust boundaryThe input helper authenticates its caller before inspecting any command orrequesting Accessibility permission. Node's macOS stdio socket pairs carry kerneldiff --git a/apps/desktop/native/remote-desktop/windows-input/src/desktop.rs b/apps/desktop/native/remote-desktop/windows-input/src/desktop.rsindex c381db77bf..8217a313a9 100644--- a/apps/desktop/native/remote-desktop/windows-input/src/desktop.rs+++ b/apps/desktop/native/remote-desktop/windows-input/src/desktop.rs@@ -29,7 +29,14 @@ impl InputDesktop {let next = OpenInputDesktop(0,0,- DESKTOP_READOBJECTS | DESKTOP_WRITEOBJECTS | DESKTOP_SWITCHDESKTOP,+ // An explicitly attached desktop needs JOURNALPLAYBACK access+ // for SendInput, even though we do not install journaling hooks.+ // Without it binding succeeds, then the first input fails with+ // ERROR_ACCESS_DENIED. The desktop ACL and UIPI still apply.+ DESKTOP_READOBJECTS+ | DESKTOP_WRITEOBJECTS+ | DESKTOP_SWITCHDESKTOP+ | DESKTOP_JOURNALPLAYBACK,);if next.is_null() {return Err(());@@ -77,3 +84,53 @@ impl Drop for InputDesktop {}}}++#[cfg(test)]+mod tests {+ use super::InputDesktop;+ use windows_sys::Win32::UI::Input::KeyboardAndMouse::*;++ // Explicit native integration check: run on an unlocked interactive Windows+ // desktop. Zero relative movement never clicks, types or moves the pointer.+ fn accepts_zero_movement() -> bool {+ let input = INPUT {+ r#type: INPUT_MOUSE,+ Anonymous: INPUT_0 {+ mi: MOUSEINPUT {+ dx: 0,+ dy: 0,+ mouseData: 0,+ dwFlags: MOUSEEVENTF_MOVE,+ time: 0,+ dwExtraInfo: 0,+ },+ },+ };+ unsafe { SendInput(1, &input, std::mem::size_of::<INPUT>() as i32) == 1 }+ }++ #[test]+ fn binding_and_rechecking_preserve_input_access() {+ assert!(+ accepts_zero_movement(),+ "requires an interactive Windows desktop"+ );+ {+ let mut desktop = InputDesktop::new();+ assert_eq!(desktop.bind(), Ok(false));+ assert!(+ accepts_zero_movement(),+ "binding must retain SendInput access"+ );+ assert_eq!(desktop.bind(), Ok(false));+ assert!(+ accepts_zero_movement(),+ "rechecking must retain SendInput access"+ );+ }+ assert!(+ accepts_zero_movement(),+ "drop must restore the original desktop"+ );+ }+}diff --git a/apps/desktop/scripts/remote-desktop-viewer-smoke.mjs b/apps/desktop/scripts/remote-desktop-viewer-smoke.mjsindex d06c77f360..4270c3ce6c 100644--- a/apps/desktop/scripts/remote-desktop-viewer-smoke.mjs+++ b/apps/desktop/scripts/remote-desktop-viewer-smoke.mjs@@ -1,5 +1,5 @@/** Real Chromium + production Desktop viewer, with a loopback synthetic host.- * Usage: node apps/desktop/scripts/remote-desktop-viewer-smoke.mjs <Vite origin> <Chrome path>+ * Usage: node apps/desktop/scripts/remote-desktop-viewer-smoke.mjs <Vite origin> <Chrome path> [win32|darwin]* No account, OS capture, credential, or remote input. Artifacts live in a unique OS temp dir.*/import assert from 'node:assert/strict';@@ -10,6 +10,8 @@ import { chromium } from 'playwright-core';const origin = new URL(process.argv[2]);assert(['localhost', '127.0.0.1'].includes(origin.hostname));+const controllerPlatform = process.argv[4] ?? 'win32';+assert(['win32', 'darwin'].includes(controllerPlatform));const artifacts = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-viewer-smoke-'));const browser = await chromium.launch({ executablePath: process.argv[3], headless: true });try {@@ -29,6 +31,7 @@ try {version: 1,enabled: true,canControl: true,+ clipboardText: true,automaticReconnect: true,videoSettings: true,platform: 'win32',@@ -92,7 +95,7 @@ try {return {};}});- await viewer.addInitScript(() => {+ await viewer.addInitScript((controllerPlatform) => {const noop = () => {},off = () => noop;const scope = {@@ -101,13 +104,16 @@ try {active: true,};window.electronAPI = {- platform: 'win32',+ platform: controllerPlatform,preferredSystemLocale: 'en',logToMain: noop,appearanceSettings: { getSync: () => null, onChanged: off },localThemes: { listSync: () => ({ success: true, themes: [], diagnostics: [] }) },authHasPersistedSessionHintSync: () => true,- appShortcuts: { getState: () => ({ overrides: {}, platform: 'win32' }), onChanged: off },+ appShortcuts: {+ getState: () => ({ overrides: {}, platform: controllerPlatform }),+ onChanged: off,+ },theme: { applyVibrancy: noop },getFullscreenState: async () => false,onFullscreenChange: off,@@ -117,7 +123,10 @@ try {remoteDesktopViewer: {state: async () => scope,onActive: off,- onLocale: off,+ onLocale: (listener) => {+ window.applyViewerLocale = listener;+ return noop;+ },rendererReady: async () => {},presentationReady: async () => {},request: (_generation, request) => window.viewerRequest(request),@@ -128,7 +137,7 @@ try {clipboard: async () => {},},};- });+ }, controllerPlatform);await viewer.goto(new URL('/?remoteDesktopViewer=1', origin.origin).href);await viewer.waitForFunction(() => document.querySelector('video')?.videoWidth > 0,@@ -136,7 +145,32 @@ try {{ timeout: 25000 },);await viewer.waitForFunction(() => document.querySelector('.remote-viewer-network') !== null);- await viewer.locator('#stage').click({ position: { x: 400, y: 300 } });+ const stage = await viewer.locator('#stage').boundingBox();+ assert(stage);+ await viewer.mouse.move(stage.x + 400, stage.y + 300);+ await host.waitForFunction(() => window.inputs.some((event) => event.kind === 'move'));+ await viewer.mouse.down();+ await host.waitForFunction(() =>+ window.inputs.some((event) => event.kind === 'button' && event.button === 0 && event.down),+ );+ await viewer.mouse.move(stage.x + 520, stage.y + 370, { steps: 5 });+ await viewer.mouse.up();+ await host.waitForFunction(() =>+ window.inputs.some((event) => event.kind === 'button' && event.button === 0 && !event.down),+ );+ const mouseEvents = await host.evaluate(() => window.inputs);+ const down = mouseEvents.findIndex((event) => event.kind === 'button' && event.down);+ const up = mouseEvents.findIndex(+ (event, index) => index > down && event.kind === 'button' && !event.down,+ );+ assert(+ mouseEvents.slice(down + 1, up).some((event) => event.kind === 'move'),+ 'drag moves reach the host while the button is held',+ );+ assert(+ !mouseEvents.slice(down + 1, up).some((event) => event.kind === 'release'),+ 'focus does not cancel a held mouse button',+ );await viewer.keyboard.type('desktop');await host.waitForFunction(() =>window.inputs.some((event) => event.kind === 'text' && event.text.includes('d')),@@ -165,11 +199,36 @@ try {'media recovery must retain its lease',);assert.deepEqual(errors, []);+ await viewer.evaluate(() => window.applyViewerLocale('zh-CN'));+ await viewer.getByRole('button', { name: '操作', exact: true }).click();+ const settings = viewer.getByRole('complementary', { name: '操作' });+ await settings.locator('label').filter({ hasText: '帧率' }).waitFor();+ assert(+ !/\?{2,}|\uFFFD/u.test(await settings.innerText()),+ 'Chinese settings must remain readable',+ );+ await viewer.screenshot({ path: path.join(artifacts, 'settings-zh-dark.png') });+ await viewer.evaluate(async () => {+ const { themeService } = await import('/themes/theme-service.ts');+ const { cindyLight } = await import('/themes/builtin/cindy-light.ts');+ themeService.applyTheme(cindyLight);+ });+ await viewer.screenshot({ path: path.join(artifacts, 'settings-zh-light.png') });+ assert.equal(+ requests.filter((op) => op === 'start').length,+ 1,+ 'locale updates retain the desktop lease',+ );+ assert.deepEqual(errors, []);console.log(JSON.stringify({video: true,keyboard: true,+ mouse: true,+ controllerPlatform,mediaRecovery: true,+ chineseSettings: true,+ localeKeepsLease: true,lightDarkArtifacts: artifacts,}),);diff --git a/apps/desktop/src/main/remote-desktop/__tests__/captureBoundary.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/captureBoundary.test.tsindex e63bb147f1..5662612c85 100644--- a/apps/desktop/src/main/remote-desktop/__tests__/captureBoundary.test.ts+++ b/apps/desktop/src/main/remote-desktop/__tests__/captureBoundary.test.ts@@ -12,6 +12,8 @@ const h = vi.hoisted(() => ({owner: null as any,dispose: vi.fn(),stop: vi.fn(),+ releaseControl: vi.fn(),+ inputFailure: null as null | (() => void),nativeStop: vi.fn(),nativeFrame: vi.fn(async () => 'frame'),input: vi.fn(),@@ -94,6 +96,7 @@ vi.mock('../controller', () => ({this.stop();}tick() {}+ releaseControl = h.releaseControl;input = h.input;viewHeartbeat = h.viewHeartbeat;},@@ -106,6 +109,9 @@ vi.mock('../nativeCapture', () => ({}));vi.mock('../inputHost', () => ({DesktopInputHost: class {+ constructor(onFailure: () => void) {+ h.inputFailure = onFailure;+ }stop = vi.fn();input = vi.fn();},@@ -158,6 +164,7 @@ beforeEach(() => {h.lease = 'lease';h.dispose.mockClear();h.stop.mockClear();+ h.releaseControl.mockClear();h.nativeStop.mockClear();h.nativeFrame.mockClear();h.input.mockReset();@@ -383,3 +390,9 @@ it('keeps replacement capture and its in-flight ICE exchange when revoked configh.handlers.get(DESKTOP_LOCAL.REPLY)(event(), exchange.id, reply);await expect(ice).resolves.toEqual(reply);});+it('routes native input failure to control release rather than capture teardown', () => {+ h.inputFailure?.();+ expect(h.releaseControl).toHaveBeenCalledOnce();+ expect(h.stop).not.toHaveBeenCalled();+ expect(h.dispose).not.toHaveBeenCalled();+});diff --git a/apps/desktop/src/main/remote-desktop/__tests__/controller.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/controller.test.tsindex 24ce5aba52..54bcde2c49 100644--- a/apps/desktop/src/main/remote-desktop/__tests__/controller.test.ts+++ b/apps/desktop/src/main/remote-desktop/__tests__/controller.test.ts@@ -40,6 +40,56 @@ function harness() {};}describe('remote desktop authority and lifecycle', () => {+ it('keeps viewing and peer isolation after native input fails, and allows explicit control recovery', async () => {+ const h = harness(),+ lease = await h.start();+ await h.controller.request('phone', { op: 'control', lease: lease.lease, enabled: true });+ h.controller.releaseControl();+ expect(h.controller.state).toEqual({ peer: 'phone', controlling: false });+ expect(h.deps.stopInput).toHaveBeenCalledOnce();+ expect(h.deps.stopVideo).not.toHaveBeenCalled();+ await expect(+ h.controller.request('phone', { op: 'heartbeat', lease: lease.lease }),+ ).resolves.toEqual({ controlling: false });+ await expect(+ h.controller.request('phone', { op: 'frame', lease: lease.lease }),+ ).resolves.toEqual({ jpeg: 'jpeg' });+ await expect(h.controller.request('other', { op: 'start', displayId: '1' })).rejects.toThrow(+ 'DESKTOP_BUSY',+ );+ await expect(+ h.controller.request('phone', {+ op: 'input',+ lease: lease.lease,+ sequence: 1,+ events: [{ kind: 'move', x: 0.5, y: 0.5 }],+ }),+ ).rejects.toThrow('DESKTOP_VIEW_ONLY');+ await expect(+ h.controller.request('phone', { op: 'control', lease: lease.lease, enabled: true }),+ ).resolves.toEqual({ controlling: true });+ expect(h.deps.stopVideo).not.toHaveBeenCalled();+ });+ it('does not grant control after the native helper fails during startup', async () => {+ const h = harness(),+ lease = await h.start();+ let ready!: () => void;+ h.deps.startInput = () =>+ new Promise<void>((resolve) => {+ ready = resolve;+ });+ const starting = h.controller.request('phone', {+ op: 'control',+ lease: lease.lease,+ enabled: true,+ });+ h.controller.releaseControl();+ ready();+ await expect(starting).rejects.toThrow();+ expect(h.controller.state).toEqual({ peer: 'phone', controlling: false });+ expect(h.deps.stopVideo).not.toHaveBeenCalled();+ });+it('locks only on explicit owner exit and blocks takeover until lock completes', async () => {const h = harness(), first = await h.start();let finish!: () => void;diff --git a/apps/desktop/src/main/remote-desktop/controller.ts b/apps/desktop/src/main/remote-desktop/controller.tsindex e53e55dee9..7e07a7a4b1 100644--- a/apps/desktop/src/main/remote-desktop/controller.ts+++ b/apps/desktop/src/main/remote-desktop/controller.ts@@ -133,6 +133,18 @@ export class RemoteDesktopController {this.deps.stopVideo();this.deps.changed();}++ /** A refused native input revokes control, while preserving viewing and the+ * peer-bound lease. Pending grants must not turn a failed helper back on. */+ releaseControl(): void {+ const active = this.active;+ if (!active || (!active.controlling && !this.inputStarting)) return;+ active.controlling = false;+ this.controlGeneration++;+ this.clipboardTransfer.reset();+ this.deps.stopInput();+ this.deps.changed();+ }/** Explicit local disconnect must not be undone by the phone's recovery. */stopByUser(): void {const target = this.active ?? this.lastEnded;diff --git a/apps/desktop/src/main/remote-desktop/index.ts b/apps/desktop/src/main/remote-desktop/index.tsindex d85e34a292..1aac23e47f 100644--- a/apps/desktop/src/main/remote-desktop/index.ts+++ b/apps/desktop/src/main/remote-desktop/index.ts@@ -121,7 +121,8 @@ let pending: {reject(error: Error): void;timer: ReturnType<typeof setTimeout>;} | null = null;-const input = new DesktopInputHost(() => remoteDesktop.stop());+// Input failure releases native keys and control, without tearing down video.+const input = new DesktopInputHost(() => remoteDesktop.releaseControl());function stopVideo(): void {offerGeneration++;videoAttempt = undefined;diff --git a/apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopViewerWindow.tsx b/apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopViewerWindow.tsxindex 623e05ec47..98c2682b4f 100644--- a/apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopViewerWindow.tsx+++ b/apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopViewerWindow.tsx@@ -15,11 +15,12 @@ import {import type { RemoteDesktopDisplayMode } from '@cindy/device-link';import { WindowControls } from '@/components/title-bar/WindowControls';import { useMacFullscreen } from '@/hooks/useMacFullscreen';+import i18n from '@/i18n';import { DesktopViewerController, type ViewerSnapshot } from './viewerController';/** A clean, standalone remote desktop surface. No App, router, agent or task providers. */export function RemoteDesktopViewerWindow() {- const { t, i18n } = useTranslation();+ const { t } = useTranslation();const { isMac, isFullscreen } = useMacFullscreen();const api = window.electronAPI.remoteDesktopViewer;const root = useRef<HTMLDivElement>(null),@@ -44,6 +45,8 @@ export function RemoteDesktopViewerWindow() {}});const locale = api.onLocale((value) => {+ // useTranslation's i18n wrapper changes with the locale. Keep the+ // connection lifetime independent of that presentation-only update.void i18n.changeLanguage(value);});const blur = () => {@@ -76,7 +79,7 @@ export function RemoteDesktopViewerWindow() {controller.current?.dispose();controller.current = null;};- }, [api, i18n]);+ }, [api]);const clipboard = async (action: 'copy' | 'paste') => {if (clipboardBusy) return;setClipboardBusy(true);diff --git a/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerLocales.test.ts b/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerLocales.test.tsnew file mode 100644index 0000000000..715f8da2b1--- /dev/null+++ b/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerLocales.test.ts@@ -0,0 +1,32 @@+import { describe, expect, it } from 'vitest';+import en from '../../../i18n/locales/en/common.json';+import zhCN from '../../../i18n/locales/zh-CN/common.json';+import zhTW from '../../../i18n/locales/zh-TW/common.json';+import ja from '../../../i18n/locales/ja/common.json';+import ko from '../../../i18n/locales/ko/common.json';++describe('remote desktop settings copy survives file encoding', () => {+ it.each([+ ['en', en, /[A-Za-z]/u],+ ['zh-CN', zhCN, /\p{Script=Han}/u],+ ['zh-TW', zhTW, /\p{Script=Han}/u],+ ['ja', ja, /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u],+ ['ko', ko, /\p{Script=Hangul}/u],+ ] as const)(+ '%s contains readable localized text, not replacement question marks',+ (_locale, catalog, letters) => {+ const entries = {+ ...catalog.remoteDesktop.viewer,+ remoteDisabled: catalog.remoteDesktop.remoteDisabled,+ accessRevoked: catalog.remoteDesktop.accessRevoked,+ };+ expect(Object.keys(catalog.remoteDesktop.viewer)).toEqual(+ Object.keys(en.remoteDesktop.viewer),+ );+ for (const [key, value] of Object.entries(entries)) {+ expect(value, key).not.toMatch(/\?{2,}|\uFFFD/u);+ expect(value, key).toMatch(letters);+ }+ },+ );+});diff --git a/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerWindow.test.tsx b/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerWindow.test.tsxnew file mode 100644index 0000000000..682397fa41--- /dev/null+++ b/apps/desktop/src/renderer/features/remote-desktop/__tests__/viewerWindow.test.tsx@@ -0,0 +1,57 @@+// @vitest-environment jsdom+import { act, cleanup, render, screen } from '@testing-library/react';+import { afterEach, expect, it, vi } from 'vitest';+import i18n from '@/i18n';+import { RemoteDesktopViewerWindow } from '../RemoteDesktopViewerWindow';++const lifecycle = vi.hoisted(() => ({ created: vi.fn(), disposed: vi.fn() }));+vi.mock('../viewerController', () => ({+ DesktopViewerController: class {+ constructor() {+ lifecycle.created();+ }+ dispose = lifecycle.disposed;+ },+}));+vi.mock('@/hooks/useMacFullscreen', () => ({+ useMacFullscreen: () => ({ isMac: true, isFullscreen: false }),+}));+vi.mock('@/components/title-bar/WindowControls', () => ({ WindowControls: () => null }));++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++it('updates translated controls without ending or recreating the viewer connection', async () => {+ await i18n.changeLanguage('en');+ const listeners = new Set<(locale: string) => void>();+ const rendererReady = vi.fn(async () => {});+ Object.assign(window, {+ electronAPI: {+ remoteDesktopViewer: {+ onActive: () => () => {},+ onLocale: (listener: (locale: string) => void) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ state: async () => ({ generation: 1 }),+ rendererReady,+ presentationReady: async () => {},+ },+ },+ });+ const view = render(<RemoteDesktopViewerWindow />);+ expect(lifecycle.created).toHaveBeenCalledOnce();+ await act(async () => {+ for (const listener of [...listeners]) listener('zh-CN');+ });+ expect(screen.getByRole('button', { name: '操作' })).toBeDefined();+ expect(lifecycle.disposed).not.toHaveBeenCalled();+ expect(lifecycle.created).toHaveBeenCalledOnce();+ expect(rendererReady).toHaveBeenCalledOnce();+ expect(listeners.size).toBe(1);+ view.unmount();+ expect(lifecycle.disposed).toHaveBeenCalledOnce();+ expect(listeners.size).toBe(0);+});diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex d10018ac9a..d762b96ed0 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -65,30 +65,30 @@"connectionBusy": "別のデバイスがこのリモートデスクトップに接続しています。そのデバイスでリモートデスクトップを終了してから、もう一度接続してください。","takeoverConnection": "接続を引き継ぐ","connectionBusyTakeover": "別のデバイスが接続中です。接続を引き継ぐと、そのデバイスは切断されます。",- "remoteDisabled": "????????????????????????",- "accessRevoked": "????????????????????????",+ "remoteDisabled": "コンピュータのリモート操作が無効になっています。",+ "accessRevoked": "このコンピュータへのアクセスが取り消されました。","viewer": {- "settings": "??",- "sound": "??",- "fullscreen": "?????",- "exitFullscreen": "????????",- "fps": "???????",- "quality": "??",- "automatic": "??",- "smooth": "????",- "balanced": "????",- "clear": "???",- "resolution": "??????????",- "clipboard": "???????????",- "copy": "??????????????????????",- "paste": "???????????????????",- "clipboardDone": "???????????",- "clipboardFailed": "??????????????????????16,384 ????????????",- "settingsFailed": "????????????????",- "inputHint": "???????????????Ctrl+Alt+Esc ?????????????????Cmd/Ctrl+W ??????????????",- "resolutionHint": "???????????????????????????",- "relay": "????",- "direct": "????"+ "settings": "操作",+ "sound": "音声",+ "fullscreen": "全画面表示",+ "exitFullscreen": "全画面表示を終了",+ "fps": "フレームレート",+ "quality": "画質",+ "automatic": "自動",+ "smooth": "スムーズ",+ "balanced": "バランス",+ "clear": "高画質",+ "resolution": "コンピュータの解像度",+ "clipboard": "テキストクリップボード",+ "copy": "リモートのテキストをこのコンピュータにコピー",+ "paste": "ローカルのテキストをリモートに貼り付け",+ "clipboardDone": "テキストを転送しました",+ "clipboardFailed": "テキストを転送できません。操作権限を確認し、16,384 文字以内にしてください。",+ "settingsFailed": "表示設定を変更できませんでした。",+ "inputHint": "画面をクリックして入力します。Ctrl+Alt+Esc でキーボードのフォーカスを解除し、Cmd/Ctrl+W でこのウィンドウを閉じます。",+ "resolutionHint": "解像度の変更はリモートの実際のモニターに反映されます。",+ "relay": "映像中継",+ "direct": "直接接続"}},"ipcError": {diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 88fe0c5023..71de91c1db 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -65,30 +65,30 @@"connectionBusy": "다른 기기가 이 원격 데스크톱에 연결되어 있습니다. 해당 기기에서 원격 데스크톱을 종료한 후 다시 연결하세요.","takeoverConnection": "연결 넘겨받기","connectionBusyTakeover": "다른 기기가 연결되어 있습니다. 연결을 넘겨받으면 해당 기기의 연결이 끊어집니다.",- "remoteDisabled": "????? ?? ??? ?? ????.",- "accessRevoked": "? ???? ?? ?? ??? ???????.",+ "remoteDisabled": "컴퓨터에서 원격 제어가 꺼져 있습니다.",+ "accessRevoked": "이 컴퓨터에 대한 접근 권한이 취소되었습니다.","viewer": {- "settings": "??",- "sound": "??",- "fullscreen": "?? ??",- "exitFullscreen": "?? ?? ??",- "fps": "??? ??",- "quality": "??",- "automatic": "??",- "smooth": "??",- "balanced": "??",- "clear": "??",- "resolution": "??? ???",- "clipboard": "??? ????",- "copy": "?? ???? ? ???? ??",- "paste": "?? ???? ???? ????",- "clipboardDone": "???? ??????",- "clipboardFailed": "???? ??? ? ????. ?? ??? ???? ??? 16,384? ??? ????.",- "settingsFailed": "????? ??? ??? ? ????.",- "inputHint": "??? ???? ?????. Ctrl+Alt+Esc? ??? ???? ???? Cmd/Ctrl+W? ? ?? ????.",- "resolutionHint": "???? ???? ?? ???? ?? ???? ?????.",- "relay": "?? ??",- "direct": "?? ??"+ "settings": "조작",+ "sound": "소리",+ "fullscreen": "전체 화면",+ "exitFullscreen": "전체 화면 종료",+ "fps": "프레임 속도",+ "quality": "화질",+ "automatic": "자동",+ "smooth": "원활",+ "balanced": "균형",+ "clear": "선명",+ "resolution": "컴퓨터 해상도",+ "clipboard": "텍스트 클립보드",+ "copy": "원격 텍스트를 이 컴퓨터에 복사",+ "paste": "로컬 텍스트를 원격으로 붙여넣기",+ "clipboardDone": "텍스트를 전송했습니다",+ "clipboardFailed": "텍스트를 전송할 수 없습니다. 제어 권한을 확인하고 내용을 16,384자 이내로 줄이세요.",+ "settingsFailed": "디스플레이 설정을 변경할 수 없습니다.",+ "inputHint": "화면을 클릭하여 입력하세요. Ctrl+Alt+Esc로 키보드 포커스를 해제하고 Cmd/Ctrl+W로 이 창을 닫습니다.",+ "resolutionHint": "해상도를 변경하면 원격 컴퓨터의 실제 모니터에 적용됩니다.",+ "relay": "영상 중계",+ "direct": "직접 연결"}},"ipcError": {diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 846ca8ba80..546a996d58 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -65,30 +65,30 @@"connectionBusy": "已有其他设备连接此远程桌面。请先在那台设备上退出远程桌面,再尝试连接。","takeoverConnection": "接管连接","connectionBusyTakeover": "已有其他设备连接此远程桌面。接管连接后,上一台设备会断开。",- "remoteDisabled": "???????????",- "accessRevoked": "????????????",+ "remoteDisabled": "电脑端已关闭远程控制。",+ "accessRevoked": "对这台电脑的访问已撤销。","viewer": {- "settings": "??",- "sound": "??",- "fullscreen": "??",- "exitFullscreen": "????",- "fps": "??",- "quality": "??",- "automatic": "??",- "smooth": "??",- "balanced": "??",- "clear": "??",- "resolution": "?????",- "clipboard": "?????",- "copy": "??????????",- "paste": "??????????",- "clipboardDone": "?????",- "clipboardFailed": "??????????????????????? 16,384 ???",- "settingsFailed": "?????????",- "inputHint": "?????????Ctrl+Alt+Esc ???????Cmd/Ctrl+W ???????",- "resolutionHint": "?????????????????",- "relay": "????",- "direct": "??"+ "settings": "操作",+ "sound": "声音",+ "fullscreen": "全屏",+ "exitFullscreen": "退出全屏",+ "fps": "帧率",+ "quality": "画质",+ "automatic": "自动",+ "smooth": "流畅",+ "balanced": "均衡",+ "clear": "清晰",+ "resolution": "电脑分辨率",+ "clipboard": "文字剪贴板",+ "copy": "把远端文字复制到本机",+ "paste": "把本机文字粘贴到远端",+ "clipboardDone": "文字已传输",+ "clipboardFailed": "文字传输失败,请确认已取得控制权,且内容不超过 16,384 字符。",+ "settingsFailed": "未能修改显示设置。",+ "inputHint": "点击画面即可输入。Ctrl+Alt+Esc 释放键盘焦点;Cmd/Ctrl+W 关闭这个窗口。",+ "resolutionHint": "分辨率修改会影响远端的实际显示器。",+ "relay": "视频中转",+ "direct": "直连"}},"ipcError": {diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex f151c69f06..b50b4db39e 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -65,30 +65,30 @@"connectionBusy": "已有其他裝置連線至此遠端桌面。請先在該裝置上退出遠端桌面,再嘗試連線。","takeoverConnection": "接管連線","connectionBusyTakeover": "已有其他裝置連線至此遠端桌面。接管連線後,上一台裝置會中斷。",- "remoteDisabled": "???????????",- "accessRevoked": "?????????????",+ "remoteDisabled": "電腦端已關閉遠端控制。",+ "accessRevoked": "對這台電腦的存取權已撤銷。","viewer": {- "settings": "??",- "sound": "??",- "fullscreen": "???",- "exitFullscreen": "?????",- "fps": "???",- "quality": "??",- "automatic": "??",- "smooth": "??",- "balanced": "??",- "clear": "??",- "resolution": "?????",- "clipboard": "?????",- "copy": "??????????",- "paste": "?????????",- "clipboardDone": "?????",- "clipboardFailed": "??????????????????????? 16,384 ???",- "settingsFailed": "?????????",- "inputHint": "?????????Ctrl+Alt+Esc ???????Cmd/Ctrl+W ???????",- "resolutionHint": "?????????????????",- "relay": "????",- "direct": "????"+ "settings": "操作",+ "sound": "聲音",+ "fullscreen": "全螢幕",+ "exitFullscreen": "結束全螢幕",+ "fps": "影格率",+ "quality": "畫質",+ "automatic": "自動",+ "smooth": "流暢",+ "balanced": "均衡",+ "clear": "清晰",+ "resolution": "電腦解析度",+ "clipboard": "文字剪貼簿",+ "copy": "將遠端文字複製到本機",+ "paste": "將本機文字貼到遠端",+ "clipboardDone": "文字已傳輸",+ "clipboardFailed": "文字傳輸失敗,請確認已取得控制權,且內容不超過 16,384 字元。",+ "settingsFailed": "無法修改顯示設定。",+ "inputHint": "點擊畫面即可輸入。Ctrl+Alt+Esc 釋放鍵盤焦點;Cmd/Ctrl+W 關閉這個視窗。",+ "resolutionHint": "解析度修改會影響遠端的實際顯示器。",+ "relay": "視訊轉送",+ "direct": "直接連線"}},"ipcError": {diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsxindex 1fc62df9b5..6c8dfc9ce8 100644--- a/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx+++ b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx@@ -285,6 +285,19 @@ export default function RemoteDesktopScreen() {(message: object) => webview.current?.postMessage(JSON.stringify(message)),[],);+ const reflectViewOnly = useCallback(+ (current: RemoteDesktopLease) => {+ if (active.current !== current) return;+ current.controlling = false;+ wantsControl.current = false;+ setLease({ ...current });+ send({ type: "control", enabled: false });+ heldKeys.current.clear();+ setModifiers([]);+ setKeyboard(false);+ },+ [send],+ );useEffect(() => {const enabled =keyboard && !fullKeys && focused && Boolean(lease?.controlling);@@ -768,7 +781,12 @@ export default function RemoteDesktopScreen() {)return;heartbeatBusy = current.lease;- void request({ op: "heartbeat", lease: current.lease })+ const wasControlling = current.controlling;+ void viewerSession.current+ .heartbeat()+ .then((result) => {+ if (wasControlling && !result.controlling) reflectViewOnly(current);+ }).catch((cause) => {// A missing reply does not prove renewal failed; the next interval// retries within the lease. Explicit host revocation still stops us.@@ -868,7 +886,7 @@ export default function RemoteDesktopScreen() {clearInterval(metrics);stop();};- }, [request, fail, send, stop, pause]);+ }, [request, fail, send, stop, pause, viewerSession, reflectViewOnly]);useEffect(() => {// Route blur means leaving this desktop (including a native back swipe).// App background/inactive events use pause() without the exit flag.@@ -1067,6 +1085,13 @@ export default function RemoteDesktopScreen() {events: message.events,}).catch((cause) => {+ if (+ cause instanceof Error &&+ cause.message.includes("DESKTOP_VIEW_ONLY")+ ) {+ reflectViewOnly(current);+ return;+ }if (active.current === current) fail(cause);}).finally(() => {diff --git a/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsxindex a282b88a21..d47591be66 100644--- a/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx+++ b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx@@ -381,6 +381,47 @@ const connect = async () => {};describe("remote desktop controls", () => {+ it("keeps the video when a fallback input is rejected because control was released", async () => {+ await connect();+ const original = fixture.invoke.getMockImplementation()!;+ fixture.invoke.mockImplementation((...args) =>+ args[2][0].op === "input"+ ? Promise.reject(new Error("DESKTOP_VIEW_ONLY"))+ : original(...args),+ );+ await act(async () => {+ fixture.message!({+ nativeEvent: {+ data: JSON.stringify({+ type: "input",+ epoch: "lease",+ sequence: 1,+ events: [{ kind: "move", x: 0.5, y: 0.5 }],+ }),+ },+ });+ });+ expect(sent()).toContainEqual({ type: "control", enabled: false });+ expect(requests().filter((r) => r.op === "stop")).toHaveLength(0);+ expect(requests().filter((r) => r.op === "start")).toHaveLength(1);+ });+ it("reflects a host-side input failure as view-only without replacing the video lease", async () => {+ await connect();+ const original = fixture.invoke.getMockImplementation()!;+ fixture.invoke.mockImplementation((...args) =>+ args[2][0].op === "heartbeat"+ ? Promise.resolve({ controlling: false })+ : original(...args),+ );+ await act(async () => vi.advanceTimersByTimeAsync(3100));+ expect(+ fixture.post.mock.calls.map(([json]) => JSON.parse(json)),+ ).toContainEqual({ type: "control", enabled: false });+ expect(requests().filter((r) => r.op === "start")).toHaveLength(1);+ expect(requests().filter((r) => r.op === "stop")).toHaveLength(0);+ act(() => button("operations").click());+ expect(visibleInputHint()).toBe("remoteDesktop.viewOnlyHint");+ });it("keeps iOS data detection disabled without passing its prop to Android", async () => {await act(async () => {});expect(fixture.webViewProps).toMatchObject({ dataDetectorTypes: "none" });diff --git a/docs/design-rules/design-inventory.md b/docs/design-rules/design-inventory.mdindex 2e4b2fd7db..20105e30cd 100644--- a/docs/design-rules/design-inventory.md+++ b/docs/design-rules/design-inventory.md@@ -9,7 +9,7 @@本区块由 `scripts/design-inventory.mjs` 生成,请勿手改。重新生成:`pnpm design:inventory`;校验:`pnpm check:design-inventory`。-计数快照日期:2026-09-11。生成命令:`pnpm design:inventory`。裸颜色匹配与 `scripts/hardcoded-color-audit.mjs` 共用 `scripts/shared/hardcoded-color-match.mjs`(HEX / RGB / HSL / OKLCH 等字面通道),两者在共享 matcher 内统一排除纯语义包装、注释及 PR 编号;数值颜色函数还需位于样式属性、CSS 声明/函数或任意值语境,普通文案字符串里的颜色函数文本不计入;字面 fallback 仍计入——语义 token 消费与注释引用不是迁移债务;裸圆角为粗粒度(`rounded*` class、`border-radius:` 与 React style 对象的 `borderRadius:`)。Token 计数为样式源里 `var(--token)` / `hsl(var(--token)` 的去重 ID 数;Mobile 的 ThemeColors / typeScale 等 RN 属性不计入此列,不能将 0 解释为未使用 Token。+计数快照日期:2026-09-12。生成命令:`pnpm design:inventory`。裸颜色匹配与 `scripts/hardcoded-color-audit.mjs` 共用 `scripts/shared/hardcoded-color-match.mjs`(HEX / RGB / HSL / OKLCH 等字面通道),两者在共享 matcher 内统一排除纯语义包装、注释及 PR 编号;数值颜色函数还需位于样式属性、CSS 声明/函数或任意值语境,普通文案字符串里的颜色函数文本不计入;字面 fallback 仍计入——语义 token 消费与注释引用不是迁移债务;裸圆角为粗粒度(`rounded*` class、`border-radius:` 与 React style 对象的 `borderRadius:`)。Token 计数为样式源里 `var(--token)` / `hsl(var(--token)` 的去重 ID 数;Mobile 的 ThemeColors / typeScale 等 RN 属性不计入此列,不能将 0 解释为未使用 Token。登记 surface 数:50。平台包含 Desktop 与 Mobile;静态入口发现不表示已迁移或已实机验证。diff --git a/packages/device-link/src/__tests__/remoteDesktopViewerSession.test.ts b/packages/device-link/src/__tests__/remoteDesktopViewerSession.test.tsindex 3cc03331b7..b53455bf9a 100644--- a/packages/device-link/src/__tests__/remoteDesktopViewerSession.test.ts+++ b/packages/device-link/src/__tests__/remoteDesktopViewerSession.test.ts@@ -36,3 +36,11 @@ it('stop cancels a pending start and cleans up the returned lease without reopenfinish({lease:'late'});await expect(connection).rejects.toThrow('DESKTOP_VIDEO_STOPPED');expect(f.request.mock.calls.at(-1)?.[0]).toEqual({op:'stop',lease:'late'});});++it("keeps confirmed control when an older heartbeat omits its projection", async () => {+ const f = fixture();+ await f.session.connect({ isCurrent: () => true });+ await f.session.control(true);+ f.request.mockResolvedValueOnce({});+ expect(await f.session.heartbeat()).toEqual({ controlling: true });+});diff --git a/packages/device-link/src/remoteDesktopViewerSession.ts b/packages/device-link/src/remoteDesktopViewerSession.tsindex 0e4d021de4..7449415198 100644--- a/packages/device-link/src/remoteDesktopViewerSession.ts+++ b/packages/device-link/src/remoteDesktopViewerSession.ts@@ -108,6 +108,10 @@ export class RemoteDesktopViewerSession {lease: lease.lease,});if (this.active !== lease) throw new Error("DESKTOP_LEASE_EXPIRED");+ // Older/malformed heartbeats without a control projection are not evidence+ // that the host revoked control. Preserve the last confirmed state.+ if (!result || typeof result.controlling !== "boolean")+ return { controlling: lease.controlling };// A heartbeat sent before a control transition cannot acknowledge that transition.if (!pendingAtStart &&