From bb5586ceb40b9b438ef3ff417a6655f32d6bf9a8 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 14:46:10 +0800 Subject: [PATCH] feat(cua): unify explicit system input and keyboard modifiers --- .../cua-system-input/guide.i18n.yaml | 16 +++ .../v0.2.2-rc.4/cua-system-input/guide.md | 20 ++++ .../v0.2.2-rc.4/cua-system-input/guide.zh.md | 20 ++++ .../experimental/cua-macos/README.i18n.yaml | 12 +- packages/experimental/cua-macos/README.md | 30 ++--- packages/experimental/cua-macos/README.zh.md | 30 ++--- .../cua-macos/native/README.i18n.yaml | 4 +- .../experimental/cua-macos/native/README.md | 8 +- .../cua-macos/native/README.zh.md | 8 +- .../native/Sources/CuaNative/AXWorker.swift | 25 ++-- .../native/Sources/CuaNative/HeldKeys.swift | 41 ++++--- .../Sources/CuaNative/KeyboardInput.swift | 46 ++++--- .../CuaNative/NativeProtocol.generated.swift | 12 +- .../CuaNative/RequestCoordinator.swift | 2 +- .../CuaNative/SystemKeyboardInput.swift | 71 +++++++++++ .../CuaNative/SystemPointerInput.swift | 6 +- .../CuaNative/WindowPointerInput.swift | 97 ++++++++------- .../cua-macos/native/generate-protocol.ts | 12 +- .../cua-macos/native/protocol.schema.json | 20 +++- .../native/tests/capabilities_e2e.py | 6 +- .../cua-macos/native/tests/e2e.py | 6 +- .../cua-macos/native/tests/electron_e2e.py | 6 +- .../native/tests/swift/SystemInputTests.swift | 85 +++++++++++++ .../cua-macos/native/upstream.json | 1 + .../experimental/cua-macos/src/guidance.ts | 17 ++- packages/experimental/cua-macos/src/index.ts | 2 +- .../cua-macos/tests/guidance.spec.ts | 34 +++--- .../tests/provider-lifecycle.spec.ts | 113 ++++++++++-------- .../experimental/cua-windows/README.i18n.yaml | 4 +- packages/experimental/cua-windows/README.md | 2 +- .../experimental/cua-windows/README.zh.md | 2 +- .../tests/loader-composition.spec.ts | 8 +- packages/experimental/cua/README.i18n.yaml | 8 +- packages/experimental/cua/README.md | 4 +- packages/experimental/cua/README.zh.md | 4 +- packages/experimental/cua/src/api.ts | 41 ++++--- packages/experimental/cua/src/config.ts | 2 +- packages/experimental/cua/src/guidance.ts | 21 +++- packages/experimental/cua/src/index.ts | 35 +++--- .../cua/src/mouse-control-locales.ts | 36 +++--- .../experimental/cua/src/mouse-control.ts | 32 ++--- packages/experimental/cua/src/protocol.ts | 35 +++--- packages/experimental/cua/src/types.ts | 33 +++-- packages/experimental/cua/tests/api.spec.ts | 41 +++++-- .../experimental/cua/tests/bridge.spec.ts | 2 +- .../experimental/cua/tests/protocol.spec.ts | 53 +++++--- 46 files changed, 730 insertions(+), 383 deletions(-) create mode 100644 docs/upgrade-guide/v0.2.2-rc.4/cua-system-input/guide.i18n.yaml create mode 100644 docs/upgrade-guide/v0.2.2-rc.4/cua-system-input/guide.md create mode 100644 docs/upgrade-guide/v0.2.2-rc.4/cua-system-input/guide.zh.md create mode 100644 packages/experimental/cua-macos/native/Sources/CuaNative/SystemKeyboardInput.swift create mode 100644 packages/experimental/cua-macos/native/tests/swift/SystemInputTests.swift diff --git a/docs/upgrade-guide/v0.2.2-rc.4/cua-system-input/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.4/cua-system-input/guide.i18n.yaml new file mode 100644 index 0000000000..6ce6a5d853 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.4/cua-system-input/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.4/cua-system-input/guide.md +/: + en: 39fcfff9cc98c5e9 + zh: 82855b6048375073 +/cua-system-input: + en: bedd1969d941db13 + zh: 3e5dd506f714c939 +/cua-system-input/change: + en: fc523d57007444b0 + zh: f812932a855f82b0 +/cua-system-input/migration: + en: 048ac9864ca1fe5b + zh: 3dc6798701563cd8 diff --git a/docs/upgrade-guide/v0.2.2-rc.4/cua-system-input/guide.md b/docs/upgrade-guide/v0.2.2-rc.4/cua-system-input/guide.md new file mode 100644 index 0000000000..9f73e8dad1 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.4/cua-system-input/guide.md @@ -0,0 +1,20 @@ +--- +kind: upgrade-guide +description: "CUA system input replaces the system-pointer option and approval setting." +--- + +# CUA system input + +English | [中文](guide.zh.md) + +## Change + +CUA replaces `useSystemPointer` with `useSystemInput`, the `systemPointer` capability with `systemInput`, and `requireSystemPointerApproval` with `requireSystemInputApproval`. macOS supports the option on `mouseMove`, `toggleMouse`, `click`, `drag`, `pressKey`, and `sendKeyEvent`. Explicit system clicks and drags send keyboard modifier down and up events as well as mouse events. Omitted or false retains the default input route. Windows does not expose this capability yet. + +System-input approval now covers keyboard and mouse operations. Errors use `SYSTEM_INPUT_*` and `SYSTEM_INPUT_APPROVAL_*` instead of `MOUSE_CONTROL_*` and `MOUSE_APPROVAL_*`. + +## Migration + +1. Replace `useSystemPointer` with `useSystemInput` in CUA programs and raw requests. Keep matching options on directional down and up calls. Pass keyboard options as the third argument of `pressKey(key, modifiers, options)` or `sendKeyEvent(key, direction, options)`. +2. Rename `requireSystemPointerApproval` in profile or home patches to `requireSystemInputApproval`, and update capability checks to `systemInput`. Update error-code handling to the new prefixes. +3. Rebuild or upgrade the macOS helper with the Host. Confirm `cua.getCapabilities().systemInput` before selecting system input, activate and observe the target, then verify a modified click or keystroke and inspect its result. `typeText`, `paste`, `scroll`, and AX methods do not accept this option. diff --git a/docs/upgrade-guide/v0.2.2-rc.4/cua-system-input/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.4/cua-system-input/guide.zh.md new file mode 100644 index 0000000000..be76af4966 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.4/cua-system-input/guide.zh.md @@ -0,0 +1,20 @@ +--- +kind: upgrade-guide +description: "CUA 系统输入选项取代系统指针选项和授权配置。" +--- + +# CUA 系统输入 + +[English](guide.md) | 中文 + +## 变更 + +CUA 将 `useSystemPointer` 改为 `useSystemInput`,能力字段 `systemPointer` 改为 `systemInput`,配置项 `requireSystemPointerApproval` 改为 `requireSystemInputApproval`。macOS 的 `mouseMove`、`toggleMouse`、`click`、`drag`、`pressKey` 和 `sendKeyEvent` 支持此选项。显式系统点击和拖动同时发送鼠标事件及键盘修饰键的按下、松开事件。省略或传 `false` 保留默认输入方式。Windows 暂不开放此能力。 + +系统输入授权覆盖键盘和鼠标操作。错误码由 `MOUSE_CONTROL_*`、`MOUSE_APPROVAL_*` 改为 `SYSTEM_INPUT_*`、`SYSTEM_INPUT_APPROVAL_*`。 + +## 迁移 + +1. 将 CUA 程序和原始请求中的 `useSystemPointer` 替换为 `useSystemInput`。单独按下和松开时使用相同选项。键盘选项放在 `pressKey(key, modifiers, options)` 或 `sendKeyEvent(key, direction, options)` 的第三个参数。 +2. 将 profile 或 home patch 中的 `requireSystemPointerApproval` 改为 `requireSystemInputApproval`,能力检查改为 `systemInput`,并更新错误码前缀。 +3. 随 Host 一起重建或升级 macOS helper。选择系统输入前确认 `cua.getCapabilities().systemInput`,激活并观察目标,验证一次带修饰键的点击或按键并检查结果。`typeText`、`paste`、`scroll` 和 AX 方法不接受此选项。 diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index 607de4a959..1866c8efbe 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -15,11 +15,11 @@ en: 1777e7bf6785f986 zh: e3daac1074ebb74d /deepseek-ai-dsh-cua-macos/use-this-package: - en: f94dc9734a47325d - zh: 4085438218993e49 + en: a211a5d7408e8a06 + zh: e11876bb9ecf8198 /deepseek-ai-dsh-cua-macos/use-this-package/connect-an-external-execution-environment: - en: 847dafcf9ca05915 - zh: 6452dcb41b43d014 + en: 6097d7d03bc8dfad + zh: 0978077447118d64 /deepseek-ai-dsh-cua-macos/understand-the-implementation: en: d441fbe64f97ddd9 zh: 821af0f6ac8bb225 @@ -45,8 +45,8 @@ en: a2c9acb5a4320dda zh: e8d1586af60215c4 /deepseek-ai-dsh-cua-macos/known-limitations-and-deferred-work: - en: b93e0a9ed7732fc4 - zh: a29e95a99132269e + en: 1eb68c7f89cacead + zh: 2eb624f5e468a763 /deepseek-ai-dsh-cua-macos/known-limitations-and-deferred-work/dev-note: en: b836f01bd0bceb4a zh: 8122fa08b2aa95fa diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index d076664d1d..92d9364c5c 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -62,7 +62,7 @@ Source builds default to `sourceSigning: ad-hoc`, without creating certificates | `screenshotTarget` | unset | Fixed `{ longEdge, maxBytes }` request-image target for screenshots. Unset resolves the target from the Agent's model route and refuses capture when that route declares no image input. | | `allowedApps` | `[]` | Legacy path/signature grants, imported once for removal; they do not authorize new bundle-ID identities. | | `helperPath` | package-owned executable | Absolute executable inside the signed helper `.app`; a bare binary fails with `NATIVE_APPLICATION_REQUIRED`. | -| `requireSystemPointerApproval` | `true` | Ask once per session before an explicitly requested system mouse move, drag, or button event. | +| `requireSystemInputApproval` | `true` | Ask once per session before an explicitly requested system mouse move, drag, or button event. | | `sourceSigning` | `ad-hoc` | Source signing: `ad-hoc`, or `{ identity, keychain }` for an existing certificate and keychain path. Ignored for installed packages and `helperPath`. | | `buildTimeoutMs` | `300000` | Maximum native preparation time. | | `timeoutMs` | `30000` | Per-operation deadline; cancellation can leave partial input. | @@ -121,11 +121,13 @@ Use the `cua` API to discover and select the application (`listApps`, `getState` `getWindow` sends no native request; screenshots and pointer input reject a closed or foreign window. Read `getAccessibilityTree()` explicitly before element operations. Screenshots do not require a successful AX read. All coordinate input, including relative coordinates, requires a successful AX observation covering the window or a screenshot; absolute pixel coordinates require a delivered screenshot. An owned window without an AX surface returns an empty snapshot only when window and sheet discovery completes without unreadable elements. Within one API instance, the facade keeps one current accessibility snapshot per application handle, shared by every app and window object for that handle, including repeated selections. Reading any window replaces that snapshot; element operations use the latest snapshot ID, so use IDs from the latest tree and do not assume an older ID still identifies the same control. Local invalid AX nodes return a successful partial snapshot with explicit unavailable-branch markers; raw state includes `hasUnreadableElements: true`. These branches have no element IDs and unknown contents; inspect them with a screenshot. Fatal observation errors publish no snapshot. See the [native observation and error semantics](native/README.md#observation-and-input) before handling errors; do not repeat preceding input automatically. Window objects own screenshots and pointer input. Keyboard methods stay on `app` because input follows the app’s current focus. -Ordinary `mouseMove(target)` defaults to AX hover. Without both `AXShowAlternateUI` and `AXShowDefaultUI` on an enabled target or ancestor, it returns `HOVER_UNAVAILABLE` without prompting. Only when the task requires physical movement should the main task call `win.mouseMove(target, { useSystemPointer: true })`. On approval the Host rechecks the window and point and dispatches this move. Pass `useSystemPointer: true` on every physical move. Later explicit moves reuse the decision until the session closes or DSH restarts. Omitting the option or passing `false` uses AX. Refusal sends no input. +Ordinary `mouseMove(target)` defaults to AX hover. Without both `AXShowAlternateUI` and `AXShowDefaultUI` on an enabled target or ancestor, it returns `HOVER_UNAVAILABLE` without prompting. Only when the task requires physical movement should the main task call `win.mouseMove(target, { useSystemInput: true })`. On approval the Host rechecks the window and point and dispatches this move. Pass `useSystemInput: true` on every physical move. Later explicit moves reuse the decision until the session closes or DSH restarts. Omitting the option or passing `false` uses AX. Refusal sends no input. -`win.toggleMouse(button, direction)` sends a window event at the current cursor by default. A press must hit the selected foreground window or it returns `FOREGROUND_REQUIRED`. A release can reach that window after the cursor leaves or focus changes. For a control that reads system button state, pass `{ useSystemPointer: true }` on both press and release. This shares the drag approval. Moving the mouse while the button is held can drag items. The end of the turn or connection releases an outstanding system button. +`win.toggleMouse(button, direction)` sends a window event at the current cursor by default. A press must hit the selected foreground window or it returns `FOREGROUND_REQUIRED`. A release can reach that window after the cursor leaves or focus changes. For a control that reads system button state, pass `{ useSystemInput: true }` on both press and release. This shares the drag approval. Moving the mouse while the button is held can drag items. The end of the turn or connection releases an outstanding system button. -By default, drag posts mouse events to the target window. For controls that need system button state, use `win.drag(from, to, { useSystemPointer: true })`. This shares the session permission for system-pointer moves. The start and path must hit the foreground window. Cancellation or loss of the target releases the button at the last posted point. +By default, drag posts mouse events to the target window. For controls that need system button state, use `win.drag(from, to, { useSystemInput: true })`. This shares the session permission for system-pointer moves. The start and path must hit the foreground window. Cancellation or loss of the target releases the button at the last posted point. + +`useSystemInput` selects the route for one `mouseMove`, `toggleMouse`, `click`, `drag`, `pressKey`, or `sendKeyEvent`. Omitted or false keeps accessibility or process-directed input. True uses the system keyboard and mouse queue and requires the selected foreground app; system pointer actions also check an unobscured target window. System clicks and drags press requested keyboard modifiers, dispatch the mouse gesture, then release the mouse before releasing modifiers in reverse order, including on cancellation. Already-held system keys return `INPUT_BUSY` and are not released by a new operation. `pressKey` takes options as its third argument; `sendKeyEvent` down and up must select the same route, and up can release after focus changes. `typeText`, `paste`, `scroll`, and AX actions retain their fixed routes. `paste(text, { format: "text" | "html" })` temporarily publishes the requested clipboard format and invokes the application’s enabled standard Paste menu command. It keeps the temporary format until a pasteboard reader requests its data, then restores every captured original format while it still owns the clipboard, preserving a later copy. Paste operations share a cross-process lock and cancellation joins helper cleanup. A forced process exit can prevent restoration. Unsupported Paste commands fail without typing fallback; `typeText` remains separate key-event input. @@ -197,7 +199,7 @@ Signatures show resolved return values after await. ActionResult = { dispatched: Supported modifier names depend on the platform and the operation; see the platform guidance. Setup and discovery: -- cua.getCapabilities() -> { platform: string, permissions: { accessibility: boolean, screenRecording: boolean }, appLevelAccessibility: boolean, systemPointer: boolean, keyboard: ('app' | 'window')[], sessionLocked: boolean | null, methods: string[], coordinateSpace: 'screenshot-pixels', browser: false } — inspect reported permissions, sessionLocked, methods, and keyboard scopes without requesting permissions. +- cua.getCapabilities() -> { platform: string, permissions: { accessibility: boolean, screenRecording: boolean }, appLevelAccessibility: boolean, systemInput: boolean, keyboard: ('app' | 'window')[], sessionLocked: boolean | null, methods: string[], coordinateSpace: 'screenshot-pixels', browser: false } — inspect reported permissions, sessionLocked, methods, and keyboard scopes without requesting permissions. - cua.listApps() -> { id: string, displayName: string, isRunning: boolean, pid?: number }[] — list applications the provider exposes for selection with their current running state; pass the returned id unchanged to cua.getApp. Each row represents one running process. To select one of several instances with the same name or bundle ID, pass String(row.pid) to cua.getApp. - cua.findApps(query: string) -> { id: string, displayName: string, path: string, isRunning: boolean, pid?: number }[] — search installed applications, including stopped matches. Running installation matches include their process ID. Stopped matches have no pid. - cua.getState() -> { apps: { id: string, displayName: string, isRunning: boolean, pid?: number }[], browsers: [] } — summarize the same provider discovery; this is not an accessibility observation. @@ -224,14 +226,14 @@ Use an explicit window for screenshots. - getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. ## Simulated mouse -Leave useSystemPointer unset for ordinary mouseMove, drag, and toggleMouse calls, even after approval. Prefer selectText for a supported text range and ordinary window-directed drag for a draggable control. If the effect is unclear, inspect the window before choosing another action. Request the system pointer only when the user explicitly asks for it or the intended effect requires it. +Leave useSystemInput unset for ordinary mouseMove, toggleMouse, click, drag, pressKey, and sendKeyEvent calls, even after approval. Prefer selectText for a supported text range and ordinary window-directed drag for a draggable control. If the effect is unclear, inspect the window before choosing another action. Request system input only when the user explicitly asks for it or the intended effect requires it. Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. -- mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemPointer?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemPointer omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemPointer?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemPointer: true on both down and up. Physical moves can then drag, including your own mouse movements. The turn ending or the connection closing releases a remaining system hold. -- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying. +- mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemInput?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemInput omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemInput: true on both down and up. Physical moves can then drag, including your own mouse movements. The turn ending or the connection closing releases a remaining system hold. +- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean, useSystemInput?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. With useSystemInput: true, the system pointer moves to the target and keyboard modifiers are pressed around the click, including release on cancellation. Verify the expected effect before typing or retrying. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. -- drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemPointer?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control. An explicit system drag shares the session decision with mouseMove and holds the chosen button along the path in the unobscured foreground window. +- drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemInput?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemInput or passing false directs the drag to the window without asking for mouse control. System input requires an unobscured foreground target, presses the requested keyboard modifiers, and releases the mouse button before those modifiers, including on cancellation. A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current AX observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. FOREGROUND_REQUIRED means explain the need, then explicitly activate the target and observe again; activation is never automatic. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry. @@ -239,14 +241,14 @@ A string target is an element id; coordinate targets are [x, y] and are pixels i Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. -- pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +- pressKey(key: string, modifiers?: Modifier[], options?: { useSystemInput?: boolean }) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. System input requires the selected foreground application and sends modifiers and the main key through the system keyboard queue, then releases them in reverse order. +- sendKeyEvent(key: string, direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. System input requires the selected app in the foreground for down; match useSystemInput on up, which releases the held key even after focus changes. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. -Only if the task cannot be completed without moving the user’s pointer, call await win.mouseMove(target, { useSystemPointer: true }). Prefer an advertised accessibility action, a click on a visible control, or browser tools when possible. The question interrupts the user. When approval is disabled an explicit move can act immediately. Pass true on every physical move, even after approval. Omitting the option or passing false uses the default hover route without prompting. Approval or refusal lasts until this session closes or DSH restarts. A refusal sends no input. If the user dismisses the request, ask again only if they request it. Wait for an outstanding request to finish. Subagents cannot request system mouse control. +Pass useSystemInput: true only when the task requires system keyboard or mouse input. Omitting the option or passing false uses the provider default. The first explicit system input requests permission; approval or refusal lasts until this session closes or DSH restarts. Approval does not change later calls: pass true on each system operation. If the user dismisses the request, ask again only if they request it. Wait for an outstanding request to finish. Subagents cannot request system input. ``` #### Token effect @@ -272,7 +274,7 @@ The queue orders individual native requests. Holding an app object does not rese - Element IDs belong to the application's current accessibility snapshot; a later read replaces them. Screenshots and pointer input require an explicit window object. - Coordinates use the returned screenshot pixels, including the title bar; `relative: true` selects integers from 0 to 999. Native point conversion is Host-owned. Window movement, application changes and other desktop users can race observations and input. - macOS Stage Manager can reduce background window bounds and screenshots to thumbnails. Full-window observation and coordinate input in this state are not guaranteed; model guidance requires explaining foreground needs and avoiding repeated focus reclamation. -- System drag checks the selected window at every movement. An input-receiving popup can interrupt the gesture even in the same application. Window checks and event delivery add to the requested movement duration. Modifiers are carried on mouse events. Applications that poll system keyboard state may ignore them. +- System drag checks the selected window at every movement. An input-receiving popup can interrupt the gesture even in the same application. Window checks and event delivery add to the requested movement duration. The default route carries modifiers only on mouse events, which applications polling system keyboard state may ignore; `useSystemInput: true` sends system keyboard down and up events. - Background input depends on private SkyLight symbols; macOS updates can make them unavailable. Validate each target OS version. - Observed failures include dispatched Unicode text not appearing in Blender and background Command+A not selecting all text in AppKit. Inspect application state after input; a successful tool result confirms dispatch only. - Source builds default to `ad-hoc` and can require new grants after binary changes. The [developer’s fixed identity](../../../.agents/skills/dsh-cua-macos-signing/SKILL.md) lives outside DSH home; deleting DSH home removes its selection, not the certificate or private key. Release distribution needs a stable Developer ID signature and notarization; the build command accepts `--identity`, and installed packages preserve the distributed signature. The [permission page](../cua/README.md) offers helper authorization and target-application revocation. diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index a38566d646..c5b50b0c82 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -62,7 +62,7 @@ pnpm dsh headless --patch packages/experimental/cua-macos/examples/macos.cordis. | `screenshotTarget` | 未设置 | 截图使用的固定 `{ longEdge, maxBytes }` 请求图片目标。未设置时按 Agent 的模型路由解析,该路由未声明图片输入时拒绝截图。 | | `allowedApps` | `[]` | 旧路径和签名许可,只导入 profile 存储一次供撤销,不授予新 Bundle ID 身份访问权限。 | | `helperPath` | 包内可执行文件 | 已签名 helper `.app` 内可执行文件的绝对路径;裸二进制会触发 `NATIVE_APPLICATION_REQUIRED`。 | -| `requireSystemPointerApproval` | `true` | 主任务首次请求移动系统指针、拖动或操作系统鼠标键时询问用户。 | +| `requireSystemInputApproval` | `true` | 主任务首次请求系统键盘或鼠标输入时询问用户。 | | `sourceSigning` | `ad-hoc` | 源码签名:`ad-hoc` 临时签名,或 `{ identity, keychain }` 指定已有证书及钥匙串路径。安装版和 `helperPath` 忽略此项。 | | `buildTimeoutMs` | `300000` | 原生组件准备的最长时间。 | | `timeoutMs` | `30000` | 单次操作截止时间,取消后可能已发生部分输入。 | @@ -121,11 +121,13 @@ inspect(await window.getScreenshot()) `getWindow` 不发送原生请求;截图和指针输入会拒绝已关闭或属于其他应用的窗口。元素操作前须显式读取 `getAccessibilityTree()`。截图不要求 AX 读取成功。所有坐标输入(包括相对坐标)都要求先成功读取覆盖该窗口的 AX 或取得截图;绝对像素坐标要求已交付的截图。仅当窗口和 sheet 发现过程未遇到不可读元素时,已确认归属但没有 AX 界面的窗口才返回空快照。在单个 API 实例内,门面按应用句柄保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享它,包括重复选择。读取任一窗口都会替换该快照;元素操作使用最新快照 ID,因此应使用最新树中的元素 ID,不应假定旧 ID 仍指向同一控件。局部 AX 节点失效时会成功返回带明确不可用分支标记的部分快照;原始状态包含 `hasUnreadableElements: true`。这些分支没有元素 ID,内容未知,应通过截图查看。致命观察错误不发布快照。处理错误前请参阅[原生观察与错误语义](native/README.zh.md#observation-and-input);不要自动重复此前的输入。窗口对象负责截图和指针输入。键盘方法保留在 `app` 上,因为输入跟随应用的当前焦点。 -普通 `mouseMove(target)` 默认通过辅助功能悬停。如果目标或其祖先没有同时声明 `AXShowAlternateUI` 和 `AXShowDefaultUI`,则返回 `HOVER_UNAVAILABLE`,不会弹窗。只有任务确实需要移动用户的鼠标时,主任务才调用 `win.mouseMove(target, { useSystemPointer: true })`。用户允许后,Host 重新检查窗口和目标位置,再执行本次移动。每次移动系统指针都要显式传 `useSystemPointer: true`。省略参数或传 `false` 时使用辅助功能悬停。拒绝时不派发输入。会话记住此次选择,直到关闭会话或重启 DSH。 +普通 `mouseMove(target)` 默认通过辅助功能悬停。如果目标或其祖先没有同时声明 `AXShowAlternateUI` 和 `AXShowDefaultUI`,则返回 `HOVER_UNAVAILABLE`,不会弹窗。只有任务确实需要移动用户的鼠标时,主任务才调用 `win.mouseMove(target, { useSystemInput: true })`。用户允许后,Host 重新检查窗口和目标位置,再执行本次移动。每次移动系统指针都要显式传 `useSystemInput: true`。省略参数或传 `false` 时使用辅助功能悬停。拒绝时不派发输入。会话记住此次选择,直到关闭会话或重启 DSH。 -默认情况下,`win.toggleMouse(button, direction)` 在当前指针位置向所选窗口发送事件。按下要求指针命中前台应用的所选窗口,否则返回 `FOREGROUND_REQUIRED`。松开允许指针移出窗口或应用失去焦点。只有控件需要读取系统鼠标键状态时,才在按下和松开时都传 `{ useSystemPointer: true }`。系统模式与拖动共用会话审批,按住期间用户移动鼠标也可能触发拖动。任务回合结束或连接关闭时会松开剩余的系统按键。 +默认情况下,`win.toggleMouse(button, direction)` 在当前指针位置向所选窗口发送事件。按下要求指针命中前台应用的所选窗口,否则返回 `FOREGROUND_REQUIRED`。松开允许指针移出窗口或应用失去焦点。只有控件需要读取系统鼠标键状态时,才在按下和松开时都传 `{ useSystemInput: true }`。系统模式与拖动共用会话审批,按住期间用户移动鼠标也可能触发拖动。任务回合结束或连接关闭时会松开剩余的系统按键。 -默认拖动向目标窗口发送鼠标事件。需要系统鼠标按键状态的控件可使用 `win.drag(from, to, { useSystemPointer: true })`。该操作与系统指针移动共用会话授权,起点和拖动路径必须位于可接收输入的前台窗口内。取消或失去目标窗口时,helper 在最后投递的位置释放鼠标键。 +默认拖动向目标窗口发送鼠标事件。需要系统鼠标按键状态的控件可使用 `win.drag(from, to, { useSystemInput: true })`。该操作与系统指针移动共用会话授权,起点和拖动路径必须位于可接收输入的前台窗口内。取消或失去目标窗口时,helper 在最后投递的位置释放鼠标键。 + +`useSystemInput` 在 `mouseMove`、`toggleMouse`、`click`、`drag`、`pressKey` 和 `sendKeyEvent` 上选择本次输入方式。省略或传 `false` 保留辅助功能或进程定向输入。`true` 使用系统键鼠队列,要求目标应用处于前台;系统鼠标操作还检查目标窗口未被遮挡。系统点击和拖动先按下所需修饰键,再发送鼠标事件,最后先释放鼠标、再反序释放修饰键;取消也执行释放。已按住的系统键返回 `INPUT_BUSY`,不会由新操作释放。`pressKey` 的选项为第三个参数;`sendKeyEvent` 的按下和松开需选择相同输入方式,松开仍可在失焦后完成。`typeText`、`paste`、`scroll` 和 AX 动作保持固定输入方式。 `paste(text, { format: "text" | "html" })` 临时提供指定格式的剪贴板内容,并调用应用已启用的标准 Paste 菜单命令。临时格式保留到剪贴板读取方请求其数据,然后只在仍持有剪贴板时恢复保存的全部原格式,保留期间产生的新复制内容。粘贴操作共用跨进程锁,取消会等待辅助进程清理。强制终止进程可能阻止恢复。应用不支持 Paste 命令时明确失败,不自动改成逐字输入;`typeText` 仍单独提供按键事件输入。 @@ -197,7 +199,7 @@ Signatures show resolved return values after await. ActionResult = { dispatched: Supported modifier names depend on the platform and the operation; see the platform guidance. Setup and discovery: -- cua.getCapabilities() -> { platform: string, permissions: { accessibility: boolean, screenRecording: boolean }, appLevelAccessibility: boolean, systemPointer: boolean, keyboard: ('app' | 'window')[], sessionLocked: boolean | null, methods: string[], coordinateSpace: 'screenshot-pixels', browser: false } — inspect reported permissions, sessionLocked, methods, and keyboard scopes without requesting permissions. +- cua.getCapabilities() -> { platform: string, permissions: { accessibility: boolean, screenRecording: boolean }, appLevelAccessibility: boolean, systemInput: boolean, keyboard: ('app' | 'window')[], sessionLocked: boolean | null, methods: string[], coordinateSpace: 'screenshot-pixels', browser: false } — inspect reported permissions, sessionLocked, methods, and keyboard scopes without requesting permissions. - cua.listApps() -> { id: string, displayName: string, isRunning: boolean, pid?: number }[] — list applications the provider exposes for selection with their current running state; pass the returned id unchanged to cua.getApp. Each row represents one running process. To select one of several instances with the same name or bundle ID, pass String(row.pid) to cua.getApp. - cua.findApps(query: string) -> { id: string, displayName: string, path: string, isRunning: boolean, pid?: number }[] — search installed applications, including stopped matches. Running installation matches include their process ID. Stopped matches have no pid. - cua.getState() -> { apps: { id: string, displayName: string, isRunning: boolean, pid?: number }[], browsers: [] } — summarize the same provider discovery; this is not an accessibility observation. @@ -224,14 +226,14 @@ Use an explicit window for screenshots. - getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. ## Simulated mouse -Leave useSystemPointer unset for ordinary mouseMove, drag, and toggleMouse calls, even after approval. Prefer selectText for a supported text range and ordinary window-directed drag for a draggable control. If the effect is unclear, inspect the window before choosing another action. Request the system pointer only when the user explicitly asks for it or the intended effect requires it. +Leave useSystemInput unset for ordinary mouseMove, toggleMouse, click, drag, pressKey, and sendKeyEvent calls, even after approval. Prefer selectText for a supported text range and ordinary window-directed drag for a draggable control. If the effect is unclear, inspect the window before choosing another action. Request system input only when the user explicitly asks for it or the intended effect requires it. Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. -- mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemPointer?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemPointer omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemPointer?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemPointer: true on both down and up. Physical moves can then drag, including your own mouse movements. The turn ending or the connection closing releases a remaining system hold. -- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying. +- mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemInput?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemInput omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemInput: true on both down and up. Physical moves can then drag, including your own mouse movements. The turn ending or the connection closing releases a remaining system hold. +- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean, useSystemInput?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. With useSystemInput: true, the system pointer moves to the target and keyboard modifiers are pressed around the click, including release on cancellation. Verify the expected effect before typing or retrying. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. -- drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemPointer?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control. An explicit system drag shares the session decision with mouseMove and holds the chosen button along the path in the unobscured foreground window. +- drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemInput?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemInput or passing false directs the drag to the window without asking for mouse control. System input requires an unobscured foreground target, presses the requested keyboard modifiers, and releases the mouse button before those modifiers, including on cancellation. A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current AX observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. FOREGROUND_REQUIRED means explain the need, then explicitly activate the target and observe again; activation is never automatic. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry. @@ -239,14 +241,14 @@ A string target is an element id; coordinate targets are [x, y] and are pixels i Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. -- pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +- pressKey(key: string, modifiers?: Modifier[], options?: { useSystemInput?: boolean }) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. System input requires the selected foreground application and sends modifiers and the main key through the system keyboard queue, then releases them in reverse order. +- sendKeyEvent(key: string, direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. System input requires the selected app in the foreground for down; match useSystemInput on up, which releases the held key even after focus changes. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. -Only if the task cannot be completed without moving the user’s pointer, call await win.mouseMove(target, { useSystemPointer: true }). Prefer an advertised accessibility action, a click on a visible control, or browser tools when possible. The question interrupts the user. When approval is disabled an explicit move can act immediately. Pass true on every physical move, even after approval. Omitting the option or passing false uses the default hover route without prompting. Approval or refusal lasts until this session closes or DSH restarts. A refusal sends no input. If the user dismisses the request, ask again only if they request it. Wait for an outstanding request to finish. Subagents cannot request system mouse control. +Pass useSystemInput: true only when the task requires system keyboard or mouse input. Omitting the option or passing false uses the provider default. The first explicit system input requests permission; approval or refusal lasts until this session closes or DSH restarts. Approval does not change later calls: pass true on each system operation. If the user dismisses the request, ask again only if they request it. Wait for an outstanding request to finish. Subagents cannot request system input. ``` #### Token 影响 @@ -272,7 +274,7 @@ Only if the task cannot be completed without moving the user’s pointer, call a - 元素 ID 只对应用当前的辅助功能快照有效;之后的读取会替换它们。截图和指针输入都要求显式的窗口对象。 - 坐标使用包含标题栏的返回截图像素;`relative: true` 使用 0~999 的整数,由 Host 换算原生 point。窗口移动、应用变化及其他桌面使用者的操作可能与观察和输入交错。 - macOS 台前调度可能将后台窗口的尺寸与截图变为缩略图,当前无法保证这种状态下的完整画面与坐标输入;模型指引要求说明前台需求并避免反复抢回焦点。 -- 系统鼠标拖动的每一步都必须命中所选窗口。同一应用中拦截鼠标的弹窗也会中断手势。检查窗口和投递事件的耗时会计入实际拖动时间。修饰键记录在鼠标事件上。读取系统键盘状态的应用可能无法识别这些修饰键。 +- 系统鼠标拖动的每一步都必须命中所选窗口。同一应用中拦截鼠标的弹窗也会中断手势。检查窗口和投递事件的耗时会计入实际拖动时间。默认路径只在鼠标事件上记录修饰键,读取系统键盘状态的应用可能无法识别;`useSystemInput: true` 会发送系统键盘按下和松开事件。 - 后台输入依赖私有 SkyLight 符号,macOS 升级可能使其不可用,需在目标系统版本验证。 - 实测 Blender Unicode 输入曾出现分派成功但界面未显示文本,后台 AppKit 的 Command+A 曾未选中全文。输入后必须检查应用状态;工具返回成功只表示已分派。 - 源码构建默认使用 `ad-hoc`,二进制变化后可能需要重新授权。[开发者固定身份](../../../.agents/skills/dsh-cua-macos-signing/SKILL.md)保存在 DSH home 之外;删除 DSH home 只删除选择它的配置,不删除证书和私钥。正式分发应以固定 Developer ID 签名并完成公证;构建命令支持 `--identity` 指定签名身份,安装版保留分发时的签名。[权限页面](../cua/README.zh.md)提供 helper 授权入口和目标应用许可撤销。 diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index 0524aac4ce..3c575d7184 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -21,8 +21,8 @@ en: bde8f9131c179da3 zh: bd5886c046505c4c /dsh-cua-native-helper/observation-and-input: - en: 1617d112aab897fe - zh: bb16c199e9559c75 + en: 4821c4e278a5c0bf + zh: 53105c1d7e175a89 /dsh-cua-native-helper/verification: en: 11172b21e8ebf972 zh: dac6787e1e75a88e diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index b50b4bac80..467bdf6b57 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -101,9 +101,9 @@ Input target discovery uses the same range recovery as observation. All recovery Hiding a window does not itself expire its AX snapshot. An inventory refresh can retain the previous screenshot mapping only while the same window ID remains present at the same observed size. An observed size change requires a new screenshot for pixel input; a closed window cannot be targeted. Omission from discovery does not block input to a known ID: ownership, geometry and input checks still apply, and dispatch does not confirm receipt. -Window-directed `toggleMouse` posts one press or release to the selected process at the current pointer. A press must hit the foreground window; a release may be outside. Explicit `useSystemPointer` posts through the HID event tap. The connection that pressed the button can move it with system `mouseMove` on that window or release it through the same window handle. The Host requests release at turn end; disconnect also releases the button. +Window-directed `toggleMouse` posts one press or release to the selected process at the current pointer. A press must hit the foreground window; a release may be outside. Explicit `useSystemInput` posts through the HID event tap. The connection that pressed the button can move it with system `mouseMove` on that window or release it through the same window handle. The Host requests release at turn end; disconnect also releases the button. -Clicks send mouse-down and mouse-up events at the element center or the supplied coordinates. Use `invoke` for the default AX action or `performAction` for a named action. Click, scroll and default drag validate window ownership and bounds, then post to the target PID and window. Each event uses SkyLight when available, otherwise the public PID-targeted API. A posted event is never repeated through the other API. Coordinates are macOS points from the top-left of the entire window, including its title bar. Positive `deltaLinesY` reveals content above; negative reveals below. Positive `deltaLinesX` reveals content left; negative reveals right. Each axis accepts an integer from -10 to 10, and at least one must be nonzero. The helper sends line-unit scroll events directly. Click and drag accept left/right/middle buttons and command/control/option/shift/fn modifiers. Only left clicks support double-click. Drag uses one button press/move/release in one window; callers explicitly supply durationMs (1..5000) and steps (1..240). The movement delay budget is divided with fractional precision across the segments; fixed press/release settling and scheduler latency are additional. An explicit `useSystemPointer: true` drag posts through the HID event tap, checks the foreground window at the start and each movement, and supplies one gesture event number and per-segment deltas. Cancellation releases at the last posted point. +Clicks send mouse-down and mouse-up events at the element center or the supplied coordinates. Use `invoke` for the default AX action or `performAction` for a named action. Click, scroll and default drag validate window ownership and bounds, then post to the target PID and window. Each event uses SkyLight when available, otherwise the public PID-targeted API. A posted event is never repeated through the other API. Coordinates are macOS points from the top-left of the entire window, including its title bar. Positive `deltaLinesY` reveals content above; negative reveals below. Positive `deltaLinesX` reveals content left; negative reveals right. Each axis accepts an integer from -10 to 10, and at least one must be nonzero. The helper sends line-unit scroll events directly. Click and drag accept left/right/middle buttons and command/control/option/shift/fn modifiers. Only left clicks support double-click. Drag uses one button press/move/release in one window; callers explicitly supply durationMs (1..5000) and steps (1..240). The movement delay budget is divided with fractional precision across the segments; fixed press/release settling and scheduler latency are additional. An explicit `useSystemInput: true` drag posts through the HID event tap, checks the foreground window at the start and each movement, and supplies one gesture event number and per-segment deltas. Cancellation releases at the last posted point. `click.holdMs` is an optional nonnegative integer in milliseconds per press; zero adds no hold delay. Each connection supplies `maxClickHoldMs` to bound explicit holds. The diagnostic helper option `--max-click-hold-ms` defaults to 5000. Omission retains ordinary click timing. The complete gesture holds the request scheduler slot; cancellation, timeout and disconnect interrupt the hold and post the pending mouse-up before releasing that slot. Received events remain effective, and forced process termination cannot guarantee cleanup. @@ -131,7 +131,9 @@ Tree observation and action discovery treat a generic AX failure reading one ele `paste` publishes one plain-text or HTML clipboard format, dispatches the application's enabled standard Paste menu command, and waits for a clipboard data request. It then restores the preserved formats only while its ownership marker and change count still match. The Host serializes its pastes across helpers with a file lock. maxClipboardBytes bounds both input and preserved contents; unsupported menus and oversized data fail before dispatch. A later copy is preserved. Cancellation restores owned clipboard data when possible; forced termination cannot guarantee restoration, and a data request does not prove the target completed editing. After dispatch, `pasteReadTimeoutMs` bounds waiting for clipboard consumption. Expiry returns `PASTE_NOT_CONSUMED`, closes the promised data provider, and restores the original clipboard only while still owned. The failure does not prove the app will never process its queued Paste command; inspect the target before deciding whether to retry. -`mouseMove` reveals or restores alternate UI through an enabled element or ancestor advertising both `AXShowAlternateUI` and `AXShowDefaultUI`. Without an AX route it returns `HOVER_UNAVAILABLE` before sending input. The Host resolves the requested route against session approval or the configured exemption before sending `useSystemPointer` to the helper. +`useSystemInput: true` dispatches `pressKey`, `sendKeyEvent`, and supported pointer operations through the system input queue. System keyboard presses verify the foreground app; releases retain the route recorded at down and release system keys even after the target loses focus or exits. `click` and `drag` reuse balanced mouse delivery and surround it with system modifier presses and reverse releases. System input rejects a new press of an already-held key rather than releasing another input owner’s key. + +`mouseMove` reveals or restores alternate UI through an enabled element or ancestor advertising both `AXShowAlternateUI` and `AXShowDefaultUI`. Without an AX route it returns `HOVER_UNAVAILABLE` before sending input. The Host resolves the requested route against session approval or the configured exemption before sending `useSystemInput` to the helper. The opt-in system pointer route returns `FOREGROUND_REQUIRED` if the target is obscured or belongs to a background app. The result reports the route and whether the visible cursor moved in `hoverRoute` and `systemPointerMoved`. It never presses a button or restores the cursor after a read. Later input may interrupt the hover. Clicks send their button events at the target without an off-window priming click. diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index 4ba6760c92..215bcd4000 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -101,9 +101,9 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 窗口隐藏本身不会使 AX 快照失效。刷新清单时,只有同一窗口 ID 仍存在且观察到的尺寸未变,才能继续使用此前截图的像素坐标。观察到尺寸变化后需要重新截图;窗口销毁后不能继续操作。清单中省略窗口不会阻止按已知 ID 发起输入。窗口归属、尺寸和输入检查仍然生效,成功分派不代表应用已接收。 -窗口模式的 `toggleMouse` 向目标进程发送一次按下或松开。按下时使用当前指针位置,松开时允许指针移出。显式开启 `useSystemPointer` 后,helper 通过 HID 发送系统按键事件。只有按下该键的连接能通过原窗口显式松开。在同一窗口请求系统指针移动会发送该按键的拖动事件。Host 在回合结束时请求清理,连接关闭也会松开按键。 +窗口模式的 `toggleMouse` 向目标进程发送一次按下或松开。按下时使用当前指针位置,松开时允许指针移出。显式开启 `useSystemInput` 后,helper 通过 HID 发送系统按键事件。只有按下该键的连接能通过原窗口显式松开。在同一窗口请求系统指针移动会发送该按键的拖动事件。Host 在回合结束时请求清理,连接关闭也会松开按键。 -点击在元素中心或给定坐标发送鼠标按下和抬起事件。执行默认 AX 动作用 `invoke`,执行指定动作用 `performAction`。点击、滚动和默认拖动核实窗口归属和边界后,向目标进程和窗口投递事件。事件优先使用 SkyLight,不可用时使用公开的 PID 定向 API;已发送的事件不通过另一 API 重发。坐标是整个窗口左上角起算的 macOS point,包含标题栏。`deltaLinesY` 为正时显示上方内容,为负时显示下方内容;`deltaLinesX` 为正时显示左侧内容,为负时显示右侧内容。每个轴接受 -10 到 10 的整数,至少一个轴非零。helper 直接发送按行计量的滚轮事件。点击和拖动支持左、右、中键及 command/control/option/shift/fn 修饰键,只有左键支持双击。拖动在一个窗口中完成一次按下、移动、抬起,调用方显式提供 durationMs(1..5000)和 steps(1..240)。移动延迟按小数精度分配到各段,按下和抬起的固定等待及调度延迟另计。显式传入 `useSystemPointer: true` 的拖动通过 HID 投递,起点及每段移动都要命中目标前台窗口。手势共用事件号,每段携带位移。取消时在最后投递的位置松开鼠标键。 +点击在元素中心或给定坐标发送鼠标按下和抬起事件。执行默认 AX 动作用 `invoke`,执行指定动作用 `performAction`。点击、滚动和默认拖动核实窗口归属和边界后,向目标进程和窗口投递事件。事件优先使用 SkyLight,不可用时使用公开的 PID 定向 API;已发送的事件不通过另一 API 重发。坐标是整个窗口左上角起算的 macOS point,包含标题栏。`deltaLinesY` 为正时显示上方内容,为负时显示下方内容;`deltaLinesX` 为正时显示左侧内容,为负时显示右侧内容。每个轴接受 -10 到 10 的整数,至少一个轴非零。helper 直接发送按行计量的滚轮事件。点击和拖动支持左、右、中键及 command/control/option/shift/fn 修饰键,只有左键支持双击。拖动在一个窗口中完成一次按下、移动、抬起,调用方显式提供 durationMs(1..5000)和 steps(1..240)。移动延迟按小数精度分配到各段,按下和抬起的固定等待及调度延迟另计。显式传入 `useSystemInput: true` 的拖动通过 HID 投递,起点及每段移动都要命中目标前台窗口。手势共用事件号,每段携带位移。取消时在最后投递的位置松开鼠标键。 `click.holdMs` 是可选的每次按住时长,单位为毫秒,接受非负整数;0 表示不额外等待。每个连接通过 `maxClickHoldMs` 限制显式按住时长。诊断 helper 的 `--max-click-hold-ms` 选项默认 5000。省略时保留普通点击时长。整个手势占用请求调度槽位;取消、超时和断开连接会中断等待,在释放槽位前发送对应的松开事件。已接收的事件仍然生效,进程被强制终止时无法保证清理。 @@ -131,7 +131,9 @@ helper 只派发一次 `AXZoomWindow`。如果 `AXUIElementPerformAction` 返回 `paste` 提供一种纯文本或 HTML 剪贴板格式,调用应用已启用的标准 Paste 菜单命令,并等待剪贴板数据请求。随后仅在所有权标记和修改计数仍匹配时恢复原有格式。Host 通过文件锁串行化不同 helper 的粘贴。maxClipboardBytes 同时限制输入和保留内容,不支持的菜单和过大的数据在分派前失败。后续复制会被保留。取消会尽可能恢复仍持有的剪贴板数据,强制结束不保证恢复,数据请求也不证明目标已完成编辑。 分派完成后,`pasteReadTimeoutMs` 限制等待剪贴板读取的时间。到期返回 `PASTE_NOT_CONSUMED`,关闭延迟数据提供方,并仅在仍持有剪贴板时恢复原内容。该失败不能证明应用以后不会处理已排队的 Paste 命令;决定是否重试前先检查目标内容。 -默认情况下,`mouseMove` 通过同一窗口内启用的控件或祖先声明的 `AXShowAlternateUI` 和 `AXShowDefaultUI` 展开或恢复界面。缺少这条路径时返回 `HOVER_UNAVAILABLE`,不发送输入。Host 根据本会话的授权或免询问配置决定本次悬停的路径,再向 helper 传入 `useSystemPointer`。 +`useSystemInput: true` 将 `pressKey`、`sendKeyEvent` 和支持的鼠标操作派发到系统输入队列。系统键盘按下检查前台应用;释放使用按下时保存的输入方式,即使目标失焦或退出也释放系统键。`click` 和 `drag` 复用已有鼠标配对释放逻辑,在手势外层按下并反序释放系统修饰键。系统模式拒绝再次按下已经持有的键,防止释放其他输入的按键。 + +默认情况下,`mouseMove` 通过同一窗口内启用的控件或祖先声明的 `AXShowAlternateUI` 和 `AXShowDefaultUI` 展开或恢复界面。缺少这条路径时返回 `HOVER_UNAVAILABLE`,不发送输入。Host 根据本会话的授权或免询问配置决定本次悬停的路径,再向 helper 传入 `useSystemInput`。 开启后,系统指针路线会检查前台应用和坐标命中的窗口,不满足条件时返回 `FOREGROUND_REQUIRED`。返回值 `hoverRoute` 和 `systemPointerMoved` 说明走了哪条路线以及是否移动了可见光标。悬停不会按下鼠标,也不会在读取后还原光标。后续输入可能中断悬停。点击只在目标点发送按键事件,不先在窗口外点击。 diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift index 7bc12e9c2d..028a3b8415 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift @@ -206,7 +206,7 @@ actor AXWorker { var recovery = AXChildRecoveryBudget(maxElements: NativeProtocol.elementRange.upperBound, timeout: axTimeout) if method == "sendKeyEvent", try params.string("direction") == "up" { let handle = try params.string("appHandle") - let dispatched = try inputs().0.keyUp(params.string("key"), app: handle, run: params.string("runId")) { + let dispatched = try inputs().0.keyUp(params.string("key"), app: handle, run: params.string("runId"), useSystemInput: params.optionalBoolean("useSystemInput") ?? false) { try NativePlatform.requireUnlocked(observeSession()) try NativePlatform.requireAccessibility() return try ax().keyboardRecipient(validateIdentity(handle), catalog: catalog, budget: &recovery) @@ -348,14 +348,17 @@ actor AXWorker { readTimeout: .milliseconds(try params.integer("pasteReadTimeoutMs", in: 1...2147483647)), maxElements: try params.integer("maxElements", in: NativeProtocol.elementRange), maxDepth: try params.integer("maxDepth", in: NativeProtocol.depthRange))) case "sendKeyEvent": - try inputs().0.keyDown(params.string("key"), app: handle, run: params.string("runId")) { - try ax().keyboardRecipient(identity, catalog: catalog, budget: &recovery) + let system = try params.optionalBoolean("useSystemInput") ?? false + try inputs().0.keyDown(params.string("key"), app: handle, run: params.string("runId"), useSystemInput: system) { + if system { return identity } + return try ax().keyboardRecipient(identity, catalog: catalog, budget: &recovery) } case "typeText", "pressKey": - let recipient = try ax().keyboardRecipient(identity, catalog: catalog, budget: &recovery) + let system = method == "pressKey" && (try params.optionalBoolean("useSystemInput") ?? false) + let recipient = system ? identity : try ax().keyboardRecipient(identity, catalog: catalog, budget: &recovery) try NativePlatform.verify(recipient) if method == "typeText" { try inputs().0.typeText(params.string("text"), to: recipient.pid) } - else { try inputs().0.pressKey(params.string("key"), modifiers: params.modifiers(), to: recipient.pid) } + else { try inputs().0.pressKey(params.string("key"), modifiers: params.modifiers(), to: recipient.pid, useSystemInput: system) } case "setValue": try ax().setAttribute(element(handle, params), "AXValue", params.values["value"]) case "performAction": try ax().performAction(element(handle, params), action: params.string("action"), argument: params.values["argument"]) @@ -383,13 +386,13 @@ actor AXWorker { window = try NativePlatform.ownedWindow(identity.pid, id) } let route = WindowRoute(owner: identity, windowID: id, bounds: window.bounds) - if try params.optionalBoolean("useSystemPointer") == true { + if try params.optionalBoolean("useSystemInput") == true { return .systemButtonDown(route, try WindowPointerInput.button(params.string("mouseButton"))) } try await inputs().1.toggleMouse(in: route, button: params.string("mouseButton"), isDown: isDown) case "click", "mouseMove": - let useSystemPointer = try params.optionalBoolean("useSystemPointer") ?? false + let useSystemInput = try params.optionalBoolean("useSystemInput") ?? false let holdMs = params.contains("holdMs") ? try params.integer("holdMs", in: 0...maxClickHoldMs) : nil let button = try params.optionalString("mouseButton") ?? "left" let count = params.contains("clickCount") ? try params.integer("clickCount", in: 1...2) : 1 @@ -409,7 +412,7 @@ actor AXWorker { } if method == "mouseMove" { _ = try NativePlatform.ownedWindow(identity.pid, enclosing.id) - if !useSystemPointer { return try moveUsingAX(selected, windowID: enclosing.id, handle: handle) } + if !useSystemInput { return try moveUsingAX(selected, windowID: enclosing.id, handle: handle) } } else { try ax().requireEnabled(selected) } @@ -426,7 +429,7 @@ actor AXWorker { let route = WindowRoute(owner: identity, windowID: window.windowID, bounds: window.bounds) if method == "mouseMove" { try WindowPointerInput.validate(point, in: route) - if !useSystemPointer { + if !useSystemInput { var hit = try ax().element(at: CGPoint(x: window.bounds.x + point.x, y: window.bounds.y + point.y), owner: identity) if let target = hit, try ax().windowID(target) != window.windowID { hit = nil } return try moveUsingAX(hit, windowID: window.windowID, handle: handle) @@ -444,7 +447,7 @@ actor AXWorker { try NativePlatform.verify(panel.process) clickRoute = WindowRoute(owner: panel.process, windowID: panel.windowID, bounds: serviceWindow.bounds) } - try await inputs().1.click(in: clickRoute, at: point, button: button, count: count, modifiers: modifiers, holdMs: holdMs) + try await inputs().1.click(in: clickRoute, at: point, button: button, count: count, modifiers: modifiers, holdMs: holdMs, useSystemInput: useSystemInput) case "scroll", "drag": let id = try params.windowID() try coordinateSnapshot(handle, params, id) @@ -458,7 +461,7 @@ actor AXWorker { try await inputs().1.drag(in: route, from: params.point("fromX", "fromY"), to: params.point("toX", "toY"), durationMs: params.integer("durationMs", in: 1...5000), steps: params.integer("steps", in: 1...240), button: params.optionalString("mouseButton") ?? "left", modifiers: params.modifiers(), - useSystemPointer: params.optionalBoolean("useSystemPointer") ?? false) + useSystemInput: params.optionalBoolean("useSystemInput") ?? false) } default: throw NativeFailure(code: "UNSUPPORTED", message: method) } diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/HeldKeys.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/HeldKeys.swift index 3d29795127..454653c606 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/HeldKeys.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/HeldKeys.swift @@ -17,13 +17,14 @@ final class HeldKeys: @unchecked Sendable { let code: CGKeyCode let flag: CGEventFlags let up: CGEvent + let system: Bool } private let lock = NSLock() private var pressed: [Press] = [] - func snapshot(pid: Int32) -> [CGKeyCode: CGEventFlags] { - lock.withLock { Dictionary(uniqueKeysWithValues: pressed.filter { $0.recipient.pid == pid }.map { ($0.code, $0.flag) }) } + func snapshot(pid: Int32, system: Bool = false) -> [CGKeyCode: CGEventFlags] { + lock.withLock { Dictionary(uniqueKeysWithValues: pressed.filter { $0.system == system && (system || $0.recipient.pid == pid) }.map { ($0.code, $0.flag) }) } } private func conflict(_ name: String, holder: Owner, caller: Owner) -> NativeFailure { @@ -35,54 +36,56 @@ final class HeldKeys: @unchecked Sendable { } /// Repeats use the saved recipient even when the selected application's focused panel has changed. - func repeatIfHeld(owner: Owner, name: String, code: CGKeyCode, down: CGEvent, post: (CGEvent, Int32) -> Void) throws -> Bool { + func repeatIfHeld(owner: Owner, name: String, code: CGKeyCode, down: CGEvent, system: Bool = false, post: (CGEvent, Int32, Bool) -> Void) throws -> Bool { try lock.withLock { guard let key = pressed.first(where: { $0.owner == owner && $0.code == code }) else { return false } + guard key.system == system else { throw RequestParameters.invalid("Match useSystemInput to the held key") } guard key.flag.isEmpty, down.type == .keyDown else { throw RequestParameters.invalid("Modifier '\(name)' is already held. Send 'up' to release it.") } try NativePlatform.verify(key.recipient) - down.flags = flags(for: key.recipient) + down.flags = flags(for: key.recipient, system: key.system) down.setIntegerValueField(.keyboardEventAutorepeat, value: 1) - post(down, key.recipient.pid) + post(down, key.recipient.pid, key.system) return true } } func down(owner: Owner, recipient: ProcessIdentity, name: String, code: CGKeyCode, flag: CGEventFlags, - down: CGEvent, up: CGEvent, post: (CGEvent, Int32) -> Void) throws { + down: CGEvent, up: CGEvent, system: Bool = false, post: (CGEvent, Int32, Bool) -> Void) throws { try lock.withLock { - if let key = pressed.first(where: { $0.code == code && $0.recipient.pid == recipient.pid }) { + if let key = pressed.first(where: { $0.code == code && (($0.system && system) || $0.recipient.pid == recipient.pid) }) { throw conflict(name, holder: key.owner, caller: owner) } - pressed.append(Press(owner: owner, recipient: recipient, code: code, flag: flag, up: up)) - down.flags = flags(for: recipient) - post(down, recipient.pid) + pressed.append(Press(owner: owner, recipient: recipient, code: code, flag: flag, up: up, system: system)) + down.flags = flags(for: recipient, system: system) + post(down, recipient.pid, system) } } - private func flags(for recipient: ProcessIdentity) -> CGEventFlags { - pressed.reduce(into: CGEventFlags()) { if $1.recipient == recipient { $0.formUnion($1.flag) } } + private func flags(for recipient: ProcessIdentity, system: Bool) -> CGEventFlags { + pressed.reduce(into: CGEventFlags()) { if $1.system == system && (system || $1.recipient == recipient) { $0.formUnion($1.flag) } } } /// An up always targets the process selected at down. Never post to a recycled PID. - private func release(at index: Int, post: (CGEvent, Int32) -> Void) throws -> Bool { + private func release(at index: Int, post: (CGEvent, Int32, Bool) -> Void) throws -> Bool { let key = pressed[index] - do { try NativePlatform.verify(key.recipient) } + do { if !key.system { try NativePlatform.verify(key.recipient) } } catch let error as NativeFailure where error.code == "STALE_APP" || error.code == "APP_UNAVAILABLE" { pressed.remove(at: index) return false } pressed.remove(at: index) - key.up.flags = flags(for: key.recipient) - post(key.up, key.recipient.pid) + key.up.flags = flags(for: key.recipient, system: key.system) + post(key.up, key.recipient.pid, key.system) return true } - func up(owner: Owner, name: String, code: CGKeyCode, recipientIfUnheld: () throws -> ProcessIdentity, - post: (CGEvent, Int32) -> Void) throws -> Bool { + func up(owner: Owner, name: String, code: CGKeyCode, system: Bool = false, recipientIfUnheld: () throws -> ProcessIdentity, + post: (CGEvent, Int32, Bool) -> Void) throws -> Bool { let dispatched = try lock.withLock { () throws -> Bool? in guard let index = pressed.firstIndex(where: { $0.owner == owner && $0.code == code }) else { return nil } + guard pressed[index].system == system else { throw RequestParameters.invalid("Match useSystemInput to the held key") } return try release(at: index, post: post) } if let dispatched { return dispatched } @@ -95,7 +98,7 @@ final class HeldKeys: @unchecked Sendable { } } - func release(connection: UUID, run: String?, post: (CGEvent, Int32) -> Void) throws { + func release(connection: UUID, run: String?, post: (CGEvent, Int32, Bool) -> Void) throws { try lock.withLock { defer { // A closed connection cannot retry an unverifiable recipient. diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift index b435d4e46b..81a7a53538 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift @@ -2,7 +2,7 @@ import CoreGraphics import Foundation -/// Balanced PID-targeted chords and scalar-based Unicode input on one serial worker. +/// Process-directed text and chords, with explicit system delivery for keystrokes and held keys. final class KeyboardInput { private struct Key { let keyCode: CGKeyCode @@ -11,34 +11,43 @@ final class KeyboardInput { private let connection = UUID() private let held: HeldKeys - private let post: (CGEvent, Int32) -> Void + private let postProcess: (CGEvent, Int32) -> Void + private let system: SystemKeyboardInput private let textEventInterval: Double private let checkCancellation: @Sendable () throws -> Void - init(post: @escaping (CGEvent, Int32) -> Void, textEventInterval: Double, held: HeldKeys = HeldKeys(), checkCancellation: @escaping @Sendable () throws -> Void = {}) { + init(post: @escaping (CGEvent, Int32) -> Void, textEventInterval: Double, held: HeldKeys = HeldKeys(), system: SystemKeyboardInput = SystemKeyboardInput(), checkCancellation: @escaping @Sendable () throws -> Void = {}) { self.held = held - self.post = post + self.postProcess = post + self.system = system self.textEventInterval = textEventInterval self.checkCancellation = checkCancellation } - func keyDown(_ name: String, app: String, run: String, recipient: () throws -> ProcessIdentity) throws { + private func post(_ event: CGEvent, _ pid: Int32, _ useSystemInput: Bool = false) { + if useSystemInput { system.post(event) } + else { postProcess(event, pid) } + } + + func keyDown(_ name: String, app: String, run: String, useSystemInput: Bool = false, recipient: () throws -> ProcessIdentity) throws { let owner = HeldKeys.Owner(connection: connection, run: run, app: app) let code = try Self.keyCode(name) let source = try Self.source() let down = try Self.keyEvent(source: source, code: code, down: true, flags: []) try checkCancellation() - if try held.repeatIfHeld(owner: owner, name: name, code: code, down: down, post: post) { return } + if useSystemInput { try system.validateTarget(recipient().pid) } + if try held.repeatIfHeld(owner: owner, name: name, code: code, down: down, system: useSystemInput, post: post) { return } + if useSystemInput { try system.requireReleased([code]) } let target = try recipient() let up = try Self.keyEvent(source: source, code: code, down: false, flags: []) try checkCancellation() try NativePlatform.verify(target) try held.down(owner: owner, recipient: target, name: name, code: code, flag: Self.namedModifier(name)?.flag ?? [], - down: down, up: up, post: post) + down: down, up: up, system: useSystemInput, post: post) } - func keyUp(_ name: String, app: String, run: String, recipientIfUnheld: () throws -> ProcessIdentity) throws -> Bool { - try held.up(owner: .init(connection: connection, run: run, app: app), name: name, code: Self.keyCode(name), + func keyUp(_ name: String, app: String, run: String, useSystemInput: Bool = false, recipientIfUnheld: () throws -> ProcessIdentity) throws -> Bool { + try held.up(owner: .init(connection: connection, run: run, app: app), name: name, code: Self.keyCode(name), system: useSystemInput, recipientIfUnheld: recipientIfUnheld, post: post) } @@ -47,19 +56,19 @@ final class KeyboardInput { } /// Prepare every event before dispatch. On cancellation, release only the keys this call pressed. - func pressKey(_ name: String, modifiers: [String], to pid: Int32) throws { + func pressKey(_ name: String, modifiers: [String], to pid: Int32, useSystemInput: Bool = false) throws { try checkCancellation() var chord = try modifiers.map(Self.modifier) let isPlus = name == "+" || name.lowercased() == "plus" if isPlus { chord.append(try Self.modifier("shift")) } let code = try Self.keyCode(isPlus ? "=" : name) chord.append(Key(keyCode: code, flag: Self.namedModifier(name)?.flag ?? [])) - let alreadyHeld = held.snapshot(pid: pid) + let alreadyHeld = held.snapshot(pid: pid, system: useSystemInput) guard alreadyHeld[code] == nil else { throw RequestParameters.invalid("Key '\(name)' is already held for this target. Use pressKey after the run_code that holds it releases it.") } var selected = Set(alreadyHeld.keys) - var flags = alreadyHeld.values.reduce(CGEventFlags()) { $0.union($1) } + var flags = alreadyHeld.values.reduce(useSystemInput ? system.currentFlags() : CGEventFlags()) { $0.union($1) } var events: [(down: CGEvent, up: CGEvent)] = [] let source = try Self.source() for key in chord { @@ -71,17 +80,22 @@ final class KeyboardInput { up: try Self.keyEvent(source: source, code: key.keyCode, down: false, flags: releasedFlags) )) } + if useSystemInput { + try system.validateTarget(pid) + try system.requireReleased(events.map { CGKeyCode($0.down.getIntegerValueField(.keyboardEventKeycode)) }) + } var pressed = 0 do { defer { for index in (0.. 0 { Thread.sleep(forTimeInterval: 0.008) } } } for event in events { try checkCancellation() - post(event.down, pid) + if useSystemInput { try system.validateTarget(pid) } + post(event.down, pid, useSystemInput) pressed += 1 Thread.sleep(forTimeInterval: 0.008) } @@ -137,14 +151,14 @@ final class KeyboardInput { try checkCancellation() } - private static func source() throws -> CGEventSource { + static func source() throws -> CGEventSource { guard let source = CGEventSource(stateID: .hidSystemState) else { throw NativeFailure(code: "NATIVE_ERROR", message: "Could not create keyboard event source") } return source } - private static func keyEvent( + static func keyEvent( source: CGEventSource, code: CGKeyCode, down: Bool, flags: CGEventFlags ) throws -> CGEvent { // CoreGraphics creates FlagsChanged for modifier virtual keys. diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift index 62d3ae2155..e81e6e8dc3 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift @@ -5,8 +5,8 @@ enum NativeProtocol { static let fields: [String: Set] = [ "activate": ["appHandle"], "applicationIcons": ["paths"], - "click": ["appHandle", "clickCount", "elementId", "holdMs", "modifiers", "mouseButton", "snapshotId", "windowId", "x", "y"], - "drag": ["appHandle", "durationMs", "fromX", "fromY", "modifiers", "mouseButton", "snapshotId", "steps", "toX", "toY", "useSystemPointer", "windowId"], + "click": ["appHandle", "clickCount", "elementId", "holdMs", "modifiers", "mouseButton", "snapshotId", "useSystemInput", "windowId", "x", "y"], + "drag": ["appHandle", "durationMs", "fromX", "fromY", "modifiers", "mouseButton", "snapshotId", "steps", "toX", "toY", "useSystemInput", "windowId"], "findApps": ["maxAppMatches", "query"], "getApp": ["selector"], "getCapabilities": [], @@ -16,22 +16,22 @@ enum NativeProtocol { "listActions": ["appHandle", "elementId", "snapshotId", "windowId"], "listApps": [], "listWindows": ["appHandle"], - "mouseMove": ["appHandle", "elementId", "snapshotId", "useSystemPointer", "windowId", "x", "y"], + "mouseMove": ["appHandle", "elementId", "snapshotId", "useSystemInput", "windowId", "x", "y"], "openPermissionSettings": ["permission", "settingsMessage"], "paste": ["appHandle", "format", "maxClipboardBytes", "maxDepth", "maxElements", "pasteReadTimeoutMs", "text", "windowId"], "performAction": ["action", "appHandle", "argument", "elementId", "snapshotId", "windowId"], "permissionStatus": [], - "pressKey": ["appHandle", "key", "modifiers", "windowId"], + "pressKey": ["appHandle", "key", "modifiers", "useSystemInput", "windowId"], "releaseHeldKeys": ["runId"], "releaseSystemButton": [], "requestPermission": ["backLabel", "finderLabel", "instruction", "permission", "pollIntervalMs", "settingsMessage", "unavailableMessage"], "screenshot": ["appHandle", "windowId"], "scroll": ["appHandle", "deltaLinesX", "deltaLinesY", "snapshotId", "windowId", "x", "y"], "selectText": ["appHandle", "elementId", "prefix", "selectionType", "snapshotId", "suffix", "text", "windowId"], - "sendKeyEvent": ["appHandle", "direction", "key", "runId", "windowId"], + "sendKeyEvent": ["appHandle", "direction", "key", "runId", "useSystemInput", "windowId"], "setValue": ["appHandle", "elementId", "snapshotId", "value", "windowId"], "show": ["appHandle", "windowId"], - "toggleMouse": ["appHandle", "direction", "mouseButton", "useSystemPointer", "windowId"], + "toggleMouse": ["appHandle", "direction", "mouseButton", "useSystemInput", "windowId"], "typeText": ["appHandle", "text", "windowId"], ] static let stringEnums: [String: [String: Set]] = [ diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift index 73d80be2bd..8a984b3d7e 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift @@ -169,7 +169,7 @@ import Darwin scheduler.systemPointer.release(connection: connectionID) return AXWorker.actionResult } - if request.method == "toggleMouse", try params.optionalBoolean("useSystemPointer") == true, + if request.method == "toggleMouse", try params.optionalBoolean("useSystemInput") == true, try params.string("direction") == "up" { try scheduler.systemPointer.up(connection: connectionID, app: params.string("appHandle"), window: params.windowID(), button: WindowPointerInput.button(params.string("mouseButton"))) diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/SystemKeyboardInput.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/SystemKeyboardInput.swift new file mode 100644 index 0000000000..2734af048d --- /dev/null +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/SystemKeyboardInput.swift @@ -0,0 +1,71 @@ +// System keyboard delivery and balanced modifiers shared by keyboard and pointer operations. +import CoreGraphics +import Foundation + +final class SystemKeyboardInput { + let post: (CGEvent) -> Void + private let foreground: () -> Int32? + private let keyState: (CGKeyCode) -> Bool + let currentFlags: () -> CGEventFlags + + init(post: @escaping (CGEvent) -> Void = { $0.post(tap: .cghidEventTap) }, + keyState: @escaping (CGKeyCode) -> Bool = { CGEventSource.keyState(.combinedSessionState, key: $0) }, + currentFlags: @escaping () -> CGEventFlags = { CGEventSource.flagsState(.combinedSessionState) }, + foreground: @escaping () -> Int32? = NativePlatform.frontPID) { + self.post = post + self.keyState = keyState + self.currentFlags = currentFlags + self.foreground = foreground + } + + func validateTarget(_ pid: Int32) throws { + guard foreground() == pid else { + throw NativeFailure(code: "FOREGROUND_REQUIRED", message: "System keyboard input requires the selected application in the foreground; activate it and observe again") + } + } + + func requireReleased(_ codes: [CGKeyCode]) throws { + guard !codes.contains(where: keyState) else { + throw NativeFailure(code: "INPUT_BUSY", message: "A requested system key is already held; release it before sending another press") + } + } + + /// Prepare all events before pressing; the returned release only covers keys pressed by this call. + func pressModifiers(_ names: [String], check: () throws -> Void) throws -> () -> Void { + let source = try KeyboardInput.source() + var seen = Set() + var flags = currentFlags() + var pairs: [(down: CGEvent, up: CGEvent)] = [] + var codes: [CGKeyCode] = [] + for name in names { + let flag = try KeyboardInput.modifierFlags([name]) + let code = try KeyboardInput.keyCode(name) + guard seen.insert(code).inserted else { continue } + let previous = flags + flags.formUnion(flag) + pairs.append((try KeyboardInput.keyEvent(source: source, code: code, down: true, flags: flags), + try KeyboardInput.keyEvent(source: source, code: code, down: false, flags: previous))) + codes.append(code) + } + try requireReleased(codes) + var pressed = 0 + let release = { [post] in + while pressed > 0 { + pressed -= 1 + post(pairs[pressed].up) + } + } + do { + for pair in pairs { + try check() + post(pair.down) + pressed += 1 + Thread.sleep(forTimeInterval: 0.008) + } + } catch { + release() + throw error + } + return release + } +} diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/SystemPointerInput.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/SystemPointerInput.swift index 06ad68fe9e..8cb55e332b 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/SystemPointerInput.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/SystemPointerInput.swift @@ -15,13 +15,13 @@ import Foundation private var press: Press? nonisolated static func event(_ type: CGEventType, source: CGEventSource?, at screen: CGPoint, button: CGMouseButton, - group: Int64, flags: CGEventFlags = []) throws -> CGEvent { + group: Int64, flags: CGEventFlags? = nil, clickState: Int64 = 1) throws -> CGEvent { guard let event = CGEvent(mouseEventSource: source, mouseType: type, mouseCursorPosition: screen, mouseButton: button) else { throw NativeFailure(code: "NATIVE_ERROR", message: "Could not create system mouse event") } - event.flags = flags + event.flags = flags ?? CGEventSource.flagsState(.combinedSessionState) event.setIntegerValueField(.mouseEventNumber, value: group) - event.setIntegerValueField(.mouseEventClickState, value: type == .mouseMoved ? 0 : 1) + event.setIntegerValueField(.mouseEventClickState, value: type == .mouseMoved ? 0 : clickState) return event } diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/WindowPointerInput.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/WindowPointerInput.swift index bca1bc6cc1..ed59cf9256 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/WindowPointerInput.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/WindowPointerInput.swift @@ -16,10 +16,12 @@ final class WindowPointerInput { } private let poster: PIDEventPoster + private let systemKeyboard: SystemKeyboardInput private let checkCancellation: @Sendable () throws -> Void - init(poster: PIDEventPoster, checkCancellation: @escaping @Sendable () throws -> Void = {}) { + init(poster: PIDEventPoster, systemKeyboard: SystemKeyboardInput = SystemKeyboardInput(), checkCancellation: @escaping @Sendable () throws -> Void = {}) { self.poster = poster + self.systemKeyboard = systemKeyboard self.checkCancellation = checkCancellation } @@ -67,9 +69,9 @@ final class WindowPointerInput { poster.post(event, to: route.owner.pid) } - /// Post balanced mouse presses; holdMs replaces each press-to-release interval and remains cancellable. + /// Post balanced mouse presses; system input also holds and releases the requested keyboard modifiers. func click(in route: WindowRoute, at point: WindowPoint, button: String, count: Int, modifiers: [String] = [], - holdMs: Int? = nil, isolation: isolated (any Actor)? = #isolation) async throws { + holdMs: Int? = nil, useSystemInput: Bool = false, isolation: isolated (any Actor)? = #isolation) async throws { try checkCancellation() try Self.validate(point, in: route) guard (button == "left" && (count == 1 || count == 2)) || (["right", "middle"].contains(button) && count == 1) else { @@ -77,40 +79,45 @@ final class WindowPointerInput { } let source = try Self.source() let selectedButton = try Self.button(button) - let flags = try KeyboardInput.modifierFlags(modifiers) + var flags = try KeyboardInput.modifierFlags(modifiers) + if useSystemInput { flags.formUnion(CGEventSource.flagsState(.combinedSessionState)) } let group = Self.clickGroup() let screen = Self.screenPoint(point, in: route) let move = try mouseEvent( source: source, route: route, screen: screen, local: point, type: .mouseMoved, button: .left, clickState: 0, subtype: 3, - group: group, number: button == "left" ? 2 : nil, flags: flags + group: group, number: button == "left" ? 2 : nil, flags: flags, useSystemInput: useSystemInput ) - if button == "left" { - var pairs: [MousePair] = [] - for index in 1...count { - pairs.append(try mousePair( - source: source, route: route, screen: screen, local: point, - button: .left, clickState: Int64(index), group: group, downNumber: 3, upNumber: 3, flags: flags - )) + let pairs = try (1...count).map { index in + try mousePair(source: source, route: route, screen: screen, local: point, + button: selectedButton, clickState: Int64(index), group: group, + downNumber: button == "left" ? 3 : nil, upNumber: button == "left" ? 3 : nil, + flags: flags, useSystemInput: useSystemInput) + } + var releaseModifiers: (() -> Void)? + defer { releaseModifiers?() } + if useSystemInput { + try Self.validateWindow(route) + try await Self.checkSystemHit(route, at: screen) + try Self.requireReleasedButtons() + releaseModifiers = try systemKeyboard.pressModifiers(modifiers, check: checkCancellation) + } + func post(_ event: CGEvent) { + if useSystemInput { SystemPointerInput.post(event) } + else { poster.post(event, to: route.owner.pid) } + } + try checkCancellation() + post(move) + try await Task.sleep(for: .milliseconds(button == "left" ? 15 : 12)) + for (index, pair) in pairs.enumerated() { + if useSystemInput { + try Self.validateWindow(route) + try await Self.checkSystemHit(route, at: screen) + try Self.requireReleasedButtons() } - try checkCancellation() - poster.post(move, to: route.owner.pid) - try await Task.sleep(for: .milliseconds(15)) - for (index, pair) in pairs.enumerated() { - try await Self.postPair(downInterval: .milliseconds(holdMs ?? 1), checkCancellation: checkCancellation, - down: { poster.post(pair.down, to: route.owner.pid) }, up: { poster.post(pair.up, to: route.owner.pid) }) - if index + 1 < pairs.count { try await Task.sleep(for: .milliseconds(80)) } - } - } else { - let pair = try mousePair( - source: source, route: route, screen: screen, local: point, - button: selectedButton, clickState: 1, group: group, flags: flags - ) - try checkCancellation() - poster.post(move, to: route.owner.pid) - try await Task.sleep(for: .milliseconds(12)) - try await Self.postPair(downInterval: .milliseconds(holdMs ?? 28), checkCancellation: checkCancellation, - down: { poster.post(pair.down, to: route.owner.pid) }, up: { poster.post(pair.up, to: route.owner.pid) }) + try await Self.postPair(downInterval: .milliseconds(holdMs ?? (button == "left" ? 1 : 28)), + checkCancellation: checkCancellation, down: { post(pair.down) }, up: { post(pair.up) }) + if index + 1 < pairs.count { try await Task.sleep(for: .milliseconds(80)) } } try checkCancellation() } @@ -152,7 +159,7 @@ final class WindowPointerInput { /// Drag the selected button along an interpolated path, releasing at the last posted point on cancellation. func drag( in route: WindowRoute, from start: WindowPoint, to end: WindowPoint, durationMs: Int, steps: Int, - button: String = "left", modifiers: [String] = [], useSystemPointer: Bool = false, + button: String = "left", modifiers: [String] = [], useSystemInput: Bool = false, isolation: isolated (any Actor)? = #isolation ) async throws { try checkCancellation() @@ -163,18 +170,19 @@ final class WindowPointerInput { } let source = try Self.source() let selected = try Self.button(button) - let flags = try KeyboardInput.modifierFlags(modifiers) + var flags = try KeyboardInput.modifierFlags(modifiers) + if useSystemInput { flags.formUnion(CGEventSource.flagsState(.combinedSessionState)) } let group = Self.clickGroup() func event(_ type: CGEventType, at point: WindowPoint) throws -> CGEvent { let screen = Self.screenPoint(point, in: route) - if !useSystemPointer { + if !useSystemInput { return try mouseEvent(source: source, route: route, screen: screen, local: point, type: type, button: selected, clickState: 1, subtype: 0, group: group, flags: flags) } return try SystemPointerInput.event(type, source: source, at: screen, button: selected, group: group, flags: flags) } func post(_ event: CGEvent) { - if useSystemPointer { + if useSystemInput { SystemPointerInput.post(event) } else { poster.post(event, to: route.owner.pid) @@ -188,25 +196,28 @@ final class WindowPointerInput { let fraction = Double(index) / Double(steps) let local = WindowPoint(x: start.x + (end.x - start.x) * fraction, y: start.y + (end.y - start.y) * fraction) let movement = try event(Self.dragged(selected), at: local) - if useSystemPointer { + if useSystemInput { movement.setIntegerValueField(.mouseEventDeltaX, value: Int64(local.x.rounded() - previous.x.rounded())) movement.setIntegerValueField(.mouseEventDeltaY, value: Int64(local.y.rounded() - previous.y.rounded())) } path.append(DragStep(movement: movement, release: try event(Self.up(selected), at: local))) previous = local } - if useSystemPointer { + var releaseModifiers: (() -> Void)? + defer { releaseModifiers?() } + if useSystemInput { try Self.validateWindow(route) try await Self.checkSystemHit(route, at: down.location) try Self.requireReleasedButtons() try checkCancellation() + releaseModifiers = try systemKeyboard.pressModifiers(modifiers, check: checkCancellation) post(try event(.mouseMoved, at: start)) } let check = checkCancellation try await Self.postDrag(down: down, initialRelease: initialRelease, path: path, interval: Self.dragStepInterval(durationMs: durationMs, steps: steps), validate: { type, point in - if useSystemPointer { + if useSystemInput { try await Self.checkSystemHit(route, at: point) if type == Self.down(selected) { try Self.requireReleasedButtons() } } @@ -261,18 +272,18 @@ final class WindowPointerInput { private func mousePair( source: CGEventSource, route: WindowRoute, screen: CGPoint, local: WindowPoint, button: CGMouseButton, clickState: Int64, group: Int64, - downNumber: Int64? = nil, upNumber: Int64? = nil, flags: CGEventFlags = [] + downNumber: Int64? = nil, upNumber: Int64? = nil, flags: CGEventFlags = [], useSystemInput: Bool = false ) throws -> MousePair { try MousePair( down: mouseEvent( source: source, route: route, screen: screen, local: local, type: Self.down(button), - button: button, clickState: clickState, subtype: 3, group: group, number: downNumber, flags: flags + button: button, clickState: clickState, subtype: 3, group: group, number: downNumber, flags: flags, useSystemInput: useSystemInput ), up: mouseEvent( source: source, route: route, screen: screen, local: local, type: Self.up(button), - button: button, clickState: clickState, subtype: 3, group: group, number: upNumber, flags: flags + button: button, clickState: clickState, subtype: 3, group: group, number: upNumber, flags: flags, useSystemInput: useSystemInput ) ) } @@ -280,8 +291,12 @@ final class WindowPointerInput { private func mouseEvent( source: CGEventSource, route: WindowRoute, screen: CGPoint, local: WindowPoint, type: CGEventType, button: CGMouseButton, clickState: Int64, subtype: Int64, - group: Int64?, number: Int64? = nil, flags: CGEventFlags = [] + group: Int64?, number: Int64? = nil, flags: CGEventFlags = [], useSystemInput: Bool = false ) throws -> CGEvent { + if useSystemInput { + return try SystemPointerInput.event(type, source: source, at: screen, button: button, + group: group ?? 0, flags: flags, clickState: clickState) + } guard let event = CGEvent( mouseEventSource: source, mouseType: type, mouseCursorPosition: screen, mouseButton: button ) else { diff --git a/packages/experimental/cua-macos/native/generate-protocol.ts b/packages/experimental/cua-macos/native/generate-protocol.ts index 081a7d9e72..9da5feb638 100644 --- a/packages/experimental/cua-macos/native/generate-protocol.ts +++ b/packages/experimental/cua-macos/native/generate-protocol.ts @@ -15,14 +15,16 @@ export function renderNativeProtocol(): { json: string; swift: string } { maxElements: z.number().int().min(1).max(AX_TRAVERSAL_MAX.maxElements), maxDepth: z.number().int().min(1).max(AX_TRAVERSAL_MAX.maxDepth), } - const systemPointer = { useSystemPointer: z.boolean().optional() } + const systemInput = { useSystemInput: z.boolean().optional() } const { fields, enums, json } = nativeProtocol({ getState: NativeResourceParameters.getState.extend(traversal), paste: NativeResourceParameters.paste.extend(traversal), - sendKeyEvent: z.object({ runId: z.string().min(1) }), - mouseMove: z.object(systemPointer), - toggleMouse: z.object(systemPointer), - drag: NativeResourceParameters.drag.extend(systemPointer), + sendKeyEvent: z.object({ runId: z.string().min(1), ...systemInput }), + pressKey: z.object(systemInput), + click: z.object(systemInput), + mouseMove: z.object(systemInput), + toggleMouse: z.object(systemInput), + drag: NativeResourceParameters.drag.extend(systemInput), requestPermission: PermissionGuideParameters, openPermissionSettings: PermissionSettingsParameters, }, [z.object({ method: z.literal('releaseHeldKeys'), params: z.object({ runId: z.string().min(1) }).strict(), diff --git a/packages/experimental/cua-macos/native/protocol.schema.json b/packages/experimental/cua-macos/native/protocol.schema.json index 10e5695f8e..90d4a391f6 100644 --- a/packages/experimental/cua-macos/native/protocol.schema.json +++ b/packages/experimental/cua-macos/native/protocol.schema.json @@ -487,7 +487,7 @@ "up" ] }, - "useSystemPointer": { + "useSystemInput": { "type": "boolean" } }, @@ -539,7 +539,7 @@ "minLength": 1, "description": "Opaque string defined by the platform provider, valid for at least the lifetime of one snapshot." }, - "useSystemPointer": { + "useSystemInput": { "type": "boolean" } }, @@ -573,7 +573,7 @@ "type": "number", "minimum": 0 }, - "useSystemPointer": { + "useSystemInput": { "type": "boolean" } }, @@ -668,6 +668,9 @@ "type": "integer", "minimum": 0, "maximum": 9007199254740991 + }, + "useSystemInput": { + "type": "boolean" } }, "required": [ @@ -741,6 +744,9 @@ "type": "integer", "minimum": 0, "maximum": 9007199254740991 + }, + "useSystemInput": { + "type": "boolean" } }, "required": [ @@ -1049,6 +1055,9 @@ "items": { "type": "string" } + }, + "useSystemInput": { + "type": "boolean" } }, "required": [ @@ -1100,6 +1109,9 @@ "runId": { "type": "string", "minLength": 1 + }, + "useSystemInput": { + "type": "boolean" } }, "required": [ @@ -1255,7 +1267,7 @@ "minimum": 1, "maximum": 240 }, - "useSystemPointer": { + "useSystemInput": { "type": "boolean" } }, diff --git a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py index 8ef081b5e9..b78282a04f 100644 --- a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py +++ b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py @@ -105,7 +105,7 @@ def check_toggle_mouse(helper, owner, state_file, executable): socket = Path(f"/tmp/dsh-cua-{os.getuid()}/{key}.sock") for index, (button, down, moved, up) in enumerate([("left", 1, 6, 2), ("right", 3, 7, 4), ("middle", 25, 27, 26)]): assert cursor(*inside) == inside - params = {**window, "mouseButton": button, "useSystemPointer": True} + params = {**window, "mouseButton": button, "useSystemInput": True} count = len(json.loads(state_file.read_text())["events"]) call("toggleMouse", {**params, "direction": "down"}) try: @@ -113,7 +113,7 @@ def check_toggle_mouse(helper, owner, state_file, executable): assert state["events"][-1]["pressedButtons"] & (1 << index), state call("toggleMouse", {**params, "direction": "down"}, "INPUT_BUSY") call("mouseMove", {**window, "x": inside[0] - bounds["x"] + 15, "y": inside[1] - bounds["y"], - "useSystemPointer": True}) + "useSystemInput": True}) state = wait_for_state(state_file, lambda s: len(s["events"]) >= count + 2) assert state["events"][-1]["type"] == moved, state assert cursor() == [inside[0] + 15, inside[1]] @@ -145,7 +145,7 @@ def check_system_drag(helper, owner, window, point, state_file): call("getState", {**window, "maxElements": 300, "maxDepth": 20}) count = len(json.loads(state_file.read_text())["events"]) params = {**window, "fromX": point["x"], "fromY": point["y"], "toX": point["x"] + 80, - "toY": point["y"] + 20, "durationMs": 400, "steps": 1, "modifiers": ["shift"], "useSystemPointer": True} + "toY": point["y"] + 20, "durationMs": 400, "steps": 1, "modifiers": ["shift"], "useSystemInput": True} call("drag", params, "FOREGROUND_REQUIRED") assert len(json.loads(state_file.read_text())["events"]) == count call("activate", owner) diff --git a/packages/experimental/cua-macos/native/tests/e2e.py b/packages/experimental/cua-macos/native/tests/e2e.py index 85e4ab2084..f9dfe065bc 100644 --- a/packages/experimental/cua-macos/native/tests/e2e.py +++ b/packages/experimental/cua-macos/native/tests/e2e.py @@ -281,7 +281,7 @@ def main(): assert (after["cursorChanges"], after["hoverVisible"]) == (before["cursorChanges"], before["hoverVisible"]), after def mouse_move(target): - result = call("mouseMove", target if args.alternate_hover else {**target, "useSystemPointer": True}) + result = call("mouseMove", target if args.alternate_hover else {**target, "useSystemInput": True}) if not args.alternate_hover: assert result["hoverRoute"] == "system-pointer" and result["systemPointerMoved"] is True, result if args.alternate_hover: @@ -316,7 +316,7 @@ def main(): mouse_move(target) wait_state(lambda actual: actual["hoverVisible"], "Input-transparent overlay blocked hover") before = cycle_overlay(2) - call("mouseMove", {**target, "useSystemPointer": True}, "FOREGROUND_REQUIRED") + call("mouseMove", {**target, "useSystemInput": True}, "FOREGROUND_REQUIRED") after = wait_state(lambda actual: actual["cursorSamples"] >= before["cursorSamples"] + 2, "Pointer observation did not advance") assert after["cursorChanges"] == before["cursorChanges"], "Rejected hover moved the system pointer" @@ -327,7 +327,7 @@ def main(): if args.alternate_hover: state = call("getState", primary_params) child = button_target(state, "Use native hover details") - result = call("mouseMove", {**child, "windowId": primary["windowId"], "useSystemPointer": True}) + result = call("mouseMove", {**child, "windowId": primary["windowId"], "useSystemInput": True}) assert result["hoverRoute"] == "system-pointer" and result["systemPointerMoved"], result current = json.loads(state_path.read_text()) assert current["hoverVisible"] and current["defaultUIRequests"] == before["defaultUIRequests"], current diff --git a/packages/experimental/cua-macos/native/tests/electron_e2e.py b/packages/experimental/cua-macos/native/tests/electron_e2e.py index d8acffbe9d..646047814f 100644 --- a/packages/experimental/cua-macos/native/tests/electron_e2e.py +++ b/packages/experimental/cua-macos/native/tests/electron_e2e.py @@ -136,7 +136,7 @@ def main(): call('mouseMove', {**owner, 'snapshotId': state['snapshotId'], 'elementId': trigger['elementId'], 'x': 0}, 'INVALID_ARGUMENT') hover_target = {**owner, 'snapshotId': state['snapshotId'], 'elementId': trigger['elementId']} call('mouseMove', hover_target, 'HOVER_UNAVAILABLE') - call('mouseMove', {**hover_target, 'useSystemPointer': True}) + call('mouseMove', {**hover_target, 'useSystemInput': True}) actual = wait_state(lambda actual: actual['popupOpen'], 'Hover did not reveal delayed information') assert actual['pointerDowns'] == baseline and actual['lastMove'] == {'buttons': 0, 'trusted': True}, actual state = observe() @@ -151,13 +151,13 @@ def main(): target = {**owner, 'windowId': window_id, 'x': bounds[0] + bounds[2] / 2 - window['bounds']['x'], 'y': bounds[1] + bounds[3] / 2 - window['bounds']['y']} - call('mouseMove', {**target, 'useSystemPointer': True}) + call('mouseMove', {**target, 'useSystemInput': True}) state = observe() assert 'Hover information' in state['tree'], 'Moving into the popup dismissed it' call('click', target) actual = wait_state(lambda actual: actual['popupClicks'] == expected_clicks, 'Popup action did not receive its click') assert actual['popupOpen'] and actual['pointerDowns'] == baseline + 1 and actual['popupClickTrusted'], actual - call('mouseMove', {**owner, 'windowId': window_id, 'x': 10, 'y': 40, 'useSystemPointer': True}) + call('mouseMove', {**owner, 'windowId': window_id, 'x': 10, 'y': 40, 'useSystemInput': True}) wait_state(lambda actual: not actual['popupOpen'], 'Leaving the hover region did not close it') hover_sequence() helper.eof() diff --git a/packages/experimental/cua-macos/native/tests/swift/SystemInputTests.swift b/packages/experimental/cua-macos/native/tests/swift/SystemInputTests.swift new file mode 100644 index 0000000000..c156f0b9be --- /dev/null +++ b/packages/experimental/cua-macos/native/tests/swift/SystemInputTests.swift @@ -0,0 +1,85 @@ +// Record synthesized events and desktop state queries without posting input to the user's desktop. +import CoreGraphics +import Darwin +import Testing +@testable import CuaNative + +@Test func systemModifiersPressKeysAndReleaseInReverseOrder() throws { + var events: [CGEvent] = [] + let input = SystemKeyboardInput(post: { events.append($0) }, keyState: { _ in false }, currentFlags: { [] }) + let release = try input.pressModifiers(["command", "shift", "cmd"], check: {}) + #expect(events.map { $0.getIntegerValueField(.keyboardEventKeycode) } == [55, 56]) + release() + release() + #expect(events.map { $0.getIntegerValueField(.keyboardEventKeycode) } == [55, 56, 56, 55]) + #expect(events.map(\.type) == [.flagsChanged, .flagsChanged, .flagsChanged, .flagsChanged]) + #expect(events.map { $0.flags.contains(.maskCommand) } == [true, true, true, false]) + #expect(events.map { $0.flags.contains(.maskShift) } == [false, true, false, false]) +} + +@Test func cancelledSystemModifierPressReleasesOnlyItsKeys() throws { + var events: [CGEvent] = [] + let input = SystemKeyboardInput(post: { events.append($0) }, keyState: { _ in false }, currentFlags: { [] }) + do { + _ = try input.pressModifiers(["command", "shift"], check: { + if !events.isEmpty { throw CancellationError() } + }) + Issue.record("Cancelled modifier press completed") + } catch { #expect(error is CancellationError) } + #expect(events.map { $0.getIntegerValueField(.keyboardEventKeycode) } == [55, 55]) + #expect(events.last?.flags.contains(.maskCommand) == false) +} + +@Test func systemModifiersRejectHeldOrInvalidKeysBeforePosting() throws { + let input = SystemKeyboardInput(post: { _ in Issue.record("Rejected modifier posted input") }, + keyState: { $0 == 56 }, currentFlags: { [] }) + #expect(throws: NativeFailure.self) { try input.pressModifiers(["command", "shift"], check: {}) } + #expect(throws: NativeFailure.self) { try input.pressModifiers(["command", "unknown"], check: {}) } +} + +@Test func systemShortcutUsesSystemEventsAndPreservesProcessDefault() throws { + var systemEvents: [CGEvent] = [] + var processEvents: [CGEvent] = [] + let system = SystemKeyboardInput(post: { systemEvents.append($0) }, keyState: { _ in false }, currentFlags: { [] }, foreground: { 42 }) + let keyboard = KeyboardInput(post: { event, pid in #expect(pid == 42); processEvents.append(event) }, textEventInterval: 0, system: system) + try keyboard.pressKey("s", modifiers: ["command", "shift"], to: 42, useSystemInput: true) + #expect(processEvents.isEmpty) + #expect(systemEvents.map { $0.getIntegerValueField(.keyboardEventKeycode) } == [55, 56, 1, 1, 56, 55]) + try keyboard.pressKey("s", modifiers: ["command"], to: 42) + #expect(processEvents.map { $0.getIntegerValueField(.keyboardEventKeycode) } == [55, 1, 1, 55]) + #expect(systemEvents.count == 6) +} + +@Test func systemShortcutReleasesAfterForegroundChanges() throws { + var events: [CGEvent] = [] + let system = SystemKeyboardInput(post: { events.append($0) }, keyState: { _ in false }, currentFlags: { [] }, + foreground: { events.isEmpty ? 42 : 99 }) + let keyboard = KeyboardInput(post: { _, _ in Issue.record("System shortcut used process delivery") }, textEventInterval: 0, system: system) + #expect(throws: NativeFailure.self) { try keyboard.pressKey("s", modifiers: ["command"], to: 42, useSystemInput: true) } + #expect(events.map { $0.getIntegerValueField(.keyboardEventKeycode) } == [55, 55]) + #expect(events.last?.flags.contains(.maskCommand) == false) +} + +@Test func systemDirectionalKeysReleaseThroughTheirRecordedRoute() throws { + let target = try NativePlatform.identity(getpid()) + var events: [CGEvent] = [] + var foreground = target.pid + let system = SystemKeyboardInput(post: { events.append($0) }, keyState: { _ in false }, currentFlags: { [] }, foreground: { foreground }) + let keyboard = KeyboardInput(post: { _, _ in Issue.record("System key used process delivery") }, textEventInterval: 0, system: system) + try keyboard.keyDown("shift", app: "app", run: "run", useSystemInput: true, recipient: { target }) + #expect(throws: NativeFailure.self) { try keyboard.keyUp("shift", app: "app", run: "run", recipientIfUnheld: { target }) } + foreground = 99 + #expect(try keyboard.keyUp("shift", app: "app", run: "run", useSystemInput: true, recipientIfUnheld: { target })) + foreground = target.pid + try keyboard.keyDown("w", app: "app", run: "run", useSystemInput: true, recipient: { target }) + foreground = 99 + try keyboard.releaseHeldKeys() + #expect(events.map { $0.getIntegerValueField(.keyboardEventKeycode) } == [56, 56, 13, 13]) +} + +@Test func systemClickEventsPreserveDoubleClickCount() throws { + let event = try SystemPointerInput.event(.leftMouseDown, source: nil, at: CGPoint(x: 3, y: 4), button: .left, + group: 7, flags: .maskShift, clickState: 2) + #expect(event.getIntegerValueField(.mouseEventClickState) == 2) + #expect(event.flags.contains(.maskShift)) +} diff --git a/packages/experimental/cua-macos/native/upstream.json b/packages/experimental/cua-macos/native/upstream.json index 24a19b9ce5..843681ca11 100644 --- a/packages/experimental/cua-macos/native/upstream.json +++ b/packages/experimental/cua-macos/native/upstream.json @@ -56,6 +56,7 @@ "Sources/CuaNative/SharedHelperProxy.swift", "Sources/CuaNative/SharedHelperRuntime.swift", "Sources/CuaNative/SharedHelperServer.swift", + "Sources/CuaNative/SystemKeyboardInput.swift", "Sources/CuaNative/TextSelection.swift", "Sources/CuaNative/WindowCapture.swift", "Sources/CuaNative/WindowGeometry.swift" diff --git a/packages/experimental/cua-macos/src/guidance.ts b/packages/experimental/cua-macos/src/guidance.ts index 7ef1486163..9d1d477489 100644 --- a/packages/experimental/cua-macos/src/guidance.ts +++ b/packages/experimental/cua-macos/src/guidance.ts @@ -5,25 +5,24 @@ import { COMMON_GUIDANCE } from '@deepseek-ai/dsh-cua/guidance' export const PLATFORM_GUIDANCE = 'macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. pressKey, click, and drag accept command, control (or ctrl), option (or alt), shift, and fn. pressKey also accepts cmd for command. For pointer input on a sheet, select its window ID with app.getWindow(id). For menu items outside a window, use app.invoke(id). findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action.' function operationGuidance(treeAdvice: string): string { - const mouseGuidance = 'Leave useSystemPointer unset for ordinary mouseMove, drag, and toggleMouse calls, even after approval. Prefer selectText for a supported text range and ordinary window-directed drag for a draggable control. If the effect is unclear, inspect the window before choosing another action. Request the system pointer only when the user explicitly asks for it or the intended effect requires it.' + const mouseGuidance = 'Leave useSystemInput unset for ordinary mouseMove, toggleMouse, click, drag, pressKey, and sendKeyEvent calls, even after approval. Prefer selectText for a supported text range and ordinary window-directed drag for a draggable control. If the effect is unclear, inspect the window before choosing another action. Request system input only when the user explicitly asks for it or the intended effect requires it.' const catalog = COMMON_GUIDANCE.replace('## Simulated mouse\n', `## Simulated mouse\n${mouseGuidance}\n\n`) const methodDetails = new Map([ ['cua.listApps', 'Each row represents one running process. To select one of several instances with the same name or bundle ID, pass String(row.pid) to cua.getApp.'], ['cua.findApps', 'Running installation matches include their process ID. Stopped matches have no pid.'], - ['sendKeyEvent', "Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients."], + ['sendKeyEvent', "Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. System input requires the selected app in the foreground for down; match useSystemInput on up, which releases the held key even after focus changes. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients."], ['getAccessibilityTree', `macOS accepts maxElements up to 100000 and maxDepth up to 512. If the tree is truncated, select a narrower window or raise the reported limit on the next read. ${treeAdvice} Use element ids from the file only while that observation is current.`], - ['mouseMove', 'With useSystemPointer omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again.'], - ['toggleMouse', 'Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemPointer: true on both down and up. Physical moves can then drag, including your own mouse movements. The turn ending or the connection closing releases a remaining system hold.'], - ['drag', 'Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control. An explicit system drag shares the session decision with mouseMove and holds the chosen button along the path in the unobscured foreground window.'], - ['click', 'click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying.'], + ['mouseMove', 'With useSystemInput omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again.'], + ['toggleMouse', 'Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemInput: true on both down and up. Physical moves can then drag, including your own mouse movements. The turn ending or the connection closing releases a remaining system hold.'], + ['pressKey', 'System input requires the selected foreground application and sends modifiers and the main key through the system keyboard queue, then releases them in reverse order.'], + ['drag', 'Omitting useSystemInput or passing false directs the drag to the window without asking for mouse control. System input requires an unobscured foreground target, presses the requested keyboard modifiers, and releases the mouse button before those modifiers, including on cancellation.'], + ['click', 'click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. With useSystemInput: true, the system pointer moves to the target and keyboard modifiers are pressed around the click, including release on cancellation. Verify the expected effect before typing or retrying.'], ]) return `${PLATFORM_GUIDANCE} ${catalog.replace(/^- ([\w.]+)\(.*$/gm, (entry, method: string) => { const detail = methodDetails.get(method) - const signature = method === 'drag' ? entry.replace('relative?: boolean }', 'relative?: boolean, useSystemPointer?: boolean }') - : method === 'toggleMouse' ? entry.replace("'up')", "'up', options?: { useSystemPointer?: boolean })") : entry - return detail ? `${signature} ${detail}` : signature + return detail ? `${entry} ${detail}` : entry })}` } diff --git a/packages/experimental/cua-macos/src/index.ts b/packages/experimental/cua-macos/src/index.ts index 87baa83eea..fc33708b92 100644 --- a/packages/experimental/cua-macos/src/index.ts +++ b/packages/experimental/cua-macos/src/index.ts @@ -14,7 +14,7 @@ import { GUIDANCE, PROGRAM_GUIDANCE } from './guidance.ts' export { GUIDANCE } from './guidance.ts' const CAPABILITIES: CuaStartupCapabilities = { - platform: 'macos', systemPointer: true, + platform: 'macos', systemInput: true, methods: [ 'activate', 'click', 'drag', 'findApps', 'getApp', 'getCapabilities', 'getState', 'invoke', 'listActions', 'listApps', 'listWindows', 'mouseMove', 'paste', 'performAction', 'pressKey', 'screenshot', 'scroll', diff --git a/packages/experimental/cua-macos/tests/guidance.spec.ts b/packages/experimental/cua-macos/tests/guidance.spec.ts index 6e774fae0c..f60b71b44b 100644 --- a/packages/experimental/cua-macos/tests/guidance.spec.ts +++ b/packages/experimental/cua-macos/tests/guidance.spec.ts @@ -1,7 +1,7 @@ /** Model-facing guidance lists the object API with platform availability and input constraints. */ import { expect, it } from 'vitest' import type { CuaApi, CuaApp, CuaSurface, CuaWindow } from '@deepseek-ai/dsh-cua/api' -import { COMMON_GUIDANCE, withSystemPointerGuidance } from '@deepseek-ai/dsh-cua/guidance' +import { COMMON_GUIDANCE, withSystemInputGuidance } from '@deepseek-ai/dsh-cua/guidance' import { GUIDANCE, PLATFORM_GUIDANCE, PROGRAM_GUIDANCE } from '../src/guidance.ts' const apiNames: Array = ['getCapabilities', 'listApps', 'findApps', 'getState', 'getApp'] @@ -35,16 +35,15 @@ it('prefixes concise platform guidance before the shared catalog', () => { }) it.each([GUIDANCE, PROGRAM_GUIDANCE])('explains when macOS mouse input needs a system-pointer prompt', (catalog) => { - const instructions = withSystemPointerGuidance(catalog) - expect(catalog.split('- mouseMove(')[0]).toContain('Leave useSystemPointer unset') - expect(instructions).toContain('Prefer an advertised accessibility action, a click on a visible control, or browser tools when possible.') - expect(instructions).toContain('The question interrupts the user.') - expect(instructions).toContain('Omitting the option or passing false uses the default hover route without prompting.') - expect(instructions).toContain("direction: 'down' | 'up', options?: { useSystemPointer?: boolean }") - expect(instructions).toContain('pass useSystemPointer: true on both down and up') - const drag = catalog.split('\n').find(line => line.startsWith('- drag(')) - expect(drag).toContain('useSystemPointer?: boolean') - expect(drag).toContain('Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control.') + const instructions = withSystemInputGuidance(catalog) + expect(catalog.split('- mouseMove(')[0]).toContain('Leave useSystemInput unset') + expect(instructions).toContain('The first explicit system input requests permission;') + expect(instructions).toContain('Omitting the option or passing false uses the provider default.') + expect(instructions).toContain("direction: 'down' | 'up', options?: { useSystemInput?: boolean }") + expect(instructions).toContain('pass useSystemInput: true on both down and up') + const drag = instructions.split('\n').find(line => line.startsWith('- drag(')) + expect(drag).toContain('useSystemInput?: boolean') + expect(drag).toContain('Omitting useSystemInput or passing false directs the drag to the window without asking for mouse control.') expect(COMMON_GUIDANCE).not.toContain('window-directed drag') }) @@ -58,7 +57,7 @@ it('states the macOS accessibility, keyboard, and mouse levels', () => { const sharedKeyEvent = COMMON_GUIDANCE.split('\n').find(line => line.startsWith('- sendKeyEvent(')) expect(sharedKeyEvent).toBeDefined() expect(GUIDANCE.split('\n').find(line => line.startsWith('- sendKeyEvent('))).toContain(sharedKeyEvent) - expect(pressKey).toBe(COMMON_GUIDANCE.split('\n').find(line => line.startsWith('- pressKey('))) + expect(pressKey).toContain(COMMON_GUIDANCE.split('\n').find(line => line.startsWith('- pressKey('))) expect(GUIDANCE).toContain('W down, D down, D up, W up') const hover = GUIDANCE.split('\n').find(line => line.startsWith('- mouseMove(')) for (const term of ['AXShowAlternateUI', 'AXShowDefaultUI', 'HOVER_UNAVAILABLE']) expect(hover).toContain(term) @@ -83,7 +82,7 @@ it('documents explicit mouse-button events immediately after mouseMove', () => { it.each([GUIDANCE, PROGRAM_GUIDANCE])('documents the default window release and the optional system hold', (catalog) => { const entry = catalog.split('\n').find(line => line.startsWith('- toggleMouse(')) expect(entry).toContain('By default the window receives the events, even a release outside it, and the system button stays up.') - expect(entry).toContain('pass useSystemPointer: true on both down and up') + expect(entry).toContain('pass useSystemInput: true on both down and up') }) it('enumerates every public method once in its catalog entry', () => { @@ -114,7 +113,7 @@ it('inlines discovery, restoration, and mouse-move return records', () => { for (const name of ['cua.getCapabilities', 'cua.listApps', 'cua.findApps', 'cua.getState', 'app.getWindows', 'app.show', 'window.show', 'mouseMove']) { expect(lines.find(line => line.startsWith(`- ${name}(`))).toMatch(/ -> \(?\{ /) } - expect(COMMON_GUIDANCE).toContain("{ platform: string, permissions: { accessibility: boolean, screenRecording: boolean }, appLevelAccessibility: boolean, systemPointer: boolean, keyboard: ('app' | 'window')[], sessionLocked: boolean | null, methods: string[], coordinateSpace: 'screenshot-pixels', browser: false }") + expect(COMMON_GUIDANCE).toContain("{ platform: string, permissions: { accessibility: boolean, screenRecording: boolean }, appLevelAccessibility: boolean, systemInput: boolean, keyboard: ('app' | 'window')[], sessionLocked: boolean | null, methods: string[], coordinateSpace: 'screenshot-pixels', browser: false }") expect(COMMON_GUIDANCE).toContain('{ id: string, displayName: string, isRunning: boolean, pid?: number }[]') expect(COMMON_GUIDANCE).toContain('{ id: string, displayName: string, path: string, isRunning: boolean, pid?: number }[]') expect(COMMON_GUIDANCE).toContain('getScreenshot() -> Image') @@ -191,3 +190,10 @@ it('documents explicit inspection and separate key arguments', () => { it('omits stale names and unrelated operations', () => { for (const stale of ['getAXState', 'emit', 'disableDiffing', 'performSecondaryAction', 'hover(', 'keyChord', 'window.typeText', 'window.pressKey', 'elementIndex', 'verified: false', 'browser tabs']) expect(GUIDANCE).not.toContain(stale) }) + +it('adds system-input selection to exactly the six supported methods', () => { + const catalog = withSystemInputGuidance(PROGRAM_GUIDANCE) + const selected = catalog.split('\n').filter(line => line.startsWith('- ') && line.split(' -> ')[0]?.includes('useSystemInput')) + .map(line => line.slice(2, line.indexOf('('))) + expect(selected).toEqual(['mouseMove', 'toggleMouse', 'click', 'drag', 'pressKey', 'sendKeyEvent']) +}) diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index ab57b77108..3f6188038f 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -87,7 +87,7 @@ vi.mock('@deepseek-ai/dsh-cua/native-client', async importOriginal => ({ })) const config = { - permissionPollIntervalMs: 1000, requireSystemPointerApproval: true, + permissionPollIntervalMs: 1000, requireSystemInputApproval: true, agentPreset: false, standaloneRunCode: CuaConfig({}).standaloneRunCode, helperPath: resolve('fixture-helper'), sourceSigning: 'ad-hoc', buildTimeoutMs: 300_000, timeoutMs: 10_000, connectTimeoutMs: 5000, screenshotTimeoutMs: 5000, axTimeoutMs: 3000, maxRequestBytes: 1024, maxResponseBytes: 4096, maxClipboardBytes: 8192, pasteReadTimeoutMs: 1000, maxAppMatches: 20, @@ -98,7 +98,7 @@ const { helperPath: _helperPath, ...automaticConfig } = config it('defaults to ad-hoc signing and requires a keychain path for certificate signing', () => { expect(NativeProvider.Config({}).sourceSigning).toBe('ad-hoc') - expect(NativeProvider.Config({}).requireSystemPointerApproval).toBe(true) + expect(NativeProvider.Config({}).requireSystemInputApproval).toBe(true) expect(NativeProvider.Config({ sourceSigning: 'ad-hoc' }).sourceSigning).toBe('ad-hoc') for (const sourceSigning of [{ identity: 'Apple Development: Example', keychain: '/keychains/custom.keychain-db' }, { identity: 'ABC123', keychain: '/keychains/custom.keychain-db' }]) { expect(NativeProvider.Config({ sourceSigning }).sourceSigning).toEqual(sourceSigning) @@ -439,7 +439,7 @@ it('merges startup capabilities into runtime native fields', async () => { native.request.mockResolvedValueOnce(runtime) const result = await f.execute('getCapabilities') expect(result.isError).toBe(false) - expect(result.value).toEqual({ ...runtime, platform: 'macos', systemPointer: true, appLevelAccessibility: true, keyboard: ['app'], browser: false, + expect(result.value).toEqual({ ...runtime, platform: 'macos', systemInput: true, appLevelAccessibility: true, keyboard: ['app'], browser: false, coordinateSpace: 'screenshot-pixels', methods: [ 'activate', 'click', 'drag', 'findApps', 'getApp', 'getCapabilities', 'getState', 'invoke', 'listActions', 'listApps', 'listWindows', 'mouseMove', 'paste', 'performAction', 'pressKey', 'screenshot', 'scroll', @@ -1204,16 +1204,16 @@ it('routes permission actions through the macOS provider with the Client languag }) const hoverTarget = { appHandle: 'app-one', snapshotId: 'snapshot', elementId: '0' } -const physicalHover = { ...hoverTarget, useSystemPointer: true } +const physicalHover = { ...hoverTarget, useSystemInput: true } async function hoverFixture(requireApproval = true) { const f = await setup() if (!requireApproval) { await f.provider.dispose() - await f.ctx.plugin(NativeProvider, { ...config, requireSystemPointerApproval: false }) + await f.ctx.plugin(NativeProvider, { ...config, requireSystemInputApproval: false }) } const questions = await f.ctx.plugin(UserQuestions) - const questionId = 'cua-mouse-control' + const questionId = 'cua-system-input' const approved = { answers: [{ id: questionId, selected: ['Allow for this session'] }] } const ask = vi.fn(async () => approved) f.ctx.on('user-questions/request', async ({ questions }) => questions[0]!.id === questionId ? ask() @@ -1244,23 +1244,23 @@ it('requires an explicit system-pointer request on every move and asks only once const pending = f.execute('mouseMove', physicalHover) await entered.promise expect(native.request).toHaveBeenCalledTimes(1) - expect(JSON.stringify((await f.execute('mouseMove', physicalHover)).content)).toContain('MOUSE_CONTROL_PENDING') + expect(JSON.stringify((await f.execute('mouseMove', physicalHover)).content)).toContain('SYSTEM_INPUT_PENDING') answer.resolve(f.approved) expect((await pending).isError).toBe(false) for (const [params, physical] of [ - [hoverTarget, false], [{ ...hoverTarget, useSystemPointer: false }, false], [physicalHover, true], + [hoverTarget, false], [{ ...hoverTarget, useSystemInput: false }, false], [physicalHover, true], ] as const) { expect((await f.execute('mouseMove', params)).isError).toBe(false) - expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...hoverTarget, useSystemPointer: physical }, expect.any(AbortSignal), expect.any(String)) + expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...hoverTarget, useSystemInput: physical }, expect.any(AbortSignal), expect.any(String)) } expect(native.request.mock.calls[1]?.[1]).toEqual(physicalHover) expect(f.ask).toHaveBeenCalledTimes(1) }) -it.each([true, false])('shares the mouse control decision for a system button with pointer movement (allow=%s)', async (allow) => { +it.each([true, false])('shares the system input decision for a system button with pointer movement (allow=%s)', async (allow) => { const f = await hoverFixture() const target = { appHandle: 'app-one', windowId: '7', mouseButton: 'left', direction: 'down' } - for (const params of [target, { ...target, useSystemPointer: false }]) { + for (const params of [target, { ...target, useSystemInput: false }]) { expect((await f.execute('toggleMouse', params)).isError).toBe(false) expect(native.request.mock.lastCall?.[1]).toEqual(target) } @@ -1268,23 +1268,23 @@ it.each([true, false])('shares the mouse control decision for a system button wi const answer = Promise.withResolvers() f.ask.mockImplementationOnce(() => answer.promise) native.request.mockClear() - const pending = f.execute('toggleMouse', { ...target, useSystemPointer: true }) + const pending = f.execute('toggleMouse', { ...target, useSystemInput: true }) try { await vi.waitFor(() => { expect(f.ask).toHaveBeenCalledOnce() }) expect(native.request).not.toHaveBeenCalled() } finally { - answer.resolve(allow ? f.approved : { answers: [{ id: 'cua-mouse-control', selected: ['Deny'] }] }) + answer.resolve(allow ? f.approved : { answers: [{ id: 'cua-system-input', selected: ['Deny'] }] }) } const results = [await pending, await f.execute('mouseMove', physicalHover), - await f.execute('toggleMouse', { ...target, direction: 'up', useSystemPointer: true })] + await f.execute('toggleMouse', { ...target, direction: 'up', useSystemInput: true })] if (allow) { expect(results.every(result => !result.isError)).toBe(true) - expect(native.request.mock.calls.map(([method, params]) => [method, params.useSystemPointer])) + expect(native.request.mock.calls.map(([method, params]) => [method, params.useSystemInput])) .toEqual([['toggleMouse', true], ['mouseMove', true], ['toggleMouse', true]]) f.handle.agent.session.append('turn/end', { turn: 1, reason: { kind: 'aborted', reason: { kind: 'user' } } }) expect(native.cleanup).toHaveBeenCalledWith('releaseSystemButton', {}) } else { - for (const result of results) expect(JSON.stringify(result.content)).toContain('MOUSE_CONTROL_DENIED') + for (const result of results) expect(JSON.stringify(result.content)).toContain('SYSTEM_INPUT_DENIED') expect(native.request).not.toHaveBeenCalled() } expect(f.ask).toHaveBeenCalledOnce() @@ -1297,11 +1297,11 @@ it('reports a failed turn-end button release once and forgets the hold', async ( const warn = vi.spyOn(f.provider.ctx.logger, 'warn').mockImplementation(() => {}) onTestFinished(() => { warn.mockRestore() }) expect((await f.execute('toggleMouse', { appHandle: 'app-one', windowId: '7', mouseButton: 'left', - direction: 'down', useSystemPointer: true })).isError).toBe(false) + direction: 'down', useSystemInput: true })).isError).toBe(false) const session = f.handle.agent.session session.append('turn/end', { turn: 1, reason: { kind: 'aborted', reason: { kind: 'user' } } }) await vi.waitFor(() => { - expect(warn).toHaveBeenCalledWith('Could not release system mouse input at turn end: %s', failure) + expect(warn).toHaveBeenCalledWith('Could not release system input at turn end: %s', failure) }) session.append('turn/end', { turn: 2, reason: { kind: 'completed' } }) expect(native.cleanup).toHaveBeenCalledExactlyOnceWith('releaseSystemButton', {}) @@ -1310,7 +1310,7 @@ it('reports a failed turn-end button release once and forgets the hold', async ( it('leaves button release to disconnect when application access was revoked before turn end', async () => { const f = await hoverFixture() expect((await f.execute('toggleMouse', { appHandle: 'app-one', windowId: '7', mouseButton: 'left', - direction: 'down', useSystemPointer: true })).isError).toBe(false) + direction: 'down', useSystemInput: true })).isError).toBe(false) await f.ctx.cuaAccess.revoke('a'.repeat(64) as Parameters[0]) expect(native.dispose).toHaveBeenCalled() f.handle.agent.session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) @@ -1323,22 +1323,22 @@ it.each([true, false])('asks before a system drag and shares the session decisio native.request.mockResolvedValueOnce({ appHandle: target.appHandle, windowId: null, snapshotId: 's', tree: '', truncated: false, windows: [{ windowId: '7', appName: 'Fixture', title: '', bounds: imageMetadata.bounds, isOnScreen: true, onCurrentSpace: true }] }) await f.execute('getState', { appHandle: target.appHandle }) - if (!allow) f.ask.mockResolvedValue({ answers: [{ id: 'cua-mouse-control', selected: ['Deny'] }] }) + if (!allow) f.ask.mockResolvedValue({ answers: [{ id: 'cua-system-input', selected: ['Deny'] }] }) native.request.mockClear() - const drag = await f.execute('drag', { ...target, useSystemPointer: true }) + const drag = await f.execute('drag', { ...target, useSystemInput: true }) const hover = await f.execute('mouseMove', physicalHover) expect(f.ask).toHaveBeenCalledTimes(1) if (allow) { expect(drag.isError).toBe(false) expect(hover.isError).toBe(false) - expect(native.request.mock.calls.map(([method, params]) => [method, params.useSystemPointer])).toEqual([['drag', true], ['mouseMove', true]]) + expect(native.request.mock.calls.map(([method, params]) => [method, params.useSystemInput])).toEqual([['drag', true], ['mouseMove', true]]) } else { - for (const result of [drag, hover]) expect(JSON.stringify(result.content)).toContain('MOUSE_CONTROL_DENIED') + for (const result of [drag, hover]) expect(JSON.stringify(result.content)).toContain('SYSTEM_INPUT_DENIED') expect(native.request).not.toHaveBeenCalled() } - for (const params of [target, { ...target, useSystemPointer: false }]) { + for (const params of [target, { ...target, useSystemInput: false }]) { expect((await f.execute('drag', params)).isError).toBe(false) - expect(native.request.mock.lastCall?.[1]).not.toHaveProperty('useSystemPointer') + expect(native.request.mock.lastCall?.[1]).not.toHaveProperty('useSystemInput') } expect(f.ask).toHaveBeenCalledTimes(1) }) @@ -1349,12 +1349,12 @@ it('keeps refusals and grants separate and forgets a closed session on reopen', const { agent } = await f.ctx.agents.create({ sessionId: brandString('other-mouse-session') }) expect(JSON.stringify((await f.call(agent, 'mouseMove', physicalHover)).content)).toContain('APP_ACCESS_REQUIRED') await f.select(agent) - f.ask.mockResolvedValueOnce({ answers: [{ id: 'cua-mouse-control', selected: ['Deny'] }] }) + f.ask.mockResolvedValueOnce({ answers: [{ id: 'cua-system-input', selected: ['Deny'] }] }) native.request.mockClear() - for (let i = 0; i < 2; i++) expect(JSON.stringify((await f.call(agent, 'mouseMove', physicalHover)).content)).toContain('MOUSE_CONTROL_DENIED') + for (let i = 0; i < 2; i++) expect(JSON.stringify((await f.call(agent, 'mouseMove', physicalHover)).content)).toContain('SYSTEM_INPUT_DENIED') expect(native.request).not.toHaveBeenCalled() expect((await f.call(agent, 'mouseMove', hoverTarget)).isError).toBe(false) - expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...hoverTarget, useSystemPointer: false }, expect.any(AbortSignal), expect.any(String)) + expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...hoverTarget, useSystemInput: false }, expect.any(AbortSignal), expect.any(String)) expect((await f.execute('mouseMove', physicalHover)).isError).toBe(false) expect(native.request).toHaveBeenLastCalledWith('mouseMove', physicalHover, expect.any(AbortSignal), expect.any(String)) const sessionId = f.handle.agent.id @@ -1362,7 +1362,7 @@ it('keeps refusals and grants separate and forgets a closed session on reopen', const reopened = await f.ctx.agents.create({ sessionId }) await f.select(reopened.agent) expect((await f.call(reopened.agent, 'mouseMove', hoverTarget)).isError).toBe(false) - expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...hoverTarget, useSystemPointer: false }, expect.any(AbortSignal), expect.any(String)) + expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...hoverTarget, useSystemInput: false }, expect.any(AbortSignal), expect.any(String)) expect((await f.call(reopened.agent, 'mouseMove', physicalHover)).isError).toBe(false) expect(f.ask).toHaveBeenCalledTimes(3) }) @@ -1387,7 +1387,7 @@ it('revalidates window coordinates after the user answers', async () => { await f.execute('listWindows', { appHandle: 'app-one' }) return f.approved }) - const result = await f.execute('mouseMove', { appHandle: 'app-one', windowId: '7', x: 500, y: 500, relative: true, useSystemPointer: true }) + const result = await f.execute('mouseMove', { appHandle: 'app-one', windowId: '7', x: 500, y: 500, relative: true, useSystemInput: true }) expect(JSON.stringify(result.content)).toContain('STALE_SNAPSHOT') expect(native.request.mock.calls.map(([name]) => name)).toEqual(['listWindows', 'listWindows']) }) @@ -1395,7 +1395,7 @@ it('revalidates window coordinates after the user answers', async () => { it('drops dismissal, aborted answers and missing human answerers without allowing input', async () => { const f = await hoverFixture() f.ask.mockRejectedValueOnce(new UserQuestionError('dismissed', 'ASK_CANCELLED')) - expect(JSON.stringify((await f.execute('mouseMove', physicalHover)).content)).toContain('MOUSE_APPROVAL_CANCELLED') + expect(JSON.stringify((await f.execute('mouseMove', physicalHover)).content)).toContain('SYSTEM_INPUT_APPROVAL_CANCELLED') f.ask.mockRejectedValueOnce(new UserQuestionError('The answer channel disconnected', 'ASK_ABORTED')) expect(JSON.stringify((await f.execute('mouseMove', physicalHover)).content)).toContain('The answer channel disconnected') const controller = new AbortController() @@ -1408,14 +1408,14 @@ it('drops dismissal, aborted answers and missing human answerers without allowin await f.ctx.plugin(NativeProvider, config) await f.select() await f.questions.dispose() - expect(JSON.stringify((await f.execute('mouseMove', physicalHover)).content)).toContain('MOUSE_APPROVAL_UNAVAILABLE') + expect(JSON.stringify((await f.execute('mouseMove', physicalHover)).content)).toContain('SYSTEM_INPUT_APPROVAL_UNAVAILABLE') }) it('allows only the explicitly requested physical move when approval is disabled', async () => { const f = await hoverFixture(false) for (const [target, expected] of [[hoverTarget, false], [physicalHover, true], [hoverTarget, false]] as const) { expect((await f.execute('mouseMove', target)).isError).toBe(false) - expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...hoverTarget, useSystemPointer: expected }, expect.any(AbortSignal), expect.any(String)) + expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...hoverTarget, useSystemInput: expected }, expect.any(AbortSignal), expect.any(String)) } expect(f.ask).not.toHaveBeenCalled() }) @@ -1431,48 +1431,63 @@ it.each([true, false])('rejects a delegated pointer move before asking or dispat selectAnswer.mockClear() native.request.mockClear() const refused = await f.call(agent, 'mouseMove', physicalHover) - expect(JSON.stringify(refused.content)).toContain('MOUSE_CONTROL_UNAVAILABLE') + expect(JSON.stringify(refused.content)).toContain('SYSTEM_INPUT_UNAVAILABLE') expect(selectAnswer).not.toHaveBeenCalled() expect(f.ask).not.toHaveBeenCalled() expect(native.request).not.toHaveBeenCalled() }) -it.each([true, false])('uses the declared systemPointer capability for a non-macOS provider (%s)', async (systemPointer) => { +it.each([true, false])('uses the declared systemInput capability for a non-macOS provider (%s)', async (systemInput) => { const f = await setup() await f.provider.dispose() await f.ctx.plugin({ name: 'fixture-window-provider', inject: NativeProvider.inject, apply(ctx: Context) { installCua(ctx, CuaConfig(config), { helperPath: config.helperPath, createChannel: native.connect, getGuidance: () => COMMON_GUIDANCE, permissionParameters: () => ({}), - capabilities: { platform: 'fixture', methods: ['getApp', 'getCapabilities', 'mouseMove'], systemPointer, + capabilities: { platform: 'fixture', methods: ['getApp', 'getCapabilities', 'mouseMove'], systemInput, appLevelAccessibility: true, keyboard: ['app'], coordinateSpace: 'screenshot-pixels', browser: false }, }) } }) - native.request.mockResolvedValueOnce({ systemPointer: !systemPointer }) - expect((await f.execute('getCapabilities')).value).toMatchObject({ platform: 'fixture', systemPointer }) + native.request.mockResolvedValueOnce({ systemInput: !systemInput }) + expect((await f.execute('getCapabilities')).value).toMatchObject({ platform: 'fixture', systemInput }) const sections = (await f.ctx.systemPrompt.assemble({ scope: f.handle.agent })).sections const guidance = sections.find(section => section.name === 'computer-use:dsh-cua')!.text - expect(guidance.includes('relative?: boolean, useSystemPointer?: boolean')).toBe(systemPointer) - expect(guidance.includes('The question interrupts the user')).toBe(systemPointer) - expect(JSON.stringify(f.ctx.tools.get('cua', f.handle.agent)!.parameters).includes('useSystemPointer')).toBe(systemPointer) + expect(guidance.includes('relative?: boolean, useSystemInput?: boolean')).toBe(systemInput) + expect(guidance.includes('The question interrupts the user')).toBe(systemInput) + expect(JSON.stringify(f.ctx.tools.get('cua', f.handle.agent)!.parameters).includes('useSystemInput')).toBe(systemInput) await selectApplication(f) native.request.mockClear() const answer = vi.spyOn(f.ctx.userQuestions, 'ask').mockResolvedValue({ - answers: [{ id: 'cua-mouse-control', selected: ['Allow for this session'] }], + answers: [{ id: 'cua-system-input', selected: ['Allow for this session'] }], }) - if (!systemPointer) { - const denied = await f.execute('drag', { appHandle: 'app-one', windowId: '7', fromX: 1, fromY: 1, toX: 2, toY: 2, useSystemPointer: true }) + if (!systemInput) { + const denied = await f.execute('drag', { appHandle: 'app-one', windowId: '7', fromX: 1, fromY: 1, toX: 2, toY: 2, useSystemInput: true }) expect(denied.isError).toBe(true) - expect(JSON.stringify(denied.content)).toContain('useSystemPointer') + expect(JSON.stringify(denied.content)).toContain('useSystemInput') expect(native.request).not.toHaveBeenCalled() expect(answer).not.toHaveBeenCalled() } const physical = await f.execute('mouseMove', physicalHover) - expect(physical.isError).toBe(!systemPointer) - expect(answer).toHaveBeenCalledTimes(systemPointer ? 1 : 0) - if (systemPointer) expect(native.request).toHaveBeenLastCalledWith('mouseMove', physicalHover, expect.any(AbortSignal), expect.any(String)) + expect(physical.isError).toBe(!systemInput) + expect(answer).toHaveBeenCalledTimes(systemInput ? 1 : 0) + if (systemInput) expect(native.request).toHaveBeenLastCalledWith('mouseMove', physicalHover, expect.any(AbortSignal), expect.any(String)) else expect(native.request).not.toHaveBeenCalled() expect((await f.execute('mouseMove', hoverTarget)).isError).toBe(false) - expect(native.request).toHaveBeenLastCalledWith('mouseMove', systemPointer ? { ...hoverTarget, useSystemPointer: false } : hoverTarget, + expect(native.request).toHaveBeenLastCalledWith('mouseMove', systemInput ? { ...hoverTarget, useSystemInput: false } : hoverTarget, expect.any(AbortSignal), expect.any(String)) }) + +it.each([true, false])('shares approval between system clicks and keyboard chords (allow=%s)', async (allow) => { + const f = await hoverFixture() + f.ask.mockResolvedValue(allow ? f.approved : { answers: [{ id: 'cua-system-input', selected: ['Deny'] }] }) + const click = { ...hoverTarget, modifiers: ['shift'], useSystemInput: true } + const chord = { appHandle: 'app-one', key: 's', modifiers: ['command'], useSystemInput: true } + for (const [method, params] of [['click', click], ['pressKey', chord]] as const) { + const result = await f.execute(method, params) + expect(result.isError === true).toBe(!allow) + if (allow) expect(native.request).toHaveBeenLastCalledWith(method, params, expect.any(AbortSignal), expect.any(String)) + else expect(JSON.stringify(result.content)).toContain('SYSTEM_INPUT_DENIED') + } + expect(f.ask).toHaveBeenCalledTimes(1) + if (!allow) expect(native.request).not.toHaveBeenCalled() +}) diff --git a/packages/experimental/cua-windows/README.i18n.yaml b/packages/experimental/cua-windows/README.i18n.yaml index 1479fbb051..b3e59d7e4f 100644 --- a/packages/experimental/cua-windows/README.i18n.yaml +++ b/packages/experimental/cua-windows/README.i18n.yaml @@ -45,8 +45,8 @@ en: db3e2957041fafbb zh: 34f953887dff37f7 /deepseek-ai-dsh-cua-windows/known-limitations-and-deferred-work: - en: 93e47def8054cd3f - zh: 20c19872c775ea98 + en: 68a4a406d55758f3 + zh: 53467eaf88fddb94 /deepseek-ai-dsh-cua-windows/known-limitations-and-deferred-work/dev-note: en: 0a1253c6f7b5e8b9 zh: 9f56528562c7c914 diff --git a/packages/experimental/cua-windows/README.md b/packages/experimental/cua-windows/README.md index 1c1fb6959b..1cf5733c77 100644 --- a/packages/experimental/cua-windows/README.md +++ b/packages/experimental/cua-windows/README.md @@ -79,7 +79,7 @@ Inspected results append to model history. Retaining an App, Window, or returned - The npm package omits the Windows helper. Use the [standalone ZIP on x64 or a matching build on ARM64](#setup). -- Hover, click, scroll and drag use the system pointer. `requireSystemPointerApproval` does not prompt separately for Windows pointer operations. +- Hover, click, scroll and drag use the system pointer. `requireSystemInputApproval` does not prompt separately for Windows pointer operations. - Drag checks the topmost window only at its starting point. An overlay from another application along the path or at the destination can receive the drop even while the selected window stays in the foreground. - The helper does not check each key or button release during cleanup. If an input remains held after a failure, release it manually before continuing. - Helper identity hashes only the exe. Different DLLs with the same apphost can reuse the old service. Stop Hosts using the same output directory before rebuilding to avoid locked files. diff --git a/packages/experimental/cua-windows/README.zh.md b/packages/experimental/cua-windows/README.zh.md index b57a4bd438..c520271405 100644 --- a/packages/experimental/cua-windows/README.zh.md +++ b/packages/experimental/cua-windows/README.zh.md @@ -79,7 +79,7 @@ kind: "package-reference" - 通过 npm 安装的包不含 Windows helper。x64 可使用独立 ZIP,ARM64 需要对应架构的构建产物,见[配置说明](#setup)。 -- 悬停、点击、滚动和拖拽使用系统指针。`requireSystemPointerApproval` 不会为 Windows 操作弹出单独的指针授权提示。 +- 悬停、点击、滚动和拖拽使用系统指针。`requireSystemInputApproval` 不会为 Windows 操作弹出单独的指针授权提示。 - 拖拽只检查起点处最上层的窗口。若其他应用遮住路径或终点,即使目标仍在前台,也可能把内容拖到其他应用。 - 清理输入时,helper 不检查每个按键或鼠标按钮的释放结果。操作失败后如有按键或按钮仍处于按下状态,请先手动释放。 - helper 的身份摘要只覆盖 exe。同一 apphost 搭配不同 DLL 时可能复用旧服务。重新构建前请先关闭使用同一输出目录的 Host,避免文件被占用。 diff --git a/packages/experimental/cua-windows/tests/loader-composition.spec.ts b/packages/experimental/cua-windows/tests/loader-composition.spec.ts index e90acbbf49..5bcdc13377 100644 --- a/packages/experimental/cua-windows/tests/loader-composition.spec.ts +++ b/packages/experimental/cua-windows/tests/loader-composition.spec.ts @@ -30,24 +30,24 @@ it.skipIf(process.platform !== 'win32')('loads the Windows provider and rejects expect(ctx.tools.get('cua', agent)).toBeDefined() const prompt = await ctx.systemPrompt.assemble({ scope: agent }) expect(prompt.sections.find(section => section.name === 'computer-use:dsh-cua')?.text).toContain('Windows:') - expect(prompt.sections.find(section => section.name === 'computer-use:dsh-cua')?.text).not.toContain('useSystemPointer') + expect(prompt.sections.find(section => section.name === 'computer-use:dsh-cua')?.text).not.toContain('useSystemInput') const toggleMouse = prompt.sections.find(section => section.name === 'computer-use:dsh-cua')?.text .split('\n').find(line => line.startsWith('- toggleMouse(')) expect(toggleMouse).toContain("toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult") expect(toggleMouse).toContain("Release held buttons explicitly with 'up'; the opposite event is not sent automatically.") expect(toggleMouse).toContain('press or release the specified mouse button at the current pointer position without moving it.') expect(toggleMouse).not.toContain('Not implemented') - expect(JSON.stringify(ctx.tools.get('cua', agent)!.parameters)).not.toContain('useSystemPointer') + expect(JSON.stringify(ctx.tools.get('cua', agent)!.parameters)).not.toContain('useSystemInput') const batch = await ctx.tools.execute({ agent, signal: new AbortController().signal, calls: [{ type: 'tool-call', id: brandString('invalid-window'), name: 'cua', arguments: JSON.stringify({ method: 'screenshot', params: { appHandle: 'app', windowId: 7 } }), }, { type: 'tool-call', id: brandString('unsupported-pointer'), name: 'cua', arguments: JSON.stringify({ method: 'drag', params: { appHandle: 'app', windowId: '7', fromX: 1, fromY: 1, - toX: 2, toY: 2, useSystemPointer: true } }), + toX: 2, toY: 2, useSystemInput: true } }), }] }) expect(batch.results[1]?.result.isError).toBe(true) - expect(JSON.stringify(batch.results[1]?.result.content)).toContain('useSystemPointer') + expect(JSON.stringify(batch.results[1]?.result.content)).toContain('useSystemInput') expect(batch.results[0]?.result.isError).toBe(true) expect(JSON.stringify(batch.results[0]?.result.content)).toContain('string') await entry.fiber.dispose() diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index 3a4ec748f2..e89f6129d7 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -15,14 +15,14 @@ en: 5db4d4fea25493b9 zh: 65ab64fc24eb0d09 /deepseek-ai-dsh-cua/use-this-package: - en: a7759cc0ce7f405a - zh: 1c7f6f11751438ec + en: caa2d68fccfaa4c7 + zh: 43fde2ee72cdc051 /deepseek-ai-dsh-cua/use-this-package/permission-controls: en: 3f638a4a76023fc5 zh: 515aeb5de6ae5b33 /deepseek-ai-dsh-cua/understand-the-implementation: - en: c9fc9c1fb5a72154 - zh: a234881ef8e03761 + en: aa21cacd5740f396 + zh: 228b7f860953832b /deepseek-ai-dsh-cua/further-exploration: en: c174fb5a00ea3681 zh: 039340042676881d diff --git a/packages/experimental/cua/README.md b/packages/experimental/cua/README.md index a4a08df9e7..233f9c4938 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -51,7 +51,7 @@ Application consent precedes launch, observation, capture, and input. Session ac Actions return a `dispatched` boolean; `mouseMove` also reports `hoverRoute` and `systemPointerMoved`, and `show()` adds `windowId` and `foregroundChanged`. Read fresh state to verify the result. Screenshots and pointer actions are available only on explicit window objects. Coordinate actions default to pixels in the latest returned screenshot; `relative: true` accepts integers from 0 to 999 after a successful AX observation covering the window or a screenshot. Selecting a window alone does not establish this observation. Values are divided by 1000 and scaled to the window dimensions, then clamped inside the window. The Host resolves attachment normalization and the selected model route’s image projection before returning the screenshot, then converts input to the provider’s native window coordinates. Resizing invalidates the screenshot mapping; `SCREENSHOT_REQUIRED` requires a new screenshot for absolute coordinates. Resizing rejects old coordinates with `WINDOW_CHANGED`; movement alone preserves window-local coordinates. -On providers with system-pointer support, `mouseMove`, `drag`, and `toggleMouse` share session mouse approval. Pass `{ useSystemPointer: true }` on each system mouse operation. +Providers with system-input support accept `useSystemInput` on `mouseMove`, `toggleMouse`, `click`, `drag`, `pressKey`, and `sendKeyEvent`. True requests system keyboard or mouse input; omission or false keeps the provider default. Keyboard options are the third argument of `pressKey(key, modifiers, options)` and `sendKeyEvent(key, direction, options)`. To hold a button across calls, use `win.toggleMouse('left', 'down')`, then explicitly call `win.toggleMouse('left', 'up')` on the same window. Left, right, and middle are supported. Each call sends one event at the current pointer position. @@ -82,7 +82,7 @@ The Host marker has no configurable fields; platform providers own native config ## Understand the implementation -Providers declaring `systemPointer: true` must support explicit `useSystemPointer: true` on `mouseMove`, `drag`, and `toggleMouse`. The operations share one session decision. CUA validates the tool arguments, asks for consent, and enforces the delegated-task restriction before calling the provider. The provider documents its default input routes. +Providers declaring `systemInput: true` implement explicit system input for all six methods, including keyboard modifiers around system clicks and drags. The shared executor uses `requireSystemInputApproval` for session consent, validates arguments, and rejects delegated system input before dispatch. Providers without this capability reject the option and receive no new native parameters. Permission responses identify their platform and report only the state that platform can observe. The shared page renders the controls those observations support. Before platform identification, it shows neutral observation and input rows without system actions. Native providers use the shared build lock and compiler cleanup. The macOS provider reads its signed application receipt after compilation completes under the same lock. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index fb6e21f8ef..1c94c4b89c 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -51,7 +51,7 @@ kind: "package-reference" 动作返回 `dispatched` 布尔值;`mouseMove` 还会返回 `hoverRoute` 和 `systemPointerMoved`,`show()` 还会返回 `windowId` 和 `foregroundChanged`。请读取新状态以验证结果。截图和指针操作只能通过显式窗口对象使用。坐标操作默认使用最近返回截图中的像素;成功读取覆盖该窗口的 AX 或取得截图后,传入 `relative: true` 可使用 0~999 的整数坐标。仅选择窗口不会建立该观察。数值除以 1000 后按窗口尺寸缩放,并限制在窗口内。Host 在返回截图前解析附件归一化和当前模型的图片缩放规则,再将输入换算为提供方的原生窗口坐标。窗口尺寸变化会使截图映射失效,绝对坐标遇到 `SCREENSHOT_REQUIRED` 时需要重新截图。窗口缩放后以 `WINDOW_CHANGED` 拒绝旧坐标;单纯移动窗口不改变窗口内坐标。 -支持系统指针的提供方在 `mouseMove`、`drag` 和 `toggleMouse` 之间共用会话鼠标授权。每次操作系统鼠标都要显式传 `{ useSystemPointer: true }`。 +支持系统输入的提供方允许 `mouseMove`、`toggleMouse`、`click`、`drag`、`pressKey` 和 `sendKeyEvent` 传入 `useSystemInput`。`true` 请求系统键鼠输入,省略或传 `false` 保留提供方的默认方式。`pressKey(key, modifiers, options)` 和 `sendKeyEvent(key, direction, options)` 的选项是第三个参数。 要在两次调用之间保持按下状态,可先调用 `win.toggleMouse('left', 'down')`,再对同一窗口调用 `win.toggleMouse('left', 'up')`。左键、右键和中键均可单独按下或松开。每次调用只在当前指针位置发送一个事件。 @@ -82,7 +82,7 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边 ## 理解实现 -提供方声明 `systemPointer: true` 后,`mouseMove`、`drag` 和 `toggleMouse` 均支持显式传入 `useSystemPointer: true`,三者共用一次会话授权。CUA 负责工具参数校验、授权提示和子代理限制,在检查应用访问权限及本次操作的授权后调用提供方。提供方负责说明各自的默认输入方式。 +声明 `systemInput: true` 的提供方必须支持上述六个方法的显式系统输入,包括系统点击和拖动期间的键盘修饰键。共通层使用 `requireSystemInputApproval` 控制会话授权,校验参数并拒绝子任务请求系统输入,再调用提供方。未声明此能力的提供方拒绝该选项,不接收新增原生参数。 权限响应标识所属平台,并且只报告该平台能够观察到的状态。共享页面显示这些观察结果支持的控件。平台尚未确认时显示通用观察和输入项,不提供系统操作。原生提供方共用编译锁和编译进程清理逻辑。macOS 提供方在锁内等待编译完成,再读取签名应用的构建回执。 diff --git a/packages/experimental/cua/src/api.ts b/packages/experimental/cua/src/api.ts index 8ea16f0a84..1cc514a80d 100644 --- a/packages/experimental/cua/src/api.ts +++ b/packages/experimental/cua/src/api.ts @@ -92,14 +92,21 @@ function createCuaObjects(call: ReturnType): { } function createCuaSurface( target: { appHandle: CuaAppHandle; windowId?: string }, + capabilities: CuaCapabilities, paramsFor: CuaScopeParams, requireAccessibility: () => void, requireKeyboard: () => void, ) { const scopedCall = (method: CuaOperation['method'], params: Record, options?: object) => call(method, paramsFor(params), options) - const action = async (method: CuaOperation['method'], params: Record) => - ActionResult.parse(await scopedCall(method, params)) + const action = async (method: CuaOperation['method'], params: Record, options?: object) => + ActionResult.parse(await scopedCall(method, params, options)) + function systemInputOptions(method: CuaOperation['method'], useSystemInput: boolean | undefined) { + if (useSystemInput !== undefined && !capabilities.systemInput) { + throw new Error(`${method} useSystemInput: not accepted for these arguments`) + } + return { useSystemInput } + } const elementParams = (): Record => ({ snapshotId: currentSnapshot(target.appHandle) }) const surface: CuaSurface = { async show() { return ShowResult.parse(await scopedCall('show', {})) }, @@ -154,30 +161,25 @@ function createCuaObjects(call: ReturnType): { ...options?.format === undefined ? {} : { format: options.format }, }) }, - async pressKey(key, modifiers = []) { + async pressKey(key, modifiers = [], options) { requireKeyboard() - return action('pressKey', { key, modifiers: [...modifiers] }) + return action('pressKey', { key, modifiers: [...modifiers] }, systemInputOptions('pressKey', options?.useSystemInput)) }, - async sendKeyEvent(key, direction) { + async sendKeyEvent(key, direction, options) { requireKeyboard() - return action('sendKeyEvent', { key, direction }) + return action('sendKeyEvent', { key, direction }, systemInputOptions('sendKeyEvent', options?.useSystemInput)) }, } - return { surface, call: scopedCall, action, elementParams } + return { surface, call: scopedCall, action, elementParams, systemInputOptions } } function createCuaWindow(appHandle: CuaAppHandle, windowId: string, capabilities: CuaCapabilities): CuaWindow { - const base = createCuaSurface({ appHandle, windowId }, + const base = createCuaSurface({ appHandle, windowId }, capabilities, params => ({ ...params, appHandle, windowId }), () => undefined, () => { if (!capabilities.keyboard.includes('window')) { throw new Error('Window-scoped keyboard input is not supported on current platform.') } }) - function systemPointerOptions(method: 'toggleMouse' | 'drag', useSystemPointer: boolean | undefined) { - if (useSystemPointer !== undefined && !capabilities.systemPointer) { - throw new Error(`${method} useSystemPointer: not accepted for these arguments`) - } - return { useSystemPointer } - } + return { ...base.surface, windowId, async getScreenshot() { @@ -190,6 +192,7 @@ function createCuaObjects(call: ReturnType): { return value as CuaProgramImage }, async mouseMove(targetPoint, options) { + base.systemInputOptions('mouseMove', options?.useSystemInput) const relative = options?.relative === undefined ? {} : { relative: options.relative } if (typeof targetPoint === 'string') { return HoverResult.parse(await base.call('mouseMove', { ...base.elementParams(), elementId: targetPoint, ...relative }, options)) @@ -198,7 +201,7 @@ function createCuaObjects(call: ReturnType): { return HoverResult.parse(await base.call('mouseMove', { ...coordinateParams(appHandle, windowId), x, y, ...relative }, options)) }, async toggleMouse(mouseButton, direction, options) { - return ActionResult.parse(await base.call('toggleMouse', { mouseButton, direction }, systemPointerOptions('toggleMouse', options?.useSystemPointer))) + return ActionResult.parse(await base.call('toggleMouse', { mouseButton, direction }, base.systemInputOptions('toggleMouse', options?.useSystemInput))) }, async click(targetPoint, options) { const mouseButton = options?.mouseButton ?? 'left' @@ -210,10 +213,10 @@ function createCuaObjects(call: ReturnType): { if (typeof targetPoint === 'string') { return base.action('click', { ...base.elementParams(), ...modifiers, ...hold, ...relative, elementId: targetPoint, ...mouseButton === 'left' ? {} : { mouseButton }, ...clickCount === 1 ? {} : { clickCount }, - }) + }, base.systemInputOptions('click', options?.useSystemInput)) } const [x, y] = targetPoint - return base.action('click', { ...coordinateParams(appHandle, windowId), x, y, mouseButton, clickCount, ...modifiers, ...hold, ...relative }) + return base.action('click', { ...coordinateParams(appHandle, windowId), x, y, mouseButton, clickCount, ...modifiers, ...hold, ...relative }, base.systemInputOptions('click', options?.useSystemInput)) }, async scroll(options) { if (options.deltaLinesX === 0 && options.deltaLinesY === 0) throw new Error('At least one scroll delta must be nonzero') @@ -229,12 +232,12 @@ function createCuaObjects(call: ReturnType): { ...options?.relative === undefined ? {} : { relative: options.relative }, ...options?.mouseButton === undefined ? {} : { mouseButton: options.mouseButton }, ...options?.modifiers === undefined ? {} : { modifiers: [...options.modifiers] }, - }, systemPointerOptions('drag', options?.useSystemPointer))) + }, base.systemInputOptions('drag', options?.useSystemInput))) }, } } function createCuaApp(appHandle: CuaAppHandle, capabilities: CuaCapabilities): CuaApp { - const base = createCuaSurface({ appHandle }, params => ({ ...params, appHandle }), () => { + const base = createCuaSurface({ appHandle }, capabilities, params => ({ ...params, appHandle }), () => { if (!capabilities.appLevelAccessibility) { throw new Error('Application-level accessibility is not supported on current platform; observe a window instead.') } diff --git a/packages/experimental/cua/src/config.ts b/packages/experimental/cua/src/config.ts index 1072932ea9..e7215645ad 100644 --- a/packages/experimental/cua/src/config.ts +++ b/packages/experimental/cua/src/config.ts @@ -39,7 +39,7 @@ export const CuaScreenshotTargetConfig: Schema = Sche /** Shared configuration fields extended by native platform providers. */ export const CuaConfigFields = { - requireSystemPointerApproval: Schema.boolean().default(true), + requireSystemInputApproval: Schema.boolean().default(true), agentPreset: Schema.union([Schema.string().min(1), Schema.const(false)]).default('ptc'), standaloneRunCode: CuaStandaloneRunCodeConfig.default({}), screenshotTarget: Schema.union([CuaScreenshotTargetConfig, Schema.const(undefined)]), diff --git a/packages/experimental/cua/src/guidance.ts b/packages/experimental/cua/src/guidance.ts index 5f5fb160c5..24da23764b 100644 --- a/packages/experimental/cua/src/guidance.ts +++ b/packages/experimental/cua/src/guidance.ts @@ -14,7 +14,7 @@ Signatures show resolved return values after await. ActionResult = { dispatched: Supported modifier names depend on the platform and the operation; see the platform guidance. Setup and discovery: -- cua.getCapabilities() -> { platform: string, permissions: { accessibility: boolean, screenRecording: boolean }, appLevelAccessibility: boolean, systemPointer: boolean, keyboard: ('app' | 'window')[], sessionLocked: boolean | null, methods: string[], coordinateSpace: 'screenshot-pixels', browser: false } — inspect reported permissions, sessionLocked, methods, and keyboard scopes without requesting permissions. +- cua.getCapabilities() -> { platform: string, permissions: { accessibility: boolean, screenRecording: boolean }, appLevelAccessibility: boolean, systemInput: boolean, keyboard: ('app' | 'window')[], sessionLocked: boolean | null, methods: string[], coordinateSpace: 'screenshot-pixels', browser: false } — inspect reported permissions, sessionLocked, methods, and keyboard scopes without requesting permissions. - cua.listApps() -> { id: string, displayName: string, isRunning: boolean, pid?: number }[] — list applications the provider exposes for selection with their current running state; pass the returned id unchanged to cua.getApp. - cua.findApps(query: string) -> { id: string, displayName: string, path: string, isRunning: boolean, pid?: number }[] — search installed applications, including stopped matches. - cua.getState() -> { apps: { id: string, displayName: string, isRunning: boolean, pid?: number }[], browsers: [] } — summarize the same provider discovery; this is not an accessibility observation. @@ -62,13 +62,22 @@ click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, a Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name.` /** - * Describe the system-pointer option for a provider that declares the capability. + * Describe the system-input option for a provider that declares the capability. * @param guidance Provider instructions including the shared operation catalog. * @returns The capability-specific signature and permission instructions. */ -export function withSystemPointerGuidance(guidance: string): string { - const signature = 'mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemPointer?: boolean })' - return `${guidance.replace(hoverSignature, signature)} +export function withSystemInputGuidance(guidance: string): string { + const methods = new Set(['mouseMove', 'toggleMouse', 'click', 'drag', 'pressKey', 'sendKeyEvent']) + const catalog = guidance.replace(/^- ([\w.]+)\(.*$/gm, (entry, method: string) => { + if (!methods.has(method)) return entry + const end = entry.indexOf(') -> ') + const signature = entry.slice(0, end) + const extended = signature.includes('options:') || signature.includes('options?:') + ? signature.replace(' }', ', useSystemInput?: boolean }') + : `${signature}, options?: { useSystemInput?: boolean }` + return extended + entry.slice(end) + }) + return `${catalog} -Only if the task cannot be completed without moving the user’s pointer, call await win.mouseMove(target, { useSystemPointer: true }). Prefer an advertised accessibility action, a click on a visible control, or browser tools when possible. The question interrupts the user. When approval is disabled an explicit move can act immediately. Pass true on every physical move, even after approval. Omitting the option or passing false uses the default hover route without prompting. Approval or refusal lasts until this session closes or DSH restarts. A refusal sends no input. If the user dismisses the request, ask again only if they request it. Wait for an outstanding request to finish. Subagents cannot request system mouse control.` +Pass useSystemInput: true only when the task requires system keyboard or mouse input. Omitting the option or passing false uses the provider default. The first explicit system input requests permission; approval or refusal lasts until this session closes or DSH restarts. Approval does not change later calls: pass true on each system operation. If the user dismisses the request, ask again only if they request it. Wait for an outstanding request to finish. Subagents cannot request system input.` } diff --git a/packages/experimental/cua/src/index.ts b/packages/experimental/cua/src/index.ts index 9226e32ad7..2eae5ea4dd 100644 --- a/packages/experimental/cua/src/index.ts +++ b/packages/experimental/cua/src/index.ts @@ -13,13 +13,13 @@ import type { ContentBlock } from '@deepseek-ai/dsh-llm' import type { JsonValue } from '@deepseek-ai/dsh-util-values' import { z } from 'zod' import { NativeClient, NativeError, type NativeClientConfig, type NativeChannelFactory } from './native-client.ts' -import { MouseControl } from './mouse-control.ts' -import { withSystemPointerGuidance } from './guidance.ts' +import { SystemInputControl } from './mouse-control.ts' +import { withSystemInputGuidance } from './guidance.ts' import { CuaPermissionStore } from './permission-store.ts' import { ApplicationAuthorizationResult, installCuaAccess } from './access.ts' import type { CuaApplicationGrant, CuaApplicationId, CuaSystemPermission } from './access-types.ts' import type { CuaAppHandle, CuaOperation, CuaStartupCapabilities } from './types.ts' -import { ApplicationIcon, AppResult, NativeScreenshotResult, Request, SystemPointerRequest, ScreenshotResult } from './protocol.ts' +import { ApplicationIcon, AppResult, NativeScreenshotResult, Request, SystemInputRequest, ScreenshotResult } from './protocol.ts' import { CuaConfigFields, type CuaScreenshotTargetConfig, type CuaStandaloneRunCodeConfig } from './config.ts' import { fixedScreenshotTarget, installCuaTools } from './tool-registration.ts' import { CuaCoordinates } from './coordinates.ts' @@ -37,8 +37,8 @@ export type { CuaPrograms } from './tool-registration.ts' /** Native executable and per-operation resource bounds. */ export interface CuaConfig { - /** Ask once per live Session before explicitly requested system-pointer operations. */ - requireSystemPointerApproval: boolean + /** Ask once per live Session before explicitly requested system keyboard or mouse input. */ + requireSystemInputApproval: boolean /** * Preset receiving raw cua; every other Agent, with or without a preset, receives cua_run_code while its * program services are available. False registers raw cua globally. @@ -207,11 +207,11 @@ export interface CuaBackend { */ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend): void { const { helperPath } = backend - const systemPointer = backend.capabilities.systemPointer === true - const mouseControl = systemPointer ? new MouseControl(ctx, config.requireSystemPointerApproval) : undefined - const requestSchema = systemPointer ? SystemPointerRequest : Request + const systemInput = backend.capabilities.systemInput === true + const systemInputControl = systemInput ? new SystemInputControl(ctx, config.requireSystemInputApproval) : undefined + const requestSchema = systemInput ? SystemInputRequest : Request const formatGuidance = (text: string): string => { - const instructions = systemPointer ? withSystemPointerGuidance(text) : text + const instructions = systemInput ? withSystemInputGuidance(text) : text return `${instructions}\n\nAX read defaults: maxElements=${config.maxElements}, maxDepth=${config.maxDepth}.\n\nMaximum click holdMs: ${config.maxClickHoldMs} ms.` } const guidance = formatGuidance(backend.getGuidance('raw')) @@ -275,18 +275,17 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) for (const result of [...await permissions, ...results, ...releases]) if (result.status === 'rejected') errors.push(result.reason) if (errors.length > 0) throw new AggregateError(errors, 'dsh-cua helper cleanup failed') } - const callNative = async (request: CuaOperation, execution: Readonly, useSystemPointer?: boolean) => { + const callNative = async (request: CuaOperation, execution: Readonly, useSystemInput?: boolean) => { const { method, params: parsedParams } = request const params = execution.coordinates.parameters(request) const agent = execution.agent const signal = execution.signal signal.throwIfAborted() const client = execution.nativeClient - // Earlier helpers accept an explicit false only for mouseMove. - if (method !== 'mouseMove' && !useSystemPointer) delete params.useSystemPointer - else if (useSystemPointer !== undefined) params.useSystemPointer = useSystemPointer + if (method !== 'mouseMove' && !useSystemInput) delete params.useSystemInput + else if (useSystemInput !== undefined) params.useSystemInput = useSystemInput if (method === 'sendKeyEvent' && backend.sendKeyEvent) return backend.sendKeyEvent(client, params, execution) - if (method === 'toggleMouse' && useSystemPointer && params.direction === 'down') mouseControl?.trackPress(agent, client) + if (method === 'toggleMouse' && useSystemInput && params.direction === 'down') systemInputControl?.trackPress(agent, client) const nativeParams = method === 'findApps' ? { ...params, maxAppMatches: config.maxAppMatches } : method === 'paste' @@ -356,7 +355,7 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) const capabilities = backend.capabilities return { ...runtime, - platform: capabilities.platform, systemPointer, + platform: capabilities.platform, systemInput, methods: [...capabilities.methods], appLevelAccessibility: capabilities.appLevelAccessibility, keyboard: [...capabilities.keyboard], @@ -408,13 +407,11 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) owner.coordinates = new CuaCoordinates() } const nativeClient = client - const route = request.method === 'mouseMove' || request.method === 'drag' || request.method === 'toggleMouse' - ? mouseControl?.resolve(agent, 'useSystemPointer' in request.params && request.params.useSystemPointer === true) - : undefined + const route = systemInputControl?.resolve(agent, 'useSystemInput' in request.params && request.params.useSystemInput === true) if (route?.prepare) owner.coordinates.parameters(request) const dispatch = async (signal: AbortSignal) => { const scoped = { ...execution, agent, signal, nativeClient, coordinates: owner.coordinates } - const result = await callNative(request, scoped, route?.useSystemPointer) + const result = await callNative(request, scoped, route?.useSystemInput) signal.throwIfAborted() return result } diff --git a/packages/experimental/cua/src/mouse-control-locales.ts b/packages/experimental/cua/src/mouse-control-locales.ts index e708ac0193..574decc4d5 100644 --- a/packages/experimental/cua/src/mouse-control-locales.ts +++ b/packages/experimental/cua/src/mouse-control-locales.ts @@ -1,23 +1,23 @@ -/** Scope and interruption shown before the user grants mouse control. */ -export const mouseControlPrompt = { +/** Scope and interruption shown before the user grants system input. */ +export const systemInputControlPrompt = { question: { - en: 'Allow the agent to control your mouse?', - zh: '允许智能体控制你的鼠标吗?', - ja: 'エージェントにマウス操作を許可しますか?', - es: '¿Permitir que el agente controle tu ratón?', - fr: 'Autoriser l’agent à contrôler votre souris ?', - de: 'Darf der Agent Ihre Maus steuern?', - ru: 'Разрешить агенту управлять вашей мышью?', - pt: 'Permitir que o agente controle seu mouse?', + en: 'Allow the agent to control your keyboard and mouse?', + zh: '允许智能体控制你的键盘和鼠标吗?', + ja: 'エージェントにキーボードとマウスの操作を許可しますか?', + es: '¿Permitir que el agente controle tu teclado y ratón?', + fr: 'Autoriser l’agent à contrôler votre clavier et votre souris ?', + de: 'Darf der Agent Ihre Tastatur und Maus steuern?', + ru: 'Разрешить агенту управлять клавиатурой и мышью?', + pt: 'Permitir que o agente controle seu teclado e mouse?', }, detail: { - en: 'The agent can move your pointer and hold or release a mouse button. Moving your mouse while a button is held can drag items. Your choice lasts until you close this session or restart DSH.', - zh: '智能体可以移动指针、按住或松开鼠标键。按住期间,你移动鼠标也可能拖动项目。此选择在关闭会话或重启 DSH 前有效。', - ja: 'エージェントはポインタを移動し、マウスボタンを押したままにしたり離したりできます。その間にマウスを動かすと項目がドラッグされることがあります。この選択はセッションを閉じるか DSH を再起動するまで有効です。', - es: 'El agente puede mover el puntero y mantener pulsado o soltar un botón. Si mueves el ratón mientras un botón está pulsado, puedes arrastrar elementos. Tu elección se mantiene hasta que cierres la sesión o reinicies DSH.', - fr: 'L’agent peut déplacer le pointeur et maintenir ou relâcher un bouton. Si vous déplacez la souris pendant qu’un bouton est enfoncé, vous pouvez faire glisser des éléments. Votre choix reste valable jusqu’à la fermeture de la session ou au redémarrage de DSH.', - de: 'Der Agent kann den Mauszeiger bewegen und eine Maustaste gedrückt halten oder loslassen. Wenn Sie die Maus bei gedrückter Taste bewegen, können Sie Elemente ziehen. Ihre Entscheidung gilt, bis Sie diese Sitzung schließen oder DSH neu starten.', - ru: 'Агент может перемещать указатель, удерживать и отпускать кнопку мыши. Если вы двигаете мышь, пока кнопка нажата, объекты могут перемещаться. Выбор сохраняется до закрытия сеанса или перезапуска DSH.', - pt: 'O agente pode mover o ponteiro e manter um botão do mouse pressionado ou soltá-lo. Se você mover o mouse enquanto um botão estiver pressionado, poderá arrastar itens. Sua escolha vale até encerrar a sessão ou reiniciar o DSH.', + en: 'The agent can send system keystrokes, move your pointer, and hold or release keys and mouse buttons. This can interrupt your input. Your choice lasts until you close this session or restart DSH.', + zh: '智能体可以发送系统键盘输入、移动指针,以及按住或松开键盘键和鼠标按钮,可能打断你的操作。此选择在关闭会话或重启 DSH 前有效。', + ja: 'エージェントはシステムへのキー入力、ポインタ移動、キーやマウスボタンの押下と解放を行えます。操作が中断される場合があります。この選択はセッションを閉じるか DSH を再起動するまで有効です。', + es: 'El agente puede enviar pulsaciones al sistema, mover el puntero y mantener pulsadas o soltar teclas y botones del ratón. Esto puede interrumpir tu interacción. Tu elección se mantiene hasta cerrar la sesión o reiniciar DSH.', + fr: 'L’agent peut envoyer des frappes au système, déplacer le pointeur et maintenir ou relâcher les touches et boutons. Cela peut interrompre vos actions. Votre choix reste valable jusqu’à la fermeture de la session ou au redémarrage de DSH.', + de: 'Der Agent kann Systemtastatureingaben senden, den Zeiger bewegen sowie Tasten und Maustasten gedrückt halten oder loslassen. Dies kann Ihre Eingabe unterbrechen. Ihre Entscheidung gilt bis zum Schließen der Sitzung oder Neustart von DSH.', + ru: 'Агент может отправлять системные нажатия клавиш, перемещать указатель, удерживать и отпускать клавиши и кнопки мыши. Это может прервать ваши действия. Выбор сохраняется до закрытия сеанса или перезапуска DSH.', + pt: 'O agente pode enviar teclas ao sistema, mover o ponteiro e manter teclas e botões pressionados ou soltá-los. Isso pode interromper sua interação. Sua escolha vale até encerrar a sessão ou reiniciar o DSH.', }, } diff --git a/packages/experimental/cua/src/mouse-control.ts b/packages/experimental/cua/src/mouse-control.ts index 255f23705d..f5977d6e8a 100644 --- a/packages/experimental/cua/src/mouse-control.ts +++ b/packages/experimental/cua/src/mouse-control.ts @@ -1,13 +1,13 @@ -/** Session approval for explicit system mouse input, shared by capable CUA providers. */ +/** Session approval for explicit system input, shared by capable CUA providers. */ import type { Context } from '@deepseek-ai/cordis' import type { Agent } from '@deepseek-ai/dsh-agent' import { UserQuestionError } from '@deepseek-ai/dsh-user-questions' import { NativeError, type NativeClient } from './native-client.ts' import { applicationAccessDisplay } from './locales.ts' -import { mouseControlPrompt } from './mouse-control-locales.ts' +import { systemInputControlPrompt } from './mouse-control-locales.ts' /** Access is scoped to the live Session and never grants application access. */ -export class MouseControl { +export class SystemInputControl { private readonly decisions = new WeakMap() private readonly pressed = new WeakMap() @@ -19,7 +19,7 @@ export class MouseControl { this.pressed.delete(session) if (client && !client.disposed) { void client.requestCleanup('releaseSystemButton', {}).catch((error: unknown) => { - ctx.logger.warn('Could not release system mouse input at turn end: %s', error) + ctx.logger.warn('Could not release system input at turn end: %s', error) }) } }) @@ -37,28 +37,28 @@ export class MouseControl { /** * Select the per-call route and any approval required before dispatch. * @param agent Agent owning the live Session. - * @param requested Whether the caller explicitly requested system mouse input. + * @param requested Whether the caller explicitly requested system input. * @returns Native pointer mode and an optional preparation that must succeed before input. */ - resolve(agent: Agent, requested: boolean): { useSystemPointer: boolean; prepare?: (signal: AbortSignal) => Promise } { - if (!requested) return { useSystemPointer: false } + resolve(agent: Agent, requested: boolean): { useSystemInput: boolean; prepare?: (signal: AbortSignal) => Promise } { + if (!requested) return { useSystemInput: false } if (agent.session.header.origin === 'subagent') { - throw new NativeError('MOUSE_CONTROL_UNAVAILABLE', 'Delegated tasks cannot control the system mouse. Use a window-directed action or report the required system-pointer gesture to the main task.') + throw new NativeError('SYSTEM_INPUT_UNAVAILABLE', 'Delegated tasks cannot control the system keyboard or mouse. Use a window-directed action or report the required system input to the main task.') } - if (!this.requireApproval || this.decisions.get(agent) === true) return { useSystemPointer: true } - return { useSystemPointer: true, prepare: signal => this.approve(agent, signal) } + if (!this.requireApproval || this.decisions.get(agent) === true) return { useSystemInput: true } + return { useSystemInput: true, prepare: signal => this.approve(agent, signal) } } private async approve(agent: Agent, signal: AbortSignal): Promise { signal.throwIfAborted() const decision = this.decisions.get(agent) - if (decision === 'asking') throw new NativeError('MOUSE_CONTROL_PENDING', 'Wait for the outstanding mouse control request') + if (decision === 'asking') throw new NativeError('SYSTEM_INPUT_PENDING', 'Wait for the outstanding system input request') let granted = decision if (granted === undefined) { const questions = this.ctx.get('userQuestions') - if (!questions) throw new NativeError('MOUSE_APPROVAL_UNAVAILABLE', 'No human answerer is available for mouse control') - const id = 'cua-mouse-control' - const display = { ...mouseControlPrompt, approve: applicationAccessDisplay.approve } + if (!questions) throw new NativeError('SYSTEM_INPUT_APPROVAL_UNAVAILABLE', 'No human answerer is available for system input') + const id = 'cua-system-input' + const display = { ...systemInputControlPrompt, approve: applicationAccessDisplay.approve } const approve = display.approve.en const reject = 'Deny' this.decisions.set(agent, 'asking') @@ -75,11 +75,11 @@ export class MouseControl { } catch (error) { this.decisions.delete(agent) if (error instanceof UserQuestionError && error.code === 'ASK_CANCELLED') { - throw new NativeError('MOUSE_APPROVAL_CANCELLED', 'The mouse control request was dismissed. Continue without mouse control unless the user asks to reconsider', { cause: error }) + throw new NativeError('SYSTEM_INPUT_APPROVAL_CANCELLED', 'The system input request was dismissed. Continue without system input unless the user asks to reconsider', { cause: error }) } throw error } } - if (!granted) throw new NativeError('MOUSE_CONTROL_DENIED', 'The user declined system mouse control for this session. No input was sent. Use pointer-free actions.') + if (!granted) throw new NativeError('SYSTEM_INPUT_DENIED', 'The user declined system input for this session. No input was sent. Use non-system actions.') } } diff --git a/packages/experimental/cua/src/protocol.ts b/packages/experimental/cua/src/protocol.ts index fd616907b1..18e565199b 100644 --- a/packages/experimental/cua/src/protocol.ts +++ b/packages/experimental/cua/src/protocol.ts @@ -51,13 +51,13 @@ const dragTargets = [ fromX: relativePoint, fromY: relativePoint, toX: relativePoint, toY: relativePoint }).strict(), ] as const -const systemPointerOption = { - useSystemPointer: z.boolean().optional().describe('Request use of the system pointer. The Host checks permission before dispatch.'), +const systemInputOption = { + useSystemInput: z.boolean().optional().describe('True sends system keyboard or mouse input and presses any requested keyboard modifiers. Omitted or false uses the provider default.'), } const toggle = z.object({ ...window, mouseButton: pointer.mouseButton.unwrap(), direction: z.enum(['down', 'up']) }).strict() -function requestSchema(hover: H, drag: D, button: T) { +function requestSchema(input: I) { return z.discriminatedUnion('method', [ operation('getCapabilities', {}), operation('listApps', {}), operation('findApps', { query: z.string().min(1, 'Expected a non-empty search string').regex(/\S/, 'Expected a non-empty search string') }), @@ -74,39 +74,36 @@ function requestSchema target.extend(input))) }).strict(), z.object({ method: z.literal('click'), params: z.union([ - z.object({ ...snapshot, ...click }).strict(), - z.object({ ...absoluteCoordinate, ...click }).strict(), - z.object({ ...relativeCoordinate, ...click }).strict(), + z.object({ ...snapshot, ...click, ...input }).strict(), + z.object({ ...absoluteCoordinate, ...click, ...input }).strict(), + z.object({ ...relativeCoordinate, ...click, ...input }).strict(), ]) }).strict(), operation('setValue', { ...snapshot, value: jsonValue }), operation('selectText', { ...snapshot, text: z.string().min(1), prefix: z.string().optional(), suffix: z.string().optional(), selectionType: z.enum(['text', 'cursor_before', 'cursor_after']).optional() }), operation('typeText', { ...app, windowId: windowId.optional(), text: z.string() }), operation('paste', { ...app, windowId: windowId.optional(), text: z.string(), format: z.enum(['text', 'html']).optional() }), - operation('pressKey', { ...app, windowId: windowId.optional(), key: z.string().min(1), modifiers: z.array(z.string()).optional() }), - operation('sendKeyEvent', { ...app, windowId: windowId.optional(), key: z.string().min(1), direction: z.enum(['down', 'up']) }), + operation('pressKey', { ...app, ...input, windowId: windowId.optional(), key: z.string().min(1), modifiers: z.array(z.string()).optional() }), + operation('sendKeyEvent', { ...app, ...input, windowId: windowId.optional(), key: z.string().min(1), direction: z.enum(['down', 'up']) }), z.object({ method: z.literal('scroll'), params: z.union([ z.object({ ...absoluteCoordinate, deltaLinesX: z.number().int().min(-10).max(10), deltaLinesY: z.number().int().min(-10).max(10) }).strict(), z.object({ ...relativeCoordinate, deltaLinesX: z.number().int().min(-10).max(10), deltaLinesY: z.number().int().min(-10).max(10) }).strict(), ]) }).strict(), - z.object({ method: z.literal('drag'), params: drag }).strict(), + z.object({ method: z.literal('drag'), params: z.union(dragTargets.map(target => target.extend(input))) }).strict(), operation('screenshot', window), ]) } -/** Portable model operations, including standard hover without a system-pointer option. */ -export const Request = requestSchema(z.union(MouseMoveTargets), z.union(dragTargets), toggle) +/** Portable operations for providers without explicit system-input selection. */ +export const Request = requestSchema({}) -/** Model operations for providers that can move the user's system pointer. */ -export const SystemPointerRequest = requestSchema( - z.union(MouseMoveTargets.map(target => target.extend(systemPointerOption))), - z.union(dragTargets.map(target => target.extend(systemPointerOption))), toggle.extend(systemPointerOption), -) +/** Operations for providers supporting explicit system mouse input and keyboard modifiers. */ +export const SystemInputRequest = requestSchema(systemInputOption) /** Native resource fields supplied or completed by the Host before dispatch. */ export const NativeResourceParameters = { @@ -177,7 +174,7 @@ export const CapabilitiesResult = z.object({ /** Whether the provider supports application-level accessibility observations. */ appLevelAccessibility: z.boolean(), /** Whether mouseMove accepts an explicit request to move the system pointer. */ - systemPointer: z.boolean().default(false), + systemInput: z.boolean().default(false), /** Scopes that support keyboard input. */ keyboard: z.array(z.enum(['app', 'window'])), sessionLocked: z.boolean().nullable(), diff --git a/packages/experimental/cua/src/types.ts b/packages/experimental/cua/src/types.ts index a057e1167a..1f05a5d6b1 100644 --- a/packages/experimental/cua/src/types.ts +++ b/packages/experimental/cua/src/types.ts @@ -2,7 +2,7 @@ import type { Branded } from '@deepseek-ai/dsh-brand' import type { JsonValue } from '@deepseek-ai/dsh-util-values' import type { z } from 'zod' -import type { ActionResult, CapabilitiesResult, FoundAppsResult, HoverResult, SystemPointerRequest, ShowResult, WindowsResult } from './protocol.ts' +import type { ActionResult, CapabilitiesResult, FoundAppsResult, HoverResult, SystemInputRequest, ShowResult, WindowsResult } from './protocol.ts' /** Helper-issued application selection; public app objects hold only this opaque handle. */ export type CuaAppHandle = Branded<'CuaAppHandle'> @@ -11,7 +11,7 @@ export type CuaSnapshotId = Branded<'CuaSnapshotId'> /** Opaque string defined by the platform provider, valid for at least the lifetime of one snapshot. */ export type CuaElementId = Branded<'CuaElementId'> /** One operation sent through an authorized and logged host dispatcher. */ -export type CuaOperation = z.output +export type CuaOperation = z.output type CuaParameters = Extract['params'] /** Dispatch exactly once; a failed action must not be retried implicitly. */ export type CuaDispatch = (operation: CuaOperation) => Promise @@ -34,7 +34,7 @@ export type CuaCapabilities = z.output export type CuaStartupCapabilities = Pick< CuaCapabilities, 'platform' | 'methods' | 'appLevelAccessibility' | 'keyboard' | 'browser' | 'coordinateSpace' -> & { systemPointer?: boolean } +> & { systemInput?: boolean } /** App discovery result accepted by getApp, including the provider-reported running state. */ export type CuaAppInfo = Pick & { /** Running process selector on macOS. */ @@ -60,7 +60,7 @@ export interface CuaCoordinateOptions { } /** Restoration dispatch; foregroundChanged compares the front app and top window before and after the request. */ export type CuaShowResult = z.output -/** Modifiers attached to a window-directed pointer gesture. */ +/** Modifiers attached to a pointer gesture; system input also presses and releases their keyboard keys. */ export type CuaPointerModifier = NonNullable['modifiers']>[number] /** Buttons supported by window-directed mouse input. */ export type CuaMouseButton = NonNullable['mouseButton']> @@ -69,11 +69,16 @@ export type CuaMouseButton = NonNullable['mouseButton']> * holdMs is a nonnegative integer in milliseconds, limited by maxClickHoldMs; zero releases immediately. * Explicit holds use pointer input; omission preserves ordinary clicks. */ -export type CuaClickOptions = Pick, 'mouseButton' | 'clickCount' | 'modifiers' | 'holdMs'> & CuaCoordinateOptions +export type CuaClickOptions = Pick, 'mouseButton' | 'clickCount' | 'modifiers' | 'holdMs'> & CuaCoordinateOptions & CuaSystemInputOptions /** One same-window drag; omitted button is left and omitted modifiers are empty. */ -export type CuaDragOptions = Pick, 'mouseButton' | 'modifiers' | 'useSystemPointer'> & CuaCoordinateOptions +export type CuaDragOptions = Pick, 'mouseButton' | 'modifiers' | 'useSystemInput'> & CuaCoordinateOptions /** Clipboard representation delivered through the application's Paste command. */ export type CuaPasteOptions = Pick, 'format'> +/** System keyboard or mouse delivery for one supported input operation. */ +export interface CuaSystemInputOptions { + /** True requests system input, including keyboard modifiers, after approval; omitted or false uses the provider default. */ + useSystemInput?: boolean +} /** Adjacent literal context disambiguates repeated text; cursor modes collapse the matched range. */ export type CuaSelectTextOptions = Pick, 'prefix' | 'suffix' | 'selectionType'> /** Positive deltas reveal content above/left; each axis is an integer from -10 to 10. */ @@ -152,18 +157,20 @@ export interface CuaSurface { * Rejects when the provider does not support keyboard input at this scope. * @param key - Provider-defined key name to press and release; not a chord. * @param modifiers - Modifier names held for this keystroke. The provider validates the names; omitted means none. + * @param options - System input selection; omitted uses the provider default. * @returns Whether the provider successfully executed the requested operation. */ - pressKey(key: string, modifiers?: string[]): Promise + pressKey(key: string, modifiers?: string[], options?: CuaSystemInputOptions): Promise /** * Send one key-down or key-up event at the current input focus. * Does not send the opposite event. * Rejects when the provider does not support keyboard input at this scope. * @param key - Platform-defined key name; modifier keys may themselves be targets. * @param direction - Explicit event direction; the opposite event is never sent implicitly. + * @param options - Input selection, matching the corresponding down or up; omitted uses the provider default. * @returns Whether the provider successfully executed the requested operation. */ - sendKeyEvent(key: string, direction: 'down' | 'up'): Promise + sendKeyEvent(key: string, direction: 'down' | 'up', options?: CuaSystemInputOptions): Promise } /** * An explicit window with screenshot and pointer input operations. @@ -184,21 +191,21 @@ export interface CuaWindow extends CuaSurface { * Returning and subsequent observations do not restore the previous pointer position. * Other input and application changes can interrupt the interaction; observe before continuing. * @param target - current element id or screenshot-local [x,y]. - * @param options - Coordinate mode for points. Only providers reporting systemPointer accept useSystemPointer. + * @param options - Coordinate mode for points. Only providers reporting systemInput accept useSystemInput. * True requests physical movement for this call only. * @returns dispatch evidence and the selected route; observe the resulting UI after any UI delay. */ mouseMove(target: CuaElementId | readonly [number, number], - options?: CuaCoordinateOptions & { useSystemPointer?: boolean }): Promise + options?: CuaCoordinateOptions & CuaSystemInputOptions): Promise /** * Send one mouse-button down or up event without moving the pointer. * Does not send the opposite event; callers explicitly release a pressed button. * @param mouseButton - Mouse button to press or release. * @param direction - Explicit event direction. - * @param options - Request a system button on a provider reporting systemPointer. + * @param options - Request a system button on a provider reporting systemInput. * @returns Whether the provider successfully executed the requested operation. */ - toggleMouse(mouseButton: CuaMouseButton, direction: 'down' | 'up', options?: { useSystemPointer?: boolean }): Promise + toggleMouse(mouseButton: CuaMouseButton, direction: 'down' | 'up', options?: CuaSystemInputOptions): Promise /** * Click a current element id or screenshot-local point. * Cancellation or timeout releases the held button; received input cannot be undone. The operation deadline includes holdMs. @@ -217,7 +224,7 @@ export interface CuaWindow extends CuaSurface { * Drag between points in one window while holding the selected button and modifiers. * @param from - starting screenshot-local point or integer ratio. * @param to - destination in the same coordinate mode. - * @param options - button, modifiers and coordinate mode. Only providers reporting systemPointer accept useSystemPointer. + * @param options - button, modifiers and coordinate mode. Only providers reporting systemInput accept useSystemInput. * @returns dispatch evidence. */ drag(from: readonly [number, number], to: readonly [number, number], options?: CuaDragOptions): Promise diff --git a/packages/experimental/cua/tests/api.spec.ts b/packages/experimental/cua/tests/api.spec.ts index dc9d018a55..0b57be746a 100644 --- a/packages/experimental/cua/tests/api.spec.ts +++ b/packages/experimental/cua/tests/api.spec.ts @@ -13,7 +13,7 @@ const IMAGE = Object.freeze({ attachmentId: 'sha256:screenshot', path: '/images/ const bounds = { x: -640, y: 100, width: 640, height: 480 } const selected = { appHandle: 'app-17', pid: 17, name: 'Editor', bundleId: 'test.editor', isRunning: true, running: true } const delivered = { dispatched: true } -const capabilities: CuaCapabilities = { platform: 'macos', systemPointer: true, sessionLocked: false, permissions: { accessibility: true, screenRecording: false }, appLevelAccessibility: true, keyboard: ['app'], methods: ['getState', 'click'], coordinateSpace: 'screenshot-pixels', browser: false } +const capabilities: CuaCapabilities = { platform: 'macos', systemInput: true, sessionLocked: false, permissions: { accessibility: true, screenRecording: false }, appLevelAccessibility: true, keyboard: ['app'], methods: ['getState', 'click'], coordinateSpace: 'screenshot-pixels', browser: false } function windowInfo(windowId: string) { return { windowId, appName: 'Editor', title: `Document ${windowId}`, bounds, isOnScreen: true, onCurrentSpace: null } @@ -230,10 +230,10 @@ describe('pointer buttons and modifiers', () => { appHandle: 'app-17', windowId: '23', snapshotId: 'snapshot-2', x: 10, y: 20, mouseButton: 'left', clickCount: 1, modifiers: ['command'], } }) - await window.drag([10, 20], [30, 40], { mouseButton: 'middle', modifiers: ['shift', 'option'], useSystemPointer: true }) + await window.drag([10, 20], [30, 40], { mouseButton: 'middle', modifiers: ['shift', 'option'], useSystemInput: true }) expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'drag', params: { appHandle: 'app-17', windowId: '23', snapshotId: 'snapshot-2', fromX: 10, fromY: 20, toX: 30, toY: 40, - useSystemPointer: true, mouseButton: 'middle', modifiers: ['shift', 'option'], + useSystemInput: true, mouseButton: 'middle', modifiers: ['shift', 'option'], } }) const count = f.dispatch.mock.calls.length await expect(window.click(element('0'), { mouseButton: 'middle', clickCount: 2 })).rejects.toThrow('Only left double-click') @@ -965,9 +965,9 @@ describe('input actions', () => { expect(f.dispatch).toHaveBeenCalledExactlyOnceWith({ method: 'toggleMouse', params: { appHandle: 'app-17', windowId: '23', mouseButton, direction, } }) - await window.toggleMouse(mouseButton, direction, { useSystemPointer: true }) + await window.toggleMouse(mouseButton, direction, { useSystemInput: true }) expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'toggleMouse', params: { - appHandle: 'app-17', windowId: '23', mouseButton, direction, useSystemPointer: true, + appHandle: 'app-17', windowId: '23', mouseButton, direction, useSystemInput: true, } }) } }) @@ -1069,10 +1069,10 @@ it('forwards provider options while retaining the selected target and coordinate appHandle: 'app-17', windowId: '23', snapshotId: 'snapshot-1', elementId: '0', trackingMode: 'precise', } }) await win.getScreenshot() - const pixelOptions = { relative: false, useSystemPointer: true, trackingMode: 'precise', x: 222 } + const pixelOptions = { relative: false, useSystemInput: true, trackingMode: 'precise', x: 222 } await win.mouseMove([30, 40], pixelOptions) expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'mouseMove', params: { - appHandle: 'app-17', snapshotId: 'snapshot-1', windowId: '23', x: 30, y: 40, relative: false, useSystemPointer: true, trackingMode: 'precise', + appHandle: 'app-17', snapshotId: 'snapshot-1', windowId: '23', x: 30, y: 40, relative: false, useSystemInput: true, trackingMode: 'precise', } }) const relativeOptions = { relative: true, trackingMode: 'coarse' } await win.mouseMove([250, 750], relativeOptions) @@ -1083,13 +1083,13 @@ it('forwards provider options while retaining the selected target and coordinate it('keeps ordinary Windows drags portable and rejects explicit system-pointer options before dispatch', async () => { const f = fixture() - f.setCapabilities({ ...capabilities, platform: 'windows', systemPointer: false, appLevelAccessibility: false, keyboard: ['window'] }) + f.setCapabilities({ ...capabilities, platform: 'windows', systemInput: false, appLevelAccessibility: false, keyboard: ['window'] }) const win = await (await f.api.getApp('Editor')).getWindow('23') await win.getAccessibilityTree() f.dispatch.mockClear() - for (const useSystemPointer of [true, false]) { - await expect(win.toggleMouse('left', 'down', { useSystemPointer })).rejects.toThrow('toggleMouse useSystemPointer: not accepted') - await expect(win.drag([10, 20], [30, 40], { useSystemPointer })).rejects.toThrow('drag useSystemPointer: not accepted') + for (const useSystemInput of [true, false]) { + await expect(win.toggleMouse('left', 'down', { useSystemInput })).rejects.toThrow('toggleMouse useSystemInput: not accepted') + await expect(win.drag([10, 20], [30, 40], { useSystemInput })).rejects.toThrow('drag useSystemInput: not accepted') } expect(f.dispatch).not.toHaveBeenCalled() await win.drag([10, 20], [30, 40], { mouseButton: 'right', modifiers: ['win'] }) @@ -1113,3 +1113,22 @@ it('forwards bounded traversal limits on a window-only provider', async () => { method: 'getState', params: { appHandle: app.appHandle, windowId: '23', maxDepth: 1, maxElements: 1 }, }) }) + +it('forwards explicit system input for clicks and both keyboard operations', async () => { + const f = fixture() + const app = await f.api.getApp('Editor') + const win = await app.getWindow('23') + await win.getAccessibilityTree() + await win.click(element('0'), { modifiers: ['shift'], useSystemInput: true }) + expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'click', params: { + appHandle: 'app-17', windowId: '23', snapshotId: 'snapshot-1', elementId: '0', modifiers: ['shift'], useSystemInput: true, + } }) + await app.pressKey('s', ['command'], { useSystemInput: true }) + expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'pressKey', params: { + appHandle: 'app-17', key: 's', modifiers: ['command'], useSystemInput: true, + } }) + await app.sendKeyEvent('shift', 'down', { useSystemInput: true }) + expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'sendKeyEvent', params: { + appHandle: 'app-17', key: 'shift', direction: 'down', useSystemInput: true, + } }) +}) diff --git a/packages/experimental/cua/tests/bridge.spec.ts b/packages/experimental/cua/tests/bridge.spec.ts index 9cab5ea8ca..b5ebdd493a 100644 --- a/packages/experimental/cua/tests/bridge.spec.ts +++ b/packages/experimental/cua/tests/bridge.spec.ts @@ -10,7 +10,7 @@ import type { CuaCapabilities, CuaElementId, CuaOperation } from '../src/types.t const element = (id: string): CuaElementId => brandString(id) const capabilities: CuaCapabilities = { - platform: 'macos', systemPointer: true, permissions: { accessibility: true, screenRecording: true }, appLevelAccessibility: true, + platform: 'macos', systemInput: true, permissions: { accessibility: true, screenRecording: true }, appLevelAccessibility: true, keyboard: ['app'], sessionLocked: false, methods: ['getCapabilities', 'getApp', 'getState', 'screenshot'], coordinateSpace: 'screenshot-pixels', browser: false, } diff --git a/packages/experimental/cua/tests/protocol.spec.ts b/packages/experimental/cua/tests/protocol.spec.ts index 711c0ae071..1ded03dc89 100644 --- a/packages/experimental/cua/tests/protocol.spec.ts +++ b/packages/experimental/cua/tests/protocol.spec.ts @@ -1,7 +1,7 @@ /** Model-authored operation JSON cannot supply host configuration or bypass retained identities. */ import { expect, it } from 'vitest' import type { JsonValue } from '@deepseek-ai/dsh-util-values' -import { CapabilitiesResult, NativeScreenshotResult, Request, ScreenshotResult, ShowResult, StateResult, SystemPointerRequest, WindowsResult } from '../src/protocol.ts' +import { CapabilitiesResult, NativeScreenshotResult, Request, ScreenshotResult, ShowResult, StateResult, SystemInputRequest, WindowsResult } from '../src/protocol.ts' it('preserves opaque window IDs in requests and results', () => { const windowId = 'window-main' @@ -72,7 +72,7 @@ it('admits arbitrary key names with an explicit key-event direction', () => { }) it.each(['left', 'right', 'middle'])('admits explicit %s mouse-button events without coordinates', (mouseButton) => { - for (const schema of [Request, SystemPointerRequest]) { + for (const schema of [Request, SystemInputRequest]) { for (const direction of ['down', 'up']) { const request = { method: 'toggleMouse', params: { appHandle: 'app', windowId: '23', mouseButton, direction } } expect(schema.parse(request)).toEqual(request) @@ -80,10 +80,10 @@ it.each(['left', 'right', 'middle'])('admits explicit %s mouse-button events wit } }) -it.each([true, false])('admits the system button option only for capable providers (%s)', (useSystemPointer) => { - const request = { method: 'toggleMouse', params: { appHandle: 'a', windowId: '1', mouseButton: 'left', direction: 'down', useSystemPointer } } +it.each([true, false])('admits the system button option only for capable providers (%s)', (useSystemInput) => { + const request = { method: 'toggleMouse', params: { appHandle: 'a', windowId: '1', mouseButton: 'left', direction: 'down', useSystemInput } } expect(Request.safeParse(request).success).toBe(false) - expect(SystemPointerRequest.parse(request)).toEqual(request) + expect(SystemInputRequest.parse(request)).toEqual(request) }) it.each([ @@ -91,10 +91,10 @@ it.each([ { direction: undefined }, { direction: 'press' }, { appHandle: undefined }, { windowId: undefined }, { x: 1 }, { y: 2 }, { relative: true }, { elementId: '0' }, { snapshotId: 'snapshot' }, - { modifiers: [] }, { useSystemPointer: 'yes' }, + { modifiers: [] }, { useSystemInput: 'yes' }, ])('rejects invalid mouse-button event parameters %j', (invalid) => { const params = { appHandle: 'app', windowId: '23', mouseButton: 'left', direction: 'down', ...invalid } - for (const schema of [Request, SystemPointerRequest]) { + for (const schema of [Request, SystemInputRequest]) { expect(schema.safeParse({ method: 'toggleMouse', params }).success).toBe(false) } }) @@ -144,7 +144,7 @@ it.each([ { appHandle: 'app', windowId: '23', x: 1, y: 2 }, ])('accepts a mouse move target %j without button input', (params) => { expect(Request.parse({ method: 'mouseMove', params })).toEqual({ method: 'mouseMove', params }) - for (const extra of [{ mouseButton: 'left' }, { clickCount: 1 }, { modifiers: ['shift'] }, { useSystemPointer: 'yes' }]) { + for (const extra of [{ mouseButton: 'left' }, { clickCount: 1 }, { modifiers: ['shift'] }, { useSystemInput: 'yes' }]) { expect(Request.safeParse({ method: 'mouseMove', params: { ...params, ...extra } }).success).toBe(false) } }) @@ -245,7 +245,7 @@ it.each([true, false])('requires the reported application-level accessibility ca platform: 'macos', permissions: { accessibility: true, screenRecording: false }, appLevelAccessibility, keyboard: ['app'], sessionLocked: false, methods: [], coordinateSpace: 'screenshot-pixels', browser: false, } - expect(CapabilitiesResult.parse(capabilities)).toEqual({ ...capabilities, systemPointer: false }) + expect(CapabilitiesResult.parse(capabilities)).toEqual({ ...capabilities, systemInput: false }) const { appLevelAccessibility: _omitted, ...missing } = capabilities expect(CapabilitiesResult.safeParse(missing).success).toBe(false) }) @@ -261,7 +261,7 @@ it.each([ platform: 'windows', permissions: { accessibility: true, screenRecording: true }, appLevelAccessibility: false, keyboard, sessionLocked: false, methods: [], coordinateSpace: 'screenshot-pixels', browser: false, } - expect(CapabilitiesResult.parse(capabilities)).toEqual({ ...capabilities, systemPointer: false }) + expect(CapabilitiesResult.parse(capabilities)).toEqual({ ...capabilities, systemInput: false }) }) it.each([ @@ -290,9 +290,34 @@ it.each<[string, Record]>([ ['drag', { relative: true, fromX: 1, fromY: 2, toX: 3, toY: 4 }], ])('admits %s system-pointer control only for supporting providers', (method, points) => { const target = { appHandle: 'app', windowId: '1', ...points } - const request = { method, params: { ...target, useSystemPointer: true } } + const request = { method, params: { ...target, useSystemInput: true } } expect(Request.safeParse(request).success).toBe(false) - expect(SystemPointerRequest.safeParse(request).success).toBe(true) - expect(SystemPointerRequest.safeParse({ ...request, params: { ...target, useSystemPointer: 'true' } }).success).toBe(false) - expect(SystemPointerRequest.safeParse({ ...request, params: { ...target, arbitraryField: true } }).success).toBe(false) + expect(SystemInputRequest.safeParse(request).success).toBe(true) + expect(SystemInputRequest.safeParse({ ...request, params: { ...target, useSystemInput: 'true' } }).success).toBe(false) + expect(SystemInputRequest.safeParse({ ...request, params: { ...target, arbitraryField: true } }).success).toBe(false) +}) + +it.each([ + { method: 'mouseMove', params: { appHandle: 'a', windowId: '1', x: 2, y: 3 } }, + { method: 'toggleMouse', params: { appHandle: 'a', windowId: '1', mouseButton: 'left', direction: 'down' } }, + { method: 'click', params: { appHandle: 'a', windowId: '1', x: 2, y: 3, modifiers: ['shift'] } }, + { method: 'drag', params: { appHandle: 'a', windowId: '1', fromX: 2, fromY: 3, toX: 4, toY: 5 } }, + { method: 'pressKey', params: { appHandle: 'a', key: 's', modifiers: ['command'] } }, + { method: 'sendKeyEvent', params: { appHandle: 'a', key: 'shift', direction: 'down' } }, +])('selects system input for $method only on a supporting provider', ({ method, params }) => { + for (const useSystemInput of [true, false]) { + const request = { method, params: { ...params, useSystemInput } } + expect(SystemInputRequest.parse(request)).toEqual(request) + expect(Request.safeParse(request).success).toBe(false) + } + expect(SystemInputRequest.safeParse({ method, params: { ...params, useSystemPointer: true } }).success).toBe(false) +}) + +it.each([ + { method: 'typeText', params: { appHandle: 'a', text: 'text' } }, + { method: 'paste', params: { appHandle: 'a', text: 'text' } }, + { method: 'scroll', params: { appHandle: 'a', windowId: '1', x: 2, y: 3, deltaLinesX: 0, deltaLinesY: 1 } }, + { method: 'invoke', params: { appHandle: 'a', snapshotId: 'snapshot', elementId: 'button' } }, +])('keeps the input route fixed for $method', ({ method, params }) => { + expect(SystemInputRequest.safeParse({ method, params: { ...params, useSystemInput: true } }).success).toBe(false) })