diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-window-discovery/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/cua-window-discovery/guide.i18n.yaml new file mode 100644 index 0000000000..3c660cca16 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-window-discovery/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.1/cua-window-discovery/guide.md +/: + en: 38fff752f1aa0555 + zh: 154a5b6fd4d10dbf +/finding-hidden-cua-windows: + en: 730a25d76910c44b + zh: 39502d2efdafc9a4 +/finding-hidden-cua-windows/change: + en: b5f962e340aa46ea + zh: 0899c0c6aebbf3f6 +/finding-hidden-cua-windows/migration: + en: b4f23d4f6a5d6309 + zh: 65d0993292b7d2dc diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-window-discovery/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/cua-window-discovery/guide.md new file mode 100644 index 0000000000..6012d7bc1c --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-window-discovery/guide.md @@ -0,0 +1,17 @@ +--- +kind: upgrade-guide +description: "CUA window discovery omits offscreen and zero-size windows by default." +--- + +# Finding hidden CUA windows + +English | [中文](guide.zh.md) + +## Change + +`listWindows`, `app.getWindows()` and the window list in `getState` now show positive-size, onscreen windows on the current desktop. A scoped observation also retains its explicitly selected window. Scripts that find minimized, hidden or other-Space windows through default discovery can miss their target. + +## Migration + +1. Call `app.getWindows({ includeHidden: true })`, or pass `includeHidden: true` with the app handle to the raw `listWindows` operation. +2. Find the target by its window ID in the full result. Use `app.getWindow(windowId)` to select it and `show()` if restoration is required. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-window-discovery/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/cua-window-discovery/guide.zh.md new file mode 100644 index 0000000000..4a8875de31 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-window-discovery/guide.zh.md @@ -0,0 +1,17 @@ +--- +kind: upgrade-guide +description: "CUA 默认窗口清单省略离屏和尺寸为零的窗口。" +--- + +# 查找隐藏的 CUA 窗口 + +[English](guide.md) | 中文 + +## 变更 + +`listWindows`、`app.getWindows()` 和 `getState` 的窗口清单默认只显示当前桌面上尺寸大于零的在屏窗口。窗口级观察还会保留显式选中的窗口。通过默认枚举查找最小化、隐藏或位于其他 Space 的窗口时,脚本可能找不到目标。 + +## 迁移 + +1. 调用 `app.getWindows({ includeHidden: true })`,或在原始 `listWindows` 操作中同时传入应用句柄和 `includeHidden: true`。 +2. 在完整清单中确认目标窗口的 ID,调用 `app.getWindow(windowId)` 选中它,需要恢复窗口时调用 `show()`。 diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index 5ec1b9b13d..c8abe22672 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -18,8 +18,8 @@ en: a6006411c8240e1a zh: 4c0129caa37b087d /deepseek-ai-dsh-experimental-cua-macos/use-this-package/connect-an-external-execution-environment: - en: 786b8fd630b11e5f - zh: 55143f15486afce8 + en: c9dea62ef5876665 + zh: 462faf1b6b9047fd /deepseek-ai-dsh-experimental-cua-macos/understand-the-implementation: en: 8b9ec208ca057a4a zh: e8dbb45891ad15b8 @@ -39,8 +39,8 @@ en: 2dbc22ffd1f8a717 zh: d4458872e75305d9 /deepseek-ai-dsh-experimental-cua-macos/model-experience/native-application-operations/token-effect: - en: ab52b46d874fa8b9 - zh: e87d3620ef77cb06 + en: c02724742dd596a3 + zh: 01ee49dce76e1815 /deepseek-ai-dsh-experimental-cua-macos/model-experience/native-application-operations/kv-cache-effect: en: a2c9acb5a4320dda zh: e8d1586af60215c4 diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index b162fdb179..8ffdd9fe4a 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -109,7 +109,7 @@ void await app.getScreenshot() Use app methods directly for single-window tasks. `getApp` reads initial AX state, so a screenshot needs no window enumeration or additional AX read. Use `app.getWindows()` and `app.getWindow(windowId)` when the task needs a particular window or default selection is ambiguous; choose by the observed title and bounds. -`getWindow` emits its initial AX tree. An owned window without an AX surface returns an empty snapshot and remains available for screenshots and coordinate input. Window objects retain separate snapshots, so reading one window does not invalidate another. Re-reading the same scope invalidates old indices. An AX node removed during observation rejects the read with `STALE_SNAPSHOT` and publishes no partial tree; read again without repeating the preceding input. App-scoped screenshots and coordinates reuse the latest AX observation: its focused on-screen, nonzero-size window, otherwise the sole such window. They do not query current focus again; read `app.getAXState()` to follow a focus change. Explicit window objects retain their selected target. Keyboard methods stay on `app` because input follows the app’s current focus. +`getWindow` emits its initial AX tree. An owned window without an AX surface returns an empty snapshot and remains available for screenshots and coordinate input. Window objects retain separate snapshots, so reading one window does not invalidate another. Re-reading the same scope invalidates old indices. An AX node removed during observation rejects the read with `STALE_SNAPSHOT` and publishes no partial tree; read again without repeating the preceding input. App-scoped screenshots and coordinates reuse the latest AX observation: its focused on-screen, nonzero-size window, otherwise the sole visible normal-layer window. They do not query current focus again; read `app.getAXState()` to follow a focus change. Explicit window objects retain their selected target. Keyboard methods stay on `app` because input follows the app’s current focus. `hover(target)` first reveals advertised AX alternate UI without moving the system cursor. Entering a revealed descendant preserves its parent UI, and leaving restores the default UI. When unavailable, hover moves the visible system cursor to an AX element center or window-local point without pressing a button, including over disabled controls. It requires the selected app to be foreground and the target point unobscured; otherwise `FOREGROUND_REQUIRED` requires explicit activation or raising and a fresh observation. Completion, AX reads and screenshots do not restore the previous point. Wait for the application’s hover delay, observe the revealed content, then hover into it and click; successive calls can visit intermediate points. Other input or application changes can interrupt the interaction. [Continuous-interaction rationale](../../../.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.md). @@ -174,7 +174,7 @@ Use cua with method getCapabilities and params {} to inspect permissions and ses Initialize the object API once in persistent PTC. Reuse its variables in later calls; put temporary declarations inside { ... } blocks to avoid redeclaration errors. All object methods are async. getAXState returns text, not a structured state object. Its text separates values and placeholders, and reports subroles, help, URLs, disabled/focused/selected/expanded state and UTF-16 selection ranges when available. Writability is true, false or unknown on relevant controls; omitted state fields do not assert false. selection=unavailable means the reported range exceeds the observed text. Compact output omits ordinary Press/Pick (click), ShowMenu (right click) and ScrollToVisible actions; details=true lists every available action. Use the displayed action name with performSecondaryAction; ambiguous aliases require the complete name from details=true. Truncation reports the reached provider limit. Narrow the window or increase that provider limit before reading again. -Use app methods directly for single-window tasks; getApp already reads initial AX state. Call app.getWindows() and await app.getWindow(windowId) only to target a particular window or resolve ambiguous window selection. App screenshots and coordinate actions use the latest AX observation: its focused on-screen, nonzero-size window, otherwise the sole such window. They do not refresh focus automatically. Read app.getAXState() to follow changed focus. Independent floating panels have their own window IDs. After opening one, refresh app.getWindows() and select its window for AX, screenshots and input; a panel may leave keyboard focus in the main window. +Use app methods directly for single-window tasks; getApp already reads initial AX state. Call app.getWindows() and await app.getWindow(windowId) only to target a particular window or resolve ambiguous window selection. App screenshots and coordinate actions use the latest AX observation: its focused on-screen, nonzero-size window, otherwise the sole visible normal-layer window. They do not refresh focus automatically. Read app.getAXState() to follow changed focus. Visible panels, menus, tooltips and status items can have their own window IDs. Select a panel from app.getWindows() for its AX, screenshot and input even if the main window retains focus. Use includeHidden:true in listWindows or app.getWindows({includeHidden:true}) to list offscreen and zero-size windows. CuaScreenshot contains { bytes: Uint8Array, mimeType: "image/png" | "image/jpeg" | "image/webp" | "image/gif", pixelWidth: number, pixelHeight: number, windowId: number }. Use mimeType to choose a file extension or declare an image; do not assume PNG. @@ -186,7 +186,7 @@ Object API signatures (options default to { emit: true }): - cua.getState(options?) -> { apps, browsers: [] } - cua.getApp(selector: string) -> App - app.activate() -> { dispatched: true, verified: false } -- app.getWindows(options?) -> Array<{ windowId, pid, appName, title, bounds, isOnScreen, onCurrentSpace }> +- app.getWindows(options?: { emit?: boolean, includeHidden?: boolean }) -> Array<{ windowId, pid, appName, title, bounds, isOnScreen, onCurrentSpace, layer? }> - app.getWindow(windowId: number) -> Window - app.typeText(text: string), app.pressKey(chord: string) -> action result - app.paste(text: string, options?: { format?: "text" | "html" }) -> action result @@ -216,7 +216,7 @@ Use selectText only on controls advertising selectionWritable. It selects a uniq #### Token effect -Enabling the plugin adds a fixed schema and guidance. AX observations, operation results and admitted images add model input. Retained objects are not serialized into prompts by this package. +Enabling the plugin adds a fixed schema and guidance. AX observations, operation results and admitted images add model input. Default window metadata includes only visible windows and the explicitly observed target. Requesting the complete list adds one record per owned window, including hidden auxiliary windows. #### KV Cache effect diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 435e3b5336..e891d67d51 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -109,7 +109,7 @@ void await app.getScreenshot() 单窗口任务直接使用 app 方法。`getApp` 已读取初始 AX,截图不需要枚举窗口或额外读取 AX。任务需要指定窗口或默认选窗存在歧义时,再调用 `app.getWindows()` 和 `app.getWindow(windowId)`,根据观察到的标题与位置选择目标。 -`getWindow` 会输出初始 AX 树。已确认归属但没有 AX 界面的窗口返回空快照,仍可截图和发送坐标输入。不同窗口分别保留快照,读取一个窗口不会使另一个窗口失效;重新读取同一范围会使旧索引失效。观察期间节点被移除时,该次读取返回 `STALE_SNAPSHOT`,不发布部分树;可以重新读取,但不要重复此前的输入。应用级截图和坐标操作复用最近一次 AX 观察:优先使用其中在屏幕上且尺寸非零的焦点窗口,否则要求只有一个符合条件的窗口。它们不会重新查询即时焦点;需要跟随焦点变化时,先读取 `app.getAXState()`。显式窗口对象保持选定的目标。键盘方法保留在 `app` 上,因为输入跟随应用的当前焦点。 +`getWindow` 会输出初始 AX 树。已确认归属但没有 AX 界面的窗口返回空快照,仍可截图和发送坐标输入。不同窗口分别保留快照,读取一个窗口不会使另一个窗口失效;重新读取同一范围会使旧索引失效。观察期间节点被移除时,该次读取返回 `STALE_SNAPSHOT`,不发布部分树;可以重新读取,但不要重复此前的输入。应用级截图和坐标操作复用最近一次 AX 观察:优先使用其中在屏幕上且尺寸非零的焦点窗口,否则要求只有一个可见的普通层窗口。它们不会重新查询即时焦点;需要跟随焦点变化时,先读取 `app.getAXState()`。显式窗口对象保持选定的目标。键盘方法保留在 `app` 上,因为输入跟随应用的当前焦点。 `hover(target)` 优先通过控件声明的 AX 动作展开替代界面,不移动系统鼠标。进入展开区域的子控件时保持父控件展开,离开后恢复默认界面。没有这条路径时,再将可见系统鼠标移到 AX 元素中心或窗口内坐标,不按鼠标按钮,也可用于禁用控件。所选应用必须在前台,且目标点未被遮挡,否则返回 `FOREGROUND_REQUIRED`,调用方需显式激活或抬起窗口并重新观察。调用结束、AX 读取和截图不恢复先前的位置。等待应用的悬停延迟后,观察出现的内容,再移入并点击;连续调用可经过中间位置。其他输入或应用自身变化可能中断交互。[连续交互的设计理由](../../../.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.zh.md)。 @@ -174,7 +174,7 @@ Use cua with method getCapabilities and params {} to inspect permissions and ses Initialize the object API once in persistent PTC. Reuse its variables in later calls; put temporary declarations inside { ... } blocks to avoid redeclaration errors. All object methods are async. getAXState returns text, not a structured state object. Its text separates values and placeholders, and reports subroles, help, URLs, disabled/focused/selected/expanded state and UTF-16 selection ranges when available. Writability is true, false or unknown on relevant controls; omitted state fields do not assert false. selection=unavailable means the reported range exceeds the observed text. Compact output omits ordinary Press/Pick (click), ShowMenu (right click) and ScrollToVisible actions; details=true lists every available action. Use the displayed action name with performSecondaryAction; ambiguous aliases require the complete name from details=true. Truncation reports the reached provider limit. Narrow the window or increase that provider limit before reading again. -Use app methods directly for single-window tasks; getApp already reads initial AX state. Call app.getWindows() and await app.getWindow(windowId) only to target a particular window or resolve ambiguous window selection. App screenshots and coordinate actions use the latest AX observation: its focused on-screen, nonzero-size window, otherwise the sole such window. They do not refresh focus automatically. Read app.getAXState() to follow changed focus. Independent floating panels have their own window IDs. After opening one, refresh app.getWindows() and select its window for AX, screenshots and input; a panel may leave keyboard focus in the main window. +Use app methods directly for single-window tasks; getApp already reads initial AX state. Call app.getWindows() and await app.getWindow(windowId) only to target a particular window or resolve ambiguous window selection. App screenshots and coordinate actions use the latest AX observation: its focused on-screen, nonzero-size window, otherwise the sole visible normal-layer window. They do not refresh focus automatically. Read app.getAXState() to follow changed focus. Visible panels, menus, tooltips and status items can have their own window IDs. Select a panel from app.getWindows() for its AX, screenshot and input even if the main window retains focus. Use includeHidden:true in listWindows or app.getWindows({includeHidden:true}) to list offscreen and zero-size windows. CuaScreenshot contains { bytes: Uint8Array, mimeType: "image/png" | "image/jpeg" | "image/webp" | "image/gif", pixelWidth: number, pixelHeight: number, windowId: number }. Use mimeType to choose a file extension or declare an image; do not assume PNG. @@ -186,7 +186,7 @@ Object API signatures (options default to { emit: true }): - cua.getState(options?) -> { apps, browsers: [] } - cua.getApp(selector: string) -> App - app.activate() -> { dispatched: true, verified: false } -- app.getWindows(options?) -> Array<{ windowId, pid, appName, title, bounds, isOnScreen, onCurrentSpace }> +- app.getWindows(options?: { emit?: boolean, includeHidden?: boolean }) -> Array<{ windowId, pid, appName, title, bounds, isOnScreen, onCurrentSpace, layer? }> - app.getWindow(windowId: number) -> Window - app.typeText(text: string), app.pressKey(chord: string) -> action result - app.paste(text: string, options?: { format?: "text" | "html" }) -> action result @@ -216,7 +216,7 @@ Use selectText only on controls advertising selectionWritable. It selects a uniq #### Token 影响 -启用插件会增加固定参数定义和指导文本。AX 观察、操作结果和已接入的图片会增加模型输入。本包不将保留的对象序列化进提示。 +启用插件会增加固定参数定义和指导文本。AX 观察、操作结果和已接入的图片会增加模型输入。默认窗口清单只列出可见窗口和显式观察的目标。请求完整清单时,每个窗口都会增加一条记录,包括隐藏的辅助窗口。 #### KV Cache 影响 diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index c5ae58f7b1..1de8edda81 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -18,11 +18,11 @@ en: 1435672513328c05 zh: 11e7a1e672410c10 /dsh-cua-native-helper/request-protocol: - en: f255df742509459a - zh: 99605a3712c8b8d4 + en: cc296f843e622f8d + zh: a0f69119bf98d720 /dsh-cua-native-helper/observation-and-input: en: 4912c5317dd0dafa - zh: 5be17a0c776959a5 + zh: 86db5a1c0c5b4555 /dsh-cua-native-helper/verification: en: 6d5444d4907e0a2b zh: 65bf25758bafb358 diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index 65ec51c060..da92c70cd9 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -74,7 +74,7 @@ Successful `activate` and `performSecondaryAction` AXRaise results include `fore | `findApps` | Installed matches `{id, displayName, path, isRunning, pid?}` from standard application directories or an absolute application path; discovery never launches them. | | `getApp` | `{appHandle, pid, name, bundleId, authorization}` selected by exact name, bundle ID, decimal PID or application path. A stopped selection has `pid: null` and waits for Host consent. Ambiguous names fail. | | `launchApp` | Host-only continuation after consent; starts the selected application without requesting activation, waits for launch completion and binds the handle to its verified process identity. | -| `listWindows` | Owned windows across all layers, including independent floating panels and menus, with `{windowId, pid, appName, title, bounds, isOnScreen, onCurrentSpace}`. Space membership can be null. | +| `listWindows` | All WindowServer layers owned by the selected process (including offscreen windows, panels, menus, tooltips and status items). Nonzero levels include a numeric `layer` alongside `{windowId, pid, appName, title, bounds, isOnScreen, onCurrentSpace}`. Space membership can be null. | | `getState` | `{appHandle, pid, windowId, focusedWindowId, snapshotId, tree, elements, windows, truncated}`. `windowId` is null for an app-wide observation. Elements include index, role, title, value, description, identifier, bounds, actions, and enabled state. Element bounds are null or [x, y, width, height] in screen points; window input uses local points. These structured element diagnostics are retained by native checks and omitted by the model tool projection. Unavailable optional descriptive properties are null, and an unavailable action list is empty; permission, communication and window-discovery failures still reject the observation. | | `hover`, `click`, `setValue`, `selectText`, `typeText`, `paste`, `pressKey`, `scroll`, `drag` | `{dispatched: true, verified: false}` records native dispatch. Read fresh state to verify the intended application change. | | `screenshot` | `{mimeType: "image/png", data, pixelWidth, pixelHeight, bounds, coordinateSpace: "window-points", windowId}`. PNG pixel dimensions can differ from window point dimensions on Retina displays. | diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index 2f9c7302d2..5182fbee2a 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -74,7 +74,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 | `findApps` | 从标准应用目录或绝对应用路径返回已安装匹配项 `{id, displayName, path, isRunning, pid?}`;发现过程不启动应用。 | | `getApp` | 按精确名称、bundle ID、十进制 PID 或应用路径选择,返回 `{appHandle, pid, name, bundleId, authorization}`。未运行的选择具有 `pid: null`,等待 Host 授权。名称歧义会失败。 | | `launchApp` | 授权后的 Host 专用续接操作;不请求激活,等待应用启动完成后将句柄绑定到已核实的进程身份。 | -| `listWindows` | 应用所属各层级窗口,包括独立浮层和菜单,包含 `{windowId, pid, appName, title, bounds, isOnScreen, onCurrentSpace}`。Space 归属可为 null。 | +| `listWindows` | 所选进程在 WindowServer 中的全部窗口,包括离屏窗口、面板、菜单、工具提示和状态栏图标。非零层级另含数字字段 `layer`。窗口字段包括 `{windowId, pid, appName, title, bounds, isOnScreen, onCurrentSpace}`。Space 归属可为 null。 | | `getState` | `{appHandle, pid, windowId, focusedWindowId, snapshotId, tree, elements, windows, truncated}`。应用级观察的 `windowId` 为 null。元素包含 index、role、title、value、description、identifier、bounds、actions 和 enabled 状态。元素边界为 null 或屏幕 point 单位的 [x, y, width, height],窗口输入使用局部 point。这些结构化元素诊断供原生检查保留,模型工具投影会移除它们。不可用的可选描述属性为 null,无法取得的动作列表为空;权限、通信和窗口发现失败仍会拒绝观察。 | | `hover`, `click`, `setValue`, `selectText`, `typeText`, `paste`, `pressKey`, `scroll`, `drag` | `{dispatched: true, verified: false}` 记录原生分派。需要读取新状态以核实预期的应用变化。 | | `screenshot` | `{mimeType: "image/png", data, pixelWidth, pixelHeight, bounds, coordinateSpace: "window-points", windowId}`。Retina 显示器上 PNG 像素尺寸可能不同于窗口 point 尺寸。 | @@ -93,7 +93,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 ## 观察与输入 -`getState` 可将 AX 遍历限定到应用所属窗口或嵌套 sheet 的 `windowId`。 窗口清单与 `listWindows` 一致,窗口级观察会登记所选浮层的坐标信息。截图单独捕获所选窗口,因此主窗口截图不包含独立浮层。新的刷新或失败的刷新使同一应用/窗口范围的旧快照失效,其他窗口范围仍可使用。应用所属 CG 窗口没有匹配 AX 界面时,getState 返回空 tree/elements、truncated 为 false 的新快照,仍可截图和坐标输入。遍历后重新检查进程生命期、窗口归属、会话未锁定及辅助功能权限。窗口发现中的 APIDisabled 和通信错误仍会失败;不支持或缺失的可选 AX 属性可以产生空观察。不存在或属于其他应用的窗口不会返回空成功结果。遍历中 AX 元素失效会以 `STALE_SNAPSHOT` 拒绝整次读取,不发布部分树。应用变化后可以重新观察,但不重复输入。元素动作要求精确的快照 ID,原生引用不跨 JSON 传递。坐标动作的可选快照 ID 必须属于该窗口或应用级观察。刷新窗口列表会释放已关闭窗口的快照。进程身份、快照代次和窗口归属检查不会锁住桌面,用户或应用仍可同时改变状态。 +`getState` 可将 AX 遍历限定到应用所属窗口或嵌套 sheet 的 `windowId`。窗口清单与 `listWindows` 一致,窗口级观察会登记所选浮层的坐标信息。截图单独捕获所选窗口,因此主窗口截图不包含独立浮层。新的刷新或失败的刷新使同一应用/窗口范围的旧快照失效,其他窗口范围仍可使用。应用所属 CG 窗口没有匹配 AX 界面时,getState 返回空 tree/elements、truncated 为 false 的新快照,仍可截图和坐标输入。遍历后重新检查进程生命期、窗口归属、会话未锁定及辅助功能权限。窗口发现中的 APIDisabled 和通信错误仍会失败;不支持或缺失的可选 AX 属性可以产生空观察。不存在或属于其他应用的窗口不会返回空成功结果。遍历中 AX 元素失效会以 `STALE_SNAPSHOT` 拒绝整次读取,不发布部分树。应用变化后可以重新观察,但不重复输入。元素动作要求精确的快照 ID,原生引用不跨 JSON 传递。坐标动作的可选快照 ID 必须属于该窗口或应用级观察。刷新窗口列表会释放已关闭窗口的快照。进程身份、快照代次和窗口归属检查不会锁住桌面,用户或应用仍可同时改变状态。 未指定 holdMs 的元素点击优先使用声明的 AX 动作,否则通过鼠标事件发送。坐标点击、滚动和拖动核实窗口归属和边界后,使用后台 PID/窗口定向输入。事件优先使用 SkyLight,不可用时使用公开的 PID 定向 API;已发送的事件不通过另一 API 重发。坐标是整个窗口左上角起算的 macOS point,包含标题栏。`deltaLinesY` 为正时显示上方内容,为负时显示下方内容;`deltaLinesX` 为正时显示左侧内容,为负时显示右侧内容。每个轴接受 -10 到 10 的整数,至少一个轴非零。helper 直接发送按行计量的滚轮事件。点击和拖动支持左、右、中键及 command/control/option/shift/fn 修饰键,只有左键支持双击。带修饰键的元素点击使用鼠标输入。拖动在一个窗口中完成一次按下、移动、抬起,调用方显式提供 durationMs(1..5000)和 steps(1..240)。移动延迟按小数精度分配到各段,按下和抬起的固定等待及调度延迟另计。不存在隐式改用全局桌面输入的后备路径。 diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/NativePlatform.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/NativePlatform.swift index 81a599639d..16ad44be07 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/NativePlatform.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/NativePlatform.swift @@ -158,7 +158,7 @@ enum NativePlatform { return WindowInfo(windowID: id, pid: pid, appName: row[kCGWindowOwnerName as String] as? String ?? "", title: row[kCGWindowName as String] as? String ?? "", bounds: bounds, isOnScreen: (row[kCGWindowIsOnscreen as String] as? NSNumber)?.boolValue ?? false, - onCurrentSpace: memberships[id]?.onCurrentSpace) + onCurrentSpace: memberships[id]?.onCurrentSpace, layer: (row[kCGWindowLayer as String] as? NSNumber)?.intValue ?? 0) } } static func frontPID() -> Int32? { WindowSpaces().frontPID() } diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/Protocol.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/Protocol.swift index 762ecaea49..22e30ee776 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/Protocol.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/Protocol.swift @@ -138,12 +138,15 @@ struct WindowInfo: Sendable { let bounds: WindowBounds let isOnScreen: Bool let onCurrentSpace: Bool? + let layer: Int var json: JSONValue { - .object([ + var fields: [String: JSONValue] = [ "windowId": .number(Double(windowID)), "pid": .number(Double(pid)), "appName": .string(appName), "title": .string(title), "bounds": bounds.json, "isOnScreen": .bool(isOnScreen), "onCurrentSpace": onCurrentSpace.map(JSONValue.bool) ?? .null, - ]) + ] + if layer != 0 { fields["layer"] = .number(Double(layer)) } + return .object(fields) } } diff --git a/packages/experimental/cua-macos/native/generate-protocol.ts b/packages/experimental/cua-macos/native/generate-protocol.ts index 1374c6fdfa..232441e758 100644 --- a/packages/experimental/cua-macos/native/generate-protocol.ts +++ b/packages/experimental/cua-macos/native/generate-protocol.ts @@ -37,7 +37,10 @@ export function renderNativeProtocol(): { json: string; swift: string } { const extension = resources.get(method) for (const variant of variants(params)) { // The Host resolves image pixels and relative coordinates before native dispatch. - if (variant.properties) delete variant.properties.relative + if (variant.properties) { + delete variant.properties.relative + if (method === 'listWindows') delete variant.properties.includeHidden + } if (variant.required) variant.required = variant.required.filter(name => name !== 'relative') if (extension !== undefined) { const extra = z.toJSONSchema(extension) diff --git a/packages/experimental/cua-macos/native/tests/floating_windows_e2e.py b/packages/experimental/cua-macos/native/tests/floating_windows_e2e.py index 62aa14fa53..9d8dc464d8 100644 --- a/packages/experimental/cua-macos/native/tests/floating_windows_e2e.py +++ b/packages/experimental/cua-macos/native/tests/floating_windows_e2e.py @@ -61,6 +61,7 @@ def main(): assert panel_id in [window['windowId'] for window in windows], windows assert all(window['pid'] == fixture.pid for window in windows), windows listed = next(window for window in windows if window['windowId'] == panel_id) + assert listed['layer'] == actual['panelLayer'], listed assert listed['onCurrentSpace'] is True, listed application = helper.call('getState', params) assert application['focusedWindowId'] == actual['mainWindowId'], application diff --git a/packages/experimental/cua-macos/native/tests/swift/ProtocolTests.swift b/packages/experimental/cua-macos/native/tests/swift/ProtocolTests.swift index 611fa6786c..f9626c250f 100644 --- a/packages/experimental/cua-macos/native/tests/swift/ProtocolTests.swift +++ b/packages/experimental/cua-macos/native/tests/swift/ProtocolTests.swift @@ -43,7 +43,7 @@ func refusesInvalidRequestEnvelopes(_ source: String) { let window = WindowInfo( windowID: 7, pid: 42, appName: "Fixture", title: "Canvas", bounds: WindowBounds(x: -100, y: 40, width: 320, height: 200), - isOnScreen: true, onCurrentSpace: nil + isOnScreen: true, onCurrentSpace: nil, layer: 0 ) let encoded = try JSONEncoder().encode(window.json) let object = try #require(JSONSerialization.jsonObject(with: encoded) as? [String: Any]) diff --git a/packages/experimental/cua-macos/native/tests/swift/WindowCaptureTests.swift b/packages/experimental/cua-macos/native/tests/swift/WindowCaptureTests.swift index da0b2a8546..9655640147 100644 --- a/packages/experimental/cua-macos/native/tests/swift/WindowCaptureTests.swift +++ b/packages/experimental/cua-macos/native/tests/swift/WindowCaptureTests.swift @@ -34,7 +34,7 @@ private final class HeldCapture: @unchecked Sendable { let worker = AXWorker(cancellation: cancellation, axTimeout: 1, textEventInterval: 0, maxClickHoldMs: 5000) let target = CaptureTarget(appHandle: "fixture", process: ProcessIdentity(pid: 1, startedSeconds: 1, startedMicroseconds: 0), window: WindowInfo(windowID: 1, pid: 1, appName: "fixture", title: "fixture", - bounds: WindowBounds(x: 0, y: 0, width: 1, height: 1), isOnScreen: true, onCurrentSpace: true)) + bounds: WindowBounds(x: 0, y: 0, width: 1, height: 1), isOnScreen: true, onCurrentSpace: true, layer: 0)) func request() -> Task { Task { try await scheduler.perform(cancellation: cancellation) { diff --git a/packages/experimental/cua-macos/native/tests/swift/WindowGeometryTests.swift b/packages/experimental/cua-macos/native/tests/swift/WindowGeometryTests.swift index 33362e80a4..8a4b686097 100644 --- a/packages/experimental/cua-macos/native/tests/swift/WindowGeometryTests.swift +++ b/packages/experimental/cua-macos/native/tests/swift/WindowGeometryTests.swift @@ -70,7 +70,7 @@ private let geometryOwner = ProcessIdentity(pid: 42, startedSeconds: 1, startedM private func geometryWindow(_ bounds: WindowBounds) -> WindowInfo { WindowInfo(windowID: 7, pid: geometryOwner.pid, appName: "Fixture", title: "Fixture", bounds: bounds, - isOnScreen: true, onCurrentSpace: true) + isOnScreen: true, onCurrentSpace: true, layer: 0) } @Test func resolveDetectsMovementDuringTheAXQueryEvenWhenTheFinalFramesMatch() { diff --git a/packages/experimental/cua-macos/src/guidance.ts b/packages/experimental/cua-macos/src/guidance.ts index 3c5d0dd53a..15e9bf0c44 100644 --- a/packages/experimental/cua-macos/src/guidance.ts +++ b/packages/experimental/cua-macos/src/guidance.ts @@ -4,7 +4,7 @@ export const GUIDANCE = `Use cua with method getCapabilities and params {} to in Initialize the object API once in persistent PTC. Reuse its variables in later calls; put temporary declarations inside { ... } blocks to avoid redeclaration errors. All object methods are async. getAXState returns text, not a structured state object. Its text separates values and placeholders, and reports subroles, help, URLs, disabled/focused/selected/expanded state and UTF-16 selection ranges when available. Writability is true, false or unknown on relevant controls; omitted state fields do not assert false. selection=unavailable means the reported range exceeds the observed text. Compact output omits ordinary Press/Pick (click), ShowMenu (right click) and ScrollToVisible actions; details=true lists every available action. Use the displayed action name with performSecondaryAction; ambiguous aliases require the complete name from details=true. Truncation reports the reached provider limit. Narrow the window or increase that provider limit before reading again. -Use app methods directly for single-window tasks; getApp already reads initial AX state. Call app.getWindows() and await app.getWindow(windowId) only to target a particular window or resolve ambiguous window selection. App screenshots and coordinate actions use the latest AX observation: its focused on-screen, nonzero-size window, otherwise the sole such window. They do not refresh focus automatically. Read app.getAXState() to follow changed focus. Independent floating panels have their own window IDs. After opening one, refresh app.getWindows() and select its window for AX, screenshots and input; a panel may leave keyboard focus in the main window. +Use app methods directly for single-window tasks; getApp already reads initial AX state. Call app.getWindows() and await app.getWindow(windowId) only to target a particular window or resolve ambiguous window selection. App screenshots and coordinate actions use the latest AX observation: its focused on-screen, nonzero-size window, otherwise the sole visible normal-layer window. They do not refresh focus automatically. Read app.getAXState() to follow changed focus. Visible panels, menus, tooltips and status items can have their own window IDs. Select a panel from app.getWindows() for its AX, screenshot and input even if the main window retains focus. Use includeHidden:true in listWindows or app.getWindows({includeHidden:true}) to list offscreen and zero-size windows. CuaScreenshot contains { bytes: Uint8Array, mimeType: "image/png" | "image/jpeg" | "image/webp" | "image/gif", pixelWidth: number, pixelHeight: number, windowId: number }. Use mimeType to choose a file extension or declare an image; do not assume PNG. @@ -16,7 +16,7 @@ Object API signatures (options default to { emit: true }): - cua.getState(options?) -> { apps, browsers: [] } - cua.getApp(selector: string) -> App - app.activate() -> { dispatched: true, verified: false } -- app.getWindows(options?) -> Array<{ windowId, pid, appName, title, bounds, isOnScreen, onCurrentSpace }> +- app.getWindows(options?: { emit?: boolean, includeHidden?: boolean }) -> Array<{ windowId, pid, appName, title, bounds, isOnScreen, onCurrentSpace, layer? }> - app.getWindow(windowId: number) -> Window - app.typeText(text: string), app.pressKey(chord: string) -> action result - app.paste(text: string, options?: { format?: "text" | "html" }) -> action result diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index bb45e394c9..82ab6ac682 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -427,6 +427,33 @@ it('keeps native element diagnostics out of model-visible state and structured t expect(JSON.parse(content.text)).toEqual(visible) }) +it('omits hidden windows from model output without forgetting their observed coordinates', async () => { + const f = await setup() + await selectApplication(f) + const params = { appHandle: 'app-one' } + const main = { windowId: 7, pid: 17, appName: 'Fixture', title: 'Main', + bounds: { x: 0, y: 0, width: 10, height: 10 }, isOnScreen: true, onCurrentSpace: true } + const panel = { ...main, windowId: 8, layer: 3, onCurrentSpace: null } + const hidden = { ...panel, windowId: 9, isOnScreen: false } + const all = [main, panel, hidden, { ...main, windowId: 10, onCurrentSpace: false }, + { ...main, windowId: 11, bounds: { ...main.bounds, width: 0 } }] + for (const [includeHidden, expected] of [[false, [main, panel]], [true, all]] as const) { + native.request.mockResolvedValueOnce(all) + const result = await f.execute('listWindows', { ...params, includeHidden }) + expect(result.value).toEqual(expected) + expect(result.content).toEqual([{ type: 'text', text: JSON.stringify(expected) }]) + } + for (const windowId of [null, 9]) { + native.request.mockResolvedValueOnce({ ...params, pid: 17, windowId, windows: all, snapshotId: 's', tree: '', truncated: false }) + const result = await f.execute('getState', windowId === null ? params : { ...params, windowId }) + expect(result.value).toMatchObject({ windows: windowId === null ? [main, panel] : [main, panel, hidden] }) + } + native.request.mockResolvedValueOnce(all) + await f.execute('listWindows', params) + native.request.mockResolvedValueOnce({ dispatched: true, verified: false }) + expect((await f.execute('click', { ...params, windowId: 9, x: 500, y: 500, relative: true })).isError).toBe(false) +}) + it('preserves screenshot attachments and invalidates pixel coordinates when window listings observe a resize', async () => { const f = await setup({ provider: 'image-fixture', model: 'vision' }) await selectApplication(f) diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index 7adacc3f3c..1de10158b5 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -15,8 +15,8 @@ en: 5db4d4fea25493b9 zh: 65ab64fc24eb0d09 /deepseek-ai-dsh-cua/use-this-package: - en: ed736a45140a6d56 - zh: 8dc89373a0a88fcc + en: 0f7ca6b5ab4303d9 + zh: db753aeccd0c9c07 /deepseek-ai-dsh-cua/use-this-package/permission-controls: en: d92d5948a7941e8d zh: d43491ae6521b87e diff --git a/packages/experimental/cua/README.md b/packages/experimental/cua/README.md index 7dd223645d..a2fd06f2e7 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -29,7 +29,7 @@ Application consent supplies English, Chinese, and Japanese display text from `s Mount the [macOS provider](../cua-macos/README.md) to enable native operations. External PTC hosts import `connectCua` from `@deepseek-ai/dsh-cua/bridge` and supply the current `tools.cua` binding. Source compositions and native preparation belong to the provider. -Use App methods for a single-window task. `getApp` reads initial accessibility state; `getWindows` and `getWindow` select an explicit window when needed. Re-reading one app/window scope replaces its element indices without invalidating another window's snapshot. Keyboard input follows the application's focus. Invalid request arguments reject before dispatch with a readable method, parameter and requirement. +Use App methods for a single-window task. `getApp` reads initial accessibility state; `getWindows` and `getWindow` select an explicit window when needed. Re-reading one app/window scope replaces its element indices without invalidating another window's snapshot. Keyboard input follows the application's focus. Invalid request arguments reject before dispatch with a readable method, parameter and requirement. Default discovery returns visible windows; use `getWindows({ includeHidden: true })` for the complete inventory. Observation methods emit and return their result. Use `void await app.getAXState()` for one visible copy, or use `emit:false` and print the returned text once. Screenshots return `CuaScreenshot` with `bytes`, `mimeType`, `pixelWidth`, `pixelHeight`, and `windowId`. The image sink receives the same object. Use its MIME type when selecting a file extension or declaring an image; the format can be PNG, JPEG, WebP, or GIF. Each screenshot enters the attachment pipeline once; `emit:false` only suppresses the object sink. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index dda0f716bf..7f89ee6463 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -29,7 +29,7 @@ kind: "package-reference" 挂载 [macOS 提供方](../cua-macos/README.zh.md)以启用原生操作。外部 PTC 宿主从 `@deepseek-ai/dsh-cua/bridge` 导入 `connectCua`,并提供当前 `tools.cua` 绑定。源码组合与原生组件准备由提供方负责。 -单窗口任务直接使用 App 方法。`getApp` 读取初始辅助功能状态;需要指定窗口时使用 `getWindows` 和 `getWindow`。重新读取一个应用或窗口范围会替换其中的元素编号,不使其他窗口的快照失效。键盘输入跟随应用焦点。请求参数校验失败时,在分派前返回包含方法、参数和要求的可读消息。 +单窗口任务直接使用 App 方法。`getApp` 读取初始辅助功能状态;需要指定窗口时使用 `getWindows` 和 `getWindow`。重新读取一个应用或窗口范围会替换其中的元素编号,不使其他窗口的快照失效。键盘输入跟随应用焦点。请求参数校验失败时,在分派前返回包含方法、参数和要求的可读消息。默认只列出可见窗口,需要完整清单时使用 `getWindows({ includeHidden: true })`。 观察方法会输出并返回结果。使用 `void await app.getAXState()` 只展示一份内容,或使用 `emit:false` 后打印一次返回文本。截图返回包含 `bytes`、`mimeType`、`pixelWidth`、`pixelHeight` 和 `windowId` 的 `CuaScreenshot`,图片输出回调接收同一个对象。选择文件后缀或声明图片时使用其中的 MIME 类型;格式可能是 PNG、JPEG、WebP 或 GIF。每张截图只进入一次附件处理链;`emit:false` 只抑制对象层的输出。 diff --git a/packages/experimental/cua/src/api.ts b/packages/experimental/cua/src/api.ts index 9a3dfb7a12..a4d6d35314 100644 --- a/packages/experimental/cua/src/api.ts +++ b/packages/experimental/cua/src/api.ts @@ -4,6 +4,7 @@ import type { z } from 'zod' import type { JsonValue } from '@deepseek-ai/dsh-util-values' import { ActionResult, AppResult, AppsResult, CapabilitiesResult, FoundAppsResult, HoverResult, Request, ScreenshotResult, ShowResult, StateResult, WindowsResult } from './protocol.ts' import type { CuaApi, CuaApp, CuaAppHandle, CuaDispatch, CuaObservationOptions, CuaObservationSink, CuaOperation, CuaScreenshot, CuaSurface, CuaWindow } from './types.ts' +import { isVisibleWindow } from './windows.ts' export type * from './types.ts' function requestIssueMessage(issues: readonly z.core.$ZodIssue[], parent: readonly PropertyKey[] = []): string { @@ -69,11 +70,12 @@ export function createCuaApi(dispatch: CuaDispatch, sink?: CuaObservationSink): } function windowId(): number { if (selectedWindow !== undefined) return selectedWindow - const windows = observed?.windows.filter(window => window.isOnScreen && window.bounds.width > 0 && window.bounds.height > 0) + const windows = observed?.windows.filter(isVisibleWindow) const focused = windows?.find(window => window.windowId === observed?.focusedWindowId) if (focused) return focused.windowId - const first = windows?.[0] - if (!first || windows.length !== 1) throw new Error('Select a window with app.getWindows() and app.getWindow(windowId) before this operation') + const ordinary = windows?.filter(window => !window.layer) + const first = ordinary?.[0] + if (!first || ordinary.length !== 1) throw new Error('Select a window with app.getWindows() and app.getWindow(windowId) before this operation') return first.windowId } const result: CuaSurface = { @@ -194,7 +196,7 @@ export function createCuaApi(dispatch: CuaDispatch, sink?: CuaObservationSink): ...surface(appHandle, pid), pid, appHandle, async activate() { return action('activate', { appHandle }) }, async getWindows(options) { - const windows = WindowsResult.parse(await call('listWindows', { appHandle })) + const windows = WindowsResult.parse(await call('listWindows', { appHandle, ...options?.includeHidden === undefined ? {} : { includeHidden: options.includeHidden } })) if (windows.some(window => window.pid !== pid)) throw new Error('Native windows belong to another application') await emit(windows, options) return windows diff --git a/packages/experimental/cua/src/index.ts b/packages/experimental/cua/src/index.ts index c776941a7b..db13b4fa8a 100644 --- a/packages/experimental/cua/src/index.ts +++ b/packages/experimental/cua/src/index.ts @@ -18,6 +18,7 @@ import { ApplicationAuthorizationResult, installCuaAccess } from './access.ts' import type { CuaApplicationGrant, CuaApplicationId, CuaSystemPermission } from './access-types.ts' import type { CuaAppHandle, CuaOperation } from './types.ts' import { ApplicationIcon, AppResult, NativeScreenshotResult, Request, ScreenshotResult, StateResult, WindowsResult } from './protocol.ts' +import { isVisibleWindow } from './windows.ts' import { CuaCoordinates } from './coordinates.ts' import { createScope, type Scope } from '@deepseek-ai/dsh-scope' import type {} from '@deepseek-ai/dsh-agent-preset-registry' @@ -229,6 +230,7 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) const callNative = async (request: CuaOperation, execution: Readonly) => { const { method, params: parsedParams } = request const params = execution.coordinates.parameters(request) + if (method === 'listWindows') delete params.includeHidden const agent = execution.agent const signal = execution.signal signal.throwIfAborted() @@ -282,9 +284,13 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) if (method === 'getState') { const state = StateResult.parse(result) execution.coordinates.observe(state.appHandle, state.windows, state.windowId ?? undefined) - return state + return { ...state, windows: state.windows.filter(window => window.windowId === state.windowId || isVisibleWindow(window)) } + } + if (method === 'listWindows') { + const windows = WindowsResult.parse(result) + execution.coordinates.observe(parsedParams.appHandle as CuaAppHandle, windows) + return parsedParams.includeHidden ? windows : windows.filter(isVisibleWindow) } - if (method === 'listWindows') execution.coordinates.observe(parsedParams.appHandle as CuaAppHandle, WindowsResult.parse(result)) return result } const tool: ToolDefinition = { diff --git a/packages/experimental/cua/src/protocol.ts b/packages/experimental/cua/src/protocol.ts index 2918014fac..e39b6a4270 100644 --- a/packages/experimental/cua/src/protocol.ts +++ b/packages/experimental/cua/src/protocol.ts @@ -37,7 +37,7 @@ export const Request = z.discriminatedUnion('method', [ operation('getApp', { selector: z.string().min(1) }), operation('activate', app), operation('show', { ...app, windowId: id.optional() }), - operation('listWindows', app), + operation('listWindows', { ...app, includeHidden: z.boolean().optional().describe('Include offscreen and zero-size windows for explicit selection or restoration.') }), operation('getState', { ...app, windowId: id.optional(), includeMenus: z.boolean().optional().describe('Expand menu contents; omitted or false shows menu-bar entries only.'), details: z.boolean().optional().describe('Include identifiers, global-point bounds and complete action names.'), @@ -101,7 +101,7 @@ export const FoundAppsResult = z.array(z.intersection(z.object({ id: z.string(). /** Current windows and their global point bounds. */ export const WindowsResult = z.array(z.object({ windowId: id, pid, appName: z.string(), title: z.string(), bounds, - isOnScreen: z.boolean(), onCurrentSpace: z.boolean().nullable(), + isOnScreen: z.boolean(), onCurrentSpace: z.boolean().nullable(), layer: z.number().int().optional(), })) /** Observed state with window and process identity for stale-target rejection. */ export const StateResult = z.object({ diff --git a/packages/experimental/cua/src/types.ts b/packages/experimental/cua/src/types.ts index ac0c16e90b..5c4422f482 100644 --- a/packages/experimental/cua/src/types.ts +++ b/packages/experimental/cua/src/types.ts @@ -49,7 +49,7 @@ export type CuaAppInfo = Pick, 'id export type CuaFoundAppInfo = z.output[number] /** Window bounds in global macOS points. Local operations use an origin of [0,0]. */ export type CuaBounds = CuaWindowInfo['bounds'] -/** Observed window metadata; identifiers are valid only while the window exists, and null Space membership is unknown. */ +/** Window IDs expire on destruction. An omitted layer is normal level zero; null Space membership is unknown. */ export type CuaWindowInfo = z.output[number] /** Successful input dispatch; application outcome still requires observation. */ export type CuaActionResult = z.output @@ -175,7 +175,7 @@ export interface CuaWindow extends CuaSurface { readonly windowId: number } /** * Native app handle supporting direct observations and actions without window enumeration. * Screenshots and coordinates reuse the latest AX observation's focused on-screen, - * nonzero-size window, or require exactly one such window. Read fresh AX to follow + * nonzero-size window, or the sole visible normal-layer window. Read fresh AX to follow * focus changes; explicit window objects retain their selected target. */ export interface CuaApp extends CuaSurface { @@ -187,11 +187,11 @@ export interface CuaApp extends CuaSurface { */ activate(): Promise /** - * Enumerate current windows. - * @param options - output options. + * Enumerate visible windows, including independent panels and menus. + * @param options - Output options; includeHidden returns the complete inventory for explicit selection. * @returns current window records. */ - getWindows(options?: CuaObservationOptions): Promise + getWindows(options?: CuaObservationOptions & { includeHidden?: boolean }): Promise /** * Observe a specific window. * @param windowId - ID obtained from getWindows. diff --git a/packages/experimental/cua/src/windows.ts b/packages/experimental/cua/src/windows.ts new file mode 100644 index 0000000000..0e499e7ad2 --- /dev/null +++ b/packages/experimental/cua/src/windows.ts @@ -0,0 +1,11 @@ +/** WindowServer visibility used for model observations and app-level target selection. */ +import type { CuaWindowInfo } from './types.ts' + +/** + * Whether the window can appear in default discovery on the current desktop. + * @param window - WindowServer record; unavailable Space membership remains unknown. + * @returns Whether a positive-size window is on screen and not known to be on another Space. + */ +export function isVisibleWindow(window: CuaWindowInfo): boolean { + return window.isOnScreen && window.onCurrentSpace !== false && window.bounds.width > 0 && window.bounds.height > 0 +} diff --git a/packages/experimental/cua/tests/api.spec.ts b/packages/experimental/cua/tests/api.spec.ts index eeed87c861..f66c19deda 100644 --- a/packages/experimental/cua/tests/api.spec.ts +++ b/packages/experimental/cua/tests/api.spec.ts @@ -299,7 +299,8 @@ describe('application and window observations', () => { ] f.setWindowRecords(windows) const app = await f.api.getApp('Editor') - expect(await app.getWindows({ emit: false })).toEqual(windows) + expect(await app.getWindows({ emit: false, includeHidden: true })).toEqual(windows) + expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'listWindows', params: { appHandle: 'app-17', includeHidden: true } }) await app.getScreenshot() expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'screenshot', params: { appHandle: 'app-17', windowId: 23 } }) await app.click([10, 20]) @@ -334,6 +335,32 @@ describe('application and window observations', () => { expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'screenshot', params: { appHandle: 'app-17', windowId: 24 } }) }) + it('uses only the sole ordinary window as a fallback without AX focus', async () => { + const f = fixture() + const app = await f.api.getApp('Editor') + const panel = { ...windowInfo(24), layer: 3 } + const status = { ...windowInfo(25), layer: 25 } + for (const [windows, target] of [ + [[panel, status, windowInfo(23)], 23], + [[panel, status], null], + [[windowInfo(23), status, windowInfo(26)], null], + ] as const) { + f.dispatch.mockResolvedValueOnce(state({ focusedWindowId: null, windows: [...windows] })) + await app.getAXState() + if (target === null) { + await expect(app.getScreenshot()).rejects.toThrow('Select a window') + await expect(app.click([0, 0])).rejects.toThrow('Select a window') + } else { + expect((await app.getScreenshot()).windowId).toBe(target) + await app.click([0, 0]) + expect(f.dispatch.mock.lastCall?.[0].params).toMatchObject({ windowId: target }) + } + } + f.dispatch.mockResolvedValueOnce(state({ focusedWindowId: 24, windows: [panel, status, windowInfo(23)] })) + await app.getAXState() + expect((await app.getScreenshot()).windowId).toBe(24) + }) + it('captures and clicks an explicitly selected floating panel while the main window keeps focus', async () => { const f = fixture() const app = await f.api.getApp('Editor') diff --git a/snapshots/session/cua-native/replay.override.json b/snapshots/session/cua-native/replay.override.json index 8c0531f14b..39f083c44d 100644 --- a/snapshots/session/cua-native/replay.override.json +++ b/snapshots/session/cua-native/replay.override.json @@ -1781,6 +1781,39 @@ } ] }, + { + "kind": "chunks", + "chunks": [ + { + "type": "block-start", + "index": 0, + "blockType": "tool-call" + }, + { + "type": "block-end", + "index": 0, + "block": { + "type": "tool-call", + "id": "cua-floating-complete-list", + "name": "cua", + "arguments": "{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\",\"includeHidden\":true}}" + } + }, + { + "type": "usage", + "usage": { + "inputTokens": 3, + "outputTokens": 3 + } + }, + { + "type": "finish", + "reason": { + "kind": "tool-calls" + } + } + ] + }, { "kind": "chunks", "chunks": [ @@ -1796,7 +1829,7 @@ "type": "tool-call", "id": "cua-floating-refresh", "name": "cua", - "arguments": "{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}" + "arguments": "{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}" } }, { diff --git a/snapshots/session/cua-native/workspace/native-helper.mjs b/snapshots/session/cua-native/workspace/native-helper.mjs index ec52fe6f1e..7be762e166 100755 --- a/snapshots/session/cua-native/workspace/native-helper.mjs +++ b/snapshots/session/cua-native/workspace/native-helper.mjs @@ -113,8 +113,10 @@ function createApplicationState(socket, record, application, captureBroker, conn const bounds = { x: 40, y: 60, width: 320, height: 200 } const window = { windowId: 7, pid: 9, appName: 'Fixture', title: 'CUA fixture', bounds, isOnScreen: true, onCurrentSpace: true } const axlessWindow = { ...window, windowId: 8, title: 'AXless canvas' } - const floatingWindow = { ...window, windowId: 10, title: 'Floating panel', bounds: { x: 100, y: 120, width: 240, height: 140 } } + const floatingWindow = { ...window, windowId: 10, layer: 3, title: 'Floating panel', bounds: { x: 100, y: 120, width: 240, height: 140 } } const transformedWindow = { ...window, windowId: 9, title: 'Transformed window', bounds: { x: 16, y: 512, width: 131, height: 145 } } + const inventory = () => [window, axlessWindow, transformedWindow, ...application.floating + ? [floatingWindow, { ...floatingWindow, windowId: 11, title: 'Cached panel', isOnScreen: false }] : []] const screenshotConfig = new URL('./fixture-screenshot.json', import.meta.url) const customScreenshot = existsSync(screenshotConfig) ? JSON.parse(readFileSync(screenshotConfig, 'utf8')) : undefined const snapshots = new Map() @@ -160,7 +162,7 @@ function createApplicationState(socket, record, application, captureBroker, conn before, after, activationRequested, raiseRequested: false, } } } - if (method === 'listWindows') return [window, axlessWindow, ...application.floating ? [floatingWindow] : []] + if (method === 'listWindows') return inventory() if (method === 'getState') { snapshots.delete(params.windowId ?? null) if (observationChanged) { @@ -173,14 +175,14 @@ function createApplicationState(socket, record, application, captureBroker, conn snapshots.set(params.windowId ?? null, { snapshotId, windowId: params.windowId ?? null, axless }) if (params.windowId === 10 && application.floating) return { appHandle: app.appHandle, pid: 9, windowId: 10, snapshotId, focusedWindowId: 7, tree: `AX scope=window offsets=UTF-16\n- AXWindow "Floating panel"\n - [0] AXButton "Increment floating panel"\n - AXStaticText "Floating count: ${application.floatingCount}"`, - elements: [], windows: [window, axlessWindow, floatingWindow], truncated: false } + elements: [], windows: inventory(), truncated: false } if (axless) return { appHandle: app.appHandle, pid: 9, windowId: 8, snapshotId, - tree: '', elements: [], windows: [axlessWindow], truncated: false } + tree: '', elements: [], focusedWindowId: 7, windows: inventory(), truncated: false } return { appHandle: app.appHandle, pid: 9, windowId: params.windowId ?? null, snapshotId: `${scope}-snapshot-${generation}`, tree: `AX scope=${params.windowId === undefined ? 'application' : 'window'} offsets=UTF-16${params.details ? ' bounds=global-points' : ''}\n- [0] AXButton "Increment"${params.details ? ' id="increment" actions=["AXPress"] bounds=[60,80,100,20]' : ''}\n- [1] AXTextField valueWritable=true selectionWritable=true value=${JSON.stringify(application.value)} placeholder="Fixture text"\n- AXStaticText "Count: ${application.count}"${application.hovering ? '\n- AXStaticText "Hover information"' : ''}\n- [2] AXMenuBarItem "File"${params.includeMenus ? '\n - [3] AXMenuItem "Fixture command"' : '\nMenu contents omitted; request includeMenus=true to expand.'}`, elements: [{ index: 0, role: 'AXButton', title: 'Increment', value: null, description: null, identifier: null, bounds: [60, 80, 100, 20], actions: ['AXPress'], enabled: true }], - windows: [params.windowId === 9 ? transformedWindow : window], truncated: false } + focusedWindowId: 7, windows: inventory(), truncated: false } } if (params.windowId === 9 && ['screenshot', 'hover', 'click', 'scroll', 'drag'].includes(method) && params.elementIndex === undefined) { refuse('WINDOW_CHANGED', 'Window display and accessibility bounds disagree. Read fresh state; if unchanged, use AX actions or explicitly restore the window before capture or coordinate input')