From f87efaaff9ac62effe59c36494cd9540ba89322a Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 21 Oct 2026 14:32:37 +0800 Subject: [PATCH 001/184] fix(cua): include floating windows in application observations --- packages/experimental/cua-macos/README.md | 2 +- packages/experimental/cua-macos/README.zh.md | 2 +- .../cua-macos/native/README.i18n.yaml | 12 +- .../experimental/cua-macos/native/README.md | 6 +- .../cua-macos/native/README.zh.md | 6 +- .../native/Sources/CuaNative/AXWorker.swift | 4 +- .../Sources/CuaNative/NativePlatform.swift | 20 +- .../native/tests/FloatingWindowFixture.swift | 82 ++++++ .../native/tests/floating_windows_e2e.py | 119 +++++++++ .../cua-macos/native/upstream.json | 2 +- .../experimental/cua-macos/src/guidance.ts | 2 +- packages/experimental/cua/tests/api.spec.ts | 19 ++ .../session/cua-native/replay.override.json | 233 +++++++++++++++++- .../cua-native/workspace/native-helper.mjs | 13 +- 14 files changed, 497 insertions(+), 25 deletions(-) create mode 100644 packages/experimental/cua-macos/native/tests/FloatingWindowFixture.swift create mode 100644 packages/experimental/cua-macos/native/tests/floating_windows_e2e.py diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index e55c6a2f6b..e44dcfafcf 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -159,7 +159,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. +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. 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. diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 5a63638f44..780bd63e55 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -159,7 +159,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. +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. 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. diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index b25c409fb1..07a247a03b 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -18,14 +18,14 @@ en: 02b25ac1126b6094 zh: 3995a1f46354531b /dsh-cua-native-helper/request-protocol: - en: c8ad13843989b314 - zh: 2a42acb2faee8803 + en: 0fcf99df88166563 + zh: 71b7c3958e91d676 /dsh-cua-native-helper/observation-and-input: - en: c527eedc3a0ee968 - zh: ce8cc12d5a62e8ae + en: 968679773d0d8d33 + zh: 7796e6f76eda961f /dsh-cua-native-helper/verification: - en: a2ac6f2d581a1e8b - zh: f82c7d0c13539421 + en: abc45c2899d7c2bb + zh: bafb1f071d0bc2b2 /dsh-cua-native-helper/further-exploration: en: 265e1927952ce6d7 zh: 7c35d9fd98b6e6c8 diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index b44d6a65f4..9e8702619b 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -48,7 +48,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 normal windows with `{windowId, pid, appName, title, bounds, isOnScreen, onCurrentSpace}`. Space membership can be null. | +| `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. | | `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. | @@ -67,7 +67,7 @@ Protocol declarations are generated from [the shared protocol](../../cua/src/pro ## Observation and input -`getState` optionally scopes AX traversal to an owned window or nested sheet `windowId`. A new or failed refresh invalidates the previous snapshot for that app/window scope, while other window scopes remain usable. When an owned CG window has no matching AX surface, getState returns a new snapshot with empty tree/elements and no truncation; its coordinates and screenshots remain available. It rechecks process lifetime, window ownership, the unlocked session and Accessibility permission after traversal. Window-discovery APIDisabled and communication errors remain failures; unsupported or absent optional AX attributes can produce an empty observation. Missing or foreign-owned windows never produce an empty success. An AX element invalidated during traversal rejects the whole read with `STALE_SNAPSHOT`; no partial snapshot is published. Callers may read again after the application changes, without repeating input. Element actions require the exact snapshot ID. Native references never cross JSON. An optional snapshot ID on coordinate actions must belong to that window or an app-wide observation. Window-list refresh releases snapshots for closed windows. Native process identity, snapshot generation, and window ownership checks do not lock the desktop against simultaneous user or application changes. +`getState` optionally scopes AX traversal to an owned window or nested sheet `windowId`. Its window inventory matches `listWindows`; scoped observations register the selected floating window for coordinate input. Screenshots capture the selected window separately, so a main-window capture does not include independent floating panels. A new or failed refresh invalidates the previous snapshot for that app/window scope, while other window scopes remain usable. When an owned CG window has no matching AX surface, getState returns a new snapshot with empty tree/elements and no truncation; its coordinates and screenshots remain available. It rechecks process lifetime, window ownership, the unlocked session and Accessibility permission after traversal. Window-discovery APIDisabled and communication errors remain failures; unsupported or absent optional AX attributes can produce an empty observation. Missing or foreign-owned windows never produce an empty success. An AX element invalidated during traversal rejects the whole read with `STALE_SNAPSHOT`; no partial snapshot is published. Callers may read again after the application changes, without repeating input. Element actions require the exact snapshot ID. Native references never cross JSON. An optional snapshot ID on coordinate actions must belong to that window or an app-wide observation. Window-list refresh releases snapshots for closed windows. Native process identity, snapshot generation, and window ownership checks do not lock the desktop against simultaneous user or application changes. Element clicks without holdMs prefer advertised AX actions and otherwise use pointer delivery. Coordinate click, scroll and drag validate window ownership and bounds, then use background PID/window-directed primitives. 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. Modified element clicks use pointer delivery. 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. No implicit fallback sends global desktop input. @@ -107,6 +107,8 @@ Run `python3 packages/experimental/cua-macos/native/tests/shared_helper_e2e.py - Run `python3 packages/experimental/cua-macos/native/tests/launcher_identity_e2e.py --helper /absolute/helper` in a GUI login session to verify a Launch Services application that starts a nested GUI launcher and then the helper. The helper identifies the outer responsible application and retains its name and icon after the launchers exit. This check owns both applications and the helper, cleans up its Launch Services registrations, and does not request Accessibility or Screen Recording access. +Run `python3 packages/experimental/cua-macos/native/tests/floating_windows_e2e.py` after building to verify a nonactivating floating panel: discovery, Space metadata, scoped AX, separate main/panel screenshots, received clicks across inventory refreshes, and resize/close rejection. The check requires existing Accessibility and Screen Recording grants and owns its AppKit application. `--helper` selects an existing helper for comparison. + Run `python3 packages/experimental/cua-macos/native/tests/axless_e2e.py` after building and unlocking the Mac to verify an owned window whose application removes and later restores its AX roots. The check requires existing Accessibility/Screen Recording grants, rejects stale element indices, captures the AXless window, verifies a coordinate click in the fixture state file, and checks restoration. It never changes system permission settings. Run `python3 packages/experimental/cua-macos/native/tests/observation_benchmark.py --reference-helper /absolute/reference --candidate-helper /absolute/candidate --artifacts /private/evidence` to compare complete observations of the same owned AppKit window with 35 and 400 synthetic rows. Each helper receives one warmup and three alternating measured requests. All result fields must match except helper-generated app and snapshot IDs. The report keeps raw timings, byte counts, hashes and replies; it sets no CI speed threshold and makes no memory claim. Fixture startup can activate the application. Run without other desktop automation or compilation jobs. diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index ecefb9c879..f24f3f43e5 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -48,7 +48,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` | 应用所属各层级窗口,包括独立浮层和菜单,包含 `{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 尺寸。 | @@ -67,7 +67,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 ## 观察与输入 -`getState` 可将 AX 遍历限定到应用所属窗口或嵌套 sheet 的 `windowId`。新的刷新或失败的刷新使同一应用/窗口范围的旧快照失效,其他窗口范围仍可使用。应用所属 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)。移动延迟按小数精度分配到各段,按下和抬起的固定等待及调度延迟另计。不存在隐式改用全局桌面输入的后备路径。 @@ -107,6 +107,8 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 在 GUI 登录会话中运行 `python3 packages/experimental/cua-macos/native/tests/launcher_identity_e2e.py --helper /absolute/helper`,验证由 Launch Services 启动的应用先启动另一个 GUI 启动器,再启动 helper。helper 识别外层责任应用,并在启动器退出后保留其名称和图标。检查只使用测试自建的两个应用和 helper,结束后清理对应的 Launch Services 注册,不申请辅助功能或屏幕录制权限。 +构建后运行 `python3 packages/experimental/cua-macos/native/tests/floating_windows_e2e.py`,验证不获取焦点的浮层:窗口发现、Space 信息、窗口级 AX、主窗口与浮层分别截图、刷新窗口清单后的实际点击,以及尺寸变化和关闭后的拒绝行为。检查需要已有辅助功能和屏幕录制权限,AppKit 应用由测试创建和清理。`--helper` 可指定已有 helper 作比较。 + 构建并解锁 Mac 后运行 `python3 packages/experimental/cua-macos/native/tests/axless_e2e.py`,验证应用移除并恢复 AX 根节点的窗口。检查需要已有辅助功能/屏幕录制权限,会拒绝过期元素索引,捕获无 AX 窗口,通过 fixture 状态文件核实坐标点击,并检查恢复。不会修改系统权限设置。 运行 `python3 packages/experimental/cua-macos/native/tests/observation_benchmark.py --reference-helper /absolute/reference --candidate-helper /absolute/candidate --artifacts /private/evidence`,对比同一自建 AppKit 窗口中 35 行和 400 行合成内容的完整观察。每个 helper 先预热一次,再交替测量三次。除 helper 生成的应用和快照 ID 外,结果字段必须一致。报告保留原始耗时、字节数、哈希和回复,不设置 CI 性能阈值,也不声称内存表现。fixture 启动可能激活应用。运行时避免其他桌面自动化或编译任务。 diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift index c11c78dc2e..4ac4c96a98 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift @@ -250,7 +250,7 @@ actor AXWorker { } let identity = try validateIdentity(handle) if method == "listWindows" { - let windows = NativePlatform.windows().filter { $0.pid == identity.pid } + let windows = NativePlatform.applicationWindows(identity.pid) // Remove closed window scopes using the current WindowServer identity set. let ids = Set(windows.map(\.windowID)) snapshots = snapshots.filter { key, _ in key.appHandle != handle || (key.windowID.map { ids.contains($0) } ?? true) } @@ -299,7 +299,7 @@ actor AXWorker { try NativePlatform.requireAccessibility() if let window { _ = try NativePlatform.ownedWindow(identity.pid, window) } try cancellation.check() - let observedWindows = NativePlatform.windows().filter { $0.pid == identity.pid } + let observedWindows = NativePlatform.applicationWindows(identity.pid) let id = try identifier("snapshot") let scope = SnapshotScope(appHandle: handle, windowID: window) snapshots[scope] = NativeSnapshot(id: id, scope: scope, elements: projection.indexed) diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/NativePlatform.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/NativePlatform.swift index e4dcfe354e..b4a1859c5f 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/NativePlatform.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/NativePlatform.swift @@ -110,12 +110,22 @@ enum NativePlatform { guard CGPreflightScreenCaptureAccess() else { throw NativeFailure(code: "PERMISSION_DENIED", message: "Screen Recording permission is required for the responsible host/helper") } } static func windows(allLayers: Bool = false) -> [WindowInfo] { - guard let rows = CGWindowListCopyWindowInfo(.excludeDesktopElements, kCGNullWindowID) as? [[String: Any]] else { return [] } - let memberships = allLayers ? [:] : WindowSpaces().memberships(windowIDs: rows.compactMap { ($0[kCGWindowNumber as String] as? NSNumber)?.uint32Value }) + let rows = windowRows().filter { allLayers || (($0[kCGWindowLayer as String] as? NSNumber)?.intValue ?? 0) == 0 } + return windowInfo(rows, includeSpaces: !allLayers) + } + /// App observations include floating panels and menus, with the same Space metadata as normal windows. + static func applicationWindows(_ pid: Int32) -> [WindowInfo] { + let rows = windowRows().filter { ($0[kCGWindowOwnerPID as String] as? NSNumber)?.int32Value == pid } + return windowInfo(rows, includeSpaces: true) + } + private static func windowRows() -> [[String: Any]] { + CGWindowListCopyWindowInfo(.excludeDesktopElements, kCGNullWindowID) as? [[String: Any]] ?? [] + } + private static func windowInfo(_ rows: [[String: Any]], includeSpaces: Bool) -> [WindowInfo] { + let memberships = includeSpaces + ? WindowSpaces().memberships(windowIDs: rows.compactMap { ($0[kCGWindowNumber as String] as? NSNumber)?.uint32Value }) : [:] return rows.compactMap { row in - let layer = (row[kCGWindowLayer as String] as? NSNumber)?.intValue ?? 0 - guard allLayers || layer == 0, - let id = (row[kCGWindowNumber as String] as? NSNumber)?.uint32Value, + guard let id = (row[kCGWindowNumber as String] as? NSNumber)?.uint32Value, let pid = (row[kCGWindowOwnerPID as String] as? NSNumber)?.int32Value else { return nil } let raw = row[kCGWindowBounds as String] as? [String: NSNumber] ?? [:] let bounds = WindowBounds(x: raw["X"]?.doubleValue ?? 0, y: raw["Y"]?.doubleValue ?? 0, diff --git a/packages/experimental/cua-macos/native/tests/FloatingWindowFixture.swift b/packages/experimental/cua-macos/native/tests/FloatingWindowFixture.swift new file mode 100644 index 0000000000..a95a8dfb94 --- /dev/null +++ b/packages/experimental/cua-macos/native/tests/FloatingWindowFixture.swift @@ -0,0 +1,82 @@ +import AppKit +import Darwin + +final class FloatingPanel: NSPanel { + override var canBecomeKey: Bool { false } +} + +/// Publishes actual window geometry and received actions independently of the helper. +final class FloatingWindowFixture: NSObject, NSApplicationDelegate { + let statePath: String + var main: NSWindow! + var panel: FloatingPanel! + var button: NSButton! + var panelID = 0 + var count = 0 + var resized = false + var closed = false + var controls: [DispatchSourceSignal] = [] + var observer: Timer? + + init(statePath: String) { self.statePath = statePath } + func applicationDidFinishLaunching(_ notification: Notification) { + main = NSWindow(contentRect: NSRect(x: 120, y: 180, width: 420, height: 300), + styleMask: [.titled, .closable], backing: .buffered, defer: false) + main.title = "Floating fixture main" + panel = FloatingPanel(contentRect: NSRect(x: 220, y: 250, width: 240, height: 140), + styleMask: [.titled, .nonactivatingPanel], backing: .buffered, defer: false) + panel.title = "Floating fixture panel" + panel.level = .floating + panel.hidesOnDeactivate = false + for window in [main!, panel!] { + window.isReleasedWhenClosed = false + window.animationBehavior = .none + window.collectionBehavior = [.canJoinAllApplications, .stationary] + } + button = NSButton(title: "Increment floating panel", target: self, action: #selector(increment)) + button.frame = NSRect(x: 20, y: 45, width: 200, height: 40) + panel.contentView!.addSubview(button) + main.makeKeyAndOrderFront(nil) + NSApplication.shared.activate(ignoringOtherApps: true) + panel.orderFrontRegardless() + panelID = panel.windowNumber + for number in [SIGUSR1, SIGUSR2] { + signal(number, SIG_IGN) + let control = DispatchSource.makeSignalSource(signal: number, queue: .main) + control.setEventHandler { [weak self] in + guard let self else { return } + if number == SIGUSR1 { self.panel.close(); self.closed = true } + else { self.panel.setContentSize(NSSize(width: 280, height: 180)); self.resized = true } + self.persist() + } + control.resume() + controls.append(control) + } + // WindowServer visibility and frame updates settle after AppKit requests return. + observer = Timer.scheduledTimer(withTimeInterval: 0.05, repeats: true) { [weak self] _ in self?.persist() } + persist() + print("READY") + fflush(stdout) + } + @objc func increment() { count += 1; persist() } + func persist() { + let rows = CGWindowListCopyWindowInfo(.excludeDesktopElements, kCGNullWindowID) as? [[String: Any]] ?? [] + let row = rows.first { ($0[kCGWindowNumber as String] as? NSNumber)?.intValue == panelID } + let rect = button.convert(button.bounds, to: nil) + let data = try! JSONSerialization.data(withJSONObject: [ + "pid": getpid(), "mainWindowId": main.windowNumber, "panelWindowId": panelID, + "panelLayer": row?[kCGWindowLayer as String] ?? -1, + "panelOnScreen": row?[kCGWindowIsOnscreen as String] ?? false, + "panelSize": [panel.frame.width, panel.frame.height], + "buttonPoint": [rect.midX, panel.frame.height - rect.midY], + "count": count, "resized": resized, "closed": closed, + ]) + try! data.write(to: URL(fileURLWithPath: statePath), options: .atomic) + } +} + +let app = NSApplication.shared +app.setActivationPolicy(.regular) +let fixture = FloatingWindowFixture(statePath: CommandLine.arguments[1]) +app.delegate = fixture +app.run() diff --git a/packages/experimental/cua-macos/native/tests/floating_windows_e2e.py b/packages/experimental/cua-macos/native/tests/floating_windows_e2e.py new file mode 100644 index 0000000000..a3988509b6 --- /dev/null +++ b/packages/experimental/cua-macos/native/tests/floating_windows_e2e.py @@ -0,0 +1,119 @@ +"""Discover, capture and operate an owned nonactivating floating panel on macOS.""" +import argparse +import base64 +import json +import os +from pathlib import Path +import plistlib +import signal +import subprocess +import tempfile +import time + +from native_test_support import ROOT, NativeHelper, line, run_cleanup, stop + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--helper', type=Path, help='Existing native helper executable') + args = parser.parse_args() + if os.uname().sysname != 'Darwin': + raise RuntimeError('This check requires macOS') + helper = NativeHelper([], args.helper) + fixture = None + try: + capabilities = helper.call('getCapabilities', {}) + if capabilities['sessionLocked'] is not False or capabilities['permissions'] != {'accessibility': True, 'screenRecording': True}: + raise RuntimeError('An unlocked Mac with Accessibility and Screen Recording grants is required') + with tempfile.TemporaryDirectory(prefix='dsh-floating-window-') as directory: + root = Path(directory) + contents = root / 'FloatingFixture.app/Contents' + (contents / 'MacOS').mkdir(parents=True) + (contents / 'Info.plist').write_bytes(plistlib.dumps({ + 'CFBundleIdentifier': 'org.deepseek-harness.' + root.name, + 'CFBundleExecutable': 'fixture', 'CFBundleName': 'Floating fixture', 'CFBundlePackageType': 'APPL', + })) + binary = contents / 'MacOS/fixture' + subprocess.run(['swiftc', str(ROOT / 'tests/FloatingWindowFixture.swift'), '-o', str(binary)], check=True) + state_path = root / 'state.json' + fixture = subprocess.Popen([str(binary), str(state_path)], stdout=subprocess.PIPE, text=True) + try: + assert line(fixture).strip() == 'READY' + + def wait_state(predicate): + deadline = time.monotonic() + 10 + while True: + state = json.loads(state_path.read_text()) + assert state['pid'] == fixture.pid, state + if predicate(state): + return state + if time.monotonic() >= deadline: + raise AssertionError('Fixture state did not settle: ' + json.dumps(state)) + time.sleep(0.025) + + actual = wait_state(lambda value: value['panelOnScreen'] and value['panelLayer'] > 0) + app = helper.call('getApp', {'selector': str(fixture.pid)}) + owner = {'appHandle': app['appHandle']} + panel_id = actual['panelWindowId'] + params = {**owner, 'maxElements': 100, 'maxDepth': 15} + panel = {**params, 'windowId': panel_id} + windows = helper.call('listWindows', owner) + 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['onCurrentSpace'] is True, listed + application = helper.call('getState', params) + assert application['focusedWindowId'] == actual['mainWindowId'], application + assert panel_id in [window['windowId'] for window in application['windows']], application + observed = helper.call('getState', panel) + assert 'Increment floating panel' in observed['tree'], observed + assert panel_id in [window['windowId'] for window in observed['windows']], observed + x, y = actual['buttonPoint'] + target = {**owner, 'windowId': panel_id, 'snapshotId': observed['snapshotId'], 'x': x, 'y': y} + helper.call('click', target) + wait_state(lambda value: value['count'] == 1) + main_capture = helper.call('screenshot', {**owner, 'windowId': actual['mainWindowId']}) + capture = helper.call('screenshot', {**owner, 'windowId': panel_id}) + assert capture['windowId'] == panel_id and main_capture['windowId'] == actual['mainWindowId'] + assert [capture['bounds']['width'], capture['bounds']['height']] == actual['panelSize'], capture + assert capture['bounds'] != main_capture['bounds'], (capture['bounds'], main_capture['bounds']) + assert base64.b64decode(capture['data'], validate=True).startswith(b'\x89PNG\r\n\x1a\n') + helper.call('click', target) + wait_state(lambda value: value['count'] == 2) + helper.call('listWindows', owner) + helper.call('click', target) + wait_state(lambda value: value['count'] == 3) + helper.call('getState', params) + helper.call('click', target) + wait_state(lambda value: value['count'] == 4) + os.kill(fixture.pid, signal.SIGUSR2) + actual = wait_state(lambda value: value['resized'] and value['panelSize'] != actual['panelSize']) + helper.call('click', target, 'WINDOW_CHANGED') + fresh = helper.call('getState', panel) + helper.call('click', target, 'STALE_SNAPSHOT') + x, y = actual['buttonPoint'] + target = {**target, 'snapshotId': fresh['snapshotId'], 'x': x, 'y': y} + helper.call('click', target) + wait_state(lambda value: value['count'] == 5) + os.kill(fixture.pid, signal.SIGUSR1) + wait_state(lambda value: value['closed'] and not value['panelOnScreen']) + deadline = time.monotonic() + 10 + while panel_id in [window['windowId'] for window in helper.call('listWindows', owner)]: + if time.monotonic() >= deadline: + raise AssertionError('Closed panel remains in WindowServer inventory') + time.sleep(0.025) + helper.call('click', target, 'STALE_SNAPSHOT') + helper.call('getState', panel, 'WINDOW_UNAVAILABLE') + helper.call('screenshot', {**owner, 'windowId': panel_id}, 'WINDOW_UNAVAILABLE') + helper.eof() + print('PASS: floating discovery, Space metadata, scoped AX, distinct captures, five received clicks, refresh, resize and close') + finally: + stop(fixture) + fixture.stdout.close() + fixture = None + finally: + run_cleanup(lambda: stop(fixture) if fixture is not None else None, helper.stop) + + +if __name__ == '__main__': + main() diff --git a/packages/experimental/cua-macos/native/upstream.json b/packages/experimental/cua-macos/native/upstream.json index df84ce4dbb..969c3c7273 100644 --- a/packages/experimental/cua-macos/native/upstream.json +++ b/packages/experimental/cua-macos/native/upstream.json @@ -33,7 +33,7 @@ { "local": "Sources/CuaNative/NativePlatform.swift", "upstream": "libs/cua-driver/rust/crates/platform-macos/src/apps/mod.rs", - "changes": "Reimplement application and window discovery using Swift AppKit/CoreGraphics, preserve process-lifetime checks, and isolate AppKit access on the main actor." + "changes": "Reimplement application and window discovery using Swift AppKit/CoreGraphics, preserve process-lifetime checks, and isolate AppKit access on the main actor. Enumerate app-owned windows across all layers with Space metadata while retaining normal-window queries for foreground diagnostics." } ], "localFiles": [ diff --git a/packages/experimental/cua-macos/src/guidance.ts b/packages/experimental/cua-macos/src/guidance.ts index 6a4392ee9d..3c5d0dd53a 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. +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. 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. diff --git a/packages/experimental/cua/tests/api.spec.ts b/packages/experimental/cua/tests/api.spec.ts index 6d1f4278cf..35d44a35e8 100644 --- a/packages/experimental/cua/tests/api.spec.ts +++ b/packages/experimental/cua/tests/api.spec.ts @@ -334,6 +334,25 @@ describe('application and window observations', () => { expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'screenshot', params: { appHandle: 'app-17', windowId: 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') + const windows = [windowInfo(23), { ...windowInfo(24), title: 'Floating panel' }] + f.setWindowRecords(windows) + expect(await app.getWindows({ emit: false })).toEqual(windows) + f.dispatch.mockResolvedValueOnce(state({ windowId: 24, focusedWindowId: 23, windows })) + const panel = await app.getWindow(24) + await panel.getScreenshot() + expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'screenshot', params: { appHandle: 'app-17', windowId: 24 } }) + await app.getWindows({ emit: false }) + await panel.click([10, 20]) + expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'click', params: { + appHandle: 'app-17', snapshotId: 'changed', windowId: 24, x: 10, y: 20, mouseButton: 'left', clickCount: 1, + } }) + await app.getScreenshot() + expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'screenshot', params: { appHandle: 'app-17', windowId: 23 } }) + }) + it('does not select a focused window absent from the application observation', 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 2fefba26f5..8c0531f14b 100644 --- a/snapshots/session/cua-native/replay.override.json +++ b/snapshots/session/cua-native/replay.override.json @@ -1649,6 +1649,237 @@ } ] }, + { + "kind": "chunks", + "chunks": [ + { + "type": "block-start", + "index": 0, + "blockType": "tool-call" + }, + { + "type": "block-end", + "index": 0, + "block": { + "type": "tool-call", + "id": "cua-floating-open", + "name": "cua", + "arguments": "{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F8\"}}" + } + }, + { + "type": "usage", + "usage": { + "inputTokens": 3, + "outputTokens": 3 + } + }, + { + "type": "finish", + "reason": { + "kind": "tool-calls" + } + } + ] + }, + { + "kind": "chunks", + "chunks": [ + { + "type": "block-start", + "index": 0, + "blockType": "tool-call" + }, + { + "type": "block-end", + "index": 0, + "block": { + "type": "tool-call", + "id": "cua-floating-list", + "name": "cua", + "arguments": "{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}" + } + }, + { + "type": "usage", + "usage": { + "inputTokens": 3, + "outputTokens": 3 + } + }, + { + "type": "finish", + "reason": { + "kind": "tool-calls" + } + } + ] + }, + { + "kind": "chunks", + "chunks": [ + { + "type": "block-start", + "index": 0, + "blockType": "tool-call" + }, + { + "type": "block-end", + "index": 0, + "block": { + "type": "tool-call", + "id": "cua-floating-observe", + "name": "cua", + "arguments": "{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}" + } + }, + { + "type": "usage", + "usage": { + "inputTokens": 3, + "outputTokens": 3 + } + }, + { + "type": "finish", + "reason": { + "kind": "tool-calls" + } + } + ] + }, + { + "kind": "chunks", + "chunks": [ + { + "type": "block-start", + "index": 0, + "blockType": "tool-call" + }, + { + "type": "block-end", + "index": 0, + "block": { + "type": "tool-call", + "id": "cua-floating-screenshot", + "name": "cua", + "arguments": "{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}" + } + }, + { + "type": "usage", + "usage": { + "inputTokens": 3, + "outputTokens": 3 + } + }, + { + "type": "finish", + "reason": { + "kind": "tool-calls" + } + } + ] + }, + { + "kind": "chunks", + "chunks": [ + { + "type": "block-start", + "index": 0, + "blockType": "tool-call" + }, + { + "type": "block-end", + "index": 0, + "block": { + "type": "tool-call", + "id": "cua-floating-refresh", + "name": "cua", + "arguments": "{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}" + } + }, + { + "type": "usage", + "usage": { + "inputTokens": 3, + "outputTokens": 3 + } + }, + { + "type": "finish", + "reason": { + "kind": "tool-calls" + } + } + ] + }, + { + "kind": "chunks", + "chunks": [ + { + "type": "block-start", + "index": 0, + "blockType": "tool-call" + }, + { + "type": "block-end", + "index": 0, + "block": { + "type": "tool-call", + "id": "cua-floating-click", + "name": "cua", + "arguments": "{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10,\"snapshotId\":\"fixture-snapshot-15\",\"x\":0,\"y\":0}}" + } + }, + { + "type": "usage", + "usage": { + "inputTokens": 3, + "outputTokens": 3 + } + }, + { + "type": "finish", + "reason": { + "kind": "tool-calls" + } + } + ] + }, + { + "kind": "chunks", + "chunks": [ + { + "type": "block-start", + "index": 0, + "blockType": "tool-call" + }, + { + "type": "block-end", + "index": 0, + "block": { + "type": "tool-call", + "id": "cua-floating-verify", + "name": "cua", + "arguments": "{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}" + } + }, + { + "type": "usage", + "usage": { + "inputTokens": 3, + "outputTokens": 3 + } + }, + { + "type": "finish", + "reason": { + "kind": "tool-calls" + } + } + ] + }, { "kind": "chunks", "chunks": [ @@ -1827,7 +2058,7 @@ "index": 0, "block": { "type": "text", - "text": "Observed Count: 4 after hovering, observing and clicking the revealed control. Moving away dismissed the hover information. Geometry conflicts rejected capture and coordinate gestures; the advertised AX button action remained available. No automatic activation or input retry was requested." + "text": "Observed Count: 4 after hovering, observing and clicking the revealed control. Moving away dismissed the hover information. Geometry conflicts rejected capture and coordinate gestures; the advertised AX button action remained available. No automatic activation or input retry was requested. The separately captured floating panel received one click after its window list was refreshed; keyboard focus stayed in the main window." } }, { diff --git a/snapshots/session/cua-native/workspace/native-helper.mjs b/snapshots/session/cua-native/workspace/native-helper.mjs index 2bbaa83188..ec52fe6f1e 100755 --- a/snapshots/session/cua-native/workspace/native-helper.mjs +++ b/snapshots/session/cua-native/workspace/native-helper.mjs @@ -38,7 +38,7 @@ function serve() { } const instanceId = randomUUID() const sockets = new Set() - const application = { count: 0, value: '', visualCount: 0, hovering: false, frontPid: 42, frontWindowId: 99 } + const application = { count: 0, value: '', visualCount: 0, floatingCount: 0, floating: false, hovering: false, frontPid: 42, frontWindowId: 99 } const captureBroker = { pendingCapture: false } let started = false let hadClient = false @@ -113,6 +113,7 @@ 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 transformedWindow = { ...window, windowId: 9, title: 'Transformed window', bounds: { x: 16, y: 512, width: 131, height: 145 } } const screenshotConfig = new URL('./fixture-screenshot.json', import.meta.url) const customScreenshot = existsSync(screenshotConfig) ? JSON.parse(readFileSync(screenshotConfig, 'utf8')) : undefined @@ -159,7 +160,7 @@ function createApplicationState(socket, record, application, captureBroker, conn before, after, activationRequested, raiseRequested: false, } } } - if (method === 'listWindows') return [window, axlessWindow] + if (method === 'listWindows') return [window, axlessWindow, ...application.floating ? [floatingWindow] : []] if (method === 'getState') { snapshots.delete(params.windowId ?? null) if (observationChanged) { @@ -170,6 +171,9 @@ function createApplicationState(socket, record, application, captureBroker, conn const axless = params.windowId === 8 const snapshotId = `${scope}-snapshot-${generation}` 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 } if (axless) return { appHandle: app.appHandle, pid: 9, windowId: 8, snapshotId, tree: '', elements: [], windows: [axlessWindow], truncated: false } return { appHandle: app.appHandle, pid: 9, windowId: params.windowId ?? null, @@ -193,7 +197,8 @@ function createApplicationState(socket, record, application, captureBroker, conn ? { pixelWidth: customScreenshot.pixelWidth, pixelHeight: customScreenshot.pixelHeight, bounds: customScreenshot.bounds, windowId: params.windowId, mimeType: 'image/png', coordinateSpace: 'window-points', data: readFileSync(new URL(customScreenshot.file, import.meta.url)).toString('base64') } - : { windowId: params.windowId, mimeType: 'image/png', data: png, pixelWidth: 1, pixelHeight: 1, bounds, coordinateSpace: 'window-points' } + : { windowId: params.windowId, mimeType: 'image/png', data: png, pixelWidth: 1, pixelHeight: 1, + bounds: params.windowId === 10 ? floatingWindow.bounds : bounds, coordinateSpace: 'window-points' } if (method === 'click' || method === 'setValue' || method === 'hover') { const observed = params.snapshotId === undefined && params.elementIndex === undefined ? snapshots.get(params.windowId) ?? snapshots.get(null) @@ -202,6 +207,7 @@ function createApplicationState(socket, record, application, captureBroker, conn if (params.windowId !== undefined && observed.windowId !== null && observed.windowId !== params.windowId) refuse('STALE_SNAPSHOT', 'Snapshot belongs to another window') if (observed.axless && params.elementIndex !== undefined) refuse('INVALID_ARGUMENT', 'Element index is absent from the selected snapshot') if (method === 'hover') application.hovering = params.elementIndex === 0 || (params.x >= 20 && params.x <= 40) + else if (method === 'click' && params.windowId === 10) application.floatingCount++ else if (method === 'click' && params.windowId === 8) application.visualCount++ else if (method === 'click') application.count++ else application.value = params.value @@ -209,6 +215,7 @@ function createApplicationState(socket, record, application, captureBroker, conn return { dispatched: true, verified: false, ...method === 'hover' ? { hoverRoute: 'accessibility', systemPointerMoved: false } : {} } } if (method === 'pressKey' && params.key === 'Return') observationChanged = true + if (method === 'pressKey' && params.key === 'F8') application.floating = true // Fixture-only keys simulate a pending system callback and its eventual completion. if (method === 'pressKey' && params.key === 'F11') captureBroker.pendingCapture = true if (method === 'pressKey' && params.key === 'F10') captureBroker.pendingCapture = false From fdb975ba9b413f9f8e0cc55e6aa6d48eefdf243f Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 21 Oct 2026 14:36:10 +0800 Subject: [PATCH 002/184] test(cua): record floating panel workflow and destroy closed fixture window --- .../native/tests/FloatingWindowFixture.swift | 19 +- packages/experimental/cua/tests/api.spec.ts | 2 + snapshots/session/cua-native/session.v4.jsonl | 167 +++++++++++------- .../cua-native/system-prompt.expected.md | 2 +- .../session/cua-ptc/system-prompt.expected.md | 2 +- 5 files changed, 120 insertions(+), 72 deletions(-) diff --git a/packages/experimental/cua-macos/native/tests/FloatingWindowFixture.swift b/packages/experimental/cua-macos/native/tests/FloatingWindowFixture.swift index a95a8dfb94..6348ab27fe 100644 --- a/packages/experimental/cua-macos/native/tests/FloatingWindowFixture.swift +++ b/packages/experimental/cua-macos/native/tests/FloatingWindowFixture.swift @@ -15,6 +15,8 @@ final class FloatingWindowFixture: NSObject, NSApplicationDelegate { var count = 0 var resized = false var closed = false + var panelSize: [CGFloat] = [] + var buttonPoint: [CGFloat] = [] var controls: [DispatchSourceSignal] = [] var observer: Timer? @@ -45,7 +47,13 @@ final class FloatingWindowFixture: NSObject, NSApplicationDelegate { let control = DispatchSource.makeSignalSource(signal: number, queue: .main) control.setEventHandler { [weak self] in guard let self else { return } - if number == SIGUSR1 { self.panel.close(); self.closed = true } + if number == SIGUSR1 { + self.panel.close() + // Releasing the retained panel destroys its WindowServer window instead of only hiding it. + self.panel = nil + self.button = nil + self.closed = true + } else { self.panel.setContentSize(NSSize(width: 280, height: 180)); self.resized = true } self.persist() } @@ -62,13 +70,16 @@ final class FloatingWindowFixture: NSObject, NSApplicationDelegate { func persist() { let rows = CGWindowListCopyWindowInfo(.excludeDesktopElements, kCGNullWindowID) as? [[String: Any]] ?? [] let row = rows.first { ($0[kCGWindowNumber as String] as? NSNumber)?.intValue == panelID } - let rect = button.convert(button.bounds, to: nil) + if let panel, let button { + let rect = button.convert(button.bounds, to: nil) + panelSize = [panel.frame.width, panel.frame.height] + buttonPoint = [rect.midX, panel.frame.height - rect.midY] + } let data = try! JSONSerialization.data(withJSONObject: [ "pid": getpid(), "mainWindowId": main.windowNumber, "panelWindowId": panelID, "panelLayer": row?[kCGWindowLayer as String] ?? -1, "panelOnScreen": row?[kCGWindowIsOnscreen as String] ?? false, - "panelSize": [panel.frame.width, panel.frame.height], - "buttonPoint": [rect.midX, panel.frame.height - rect.midY], + "panelSize": panelSize, "buttonPoint": buttonPoint, "count": count, "resized": resized, "closed": closed, ]) try! data.write(to: URL(fileURLWithPath: statePath), options: .atomic) diff --git a/packages/experimental/cua/tests/api.spec.ts b/packages/experimental/cua/tests/api.spec.ts index 35d44a35e8..eeed87c861 100644 --- a/packages/experimental/cua/tests/api.spec.ts +++ b/packages/experimental/cua/tests/api.spec.ts @@ -340,6 +340,8 @@ describe('application and window observations', () => { const windows = [windowInfo(23), { ...windowInfo(24), title: 'Floating panel' }] f.setWindowRecords(windows) expect(await app.getWindows({ emit: false })).toEqual(windows) + f.dispatch.mockResolvedValueOnce(state({ focusedWindowId: 23, windows })) + await app.getAXState() f.dispatch.mockResolvedValueOnce(state({ windowId: 24, focusedWindowId: 23, windows })) const panel = await app.getWindow(24) await panel.getScreenshot() diff --git a/snapshots/session/cua-native/session.v4.jsonl b/snapshots/session/cua-native/session.v4.jsonl index e7587237ab..d47ce2e40e 100644 --- a/snapshots/session/cua-native/session.v4.jsonl +++ b/snapshots/session/cua-native/session.v4.jsonl @@ -12,281 +12,316 @@ {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"}} {"type":"session/title","data":{"title":"Inspect CUA capabilities, select the","messageSeqs":[8],"source":{"kind":"fallback"}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-1","name":"cua","arguments":"{\"method\":\"getCapabilities\",\"params\":{}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947688973,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947688973,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-1","name":"cua","arguments":"{\"method\":\"getCapabilities\",\"params\":{}}"}}},{"type":"chunk","time":1791947688973,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947688973,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-1","name":"cua","arguments":"{\"method\":\"getCapabilities\",\"params\":{}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564511530,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564511530,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-1","name":"cua","arguments":"{\"method\":\"getCapabilities\",\"params\":{}}"}}},{"type":"chunk","time":1792564511530,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564511530,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua-native-1","name":"cua","arguments":"{\"method\":\"getCapabilities\",\"params\":{}}"}} {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-1"},"toolCallId":"cua-native-1","content":[{"type":"text","text":"{\"platform\":\"macos\",\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"methods\":[\"getCapabilities\",\"listApps\",\"getApp\",\"activate\",\"show\",\"listWindows\",\"getState\",\"hover\",\"click\",\"setValue\",\"typeText\",\"paste\",\"pressKey\",\"scroll\",\"drag\",\"screenshot\"],\"coordinateSpace\":\"screenshot-pixels\",\"browser\":false}"}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} -{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-unauthorized-getState","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:6}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689573,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689573,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-unauthorized-getState","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1791947689573,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689573,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-unauthorized-getState","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:6}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512128,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512128,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-unauthorized-getState","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1792564512128,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512128,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"cua-unauthorized-getState","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} {"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-unauthorized-getState"},"toolCallId":"cua-unauthorized-getState","content":[{"type":"text","text":"Error: APP_ACCESS_REQUIRED: Select the application with getApp and obtain user consent before reading or controlling it"}],"isError":true,"id":"{{message:7}}"}},"sourceEventSeqs":[19],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"step/start","data":{"turn":1,"step":3}} -{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-unauthorized-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:8}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689596,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689596,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-unauthorized-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947689596,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689596,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-unauthorized-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:8}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512153,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512153,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-unauthorized-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512153,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512154,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":3,"callId":"cua-unauthorized-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":3,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-unauthorized-screenshot"},"toolCallId":"cua-unauthorized-screenshot","content":[{"type":"text","text":"Error: APP_ACCESS_REQUIRED: Select the application with getApp and obtain user consent before reading or controlling it"}],"isError":true,"id":"{{message:9}}"}},"sourceEventSeqs":[24],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":3}} {"type":"step/start","data":{"turn":1,"step":4}} -{"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-unauthorized-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:10}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689615,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689615,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-unauthorized-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1791947689615,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689615,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-unauthorized-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:10}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512173,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512173,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-unauthorized-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1792564512173,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512173,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":4,"callId":"cua-unauthorized-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0}}"}} {"type":"tool/result","data":{"turn":1,"step":4,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-unauthorized-click"},"toolCallId":"cua-unauthorized-click","content":[{"type":"text","text":"Error: APP_ACCESS_REQUIRED: Select the application with getApp and obtain user consent before reading or controlling it"}],"isError":true,"id":"{{message:11}}"}},"sourceEventSeqs":[29],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":4}} {"type":"step/start","data":{"turn":1,"step":5}} -{"type":"assistant/message","data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-2","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"test.fixture\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:12}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689634,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689634,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-2","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"test.fixture\"}}"}}},{"type":"chunk","time":1791947689634,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689634,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-2","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"test.fixture\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:12}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512194,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512194,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-2","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"test.fixture\"}}"}}},{"type":"chunk","time":1792564512194,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512194,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":5,"callId":"cua-native-2","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"test.fixture\"}}"}} {"type":"tool/result","data":{"turn":1,"step":5,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-2"},"toolCallId":"cua-native-2","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"name\":\"Fixture\",\"bundleId\":\"test.fixture\"}"}],"isError":false,"id":"{{message:13}}"}},"sourceEventSeqs":[34],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":5}} {"type":"step/start","data":{"turn":1,"step":6}} -{"type":"assistant/message","data":{"turn":1,"step":6,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-3","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"includeMenus\":true,\"details\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:14}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689657,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689657,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-3","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"includeMenus\":true,\"details\":true}}"}}},{"type":"chunk","time":1791947689657,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689657,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":6,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-3","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"includeMenus\":true,\"details\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:14}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512221,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512221,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-3","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"includeMenus\":true,\"details\":true}}"}}},{"type":"chunk","time":1792564512221,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512221,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":6,"callId":"cua-native-3","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"includeMenus\":true,\"details\":true}}"}} {"type":"tool/result","data":{"turn":1,"step":6,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-3"},"toolCallId":"cua-native-3","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-1\",\"tree\":\"AX scope=window offsets=UTF-16 bounds=global-points\\n- [0] AXButton \\\"Increment\\\" id=\\\"increment\\\" actions=[\\\"AXPress\\\"] bounds=[60,80,100,20]\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 0\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\n - [3] AXMenuItem \\\"Fixture command\\\"\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:15}}"}},"sourceEventSeqs":[39],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":6}} {"type":"step/start","data":{"turn":1,"step":7}} -{"type":"assistant/message","data":{"turn":1,"step":7,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-4","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0,\"holdMs\":800}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:16}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689683,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689683,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-4","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0,\"holdMs\":800}}"}}},{"type":"chunk","time":1791947689683,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689683,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":7,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-4","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0,\"holdMs\":800}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:16}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512246,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512246,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-4","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0,\"holdMs\":800}}"}}},{"type":"chunk","time":1792564512246,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512246,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":7,"callId":"cua-native-4","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0,\"holdMs\":800}}"}} {"type":"tool/result","data":{"turn":1,"step":7,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-4"},"toolCallId":"cua-native-4","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:17}}"}},"sourceEventSeqs":[44],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":7}} {"type":"step/start","data":{"turn":1,"step":8}} -{"type":"assistant/message","data":{"turn":1,"step":8,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-5","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:18}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689706,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689706,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-5","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947689706,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689706,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":8,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-5","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:18}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512265,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512266,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-5","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512266,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512266,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":8,"callId":"cua-native-5","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":8,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-5"},"toolCallId":"cua-native-5","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-2\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 1\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:19}}"}},"sourceEventSeqs":[49],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":8}} {"type":"step/start","data":{"turn":1,"step":9}} -{"type":"assistant/message","data":{"turn":1,"step":9,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-6","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:20}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689729,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689729,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-6","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947689729,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689729,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":9,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-6","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:20}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512288,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512288,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-6","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512288,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512288,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":9,"callId":"cua-native-6","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":9,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-6"},"toolCallId":"cua-native-6","content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"isError":false,"id":"{{message:21}}"}},"sourceEventSeqs":[54],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":9}} {"type":"step/start","data":{"turn":1,"step":10}} -{"type":"assistant/message","data":{"turn":1,"step":10,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-7","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:22}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689792,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689792,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-7","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1791947689792,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689792,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":10,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-7","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:22}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512368,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512368,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-7","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1792564512368,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512368,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":10,"callId":"cua-native-7","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} {"type":"tool/result","data":{"turn":1,"step":10,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-7"},"toolCallId":"cua-native-7","content":[{"type":"text","text":"[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}]"}],"isError":false,"id":"{{message:23}}"}},"sourceEventSeqs":[59],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":10}} {"type":"step/start","data":{"turn":1,"step":11}} -{"type":"assistant/message","data":{"turn":1,"step":11,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-8","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:24}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689834,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689834,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-8","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}}},{"type":"chunk","time":1791947689834,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689834,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":11,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-8","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:24}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512388,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512388,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-8","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}}},{"type":"chunk","time":1792564512388,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512388,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":11,"callId":"cua-native-8","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}} {"type":"tool/result","data":{"turn":1,"step":11,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-8"},"toolCallId":"cua-native-8","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":8,\"snapshotId\":\"fixture-snapshot-3\",\"tree\":\"\",\"windows\":[{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:25}}"}},"sourceEventSeqs":[64],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":11}} {"type":"step/start","data":{"turn":1,"step":12}} -{"type":"assistant/message","data":{"turn":1,"step":12,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-9","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:26}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689861,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689861,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-9","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}}},{"type":"chunk","time":1791947689861,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689861,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":12,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-9","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:26}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512406,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512406,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-9","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}}},{"type":"chunk","time":1792564512406,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512406,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":12,"callId":"cua-native-9","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}} {"type":"tool/result","data":{"turn":1,"step":12,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-9"},"toolCallId":"cua-native-9","content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":8,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"isError":false,"id":"{{message:27}}"}},"sourceEventSeqs":[69],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":12}} {"type":"step/start","data":{"turn":1,"step":13}} -{"type":"assistant/message","data":{"turn":1,"step":13,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-10","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-3\",\"x\":0,\"y\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:28}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689896,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689896,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-10","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-3\",\"x\":0,\"y\":0}}"}}},{"type":"chunk","time":1791947689896,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689896,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":13,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-10","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-3\",\"x\":0,\"y\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:28}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512445,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512445,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-10","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-3\",\"x\":0,\"y\":0}}"}}},{"type":"chunk","time":1792564512445,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512445,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":13,"callId":"cua-native-10","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-3\",\"x\":0,\"y\":0}}"}} {"type":"tool/result","data":{"turn":1,"step":13,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-10"},"toolCallId":"cua-native-10","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:29}}"}},"sourceEventSeqs":[74],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":13}} {"type":"step/start","data":{"turn":1,"step":14}} -{"type":"assistant/message","data":{"turn":1,"step":14,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-11","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:30}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689918,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689918,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-11","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}}},{"type":"chunk","time":1791947689918,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689918,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":14,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-11","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:30}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512464,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512464,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-11","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}}},{"type":"chunk","time":1792564512464,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512464,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":14,"callId":"cua-native-11","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}} {"type":"tool/result","data":{"turn":1,"step":14,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-11"},"toolCallId":"cua-native-11","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":8,\"snapshotId\":\"fixture-snapshot-4\",\"tree\":\"\",\"windows\":[{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:31}}"}},"sourceEventSeqs":[79],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":14}} {"type":"step/start","data":{"turn":1,"step":15}} -{"type":"assistant/message","data":{"turn":1,"step":15,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-show","name":"cua","arguments":"{\"method\":\"show\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:32}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689940,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689940,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-show","name":"cua","arguments":"{\"method\":\"show\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947689940,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689940,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":15,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-show","name":"cua","arguments":"{\"method\":\"show\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:32}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512484,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512484,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-show","name":"cua","arguments":"{\"method\":\"show\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512484,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512484,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":15,"callId":"cua-native-show","name":"cua","arguments":"{\"method\":\"show\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":15,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-show"},"toolCallId":"cua-native-show","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false,\"windowId\":7,\"foregroundChanged\":false}"}],"isError":false,"id":"{{message:33}}"}},"sourceEventSeqs":[84],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":15}} {"type":"step/start","data":{"turn":1,"step":16}} -{"type":"assistant/message","data":{"turn":1,"step":16,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-activate-first","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:34}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689961,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689961,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-activate-first","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1791947689961,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689961,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":16,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-activate-first","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:34}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512511,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512511,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-activate-first","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1792564512511,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512511,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":16,"callId":"cua-native-activate-first","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} {"type":"tool/result","data":{"turn":1,"step":16,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-activate-first"},"toolCallId":"cua-native-activate-first","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false,\"foreground\":{\"requestId\":\"cua-native-activate-first\",\"operation\":\"activate\",\"targetPid\":9,\"targetWindowId\":null,\"before\":{\"frontPid\":42,\"focusedWindowId\":7,\"frontWindowId\":99,\"frontWindowPid\":42},\"after\":{\"frontPid\":9,\"focusedWindowId\":7,\"frontWindowId\":7,\"frontWindowPid\":9},\"activationRequested\":true,\"raiseRequested\":false}}"}],"isError":false,"id":"{{message:35}}"}},"sourceEventSeqs":[89],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":16}} {"type":"step/start","data":{"turn":1,"step":17}} -{"type":"assistant/message","data":{"turn":1,"step":17,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-activate-repeat","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:36}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689983,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689983,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-activate-repeat","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1791947689983,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689983,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":17,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-activate-repeat","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:36}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512531,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512531,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-activate-repeat","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1792564512531,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512531,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":17,"callId":"cua-native-activate-repeat","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} {"type":"tool/result","data":{"turn":1,"step":17,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-activate-repeat"},"toolCallId":"cua-native-activate-repeat","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false,\"foreground\":{\"requestId\":\"cua-native-activate-repeat\",\"operation\":\"activate\",\"targetPid\":9,\"targetWindowId\":null,\"before\":{\"frontPid\":9,\"focusedWindowId\":7,\"frontWindowId\":7,\"frontWindowPid\":9},\"after\":{\"frontPid\":9,\"focusedWindowId\":7,\"frontWindowId\":7,\"frontWindowPid\":9},\"activationRequested\":false,\"raiseRequested\":false}}"}],"isError":false,"id":"{{message:37}}"}},"sourceEventSeqs":[94],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":17}} {"type":"step/start","data":{"turn":1,"step":18}} -{"type":"assistant/message","data":{"turn":1,"step":18,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-transition","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"Return\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:38}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690002,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690002,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-transition","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"Return\"}}"}}},{"type":"chunk","time":1791947690002,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690002,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":18,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-transition","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"Return\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:38}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512552,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512552,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-transition","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"Return\"}}"}}},{"type":"chunk","time":1792564512552,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512552,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":18,"callId":"cua-native-transition","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"Return\"}}"}} {"type":"tool/result","data":{"turn":1,"step":18,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-transition"},"toolCallId":"cua-native-transition","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:39}}"}},"sourceEventSeqs":[99],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":18}} {"type":"step/start","data":{"turn":1,"step":19}} -{"type":"assistant/message","data":{"turn":1,"step":19,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-stale-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:40}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690019,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690019,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-stale-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690019,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690019,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":19,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-stale-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:40}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512570,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512570,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-stale-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512570,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512570,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":19,"callId":"cua-native-stale-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":19,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-stale-read"},"toolCallId":"cua-native-stale-read","content":[{"type":"text","text":"Error: STALE_SNAPSHOT: Accessibility tree changed during observation; read fresh getAXState"}],"isError":true,"id":"{{message:41}}"}},"sourceEventSeqs":[104],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":19}} {"type":"step/start","data":{"turn":1,"step":20}} -{"type":"assistant/message","data":{"turn":1,"step":20,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-stale-index","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-2\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:42}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690040,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690040,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-stale-index","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-2\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1791947690040,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690040,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":20,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-stale-index","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-2\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:42}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512590,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512590,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-stale-index","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-2\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1792564512590,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512590,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":20,"callId":"cua-native-stale-index","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-2\",\"elementIndex\":0}}"}} {"type":"tool/result","data":{"turn":1,"step":20,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-stale-index"},"toolCallId":"cua-native-stale-index","content":[{"type":"text","text":"Error: STALE_SNAPSHOT: Read fresh state before acting"}],"isError":true,"id":"{{message:43}}"}},"sourceEventSeqs":[109],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":20}} {"type":"step/start","data":{"turn":1,"step":21}} -{"type":"assistant/message","data":{"turn":1,"step":21,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-other-window","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-4\",\"x\":0,\"y\":0,\"holdMs\":800}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:44}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690064,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690064,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-other-window","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-4\",\"x\":0,\"y\":0,\"holdMs\":800}}"}}},{"type":"chunk","time":1791947690064,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690064,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":21,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-other-window","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-4\",\"x\":0,\"y\":0,\"holdMs\":800}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:44}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512616,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512616,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-other-window","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-4\",\"x\":0,\"y\":0,\"holdMs\":800}}"}}},{"type":"chunk","time":1792564512616,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512616,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":21,"callId":"cua-native-other-window","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-4\",\"x\":0,\"y\":0,\"holdMs\":800}}"}} {"type":"tool/result","data":{"turn":1,"step":21,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-other-window"},"toolCallId":"cua-native-other-window","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:45}}"}},"sourceEventSeqs":[114],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":21}} {"type":"step/start","data":{"turn":1,"step":22}} -{"type":"assistant/message","data":{"turn":1,"step":22,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-fresh-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:46}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690087,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690087,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-fresh-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690087,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690087,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":22,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-fresh-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:46}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512634,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512634,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-fresh-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512634,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512634,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":22,"callId":"cua-native-fresh-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":22,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-fresh-read"},"toolCallId":"cua-native-fresh-read","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-5\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 1\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:47}}"}},"sourceEventSeqs":[119],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":22}} {"type":"step/start","data":{"turn":1,"step":23}} -{"type":"assistant/message","data":{"turn":1,"step":23,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-fresh-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-5\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:48}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690111,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690111,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-fresh-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-5\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1791947690111,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690111,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":23,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-fresh-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-5\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:48}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512654,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512654,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-fresh-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-5\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1792564512654,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512654,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":23,"callId":"cua-native-fresh-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-5\",\"elementIndex\":0}}"}} {"type":"tool/result","data":{"turn":1,"step":23,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-fresh-click"},"toolCallId":"cua-native-fresh-click","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:49}}"}},"sourceEventSeqs":[124],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":23}} {"type":"step/start","data":{"turn":1,"step":24}} -{"type":"assistant/message","data":{"turn":1,"step":24,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:50}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690141,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690141,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690141,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690141,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":24,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:50}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512675,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512675,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512675,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512675,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":24,"callId":"cua-native-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":24,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-verify"},"toolCallId":"cua-native-verify","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-6\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 2\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:51}}"}},"sourceEventSeqs":[129],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":24}} {"type":"step/start","data":{"turn":1,"step":25}} -{"type":"assistant/message","data":{"turn":1,"step":25,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:52}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690162,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690162,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}}},{"type":"chunk","time":1791947690162,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690162,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":25,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:52}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512696,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512696,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}}},{"type":"chunk","time":1792564512696,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512696,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":25,"callId":"cua-native-geometry-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}} {"type":"tool/result","data":{"turn":1,"step":25,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-observe"},"toolCallId":"cua-native-geometry-observe","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":9,\"snapshotId\":\"fixture-snapshot-7\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 2\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:53}}"}},"sourceEventSeqs":[134],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":25}} {"type":"step/start","data":{"turn":1,"step":26}} -{"type":"assistant/message","data":{"turn":1,"step":26,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:54}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690186,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690186,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}}},{"type":"chunk","time":1791947690186,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690186,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":26,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:54}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512716,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512716,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}}},{"type":"chunk","time":1792564512716,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512716,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":26,"callId":"cua-native-geometry-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}} {"type":"tool/result","data":{"turn":1,"step":26,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-capture"},"toolCallId":"cua-native-geometry-capture","content":[{"type":"text","text":"Error: 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"}],"isError":true,"id":"{{message:55}}"}},"sourceEventSeqs":[139],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":26}} {"type":"step/start","data":{"turn":1,"step":27}} -{"type":"assistant/message","data":{"turn":1,"step":27,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"snapshotId\":\"fixture-snapshot-7\",\"x\":20,\"y\":20,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:56}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690221,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690221,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"snapshotId\":\"fixture-snapshot-7\",\"x\":20,\"y\":20,\"relative\":true}}"}}},{"type":"chunk","time":1791947690221,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690221,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":27,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"snapshotId\":\"fixture-snapshot-7\",\"x\":20,\"y\":20,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:56}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512734,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512734,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"snapshotId\":\"fixture-snapshot-7\",\"x\":20,\"y\":20,\"relative\":true}}"}}},{"type":"chunk","time":1792564512734,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512734,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":27,"callId":"cua-native-geometry-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"snapshotId\":\"fixture-snapshot-7\",\"x\":20,\"y\":20,\"relative\":true}}"}} {"type":"tool/result","data":{"turn":1,"step":27,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-click"},"toolCallId":"cua-native-geometry-click","content":[{"type":"text","text":"Error: 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"}],"isError":true,"id":"{{message:57}}"}},"sourceEventSeqs":[144],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":27}} {"type":"step/start","data":{"turn":1,"step":28}} -{"type":"assistant/message","data":{"turn":1,"step":28,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-scroll","name":"cua","arguments":"{\"method\":\"scroll\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"x\":20,\"y\":20,\"deltaLinesX\":0,\"deltaLinesY\":-1,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:58}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690248,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690248,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-scroll","name":"cua","arguments":"{\"method\":\"scroll\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"x\":20,\"y\":20,\"deltaLinesX\":0,\"deltaLinesY\":-1,\"relative\":true}}"}}},{"type":"chunk","time":1791947690248,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690248,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":28,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-scroll","name":"cua","arguments":"{\"method\":\"scroll\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"x\":20,\"y\":20,\"deltaLinesX\":0,\"deltaLinesY\":-1,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:58}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512755,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512755,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-scroll","name":"cua","arguments":"{\"method\":\"scroll\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"x\":20,\"y\":20,\"deltaLinesX\":0,\"deltaLinesY\":-1,\"relative\":true}}"}}},{"type":"chunk","time":1792564512755,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512755,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":28,"callId":"cua-native-geometry-scroll","name":"cua","arguments":"{\"method\":\"scroll\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"x\":20,\"y\":20,\"deltaLinesX\":0,\"deltaLinesY\":-1,\"relative\":true}}"}} {"type":"tool/result","data":{"turn":1,"step":28,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-scroll"},"toolCallId":"cua-native-geometry-scroll","content":[{"type":"text","text":"Error: 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"}],"isError":true,"id":"{{message:59}}"}},"sourceEventSeqs":[149],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":28}} {"type":"step/start","data":{"turn":1,"step":29}} -{"type":"assistant/message","data":{"turn":1,"step":29,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-drag","name":"cua","arguments":"{\"method\":\"drag\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"fromX\":20,\"fromY\":20,\"toX\":30,\"toY\":30,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:60}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690267,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690267,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-drag","name":"cua","arguments":"{\"method\":\"drag\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"fromX\":20,\"fromY\":20,\"toX\":30,\"toY\":30,\"relative\":true}}"}}},{"type":"chunk","time":1791947690267,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690267,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":29,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-drag","name":"cua","arguments":"{\"method\":\"drag\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"fromX\":20,\"fromY\":20,\"toX\":30,\"toY\":30,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:60}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512781,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512781,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-drag","name":"cua","arguments":"{\"method\":\"drag\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"fromX\":20,\"fromY\":20,\"toX\":30,\"toY\":30,\"relative\":true}}"}}},{"type":"chunk","time":1792564512781,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512781,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":29,"callId":"cua-native-geometry-drag","name":"cua","arguments":"{\"method\":\"drag\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"fromX\":20,\"fromY\":20,\"toX\":30,\"toY\":30,\"relative\":true}}"}} {"type":"tool/result","data":{"turn":1,"step":29,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-drag"},"toolCallId":"cua-native-geometry-drag","content":[{"type":"text","text":"Error: 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"}],"isError":true,"id":"{{message:61}}"}},"sourceEventSeqs":[154],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":29}} {"type":"step/start","data":{"turn":1,"step":30}} -{"type":"assistant/message","data":{"turn":1,"step":30,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-ax","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-7\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:62}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690294,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690294,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-ax","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-7\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1791947690294,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690294,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":30,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-ax","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-7\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:62}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512800,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512800,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-ax","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-7\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1792564512800,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512800,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":30,"callId":"cua-native-geometry-ax","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-7\",\"elementIndex\":0}}"}} {"type":"tool/result","data":{"turn":1,"step":30,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-ax"},"toolCallId":"cua-native-geometry-ax","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:63}}"}},"sourceEventSeqs":[159],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":30}} {"type":"step/start","data":{"turn":1,"step":31}} -{"type":"assistant/message","data":{"turn":1,"step":31,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:64}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690314,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690314,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}}},{"type":"chunk","time":1791947690314,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690314,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":31,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:64}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512832,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512832,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}}},{"type":"chunk","time":1792564512832,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512832,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":31,"callId":"cua-native-geometry-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}} {"type":"tool/result","data":{"turn":1,"step":31,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-verify"},"toolCallId":"cua-native-geometry-verify","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":9,\"snapshotId\":\"fixture-snapshot-8\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 3\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:65}}"}},"sourceEventSeqs":[164],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":31}} {"type":"step/start","data":{"turn":1,"step":32}} -{"type":"assistant/message","data":{"turn":1,"step":32,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-busy-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F11\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:66}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690340,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690340,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-busy-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F11\"}}"}}},{"type":"chunk","time":1791947690340,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690340,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":32,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-busy-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F11\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:66}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512855,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512855,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-busy-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F11\"}}"}}},{"type":"chunk","time":1792564512855,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512855,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":32,"callId":"cua-capture-busy-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F11\"}}"}} {"type":"tool/result","data":{"turn":1,"step":32,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-capture-busy-arm"},"toolCallId":"cua-capture-busy-arm","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:67}}"}},"sourceEventSeqs":[169],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":32}} {"type":"step/start","data":{"turn":1,"step":33}} -{"type":"assistant/message","data":{"turn":1,"step":33,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-busy","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:68}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690365,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690365,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-busy","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690365,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690365,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":33,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-busy","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:68}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512882,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512882,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-busy","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512882,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512882,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":33,"callId":"cua-capture-busy","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":33,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-capture-busy"},"toolCallId":"cua-capture-busy","content":[{"type":"text","text":"Error: CAPTURE_BUSY: A previous system capture is still pending; other native operations remain available\nScreenshot diagnostics:\n[cua-screenshot] {\"requestId\":\"cua-capture-busy\",\"stage\":\"helper.failed\",\"elapsedMs\":1,\"errorCode\":\"CAPTURE_BUSY\"}"}],"isError":true,"id":"{{message:69}}"}},"sourceEventSeqs":[174],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":33}} {"type":"step/start","data":{"turn":1,"step":34}} -{"type":"assistant/message","data":{"turn":1,"step":34,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-busy-ax","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:70}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690394,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690394,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-busy-ax","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690394,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690394,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":34,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-busy-ax","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:70}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512913,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512913,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-busy-ax","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512913,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512913,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":34,"callId":"cua-capture-busy-ax","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":34,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-capture-busy-ax"},"toolCallId":"cua-capture-busy-ax","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-9\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 3\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:71}}"}},"sourceEventSeqs":[179],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":34}} {"type":"step/start","data":{"turn":1,"step":35}} -{"type":"assistant/message","data":{"turn":1,"step":35,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-callback","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F10\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:72}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690414,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690414,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-callback","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F10\"}}"}}},{"type":"chunk","time":1791947690414,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690414,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":35,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-callback","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F10\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:72}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512942,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512942,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-callback","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F10\"}}"}}},{"type":"chunk","time":1792564512942,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512942,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":35,"callId":"cua-capture-callback","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F10\"}}"}} {"type":"tool/result","data":{"turn":1,"step":35,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-capture-callback"},"toolCallId":"cua-capture-callback","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:73}}"}},"sourceEventSeqs":[184],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":35}} {"type":"step/start","data":{"turn":1,"step":36}} -{"type":"assistant/message","data":{"turn":1,"step":36,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-recovered","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:74}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690434,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690434,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-recovered","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690434,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690434,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":36,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-recovered","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:74}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512970,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512970,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-recovered","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512970,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512970,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":36,"callId":"cua-capture-recovered","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":36,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-capture-recovered"},"toolCallId":"cua-capture-recovered","content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"isError":false,"id":"{{message:75}}"}},"sourceEventSeqs":[189],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":36}} {"type":"step/start","data":{"turn":1,"step":37}} -{"type":"assistant/message","data":{"turn":1,"step":37,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-enter","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-9\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:76}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690466,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690466,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-enter","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-9\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1791947690466,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690466,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":37,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-enter","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-9\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:76}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513023,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513024,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-enter","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-9\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1792564513024,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513024,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":37,"callId":"cua-hover-enter","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-9\",\"elementIndex\":0}}"}} {"type":"tool/result","data":{"turn":1,"step":37,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-enter"},"toolCallId":"cua-hover-enter","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false,\"hoverRoute\":\"accessibility\",\"systemPointerMoved\":false}"}],"isError":false,"id":"{{message:77}}"}},"sourceEventSeqs":[194],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":37}} {"type":"step/start","data":{"turn":1,"step":38}} -{"type":"assistant/message","data":{"turn":1,"step":38,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:78}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690495,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690495,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690495,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690495,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":38,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:78}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513075,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513075,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564513075,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513075,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":38,"callId":"cua-hover-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":38,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-observe"},"toolCallId":"cua-hover-observe","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-10\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 3\\\"\\n- AXStaticText \\\"Hover information\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:79}}"}},"sourceEventSeqs":[199],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":38}} {"type":"step/start","data":{"turn":1,"step":39}} -{"type":"assistant/message","data":{"turn":1,"step":39,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:80}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690517,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690517,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690517,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690517,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":39,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:80}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513125,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513125,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564513125,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513125,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":39,"callId":"cua-hover-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":39,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-capture"},"toolCallId":"cua-hover-capture","content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"isError":false,"id":"{{message:81}}"}},"sourceEventSeqs":[204],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":39}} {"type":"step/start","data":{"turn":1,"step":40}} -{"type":"assistant/message","data":{"turn":1,"step":40,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-popup","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":100,\"y\":200,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:82}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690565,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690565,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-popup","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":100,\"y\":200,\"relative\":true}}"}}},{"type":"chunk","time":1791947690565,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690565,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":40,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-popup","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":100,\"y\":200,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:82}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513163,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513163,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-popup","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":100,\"y\":200,\"relative\":true}}"}}},{"type":"chunk","time":1792564513163,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513163,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":40,"callId":"cua-hover-popup","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":100,\"y\":200,\"relative\":true}}"}} {"type":"tool/result","data":{"turn":1,"step":40,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-popup"},"toolCallId":"cua-hover-popup","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false,\"hoverRoute\":\"accessibility\",\"systemPointerMoved\":false}"}],"isError":false,"id":"{{message:83}}"}},"sourceEventSeqs":[209],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":40}} {"type":"step/start","data":{"turn":1,"step":41}} -{"type":"assistant/message","data":{"turn":1,"step":41,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-10\",\"x\":100,\"y\":200,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:84}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690590,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690590,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-10\",\"x\":100,\"y\":200,\"relative\":true}}"}}},{"type":"chunk","time":1791947690590,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690590,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":41,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-10\",\"x\":100,\"y\":200,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:84}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513183,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513183,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-10\",\"x\":100,\"y\":200,\"relative\":true}}"}}},{"type":"chunk","time":1792564513183,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513183,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":41,"callId":"cua-hover-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-10\",\"x\":100,\"y\":200,\"relative\":true}}"}} {"type":"tool/result","data":{"turn":1,"step":41,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-click"},"toolCallId":"cua-hover-click","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:85}}"}},"sourceEventSeqs":[214],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":41}} {"type":"step/start","data":{"turn":1,"step":42}} -{"type":"assistant/message","data":{"turn":1,"step":42,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-exit","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":0,\"y\":200,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:86}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690613,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690613,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-exit","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":0,\"y\":200,\"relative\":true}}"}}},{"type":"chunk","time":1791947690613,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690613,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":42,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-exit","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":0,\"y\":200,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:86}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513205,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513205,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-exit","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":0,\"y\":200,\"relative\":true}}"}}},{"type":"chunk","time":1792564513205,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513205,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":42,"callId":"cua-hover-exit","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":0,\"y\":200,\"relative\":true}}"}} {"type":"tool/result","data":{"turn":1,"step":42,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-exit"},"toolCallId":"cua-hover-exit","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false,\"hoverRoute\":\"accessibility\",\"systemPointerMoved\":false}"}],"isError":false,"id":"{{message:87}}"}},"sourceEventSeqs":[219],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":42}} {"type":"step/start","data":{"turn":1,"step":43}} -{"type":"assistant/message","data":{"turn":1,"step":43,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:88}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690633,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690633,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690633,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690633,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":43,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:88}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513224,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513224,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564513224,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513224,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":43,"callId":"cua-hover-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":43,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-verify"},"toolCallId":"cua-hover-verify","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-11\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 4\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:89}}"}},"sourceEventSeqs":[224],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":43}} {"type":"step/start","data":{"turn":1,"step":44}} -{"type":"assistant/message","data":{"turn":1,"step":44,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-background","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F9\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:90}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690653,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690653,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-background","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F9\"}}"}}},{"type":"chunk","time":1791947690653,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690653,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":44,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-background","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F9\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:90}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513244,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513244,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-background","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F9\"}}"}}},{"type":"chunk","time":1792564513244,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513244,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":44,"callId":"cua-paste-background","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F9\"}}"}} {"type":"tool/result","data":{"turn":1,"step":44,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-background"},"toolCallId":"cua-paste-background","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:91}}"}},"sourceEventSeqs":[229],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":44}} {"type":"step/start","data":{"turn":1,"step":45}} -{"type":"assistant/message","data":{"turn":1,"step":45,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-unread","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:92}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690672,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690672,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-unread","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}}},{"type":"chunk","time":1791947690672,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690672,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":45,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-unread","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:92}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513264,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513264,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-unread","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}}},{"type":"chunk","time":1792564513264,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513264,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":45,"callId":"cua-paste-unread","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}} {"type":"tool/result","data":{"turn":1,"step":45,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-unread"},"toolCallId":"cua-paste-unread","content":[{"type":"text","text":"Error: PASTE_NOT_CONSUMED: Paste command was dispatched, but clipboard data was not requested within the read deadline. Bring the target app to the foreground and focus its text input. Inspect the contents before deciding whether to retry; a delayed paste may still run."}],"isError":true,"id":"{{message:93}}"}},"sourceEventSeqs":[234],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":45}} {"type":"step/start","data":{"turn":1,"step":46}} -{"type":"assistant/message","data":{"turn":1,"step":46,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-inspect","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:94}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690696,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690696,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-inspect","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690696,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690696,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":46,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-inspect","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:94}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513290,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513290,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-inspect","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564513290,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513290,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":46,"callId":"cua-paste-inspect","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":46,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-inspect"},"toolCallId":"cua-paste-inspect","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-12\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 4\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:95}}"}},"sourceEventSeqs":[239],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":46}} {"type":"step/start","data":{"turn":1,"step":47}} -{"type":"assistant/message","data":{"turn":1,"step":47,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-activate","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:96}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690714,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690714,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-activate","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1791947690714,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690714,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":47,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-activate","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:96}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513314,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513314,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-activate","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1792564513314,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513314,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":47,"callId":"cua-paste-activate","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} {"type":"tool/result","data":{"turn":1,"step":47,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-activate"},"toolCallId":"cua-paste-activate","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false,\"foreground\":{\"requestId\":\"cua-paste-activate\",\"operation\":\"activate\",\"targetPid\":9,\"targetWindowId\":null,\"before\":{\"frontPid\":42,\"focusedWindowId\":7,\"frontWindowId\":99,\"frontWindowPid\":42},\"after\":{\"frontPid\":9,\"focusedWindowId\":7,\"frontWindowId\":7,\"frontWindowPid\":9},\"activationRequested\":true,\"raiseRequested\":false}}"}],"isError":false,"id":"{{message:97}}"}},"sourceEventSeqs":[244],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":47}} {"type":"step/start","data":{"turn":1,"step":48}} -{"type":"assistant/message","data":{"turn":1,"step":48,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-focus","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:98}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690734,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690734,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-focus","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690734,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690734,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":48,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-focus","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:98}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513332,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513332,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-focus","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564513332,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513332,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":48,"callId":"cua-paste-focus","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":48,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-focus"},"toolCallId":"cua-paste-focus","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-13\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 4\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:99}}"}},"sourceEventSeqs":[249],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":48}} {"type":"step/start","data":{"turn":1,"step":49}} -{"type":"assistant/message","data":{"turn":1,"step":49,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-consumed","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:100}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690757,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690757,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-consumed","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}}},{"type":"chunk","time":1791947690757,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690757,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":49,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-consumed","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:100}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513353,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513353,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-consumed","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}}},{"type":"chunk","time":1792564513353,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513353,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":49,"callId":"cua-paste-consumed","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}} {"type":"tool/result","data":{"turn":1,"step":49,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-consumed"},"toolCallId":"cua-paste-consumed","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:101}}"}},"sourceEventSeqs":[254],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":49}} {"type":"step/start","data":{"turn":1,"step":50}} -{"type":"assistant/message","data":{"turn":1,"step":50,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:102}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690778,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690778,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690778,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690778,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":50,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:102}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513374,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513374,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564513374,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513374,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":50,"callId":"cua-paste-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":50,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-verify"},"toolCallId":"cua-paste-verify","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-14\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"fixture paste\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 4\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:103}}"}},"sourceEventSeqs":[259],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":50}} {"type":"step/start","data":{"turn":1,"step":51}} -{"type":"assistant/message","data":{"turn":1,"step":51,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-debug-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F12\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:104}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690801,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690801,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-debug-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F12\"}}"}}},{"type":"chunk","time":1791947690801,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690801,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":51,"callId":"cua-debug-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F12\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":51,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-debug-arm"},"toolCallId":"cua-debug-arm","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:105}}"}},"sourceEventSeqs":[264],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":51,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-open","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F8\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:104}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513395,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513395,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-open","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F8\"}}"}}},{"type":"chunk","time":1792564513395,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513395,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":51,"callId":"cua-floating-open","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F8\"}}"}} +{"type":"tool/result","data":{"turn":1,"step":51,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-open"},"toolCallId":"cua-floating-open","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:105}}"}},"sourceEventSeqs":[264],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":51}} {"type":"step/start","data":{"turn":1,"step":52}} -{"type":"assistant/message","data":{"turn":1,"step":52,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-debug-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:106}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690821,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690821,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-debug-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690821,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690821,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":52,"callId":"cua-debug-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} -{"type":"tool/result","data":{"turn":1,"step":52,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-debug-screenshot"},"toolCallId":"cua-debug-screenshot","content":[{"type":"text","text":"Error: NATIVE_PROTOCOL: Helper returned an invalid response; acquire fresh application handles\nScreenshot diagnostics:\n[cua-screenshot] {\"requestId\":\"cua-debug-screenshot\",\"stage\":\"capture-image.begin\",\"elapsedMs\":1}"}],"isError":true,"id":"{{message:107}}"}},"sourceEventSeqs":[269],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":52,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-list","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:106}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513415,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513415,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-list","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1792564513415,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513415,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":52,"callId":"cua-floating-list","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} +{"type":"tool/result","data":{"turn":1,"step":52,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-list"},"toolCallId":"cua-floating-list","content":[{"type":"text","text":"[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":10,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Floating panel\",\"bounds\":{\"x\":100,\"y\":120,\"width\":240,\"height\":140},\"isOnScreen\":true,\"onCurrentSpace\":true}]"}],"isError":false,"id":"{{message:107}}"}},"sourceEventSeqs":[269],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":52}} {"type":"step/start","data":{"turn":1,"step":53}} -{"type":"assistant/message","data":{"turn":1,"step":53,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-consent-denied","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Denied Fixture\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:108}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690852,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690852,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-consent-denied","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Denied Fixture\"}}"}}},{"type":"chunk","time":1791947690852,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690852,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":53,"callId":"cua-consent-denied","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Denied Fixture\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":53,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-denied"},"toolCallId":"cua-consent-denied","content":[{"type":"text","text":"Error: APP_ACCESS_DENIED: The user denied access to Denied Fixture. Do not retry or use another tool to bypass this decision."}],"isError":true,"id":"{{message:109}}"}},"sourceEventSeqs":[274],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":53,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:108}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513434,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513434,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}}},{"type":"chunk","time":1792564513434,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513434,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":53,"callId":"cua-floating-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}} +{"type":"tool/result","data":{"turn":1,"step":53,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-observe"},"toolCallId":"cua-floating-observe","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":10,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-15\",\"tree\":\"AX scope=window offsets=UTF-16\\n- AXWindow \\\"Floating panel\\\"\\n - [0] AXButton \\\"Increment floating panel\\\"\\n - AXStaticText \\\"Floating count: 0\\\"\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":10,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Floating panel\",\"bounds\":{\"x\":100,\"y\":120,\"width\":240,\"height\":140},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:109}}"}},"sourceEventSeqs":[274],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":53}} {"type":"step/start","data":{"turn":1,"step":54}} -{"type":"assistant/message","data":{"turn":1,"step":54,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-consent-revocable","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Revocable Fixture\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:110}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947691022,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947691022,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-consent-revocable","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Revocable Fixture\"}}"}}},{"type":"chunk","time":1791947691022,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947691022,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":54,"callId":"cua-consent-revocable","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Revocable Fixture\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":54,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-revocable"},"toolCallId":"cua-consent-revocable","content":[{"type":"text","text":"{\"appHandle\":\"revoked-app\",\"pid\":17,\"name\":\"Revocable Fixture\"}"}],"isError":false,"id":"{{message:111}}"}},"sourceEventSeqs":[279],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":54,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:110}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513453,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513453,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}}},{"type":"chunk","time":1792564513453,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513453,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":54,"callId":"cua-floating-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}} +{"type":"tool/result","data":{"turn":1,"step":54,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-screenshot"},"toolCallId":"cua-floating-screenshot","content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":10,\"bounds\":{\"x\":100,\"y\":120,\"width\":240,\"height\":140},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"isError":false,"id":"{{message:111}}"}},"sourceEventSeqs":[279],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":54}} {"type":"step/start","data":{"turn":1,"step":55}} -{"type":"assistant/message","data":{"turn":1,"step":55,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-consent-revoked","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"revoked-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:112}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947691192,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947691192,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-consent-revoked","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"revoked-app\"}}"}}},{"type":"chunk","time":1791947691192,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947691192,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":55,"callId":"cua-consent-revoked","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"revoked-app\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":55,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-revoked"},"toolCallId":"cua-consent-revoked","content":[{"type":"text","text":"Error: APP_ACCESS_REVOKED: Application access was revoked; stop using this application"}],"isError":true,"id":"{{message:113}}"}},"sourceEventSeqs":[284],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":55,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-refresh","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:112}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513493,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513493,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-refresh","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1792564513493,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513493,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":55,"callId":"cua-floating-refresh","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} +{"type":"tool/result","data":{"turn":1,"step":55,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-refresh"},"toolCallId":"cua-floating-refresh","content":[{"type":"text","text":"[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":10,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Floating panel\",\"bounds\":{\"x\":100,\"y\":120,\"width\":240,\"height\":140},\"isOnScreen\":true,\"onCurrentSpace\":true}]"}],"isError":false,"id":"{{message:113}}"}},"sourceEventSeqs":[284],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":55}} {"type":"step/start","data":{"turn":1,"step":56}} -{"type":"assistant/message","data":{"turn":1,"step":56,"message":{"role":"assistant","content":[{"type":"text","text":"Observed Count: 4 after hovering, observing and clicking the revealed control. Moving away dismissed the hover information. Geometry conflicts rejected capture and coordinate gestures; the advertised AX button action remained available. No automatic activation or input retry was requested."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:114}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947691212,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1791947691212,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Observed Count: 4 after hovering, observing and clicking the revealed control. Moving away dismissed the hover information. Geometry conflicts rejected capture and coordinate gestures; the advertised AX button action remained available. No automatic activation or input retry was requested."}}},{"type":"chunk","time":1791947691212,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947691212,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":56,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10,\"snapshotId\":\"fixture-snapshot-15\",\"x\":0,\"y\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:114}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513513,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513513,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10,\"snapshotId\":\"fixture-snapshot-15\",\"x\":0,\"y\":0}}"}}},{"type":"chunk","time":1792564513513,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513513,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":56,"callId":"cua-floating-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10,\"snapshotId\":\"fixture-snapshot-15\",\"x\":0,\"y\":0}}"}} +{"type":"tool/result","data":{"turn":1,"step":56,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-click"},"toolCallId":"cua-floating-click","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:115}}"}},"sourceEventSeqs":[289],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":56}} +{"type":"step/start","data":{"turn":1,"step":57}} +{"type":"assistant/message","data":{"turn":1,"step":57,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:116}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513535,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513535,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}}},{"type":"chunk","time":1792564513535,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513535,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":57,"callId":"cua-floating-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}} +{"type":"tool/result","data":{"turn":1,"step":57,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-verify"},"toolCallId":"cua-floating-verify","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":10,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-16\",\"tree\":\"AX scope=window offsets=UTF-16\\n- AXWindow \\\"Floating panel\\\"\\n - [0] AXButton \\\"Increment floating panel\\\"\\n - AXStaticText \\\"Floating count: 1\\\"\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":10,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Floating panel\",\"bounds\":{\"x\":100,\"y\":120,\"width\":240,\"height\":140},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:117}}"}},"sourceEventSeqs":[294],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":57}} +{"type":"step/start","data":{"turn":1,"step":58}} +{"type":"assistant/message","data":{"turn":1,"step":58,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-debug-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F12\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:118}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513564,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513564,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-debug-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F12\"}}"}}},{"type":"chunk","time":1792564513564,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513564,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":58,"callId":"cua-debug-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F12\"}}"}} +{"type":"tool/result","data":{"turn":1,"step":58,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-debug-arm"},"toolCallId":"cua-debug-arm","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:119}}"}},"sourceEventSeqs":[299],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":58}} +{"type":"step/start","data":{"turn":1,"step":59}} +{"type":"assistant/message","data":{"turn":1,"step":59,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-debug-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:120}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513582,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513582,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-debug-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564513582,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513582,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":59,"callId":"cua-debug-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} +{"type":"tool/result","data":{"turn":1,"step":59,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-debug-screenshot"},"toolCallId":"cua-debug-screenshot","content":[{"type":"text","text":"Error: NATIVE_PROTOCOL: Helper returned an invalid response; acquire fresh application handles\nScreenshot diagnostics:\n[cua-screenshot] {\"requestId\":\"cua-debug-screenshot\",\"stage\":\"capture-image.begin\",\"elapsedMs\":1}"}],"isError":true,"id":"{{message:121}}"}},"sourceEventSeqs":[304],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":59}} +{"type":"step/start","data":{"turn":1,"step":60}} +{"type":"assistant/message","data":{"turn":1,"step":60,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-consent-denied","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Denied Fixture\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:122}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513611,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513611,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-consent-denied","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Denied Fixture\"}}"}}},{"type":"chunk","time":1792564513611,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513611,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":60,"callId":"cua-consent-denied","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Denied Fixture\"}}"}} +{"type":"tool/result","data":{"turn":1,"step":60,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-denied"},"toolCallId":"cua-consent-denied","content":[{"type":"text","text":"Error: APP_ACCESS_DENIED: The user denied access to Denied Fixture. Do not retry or use another tool to bypass this decision."}],"isError":true,"id":"{{message:123}}"}},"sourceEventSeqs":[309],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":60}} +{"type":"step/start","data":{"turn":1,"step":61}} +{"type":"assistant/message","data":{"turn":1,"step":61,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-consent-revocable","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Revocable Fixture\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:124}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513776,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513776,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-consent-revocable","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Revocable Fixture\"}}"}}},{"type":"chunk","time":1792564513776,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513776,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":61,"callId":"cua-consent-revocable","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Revocable Fixture\"}}"}} +{"type":"tool/result","data":{"turn":1,"step":61,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-revocable"},"toolCallId":"cua-consent-revocable","content":[{"type":"text","text":"{\"appHandle\":\"revoked-app\",\"pid\":17,\"name\":\"Revocable Fixture\"}"}],"isError":false,"id":"{{message:125}}"}},"sourceEventSeqs":[314],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":61}} +{"type":"step/start","data":{"turn":1,"step":62}} +{"type":"assistant/message","data":{"turn":1,"step":62,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-consent-revoked","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"revoked-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:126}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513949,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513949,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-consent-revoked","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"revoked-app\"}}"}}},{"type":"chunk","time":1792564513949,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513949,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":62,"callId":"cua-consent-revoked","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"revoked-app\"}}"}} +{"type":"tool/result","data":{"turn":1,"step":62,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-revoked"},"toolCallId":"cua-consent-revoked","content":[{"type":"text","text":"Error: APP_ACCESS_REVOKED: Application access was revoked; stop using this application"}],"isError":true,"id":"{{message:127}}"}},"sourceEventSeqs":[319],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":62}} +{"type":"step/start","data":{"turn":1,"step":63}} +{"type":"assistant/message","data":{"turn":1,"step":63,"message":{"role":"assistant","content":[{"type":"text","text":"Observed Count: 4 after hovering, observing and clicking the revealed control. Moving away dismissed the hover information. Geometry conflicts rejected capture and coordinate gestures; the advertised AX button action remained available. No automatic activation or input retry was requested. The separately captured floating panel received one click after its window list was refreshed; keyboard focus stayed in the main window."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:128}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513967,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1792564513967,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Observed Count: 4 after hovering, observing and clicking the revealed control. Moving away dismissed the hover information. Geometry conflicts rejected capture and coordinate gestures; the advertised AX button action remained available. No automatic activation or input retry was requested. The separately captured floating panel received one click after its window list was refreshed; keyboard focus stayed in the main window."}}},{"type":"chunk","time":1792564513967,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513967,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":63}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/snapshots/session/cua-native/system-prompt.expected.md b/snapshots/session/cua-native/system-prompt.expected.md index d51551ecbe..5fd3c14a9d 100644 --- a/snapshots/session/cua-native/system-prompt.expected.md +++ b/snapshots/session/cua-native/system-prompt.expected.md @@ -33,7 +33,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. +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. 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. diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index 15b7b997fb..af955c1c45 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -35,7 +35,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. +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. 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. From 1e183c1fcd7f45386c39b952fa1c0137a680603e Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 21 Oct 2026 14:41:28 +0800 Subject: [PATCH 003/184] test(cua): close floating fixture through its main window --- .../native/tests/FloatingWindowFixture.swift | 41 +++++++++++-------- .../native/tests/floating_windows_e2e.py | 5 ++- 2 files changed, 27 insertions(+), 19 deletions(-) diff --git a/packages/experimental/cua-macos/native/tests/FloatingWindowFixture.swift b/packages/experimental/cua-macos/native/tests/FloatingWindowFixture.swift index 6348ab27fe..46e524886f 100644 --- a/packages/experimental/cua-macos/native/tests/FloatingWindowFixture.swift +++ b/packages/experimental/cua-macos/native/tests/FloatingWindowFixture.swift @@ -11,13 +11,14 @@ final class FloatingWindowFixture: NSObject, NSApplicationDelegate { var main: NSWindow! var panel: FloatingPanel! var button: NSButton! + var closeButton: NSButton! var panelID = 0 var count = 0 var resized = false var closed = false var panelSize: [CGFloat] = [] var buttonPoint: [CGFloat] = [] - var controls: [DispatchSourceSignal] = [] + var resizeControl: DispatchSourceSignal? var observer: Timer? init(statePath: String) { self.statePath = statePath } @@ -25,6 +26,9 @@ final class FloatingWindowFixture: NSObject, NSApplicationDelegate { main = NSWindow(contentRect: NSRect(x: 120, y: 180, width: 420, height: 300), styleMask: [.titled, .closable], backing: .buffered, defer: false) main.title = "Floating fixture main" + closeButton = NSButton(title: "Close panel", target: self, action: #selector(closePanel)) + closeButton.frame = NSRect(x: 280, y: 30, width: 120, height: 35) + main.contentView!.addSubview(closeButton) panel = FloatingPanel(contentRect: NSRect(x: 220, y: 250, width: 240, height: 140), styleMask: [.titled, .nonactivatingPanel], backing: .buffered, defer: false) panel.title = "Floating fixture panel" @@ -42,24 +46,16 @@ final class FloatingWindowFixture: NSObject, NSApplicationDelegate { NSApplication.shared.activate(ignoringOtherApps: true) panel.orderFrontRegardless() panelID = panel.windowNumber - for number in [SIGUSR1, SIGUSR2] { - signal(number, SIG_IGN) - let control = DispatchSource.makeSignalSource(signal: number, queue: .main) - control.setEventHandler { [weak self] in - guard let self else { return } - if number == SIGUSR1 { - self.panel.close() - // Releasing the retained panel destroys its WindowServer window instead of only hiding it. - self.panel = nil - self.button = nil - self.closed = true - } - else { self.panel.setContentSize(NSSize(width: 280, height: 180)); self.resized = true } - self.persist() - } - control.resume() - controls.append(control) + signal(SIGUSR2, SIG_IGN) + let control = DispatchSource.makeSignalSource(signal: SIGUSR2, queue: .main) + control.setEventHandler { [weak self] in + guard let self else { return } + self.panel.setContentSize(NSSize(width: 280, height: 180)) + self.resized = true + self.persist() } + control.resume() + resizeControl = control // WindowServer visibility and frame updates settle after AppKit requests return. observer = Timer.scheduledTimer(withTimeInterval: 0.05, repeats: true) { [weak self] _ in self?.persist() } persist() @@ -67,6 +63,13 @@ final class FloatingWindowFixture: NSObject, NSApplicationDelegate { fflush(stdout) } @objc func increment() { count += 1; persist() } + @objc func closePanel() { + panel.close() + panel = nil + button = nil + closed = true + persist() + } func persist() { let rows = CGWindowListCopyWindowInfo(.excludeDesktopElements, kCGNullWindowID) as? [[String: Any]] ?? [] let row = rows.first { ($0[kCGWindowNumber as String] as? NSNumber)?.intValue == panelID } @@ -75,11 +78,13 @@ final class FloatingWindowFixture: NSObject, NSApplicationDelegate { panelSize = [panel.frame.width, panel.frame.height] buttonPoint = [rect.midX, panel.frame.height - rect.midY] } + let closeRect = closeButton.convert(closeButton.bounds, to: nil) let data = try! JSONSerialization.data(withJSONObject: [ "pid": getpid(), "mainWindowId": main.windowNumber, "panelWindowId": panelID, "panelLayer": row?[kCGWindowLayer as String] ?? -1, "panelOnScreen": row?[kCGWindowIsOnscreen as String] ?? false, "panelSize": panelSize, "buttonPoint": buttonPoint, + "closePoint": [closeRect.midX, main.frame.height - closeRect.midY], "count": count, "resized": resized, "closed": closed, ]) try! data.write(to: URL(fileURLWithPath: statePath), options: .atomic) 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 a3988509b6..62aa14fa53 100644 --- a/packages/experimental/cua-macos/native/tests/floating_windows_e2e.py +++ b/packages/experimental/cua-macos/native/tests/floating_windows_e2e.py @@ -95,7 +95,10 @@ def main(): target = {**target, 'snapshotId': fresh['snapshotId'], 'x': x, 'y': y} helper.call('click', target) wait_state(lambda value: value['count'] == 5) - os.kill(fixture.pid, signal.SIGUSR1) + # AppKit's current mouse event retains its target window. Closing from the main + # window replaces that event so the floating window can actually be destroyed. + close_x, close_y = actual['closePoint'] + helper.call('click', {**owner, 'windowId': actual['mainWindowId'], 'x': close_x, 'y': close_y}) wait_state(lambda value: value['closed'] and not value['panelOnScreen']) deadline = time.monotonic() + 10 while panel_id in [window['windowId'] for window in helper.call('listWindows', owner)]: From 2c9d2f46495a7aa720274e90c95a4150eca4e16d Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 5 Nov 2026 16:13:26 +0800 Subject: [PATCH 004/184] fix(cua): keep hidden windows and auxiliary layers out of default targeting --- .../cua-window-discovery/guide.i18n.yaml | 16 +++++++++ .../v0.2.2-rc.1/cua-window-discovery/guide.md | 17 +++++++++ .../cua-window-discovery/guide.zh.md | 17 +++++++++ .../experimental/cua-macos/README.i18n.yaml | 8 ++--- packages/experimental/cua-macos/README.md | 8 ++--- packages/experimental/cua-macos/README.zh.md | 8 ++--- .../cua-macos/native/README.i18n.yaml | 6 ++-- .../experimental/cua-macos/native/README.md | 2 +- .../cua-macos/native/README.zh.md | 4 +-- .../Sources/CuaNative/NativePlatform.swift | 2 +- .../native/Sources/CuaNative/Protocol.swift | 7 ++-- .../cua-macos/native/generate-protocol.ts | 5 ++- .../native/tests/floating_windows_e2e.py | 1 + .../native/tests/swift/ProtocolTests.swift | 2 +- .../tests/swift/WindowCaptureTests.swift | 2 +- .../tests/swift/WindowGeometryTests.swift | 2 +- .../experimental/cua-macos/src/guidance.ts | 4 +-- .../tests/provider-lifecycle.spec.ts | 27 ++++++++++++++ packages/experimental/cua/README.i18n.yaml | 4 +-- packages/experimental/cua/README.md | 2 +- packages/experimental/cua/README.zh.md | 2 +- packages/experimental/cua/src/api.ts | 10 +++--- packages/experimental/cua/src/index.ts | 10 ++++-- packages/experimental/cua/src/protocol.ts | 4 +-- packages/experimental/cua/src/types.ts | 10 +++--- packages/experimental/cua/src/windows.ts | 11 ++++++ packages/experimental/cua/tests/api.spec.ts | 29 ++++++++++++++- .../session/cua-native/replay.override.json | 35 ++++++++++++++++++- .../cua-native/workspace/native-helper.mjs | 12 ++++--- 29 files changed, 216 insertions(+), 51 deletions(-) create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/cua-window-discovery/guide.i18n.yaml create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/cua-window-discovery/guide.md create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/cua-window-discovery/guide.zh.md create mode 100644 packages/experimental/cua/src/windows.ts 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') From c14c53ad84cca8ba62ceb07cb3a1a7f8e12bfdaf Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 5 Nov 2026 16:16:48 +0800 Subject: [PATCH 005/184] test(cua): record visible and complete window inventories --- snapshots/session/cua-native/session.v4.jsonl | 197 +++++++++--------- .../cua-native/system-prompt.expected.md | 4 +- .../cua-native/tool-schemas.expected.json | 4 + snapshots/session/cua-ptc/session.v4.jsonl | 2 +- .../session/cua-ptc/system-prompt.expected.md | 4 +- 5 files changed, 110 insertions(+), 101 deletions(-) diff --git a/snapshots/session/cua-native/session.v4.jsonl b/snapshots/session/cua-native/session.v4.jsonl index 153095ab8a..0530baf8ac 100644 --- a/snapshots/session/cua-native/session.v4.jsonl +++ b/snapshots/session/cua-native/session.v4.jsonl @@ -12,316 +12,321 @@ {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"}} {"type":"session/title","data":{"title":"Inspect CUA capabilities, select the","messageSeqs":[8],"source":{"kind":"fallback"}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-1","name":"cua","arguments":"{\"method\":\"getCapabilities\",\"params\":{}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564511530,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564511530,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-1","name":"cua","arguments":"{\"method\":\"getCapabilities\",\"params\":{}}"}}},{"type":"chunk","time":1792564511530,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564511530,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-1","name":"cua","arguments":"{\"method\":\"getCapabilities\",\"params\":{}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866514904,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866514904,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-1","name":"cua","arguments":"{\"method\":\"getCapabilities\",\"params\":{}}"}}},{"type":"chunk","time":1793866514904,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866514904,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua-native-1","name":"cua","arguments":"{\"method\":\"getCapabilities\",\"params\":{}}"}} {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-1"},"toolCallId":"cua-native-1","content":[{"type":"text","text":"{\"platform\":\"macos\",\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"methods\":[\"getCapabilities\",\"listApps\",\"getApp\",\"activate\",\"show\",\"listWindows\",\"getState\",\"hover\",\"click\",\"setValue\",\"typeText\",\"paste\",\"pressKey\",\"scroll\",\"drag\",\"screenshot\"],\"coordinateSpace\":\"screenshot-pixels\",\"browser\":false}"}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} -{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-unauthorized-getState","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:6}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512128,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512128,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-unauthorized-getState","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1792564512128,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512128,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-unauthorized-getState","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:6}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515470,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515470,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-unauthorized-getState","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1793866515470,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515470,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"cua-unauthorized-getState","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} {"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-unauthorized-getState"},"toolCallId":"cua-unauthorized-getState","content":[{"type":"text","text":"Error: APP_ACCESS_REQUIRED: Select the application with getApp and obtain user consent before reading or controlling it"}],"isError":true,"id":"{{message:7}}"}},"sourceEventSeqs":[19],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"step/start","data":{"turn":1,"step":3}} -{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-unauthorized-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:8}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512153,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512153,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-unauthorized-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512153,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512154,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-unauthorized-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:8}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515486,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515486,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-unauthorized-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793866515486,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515486,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":3,"callId":"cua-unauthorized-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":3,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-unauthorized-screenshot"},"toolCallId":"cua-unauthorized-screenshot","content":[{"type":"text","text":"Error: APP_ACCESS_REQUIRED: Select the application with getApp and obtain user consent before reading or controlling it"}],"isError":true,"id":"{{message:9}}"}},"sourceEventSeqs":[24],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":3}} {"type":"step/start","data":{"turn":1,"step":4}} -{"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-unauthorized-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:10}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512173,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512173,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-unauthorized-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1792564512173,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512173,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-unauthorized-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:10}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515501,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515501,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-unauthorized-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1793866515501,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515501,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":4,"callId":"cua-unauthorized-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0}}"}} {"type":"tool/result","data":{"turn":1,"step":4,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-unauthorized-click"},"toolCallId":"cua-unauthorized-click","content":[{"type":"text","text":"Error: APP_ACCESS_REQUIRED: Select the application with getApp and obtain user consent before reading or controlling it"}],"isError":true,"id":"{{message:11}}"}},"sourceEventSeqs":[29],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":4}} {"type":"step/start","data":{"turn":1,"step":5}} -{"type":"assistant/message","data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-2","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"test.fixture\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:12}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512194,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512194,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-2","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"test.fixture\"}}"}}},{"type":"chunk","time":1792564512194,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512194,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-2","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"test.fixture\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:12}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515518,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515518,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-2","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"test.fixture\"}}"}}},{"type":"chunk","time":1793866515518,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515518,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":5,"callId":"cua-native-2","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"test.fixture\"}}"}} {"type":"tool/result","data":{"turn":1,"step":5,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-2"},"toolCallId":"cua-native-2","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"name\":\"Fixture\",\"bundleId\":\"test.fixture\"}"}],"isError":false,"id":"{{message:13}}"}},"sourceEventSeqs":[34],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":5}} {"type":"step/start","data":{"turn":1,"step":6}} -{"type":"assistant/message","data":{"turn":1,"step":6,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-3","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"includeMenus\":true,\"details\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:14}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512221,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512221,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-3","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"includeMenus\":true,\"details\":true}}"}}},{"type":"chunk","time":1792564512221,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512221,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":6,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-3","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"includeMenus\":true,\"details\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:14}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515553,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515553,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-3","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"includeMenus\":true,\"details\":true}}"}}},{"type":"chunk","time":1793866515553,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515553,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":6,"callId":"cua-native-3","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"includeMenus\":true,\"details\":true}}"}} -{"type":"tool/result","data":{"turn":1,"step":6,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-3"},"toolCallId":"cua-native-3","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-1\",\"tree\":\"AX scope=window offsets=UTF-16 bounds=global-points\\n- [0] AXButton \\\"Increment\\\" id=\\\"increment\\\" actions=[\\\"AXPress\\\"] bounds=[60,80,100,20]\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 0\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\n - [3] AXMenuItem \\\"Fixture command\\\"\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:15}}"}},"sourceEventSeqs":[39],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":6,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-3"},"toolCallId":"cua-native-3","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-1\",\"tree\":\"AX scope=window offsets=UTF-16 bounds=global-points\\n- [0] AXButton \\\"Increment\\\" id=\\\"increment\\\" actions=[\\\"AXPress\\\"] bounds=[60,80,100,20]\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 0\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\n - [3] AXMenuItem \\\"Fixture command\\\"\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:15}}"}},"sourceEventSeqs":[39],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":6}} {"type":"step/start","data":{"turn":1,"step":7}} -{"type":"assistant/message","data":{"turn":1,"step":7,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-4","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0,\"holdMs\":800}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:16}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512246,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512246,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-4","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0,\"holdMs\":800}}"}}},{"type":"chunk","time":1792564512246,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512246,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":7,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-4","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0,\"holdMs\":800}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:16}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515571,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515571,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-4","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0,\"holdMs\":800}}"}}},{"type":"chunk","time":1793866515571,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515571,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":7,"callId":"cua-native-4","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0,\"holdMs\":800}}"}} {"type":"tool/result","data":{"turn":1,"step":7,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-4"},"toolCallId":"cua-native-4","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:17}}"}},"sourceEventSeqs":[44],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":7}} {"type":"step/start","data":{"turn":1,"step":8}} -{"type":"assistant/message","data":{"turn":1,"step":8,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-5","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:18}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512265,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512266,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-5","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512266,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512266,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":8,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-5","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:18}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515589,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515589,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-5","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793866515589,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515589,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":8,"callId":"cua-native-5","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} -{"type":"tool/result","data":{"turn":1,"step":8,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-5"},"toolCallId":"cua-native-5","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-2\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 1\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:19}}"}},"sourceEventSeqs":[49],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":8,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-5"},"toolCallId":"cua-native-5","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-2\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 1\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:19}}"}},"sourceEventSeqs":[49],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":8}} {"type":"step/start","data":{"turn":1,"step":9}} -{"type":"assistant/message","data":{"turn":1,"step":9,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-6","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:20}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512288,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512288,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-6","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512288,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512288,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":9,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-6","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:20}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515606,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515606,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-6","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793866515606,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515606,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":9,"callId":"cua-native-6","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":9,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-6"},"toolCallId":"cua-native-6","content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"isError":false,"id":"{{message:21}}"}},"sourceEventSeqs":[54],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":9}} {"type":"step/start","data":{"turn":1,"step":10}} -{"type":"assistant/message","data":{"turn":1,"step":10,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-7","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:22}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512368,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512368,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-7","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1792564512368,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512368,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":10,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-7","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:22}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515685,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515685,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-7","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1793866515685,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515685,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":10,"callId":"cua-native-7","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":10,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-7"},"toolCallId":"cua-native-7","content":[{"type":"text","text":"[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}]"}],"isError":false,"id":"{{message:23}}"}},"sourceEventSeqs":[59],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":10,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-7"},"toolCallId":"cua-native-7","content":[{"type":"text","text":"[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}]"}],"isError":false,"id":"{{message:23}}"}},"sourceEventSeqs":[59],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":10}} {"type":"step/start","data":{"turn":1,"step":11}} -{"type":"assistant/message","data":{"turn":1,"step":11,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-8","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:24}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512388,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512388,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-8","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}}},{"type":"chunk","time":1792564512388,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512388,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":11,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-8","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:24}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515702,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515702,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-8","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}}},{"type":"chunk","time":1793866515702,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515702,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":11,"callId":"cua-native-8","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}} -{"type":"tool/result","data":{"turn":1,"step":11,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-8"},"toolCallId":"cua-native-8","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":8,\"snapshotId\":\"fixture-snapshot-3\",\"tree\":\"\",\"windows\":[{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:25}}"}},"sourceEventSeqs":[64],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":11,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-8"},"toolCallId":"cua-native-8","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":8,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-3\",\"tree\":\"\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:25}}"}},"sourceEventSeqs":[64],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":11}} {"type":"step/start","data":{"turn":1,"step":12}} -{"type":"assistant/message","data":{"turn":1,"step":12,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-9","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:26}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512406,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512406,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-9","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}}},{"type":"chunk","time":1792564512406,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512406,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":12,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-9","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:26}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515725,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515725,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-9","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}}},{"type":"chunk","time":1793866515725,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515725,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":12,"callId":"cua-native-9","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}} {"type":"tool/result","data":{"turn":1,"step":12,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-9"},"toolCallId":"cua-native-9","content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":8,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"isError":false,"id":"{{message:27}}"}},"sourceEventSeqs":[69],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":12}} {"type":"step/start","data":{"turn":1,"step":13}} -{"type":"assistant/message","data":{"turn":1,"step":13,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-10","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-3\",\"x\":0,\"y\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:28}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512445,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512445,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-10","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-3\",\"x\":0,\"y\":0}}"}}},{"type":"chunk","time":1792564512445,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512445,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":13,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-10","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-3\",\"x\":0,\"y\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:28}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515765,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515765,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-10","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-3\",\"x\":0,\"y\":0}}"}}},{"type":"chunk","time":1793866515765,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515765,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":13,"callId":"cua-native-10","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-3\",\"x\":0,\"y\":0}}"}} {"type":"tool/result","data":{"turn":1,"step":13,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-10"},"toolCallId":"cua-native-10","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:29}}"}},"sourceEventSeqs":[74],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":13}} {"type":"step/start","data":{"turn":1,"step":14}} -{"type":"assistant/message","data":{"turn":1,"step":14,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-11","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:30}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512464,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512464,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-11","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}}},{"type":"chunk","time":1792564512464,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512464,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":14,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-11","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:30}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515782,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515782,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-11","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}}},{"type":"chunk","time":1793866515782,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515782,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":14,"callId":"cua-native-11","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}} -{"type":"tool/result","data":{"turn":1,"step":14,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-11"},"toolCallId":"cua-native-11","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":8,\"snapshotId\":\"fixture-snapshot-4\",\"tree\":\"\",\"windows\":[{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:31}}"}},"sourceEventSeqs":[79],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":14,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-11"},"toolCallId":"cua-native-11","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":8,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-4\",\"tree\":\"\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:31}}"}},"sourceEventSeqs":[79],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":14}} {"type":"step/start","data":{"turn":1,"step":15}} -{"type":"assistant/message","data":{"turn":1,"step":15,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-show","name":"cua","arguments":"{\"method\":\"show\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:32}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512484,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512484,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-show","name":"cua","arguments":"{\"method\":\"show\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512484,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512484,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":15,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-show","name":"cua","arguments":"{\"method\":\"show\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:32}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515800,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515800,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-show","name":"cua","arguments":"{\"method\":\"show\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793866515800,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515800,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":15,"callId":"cua-native-show","name":"cua","arguments":"{\"method\":\"show\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":15,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-show"},"toolCallId":"cua-native-show","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false,\"windowId\":7,\"foregroundChanged\":false}"}],"isError":false,"id":"{{message:33}}"}},"sourceEventSeqs":[84],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":15}} {"type":"step/start","data":{"turn":1,"step":16}} -{"type":"assistant/message","data":{"turn":1,"step":16,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-activate-first","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:34}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512511,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512511,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-activate-first","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1792564512511,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512511,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":16,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-activate-first","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:34}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515816,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515816,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-activate-first","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1793866515816,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515816,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":16,"callId":"cua-native-activate-first","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} {"type":"tool/result","data":{"turn":1,"step":16,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-activate-first"},"toolCallId":"cua-native-activate-first","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false,\"foreground\":{\"requestId\":\"cua-native-activate-first\",\"operation\":\"activate\",\"targetPid\":9,\"targetWindowId\":null,\"before\":{\"frontPid\":42,\"focusedWindowId\":7,\"frontWindowId\":99,\"frontWindowPid\":42},\"after\":{\"frontPid\":9,\"focusedWindowId\":7,\"frontWindowId\":7,\"frontWindowPid\":9},\"activationRequested\":true,\"raiseRequested\":false}}"}],"isError":false,"id":"{{message:35}}"}},"sourceEventSeqs":[89],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":16}} {"type":"step/start","data":{"turn":1,"step":17}} -{"type":"assistant/message","data":{"turn":1,"step":17,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-activate-repeat","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:36}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512531,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512531,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-activate-repeat","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1792564512531,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512531,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":17,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-activate-repeat","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:36}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515832,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515832,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-activate-repeat","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1793866515832,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515832,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":17,"callId":"cua-native-activate-repeat","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} {"type":"tool/result","data":{"turn":1,"step":17,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-activate-repeat"},"toolCallId":"cua-native-activate-repeat","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false,\"foreground\":{\"requestId\":\"cua-native-activate-repeat\",\"operation\":\"activate\",\"targetPid\":9,\"targetWindowId\":null,\"before\":{\"frontPid\":9,\"focusedWindowId\":7,\"frontWindowId\":7,\"frontWindowPid\":9},\"after\":{\"frontPid\":9,\"focusedWindowId\":7,\"frontWindowId\":7,\"frontWindowPid\":9},\"activationRequested\":false,\"raiseRequested\":false}}"}],"isError":false,"id":"{{message:37}}"}},"sourceEventSeqs":[94],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":17}} {"type":"step/start","data":{"turn":1,"step":18}} -{"type":"assistant/message","data":{"turn":1,"step":18,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-transition","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"Return\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:38}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512552,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512552,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-transition","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"Return\"}}"}}},{"type":"chunk","time":1792564512552,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512552,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":18,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-transition","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"Return\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:38}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515848,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515848,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-transition","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"Return\"}}"}}},{"type":"chunk","time":1793866515848,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515848,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":18,"callId":"cua-native-transition","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"Return\"}}"}} {"type":"tool/result","data":{"turn":1,"step":18,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-transition"},"toolCallId":"cua-native-transition","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:39}}"}},"sourceEventSeqs":[99],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":18}} {"type":"step/start","data":{"turn":1,"step":19}} -{"type":"assistant/message","data":{"turn":1,"step":19,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-stale-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:40}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512570,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512570,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-stale-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512570,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512570,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":19,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-stale-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:40}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515864,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515864,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-stale-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793866515864,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515864,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":19,"callId":"cua-native-stale-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":19,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-stale-read"},"toolCallId":"cua-native-stale-read","content":[{"type":"text","text":"Error: STALE_SNAPSHOT: Accessibility tree changed during observation; read fresh getAXState"}],"isError":true,"id":"{{message:41}}"}},"sourceEventSeqs":[104],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":19}} {"type":"step/start","data":{"turn":1,"step":20}} -{"type":"assistant/message","data":{"turn":1,"step":20,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-stale-index","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-2\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:42}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512590,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512590,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-stale-index","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-2\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1792564512590,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512590,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":20,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-stale-index","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-2\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:42}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515881,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515881,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-stale-index","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-2\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1793866515881,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515881,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":20,"callId":"cua-native-stale-index","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-2\",\"elementIndex\":0}}"}} {"type":"tool/result","data":{"turn":1,"step":20,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-stale-index"},"toolCallId":"cua-native-stale-index","content":[{"type":"text","text":"Error: STALE_SNAPSHOT: Read fresh state before acting"}],"isError":true,"id":"{{message:43}}"}},"sourceEventSeqs":[109],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":20}} {"type":"step/start","data":{"turn":1,"step":21}} -{"type":"assistant/message","data":{"turn":1,"step":21,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-other-window","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-4\",\"x\":0,\"y\":0,\"holdMs\":800}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:44}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512616,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512616,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-other-window","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-4\",\"x\":0,\"y\":0,\"holdMs\":800}}"}}},{"type":"chunk","time":1792564512616,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512616,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":21,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-other-window","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-4\",\"x\":0,\"y\":0,\"holdMs\":800}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:44}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515897,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515897,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-other-window","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-4\",\"x\":0,\"y\":0,\"holdMs\":800}}"}}},{"type":"chunk","time":1793866515897,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515897,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":21,"callId":"cua-native-other-window","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-4\",\"x\":0,\"y\":0,\"holdMs\":800}}"}} {"type":"tool/result","data":{"turn":1,"step":21,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-other-window"},"toolCallId":"cua-native-other-window","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:45}}"}},"sourceEventSeqs":[114],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":21}} {"type":"step/start","data":{"turn":1,"step":22}} -{"type":"assistant/message","data":{"turn":1,"step":22,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-fresh-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:46}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512634,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512634,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-fresh-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512634,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512634,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":22,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-fresh-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:46}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515913,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515913,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-fresh-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793866515913,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515913,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":22,"callId":"cua-native-fresh-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} -{"type":"tool/result","data":{"turn":1,"step":22,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-fresh-read"},"toolCallId":"cua-native-fresh-read","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-5\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 1\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:47}}"}},"sourceEventSeqs":[119],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":22,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-fresh-read"},"toolCallId":"cua-native-fresh-read","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-5\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 1\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:47}}"}},"sourceEventSeqs":[119],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":22}} {"type":"step/start","data":{"turn":1,"step":23}} -{"type":"assistant/message","data":{"turn":1,"step":23,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-fresh-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-5\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:48}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512654,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512654,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-fresh-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-5\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1792564512654,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512654,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":23,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-fresh-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-5\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:48}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515929,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515929,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-fresh-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-5\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1793866515929,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515929,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":23,"callId":"cua-native-fresh-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-5\",\"elementIndex\":0}}"}} {"type":"tool/result","data":{"turn":1,"step":23,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-fresh-click"},"toolCallId":"cua-native-fresh-click","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:49}}"}},"sourceEventSeqs":[124],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":23}} {"type":"step/start","data":{"turn":1,"step":24}} -{"type":"assistant/message","data":{"turn":1,"step":24,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:50}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512675,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512675,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512675,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512675,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":24,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:50}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515945,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515945,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793866515945,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515945,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":24,"callId":"cua-native-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} -{"type":"tool/result","data":{"turn":1,"step":24,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-verify"},"toolCallId":"cua-native-verify","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-6\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 2\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:51}}"}},"sourceEventSeqs":[129],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":24,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-verify"},"toolCallId":"cua-native-verify","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-6\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 2\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:51}}"}},"sourceEventSeqs":[129],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":24}} {"type":"step/start","data":{"turn":1,"step":25}} -{"type":"assistant/message","data":{"turn":1,"step":25,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:52}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512696,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512696,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}}},{"type":"chunk","time":1792564512696,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512696,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":25,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:52}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515962,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515962,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}}},{"type":"chunk","time":1793866515962,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515962,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":25,"callId":"cua-native-geometry-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}} -{"type":"tool/result","data":{"turn":1,"step":25,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-observe"},"toolCallId":"cua-native-geometry-observe","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":9,\"snapshotId\":\"fixture-snapshot-7\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 2\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:53}}"}},"sourceEventSeqs":[134],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":25,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-observe"},"toolCallId":"cua-native-geometry-observe","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":9,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-7\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 2\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:53}}"}},"sourceEventSeqs":[134],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":25}} {"type":"step/start","data":{"turn":1,"step":26}} -{"type":"assistant/message","data":{"turn":1,"step":26,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:54}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512716,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512716,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}}},{"type":"chunk","time":1792564512716,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512716,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":26,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:54}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515979,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515979,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}}},{"type":"chunk","time":1793866515979,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515979,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":26,"callId":"cua-native-geometry-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}} {"type":"tool/result","data":{"turn":1,"step":26,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-capture"},"toolCallId":"cua-native-geometry-capture","content":[{"type":"text","text":"Error: 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"}],"isError":true,"id":"{{message:55}}"}},"sourceEventSeqs":[139],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":26}} {"type":"step/start","data":{"turn":1,"step":27}} -{"type":"assistant/message","data":{"turn":1,"step":27,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"snapshotId\":\"fixture-snapshot-7\",\"x\":20,\"y\":20,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:56}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512734,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512734,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"snapshotId\":\"fixture-snapshot-7\",\"x\":20,\"y\":20,\"relative\":true}}"}}},{"type":"chunk","time":1792564512734,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512734,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":27,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"snapshotId\":\"fixture-snapshot-7\",\"x\":20,\"y\":20,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:56}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515995,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515995,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"snapshotId\":\"fixture-snapshot-7\",\"x\":20,\"y\":20,\"relative\":true}}"}}},{"type":"chunk","time":1793866515995,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515995,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":27,"callId":"cua-native-geometry-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"snapshotId\":\"fixture-snapshot-7\",\"x\":20,\"y\":20,\"relative\":true}}"}} {"type":"tool/result","data":{"turn":1,"step":27,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-click"},"toolCallId":"cua-native-geometry-click","content":[{"type":"text","text":"Error: 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"}],"isError":true,"id":"{{message:57}}"}},"sourceEventSeqs":[144],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":27}} {"type":"step/start","data":{"turn":1,"step":28}} -{"type":"assistant/message","data":{"turn":1,"step":28,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-scroll","name":"cua","arguments":"{\"method\":\"scroll\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"x\":20,\"y\":20,\"deltaLinesX\":0,\"deltaLinesY\":-1,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:58}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512755,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512755,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-scroll","name":"cua","arguments":"{\"method\":\"scroll\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"x\":20,\"y\":20,\"deltaLinesX\":0,\"deltaLinesY\":-1,\"relative\":true}}"}}},{"type":"chunk","time":1792564512755,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512755,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":28,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-scroll","name":"cua","arguments":"{\"method\":\"scroll\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"x\":20,\"y\":20,\"deltaLinesX\":0,\"deltaLinesY\":-1,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:58}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516013,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516013,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-scroll","name":"cua","arguments":"{\"method\":\"scroll\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"x\":20,\"y\":20,\"deltaLinesX\":0,\"deltaLinesY\":-1,\"relative\":true}}"}}},{"type":"chunk","time":1793866516013,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516013,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":28,"callId":"cua-native-geometry-scroll","name":"cua","arguments":"{\"method\":\"scroll\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"x\":20,\"y\":20,\"deltaLinesX\":0,\"deltaLinesY\":-1,\"relative\":true}}"}} {"type":"tool/result","data":{"turn":1,"step":28,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-scroll"},"toolCallId":"cua-native-geometry-scroll","content":[{"type":"text","text":"Error: 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"}],"isError":true,"id":"{{message:59}}"}},"sourceEventSeqs":[149],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":28}} {"type":"step/start","data":{"turn":1,"step":29}} -{"type":"assistant/message","data":{"turn":1,"step":29,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-drag","name":"cua","arguments":"{\"method\":\"drag\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"fromX\":20,\"fromY\":20,\"toX\":30,\"toY\":30,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:60}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512781,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512781,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-drag","name":"cua","arguments":"{\"method\":\"drag\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"fromX\":20,\"fromY\":20,\"toX\":30,\"toY\":30,\"relative\":true}}"}}},{"type":"chunk","time":1792564512781,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512781,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":29,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-drag","name":"cua","arguments":"{\"method\":\"drag\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"fromX\":20,\"fromY\":20,\"toX\":30,\"toY\":30,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:60}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516030,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516030,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-drag","name":"cua","arguments":"{\"method\":\"drag\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"fromX\":20,\"fromY\":20,\"toX\":30,\"toY\":30,\"relative\":true}}"}}},{"type":"chunk","time":1793866516030,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516030,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":29,"callId":"cua-native-geometry-drag","name":"cua","arguments":"{\"method\":\"drag\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"fromX\":20,\"fromY\":20,\"toX\":30,\"toY\":30,\"relative\":true}}"}} {"type":"tool/result","data":{"turn":1,"step":29,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-drag"},"toolCallId":"cua-native-geometry-drag","content":[{"type":"text","text":"Error: 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"}],"isError":true,"id":"{{message:61}}"}},"sourceEventSeqs":[154],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":29}} {"type":"step/start","data":{"turn":1,"step":30}} -{"type":"assistant/message","data":{"turn":1,"step":30,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-ax","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-7\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:62}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512800,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512800,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-ax","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-7\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1792564512800,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512800,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":30,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-ax","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-7\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:62}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516047,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516047,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-ax","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-7\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1793866516047,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516047,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":30,"callId":"cua-native-geometry-ax","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-7\",\"elementIndex\":0}}"}} {"type":"tool/result","data":{"turn":1,"step":30,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-ax"},"toolCallId":"cua-native-geometry-ax","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:63}}"}},"sourceEventSeqs":[159],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":30}} {"type":"step/start","data":{"turn":1,"step":31}} -{"type":"assistant/message","data":{"turn":1,"step":31,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:64}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512832,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512832,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}}},{"type":"chunk","time":1792564512832,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512832,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":31,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:64}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516063,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516063,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}}},{"type":"chunk","time":1793866516063,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516063,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":31,"callId":"cua-native-geometry-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}} -{"type":"tool/result","data":{"turn":1,"step":31,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-verify"},"toolCallId":"cua-native-geometry-verify","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":9,\"snapshotId\":\"fixture-snapshot-8\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 3\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:65}}"}},"sourceEventSeqs":[164],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":31,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-verify"},"toolCallId":"cua-native-geometry-verify","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":9,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-8\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 3\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:65}}"}},"sourceEventSeqs":[164],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":31}} {"type":"step/start","data":{"turn":1,"step":32}} -{"type":"assistant/message","data":{"turn":1,"step":32,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-busy-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F11\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:66}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512855,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512855,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-busy-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F11\"}}"}}},{"type":"chunk","time":1792564512855,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512855,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":32,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-busy-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F11\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:66}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516079,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516079,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-busy-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F11\"}}"}}},{"type":"chunk","time":1793866516079,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516079,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":32,"callId":"cua-capture-busy-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F11\"}}"}} {"type":"tool/result","data":{"turn":1,"step":32,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-capture-busy-arm"},"toolCallId":"cua-capture-busy-arm","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:67}}"}},"sourceEventSeqs":[169],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":32}} {"type":"step/start","data":{"turn":1,"step":33}} -{"type":"assistant/message","data":{"turn":1,"step":33,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-busy","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:68}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512882,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512882,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-busy","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512882,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512882,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":33,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-busy","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:68}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516095,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516095,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-busy","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793866516095,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516095,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":33,"callId":"cua-capture-busy","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":33,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-capture-busy"},"toolCallId":"cua-capture-busy","content":[{"type":"text","text":"Error: CAPTURE_BUSY: A previous system capture is still pending; other native operations remain available\nScreenshot diagnostics:\n[cua-screenshot] {\"requestId\":\"cua-capture-busy\",\"stage\":\"helper.failed\",\"elapsedMs\":1,\"errorCode\":\"CAPTURE_BUSY\"}"}],"isError":true,"id":"{{message:69}}"}},"sourceEventSeqs":[174],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":33}} {"type":"step/start","data":{"turn":1,"step":34}} -{"type":"assistant/message","data":{"turn":1,"step":34,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-busy-ax","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:70}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512913,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512913,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-busy-ax","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512913,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512913,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":34,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-busy-ax","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:70}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516113,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516113,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-busy-ax","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793866516113,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516113,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":34,"callId":"cua-capture-busy-ax","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} -{"type":"tool/result","data":{"turn":1,"step":34,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-capture-busy-ax"},"toolCallId":"cua-capture-busy-ax","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-9\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 3\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:71}}"}},"sourceEventSeqs":[179],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":34,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-capture-busy-ax"},"toolCallId":"cua-capture-busy-ax","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-9\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 3\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:71}}"}},"sourceEventSeqs":[179],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":34}} {"type":"step/start","data":{"turn":1,"step":35}} -{"type":"assistant/message","data":{"turn":1,"step":35,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-callback","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F10\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:72}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512942,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512942,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-callback","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F10\"}}"}}},{"type":"chunk","time":1792564512942,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512942,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":35,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-callback","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F10\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:72}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516130,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516130,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-callback","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F10\"}}"}}},{"type":"chunk","time":1793866516130,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516130,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":35,"callId":"cua-capture-callback","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F10\"}}"}} {"type":"tool/result","data":{"turn":1,"step":35,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-capture-callback"},"toolCallId":"cua-capture-callback","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:73}}"}},"sourceEventSeqs":[184],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":35}} {"type":"step/start","data":{"turn":1,"step":36}} -{"type":"assistant/message","data":{"turn":1,"step":36,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-recovered","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:74}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512970,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512970,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-recovered","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512970,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512970,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":36,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-recovered","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:74}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516146,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516146,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-recovered","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793866516146,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516146,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":36,"callId":"cua-capture-recovered","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":36,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-capture-recovered"},"toolCallId":"cua-capture-recovered","content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"isError":false,"id":"{{message:75}}"}},"sourceEventSeqs":[189],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":36}} {"type":"step/start","data":{"turn":1,"step":37}} -{"type":"assistant/message","data":{"turn":1,"step":37,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-enter","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-9\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:76}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513023,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513024,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-enter","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-9\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1792564513024,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513024,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":37,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-enter","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-9\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:76}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516194,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516194,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-enter","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-9\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1793866516194,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516194,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":37,"callId":"cua-hover-enter","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-9\",\"elementIndex\":0}}"}} {"type":"tool/result","data":{"turn":1,"step":37,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-enter"},"toolCallId":"cua-hover-enter","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false,\"hoverRoute\":\"accessibility\",\"systemPointerMoved\":false}"}],"isError":false,"id":"{{message:77}}"}},"sourceEventSeqs":[194],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":37}} {"type":"step/start","data":{"turn":1,"step":38}} -{"type":"assistant/message","data":{"turn":1,"step":38,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:78}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513075,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513075,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564513075,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513075,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":38,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:78}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516210,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516210,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793866516210,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516210,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":38,"callId":"cua-hover-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} -{"type":"tool/result","data":{"turn":1,"step":38,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-observe"},"toolCallId":"cua-hover-observe","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-10\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 3\\\"\\n- AXStaticText \\\"Hover information\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:79}}"}},"sourceEventSeqs":[199],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":38,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-observe"},"toolCallId":"cua-hover-observe","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-10\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 3\\\"\\n- AXStaticText \\\"Hover information\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:79}}"}},"sourceEventSeqs":[199],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":38}} {"type":"step/start","data":{"turn":1,"step":39}} -{"type":"assistant/message","data":{"turn":1,"step":39,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:80}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513125,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513125,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564513125,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513125,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":39,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:80}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516231,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516231,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793866516231,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516231,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":39,"callId":"cua-hover-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":39,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-capture"},"toolCallId":"cua-hover-capture","content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"isError":false,"id":"{{message:81}}"}},"sourceEventSeqs":[204],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":39}} {"type":"step/start","data":{"turn":1,"step":40}} -{"type":"assistant/message","data":{"turn":1,"step":40,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-popup","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":100,\"y\":200,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:82}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513163,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513163,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-popup","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":100,\"y\":200,\"relative\":true}}"}}},{"type":"chunk","time":1792564513163,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513163,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":40,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-popup","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":100,\"y\":200,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:82}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516262,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516262,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-popup","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":100,\"y\":200,\"relative\":true}}"}}},{"type":"chunk","time":1793866516262,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516262,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":40,"callId":"cua-hover-popup","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":100,\"y\":200,\"relative\":true}}"}} {"type":"tool/result","data":{"turn":1,"step":40,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-popup"},"toolCallId":"cua-hover-popup","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false,\"hoverRoute\":\"accessibility\",\"systemPointerMoved\":false}"}],"isError":false,"id":"{{message:83}}"}},"sourceEventSeqs":[209],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":40}} {"type":"step/start","data":{"turn":1,"step":41}} -{"type":"assistant/message","data":{"turn":1,"step":41,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-10\",\"x\":100,\"y\":200,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:84}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513183,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513183,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-10\",\"x\":100,\"y\":200,\"relative\":true}}"}}},{"type":"chunk","time":1792564513183,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513183,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":41,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-10\",\"x\":100,\"y\":200,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:84}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516292,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516292,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-10\",\"x\":100,\"y\":200,\"relative\":true}}"}}},{"type":"chunk","time":1793866516292,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516292,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":41,"callId":"cua-hover-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-10\",\"x\":100,\"y\":200,\"relative\":true}}"}} {"type":"tool/result","data":{"turn":1,"step":41,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-click"},"toolCallId":"cua-hover-click","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:85}}"}},"sourceEventSeqs":[214],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":41}} {"type":"step/start","data":{"turn":1,"step":42}} -{"type":"assistant/message","data":{"turn":1,"step":42,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-exit","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":0,\"y\":200,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:86}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513205,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513205,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-exit","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":0,\"y\":200,\"relative\":true}}"}}},{"type":"chunk","time":1792564513205,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513205,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":42,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-exit","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":0,\"y\":200,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:86}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516317,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516317,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-exit","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":0,\"y\":200,\"relative\":true}}"}}},{"type":"chunk","time":1793866516317,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516317,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":42,"callId":"cua-hover-exit","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":0,\"y\":200,\"relative\":true}}"}} {"type":"tool/result","data":{"turn":1,"step":42,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-exit"},"toolCallId":"cua-hover-exit","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false,\"hoverRoute\":\"accessibility\",\"systemPointerMoved\":false}"}],"isError":false,"id":"{{message:87}}"}},"sourceEventSeqs":[219],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":42}} {"type":"step/start","data":{"turn":1,"step":43}} -{"type":"assistant/message","data":{"turn":1,"step":43,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:88}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513224,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513224,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564513224,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513224,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":43,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:88}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516338,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516338,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793866516338,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516338,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":43,"callId":"cua-hover-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} -{"type":"tool/result","data":{"turn":1,"step":43,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-verify"},"toolCallId":"cua-hover-verify","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-11\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 4\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:89}}"}},"sourceEventSeqs":[224],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":43,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-verify"},"toolCallId":"cua-hover-verify","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-11\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 4\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:89}}"}},"sourceEventSeqs":[224],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":43}} {"type":"step/start","data":{"turn":1,"step":44}} -{"type":"assistant/message","data":{"turn":1,"step":44,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-background","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F9\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:90}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513244,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513244,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-background","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F9\"}}"}}},{"type":"chunk","time":1792564513244,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513244,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":44,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-background","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F9\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:90}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516355,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516355,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-background","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F9\"}}"}}},{"type":"chunk","time":1793866516355,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516355,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":44,"callId":"cua-paste-background","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F9\"}}"}} {"type":"tool/result","data":{"turn":1,"step":44,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-background"},"toolCallId":"cua-paste-background","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:91}}"}},"sourceEventSeqs":[229],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":44}} {"type":"step/start","data":{"turn":1,"step":45}} -{"type":"assistant/message","data":{"turn":1,"step":45,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-unread","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:92}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513264,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513264,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-unread","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}}},{"type":"chunk","time":1792564513264,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513264,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":45,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-unread","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:92}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516372,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516372,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-unread","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}}},{"type":"chunk","time":1793866516372,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516372,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":45,"callId":"cua-paste-unread","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}} {"type":"tool/result","data":{"turn":1,"step":45,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-unread"},"toolCallId":"cua-paste-unread","content":[{"type":"text","text":"Error: PASTE_NOT_CONSUMED: Paste command was dispatched, but clipboard data was not requested within the read deadline. Bring the target app to the foreground and focus its text input. Inspect the contents before deciding whether to retry; a delayed paste may still run."}],"isError":true,"id":"{{message:93}}"}},"sourceEventSeqs":[234],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":45}} {"type":"step/start","data":{"turn":1,"step":46}} -{"type":"assistant/message","data":{"turn":1,"step":46,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-inspect","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:94}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513290,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513290,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-inspect","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564513290,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513290,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":46,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-inspect","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:94}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516389,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516389,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-inspect","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793866516389,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516389,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":46,"callId":"cua-paste-inspect","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} -{"type":"tool/result","data":{"turn":1,"step":46,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-inspect"},"toolCallId":"cua-paste-inspect","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-12\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 4\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:95}}"}},"sourceEventSeqs":[239],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":46,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-inspect"},"toolCallId":"cua-paste-inspect","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-12\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 4\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:95}}"}},"sourceEventSeqs":[239],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":46}} {"type":"step/start","data":{"turn":1,"step":47}} -{"type":"assistant/message","data":{"turn":1,"step":47,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-activate","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:96}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513314,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513314,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-activate","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1792564513314,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513314,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":47,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-activate","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:96}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516406,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516406,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-activate","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1793866516406,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516406,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":47,"callId":"cua-paste-activate","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} {"type":"tool/result","data":{"turn":1,"step":47,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-activate"},"toolCallId":"cua-paste-activate","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false,\"foreground\":{\"requestId\":\"cua-paste-activate\",\"operation\":\"activate\",\"targetPid\":9,\"targetWindowId\":null,\"before\":{\"frontPid\":42,\"focusedWindowId\":7,\"frontWindowId\":99,\"frontWindowPid\":42},\"after\":{\"frontPid\":9,\"focusedWindowId\":7,\"frontWindowId\":7,\"frontWindowPid\":9},\"activationRequested\":true,\"raiseRequested\":false}}"}],"isError":false,"id":"{{message:97}}"}},"sourceEventSeqs":[244],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":47}} {"type":"step/start","data":{"turn":1,"step":48}} -{"type":"assistant/message","data":{"turn":1,"step":48,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-focus","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:98}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513332,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513332,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-focus","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564513332,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513332,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":48,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-focus","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:98}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516424,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516424,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-focus","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793866516424,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516424,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":48,"callId":"cua-paste-focus","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} -{"type":"tool/result","data":{"turn":1,"step":48,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-focus"},"toolCallId":"cua-paste-focus","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-13\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 4\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:99}}"}},"sourceEventSeqs":[249],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":48,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-focus"},"toolCallId":"cua-paste-focus","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-13\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 4\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:99}}"}},"sourceEventSeqs":[249],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":48}} {"type":"step/start","data":{"turn":1,"step":49}} -{"type":"assistant/message","data":{"turn":1,"step":49,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-consumed","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:100}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513353,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513353,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-consumed","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}}},{"type":"chunk","time":1792564513353,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513353,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":49,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-consumed","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:100}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516449,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516449,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-consumed","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}}},{"type":"chunk","time":1793866516449,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516449,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":49,"callId":"cua-paste-consumed","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}} {"type":"tool/result","data":{"turn":1,"step":49,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-consumed"},"toolCallId":"cua-paste-consumed","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:101}}"}},"sourceEventSeqs":[254],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":49}} {"type":"step/start","data":{"turn":1,"step":50}} -{"type":"assistant/message","data":{"turn":1,"step":50,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:102}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513374,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513374,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564513374,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513374,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":50,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:102}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516466,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516466,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793866516466,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516466,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":50,"callId":"cua-paste-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} -{"type":"tool/result","data":{"turn":1,"step":50,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-verify"},"toolCallId":"cua-paste-verify","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-14\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"fixture paste\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 4\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:103}}"}},"sourceEventSeqs":[259],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":50,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-verify"},"toolCallId":"cua-paste-verify","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-14\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"fixture paste\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 4\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:103}}"}},"sourceEventSeqs":[259],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":50}} {"type":"step/start","data":{"turn":1,"step":51}} -{"type":"assistant/message","data":{"turn":1,"step":51,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-open","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F8\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:104}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513395,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513395,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-open","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F8\"}}"}}},{"type":"chunk","time":1792564513395,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513395,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":51,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-open","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F8\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:104}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516483,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516483,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-open","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F8\"}}"}}},{"type":"chunk","time":1793866516483,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516483,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":51,"callId":"cua-floating-open","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F8\"}}"}} {"type":"tool/result","data":{"turn":1,"step":51,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-open"},"toolCallId":"cua-floating-open","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:105}}"}},"sourceEventSeqs":[264],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":51}} {"type":"step/start","data":{"turn":1,"step":52}} -{"type":"assistant/message","data":{"turn":1,"step":52,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-list","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:106}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513415,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513415,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-list","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1792564513415,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513415,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":52,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-list","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:106}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516499,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516499,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-list","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1793866516499,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516499,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":52,"callId":"cua-floating-list","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":52,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-list"},"toolCallId":"cua-floating-list","content":[{"type":"text","text":"[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":10,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Floating panel\",\"bounds\":{\"x\":100,\"y\":120,\"width\":240,\"height\":140},\"isOnScreen\":true,\"onCurrentSpace\":true}]"}],"isError":false,"id":"{{message:107}}"}},"sourceEventSeqs":[269],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":52,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-list"},"toolCallId":"cua-floating-list","content":[{"type":"text","text":"[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":10,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Floating panel\",\"bounds\":{\"x\":100,\"y\":120,\"width\":240,\"height\":140},\"isOnScreen\":true,\"onCurrentSpace\":true,\"layer\":3}]"}],"isError":false,"id":"{{message:107}}"}},"sourceEventSeqs":[269],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":52}} {"type":"step/start","data":{"turn":1,"step":53}} -{"type":"assistant/message","data":{"turn":1,"step":53,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:108}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513434,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513434,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}}},{"type":"chunk","time":1792564513434,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513434,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":53,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:108}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516515,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516515,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}}},{"type":"chunk","time":1793866516515,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516515,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":53,"callId":"cua-floating-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}} -{"type":"tool/result","data":{"turn":1,"step":53,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-observe"},"toolCallId":"cua-floating-observe","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":10,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-15\",\"tree\":\"AX scope=window offsets=UTF-16\\n- AXWindow \\\"Floating panel\\\"\\n - [0] AXButton \\\"Increment floating panel\\\"\\n - AXStaticText \\\"Floating count: 0\\\"\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":10,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Floating panel\",\"bounds\":{\"x\":100,\"y\":120,\"width\":240,\"height\":140},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:109}}"}},"sourceEventSeqs":[274],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":53,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-observe"},"toolCallId":"cua-floating-observe","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":10,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-15\",\"tree\":\"AX scope=window offsets=UTF-16\\n- AXWindow \\\"Floating panel\\\"\\n - [0] AXButton \\\"Increment floating panel\\\"\\n - AXStaticText \\\"Floating count: 0\\\"\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":10,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Floating panel\",\"bounds\":{\"x\":100,\"y\":120,\"width\":240,\"height\":140},\"isOnScreen\":true,\"onCurrentSpace\":true,\"layer\":3}],\"truncated\":false}"}],"isError":false,"id":"{{message:109}}"}},"sourceEventSeqs":[274],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":53}} {"type":"step/start","data":{"turn":1,"step":54}} -{"type":"assistant/message","data":{"turn":1,"step":54,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:110}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513453,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513453,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}}},{"type":"chunk","time":1792564513453,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513453,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":54,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:110}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516531,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516531,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}}},{"type":"chunk","time":1793866516531,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516531,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":54,"callId":"cua-floating-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}} {"type":"tool/result","data":{"turn":1,"step":54,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-screenshot"},"toolCallId":"cua-floating-screenshot","content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":10,\"bounds\":{\"x\":100,\"y\":120,\"width\":240,\"height\":140},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"isError":false,"id":"{{message:111}}"}},"sourceEventSeqs":[279],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":54}} {"type":"step/start","data":{"turn":1,"step":55}} -{"type":"assistant/message","data":{"turn":1,"step":55,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-refresh","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:112}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513493,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513493,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-refresh","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1792564513493,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513493,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":55,"callId":"cua-floating-refresh","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":55,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-refresh"},"toolCallId":"cua-floating-refresh","content":[{"type":"text","text":"[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":10,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Floating panel\",\"bounds\":{\"x\":100,\"y\":120,\"width\":240,\"height\":140},\"isOnScreen\":true,\"onCurrentSpace\":true}]"}],"isError":false,"id":"{{message:113}}"}},"sourceEventSeqs":[284],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":55,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-complete-list","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\",\"includeHidden\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:112}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516569,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516569,"chunk":{"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":"chunk","time":1793866516569,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516569,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":55,"callId":"cua-floating-complete-list","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\",\"includeHidden\":true}}"}} +{"type":"tool/result","data":{"turn":1,"step":55,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-complete-list"},"toolCallId":"cua-floating-complete-list","content":[{"type":"text","text":"[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":10,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Floating panel\",\"bounds\":{\"x\":100,\"y\":120,\"width\":240,\"height\":140},\"isOnScreen\":true,\"onCurrentSpace\":true,\"layer\":3},{\"windowId\":11,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Cached panel\",\"bounds\":{\"x\":100,\"y\":120,\"width\":240,\"height\":140},\"isOnScreen\":false,\"onCurrentSpace\":true,\"layer\":3}]"}],"isError":false,"id":"{{message:113}}"}},"sourceEventSeqs":[284],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":55}} {"type":"step/start","data":{"turn":1,"step":56}} -{"type":"assistant/message","data":{"turn":1,"step":56,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10,\"snapshotId\":\"fixture-snapshot-15\",\"x\":0,\"y\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:114}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513513,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513513,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10,\"snapshotId\":\"fixture-snapshot-15\",\"x\":0,\"y\":0}}"}}},{"type":"chunk","time":1792564513513,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513513,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":56,"callId":"cua-floating-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10,\"snapshotId\":\"fixture-snapshot-15\",\"x\":0,\"y\":0}}"}} -{"type":"tool/result","data":{"turn":1,"step":56,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-click"},"toolCallId":"cua-floating-click","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:115}}"}},"sourceEventSeqs":[289],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":56,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-refresh","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:114}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516586,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516586,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-refresh","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1793866516586,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516586,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":56,"callId":"cua-floating-refresh","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} +{"type":"tool/result","data":{"turn":1,"step":56,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-refresh"},"toolCallId":"cua-floating-refresh","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":null,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-16\",\"tree\":\"AX scope=application offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"fixture paste\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 4\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":10,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Floating panel\",\"bounds\":{\"x\":100,\"y\":120,\"width\":240,\"height\":140},\"isOnScreen\":true,\"onCurrentSpace\":true,\"layer\":3}],\"truncated\":false}"}],"isError":false,"id":"{{message:115}}"}},"sourceEventSeqs":[289],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":56}} {"type":"step/start","data":{"turn":1,"step":57}} -{"type":"assistant/message","data":{"turn":1,"step":57,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:116}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513535,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513535,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}}},{"type":"chunk","time":1792564513535,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513535,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":57,"callId":"cua-floating-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}} -{"type":"tool/result","data":{"turn":1,"step":57,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-verify"},"toolCallId":"cua-floating-verify","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":10,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-16\",\"tree\":\"AX scope=window offsets=UTF-16\\n- AXWindow \\\"Floating panel\\\"\\n - [0] AXButton \\\"Increment floating panel\\\"\\n - AXStaticText \\\"Floating count: 1\\\"\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":10,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Floating panel\",\"bounds\":{\"x\":100,\"y\":120,\"width\":240,\"height\":140},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:117}}"}},"sourceEventSeqs":[294],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":57,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10,\"snapshotId\":\"fixture-snapshot-15\",\"x\":0,\"y\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:116}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516603,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516603,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10,\"snapshotId\":\"fixture-snapshot-15\",\"x\":0,\"y\":0}}"}}},{"type":"chunk","time":1793866516603,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516603,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":57,"callId":"cua-floating-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10,\"snapshotId\":\"fixture-snapshot-15\",\"x\":0,\"y\":0}}"}} +{"type":"tool/result","data":{"turn":1,"step":57,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-click"},"toolCallId":"cua-floating-click","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:117}}"}},"sourceEventSeqs":[294],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":57}} {"type":"step/start","data":{"turn":1,"step":58}} -{"type":"assistant/message","data":{"turn":1,"step":58,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-debug-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F12\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:118}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513564,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513564,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-debug-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F12\"}}"}}},{"type":"chunk","time":1792564513564,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513564,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":58,"callId":"cua-debug-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F12\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":58,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-debug-arm"},"toolCallId":"cua-debug-arm","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:119}}"}},"sourceEventSeqs":[299],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":58,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:118}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516619,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516619,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}}},{"type":"chunk","time":1793866516619,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516619,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":58,"callId":"cua-floating-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}} +{"type":"tool/result","data":{"turn":1,"step":58,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-verify"},"toolCallId":"cua-floating-verify","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":10,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-17\",\"tree\":\"AX scope=window offsets=UTF-16\\n- AXWindow \\\"Floating panel\\\"\\n - [0] AXButton \\\"Increment floating panel\\\"\\n - AXStaticText \\\"Floating count: 1\\\"\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":10,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Floating panel\",\"bounds\":{\"x\":100,\"y\":120,\"width\":240,\"height\":140},\"isOnScreen\":true,\"onCurrentSpace\":true,\"layer\":3}],\"truncated\":false}"}],"isError":false,"id":"{{message:119}}"}},"sourceEventSeqs":[299],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":58}} {"type":"step/start","data":{"turn":1,"step":59}} -{"type":"assistant/message","data":{"turn":1,"step":59,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-debug-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:120}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513582,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513582,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-debug-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564513582,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513582,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":59,"callId":"cua-debug-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} -{"type":"tool/result","data":{"turn":1,"step":59,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-debug-screenshot"},"toolCallId":"cua-debug-screenshot","content":[{"type":"text","text":"Error: NATIVE_PROTOCOL: Helper returned an invalid response; acquire fresh application handles\nScreenshot diagnostics:\n[cua-screenshot] {\"requestId\":\"cua-debug-screenshot\",\"stage\":\"capture-image.begin\",\"elapsedMs\":1}"}],"isError":true,"id":"{{message:121}}"}},"sourceEventSeqs":[304],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":59,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-debug-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F12\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:120}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516635,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516635,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-debug-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F12\"}}"}}},{"type":"chunk","time":1793866516635,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516635,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":59,"callId":"cua-debug-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F12\"}}"}} +{"type":"tool/result","data":{"turn":1,"step":59,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-debug-arm"},"toolCallId":"cua-debug-arm","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:121}}"}},"sourceEventSeqs":[304],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":59}} {"type":"step/start","data":{"turn":1,"step":60}} -{"type":"assistant/message","data":{"turn":1,"step":60,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-consent-denied","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Denied Fixture\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:122}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513611,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513611,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-consent-denied","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Denied Fixture\"}}"}}},{"type":"chunk","time":1792564513611,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513611,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":60,"callId":"cua-consent-denied","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Denied Fixture\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":60,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-denied"},"toolCallId":"cua-consent-denied","content":[{"type":"text","text":"Error: APP_ACCESS_DENIED: The user denied access to Denied Fixture. Do not retry or use another tool to bypass this decision."}],"isError":true,"id":"{{message:123}}"}},"sourceEventSeqs":[309],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":60,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-debug-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:122}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516651,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516651,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-debug-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793866516651,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516651,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":60,"callId":"cua-debug-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} +{"type":"tool/result","data":{"turn":1,"step":60,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-debug-screenshot"},"toolCallId":"cua-debug-screenshot","content":[{"type":"text","text":"Error: NATIVE_PROTOCOL: Helper returned an invalid response; acquire fresh application handles\nScreenshot diagnostics:\n[cua-screenshot] {\"requestId\":\"cua-debug-screenshot\",\"stage\":\"capture-image.begin\",\"elapsedMs\":1}"}],"isError":true,"id":"{{message:123}}"}},"sourceEventSeqs":[309],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":60}} {"type":"step/start","data":{"turn":1,"step":61}} -{"type":"assistant/message","data":{"turn":1,"step":61,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-consent-revocable","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Revocable Fixture\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:124}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513776,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513776,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-consent-revocable","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Revocable Fixture\"}}"}}},{"type":"chunk","time":1792564513776,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513776,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":61,"callId":"cua-consent-revocable","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Revocable Fixture\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":61,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-revocable"},"toolCallId":"cua-consent-revocable","content":[{"type":"text","text":"{\"appHandle\":\"revoked-app\",\"pid\":17,\"name\":\"Revocable Fixture\"}"}],"isError":false,"id":"{{message:125}}"}},"sourceEventSeqs":[314],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":61,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-consent-denied","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Denied Fixture\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:124}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516670,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516670,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-consent-denied","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Denied Fixture\"}}"}}},{"type":"chunk","time":1793866516670,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516670,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":61,"callId":"cua-consent-denied","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Denied Fixture\"}}"}} +{"type":"tool/result","data":{"turn":1,"step":61,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-denied"},"toolCallId":"cua-consent-denied","content":[{"type":"text","text":"Error: APP_ACCESS_DENIED: The user denied access to Denied Fixture. Do not retry or use another tool to bypass this decision."}],"isError":true,"id":"{{message:125}}"}},"sourceEventSeqs":[314],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":61}} {"type":"step/start","data":{"turn":1,"step":62}} -{"type":"assistant/message","data":{"turn":1,"step":62,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-consent-revoked","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"revoked-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:126}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513949,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513949,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-consent-revoked","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"revoked-app\"}}"}}},{"type":"chunk","time":1792564513949,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513949,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":62,"callId":"cua-consent-revoked","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"revoked-app\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":62,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-revoked"},"toolCallId":"cua-consent-revoked","content":[{"type":"text","text":"Error: APP_ACCESS_REVOKED: Application access was revoked; stop using this application"}],"isError":true,"id":"{{message:127}}"}},"sourceEventSeqs":[319],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":62,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-consent-revocable","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Revocable Fixture\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:126}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516810,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516810,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-consent-revocable","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Revocable Fixture\"}}"}}},{"type":"chunk","time":1793866516810,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516810,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":62,"callId":"cua-consent-revocable","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Revocable Fixture\"}}"}} +{"type":"tool/result","data":{"turn":1,"step":62,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-revocable"},"toolCallId":"cua-consent-revocable","content":[{"type":"text","text":"{\"appHandle\":\"revoked-app\",\"pid\":17,\"name\":\"Revocable Fixture\"}"}],"isError":false,"id":"{{message:127}}"}},"sourceEventSeqs":[319],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":62}} {"type":"step/start","data":{"turn":1,"step":63}} -{"type":"assistant/message","data":{"turn":1,"step":63,"message":{"role":"assistant","content":[{"type":"text","text":"Observed Count: 4 after hovering, observing and clicking the revealed control. Moving away dismissed the hover information. Geometry conflicts rejected capture and coordinate gestures; the advertised AX button action remained available. No automatic activation or input retry was requested. The separately captured floating panel received one click after its window list was refreshed; keyboard focus stayed in the main window."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:128}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513967,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1792564513967,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Observed Count: 4 after hovering, observing and clicking the revealed control. Moving away dismissed the hover information. Geometry conflicts rejected capture and coordinate gestures; the advertised AX button action remained available. No automatic activation or input retry was requested. The separately captured floating panel received one click after its window list was refreshed; keyboard focus stayed in the main window."}}},{"type":"chunk","time":1792564513967,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513967,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":63,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-consent-revoked","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"revoked-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:128}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516960,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516960,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-consent-revoked","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"revoked-app\"}}"}}},{"type":"chunk","time":1793866516960,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516960,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":63,"callId":"cua-consent-revoked","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"revoked-app\"}}"}} +{"type":"tool/result","data":{"turn":1,"step":63,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-revoked"},"toolCallId":"cua-consent-revoked","content":[{"type":"text","text":"Error: APP_ACCESS_REVOKED: Application access was revoked; stop using this application"}],"isError":true,"id":"{{message:129}}"}},"sourceEventSeqs":[324],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":63}} +{"type":"step/start","data":{"turn":1,"step":64}} +{"type":"assistant/message","data":{"turn":1,"step":64,"message":{"role":"assistant","content":[{"type":"text","text":"Observed Count: 4 after hovering, observing and clicking the revealed control. Moving away dismissed the hover information. Geometry conflicts rejected capture and coordinate gestures; the advertised AX button action remained available. No automatic activation or input retry was requested. The separately captured floating panel received one click after its window list was refreshed; keyboard focus stayed in the main window."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:130}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516975,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1793866516975,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Observed Count: 4 after hovering, observing and clicking the revealed control. Moving away dismissed the hover information. Geometry conflicts rejected capture and coordinate gestures; the advertised AX button action remained available. No automatic activation or input retry was requested. The separately captured floating panel received one click after its window list was refreshed; keyboard focus stayed in the main window."}}},{"type":"chunk","time":1793866516975,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516975,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":64}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/snapshots/session/cua-native/system-prompt.expected.md b/snapshots/session/cua-native/system-prompt.expected.md index 5542f1e18d..1f0a2ecc89 100644 --- a/snapshots/session/cua-native/system-prompt.expected.md +++ b/snapshots/session/cua-native/system-prompt.expected.md @@ -37,7 +37,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. @@ -49,7 +49,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/snapshots/session/cua-native/tool-schemas.expected.json b/snapshots/session/cua-native/tool-schemas.expected.json index 658035fe87..68cfa13e7e 100644 --- a/snapshots/session/cua-native/tool-schemas.expected.json +++ b/snapshots/session/cua-native/tool-schemas.expected.json @@ -264,6 +264,10 @@ "appHandle": { "type": "string", "minLength": 1 + }, + "includeHidden": { + "description": "Include offscreen and zero-size windows for explicit selection or restoration.", + "type": "boolean" } }, "required": [ diff --git a/snapshots/session/cua-ptc/session.v4.jsonl b/snapshots/session/cua-ptc/session.v4.jsonl index 78309a521e..346715c359 100644 --- a/snapshots/session/cua-ptc/session.v4.jsonl +++ b/snapshots/session/cua-ptc/session.v4.jsonl @@ -17,7 +17,7 @@ {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-native-result","parentCallId":"cua-ptc-native-result","subCallId":"cua-ptc-native-result:ptc:1","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-native-result","parentCallId":"cua-ptc-native-result","subCallId":"cua-ptc-native-result:ptc:1","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"name\":\"Fixture\",\"bundleId\":\"test.fixture\"}"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-native-result","parentCallId":"cua-ptc-native-result","subCallId":"cua-ptc-native-result:ptc:2","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":7}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-native-result","parentCallId":"cua-ptc-native-result","subCallId":"cua-ptc-native-result:ptc:2","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":7}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-1\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 0\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-native-result","parentCallId":"cua-ptc-native-result","subCallId":"cua-ptc-native-result:ptc:2","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":7}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-1\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 0\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-native-result","parentCallId":"cua-ptc-native-result","subCallId":"cua-ptc-native-result:ptc:3","name":"cua","arguments":{"method":"screenshot","params":{"appHandle":"fixture-app","windowId":7}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-native-result","parentCallId":"cua-ptc-native-result","subCallId":"cua-ptc-native-result:ptc:3","name":"cua","arguments":{"method":"screenshot","params":{"appHandle":"fixture-app","windowId":7}},"isError":false,"content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}]}} {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-ptc-native-result"},"toolCallId":"cua-ptc-native-result","content":[{"type":"text","text":"{\n \"appHandle\": \"fixture-app\",\n \"hasIncrement\": true,\n \"pngBytes\": 90,\n \"signature\": \"89504e470d0a1a0a\",\n \"imageWidth\": 1,\n \"imageHeight\": 1\n}"}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index 83a083cf45..23e211d6a4 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -39,7 +39,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. @@ -51,7 +51,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 From 7faa643f4674653f492141ff86d36b78eb8a85ae Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 5 Nov 2026 16:28:00 +0800 Subject: [PATCH 006/184] test(cua): refresh the retained script prompt for window discovery --- .../session/ptc-script-retained/system-prompt.expected.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/snapshots/session/ptc-script-retained/system-prompt.expected.md b/snapshots/session/ptc-script-retained/system-prompt.expected.md index 6f5b16bfa1..c7bf71c48f 100644 --- a/snapshots/session/ptc-script-retained/system-prompt.expected.md +++ b/snapshots/session/ptc-script-retained/system-prompt.expected.md @@ -39,7 +39,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. +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. @@ -51,7 +51,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 From 1a3d59a0ff4d1b68a01514d3a9e6c5fe2e13e5eb Mon Sep 17 00:00:00 2001 From: dsh-ci-bot Date: Fri, 6 Nov 2026 16:06:14 +0800 Subject: [PATCH 007/184] test(ui-theme): skip dot directories in the package scan The hover-styles contract walks packages/ for package.json files. Typert generator specs create temporary roots inside that tree with mkdtempSync(join(import.meta.dirname, '....')) and remove them in afterEach, so a concurrent scan can readdir one and then hit ENOENT when its owner deletes it. Dot directories hold VCS metadata and those transient roots, never shipped source, so skip them and let the helper walk an explicit root for the regression test. --- .../ui-theme/tests/stylesheet-scan.spec.ts | 23 +++++++++++++++++++ .../client/ui-theme/tests/stylesheet-scan.ts | 12 ++++++---- 2 files changed, 31 insertions(+), 4 deletions(-) create mode 100644 packages/client/ui-theme/tests/stylesheet-scan.spec.ts diff --git a/packages/client/ui-theme/tests/stylesheet-scan.spec.ts b/packages/client/ui-theme/tests/stylesheet-scan.spec.ts new file mode 100644 index 0000000000..1614ee55a7 --- /dev/null +++ b/packages/client/ui-theme/tests/stylesheet-scan.spec.ts @@ -0,0 +1,23 @@ +/** Tests for the package-tree scan helpers that the stylesheet contracts range over. */ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it } from 'vitest' +import { packageFiles } from './stylesheet-scan.ts' + +const roots: string[] = [] + +afterEach(() => { + for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) +}) + +it('walks shipped package files and skips dot directories holding transient roots', () => { + const root = mkdtempSync(join(tmpdir(), 'dsh-stylesheet-scan-')) + roots.push(root) + mkdirSync(join(root, 'pkg')) + writeFileSync(join(root, 'pkg', 'package.json'), '{}') + mkdirSync(join(root, '.typert-worker-failure-probe')) + writeFileSync(join(root, '.typert-worker-failure-probe', 'package.json'), '{}') + + expect(packageFiles(name => name === 'package.json', root)).toEqual([`${root}/pkg/package.json`]) +}) diff --git a/packages/client/ui-theme/tests/stylesheet-scan.ts b/packages/client/ui-theme/tests/stylesheet-scan.ts index 91311945bf..0ddb93e0f8 100644 --- a/packages/client/ui-theme/tests/stylesheet-scan.ts +++ b/packages/client/ui-theme/tests/stylesheet-scan.ts @@ -75,20 +75,24 @@ export function varReferences(value: string): string[] { * Every file shipped as package source whose name the predicate accepts, * excluding build output and installed dependencies. * @param accepts - filename predicate. - * @returns absolute paths under packages/, `/`-separated on every platform so + * @param root - tree to walk, the packages directory by default. + * @returns absolute paths under `root`, `/`-separated on every platform so * specs can match repo-relative suffixes verbatim. */ -export function packageFiles(accepts: (name: string) => boolean): string[] { +export function packageFiles(accepts: (name: string) => boolean, root: string = PACKAGES_DIR): string[] { const found: string[] = [] const walk = (dir: string): void => { for (const entry of readdirSync(dir, { withFileTypes: true })) { const path = join(dir, entry.name) if (entry.isDirectory()) { - if (entry.name !== 'node_modules' && entry.name !== 'lib' && entry.name !== 'dist') walk(path) + // Dot directories hold VCS metadata and per-test temporary roots (for + // example `.typert-worker-failure-*`), never shipped package source; a + // concurrent owner can remove one while a scan reads it. + if (!entry.name.startsWith('.') && entry.name !== 'node_modules' && entry.name !== 'lib' && entry.name !== 'dist') walk(path) } else if (accepts(entry.name)) found.push(path.replaceAll('\\', '/')) } } - walk(PACKAGES_DIR) + walk(root) return found } From 646e46e0afeb47bce742a1eae4e473b8d6f51a99 Mon Sep 17 00:00:00 2001 From: dsh-ci-bot Date: Fri, 6 Nov 2026 16:24:29 +0800 Subject: [PATCH 008/184] test(ui-theme): scope the package-scan spec to the client face packageFiles() reports '/'-separated paths on every platform, so the fixture's temporary root must be normalized before it forms the expectation; otherwise the Windows coverage lane fails. The spec also belongs to the client aggregate, because an unsuffixed spec file under packages/client is compiled by both aggregates. --- ...stylesheet-scan.spec.ts => stylesheet-scan.client.spec.ts} | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) rename packages/client/ui-theme/tests/{stylesheet-scan.spec.ts => stylesheet-scan.client.spec.ts} (82%) diff --git a/packages/client/ui-theme/tests/stylesheet-scan.spec.ts b/packages/client/ui-theme/tests/stylesheet-scan.client.spec.ts similarity index 82% rename from packages/client/ui-theme/tests/stylesheet-scan.spec.ts rename to packages/client/ui-theme/tests/stylesheet-scan.client.spec.ts index 1614ee55a7..312ee01382 100644 --- a/packages/client/ui-theme/tests/stylesheet-scan.spec.ts +++ b/packages/client/ui-theme/tests/stylesheet-scan.client.spec.ts @@ -19,5 +19,7 @@ it('walks shipped package files and skips dot directories holding transient root mkdirSync(join(root, '.typert-worker-failure-probe')) writeFileSync(join(root, '.typert-worker-failure-probe', 'package.json'), '{}') - expect(packageFiles(name => name === 'package.json', root)).toEqual([`${root}/pkg/package.json`]) + // The helper reports `/`-separated paths on every platform, so the Windows + // temporary root's separators must not reach the expectation. + expect(packageFiles(name => name === 'package.json', root)).toEqual([`${root.replaceAll('\\', '/')}/pkg/package.json`]) }) From 50577597e925fd37767dd9147b1ad9bb5d12a95c Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Fri, 6 Nov 2026 17:40:53 +0800 Subject: [PATCH 009/184] feat(cua-windows): port Windows provider from old branch Port the existing Windows CUA implementation from feat/cua-windows in deepseek-harness2 to the current branch, with adapters for the current app/window interfaces and Windows-only bundle activation. Retain the native Shell/UWP implementation for later interface work. --- package.json | 1 + .../experimental/cua-bundle/README.i18n.yaml | 16 +- packages/experimental/cua-bundle/README.md | 14 +- packages/experimental/cua-bundle/README.zh.md | 14 +- .../experimental/cua-bundle/cordis.patch.yml | 5 + packages/experimental/cua-bundle/package.json | 6 +- .../cua-bundle/tests/platform.spec.ts | 3 +- .../experimental/cua-windows/README.i18n.yaml | 10 + packages/experimental/cua-windows/README.md | 12 + .../experimental/cua-windows/README.zh.md | 12 + .../cua-windows/native/.gitignore | 3 + .../cua-windows/native/.npmignore | 3 + .../cua-windows/native/CuaWindows.csproj | 26 + .../cua-windows/native/Directory.Build.props | 6 + .../cua-windows/native/app.manifest | 13 + .../native/capture-probe/CaptureProbe.cs | 221 +++ .../capture-probe/CaptureProbe.exe.config | 6 + .../native/capture-probe/README.i18n.yaml | 28 + .../native/capture-probe/README.md | 93 ++ .../native/capture-probe/README.zh.md | 93 ++ .../native/capture-probe/app.manifest | 12 + .../cua-windows/native/capture-probe/run.ps1 | 28 + .../desktop-tests/DesktopFixture.csproj | 13 + .../native/desktop-tests/Program.cs | 95 ++ .../cua-windows/native/generate-protocol.ts | 9 + .../cua-windows/native/packages.lock.json | 95 ++ .../cua-windows/native/protocol.schema.json | 1414 +++++++++++++++++ .../native/protocol/AccessibilityText.cs | 74 + .../native/protocol/CuaProtocol.csproj | 14 + .../cua-windows/native/protocol/KeyChord.cs | 25 + .../native/protocol/NativeControlFrame.cs | 23 + .../native/protocol/NativeRequest.cs | 99 ++ .../native/protocol/TextSelection.cs | 49 + .../native/protocol/packages.lock.json | 37 + .../cua-windows/native/src/Accessibility.cs | 245 +++ .../native/src/AccessibilityActions.cs | 163 ++ .../cua-windows/native/src/Applications.cs | 291 ++++ .../native/src/CaptureAdmission.cs | 34 + .../cua-windows/native/src/ClipboardPaste.cs | 183 +++ .../cua-windows/native/src/DesktopExecutor.cs | 264 +++ .../cua-windows/native/src/DesktopSession.cs | 45 + .../cua-windows/native/src/DesktopWindows.cs | 109 ++ .../cua-windows/native/src/Dispatchers.cs | 178 +++ .../cua-windows/native/src/GlobalUsings.cs | 1 + .../cua-windows/native/src/Input.cs | 263 +++ .../cua-windows/native/src/LaunchEntries.cs | 88 + .../cua-windows/native/src/NativeServer.cs | 196 +++ .../cua-windows/native/src/Program.cs | 35 + .../cua-windows/native/src/SharedRuntime.cs | 110 ++ .../cua-windows/native/src/ShellBroker.cs | 111 ++ .../cua-windows/native/src/Win32.cs | 136 ++ .../cua-windows/native/src/WindowCapture.cs | 243 +++ .../cua-windows/native/src/Windows.cs | 176 ++ .../cua-windows/native/tests/Program.cs | 96 ++ .../native/tests/Protocol.Tests.csproj | 11 + .../native/tests/packages.lock.json | 40 + .../experimental/cua-windows/package.json | 95 ++ .../experimental/cua-windows/src/guidance.ts | 2 + .../experimental/cua-windows/src/index.ts | 91 ++ .../cua-windows/src/native-build.ts | 73 + .../cua-windows/src/native-runtime.ts | 354 +++++ .../cua-windows/src/native-transport.ts | 65 + .../cua-windows/src/windows-host.ts | 93 ++ .../cua-windows/tests/desktop-runtime.spec.ts | 22 + .../cua-windows/tests/desktop-smoke.mjs | 285 ++++ .../cua-windows/tests/desktop-tool.spec.ts | 71 + .../cua-windows/tests/native-build.spec.ts | 61 + .../cua-windows/tests/native-runtime.spec.ts | 448 ++++++ .../tests/native-transport.spec.ts | 29 + .../cua-windows/tests/protocol.spec.ts | 30 + .../tests/provider-lifecycle.spec.ts | 108 ++ .../cua-windows/tests/windows-host.spec.ts | 66 + .../experimental/cua-windows/tsconfig.json | 30 + packages/experimental/cua/src/access-types.ts | 4 +- packages/experimental/cua/src/access.ts | 2 +- .../cua/src/client/PermissionPanel.tsx | 12 +- packages/experimental/cua/src/guidance.ts | 2 +- .../cua/tests/panel.client.spec.tsx | 6 +- pnpm-lock.yaml | 115 ++ scripts/check-workspace-constraints.ts | 1 + scripts/experimental-package-policy.ts | 1 + scripts/release/families.spec.ts | 1 + tsconfig.base.json | 1 + tsconfig.host.json | 2 + 84 files changed, 7626 insertions(+), 34 deletions(-) create mode 100644 packages/experimental/cua-windows/README.i18n.yaml create mode 100644 packages/experimental/cua-windows/README.md create mode 100644 packages/experimental/cua-windows/README.zh.md create mode 100644 packages/experimental/cua-windows/native/.gitignore create mode 100644 packages/experimental/cua-windows/native/.npmignore create mode 100644 packages/experimental/cua-windows/native/CuaWindows.csproj create mode 100644 packages/experimental/cua-windows/native/Directory.Build.props create mode 100644 packages/experimental/cua-windows/native/app.manifest create mode 100644 packages/experimental/cua-windows/native/capture-probe/CaptureProbe.cs create mode 100644 packages/experimental/cua-windows/native/capture-probe/CaptureProbe.exe.config create mode 100644 packages/experimental/cua-windows/native/capture-probe/README.i18n.yaml create mode 100644 packages/experimental/cua-windows/native/capture-probe/README.md create mode 100644 packages/experimental/cua-windows/native/capture-probe/README.zh.md create mode 100644 packages/experimental/cua-windows/native/capture-probe/app.manifest create mode 100644 packages/experimental/cua-windows/native/capture-probe/run.ps1 create mode 100644 packages/experimental/cua-windows/native/desktop-tests/DesktopFixture.csproj create mode 100644 packages/experimental/cua-windows/native/desktop-tests/Program.cs create mode 100644 packages/experimental/cua-windows/native/generate-protocol.ts create mode 100644 packages/experimental/cua-windows/native/packages.lock.json create mode 100644 packages/experimental/cua-windows/native/protocol.schema.json create mode 100644 packages/experimental/cua-windows/native/protocol/AccessibilityText.cs create mode 100644 packages/experimental/cua-windows/native/protocol/CuaProtocol.csproj create mode 100644 packages/experimental/cua-windows/native/protocol/KeyChord.cs create mode 100644 packages/experimental/cua-windows/native/protocol/NativeControlFrame.cs create mode 100644 packages/experimental/cua-windows/native/protocol/NativeRequest.cs create mode 100644 packages/experimental/cua-windows/native/protocol/TextSelection.cs create mode 100644 packages/experimental/cua-windows/native/protocol/packages.lock.json create mode 100644 packages/experimental/cua-windows/native/src/Accessibility.cs create mode 100644 packages/experimental/cua-windows/native/src/AccessibilityActions.cs create mode 100644 packages/experimental/cua-windows/native/src/Applications.cs create mode 100644 packages/experimental/cua-windows/native/src/CaptureAdmission.cs create mode 100644 packages/experimental/cua-windows/native/src/ClipboardPaste.cs create mode 100644 packages/experimental/cua-windows/native/src/DesktopExecutor.cs create mode 100644 packages/experimental/cua-windows/native/src/DesktopSession.cs create mode 100644 packages/experimental/cua-windows/native/src/DesktopWindows.cs create mode 100644 packages/experimental/cua-windows/native/src/Dispatchers.cs create mode 100644 packages/experimental/cua-windows/native/src/GlobalUsings.cs create mode 100644 packages/experimental/cua-windows/native/src/Input.cs create mode 100644 packages/experimental/cua-windows/native/src/LaunchEntries.cs create mode 100644 packages/experimental/cua-windows/native/src/NativeServer.cs create mode 100644 packages/experimental/cua-windows/native/src/Program.cs create mode 100644 packages/experimental/cua-windows/native/src/SharedRuntime.cs create mode 100644 packages/experimental/cua-windows/native/src/ShellBroker.cs create mode 100644 packages/experimental/cua-windows/native/src/Win32.cs create mode 100644 packages/experimental/cua-windows/native/src/WindowCapture.cs create mode 100644 packages/experimental/cua-windows/native/src/Windows.cs create mode 100644 packages/experimental/cua-windows/native/tests/Program.cs create mode 100644 packages/experimental/cua-windows/native/tests/Protocol.Tests.csproj create mode 100644 packages/experimental/cua-windows/native/tests/packages.lock.json create mode 100644 packages/experimental/cua-windows/package.json create mode 100644 packages/experimental/cua-windows/src/guidance.ts create mode 100644 packages/experimental/cua-windows/src/index.ts create mode 100644 packages/experimental/cua-windows/src/native-build.ts create mode 100644 packages/experimental/cua-windows/src/native-runtime.ts create mode 100644 packages/experimental/cua-windows/src/native-transport.ts create mode 100644 packages/experimental/cua-windows/src/windows-host.ts create mode 100644 packages/experimental/cua-windows/tests/desktop-runtime.spec.ts create mode 100644 packages/experimental/cua-windows/tests/desktop-smoke.mjs create mode 100644 packages/experimental/cua-windows/tests/desktop-tool.spec.ts create mode 100644 packages/experimental/cua-windows/tests/native-build.spec.ts create mode 100644 packages/experimental/cua-windows/tests/native-runtime.spec.ts create mode 100644 packages/experimental/cua-windows/tests/native-transport.spec.ts create mode 100644 packages/experimental/cua-windows/tests/protocol.spec.ts create mode 100644 packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts create mode 100644 packages/experimental/cua-windows/tests/windows-host.spec.ts create mode 100644 packages/experimental/cua-windows/tsconfig.json diff --git a/package.json b/package.json index 37b86b60d5..d50b670493 100644 --- a/package.json +++ b/package.json @@ -301,6 +301,7 @@ "@deepseek-ai/dsh-experimental-worktree": "workspace:*", "@deepseek-ai/dsh-experimental-tool-worktree": "workspace:*", "@deepseek-ai/dsh-cua-bundle": "workspace:*", + "@deepseek-ai/dsh-cua-windows": "workspace:*", "@deepseek-ai/dsh-experimental-subagent-oar": "workspace:*", "@deepseek-ai/dsh-experimental-tool-subagent-oar": "workspace:*", "@deepseek-ai/dsh-experimental-cua-macos": "workspace:*", diff --git a/packages/experimental/cua-bundle/README.i18n.yaml b/packages/experimental/cua-bundle/README.i18n.yaml index b561f27e44..a04d2cf4b4 100644 --- a/packages/experimental/cua-bundle/README.i18n.yaml +++ b/packages/experimental/cua-bundle/README.i18n.yaml @@ -3,23 +3,23 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/experimental/cua-bundle/README.md /: - en: cc518dcd97629a96 - zh: 465e999011282dc3 + en: 0df5d6f2b9e2ac15 + zh: d0a9bd1f4e172d25 /deepseek-ai-dsh-cua-bundle: en: 9084fb48d0f6489c zh: ce692972d91cf663 /deepseek-ai-dsh-cua-bundle/summary: - en: 0d93f44a8ce7404c - zh: 6a73ed42d0efc9ea + en: f9f318c0ddc27bff + zh: 8a0c5ec31a63eb05 /deepseek-ai-dsh-cua-bundle/table-of-contents: en: b563e4ec4727d0de zh: d0228da978238e05 /deepseek-ai-dsh-cua-bundle/use-this-package: - en: 5c025a58990bb2eb - zh: c3d1280ccbdfe214 + en: f22a10946cefc2d8 + zh: 430d5f0cfc244ef0 /deepseek-ai-dsh-cua-bundle/understand-the-implementation: - en: b1011db52cfc17cd - zh: 6fa8798fedc5c0b6 + en: acb42fb7b181194b + zh: 6961f4cb732560e9 /deepseek-ai-dsh-cua-bundle/further-exploration: en: 9f15d56b5b16e1ca zh: 75eb08e8828c8877 diff --git a/packages/experimental/cua-bundle/README.md b/packages/experimental/cua-bundle/README.md index 50109f1066..9c19ccbbb1 100644 --- a/packages/experimental/cua-bundle/README.md +++ b/packages/experimental/cua-bundle/README.md @@ -1,5 +1,5 @@ --- -description: "Enable optional macOS Computer Use and its permission page." +description: "Enable optional Computer Use on macOS and Windows with its permission page." kind: "package-bundle" --- @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -Enable macOS Computer Use from Plugins for existing and new PTC sessions. Windows support is in development. This bundle remains in `experimental` until that support is complete, then moves to the `computer-use` group. It ships with DSH switched off and appears in the Experimental plugins list on macOS Hosts; disabled profiles prepare no native components and register neither CUA tools nor their model guidance. +Enable Computer Use from Plugins on macOS and Windows for existing and new PTC sessions. The bundle ships with DSH switched off and appears in the Experimental plugins list on supported Hosts. Each Host loads its platform's native provider and the shared permission page. Disabled profiles prepare no native components and register neither CUA tools nor their model guidance. ## Table of Contents @@ -24,7 +24,11 @@ Enable macOS Computer Use from Plugins for existing and new PTC sessions. Window ## Use this package -On macOS, open **Plugins → More** and switch on **Computer use** in the Experimental plugins list. The bundle ships with DSH and updates with it, so enabling it downloads nothing. Published packages contain the signed and notarized helper; users need no compiler. Source Web and development Desktop prepare an ad-hoc helper when enabled. Open its details, choose PTC if needed, and grant Accessibility and Screen Recording to `DSH Computer Use.app`. An enabled bundle also appears in the main plugin list; switching it off returns it to the Experimental plugins list only. For source Web, run these commands from the repository root: +On macOS or Windows, open **Plugins → More** and switch on **Computer use** in the Experimental plugins list. Open its details and choose PTC if needed. An enabled bundle also appears in the main plugin list; switching it off returns it to the Experimental plugins list only. + +On macOS, the bundle ships with DSH and updates with it, so enabling it downloads nothing. Published packages contain the signed and notarized helper; users need no compiler. Source Web and development Desktop prepare an ad-hoc helper when enabled. Grant Accessibility and Screen Recording to `DSH Computer Use.app`. + +Native preparation and access requirements belong to the [macOS provider](../cua-macos/README.md) and [Windows provider](../cua-windows/README.md). For source Web, run these commands from the repository root: ```sh pnpm run build @@ -37,7 +41,7 @@ The switch saves bundle selection in the profile’s `package.json`. Computer Us Disabling unloads the provider and withdraws CUA tools from its Agent scopes. Runtime configuration, the new-session default and saved grants remain. -Computer Use is available only on a macOS DSH Host. The native provider is an optional dependency installed only on macOS; shared CUA and Client packages remain in the installation. Other Hosts hide the bundle from default plugin lists and model recommendations and refuse enablement before saving settings. Explicit profile dependencies and saved selections remain visible for management. An already selected bundle is skipped at startup with a diagnostic and remains available for deselection; saved user settings remain. A browser on another operating system can connect to a supported Mac Host. +The bundle supports macOS and native Windows DSH Hosts; it does not enable Windows Computer Use from WSL. Native providers are optional dependencies, and each Host loads only its matching provider; shared CUA and Client packages remain in the installation. Other Hosts hide the bundle from default plugin lists and model recommendations and refuse enablement before saving settings. Explicit profile dependencies and saved selections remain visible for management. An already selected bundle is skipped at startup with a diagnostic and remains available for deselection; saved user settings remain. A browser on another operating system can connect to a supported DSH Host. If preparation fails, the saved selection remains and CUA operations stay unavailable. Refresh or reopen the plugin page to read the component diagnostic, correct its cause, then restart DSH. @@ -51,7 +55,7 @@ Explicit activation runs a read-only permission check, which may start a helper
Maintainer details -The bundle patch mounts the native provider and permission UI with `agentPreset: ptc`. Using the exported `cordis.patch.yml` directly as an overlay bypasses bundle admission; its row-level condition skips the optional macOS provider on other Hosts. Shared entries alone do not provide computer control. Existing Agent scopes register the tools without changing preset documents. The detail-page action uses the existing settings form to save `agent-preset-registry.selectedDefault: ptc` only when clicked. [CUA](../cua/README.md) owns registration and disposal. +The bundle patch mounts the native provider and permission UI with `agentPreset: ptc`. Using the exported `cordis.patch.yml` directly as an overlay bypasses bundle admission; its row-level conditions load the macOS provider only on macOS and the Windows provider only on native Windows. Shared entries alone do not provide computer control. Existing Agent scopes register the tools without changing preset documents. The detail-page action uses the existing settings form to save `agent-preset-registry.selectedDefault: ptc` only when clicked. [CUA](../cua/README.md) owns registration and disposal.
diff --git a/packages/experimental/cua-bundle/README.zh.md b/packages/experimental/cua-bundle/README.zh.md index b7d8804e91..2318aeb313 100644 --- a/packages/experimental/cua-bundle/README.zh.md +++ b/packages/experimental/cua-bundle/README.zh.md @@ -1,5 +1,5 @@ --- -description: "开启可选 macOS Computer Use 及权限页面。" +description: "在 macOS 和 Windows 上开启可选 Computer Use 及权限页面。" kind: "package-bundle" --- @@ -9,7 +9,7 @@ kind: "package-bundle" ## 概述 -从插件页为已有和新建 PTC 会话开启 macOS Computer Use。Windows 支持正在开发中。本组合包暂放在 `experimental`,待 Windows 支持完成后迁回 `computer-use` 组。随 DSH 提供且默认关闭,在 macOS Host 的实验性插件列表中显示;关闭时不准备本机组件、不注册 CUA 工具或添加其模型指引。 +在 macOS 和 Windows 的插件页为已有和新建 PTC 会话开启 Computer Use。组合包随 DSH 提供且默认关闭,在受支持 Host 的实验性插件列表中显示。各 Host 加载对应平台的原生提供方和共享权限页面。关闭时不准备本机组件、不注册 CUA 工具或添加其模型指引。 ## 目录 @@ -24,7 +24,11 @@ kind: "package-bundle" ## 使用本包 -在 macOS 上打开“插件 → 更多”,在实验性插件列表中开启 Computer Use。组合包随 DSH 提供并随之升级,开启时无需下载。发布包包含已签名和公证的 helper,用户无需编译工具。源码 Web 和开发 Desktop 在开启时准备临时签名的 helper。打开它的详情,按需设置 PTC,并为 `DSH Computer Use.app` 授予辅助功能和屏幕录制权限。开启后组合包也会出现在插件主列表中,关闭后只留在实验性插件列表。源码 Web 在仓库根目录运行以下命令: +在 macOS 或 Windows 上打开“插件 → 更多”,在实验性插件列表中开启 Computer Use。打开详情,按需设置 PTC。开启后组合包也会出现在插件主列表中,关闭后只留在实验性插件列表。 + +在 macOS 上,组合包随 DSH 提供并随之升级,开启时无需下载。发布包包含已签名和公证的 helper,用户无需编译工具。源码 Web 和开发 Desktop 在开启时准备临时签名的 helper。请为 `DSH Computer Use.app` 授予辅助功能和屏幕录制权限。 + +各平台的原生准备和访问要求分别见 [macOS 提供方](../cua-macos/README.zh.md)和 [Windows 提供方](../cua-windows/README.zh.md)。源码 Web 在仓库根目录运行以下命令: ```sh pnpm run build @@ -37,7 +41,7 @@ pnpm dsh web 关闭会卸载提供方,并从其 Agent 作用域中撤回 CUA 工具。执行器配置、新会话默认值和已保存的授权保留。 -Computer Use 仅支持 macOS DSH Host。原生提供方是仅在 macOS 安装的可选依赖,共享 CUA 和 Client 包仍随安装提供。其他 Host 默认不在插件列表和模型推荐中展示此组合包,并在保存设置前拒绝启用。profile 显式安装的依赖和已保存的选择仍保留管理入口。已选中的组合包会在启动时跳过并报告原因,仍可取消选择;已保存的用户设置保留。其他操作系统上的浏览器可以连接受支持的 Mac Host。 +组合包支持 macOS 和原生 Windows DSH Host,不在 WSL 中启用 Windows Computer Use。原生提供方作为可选依赖提供,各 Host 只加载对应平台的提供方;共享 CUA 和 Client 包仍随安装提供。其他 Host 默认不在插件列表和模型推荐中展示此组合包,并在保存设置前拒绝启用。profile 显式安装的依赖和已保存的选择仍保留管理入口。已选中的组合包会在启动时跳过并报告原因,仍可取消选择;已保存的用户设置保留。其他操作系统上的浏览器可以连接受支持的 DSH Host。 准备失败时,已保存的选择保留,CUA 操作不可用。刷新或重新打开插件页查看组件诊断,修复后重启 DSH。 @@ -51,7 +55,7 @@ Computer Use 仅支持 macOS DSH Host。原生提供方是仅在 macOS 安装的
维护者说明 -组合包 patch 通过 `agentPreset: ptc` 挂载原生提供方和权限界面。直接将导出的 `cordis.patch.yml` 用作覆盖层时不会经过组合包准入;行级条件会在其他 Host 上跳过可选的 macOS 提供方。仅加载共享条目不能提供计算机控制。工具通过现有 Agent 作用域注册,preset 文档保持不变。详情页按钮复用现有设置表单,仅在点击后保存 `agent-preset-registry.selectedDefault: ptc`。[CUA](../cua/README.zh.md)负责注册和销毁。 +组合包 patch 通过 `agentPreset: ptc` 挂载原生提供方和权限界面。直接将导出的 `cordis.patch.yml` 用作覆盖层时不会经过组合包准入;行级条件确保 macOS 提供方仅在 macOS 加载,Windows 提供方仅在原生 Windows 加载。仅加载共享条目不能提供计算机控制。工具通过现有 Agent 作用域注册,preset 文档保持不变。详情页按钮复用现有设置表单,仅在点击后保存 `agent-preset-registry.selectedDefault: ptc`。[CUA](../cua/README.zh.md)负责注册和销毁。
diff --git a/packages/experimental/cua-bundle/cordis.patch.yml b/packages/experimental/cua-bundle/cordis.patch.yml index 5d5fb48b6f..82d3d0960f 100644 --- a/packages/experimental/cua-bundle/cordis.patch.yml +++ b/packages/experimental/cua-bundle/cordis.patch.yml @@ -6,5 +6,10 @@ disabled: !!js process.platform !== 'darwin' config: agentPreset: ptc + - id: cua-windows + name: '@deepseek-ai/dsh-cua-windows' + disabled: !!js process.platform !== 'win32' + config: + agentPreset: ptc - id: ui-cua name: '@deepseek-ai/dsh-cua' diff --git a/packages/experimental/cua-bundle/package.json b/packages/experimental/cua-bundle/package.json index f9ba508721..699b5bae93 100644 --- a/packages/experimental/cua-bundle/package.json +++ b/packages/experimental/cua-bundle/package.json @@ -40,7 +40,8 @@ "bundle": { "patch": "./cordis.patch.yml", "platforms": [ - "darwin" + "darwin", + "win32" ] } }, @@ -58,6 +59,7 @@ "@deepseek-ai/cordis-plugin-loader": "workspace:~" }, "optionalDependencies": { - "@deepseek-ai/dsh-experimental-cua-macos": "workspace:*" + "@deepseek-ai/dsh-experimental-cua-macos": "workspace:*", + "@deepseek-ai/dsh-cua-windows": "workspace:*" } } diff --git a/packages/experimental/cua-bundle/tests/platform.spec.ts b/packages/experimental/cua-bundle/tests/platform.spec.ts index 4230e4f406..912e2c56b9 100644 --- a/packages/experimental/cua-bundle/tests/platform.spec.ts +++ b/packages/experimental/cua-bundle/tests/platform.spec.ts @@ -6,7 +6,7 @@ import { entryListSchema } from '@deepseek-ai/cordis-plugin-include' import { load } from 'js-yaml' import { expect, it, vi } from 'vitest' -it.each(['darwin', 'win32', 'linux'])('loads the exported patch directly on %s and imports the native provider only on Darwin', async (platform) => { +it.each(['darwin', 'win32', 'linux'])('loads the exported patch directly on %s and selects its native provider', async (platform) => { const patch = load(await readFile(new URL('../cordis.patch.yml', import.meta.url), 'utf8'), { schema: entryListSchema, }) as { insert: EntryOptions[] }[] @@ -28,6 +28,7 @@ it.each(['darwin', 'win32', 'linux'])('loads the exported patch directly on %s a expect(imports).toContain('@deepseek-ai/dsh-cua') expect(imports).toContain('@deepseek-ai/dsh-computer-use') expect(imports.includes('@deepseek-ai/dsh-experimental-cua-macos')).toBe(platform === 'darwin') + expect(imports.includes('@deepseek-ai/dsh-cua-windows')).toBe(platform === 'win32') } finally { await ctx.fiber.dispose() imported.mockRestore() diff --git a/packages/experimental/cua-windows/README.i18n.yaml b/packages/experimental/cua-windows/README.i18n.yaml new file mode 100644 index 0000000000..30b2eb4f1f --- /dev/null +++ b/packages/experimental/cua-windows/README.i18n.yaml @@ -0,0 +1,10 @@ +# Bilingual-pair consistency record for README.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 packages/experimental/cua-windows/README.md +/: + en: 74cec3b0e35e9bf4 + zh: 8c7eb35b11ada2b5 +/deepseek-ai-dsh-cua-windows: + en: f31869d4398aa0ae + zh: b94122bb2bc53a53 diff --git a/packages/experimental/cua-windows/README.md b/packages/experimental/cua-windows/README.md new file mode 100644 index 0000000000..40a31c5e3f --- /dev/null +++ b/packages/experimental/cua-windows/README.md @@ -0,0 +1,12 @@ +--- +description: "TODO: Windows Computer Use documentation." +kind: "package-reference" +--- + +# @deepseek-ai/dsh-cua-windows + +English | [中文](README.zh.md) + +TODO: Document the migrated provider after the interface is finalized. + +TODO: Expose the retained native Shell/UWP discovery and launch operations. diff --git a/packages/experimental/cua-windows/README.zh.md b/packages/experimental/cua-windows/README.zh.md new file mode 100644 index 0000000000..9f118ebe6f --- /dev/null +++ b/packages/experimental/cua-windows/README.zh.md @@ -0,0 +1,12 @@ +--- +description: "TODO:Windows Computer Use 文档。" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-cua-windows + +[English](README.md) | 中文 + +TODO:接口定稿后统一补齐迁移后提供方的文档。 + +TODO:暴露保留的 native Shell/UWP 发现和启动操作。 diff --git a/packages/experimental/cua-windows/native/.gitignore b/packages/experimental/cua-windows/native/.gitignore new file mode 100644 index 0000000000..d519714059 --- /dev/null +++ b/packages/experimental/cua-windows/native/.gitignore @@ -0,0 +1,3 @@ +**/bin/ +**/obj/ +.build/ diff --git a/packages/experimental/cua-windows/native/.npmignore b/packages/experimental/cua-windows/native/.npmignore new file mode 100644 index 0000000000..6fd41ce451 --- /dev/null +++ b/packages/experimental/cua-windows/native/.npmignore @@ -0,0 +1,3 @@ +obj/ +protocol/bin/ +tests/bin/ diff --git a/packages/experimental/cua-windows/native/CuaWindows.csproj b/packages/experimental/cua-windows/native/CuaWindows.csproj new file mode 100644 index 0000000000..0cc65b6907 --- /dev/null +++ b/packages/experimental/cua-windows/native/CuaWindows.csproj @@ -0,0 +1,26 @@ + + + Exe + net10.0-windows10.0.19041.0 + true + true + true + false + enable + enable + true + dsh-cua-windows + app.manifest + true + win-x64;win-arm64 + true + true + none + false + + + + + + + diff --git a/packages/experimental/cua-windows/native/Directory.Build.props b/packages/experimental/cua-windows/native/Directory.Build.props new file mode 100644 index 0000000000..b4fbcbc808 --- /dev/null +++ b/packages/experimental/cua-windows/native/Directory.Build.props @@ -0,0 +1,6 @@ + + + $(MSBuildThisFileDirectory).build/$(MSBuildProjectName)/bin/ + $(MSBuildThisFileDirectory).build/$(MSBuildProjectName)/obj/ + + diff --git a/packages/experimental/cua-windows/native/app.manifest b/packages/experimental/cua-windows/native/app.manifest new file mode 100644 index 0000000000..a2e299ca4e --- /dev/null +++ b/packages/experimental/cua-windows/native/app.manifest @@ -0,0 +1,13 @@ + + + + + + + + + PerMonitorV2 + true + + + diff --git a/packages/experimental/cua-windows/native/capture-probe/CaptureProbe.cs b/packages/experimental/cua-windows/native/capture-probe/CaptureProbe.cs new file mode 100644 index 0000000000..6f118d63ae --- /dev/null +++ b/packages/experimental/cua-windows/native/capture-probe/CaptureProbe.cs @@ -0,0 +1,221 @@ +// Private .NET Framework experiment. Each blocking capture runs in a disposable child process. +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Drawing; +using System.Drawing.Imaging; +using System.IO; +using System.Runtime.InteropServices; +using System.Threading.Tasks; +using System.Web.Script.Serialization; +using System.Windows.Automation; +using System.Windows.Forms; + +internal static class CaptureProbe +{ + private static readonly JavaScriptSerializer Json = new JavaScriptSerializer(); + private static readonly string[] Methods = { "screen", "window-dc", "print", "print-full" }; + + [STAThread] + private static int Main(string[] args) + { + try + { + SetProcessDpiAwarenessContext(new IntPtr(-4)); + if (args.Length == 4 && args[0] == "--one") + { + Capture(new IntPtr(long.Parse(args[1])), args[2], args[3]); + return 0; + } + if (args.Length == 3 && args[0] == "--compare") + { + var output = NewOutput(args[2]); + Compare(new IntPtr(long.Parse(args[1])), output, "selected"); + return 0; + } + if (args.Length != 2 || args[0] != "--demo") + throw new ArgumentException("Expected --demo OUTPUT or --compare DECIMAL_HWND OUTPUT"); + var directory = NewOutput(args[1]); + Application.EnableVisualStyles(); + using (var target = new Form()) + using (var cover = new Form()) + { + target.Text = "DSH capture probe: owned target"; + target.StartPosition = cover.StartPosition = FormStartPosition.Manual; + target.Bounds = new Rectangle(100, 100, 520, 400); + target.BackColor = Color.FromArgb(20, 180, 60); + target.TopMost = true; + cover.Text = "DSH capture probe: owned cover"; + cover.Bounds = target.Bounds; + cover.BackColor = Color.Magenta; + cover.TopMost = true; + Exception failure = null; + target.Shown += async delegate + { + try + { + var hwnd = target.Handle; + var automation = await Task.Run(() => AutomationElement.FromHandle(hwnd).Current.Name); + Write(Path.Combine(directory, "runtime.json"), new + { + framework = Environment.Version.ToString(), + automationName = automation, + os = Environment.OSVersion.VersionString, + pointerBytes = IntPtr.Size + }); + target.Refresh(); + var center = new Point(target.Left + target.Width / 2, target.Top + target.Height / 2); + await WaitForPixel(center, target.BackColor); + await Task.Run(() => Compare(hwnd, directory, "visible")); + cover.Show(); + cover.Refresh(); + await WaitForPixel(center, cover.BackColor); + // A new marker distinguishes a fresh covered image from a cached visible image. + target.BackColor = Color.FromArgb(30, 90, 220); + target.Refresh(); + await Task.Run(() => Compare(hwnd, directory, "covered-updated")); + target.WindowState = FormWindowState.Minimized; + await Task.Run(() => Compare(hwnd, directory, "minimized")); + } + catch (Exception error) { failure = error; } + finally { cover.Close(); target.Close(); } + }; + Application.Run(target); + if (failure != null) throw failure; + } + return 0; + } + catch (Exception error) + { + Console.Error.WriteLine(error); + return 1; + } + } + + private static string NewOutput(string path) + { + var result = Path.GetFullPath(path); + if (Directory.Exists(result)) throw new IOException("Use a new output directory for each experiment"); + Directory.CreateDirectory(result); + return result; + } + + private static async Task WaitForPixel(Point point, Color expected) + { + var clock = Stopwatch.StartNew(); + using (var sample = new Bitmap(1, 1)) + using (var graphics = Graphics.FromImage(sample)) + { + while (true) + { + graphics.CopyFromScreen(point.X, point.Y, 0, 0, sample.Size); + if (sample.GetPixel(0, 0).ToArgb() == expected.ToArgb()) return; + if (clock.ElapsedMilliseconds > 5000) throw new TimeoutException("The owned window marker is not visible"); + await Task.Delay(25); + } + } + } + + private static void Compare(IntPtr window, string directory, string scenario) + { + foreach (var method in Methods) + { + var prefix = Path.Combine(directory, scenario + "-" + method); + var start = new ProcessStartInfo(Application.ExecutablePath, + "--one " + window.ToInt64() + " " + method + " \"" + prefix + "\"") + { + UseShellExecute = false, + CreateNoWindow = true + }; + using (var process = Process.Start(start)) + { + if (!process.WaitForExit(5000)) + { + process.Kill(); + process.WaitForExit(); + Write(prefix + ".json", new { method, timeout = true }); + } + else if (process.ExitCode != 0) + throw new InvalidOperationException(method + " child exited " + process.ExitCode); + } + Console.WriteLine(File.ReadAllText(prefix + ".json")); + } + } + + private static void Capture(IntPtr window, string method, string prefix) + { + Rect bounds; + if (!GetWindowRect(window, out bounds)) throw new InvalidOperationException("Window no longer exists"); + var width = bounds.Right - bounds.Left; + var height = bounds.Bottom - bounds.Top; + if (width <= 0 || height <= 0 || (long)width * height > 40000000) + throw new InvalidOperationException("Window dimensions exceed the experiment limit"); + var foreground = GetForegroundWindow(); + var clock = Stopwatch.StartNew(); + using (var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb)) + { + bool returned; + using (var graphics = Graphics.FromImage(bitmap)) + { + graphics.Clear(Color.Yellow); + if (method == "screen") + { + graphics.CopyFromScreen(bounds.Left, bounds.Top, 0, 0, new Size(width, height)); + returned = true; + } + else if (method == "window-dc") + { + var source = GetWindowDC(window); + if (source == IntPtr.Zero) throw new InvalidOperationException("Window DC is unavailable"); + try + { + var destination = graphics.GetHdc(); + try { returned = BitBlt(destination, 0, 0, width, height, source, 0, 0, 0x00CC0020); } + finally { graphics.ReleaseHdc(destination); } + } + finally { ReleaseDC(window, source); } + } + else + { + var dc = graphics.GetHdc(); + try { returned = PrintWindow(window, dc, method == "print-full" ? 2u : 0u); } + finally { graphics.ReleaseHdc(dc); } + } + } + clock.Stop(); + var markers = new Dictionary { { "green", 0 }, { "blue", 0 }, { "cover", 0 }, { "black", 0 } }; + for (var y = 0; y < height; y += 4) + for (var x = 0; x < width; x += 4) + { + var pixel = bitmap.GetPixel(x, y); + if (pixel.R == 20 && pixel.G == 180 && pixel.B == 60) markers["green"]++; + if (pixel.R == 30 && pixel.G == 90 && pixel.B == 220) markers["blue"]++; + if (pixel.R == 255 && pixel.G == 0 && pixel.B == 255) markers["cover"]++; + if (pixel.R == 0 && pixel.G == 0 && pixel.B == 0) markers["black"]++; + } + bitmap.Save(prefix + ".png", ImageFormat.Png); + Write(prefix + ".json", new + { + method, returned, width, height, elapsedMs = clock.ElapsedMilliseconds, markers, + minimized = IsIconic(window), foregroundChanged = foreground != GetForegroundWindow() + }); + } + } + + private static void Write(string path, object value) + { + File.WriteAllText(path, Json.Serialize(value) + Environment.NewLine); + } + + [StructLayout(LayoutKind.Sequential)] + private struct Rect { internal int Left, Top, Right, Bottom; } + [DllImport("user32.dll")] private static extern bool SetProcessDpiAwarenessContext(IntPtr context); + [DllImport("user32.dll")] private static extern bool GetWindowRect(IntPtr hwnd, out Rect rect); + [DllImport("user32.dll")] private static extern bool PrintWindow(IntPtr hwnd, IntPtr dc, uint flags); + [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); + [DllImport("user32.dll")] private static extern bool IsIconic(IntPtr hwnd); + [DllImport("user32.dll")] private static extern IntPtr GetWindowDC(IntPtr hwnd); + [DllImport("user32.dll")] private static extern int ReleaseDC(IntPtr hwnd, IntPtr dc); + [DllImport("gdi32.dll")] private static extern bool BitBlt(IntPtr destination, int x, int y, int width, int height, + IntPtr source, int sourceX, int sourceY, uint operation); +} diff --git a/packages/experimental/cua-windows/native/capture-probe/CaptureProbe.exe.config b/packages/experimental/cua-windows/native/capture-probe/CaptureProbe.exe.config new file mode 100644 index 0000000000..6c3273cff7 --- /dev/null +++ b/packages/experimental/cua-windows/native/capture-probe/CaptureProbe.exe.config @@ -0,0 +1,6 @@ + + + + + + diff --git a/packages/experimental/cua-windows/native/capture-probe/README.i18n.yaml b/packages/experimental/cua-windows/native/capture-probe/README.i18n.yaml new file mode 100644 index 0000000000..29c76d358f --- /dev/null +++ b/packages/experimental/cua-windows/native/capture-probe/README.i18n.yaml @@ -0,0 +1,28 @@ +# Bilingual-pair consistency record for README.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 packages/experimental/cua-windows/native/capture-probe/README.md +/: + en: eeabe421bc58f08c + zh: decfb432f67c7a10 +/windows-capture-experiment: + en: 04636b80e16e9c77 + zh: 1939a876909a0728 +/windows-capture-experiment/summary: + en: b7d5300b63fbf75d + zh: 7ac6fff1d0e0ff39 +/windows-capture-experiment/table-of-contents: + en: 5fe6d5c7d6ef2980 + zh: 1b6c59a3a0dae8cd +/windows-capture-experiment/run-the-experiment: + en: 0a3af6cd49068299 + zh: 8efa8e90294c4f28 +/windows-capture-experiment/interpret-the-output: + en: aa765881c455c6c0 + zh: 6d76f02d287f5260 +/windows-capture-experiment/further-exploration: + en: e886759b879c9754 + zh: 0dfaea2ea703055f +/windows-capture-experiment/further-exploration/dev-note: + en: 8a4492cdafa89a70 + zh: b2d7be08c34a0b10 diff --git a/packages/experimental/cua-windows/native/capture-probe/README.md b/packages/experimental/cua-windows/native/capture-probe/README.md new file mode 100644 index 0000000000..737fe1306d --- /dev/null +++ b/packages/experimental/cua-windows/native/capture-probe/README.md @@ -0,0 +1,93 @@ +--- +description: "Run Windows capture comparisons with the installed .NET Framework and review the native runtime migration plan." +--- + +# Windows capture experiment + +English | [中文](README.zh.md) + +## Summary + +Compare screen copying, window DC copying, and PrintWindow without installing a .NET SDK or third-party library. The private experiment targets .NET Framework 4.8 and uses the compiler and assemblies installed with Windows. It does not replace the provider's capture implementation. + +## Table of Contents + +- [Run the experiment](#run-the-experiment) +- [Interpret the output](#interpret-the-output) +- [Further Exploration](#further-exploration) +- [Dev Note](#dev-note) + +----- + + +## Run the experiment + +On an interactive x64 Windows desktop, run this command from the repository root in Windows PowerShell. The demo creates two temporary windows, tests a visible green target, covers it while changing its content to blue, then minimizes it. It closes both windows on completion. + +```powershell +powershell -NoProfile -File packages/experimental/cua-windows/native/capture-probe/run.ps1 +``` + +The printed output directory contains PNGs and JSON measurements. The script compiles into a unique temporary directory and removes the executable afterward. A new output directory is required for every run. Compilation errors, unavailable windows, and failed captures produce a nonzero exit. + +To compare an application you select, pass its decimal top-level HWND and a new output directory. This mode captures its current state without changing focus, position, or visibility. Obtain the HWND with a window inspector; a PID is not a window handle. + +```powershell +powershell -NoProfile -File packages/experimental/cua-windows/native/capture-probe/run.ps1 -WindowHandle 123456 -OutputDirectory C:\Temp\cua-capture-example +``` + +Replace the example HWND and output directory. Repeat with the window covered, after its content changes, and after resizing. The screen-copy image includes whatever occupies those screen coordinates. Keep evidence local when other applications can appear there. + +----- + + +## Interpret the output + +Each capture runs in a separate process with a five-second deadline. A hung capture is terminated and recorded as a timeout. JSON records the API return value, image dimensions, elapsed capture time, sampled foreground change, and counts of known marker colors. A successful API return or a valid PNG does not establish that the image contains current target content. + +| Method | Windows facility | What to inspect | +|---|---|---| +| `screen` | `System.Drawing.Graphics.CopyFromScreen` | Whether another window replaces the target pixels. | +| `window-dc` | `GetWindowDC` and GDI `BitBlt` | Whether compositor-backed content is missing or stale. | +| `print` | `PrintWindow`, flags `0` | Whether the target handles print requests. | +| `print-full` | `PrintWindow`, `PW_RENDERFULLCONTENT` | Whether the complete, current client content appears. | + +The demo waits until its visible marker reaches the screen before comparing methods. It samples UI Automation from an MTA thread and records the result in `runtime.json`. Marker checks are intended for the owned fixture; other applications require visual comparison against their actual state. This experiment does not test WGC, clipboard restoration, input, service sharing, or ARM64 compatibility. + +----- + + +## Further Exploration + +- [Provider behavior and desktop acceptance](../../README.md) +- [PrintWindow and its synchronous execution](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-printwindow) +- [Windows SDK capture flags](https://github.com/microsoft/win32metadata/blob/main/generation/WinSDK/RecompiledIdlHeaders/um/WinUser.h) +- [Windows Graphics Capture](https://learn.microsoft.com/en-us/windows/apps/develop/media-authoring-processing/screen-capture) +- [.NET Framework system requirements](https://learn.microsoft.com/en-us/dotnet/framework/get-started/system-requirements) +- [Code Pack window capture source](https://github.com/aybe/Windows-API-Code-Pack-1.1/blob/master/source/WindowsAPICodePack/Shell/Taskbar/TabbedThumbnailScreenCapture.cs) + +----- + + +### Dev Note + +Research and proposed work below are non-authoritative; the production helper still targets .NET 10 and captures through WGC/Direct3D11. + +The Windows x64 machine used on 2026-10-20 has Framework release `533509` (4.8.1). The Framework-only probe compiled, queried the owned window through `System.Windows.Automation`, and captured images without NuGet dependencies. The current self-contained production helper is approximately 192 MiB; the probe is much smaller because it implements only this experiment. Its size is not an estimate of a complete port. + +For the painted WinForms fixture, all four methods captured the visible green content. After covering the window and changing it to blue, screen copying returned the magenta cover, while window DC copying and both PrintWindow variants returned the new blue content. After minimization, every API reported success but returned only a 314 × 50 image without the content marker. These observations do not establish behavior for other rendering engines or monitors. + +For an owned local HTML page in Edge, window DC copying and ordinary PrintWindow returned black images even while visible. Full-content PrintWindow captured the visible green page. After covering it, JavaScript changed the background to blue and updated the title; full-content PrintWindow captured the updated title with the old green client content. The fresh-content requirement remains unresolved for this case, including whether WGC behaves differently. This is a reason to compare rendering engines before replacing the backend. + +The capture decision must preserve background window observation. `CopyFromScreen` and desktop duplication observe the composed desktop, so they cannot substitute for covered-window capture. DWM thumbnails display another window in a destination window rather than directly returning PNG pixels. WGC supplies Direct3D11 frames by design; removing the Vortice wrapper does not remove that dependency from the API. + +Windows API Code Pack is useful reference material for Shell objects, links, common dialogs, and taskbar integration. Its `TabbedThumbnailScreenCapture` wraps GDI window DC copying and documents limitations for hidden or obstructed controls. It does not provide a general replacement for WGC or target-confirmed clipboard consumption. WinForms already provides ordinary clipboard access, drawing, images, and a message loop; UI Automation is also in the Framework. Add a Code Pack dependency only for a specific capability that removes more maintained code than it introduces. + +Proposed implementation order: + +1. Compare PrintWindow's full-content mode against WGC on Chromium/Electron, WPF, classic controls, changed covered content, mixed DPI, and a hung target. Keep the saved PNGs and observed state together. Select a production backend only after this comparison; do not silently fall back to screen pixels when a window capture fails. +2. Use .NET Framework 4.8 as the runtime port candidate for x64. Keep `System.Windows.Automation`, WinForms, `System.Drawing`, and Windows P/Invoke. Verify the ARM64 runtime and delivery requirements separately; this x64 experiment cannot establish them. +3. Port runtime APIs deliberately: pipe and mutex access control, cancellation and disposal, hashing, and JSON handling. Framework `JavaScriptSerializer` can emit the probe's JSON, but replacing `System.Text.Json` must preserve protocol validation, duplicate-property rejection, numeric limits, and escaping. `JsonSchema.Net` has a netstandard2.0 asset; the installed Vortice version has only modern .NET assets. Avoid introducing a handwritten JSON/schema framework merely to remove a package. +4. Run the owned desktop smoke and shared-service lifetime checks against the selected runtime, then update source preparation and packaging. Remove superseded implementations and dependencies after those checks pass. Keep the shared `cua` API and the macOS provider outside this Windows runtime change. + +The current desktop smoke exposed clipboard prefetch by the Remote Desktop client before the selected editor consumed the data. The pending fix identifies the requesting window's process and leaves the format delayed for other readers. Readers that open the clipboard without an HWND cannot be attributed and time out. The revised native binary cross-compiles, but Smart App Control blocked its execution on this machine. The branch is handed over for human-owned Windows acceptance with an approved signed build or test environment. Earlier smoke results must not be represented as validation of that binary. diff --git a/packages/experimental/cua-windows/native/capture-probe/README.zh.md b/packages/experimental/cua-windows/native/capture-probe/README.zh.md new file mode 100644 index 0000000000..cf07001498 --- /dev/null +++ b/packages/experimental/cua-windows/native/capture-probe/README.zh.md @@ -0,0 +1,93 @@ +--- +description: "使用系统安装的 .NET Framework 对比 Windows 截图方案,并审阅原生运行时迁移计划。" +--- + +# Windows 截图实验 + +[English](README.md) | 中文 + +## 摘要 + +无需安装 .NET SDK 或第三方库,即可对比屏幕复制、窗口 DC 复制和 PrintWindow。此私有实验以 .NET Framework 4.8 为目标,使用 Windows 已安装的编译器和程序集。它不替换提供方的截图实现。 + +## 目录 + +- [运行实验](#run-the-experiment) +- [解读输出](#interpret-the-output) +- [延伸阅读](#further-exploration) +- [开发备注](#dev-note) + +----- + + +## 运行实验 + +在交互式 x64 Windows 桌面上,从仓库根目录使用 Windows PowerShell 运行以下命令。演示创建两个临时窗口,测试可见的绿色目标,在遮挡后将其内容改为蓝色,然后将其最小化。完成后关闭两个窗口。 + +```powershell +powershell -NoProfile -File packages/experimental/cua-windows/native/capture-probe/run.ps1 +``` + +打印的输出目录包含 PNG 和 JSON 测量结果。脚本在唯一临时目录中编译,运行后删除可执行文件。每次运行必须使用新的输出目录。编译错误、窗口不可用和截图失败均产生非零退出状态。 + +要对比自行选择的应用,传入其十进制顶层窗口 HWND 和新的输出目录。此模式捕获当前状态,不改变焦点、位置或可见性。可用窗口检查工具取得 HWND;PID 不是窗口句柄。 + +```powershell +powershell -NoProfile -File packages/experimental/cua-windows/native/capture-probe/run.ps1 -WindowHandle 123456 -OutputDirectory C:\Temp\cua-capture-example +``` + +替换示例中的 HWND 和输出目录。在窗口被遮挡、内容变化和尺寸变化后重复运行。屏幕复制的图片包含相应屏幕坐标上实际显示的内容;当其他应用可能出现在该位置时,证据应保留在本地。 + +----- + + +## 解读输出 + +每次截图在独立进程中执行,期限为五秒。卡住的截图会被终止,并记录为超时。JSON 记录 API 返回值、图片尺寸、截图耗时、采样到的前台变化以及已知标记颜色的数量。API 返回成功或生成有效 PNG,并不能证明图片包含目标的最新内容。 + +| 方法 | Windows 功能 | 检查内容 | +|---|---|---| +| `screen` | `System.Drawing.Graphics.CopyFromScreen` | 其他窗口是否替代了目标像素。 | +| `window-dc` | `GetWindowDC` 与 GDI `BitBlt` | 合成器承载的内容是否缺失或过时。 | +| `print` | `PrintWindow`,标志 `0` | 目标是否处理打印请求。 | +| `print-full` | `PrintWindow`,`PW_RENDERFULLCONTENT` | 是否包含完整、最新的客户区内容。 | + +演示等待可见标记实际显示到屏幕后,再比较各方法。它在 MTA 线程读取 UI Automation,并将结果记入 `runtime.json`。标记检查适用于自有测试窗口;其他应用需要与实际状态进行视觉比较。本实验不测试 WGC、剪贴板恢复、输入、服务共享或 ARM64 兼容性。 + +----- + + +## 延伸阅读 + +- [提供方行为与桌面验收](../../README.zh.md) +- [PrintWindow 及其同步执行](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-printwindow) +- [Windows SDK 截图标志](https://github.com/microsoft/win32metadata/blob/main/generation/WinSDK/RecompiledIdlHeaders/um/WinUser.h) +- [Windows Graphics Capture](https://learn.microsoft.com/en-us/windows/apps/develop/media-authoring-processing/screen-capture) +- [.NET Framework 系统要求](https://learn.microsoft.com/en-us/dotnet/framework/get-started/system-requirements) +- [Code Pack 窗口截图源码](https://github.com/aybe/Windows-API-Code-Pack-1.1/blob/master/source/WindowsAPICodePack/Shell/Taskbar/TabbedThumbnailScreenCapture.cs) + +----- + + +### 开发备注 + +以下调研和拟议工作不是正式约定;生产 helper 仍以 .NET 10 为目标,并通过 WGC/Direct3D11 截图。 + +2026-10-20 使用的 Windows x64 机器安装了 Framework 版本标识 `533509`(4.8.1)。仅依赖 Framework 的探针已完成编译,通过 `System.Windows.Automation` 查询自有窗口并截图,无需 NuGet 依赖。当前自包含生产 helper 约为 192 MiB;探针小得多,因为它只实现本实验。其大小不能用来估算完整移植的大小。 + +对于完成绘制的 WinForms 测试窗口,四种方法均捕获了可见的绿色内容。遮挡窗口并将内容改为蓝色后,屏幕复制返回紫红色遮挡窗口,窗口 DC 复制和两种 PrintWindow 模式则返回新的蓝色内容。最小化后,各 API 都报告成功,但仅返回不含内容标记的 314 × 50 图片。这些结果不能证明其他渲染引擎或显示器上的行为。 + +对于 Edge 中的自有本地 HTML 页面,窗口 DC 复制和普通 PrintWindow 即使在窗口可见时也返回黑图。完整内容模式的 PrintWindow 捕获了可见的绿色页面。遮挡后,JavaScript 将背景改为蓝色并更新标题;完整内容模式捕获了更新后的标题,但客户区仍为旧的绿色内容。此场景的内容新鲜度要求尚未解决,包括 WGC 是否有不同行为。这说明替换后端前需要比较不同渲染引擎。 + +截图选型必须保留后台窗口观察能力。`CopyFromScreen` 和桌面复制读取合成后的桌面,因此不能替代遮挡窗口截图。DWM 缩略图在目标窗口中显示另一窗口,而不直接返回 PNG 像素。WGC 的接口本身就提供 Direct3D11 帧;删除 Vortice 包装库并不能消除该 API 的此项依赖。 + +Windows API Code Pack 可用于参考 Shell 对象、链接、通用对话框和任务栏集成。其 `TabbedThumbnailScreenCapture` 封装了 GDI 窗口 DC 复制,并明确说明隐藏或遮挡控件的限制。它不提供 WGC 或确认目标消费剪贴板数据的通用替代品。WinForms 已提供普通剪贴板访问、绘图、图片和消息循环;UI Automation 也属于 Framework。只有在具体能力能删除更多自有维护代码时,才引入 Code Pack 依赖。 + +拟议实现顺序: + +1. 在 Chromium/Electron、WPF、传统控件、遮挡后的内容变化、混合 DPI 及卡死目标上,对比 PrintWindow 完整内容模式与 WGC。将保存的 PNG 与实际状态放在一起。完成对比后再选择生产后端;窗口截图失败时不得静默改用屏幕像素。 +2. 将 .NET Framework 4.8 作为 x64 运行时移植候选,保留 `System.Windows.Automation`、WinForms、`System.Drawing` 和 Windows P/Invoke。单独验证 ARM64 运行时及交付要求;本次 x64 实验不能证明它们。 +3. 明确迁移运行时 API:命名管道和互斥量访问控制、取消和释放、散列及 JSON 处理。Framework 的 `JavaScriptSerializer` 可以输出探针的 JSON,但替代 `System.Text.Json` 必须保留协议校验、重复属性拒绝、数字限制和转义行为。`JsonSchema.Net` 有 netstandard2.0 产物;当前 Vortice 版本只有现代 .NET 产物。避免仅为删除一个依赖包而手写 JSON/schema 框架。 +4. 在所选运行时上执行自有桌面验收和共享服务生命周期检查,再更新源码准备和打包。检查通过后删除被替代的实现与依赖。此 Windows 运行时改动不扩展到共享 `cua` API 或 macOS 提供方。 + +当前桌面验收发现远程桌面客户端会在选定编辑器消费前预读剪贴板。待验证的修复会确认请求窗口所属进程,并为其他读取方继续延迟提供该格式。未携带 HWND 打开剪贴板的读取方无法归属,将超时。修订后的原生二进制已通过交叉编译,但本机 Smart App Control 阻止了它执行。分支交由用户在已获准的签名构建或测试环境中完成 Windows 验收。不能把此前的验收结果视为对该二进制的验证。 diff --git a/packages/experimental/cua-windows/native/capture-probe/app.manifest b/packages/experimental/cua-windows/native/capture-probe/app.manifest new file mode 100644 index 0000000000..64eb2db51c --- /dev/null +++ b/packages/experimental/cua-windows/native/capture-probe/app.manifest @@ -0,0 +1,12 @@ + + + + + + + + + PerMonitorV2 + + + diff --git a/packages/experimental/cua-windows/native/capture-probe/run.ps1 b/packages/experimental/cua-windows/native/capture-probe/run.ps1 new file mode 100644 index 0000000000..4edba996d1 --- /dev/null +++ b/packages/experimental/cua-windows/native/capture-probe/run.ps1 @@ -0,0 +1,28 @@ +# Compile and run a private capture experiment using only the installed .NET Framework. +param( + [long]$WindowHandle = 0, + [string]$OutputDirectory = (Join-Path $env:TEMP ("dsh-capture-" + [guid]::NewGuid().ToString("N"))) +) +$ErrorActionPreference = "Stop" +$framework = Join-Path $env:WINDIR "Microsoft.NET\Framework64\v4.0.30319" +$build = Join-Path $PSScriptRoot ("..\..\.probe-build-" + [guid]::NewGuid().ToString("N")) +New-Item -ItemType Directory -Path $build | Out-Null +try { + $executable = Join-Path $build "CaptureProbe.exe" + $compilerArguments = @("/nologo", "/target:exe", "/platform:x64", "/out:$executable", + ("/win32manifest:" + (Join-Path $PSScriptRoot "app.manifest")), + "/r:System.Drawing.dll", "/r:System.Windows.Forms.dll", "/r:System.Web.Extensions.dll", + "/r:$framework\WPF\UIAutomationClient.dll", "/r:$framework\WPF\UIAutomationTypes.dll", + "/r:$framework\WPF\WindowsBase.dll", (Join-Path $PSScriptRoot "CaptureProbe.cs")) + $compiler = Start-Process (Join-Path $framework "csc.exe") -NoNewWindow -Wait -PassThru ` + -ArgumentList ($compilerArguments | ForEach-Object { '"' + $_ + '"' }) + if ($compiler.ExitCode -ne 0) { throw "Capture probe compilation failed: $($compiler.ExitCode)" } + Copy-Item (Join-Path $PSScriptRoot "CaptureProbe.exe.config") "$executable.config" + $probeArguments = if ($WindowHandle -eq 0) { @("--demo", $OutputDirectory) } + else { @("--compare", $WindowHandle, $OutputDirectory) } + $probe = Start-Process $executable -NoNewWindow -Wait -PassThru ` + -ArgumentList ($probeArguments | ForEach-Object { '"' + $_ + '"' }) + if ($probe.ExitCode -ne 0) { throw "Capture probe failed; inspect $OutputDirectory" } + Write-Output "Capture evidence: $OutputDirectory" +} +finally { Remove-Item -LiteralPath $build -Recurse -Force } diff --git a/packages/experimental/cua-windows/native/desktop-tests/DesktopFixture.csproj b/packages/experimental/cua-windows/native/desktop-tests/DesktopFixture.csproj new file mode 100644 index 0000000000..cb0fda00a0 --- /dev/null +++ b/packages/experimental/cua-windows/native/desktop-tests/DesktopFixture.csproj @@ -0,0 +1,13 @@ + + + Exe + net10.0-windows + true + true + enable + enable + dsh-cua-desktop-fixture + true + true + + diff --git a/packages/experimental/cua-windows/native/desktop-tests/Program.cs b/packages/experimental/cua-windows/native/desktop-tests/Program.cs new file mode 100644 index 0000000000..ed6948f482 --- /dev/null +++ b/packages/experimental/cua-windows/native/desktop-tests/Program.cs @@ -0,0 +1,95 @@ +// Private desktop fixture: commands inspect or arrange only the windows owned by this process. +using System.Runtime.InteropServices; +using System.Text.Json; +using System.Security.Cryptography; +using System.Text; + +internal sealed class FixtureForm : Form +{ + protected override bool ShowWithoutActivation => true; + internal readonly TextBox Editor = new() { Name = "editor", AccessibleName = "CUA test text", Multiline = true, Bounds = new(20, 20, 440, 100) }; + private readonly Button button = new() { Name = "submit", Text = "Record click", Bounds = new(20, 140, 180, 40) }; + private int clicks; + private readonly ToolTip tooltip = new(); + + internal FixtureForm(string title) + { + Text = title; + StartPosition = FormStartPosition.Manual; + Location = new(100, 100); + ClientSize = new(500, 300); + Controls.Add(Editor); + Controls.Add(button); + button.Click += (_, _) => clicks++; + tooltip.SetToolTip(button, "CUA hover is retained"); + } + + internal object Inspect() => new + { + text = Editor.Text, clicks, window = Handle.ToInt64(), foreground = GetForegroundWindow().ToInt64(), + cursor = new { x = Cursor.Position.X, y = Cursor.Position.Y }, + button = new { x = button.Left + button.Width / 2, y = button.Top + button.Height / 2 }, + selection = new { start = Editor.SelectionStart, length = Editor.SelectionLength }, + buttons = MouseButtons.ToString(), minimized = WindowState == FormWindowState.Minimized, visible = Visible, + }; + + protected override void Dispose(bool disposing) + { + if (disposing) tooltip.Dispose(); + base.Dispose(disposing); + } + + [DllImport("user32.dll")] private static extern nint GetForegroundWindow(); +} + +internal static class Program +{ + private static void Write(object value) { Console.WriteLine(JsonSerializer.Serialize(value)); Console.Out.Flush(); } + + [STAThread] + private static void Main() + { + Application.SetHighDpiMode(HighDpiMode.PerMonitorV2); + Application.EnableVisualStyles(); + using var form = new FixtureForm("DSH CUA owned test window"); + using var sibling = new FixtureForm("DSH CUA sibling test window"); + form.Shown += (_, _) => + { + Write(new { pid = Environment.ProcessId, state = form.Inspect() }); + _ = Task.Run(() => + { + while (Console.ReadLine() is { } command) + { + form.Invoke(() => + { + switch (command) + { + case "sibling": sibling.Show(); sibling.Activate(); sibling.Editor.Focus(); Write(sibling.Inspect()); break; + case "inspect": Write(form.Inspect()); break; + case "focus": form.Activate(); form.Editor.Focus(); Write(form.Inspect()); break; + case "minimize": form.WindowState = FormWindowState.Minimized; Write(form.Inspect()); break; + case "hide": form.Hide(); Write(form.Inspect()); break; + case "resize": form.Width += 50; Write(form.Inspect()); break; + case "clipboard-digest": + Write(new { digest = Convert.ToHexString(SHA256.HashData(Encoding.Unicode.GetBytes(Clipboard.GetText()))) }); + break; + case "close": form.Close(); break; + default: + if (command.StartsWith("allow:", StringComparison.Ordinal) && uint.TryParse(command[6..], out var pid)) + Write(new { allowed = AllowSetForegroundWindow(pid) }); + else Write(new { error = "Unknown fixture command" }); + break; + } + }); + if (command == "close") return; + } + if (!form.IsDisposed) form.BeginInvoke(form.Close); + }); + }; + Application.Run(form); + } + + [DllImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool AllowSetForegroundWindow(uint processId); +} diff --git a/packages/experimental/cua-windows/native/generate-protocol.ts b/packages/experimental/cua-windows/native/generate-protocol.ts new file mode 100644 index 0000000000..3a23f8140f --- /dev/null +++ b/packages/experimental/cua-windows/native/generate-protocol.ts @@ -0,0 +1,9 @@ +/** Generate Windows native admission from the shared CUA operation definitions. */ +import { readFile, writeFile } from 'node:fs/promises' +import { nativeProtocol } from '@deepseek-ai/dsh-cua/native-schema' + +const path = new URL('protocol.schema.json', import.meta.url) +const content = nativeProtocol().json +if (process.argv.includes('--check')) { + if (await readFile(path, 'utf8') !== content) throw new Error('Stale Windows CUA native request schema') +} else await writeFile(path, content) diff --git a/packages/experimental/cua-windows/native/packages.lock.json b/packages/experimental/cua-windows/native/packages.lock.json new file mode 100644 index 0000000000..dee2e0c44b --- /dev/null +++ b/packages/experimental/cua-windows/native/packages.lock.json @@ -0,0 +1,95 @@ +{ + "version": 1, + "dependencies": { + "net10.0-windows10.0.19041": { + "Microsoft.NET.ILLink.Tasks": { + "type": "Direct", + "requested": "[10.0.14, )", + "resolved": "10.0.14", + "contentHash": "YlTamXppEQls6DYWt7RdUuwWDb0lyw/vXCaGeQpLCpsLmfwGuCkOz/vIGgMTV7ECsJcavkCOkxZXv9s8rdAHkQ==" + }, + "Vortice.Direct3D11": { + "type": "Direct", + "requested": "[3.8.3, )", + "resolved": "3.8.3", + "contentHash": "JgFUswu2mgrSwcd0KRF2AnfeE5VbMEgcicmxPD1g2yXyomPIHbnX3wldBNHPOzzD0URC1WJ/pO1ymfi3imZwvg==", + "dependencies": { + "SharpGen.Runtime": "2.4.2-beta", + "Vortice.DXGI": "3.8.3" + } + }, + "Humanizer.Core": { + "type": "Transitive", + "resolved": "3.0.10", + "contentHash": "yZIhtw8sYuvsONzQbZxWpR60tMWYHXoo0DL6nyOqSFiU5POjBTSEyWFpTQtJEZuy+oqiYTXKXY/Mjx7KnqIQFw==" + }, + "Json.More.Net": { + "type": "Transitive", + "resolved": "3.0.1", + "contentHash": "fRctF2J2SILYG6wqP21drmeEODmCVkVQ/b3MndDu2fT1swfySyUgq7ePCk+aENGlDcIm05fyfjh9vcuqDEfv3w==" + }, + "JsonPointer.Net": { + "type": "Transitive", + "resolved": "7.0.2", + "contentHash": "oClYHv2ooeRrtPZyC9sb/Za/ie5pGhjTbNHlAyFg4XOCyU+606FdoZKS7UdaWvtsPlrF+U2w0Ja3TRvn5+spyA==", + "dependencies": { + "Humanizer.Core": "3.0.10", + "Json.More.Net": "3.0.1" + } + }, + "JsonSchema.Net": { + "type": "Transitive", + "resolved": "9.4.0", + "contentHash": "muE4nPuzbD9x5XA1mkXJNqX4mhz47oF3EY8qFLY1pyUY7lhXFKq65t/dSKIHeNSLBV17zwZuq24MD1em90rMNg==", + "dependencies": { + "JsonPointer.Net": "7.0.2" + } + }, + "SharpGen.Runtime": { + "type": "Transitive", + "resolved": "2.4.2-beta", + "contentHash": "niTtWAUov1F7wZGAlVeEvW+Tnqvg5yTmhI7rxmYu2Utoyu2TbC9tWWpUpMs0PQg5lu5svoYpCAztNjxCqMFP/w==" + }, + "SharpGen.Runtime.COM": { + "type": "Transitive", + "resolved": "2.4.2-beta", + "contentHash": "9lxDFMiepqo3lJQzMSjECCIONeCc2f3Drokgj6HtrTLZcJSftNgcLbD6/iXYj2iphkwgrZb1oLsDOZxoFZkawQ==", + "dependencies": { + "SharpGen.Runtime": "2.4.2-beta" + } + }, + "Vortice.DirectX": { + "type": "Transitive", + "resolved": "3.8.3", + "contentHash": "nKwSavv0w5rDF7prSefqAVPDcTyqrfZxKFMVfttiXPfm62VdA/1d+b3PhCZpW4xO7jXczXDwjQdWgD1zGsvM8w==", + "dependencies": { + "SharpGen.Runtime": "2.4.2-beta", + "SharpGen.Runtime.COM": "2.4.2-beta", + "Vortice.Mathematics": "2.1.0" + } + }, + "Vortice.DXGI": { + "type": "Transitive", + "resolved": "3.8.3", + "contentHash": "MbAUnTeQ6WD99ctAdrj5CQO2I7oaax0Kt2eVdWSUj0bYP9Ed0726+s7dIHe4+tqhpmINW/dcPt0mNtc72o+E0w==", + "dependencies": { + "SharpGen.Runtime": "2.4.2-beta", + "Vortice.DirectX": "3.8.3" + } + }, + "Vortice.Mathematics": { + "type": "Transitive", + "resolved": "2.1.0", + "contentHash": "KK+SjNSuKdP+zbavekubi+vaeb1Jo4k87ZF6CMkVWjr6RjJwc8peVtmgzXXDIMy4ZC3ZISyk3llY3q65ISOkBQ==" + }, + "cuaprotocol": { + "type": "Project", + "dependencies": { + "JsonSchema.Net": "[9.4.0, )" + } + } + }, + "net10.0-windows10.0.19041/win-arm64": {}, + "net10.0-windows10.0.19041/win-x64": {} + } +} \ No newline at end of file diff --git a/packages/experimental/cua-windows/native/protocol.schema.json b/packages/experimental/cua-windows/native/protocol.schema.json new file mode 100644 index 0000000000..c25c65c1e0 --- /dev/null +++ b/packages/experimental/cua-windows/native/protocol.schema.json @@ -0,0 +1,1414 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$comment": "Generated from the shared CUA operation schema. Do not edit.", + "title": "dsh-cua native request", + "description": "Host resource fields and private continuations are not model tool parameters. App handles and snapshots belong to one helper; coordinates use window-local native units.", + "oneOf": [ + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "getCapabilities" + }, + "params": { + "type": "object", + "properties": {}, + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "listApps" + }, + "params": { + "type": "object", + "properties": {}, + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "findApps" + }, + "params": { + "type": "object", + "properties": { + "query": { + "type": "string", + "minLength": 1, + "pattern": "\\S" + }, + "maxAppMatches": { + "type": "integer", + "minimum": 1, + "maximum": 1000 + } + }, + "required": [ + "query", + "maxAppMatches" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "getApp" + }, + "params": { + "type": "object", + "properties": { + "selector": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "selector" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "activate" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "appHandle" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "show" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + } + }, + "required": [ + "appHandle" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "listWindows" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "appHandle" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "getState" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "includeMenus": { + "description": "Expand menu contents; omitted or false shows menu-bar entries only.", + "type": "boolean" + }, + "details": { + "description": "Include identifiers, global native bounds and complete action names.", + "type": "boolean" + }, + "maxElements": { + "type": "integer", + "minimum": 1, + "maximum": 10000 + }, + "maxDepth": { + "type": "integer", + "minimum": 1, + "maximum": 100 + } + }, + "required": [ + "appHandle", + "maxElements", + "maxDepth" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "listActions" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "snapshotId": { + "type": "string", + "minLength": 1 + }, + "elementId": { + "type": "string", + "minLength": 1, + "description": "Opaque string defined by the platform provider, valid for at least the lifetime of one snapshot." + } + }, + "required": [ + "appHandle", + "snapshotId", + "elementId" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "performAction" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "snapshotId": { + "type": "string", + "minLength": 1 + }, + "elementId": { + "type": "string", + "minLength": 1, + "description": "Opaque string defined by the platform provider, valid for at least the lifetime of one snapshot." + }, + "action": { + "type": "string", + "minLength": 1 + }, + "argument": { + "$ref": "#/$defs/__schema0" + } + }, + "required": [ + "appHandle", + "snapshotId", + "elementId", + "action" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false, + "$defs": { + "__schema0": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "boolean" + }, + { + "type": "null" + }, + { + "type": "array", + "items": { + "$ref": "#/$defs/__schema0" + } + }, + { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + } + ] + } + }, + "$id": "urn:deepseek-harness:cua:request:performAction" + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "invoke" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "snapshotId": { + "type": "string", + "minLength": 1 + }, + "elementId": { + "type": "string", + "minLength": 1, + "description": "Opaque string defined by the platform provider, valid for at least the lifetime of one snapshot." + } + }, + "required": [ + "appHandle", + "snapshotId", + "elementId" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "mouseMove" + }, + "params": { + "anyOf": [ + { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "snapshotId": { + "type": "string", + "minLength": 1 + }, + "elementId": { + "type": "string", + "minLength": 1, + "description": "Opaque string defined by the platform provider, valid for at least the lifetime of one snapshot." + } + }, + "required": [ + "appHandle", + "snapshotId", + "elementId" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "snapshotId": { + "type": "string", + "minLength": 1 + }, + "x": { + "type": "number", + "minimum": 0 + }, + "y": { + "type": "number", + "minimum": 0 + } + }, + "required": [ + "appHandle", + "windowId", + "x", + "y" + ], + "additionalProperties": false + } + ] + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "click" + }, + "params": { + "anyOf": [ + { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "snapshotId": { + "type": "string", + "minLength": 1 + }, + "elementId": { + "type": "string", + "minLength": 1, + "description": "Opaque string defined by the platform provider, valid for at least the lifetime of one snapshot." + }, + "mouseButton": { + "type": "string", + "enum": [ + "left", + "right", + "middle" + ] + }, + "modifiers": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "command", + "control", + "option", + "shift", + "fn" + ] + } + }, + "clickCount": { + "anyOf": [ + { + "type": "number", + "const": 1 + }, + { + "type": "number", + "const": 2 + } + ] + }, + "holdMs": { + "description": "Milliseconds between each mouse press and release; omitted for an ordinary click.", + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "appHandle", + "snapshotId", + "elementId" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "snapshotId": { + "type": "string", + "minLength": 1 + }, + "x": { + "type": "number", + "minimum": 0 + }, + "y": { + "type": "number", + "minimum": 0 + }, + "mouseButton": { + "type": "string", + "enum": [ + "left", + "right", + "middle" + ] + }, + "modifiers": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "command", + "control", + "option", + "shift", + "fn" + ] + } + }, + "clickCount": { + "anyOf": [ + { + "type": "number", + "const": 1 + }, + { + "type": "number", + "const": 2 + } + ] + }, + "holdMs": { + "description": "Milliseconds between each mouse press and release; omitted for an ordinary click.", + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "appHandle", + "windowId", + "x", + "y" + ], + "additionalProperties": false + } + ] + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "setValue" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "snapshotId": { + "type": "string", + "minLength": 1 + }, + "elementId": { + "type": "string", + "minLength": 1, + "description": "Opaque string defined by the platform provider, valid for at least the lifetime of one snapshot." + }, + "value": { + "$ref": "#/$defs/__schema0" + } + }, + "required": [ + "appHandle", + "snapshotId", + "elementId", + "value" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false, + "$defs": { + "__schema0": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "boolean" + }, + { + "type": "null" + }, + { + "type": "array", + "items": { + "$ref": "#/$defs/__schema0" + } + }, + { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + } + ] + } + }, + "$id": "urn:deepseek-harness:cua:request:setValue" + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "selectText" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "snapshotId": { + "type": "string", + "minLength": 1 + }, + "elementId": { + "type": "string", + "minLength": 1, + "description": "Opaque string defined by the platform provider, valid for at least the lifetime of one snapshot." + }, + "text": { + "type": "string", + "minLength": 1 + }, + "prefix": { + "type": "string" + }, + "suffix": { + "type": "string" + }, + "selectionType": { + "type": "string", + "enum": [ + "text", + "cursor_before", + "cursor_after" + ] + } + }, + "required": [ + "appHandle", + "snapshotId", + "elementId", + "text" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "typeText" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "text": { + "type": "string" + } + }, + "required": [ + "appHandle", + "text" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "paste" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "text": { + "type": "string" + }, + "format": { + "type": "string", + "enum": [ + "text", + "html" + ] + }, + "maxClipboardBytes": { + "type": "integer", + "minimum": 1024, + "maximum": 9007199254740991 + }, + "pasteReadTimeoutMs": { + "type": "integer", + "minimum": 1, + "maximum": 2147483647 + }, + "maxElements": { + "type": "integer", + "minimum": 1, + "maximum": 10000 + }, + "maxDepth": { + "type": "integer", + "minimum": 1, + "maximum": 100 + } + }, + "required": [ + "appHandle", + "text", + "maxClipboardBytes", + "pasteReadTimeoutMs", + "maxElements", + "maxDepth" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "pressKey" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "key": { + "type": "string", + "minLength": 1 + }, + "modifiers": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": [ + "appHandle", + "key" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "sendKeyEvent" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "key": { + "type": "string", + "minLength": 1 + }, + "direction": { + "type": "string", + "enum": [ + "down", + "up" + ] + } + }, + "required": [ + "appHandle", + "key", + "direction" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "scroll" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "snapshotId": { + "type": "string", + "minLength": 1 + }, + "x": { + "type": "number", + "minimum": 0 + }, + "y": { + "type": "number", + "minimum": 0 + }, + "deltaLinesX": { + "type": "integer", + "minimum": -10, + "maximum": 10 + }, + "deltaLinesY": { + "type": "integer", + "minimum": -10, + "maximum": 10 + } + }, + "required": [ + "appHandle", + "windowId", + "x", + "y", + "deltaLinesX", + "deltaLinesY" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "drag" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "mouseButton": { + "type": "string", + "enum": [ + "left", + "right", + "middle" + ] + }, + "modifiers": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "command", + "control", + "option", + "shift", + "fn" + ] + } + }, + "snapshotId": { + "type": "string", + "minLength": 1 + }, + "fromX": { + "type": "number", + "minimum": 0 + }, + "fromY": { + "type": "number", + "minimum": 0 + }, + "toX": { + "type": "number", + "minimum": 0 + }, + "toY": { + "type": "number", + "minimum": 0 + }, + "durationMs": { + "type": "integer", + "minimum": 1, + "maximum": 5000 + }, + "steps": { + "type": "integer", + "minimum": 1, + "maximum": 240 + } + }, + "required": [ + "appHandle", + "windowId", + "fromX", + "fromY", + "toX", + "toY", + "durationMs", + "steps" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "screenshot" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + } + }, + "required": [ + "appHandle", + "windowId" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "launchApp" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "appHandle" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "permissionStatus" + }, + "params": { + "type": "object", + "properties": {}, + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "applicationIcons" + }, + "params": { + "type": "object", + "properties": { + "paths": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + } + }, + "required": [ + "paths" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "requestPermission" + }, + "params": { + "type": "object", + "properties": { + "permission": { + "type": "string", + "enum": [ + "accessibility", + "screenRecording" + ] + } + }, + "required": [ + "permission" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "openPermissionSettings" + }, + "params": { + "type": "object", + "properties": { + "permission": { + "type": "string", + "enum": [ + "accessibility", + "screenRecording" + ] + } + }, + "required": [ + "permission" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + } + ] +} diff --git a/packages/experimental/cua-windows/native/protocol/AccessibilityText.cs b/packages/experimental/cua-windows/native/protocol/AccessibilityText.cs new file mode 100644 index 0000000000..35c6acdb75 --- /dev/null +++ b/packages/experimental/cua-windows/native/protocol/AccessibilityText.cs @@ -0,0 +1,74 @@ +// Formatting owns no native references or snapshot indices. +using System.Globalization; +using System.Text; +using System.Text.Json; + +namespace DeepSeek.Cua.Protocol; + +public sealed record AccessibilityNode +{ + public required string Role { get; init; } + public string Name { get; init; } = ""; + public string? Subrole { get; init; } + public string? Help { get; init; } + public string? Identifier { get; init; } + public string? Value { get; init; } + public string? Placeholder { get; init; } + public bool HasValue { get; init; } + public bool? Enabled { get; init; } + public bool? Focused { get; init; } + public bool? Selected { get; init; } + public bool? Expanded { get; init; } + public string? ValueWritable { get; init; } + public bool? SelectionWritable { get; init; } + public bool HasSelection { get; init; } + public TextMatch? Selection { get; init; } + public string? SelectedText { get; init; } + public string[] Actions { get; init; } = []; + public (double X, double Y, double Width, double Height)? Bounds { get; init; } +} + +public static class AccessibilityText +{ + private static string Quote(string value) => JsonSerializer.Serialize(value, WireJson.Options); + + public static bool Retain(AccessibilityNode node) => node.Role is not ("AXGroup" or "AXScrollArea") + || node.Name.Length != 0 || !string.IsNullOrEmpty(node.Help) || node.HasValue || node.Actions.Length != 0 + || node.Enabled == false || node.Focused == true || node.Selected.HasValue || node.Expanded.HasValue; + + public static string Format(AccessibilityNode node, int? index, bool details) + { + var text = new StringBuilder("- "); + if (index is { } number) text.Append('[').Append(number).Append("] "); + text.Append(node.Role); + if (node.Subrole is { Length: > 0 } subrole) text.Append(" subrole=").Append(Quote(subrole)); + if (node.Enabled == false) text.Append(" disabled"); + if (node.Focused == true) text.Append(" focused"); + if (node.Selected is { } selected) text.Append(" selected=").Append(selected ? "true" : "false"); + if (node.Expanded is { } expanded) text.Append(" expanded=").Append(expanded ? "true" : "false"); + if (node.ValueWritable is { } writable) text.Append(" valueWritable=").Append(writable); + if (node.SelectionWritable is { } selectionWritable) text.Append(" selectionWritable=").Append(selectionWritable ? "true" : "false"); + if (node.Name.Length != 0) text.Append(' ').Append(Quote(node.Name)); + if (node.HasValue) text.Append(" = ").Append(node.Value is { } value ? Quote(value) : "unavailable"); + if (node.Placeholder is { } placeholder) text.Append(" placeholder=").Append(Quote(placeholder)); + if (node.Help is { Length: > 0 } help && help != node.Name) text.Append(" help=").Append(Quote(help)); + if (node.HasSelection) + { + if (node.Selection is { } range && node.Value is { } value && range.Start >= 0 && range.Length >= 0 + && range.Start <= value.Length - range.Length) + text.Append(" selection=[").Append(range.Start).Append(',').Append(range.Length).Append(']'); + else text.Append(" selection=unavailable"); + if (node.SelectedText is { Length: > 0 } selectedText) text.Append(" selectedText=").Append(Quote(selectedText)); + } + var actions = details ? node.Actions : node.Actions.Where(action => action is not ("Press" or "Pick" or "ScrollToVisible")).ToArray(); + if (actions.Length != 0) text.Append(" actions=[").Append(string.Join(", ", actions.Select(Quote))).Append(']'); + if (details) + { + if (!string.IsNullOrEmpty(node.Identifier)) text.Append(" id=").Append(Quote(node.Identifier)); + if (index.HasValue && node.Bounds is { } bounds) + text.Append(" bounds=[").Append(string.Join(',', new[] { bounds.X, bounds.Y, bounds.Width, bounds.Height } + .Select(number => number.ToString("G", CultureInfo.InvariantCulture)))).Append(']'); + } + return text.ToString(); + } +} diff --git a/packages/experimental/cua-windows/native/protocol/CuaProtocol.csproj b/packages/experimental/cua-windows/native/protocol/CuaProtocol.csproj new file mode 100644 index 0000000000..353ac1afa7 --- /dev/null +++ b/packages/experimental/cua-windows/native/protocol/CuaProtocol.csproj @@ -0,0 +1,14 @@ + + + net10.0 + enable + enable + true + win-x64;win-arm64 + false + + + + + + diff --git a/packages/experimental/cua-windows/native/protocol/KeyChord.cs b/packages/experimental/cua-windows/native/protocol/KeyChord.cs new file mode 100644 index 0000000000..74d375ab35 --- /dev/null +++ b/packages/experimental/cua-windows/native/protocol/KeyChord.cs @@ -0,0 +1,25 @@ +namespace DeepSeek.Cua.Protocol; + +public sealed record KeyChord(string Key, string[] Modifiers) +{ + public static KeyChord Parse(string text, IEnumerable extra) + { + if (text.Length == 0) throw new NativeFailure("INVALID_ARGUMENT", "A key name is required"); + var plus = text == "+" || text.EndsWith("++", StringComparison.Ordinal); + var parts = plus ? text[..^1].TrimEnd('+').Split('+', StringSplitOptions.RemoveEmptyEntries) : text.Split('+'); + var key = plus ? "+" : parts[^1]; + if (key.Length == 0) throw new NativeFailure("INVALID_ARGUMENT", "A key chord must end with a key"); + var modifiers = (plus ? parts : parts[..^1]).Concat(extra).Select(NormalizeModifier).Distinct().ToArray(); + return new(key, modifiers); + } + + public static string NormalizeModifier(string value) => value.ToLowerInvariant() switch + { + "control" or "ctrl" => "control", + "shift" => "shift", + "option" or "alt" => "option", + "command" or "cmd" or "meta" or "win" or "windows" => "command", + "fn" => throw new NativeFailure("UNSUPPORTED", "Windows has no general Fn-key injection; use an available application action"), + _ => throw new NativeFailure("INVALID_ARGUMENT", "Unknown key modifier"), + }; +} diff --git a/packages/experimental/cua-windows/native/protocol/NativeControlFrame.cs b/packages/experimental/cua-windows/native/protocol/NativeControlFrame.cs new file mode 100644 index 0000000000..fe3fe18efc --- /dev/null +++ b/packages/experimental/cua-windows/native/protocol/NativeControlFrame.cs @@ -0,0 +1,23 @@ +// Connection controls never enter the model operation schema. +using System.Text.Json; + +namespace DeepSeek.Cua.Protocol; + +public enum NativeControl { Close, Cancel, CompletedCancel } + +/// Cancellation matches the latest request; a late cancellation after its completion is a no-op. +public static class NativeControlFrame +{ + public static NativeControl Parse(JsonElement value, string? requestId, bool completed = false) + { + if (value.ValueKind != JsonValueKind.Object || !value.TryGetProperty("type", out var type) + || type.ValueKind != JsonValueKind.String) + throw new NativeFailure("INVALID_REQUEST", "Expected a native connection control"); + if (type.GetString() == "close" && value.EnumerateObject().Count() == 1) return NativeControl.Close; + if (type.GetString() == "cancel" && value.EnumerateObject().Count() == 2 + && value.TryGetProperty("id", out var id) && id.ValueKind == JsonValueKind.String + && !string.IsNullOrEmpty(requestId) && id.GetString() == requestId) + return completed ? NativeControl.CompletedCancel : NativeControl.Cancel; + throw new NativeFailure("INVALID_REQUEST", "Cancellation requires a matching request; close accepts no fields"); + } +} diff --git a/packages/experimental/cua-windows/native/protocol/NativeRequest.cs b/packages/experimental/cua-windows/native/protocol/NativeRequest.cs new file mode 100644 index 0000000000..8cdd6a3293 --- /dev/null +++ b/packages/experimental/cua-windows/native/protocol/NativeRequest.cs @@ -0,0 +1,99 @@ +// Strict JSONL admission shares the TypeScript operation schema with the macOS provider. +using System.Text; +using System.Text.Encodings.Web; +using System.Text.Json; +using Json.Schema; + +namespace DeepSeek.Cua.Protocol; + +/// A native refusal whose code remains visible through the shared CUA client. +public sealed class NativeFailure(string code, string message) : Exception(message) +{ + public string Code { get; } = code; +} + +/// Wire encoding preserves readable task text and always emits one JSON value per line. +public static class WireJson +{ + public static readonly JsonSerializerOptions Options = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + }; + public static readonly UTF8Encoding Utf8 = new(false, true); + + public static JsonElement Parse(string text) + { + using var document = JsonDocument.Parse(text); + RejectDuplicates(document.RootElement); + return document.RootElement.Clone(); + } + + private static void RejectDuplicates(JsonElement value) + { + if (value.ValueKind == JsonValueKind.Object) + { + var names = new HashSet(StringComparer.Ordinal); + foreach (var property in value.EnumerateObject()) + { + if (!names.Add(property.Name)) throw new NativeFailure("INVALID_REQUEST", "Repeated JSON property"); + RejectDuplicates(property.Value); + } + } + else if (value.ValueKind == JsonValueKind.Array) + foreach (var item in value.EnumerateArray()) RejectDuplicates(item); + } +} + +/// Validated operation parameters. Resource fields are supplied only by the Host. +public sealed record NativeRequest(string Id, string Method, JsonElement Params) +{ + private static readonly JsonSchema Schema = LoadSchema(); + + private static JsonSchema LoadSchema() + { + using var stream = typeof(NativeRequest).Assembly.GetManifestResourceStream("DeepSeek.Cua.NativeRequestSchema.json") + ?? throw new InvalidOperationException("The native request schema is missing"); + using var reader = new StreamReader(stream, WireJson.Utf8); + return JsonSchema.FromText(reader.ReadToEnd()); + } + + public static NativeRequest Parse(JsonElement value) + { + if (!Schema.Evaluate(value, new EvaluationOptions { OutputFormat = OutputFormat.Flag }).IsValid) + throw new NativeFailure("INVALID_ARGUMENT", "The request does not match the CUA operation schema"); + return new(value.GetProperty("id").GetString()!, value.GetProperty("method").GetString()!, value.GetProperty("params")); + } +} + +/// Reads bounded UTF-8 frames without allowing an unterminated line to grow without limit. +public sealed class FrameReader(Stream stream) +{ + private readonly byte[] buffer = new byte[4096]; + private int start; + private int end; + + public async Task ReadAsync(int maximumBytes, CancellationToken cancellation) + { + using var line = new MemoryStream(); + while (true) + { + if (start == end) + { + end = await stream.ReadAsync(buffer, cancellation); + start = 0; + if (end == 0) + { + if (line.Length != 0) throw new NativeFailure("INVALID_REQUEST", "Native input ended inside a frame"); + return null; + } + } + var newline = Array.IndexOf(buffer, (byte)'\n', start, end - start); + var count = (newline < 0 ? end : newline + 1) - start; + if (line.Length + count > maximumBytes) throw new NativeFailure("NATIVE_REQUEST_LIMIT", "Request exceeded its byte limit"); + line.Write(buffer, start, count); + start += count; + if (newline >= 0) return WireJson.Utf8.GetString(line.GetBuffer(), 0, checked((int)line.Length - 1)); + } + } +} diff --git a/packages/experimental/cua-windows/native/protocol/TextSelection.cs b/packages/experimental/cua-windows/native/protocol/TextSelection.cs new file mode 100644 index 0000000000..251474b5ab --- /dev/null +++ b/packages/experimental/cua-windows/native/protocol/TextSelection.cs @@ -0,0 +1,49 @@ +// Literal selection and CF_HTML encoding are independent of Windows UI Automation. +using System.Globalization; +using System.Text; + +namespace DeepSeek.Cua.Protocol; + +public readonly record struct TextMatch(int Start, int Length); + +public static class TextSelection +{ + /// Find one literal UTF-16 range, with immediately adjacent optional context. + public static TextMatch Find(string value, string text, string? prefix, string? suffix) + { + if (text.Length == 0) throw new NativeFailure("INVALID_ARGUMENT", "Selection text must not be empty"); + TextMatch? selected = null; + for (var offset = 0; offset <= value.Length - text.Length;) + { + var start = value.IndexOf(text, offset, StringComparison.Ordinal); + if (start < 0) break; + var end = start + text.Length; + var before = prefix is null || (start >= prefix.Length && value.AsSpan(start - prefix.Length, prefix.Length).SequenceEqual(prefix)); + var after = suffix is null || (end + suffix.Length <= value.Length && value.AsSpan(end, suffix.Length).SequenceEqual(suffix)); + if (before && after) + { + if (selected is not null) throw new NativeFailure("AMBIGUOUS_TEXT", "Add immediately adjacent prefix or suffix text"); + selected = new(start, text.Length); + } + offset = start + 1; + } + return selected ?? throw new NativeFailure("TEXT_NOT_FOUND", "Read fresh state before selecting text"); + } +} + +public static class HtmlClipboard +{ + /// CF_HTML offsets count UTF-8 bytes, independently of UTF-16 selection offsets. + public static byte[] Encode(string fragment) + { + const string before = ""; + const string after = ""; + const string template = "Version:1.0\r\nStartHTML:{0:D10}\r\nEndHTML:{1:D10}\r\nStartFragment:{2:D10}\r\nEndFragment:{3:D10}\r\n"; + var headerSize = Encoding.UTF8.GetByteCount(string.Format(CultureInfo.InvariantCulture, template, 0, 0, 0, 0)); + var start = headerSize + Encoding.UTF8.GetByteCount(before); + var end = start + Encoding.UTF8.GetByteCount(fragment); + var header = string.Format(CultureInfo.InvariantCulture, template, headerSize, + end + Encoding.UTF8.GetByteCount(after), start, end); + return Encoding.UTF8.GetBytes(header + before + fragment + after + "\0"); + } +} diff --git a/packages/experimental/cua-windows/native/protocol/packages.lock.json b/packages/experimental/cua-windows/native/protocol/packages.lock.json new file mode 100644 index 0000000000..4118720b93 --- /dev/null +++ b/packages/experimental/cua-windows/native/protocol/packages.lock.json @@ -0,0 +1,37 @@ +{ + "version": 1, + "dependencies": { + "net10.0": { + "JsonSchema.Net": { + "type": "Direct", + "requested": "[9.4.0, )", + "resolved": "9.4.0", + "contentHash": "muE4nPuzbD9x5XA1mkXJNqX4mhz47oF3EY8qFLY1pyUY7lhXFKq65t/dSKIHeNSLBV17zwZuq24MD1em90rMNg==", + "dependencies": { + "JsonPointer.Net": "7.0.2" + } + }, + "Humanizer.Core": { + "type": "Transitive", + "resolved": "3.0.10", + "contentHash": "yZIhtw8sYuvsONzQbZxWpR60tMWYHXoo0DL6nyOqSFiU5POjBTSEyWFpTQtJEZuy+oqiYTXKXY/Mjx7KnqIQFw==" + }, + "Json.More.Net": { + "type": "Transitive", + "resolved": "3.0.1", + "contentHash": "fRctF2J2SILYG6wqP21drmeEODmCVkVQ/b3MndDu2fT1swfySyUgq7ePCk+aENGlDcIm05fyfjh9vcuqDEfv3w==" + }, + "JsonPointer.Net": { + "type": "Transitive", + "resolved": "7.0.2", + "contentHash": "oClYHv2ooeRrtPZyC9sb/Za/ie5pGhjTbNHlAyFg4XOCyU+606FdoZKS7UdaWvtsPlrF+U2w0Ja3TRvn5+spyA==", + "dependencies": { + "Humanizer.Core": "3.0.10", + "Json.More.Net": "3.0.1" + } + } + }, + "net10.0/win-arm64": {}, + "net10.0/win-x64": {} + } +} diff --git a/packages/experimental/cua-windows/native/src/Accessibility.cs b/packages/experimental/cua-windows/native/src/Accessibility.cs new file mode 100644 index 0000000000..f1068643f2 --- /dev/null +++ b/packages/experimental/cua-windows/native/src/Accessibility.cs @@ -0,0 +1,245 @@ +// One traversal owns both the disclosed indices and their retained UI Automation elements. +using System.Globalization; +using System.Text; +using System.Windows.Automation; +using System.Windows.Automation.Text; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal sealed record ElementReference(AutomationElement Element, WindowState Window); +internal sealed record Snapshot(string Id, uint Scope, WindowState[] Windows, IReadOnlyDictionary Elements); + +internal static class Accessibility +{ + private static readonly AutomationProperty[] Properties = [ + AutomationElement.ControlTypeProperty, AutomationElement.NameProperty, AutomationElement.HelpTextProperty, + AutomationElement.AutomationIdProperty, AutomationElement.ClassNameProperty, AutomationElement.IsEnabledProperty, + AutomationElement.HasKeyboardFocusProperty, AutomationElement.IsKeyboardFocusableProperty, AutomationElement.IsPasswordProperty, + AutomationElement.BoundingRectangleProperty, AutomationElement.IsInvokePatternAvailableProperty, + AutomationElement.IsValuePatternAvailableProperty, AutomationElement.IsRangeValuePatternAvailableProperty, + AutomationElement.IsTextPatternAvailableProperty, AutomationElement.IsSelectionItemPatternAvailableProperty, + AutomationElement.IsTogglePatternAvailableProperty, AutomationElement.IsExpandCollapsePatternAvailableProperty, + AutomationElement.IsScrollItemPatternAvailableProperty, ValuePattern.ValueProperty, ValuePattern.IsReadOnlyProperty, + RangeValuePattern.ValueProperty, RangeValuePattern.IsReadOnlyProperty, SelectionItemPattern.IsSelectedProperty, + TogglePattern.ToggleStateProperty, ExpandCollapsePattern.ExpandCollapseStateProperty, + ]; + + internal static object State(AppState app, uint selected, int maximumElements, int maximumDepth, + bool includeMenus, bool details, RequestContext context) + { + var all = Windows.Refresh(app, context); + var targets = new[] { all.SingleOrDefault(window => window.Id == selected) + ?? throw new NativeFailure("WINDOW_CHANGED", "Select a current window") }; + var rows = new List { "AX scope=window offsets=UTF-16" }; + var elements = new Dictionary(); + var observations = new List<(WindowState Window, WindowGeometry Geometry)>(); + var visited = new HashSet(StringComparer.Ordinal); + var cache = new CacheRequest { AutomationElementMode = AutomationElementMode.Full, TreeScope = TreeScope.Element }; + foreach (var property in Properties) cache.Add(property); + var truncated = false; + var count = 0; + var nextIndex = 0; + var bytes = Encoding.UTF8.GetByteCount(rows[0]); + void Add(string row) + { + bytes += Encoding.UTF8.GetByteCount(row) + 1; + if (bytes > context.Config.MaxResponseBytes) throw new NativeFailure("NATIVE_RESPONSE_LIMIT", "Accessibility text exceeds the response limit; select a narrower window or reduce traversal limits"); + rows.Add(row); + } + foreach (var window in targets) + { + if (count >= maximumElements) { truncated = true; break; } + var geometry = window.Geometry(app, context); + try + { + var root = context.Ax(() => AutomationElement.FromHandle(window.Handle).GetUpdatedCache(cache)); + Walk(root, window, geometry, 0, 0); + } + catch (ElementNotAvailableException) { throw new NativeFailure("STALE_SNAPSHOT", "An accessibility element disappeared; read fresh state without repeating input"); } + var after = window.Geometry(app, context); + if (after.Pixels.Width != geometry.Pixels.Width || after.Pixels.Height != geometry.Pixels.Height || after.Dpi != geometry.Dpi) + throw new NativeFailure("WINDOW_CHANGED", "The window changed during AX observation; read fresh state"); + observations.Add((window, after)); + } + if (truncated) Add($"[truncated: maxElements={maximumElements}, maxDepth={maximumDepth}]"); + DesktopSession.RequireInteractive(); + var scope = selected; + var snapshot = new Snapshot(Guid.NewGuid().ToString("N"), scope, targets, elements); + var result = new + { + appHandle = app.Handle, pid = 4, windowId = selected, + focusedWindowId = (uint?)Windows.Focused(app, all)?.Id, + snapshotId = snapshot.Id, tree = string.Join('\n', rows), windows = all.Select(window => window.Describe(app, context)).ToArray(), truncated, + }; + context.Check(); + app.Snapshots[scope] = snapshot; + foreach (var observation in observations) observation.Window.Observe(observation.Geometry); + return result; + + void Walk(AutomationElement element, WindowState window, WindowGeometry geometry, int depth, int indent) + { + context.Check(); + if (count >= maximumElements || depth >= maximumDepth) { truncated = true; return; } + count++; + if (!visited.Add(string.Join(',', context.Ax(element.GetRuntimeId)))) return; + var node = Read(element, window, geometry, context); + var retained = AccessibilityText.Retain(node); + if (retained) + { + int? index = null; + if (node.Enabled != false && (node.Actions.Length != 0 || node.ValueWritable == "true" || node.SelectionWritable == true)) + { + index = nextIndex++; + elements.Add(index.Value, new(element, window)); + } + Add(new string(' ', indent * 2) + AccessibilityText.Format(node, index, details)); + } + if (!includeMenus && node.Role == "AXMenu") + { + Add(new string(' ', (indent + 1) * 2) + "[menu contents omitted; includeMenus:true]"); + return; + } + var first = context.Ax(() => TreeWalker.ControlViewWalker.GetFirstChild(element, cache)); + if (first is not null && depth + 1 >= maximumDepth) { truncated = true; return; } + for (var child = first; child is not null; + child = context.Ax(() => TreeWalker.ControlViewWalker.GetNextSibling(child, cache))) + { + Walk(child, window, geometry, depth + 1, indent + (retained ? 1 : 0)); + if (count >= maximumElements) + { + if (context.Ax(() => TreeWalker.ControlViewWalker.GetNextSibling(child, cache)) is not null) truncated = true; + break; + } + } + } + } + + private static object Property(AutomationElement element, AutomationProperty property) => element.GetCachedPropertyValue(property, true); + private static bool Flag(AutomationElement element, AutomationProperty property) => Property(element, property) is true; + private static string Text(AutomationElement element, AutomationProperty property) => Property(element, property) as string ?? ""; + + private static AccessibilityNode Read(AutomationElement element, WindowState window, WindowGeometry geometry, RequestContext context) + { + var type = Property(element, AutomationElement.ControlTypeProperty) as ControlType ?? ControlType.Custom; + var actions = new List(); + if (Flag(element, AutomationElement.IsInvokePatternAvailableProperty)) actions.Add("Press"); + if (Flag(element, AutomationElement.IsTogglePatternAvailableProperty)) actions.Add("Toggle"); + if (Flag(element, AutomationElement.IsSelectionItemPatternAvailableProperty)) actions.Add("Pick"); + if (Flag(element, AutomationElement.IsExpandCollapsePatternAvailableProperty)) { actions.Add("Expand"); actions.Add("Collapse"); } + if (Flag(element, AutomationElement.IsScrollItemPatternAvailableProperty)) actions.Add("ScrollToVisible"); + if (Flag(element, AutomationElement.IsKeyboardFocusableProperty)) actions.Add("Focus"); + if (type == ControlType.Window) actions.Add("Raise"); + var password = Flag(element, AutomationElement.IsPasswordProperty); + string? value = null; + var hasValue = false; + string? writable = type == ControlType.Edit || type == ControlType.Document ? "unknown" : null; + if (Flag(element, AutomationElement.IsValuePatternAvailableProperty)) + { + hasValue = true; + if (!password) value = Property(element, ValuePattern.ValueProperty) as string; + writable = Property(element, ValuePattern.IsReadOnlyProperty) is bool readOnly ? readOnly ? "false" : "true" : "unknown"; + } + else if (Flag(element, AutomationElement.IsRangeValuePatternAvailableProperty)) + { + hasValue = true; + if (Property(element, RangeValuePattern.ValueProperty) is double number) value = number.ToString("G", CultureInfo.InvariantCulture); + writable = Property(element, RangeValuePattern.IsReadOnlyProperty) is bool readOnly ? readOnly ? "false" : "true" : "unknown"; + } + else if (Property(element, TogglePattern.ToggleStateProperty) is ToggleState toggle) + { + hasValue = true; value = toggle == ToggleState.Indeterminate ? "mixed" : toggle == ToggleState.On ? "true" : "false"; + } + bool? selectionWritable = null; + var hasSelection = false; + TextMatch? selection = null; + string? selectedText = null; + if (!password && Flag(element, AutomationElement.IsTextPatternAvailableProperty)) + { + var text = context.Ax(() => (TextPattern)element.GetCurrentPattern(TextPattern.Pattern)); + var document = context.Ax(() => text.DocumentRange); + value = context.Ax(() => document.GetText(context.Config.MaxResponseBytes)); + hasValue = true; + selectionWritable = context.Ax(() => text.SupportedTextSelection) != SupportedTextSelection.None; + hasSelection = true; + var ranges = context.Ax(text.GetSelection); + if (ranges.Length == 1) + { + var prefix = context.Ax(document.Clone); + context.Ax(() => { prefix.MoveEndpointByRange(TextPatternRangeEndpoint.End, ranges[0], TextPatternRangeEndpoint.Start); return true; }); + var start = context.Ax(() => prefix.GetText(context.Config.MaxResponseBytes)).Length; + selectedText = context.Ax(() => ranges[0].GetText(context.Config.MaxResponseBytes)); + selection = new(start, selectedText.Length); + } + } + var role = Role(type, password, value); + var bounds = Property(element, AutomationElement.BoundingRectangleProperty) is System.Windows.Rect rectangle && !rectangle.IsEmpty + ? ((double, double, double, double)?)(rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height) : null; + var expanded = Property(element, ExpandCollapsePattern.ExpandCollapseStateProperty) is ExpandCollapseState state + ? state == ExpandCollapseState.Expanded ? true : state == ExpandCollapseState.Collapsed ? false : (bool?)null : null; + return new() + { + Role = role, Name = Text(element, AutomationElement.NameProperty), Help = Text(element, AutomationElement.HelpTextProperty), + Identifier = Text(element, AutomationElement.AutomationIdProperty), Subrole = type == ControlType.Custom ? Text(element, AutomationElement.ClassNameProperty) : null, + Value = value, HasValue = hasValue, ValueWritable = writable, + Enabled = Property(element, AutomationElement.IsEnabledProperty) as bool?, Focused = Property(element, AutomationElement.HasKeyboardFocusProperty) as bool?, + Selected = Property(element, SelectionItemPattern.IsSelectedProperty) as bool?, Expanded = expanded, + HasSelection = hasSelection, Selection = selection, SelectedText = selectedText, SelectionWritable = selectionWritable, + Actions = actions.ToArray(), Bounds = bounds, + }; + } + + private static string Role(ControlType type, bool password, string? value) + { + if (password) return "AXSecureTextField"; + if (type == ControlType.Edit) return value?.Contains('\n') == true ? "AXTextArea" : "AXTextField"; + if (type == ControlType.Document) return "AXTextArea"; + if (type == ControlType.Button) return "AXButton"; + if (type == ControlType.CheckBox) return "AXCheckBox"; + if (type == ControlType.RadioButton) return "AXRadioButton"; + if (type == ControlType.Text) return "AXStaticText"; + if (type == ControlType.Window) return "AXWindow"; + if (type == ControlType.MenuBar) return "AXMenuBar"; + if (type == ControlType.Menu) return "AXMenu"; + if (type == ControlType.MenuItem) return "AXMenuItem"; + if (type == ControlType.ComboBox) return "AXComboBox"; + if (type == ControlType.List) return "AXList"; + if (type == ControlType.ListItem) return "AXRow"; + if (type == ControlType.Tree) return "AXOutline"; + if (type == ControlType.TreeItem) return "AXRow"; + if (type == ControlType.Tab) return "AXTabGroup"; + if (type == ControlType.TabItem) return "AXRadioButton"; + if (type == ControlType.Slider) return "AXSlider"; + if (type == ControlType.Spinner) return "AXIncrementor"; + if (type == ControlType.ScrollBar) return "AXScrollBar"; + if (type == ControlType.Image) return "AXImage"; + if (type == ControlType.Hyperlink) return "AXLink"; + if (type == ControlType.Table || type == ControlType.DataGrid) return "AXTable"; + return "AXGroup"; + } + + internal static ElementReference Element(AppState app, string snapshotId, string elementId, RequestContext context) + { + if (!int.TryParse(elementId, NumberStyles.None, CultureInfo.InvariantCulture, out var index)) + throw new NativeFailure("INVALID_ELEMENT", "Use an elementId from this snapshot"); + Windows.Refresh(app, context); + var selected = app.SelectedWindow ?? throw new NativeFailure("APP_ACCESS_REQUIRED", "Select a window with getApp before using element identifiers"); + var snapshot = app.Snapshots.Values.SingleOrDefault(value => value.Id == snapshotId) + ?? throw new NativeFailure("STALE_SNAPSHOT", "Read fresh AX state before using element identifiers"); + if (snapshot.Windows.Length != 1 || snapshot.Windows[0].Id != selected.Id) + throw new NativeFailure("STALE_SNAPSHOT", "Use an observation from the selected window"); + if (!snapshot.Elements.TryGetValue(index, out var element)) throw new NativeFailure("INVALID_ELEMENT", "Use an elementId from this snapshot"); + element.Window.Geometry(app, context); + if (!context.Ax(() => element.Element.Current.IsEnabled)) throw new NativeFailure("ELEMENT_DISABLED", "The element is disabled"); + return element; + } + + internal static void RequireSnapshot(AppState app, string snapshotId, uint windowId) + { + var selected = app.SelectedWindow; + var snapshot = app.Snapshots.Values.SingleOrDefault(value => value.Id == snapshotId); + if (snapshot is null || selected is null || selected.Id != windowId + || snapshot.Windows.Length != 1 || snapshot.Windows[0].Id != windowId) + throw new NativeFailure("STALE_SNAPSHOT", "Use a fresh observation from the selected window"); + } +} diff --git a/packages/experimental/cua-windows/native/src/AccessibilityActions.cs b/packages/experimental/cua-windows/native/src/AccessibilityActions.cs new file mode 100644 index 0000000000..ae21c9610f --- /dev/null +++ b/packages/experimental/cua-windows/native/src/AccessibilityActions.cs @@ -0,0 +1,163 @@ +// Actions use retained UIA references only after snapshot and window validation. +using System.Globalization; +using System.Text.Json; +using System.Windows.Automation; +using System.Windows.Automation.Text; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal static class AccessibilityActions +{ + private static T Pattern(AutomationElement element, AutomationPattern pattern, RequestContext context) where T : BasePattern + { + object? value = null; + if (!context.Ax(() => element.TryGetCurrentPattern(pattern, out value))) + throw new NativeFailure("UNSUPPORTED", "The control does not expose this accessibility action"); + return (T)value!; + } + + internal static string[] Actions(ElementReference reference, RequestContext context) + { + var element = reference.Element; + var actions = new List(); + if (context.Ax(() => element.TryGetCurrentPattern(InvokePattern.Pattern, out _))) actions.Add("Press"); + if (context.Ax(() => element.TryGetCurrentPattern(TogglePattern.Pattern, out _))) actions.Add("Toggle"); + if (context.Ax(() => element.TryGetCurrentPattern(SelectionItemPattern.Pattern, out _))) actions.Add("Pick"); + if (context.Ax(() => element.TryGetCurrentPattern(ExpandCollapsePattern.Pattern, out _))) { actions.Add("Expand"); actions.Add("Collapse"); } + if (context.Ax(() => element.TryGetCurrentPattern(ScrollItemPattern.Pattern, out _))) actions.Add("ScrollToVisible"); + if (context.Ax(() => element.Current.IsKeyboardFocusable)) actions.Add("Focus"); + if (context.Ax(() => element.Current.ControlType) == ControlType.Window) actions.Add("Raise"); + return actions.ToArray(); + } + + internal static void Perform(AppState app, ElementReference reference, string action, JsonElement? argument, RequestContext context) + { + if (argument is { } value && value.ValueKind is not (JsonValueKind.Null or JsonValueKind.Undefined)) + throw new NativeFailure("INVALID_ARGUMENT", "This accessibility action does not accept an argument"); + Secondary(app, reference, action, context); + } + + internal static bool Invoke(ElementReference reference, RequestContext context) + { + object? pattern = null; + var element = reference.Element; + if (context.Ax(() => element.TryGetCurrentPattern(InvokePattern.Pattern, out pattern))) + context.Ax(() => { ((InvokePattern)pattern!).Invoke(); return true; }); + else if (context.Ax(() => element.TryGetCurrentPattern(SelectionItemPattern.Pattern, out pattern))) + context.Ax(() => { ((SelectionItemPattern)pattern!).Select(); return true; }); + else return false; + return true; + } + + internal static bool Click(ElementReference reference, RequestContext context) + { + object? pattern = null; + var element = reference.Element; + if (context.Ax(() => element.TryGetCurrentPattern(InvokePattern.Pattern, out pattern))) + context.Ax(() => { ((InvokePattern)pattern!).Invoke(); return true; }); + else if (context.Ax(() => element.TryGetCurrentPattern(SelectionItemPattern.Pattern, out pattern))) + context.Ax(() => { ((SelectionItemPattern)pattern!).Select(); return true; }); + else if (context.Ax(() => element.TryGetCurrentPattern(TogglePattern.Pattern, out pattern))) + context.Ax(() => { ((TogglePattern)pattern!).Toggle(); return true; }); + else return false; + return true; + } + + internal static void SetValue(ElementReference reference, JsonElement value, RequestContext context) + { + if (value.ValueKind is not (JsonValueKind.String or JsonValueKind.Number) + || value.ValueKind == JsonValueKind.Number && (!value.TryGetDouble(out var numeric) || !double.IsFinite(numeric))) + throw new NativeFailure("INVALID_ARGUMENT", "The value must be a string or a finite number"); + object? pattern = null; + if (context.Ax(() => reference.Element.TryGetCurrentPattern(ValuePattern.Pattern, out pattern))) + { + var setter = (ValuePattern)pattern!; + if (context.Ax(() => setter.Current.IsReadOnly)) throw new NativeFailure("UNSUPPORTED", "The control value is read-only"); + var text = value.ValueKind == JsonValueKind.String + ? value.GetString()! : value.GetDouble().ToString("G", CultureInfo.InvariantCulture); + context.Ax(() => { setter.SetValue(text); return true; }); + return; + } + var number = double.NaN; + if (value.ValueKind == JsonValueKind.Number) { if (!value.TryGetDouble(out number)) number = double.NaN; } + else if (!double.TryParse(value.GetString(), NumberStyles.Float, CultureInfo.InvariantCulture, out number)) number = double.NaN; + if (!double.IsFinite(number)) throw new NativeFailure("INVALID_ARGUMENT", "This control requires a finite numeric value"); + var range = Pattern(reference.Element, RangeValuePattern.Pattern, context); + var current = context.Ax(() => range.Current); + if (current.IsReadOnly || number < current.Minimum || number > current.Maximum) + throw new NativeFailure("UNSUPPORTED", "The control cannot accept this value"); + context.Ax(() => { range.SetValue(number); return true; }); + } + + internal static void Secondary(AppState app, ElementReference reference, string action, RequestContext context) + { + switch (action.ToLowerInvariant()) + { + case "press": + context.Ax(() => { Pattern(reference.Element, InvokePattern.Pattern, context).Invoke(); return true; }); + break; + case "pick": + context.Ax(() => { Pattern(reference.Element, SelectionItemPattern.Pattern, context).Select(); return true; }); + break; + case "toggle": + context.Ax(() => { Pattern(reference.Element, TogglePattern.Pattern, context).Toggle(); return true; }); + break; + case "expand": + context.Ax(() => { Pattern(reference.Element, ExpandCollapsePattern.Pattern, context).Expand(); return true; }); + break; + case "collapse": + context.Ax(() => { Pattern(reference.Element, ExpandCollapsePattern.Pattern, context).Collapse(); return true; }); + break; + case "scrolltovisible": + context.Ax(() => { Pattern(reference.Element, ScrollItemPattern.Pattern, context).ScrollIntoView(); return true; }); + break; + case "focus": + context.Ax(() => { reference.Element.SetFocus(); return true; }); + break; + case "raise": + if (context.Ax(() => reference.Element.Current.ControlType) != ControlType.Window) + throw new NativeFailure("UNSUPPORTED", "Raise is available only on the observed window element"); + Windows.Activate(app, reference.Window, context); + break; + default: throw new NativeFailure("UNSUPPORTED", "Use an action name from a fresh details:true observation"); + } + } + + internal static void SelectText(ElementReference reference, string text, string? prefix, string? suffix, + string selectionType, RequestContext context) + { + var pattern = Pattern(reference.Element, TextPattern.Pattern, context); + if (context.Ax(() => pattern.SupportedTextSelection) == SupportedTextSelection.None) + throw new NativeFailure("UNSUPPORTED", "The control does not support text selection"); + var document = context.Ax(() => pattern.DocumentRange); + var value = context.Ax(() => document.GetText(context.Config.MaxResponseBytes)); + var expected = TextSelection.Find(value, text, prefix, suffix); + var search = context.Ax(document.Clone); + TextPatternRange? selected = null; + while (true) + { + context.Check(); + var found = context.Ax(() => search.FindText(text, false, false)); + if (found is null) break; + var before = context.Ax(document.Clone); + context.Ax(() => { before.MoveEndpointByRange(TextPatternRangeEndpoint.End, found, TextPatternRangeEndpoint.Start); return true; }); + if (context.Ax(() => before.GetText(context.Config.MaxResponseBytes)).Length == expected.Start) { selected = found; break; } + var oldStart = context.Ax(search.Clone); + context.Ax(() => { search.MoveEndpointByRange(TextPatternRangeEndpoint.Start, found, TextPatternRangeEndpoint.Start); + search.MoveEndpointByUnit(TextPatternRangeEndpoint.Start, TextUnit.Character, 1); return true; }); + if (context.Ax(() => search.CompareEndpoints(TextPatternRangeEndpoint.Start, oldStart, TextPatternRangeEndpoint.Start)) <= 0) break; + } + if (selected is null || context.Ax(() => selected.GetText(context.Config.MaxResponseBytes)) != text) + throw new NativeFailure("SELECTION_CHANGED", "The control text changed; read fresh state before selecting"); + if (selectionType == "cursor_before") + context.Ax(() => { selected.MoveEndpointByRange(TextPatternRangeEndpoint.End, selected, TextPatternRangeEndpoint.Start); return true; }); + else if (selectionType == "cursor_after") + context.Ax(() => { selected.MoveEndpointByRange(TextPatternRangeEndpoint.Start, selected, TextPatternRangeEndpoint.End); return true; }); + context.Ax(() => { selected.Select(); return true; }); + var actual = context.Ax(pattern.GetSelection); + if (actual.Length != 1 || context.Ax(() => actual[0].CompareEndpoints(TextPatternRangeEndpoint.Start, selected, TextPatternRangeEndpoint.Start)) != 0 + || context.Ax(() => actual[0].CompareEndpoints(TextPatternRangeEndpoint.End, selected, TextPatternRangeEndpoint.End)) != 0) + throw new NativeFailure("SELECTION_CHANGED", "The control did not retain the requested selection; read fresh state"); + } +} diff --git a/packages/experimental/cua-windows/native/src/Applications.cs b/packages/experimental/cua-windows/native/src/Applications.cs new file mode 100644 index 0000000000..eff65c0497 --- /dev/null +++ b/packages/experimental/cua-windows/native/src/Applications.cs @@ -0,0 +1,291 @@ +// Application consent identifies the executable before any launch or UI observation. +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using Microsoft.Win32; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal sealed record ApplicationIdentity(string Id, string Name, string ExecutablePath, bool Persistable); +internal sealed record RunningApplication(int Pid, long Started, string Path, string Name); +internal sealed record InstalledApplication(string Name, string Path); + +internal sealed class AppState(string handle, ApplicationIdentity authorization, string digest, RunningApplication? process) : IDisposable +{ + internal string Handle { get; } = handle; + internal WindowState? SelectedWindow { get; set; } + internal ApplicationIdentity Authorization { get; } = authorization; + internal string Digest { get; } = digest; + internal RunningApplication? Process { get; set; } = process; + internal Dictionary Windows { get; } = []; + internal Dictionary Snapshots { get; } = []; + private uint nextWindowId; + private System.Diagnostics.Process? owner; + internal uint AllocateWindowId() + { + if (nextWindowId == uint.MaxValue) throw new NativeFailure("NATIVE_LIMIT", "Select the application again to allocate new window identifiers"); + return ++nextWindowId; + } + internal RunningApplication RequireProcess() + { + var selected = Process ?? throw new NativeFailure("APP_ACCESS_REQUIRED", "Application launch requires Host authorization"); + try + { + owner ??= System.Diagnostics.Process.GetProcessById(selected.Pid); + if (owner.HasExited || Applications.Started(owner) != selected.Started) + throw new NativeFailure("STALE_APP", "Select the application again after its process changes"); + } + catch (ArgumentException) { throw new NativeFailure("STALE_APP", "Select the application again after it exits"); } + return selected; + } + public void Dispose() { owner?.Dispose(); Snapshots.Clear(); Windows.Clear(); } +} + +internal static class Applications +{ + internal static object Icons(JsonElement parameters, RequestContext context) + { + var paths = parameters.GetProperty("paths"); + if (paths.ValueKind != JsonValueKind.Array) + throw new NativeFailure("INVALID_ARGUMENT", "paths must be an array"); + var result = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var element in paths.EnumerateArray()) + { + context.Check(); + if (element.ValueKind != JsonValueKind.String || string.IsNullOrEmpty(element.GetString())) + throw new NativeFailure("INVALID_ARGUMENT", "paths must contain nonempty strings"); + var path = element.GetString()!; + try + { + using var icon = System.Drawing.Icon.ExtractAssociatedIcon(path); + if (icon is null) continue; + using var original = icon.ToBitmap(); + using var bitmap = new System.Drawing.Bitmap(original, new System.Drawing.Size(64, 64)); + using var stream = new MemoryStream(); + bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png); + result[path] = "data:image/png;base64," + Convert.ToBase64String(stream.ToArray()); + } + catch (Exception error) when (error is IOException or UnauthorizedAccessException or ArgumentException + or System.ComponentModel.Win32Exception) + { + // Missing or unreadable executable metadata has no icon; application access is unchanged. + } + } + return result; + } + + private static readonly int SessionId = CurrentSession(); + private static int CurrentSession() { using var process = System.Diagnostics.Process.GetCurrentProcess(); return process.SessionId; } + internal static long Started(System.Diagnostics.Process process) + { + if (!Win32.GetProcessTimes(process.SafeHandle, out var created, out _, out _, out _)) + throw new NativeFailure("STALE_APP", "The process lifetime is unavailable; select the application again"); + return created; + } + internal static string CanonicalPath(string path) + { + using var handle = File.OpenHandle(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); + var capacity = Win32.GetFinalPathNameByHandle(handle, new StringBuilder(), 0, 0); + if (capacity == 0) throw new NativeFailure("APP_IDENTITY_UNAVAILABLE", "The executable path could not be resolved"); + var text = new StringBuilder(checked((int)capacity + 1)); + if (Win32.GetFinalPathNameByHandle(handle, text, (uint)text.Capacity, 0) == 0) + throw new NativeFailure("APP_IDENTITY_UNAVAILABLE", "The executable path changed during selection"); + var resolved = text.ToString(); + return resolved.StartsWith(@"\\?\UNC\", StringComparison.OrdinalIgnoreCase) + ? @"\\" + resolved[8..] : resolved.StartsWith(@"\\?\", StringComparison.Ordinal) ? resolved[4..] : resolved; + } + + internal static string Digest(string path) + { + using var file = File.OpenRead(path); + return Convert.ToHexStringLower(SHA256.HashData(file)); + } + + private static string? VerifiedSigner(string path) + { + var file = new Win32.TrustFile { Size = (uint)Marshal.SizeOf(), Path = path }; + var memory = Marshal.AllocHGlobal(Marshal.SizeOf()); + Marshal.StructureToPtr(file, memory, false); + var data = new Win32.TrustData + { + Size = (uint)Marshal.SizeOf(), UiChoice = 2, UnionChoice = 1, + File = memory, StateAction = 1, ProviderFlags = 0x1000 | 0x80, + }; + var action = new Guid("00AAC56B-CD44-11D0-8CC2-00C04FC295EE"); + try + { + if (Win32.WinVerifyTrust(0, ref action, ref data) != 0) return null; + var provider = Win32.WTHelperProvDataFromStateData(data.StateData); + var signerPointer = provider == 0 ? 0 : Win32.WTHelperGetProvSignerFromChain(provider, 0, false, 0); + if (signerPointer == 0) return null; + var signer = Marshal.PtrToStructure(signerPointer); + if (signer.CertificateCount == 0 || signer.Certificates == 0) return null; + var certificate = Marshal.PtrToStructure(signer.Certificates); + if (certificate.Certificate == 0) return null; + var context = Marshal.PtrToStructure(certificate.Certificate); + if (context.Encoded == 0 || context.EncodedSize == 0 || context.EncodedSize > int.MaxValue) return null; + var bytes = new byte[(int)context.EncodedSize]; + Marshal.Copy(context.Encoded, bytes, 0, bytes.Length); + return Convert.ToHexStringLower(SHA256.HashData(bytes)); + } + catch (CryptographicException) { return null; } + finally + { + data.StateAction = 2; + Win32.WinVerifyTrust(0, ref action, ref data); + Marshal.DestroyStructure(memory); + Marshal.FreeHGlobal(memory); + } + } + + internal static (ApplicationIdentity Identity, string Digest) Identify(string path, string name, RunningApplication? process) + { + var canonical = CanonicalPath(path); + var digest = Digest(canonical); + var signer = VerifiedSigner(canonical); + var requirement = signer is not null ? "signed:" + signer + : process is null ? "pending:" + digest : $"process:{process.Pid}:{process.Started}:{digest}"; + var id = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes("win32\0" + canonical + "\0" + requirement))); + return (new(id, name, canonical, signer is not null), digest); + } + + internal static RunningApplication Running(int pid) + { + try + { + using var process = System.Diagnostics.Process.GetProcessById(pid); + if (process.SessionId != SessionId) + throw new NativeFailure("UNSUPPORTED_SESSION", "Select an application in this interactive desktop session"); + var path = process.MainModule?.FileName + ?? throw new NativeFailure("APP_IDENTITY_UNAVAILABLE", "The application executable is unavailable"); + return new(pid, Started(process), CanonicalPath(path), process.ProcessName); + } + catch (System.ComponentModel.Win32Exception) + { + throw new NativeFailure("PERMISSION_DENIED", "Windows refused the application identity; its privilege level may exceed the helper's"); + } + catch (ArgumentException) { throw new NativeFailure("STALE_APP", "The selected process has exited"); } + } + + internal static IReadOnlyList List() + { + var ids = new HashSet(); + Win32.EnumWindows((window, _) => + { + if (Win32.IsWindowVisible(window)) + { + Win32.GetWindowThreadProcessId(window, out var pid); + if (pid != 0 && pid <= int.MaxValue) ids.Add((int)pid); + } + return true; + }, 0); + var result = new List(); + foreach (var pid in ids.Order()) + { + try { result.Add(Running(pid)); } + catch (NativeFailure) { /* Processes can exit or deny metadata while the desktop is enumerated. */ } + catch (IOException) { /* A disappearing executable is not a selectable application. */ } + } + return result; + } + + internal static IReadOnlyList Find(string query, int maximum, bool exact = false) + { + var found = new Dictionary(StringComparer.Ordinal); + void Add(string name, string path) + { + if (exact ? !string.Equals(name, query, StringComparison.OrdinalIgnoreCase) && !string.Equals(Path.GetFileName(path), query, StringComparison.OrdinalIgnoreCase) + : !name.Contains(query, StringComparison.OrdinalIgnoreCase) && !Path.GetFileName(path).Contains(query, StringComparison.OrdinalIgnoreCase)) return; + if (!Path.IsPathFullyQualified(path) || !path.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) || !File.Exists(path)) return; + found.TryAdd(CanonicalPath(path), new(name, CanonicalPath(path))); + if (found.Count > maximum) throw new NativeFailure("TOO_MANY_APPS", "Use a more specific application name or executable path"); + } + foreach (var app in List()) Add(app.Name, app.Path); + foreach (var hive in new[] { RegistryHive.CurrentUser, RegistryHive.LocalMachine }) + foreach (var view in new[] { RegistryView.Registry64, RegistryView.Registry32 }) + { + using var registry = RegistryKey.OpenBaseKey(hive, view); + using var paths = registry.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths"); + if (paths is null) continue; + foreach (var key in paths.GetSubKeyNames()) + { + using var app = paths.OpenSubKey(key); + if (app?.GetValue(null) is string path) Add(Path.GetFileNameWithoutExtension(key), Environment.ExpandEnvironmentVariables(path.Trim('"'))); + } + } + foreach (var directory in new[] { Environment.SpecialFolder.Programs, Environment.SpecialFolder.CommonPrograms }) + { + var root = Environment.GetFolderPath(directory); + if (!Directory.Exists(root)) continue; + foreach (var link in Directory.EnumerateFiles(root, "*.lnk", new EnumerationOptions + { RecurseSubdirectories = true, IgnoreInaccessible = true, AttributesToSkip = FileAttributes.ReparsePoint })) + { + var name = Path.GetFileNameWithoutExtension(link); + if (!name.Contains(query, StringComparison.OrdinalIgnoreCase)) continue; + var target = ShellBroker.ShortcutTarget(link); + if (target is not null) Add(name, target); + } + } + return found.Values.OrderBy(app => app.Name, StringComparer.OrdinalIgnoreCase).ToArray(); + } + + internal static AppState Select(string selector, IEnumerable retained) + { + RunningApplication? running = null; + string path, name; + if (int.TryParse(selector, out var pid)) + { + running = Running(pid); path = running.Path; name = running.Name; + } + else + { + var absolute = Path.IsPathFullyQualified(selector) ? CanonicalPath(selector) : null; + var matches = List().Where(app => absolute is not null ? string.Equals(app.Path, absolute, StringComparison.Ordinal) : string.Equals(app.Name, selector, StringComparison.OrdinalIgnoreCase) + || string.Equals(Path.GetFileName(app.Path), selector, StringComparison.OrdinalIgnoreCase) + ).ToArray(); + if (matches.Length > 1) throw new NativeFailure("AMBIGUOUS_APP", "Select one of the observed process IDs"); + if (matches.Length == 1) { running = matches[0]; path = running.Path; name = running.Name; } + else if (absolute is not null) { path = absolute; name = Path.GetFileNameWithoutExtension(path); } + else + { + var installed = Find(selector, 1, true).Where(app => string.Equals(app.Name, selector, StringComparison.OrdinalIgnoreCase) + || string.Equals(Path.GetFileName(app.Path), selector, StringComparison.OrdinalIgnoreCase)).ToArray(); + if (installed.Length != 1) throw new NativeFailure(installed.Length == 0 ? "APP_NOT_FOUND" : "AMBIGUOUS_APP", "Use findApps, an executable path, or an observed PID"); + path = installed[0].Path; name = installed[0].Name; + } + } + if (!path.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) throw new NativeFailure("UNSUPPORTED", "Select a Windows application executable"); + if (running is not null) + { + var previous = retained.FirstOrDefault(app => app.Process?.Pid == running.Pid && app.Process.Started == running.Started); + if (previous is not null) return previous; + } + var identity = Identify(path, name, running); + return new(Guid.NewGuid().ToString("N"), identity.Identity, identity.Digest, running); + } + + internal static async Task Launch(AppState app, RequestContext context) + { + if (app.Process is not null) { app.RequireProcess(); return; } + var identity = app.Authorization; + if (Digest(identity.ExecutablePath) != app.Digest) throw new NativeFailure("STALE_APP", "The selected executable changed before launch; select it again"); + context.Check(); + await context.Sta.Invoke(() => ShellBroker.Launch(identity.ExecutablePath), context.Cancellation); + while (true) + { + context.Check(); + var matches = List().Where(candidate => string.Equals(candidate.Path, identity.ExecutablePath, StringComparison.Ordinal)).ToArray(); + if (matches.Length > 1) throw new NativeFailure("AMBIGUOUS_APP", "Several matching processes started; select an observed PID"); + if (matches.Length == 1) + { + if (Digest(matches[0].Path) != app.Digest) throw new NativeFailure("STALE_APP", "The launched executable differs from the approved file"); + app.Process = matches[0]; + return; + } + await Task.Delay(context.Config.PollIntervalMs, context.Cancellation); + } + } +} diff --git a/packages/experimental/cua-windows/native/src/CaptureAdmission.cs b/packages/experimental/cua-windows/native/src/CaptureAdmission.cs new file mode 100644 index 0000000000..5014f34f85 --- /dev/null +++ b/packages/experimental/cua-windows/native/src/CaptureAdmission.cs @@ -0,0 +1,34 @@ +// The native operation owns its capture slot until cleanup finishes, independently of the caller's await. +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal sealed class CaptureAdmission +{ + private readonly object gate = new(); + private Task? pending; + + internal Task Start(Func> operation) + { + lock (gate) + { + if (pending is { IsCompleted: false }) + throw new NativeFailure("CAPTURE_BUSY", "The previous Windows capture is still releasing its resources; UIA and input remain available"); + pending = operation(); + _ = pending.ContinueWith(completed => { _ = completed.Exception; }, CancellationToken.None, + TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + return pending; + } + } + + internal async Task Join() + { + Task? active; + lock (gate) active = pending; + if (active is not null) + { + try { await active; } + catch (Exception error) { _ = error; /* The requesting connection owns the capture failure. */ } + } + } +} diff --git a/packages/experimental/cua-windows/native/src/ClipboardPaste.cs b/packages/experimental/cua-windows/native/src/ClipboardPaste.cs new file mode 100644 index 0000000000..6244fc9fa7 --- /dev/null +++ b/packages/experimental/cua-windows/native/src/ClipboardPaste.cs @@ -0,0 +1,183 @@ +// Delayed rendering waits for clipboard data consumption before restoring the previous formats. +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Text; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal sealed class ClipboardPaste +{ + private sealed class Transaction(ServiceControl control, int targetPid, uint format, byte[] payload, List<(uint Format, byte[] Data)> previous, uint originalSequence) + { + internal readonly TaskCompletionSource Consumed = new(TaskCreationOptions.RunContinuationsAsynchronously); + private uint sequence = originalSequence; + private bool replaced; + private bool restoring; + private bool changed; + private bool rendered; + + internal void Begin() + { + if (!Win32.OpenClipboard(control.Handle)) throw new NativeFailure("CLIPBOARD_BUSY", "Another application is using the clipboard"); + try + { + if (Win32.GetClipboardSequenceNumber() != sequence) throw new NativeFailure("CLIPBOARD_CHANGED", "The clipboard changed before paste; it was not replaced"); + if (!Win32.EmptyClipboard()) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "Windows refused clipboard replacement"); + replaced = true; + control.ClipboardMessage = Message; + Marshal.SetLastPInvokeError(0); + Win32.SetClipboardData(format, 0); + var error = Marshal.GetLastPInvokeError(); + sequence = Win32.GetClipboardSequenceNumber(); + if (error != 0) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "Windows refused the temporary clipboard format"); + } + finally { Win32.CloseClipboard(); } + // CloseClipboard can add synthesized formats and advance the sequence. + sequence = Win32.GetClipboardSequenceNumber(); + } + + private bool Message(int message, nint parameter) + { + if (message == 0x0307 && !restoring) + { + changed = true; + Consumed.TrySetException(new NativeFailure("CLIPBOARD_CHANGED", "Another writer replaced the clipboard; observe before deciding on further input")); + return true; + } + if (message is not (0x0305 or 0x0306)) return false; + if (message == 0x0305 && (uint)parameter != format) return false; + if (message == 0x0305) + { + Win32.GetWindowThreadProcessId(Win32.GetOpenClipboardWindow(), out var readerPid); + // Clipboard monitors can request data before the target handles Control+V. + // Leave the format delayed until the selected application requests it. + if (readerPid != targetPid) return true; + } + var opened = false; + try + { + if (Win32.GetClipboardOwner() != control.Handle) return true; + if (message == 0x0306) + { + if (!Win32.OpenClipboard(control.Handle)) return true; + opened = true; + } + if (Win32.GetClipboardSequenceNumber() != sequence) changed = true; + Publish(format, payload); + rendered = true; + sequence = Win32.GetClipboardSequenceNumber(); + if (changed) Consumed.TrySetException(new NativeFailure("CLIPBOARD_CHANGED", "Another writer changed the clipboard during paste")); + else if (message == 0x0305) Consumed.TrySetResult(); + } + catch (Exception error) { Consumed.TrySetException(error); } + finally { if (opened) Win32.CloseClipboard(); } + return true; + } + + internal bool Restore() + { + if (!replaced) return true; + if (Win32.GetClipboardOwner() != control.Handle) { control.ClipboardMessage = null; return true; } + if (!Win32.OpenClipboard(control.Handle)) return false; + try + { + if (Win32.GetClipboardSequenceNumber() != sequence) changed = true; + if (changed) + { + // A later writer keeps its data; fulfill any remaining promise before releasing its renderer. + if (!rendered) Publish(format, payload); + return true; + } + restoring = true; + if (!Win32.EmptyClipboard()) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "Windows refused clipboard restoration"); + foreach (var original in previous) Publish(original.Format, original.Data); + return true; + } + finally { control.ClipboardMessage = null; Win32.CloseClipboard(); } + } + } + + private static void Publish(uint format, byte[] bytes) + { + var memory = Win32.GlobalAlloc(0x0002, (nuint)bytes.Length); + if (memory == 0) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "Clipboard memory allocation failed"); + try + { + var pointer = Win32.GlobalLock(memory); + if (pointer == 0) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "Clipboard memory could not be locked"); + try { Marshal.Copy(bytes, 0, pointer, bytes.Length); } + finally { Win32.GlobalUnlock(memory); } + if (Win32.SetClipboardData(format, memory) == 0) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "Windows refused clipboard data"); + memory = 0; + } + finally { if (memory != 0) Win32.GlobalFree(memory); } + } + + private static Transaction Prepare(ServiceControl control, int targetPid, string text, string format, int maximumBytes) + { + if (!Win32.OpenClipboard(control.Handle)) throw new NativeFailure("CLIPBOARD_BUSY", "Another application is using the clipboard"); + try + { + var previous = new List<(uint, byte[])>(); + long total = 0; + uint current = 0; + while (true) + { + Marshal.SetLastPInvokeError(0); + current = Win32.EnumClipboardFormats(current); + if (current == 0) + { + if (Marshal.GetLastPInvokeError() != 0) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "The existing clipboard formats could not be enumerated"); + break; + } + if (current is 3 or 0x0083) + throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "The clipboard contains a metafile with nested handles; paste left it unchanged"); + var memory = Win32.GetClipboardData(current); + var size = memory == 0 ? 0 : Win32.GlobalSize(memory); + if (size == 0 || size > int.MaxValue) + throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "The current clipboard includes a format that cannot be preserved as bytes; paste left it unchanged"); + total += (long)size; + if (total > maximumBytes) throw new NativeFailure("CLIPBOARD_LIMIT", "The existing clipboard exceeds maxClipboardBytes; it was not replaced"); + var pointer = Win32.GlobalLock(memory); + if (pointer == 0) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "The current clipboard data could not be read; it was not replaced"); + var bytes = new byte[(int)size]; + try { Marshal.Copy(pointer, bytes, 0, bytes.Length); } + finally { Win32.GlobalUnlock(memory); } + previous.Add((current, bytes)); + } + var payload = format == "html" ? HtmlClipboard.Encode(text) : Encoding.Unicode.GetBytes(text + "\0"); + var nativeFormat = format == "html" ? Win32.RegisterClipboardFormat("HTML Format") : 13u; + if (nativeFormat == 0) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "Windows could not register the requested clipboard format"); + return new(control, targetPid, nativeFormat, payload, previous, Win32.GetClipboardSequenceNumber()); + } + finally { Win32.CloseClipboard(); } + } + + internal async Task Paste(AppState app, string text, string format, int maximumBytes, int readTimeoutMs, RequestContext context) + { + Windows.RequireForeground(app, null, context); + var targetPid = app.RequireProcess().Pid; + var transaction = await context.Sta.Invoke(control => Prepare(control, targetPid, text, format, maximumBytes), context.Cancellation); + try + { + await context.Sta.Invoke(() => transaction.Begin(), context.Cancellation); + Input.Press(app, "v", ["control"], context); + try { await transaction.Consumed.Task.WaitAsync(TimeSpan.FromMilliseconds(readTimeoutMs), context.Cancellation); } + catch (TimeoutException) + { + throw new NativeFailure("PASTE_NOT_CONSUMED", "The target did not request clipboard data before pasteReadTimeoutMs; observe before deciding on further input"); + } + } + finally + { + var clock = Stopwatch.StartNew(); + while (!await context.Sta.Invoke(_ => transaction.Restore(), CancellationToken.None)) + { + if (clock.ElapsedMilliseconds >= context.Config.GraceMs) + NativeServer.Fatal("CLIPBOARD_CLEANUP", "Clipboard cleanup did not finish before the native grace deadline"); + await Task.Delay(context.Config.PollIntervalMs); + } + } + } +} diff --git a/packages/experimental/cua-windows/native/src/DesktopExecutor.cs b/packages/experimental/cua-windows/native/src/DesktopExecutor.cs new file mode 100644 index 0000000000..7e9b33a9e0 --- /dev/null +++ b/packages/experimental/cua-windows/native/src/DesktopExecutor.cs @@ -0,0 +1,264 @@ +// The shared Host policy authorizes handles before these platform operations execute. +using System.Text.Json; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal sealed class ClientState +{ + internal DesktopWindows Desktop { get; } = new(); + internal Dictionary Launches { get; } = new(StringComparer.Ordinal); + internal Dictionary Apps { get; } = new(StringComparer.Ordinal); + internal AppState App(string handle) => Apps.GetValueOrDefault(handle) + ?? throw new NativeFailure("STALE_APP", "Select the application again on this connection"); + internal void Clear() { foreach (var app in Apps.Values) app.Dispose(); Apps.Clear(); Launches.Clear(); } +} + +internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta, int graceMs) : IAsyncDisposable +{ + private readonly WindowCapture capture = new(); + private readonly ClipboardPaste clipboard = new(); + private readonly SemaphoreSlim queue = new(1); + + private static object ActionResult(nint before) => new + { + dispatched = true, + foregroundChanged = before == 0 || Win32.GetForegroundWindow() == 0 ? (bool?)null : before != Win32.GetForegroundWindow(), + }; + private static string String(JsonElement value, string key) => value.GetProperty(key).GetString()!; + private static string? OptionalString(JsonElement value, string key) => value.TryGetProperty(key, out var item) ? item.GetString() : null; + private static bool Flag(JsonElement value, string key) => value.TryGetProperty(key, out var item) && item.GetBoolean(); + private static uint? WindowId(JsonElement value) => value.TryGetProperty("windowId", out var id) ? id.GetUInt32() : null; + private static string[] Modifiers(JsonElement value) => value.TryGetProperty("modifiers", out var items) ? items.EnumerateArray().Select(item => item.GetString()!).ToArray() : []; + + // Window-scoped operations act only on the window authorized at getApp; the request must name it. + private static WindowState Selected(AppState app, JsonElement parameters, RequestContext context) + { + if (!parameters.TryGetProperty("windowId", out var raw)) + throw new NativeFailure("UNSUPPORTED", "This operation requires a window target; select a window with getApp and pass its windowId"); + if (!raw.TryGetUInt32(out var id)) + throw new NativeFailure("INVALID_ARGUMENT", "windowId must be a non-negative 32-bit identifier"); + var selected = app.SelectedWindow ?? throw new NativeFailure("APP_ACCESS_REQUIRED", "Select a window with getApp before this operation"); + if (selected.Id != id) + throw new NativeFailure("WINDOW_CHANGED", "The request targets another window; select that window with getApp"); + selected.Geometry(app, context); + return selected; + } + + private static (WindowState Window, double X, double Y) Coordinate(AppState app, JsonElement parameters, RequestContext context) + { + var window = Selected(app, parameters, context); + if (OptionalString(parameters, "snapshotId") is { } snapshot) Accessibility.RequireSnapshot(app, snapshot, window.Id); + return (window, parameters.GetProperty("x").GetDouble(), parameters.GetProperty("y").GetDouble()); + } + + internal async Task Execute(NativeRequest request, ClientState state, NativeConfig config, CancellationToken cancellation) + { + if (request.Method == "screenshot") + { + var context = new RequestContext(config, cancellation, mta, sta); + AppState app; + WindowState window; + await queue.WaitAsync(cancellation); + try + { + DesktopSession.RequireInteractive(); + app = state.App(String(request.Params, "appHandle")); + window = Selected(app, request.Params, context); + } + finally { queue.Release(); } + return await capture.Capture(app, window, context); + } + await queue.WaitAsync(cancellation); + try + { + var context = new RequestContext(config, cancellation, mta, sta); + context.Check(); + var parameters = request.Params; + if (request.Method == "permissionStatus") return DesktopSession.Status(await capture.IsSupported(cancellation)); + if (request.Method == "applicationIcons") return await sta.Invoke(_ => Applications.Icons(parameters, context), cancellation); + if (request.Method == "getCapabilities") + { + var locked = DesktopSession.Locked(); + return new { permissions = new { accessibility = locked == false, + screenRecording = locked == false && await capture.IsSupported(cancellation) }, + sessionLocked = locked }; + } + if (request.Method is "requestPermission" or "openPermissionSettings") + throw new NativeFailure("UNSUPPORTED", "Windows desktop access has no macOS permission switches; inspect the Windows session status"); + DesktopSession.RequireInteractive(); + if (request.Method == "listApps") return state.Desktop.ListApps(context); + if (request.Method == "findApps") + throw new NativeFailure("UNSUPPORTED", "Windows discovers selectable windows with listApps; installed launch entries are not part of this selection"); + if (request.Method == "getApp") + { + var selected = state.Desktop.Select(String(parameters, "selector"), context); + state.Apps[selected.Handle] = selected; + return new { appHandle = selected.Handle, pid = 4, name = selected.Authorization.Name, + running = true, authorization = selected.Authorization }; + } + if (request.Method == "launchApp") + throw new NativeFailure("UNSUPPORTED", "A selected Windows window cannot be launched; select an observed window from listApps"); + var app = state.App(String(parameters, "appHandle")); + app.RequireProcess(); + var foreground = Win32.GetForegroundWindow(); + switch (request.Method) + { + case "listWindows": return Windows.Refresh(app, context).Select(window => window.Describe(app, context)).ToArray(); + case "getState": + { + var target = Selected(app, parameters, context); + return await mta.Invoke(() => Accessibility.State(app, target.Id, parameters.GetProperty("maxElements").GetInt32(), + parameters.GetProperty("maxDepth").GetInt32(), Flag(parameters, "includeMenus"), Flag(parameters, "details"), context), cancellation); + } + case "activate": Windows.Activate(app, null, context); return ActionResult(foreground); + case "show": return Windows.Show(app, WindowId(parameters), context); + case "typeText": + Selected(app, parameters, context); + await Input.Type(app, String(parameters, "text"), context); + return ActionResult(foreground); + case "pressKey": + Selected(app, parameters, context); + Input.Press(app, String(parameters, "key"), Modifiers(parameters), context); + return ActionResult(foreground); + case "sendKeyEvent": + throw new NativeFailure("UNSUPPORTED", "Held key events are not supported on current platform."); + case "paste": + Selected(app, parameters, context); + await clipboard.Paste(app, String(parameters, "text"), OptionalString(parameters, "format") ?? "text", + parameters.GetProperty("maxClipboardBytes").GetInt32(), parameters.GetProperty("pasteReadTimeoutMs").GetInt32(), context); + return ActionResult(foreground); + case "mouseMove": + { + if (parameters.TryGetProperty("elementId", out _)) + { + var target = Selected(app, parameters, context); + return await mta.Invoke(() => + { + var element = Accessibility.Element(app, String(parameters, "snapshotId"), String(parameters, "elementId"), context); + if (element.Window.Id != target.Id) throw new NativeFailure("WINDOW_CHANGED", "The element belongs to another window"); + var bounds = context.Ax(() => element.Element.Current.BoundingRectangle); + if (bounds.IsEmpty) throw new NativeFailure("UNSUPPORTED", "The element has no pointer bounds"); + var geometry = element.Window.RequireObservation(app, context); + return Input.MouseMove(app, element.Window, (bounds.X + bounds.Width / 2 - geometry.Pixels.Left), + (bounds.Y + bounds.Height / 2 - geometry.Pixels.Top), context); + }, cancellation); + } + var pointed = Coordinate(app, parameters, context); + return Input.MouseMove(app, pointed.Window, pointed.X, pointed.Y, context); + } + case "scroll": + { + var target = Coordinate(app, parameters, context); + Input.Scroll(app, target.Window, target.X, target.Y, parameters.GetProperty("deltaLinesX").GetInt32(), + parameters.GetProperty("deltaLinesY").GetInt32(), context); + return ActionResult(foreground); + } + case "drag": + { + var target = Selected(app, parameters, context); + if (OptionalString(parameters, "snapshotId") is { } snapshot) Accessibility.RequireSnapshot(app, snapshot, target.Id); + await Input.Drag(app, target, parameters.GetProperty("fromX").GetDouble(), + parameters.GetProperty("fromY").GetDouble(), parameters.GetProperty("toX").GetDouble(), parameters.GetProperty("toY").GetDouble(), + OptionalString(parameters, "mouseButton") ?? "left", Modifiers(parameters), parameters.GetProperty("durationMs").GetInt32(), + parameters.GetProperty("steps").GetInt32(), context); + return ActionResult(foreground); + } + case "click": + { + var target = Selected(app, parameters, context); + int? hold = null; + if (parameters.TryGetProperty("holdMs", out var duration)) + { + if (!duration.TryGetInt32(out var value) || value > config.MaxClickHoldMs) + throw new NativeFailure("INVALID_ARGUMENT", "The requested click exceeds maxClickHoldMs"); + hold = value; + } + var button = OptionalString(parameters, "mouseButton") ?? "left"; + var count = parameters.TryGetProperty("clickCount", out var clickCount) ? clickCount.GetInt32() : 1; + var modifiers = Modifiers(parameters); + (WindowState Window, double X, double Y)? pointer = null; + if (parameters.TryGetProperty("elementId", out _)) + { + await mta.Invoke(() => + { + var element = Accessibility.Element(app, String(parameters, "snapshotId"), String(parameters, "elementId"), context); + if (element.Window.Id != target.Id) throw new NativeFailure("WINDOW_CHANGED", "The element belongs to another window"); + if (!hold.HasValue && button == "left" && count == 1 && modifiers.Length == 0 && AccessibilityActions.Click(element, context)) return true; + var bounds = context.Ax(() => element.Element.Current.BoundingRectangle); + if (bounds.IsEmpty) throw new NativeFailure("UNSUPPORTED", "The element has no pointer bounds"); + var geometry = element.Window.RequireObservation(app, context); + pointer = (element.Window, bounds.X + bounds.Width / 2 - geometry.Pixels.Left, + bounds.Y + bounds.Height / 2 - geometry.Pixels.Top); + return true; + }, cancellation); + } + else pointer = Coordinate(app, parameters, context); + if (pointer is { } targetPoint) + { + if (hold is { } held) await Input.HoldClick(app, targetPoint.Window, targetPoint.X, targetPoint.Y, button, count, modifiers, held, context); + else Input.Click(app, targetPoint.Window, targetPoint.X, targetPoint.Y, button, count, modifiers, context); + } + return ActionResult(foreground); + } + case "listActions": + { + Selected(app, parameters, context); + return await mta.Invoke(() => AccessibilityActions.Actions( + Accessibility.Element(app, String(parameters, "snapshotId"), String(parameters, "elementId"), context), context), cancellation); + } + case "performAction": + { + Selected(app, parameters, context); + var argument = parameters.TryGetProperty("argument", out var raw) ? raw : (JsonElement?)null; + await mta.Invoke(() => + { + var element = Accessibility.Element(app, String(parameters, "snapshotId"), String(parameters, "elementId"), context); + AccessibilityActions.Perform(app, element, String(parameters, "action"), argument, context); + return true; + }, cancellation); + return ActionResult(foreground); + } + case "invoke": + { + Selected(app, parameters, context); + var dispatched = await mta.Invoke(() => AccessibilityActions.Invoke( + Accessibility.Element(app, String(parameters, "snapshotId"), String(parameters, "elementId"), context), context), cancellation); + return new { dispatched }; + } + case "setValue": + { + Selected(app, parameters, context); + await mta.Invoke(() => + { + var element = Accessibility.Element(app, String(parameters, "snapshotId"), String(parameters, "elementId"), context); + AccessibilityActions.SetValue(element, parameters.GetProperty("value"), context); + return true; + }, cancellation); + return ActionResult(foreground); + } + case "selectText": + { + Selected(app, parameters, context); + await mta.Invoke(() => + { + var element = Accessibility.Element(app, String(parameters, "snapshotId"), String(parameters, "elementId"), context); + AccessibilityActions.SelectText(element, String(parameters, "text"), OptionalString(parameters, "prefix"), OptionalString(parameters, "suffix"), + OptionalString(parameters, "selectionType") ?? "text", context); + return true; + }, cancellation); + return ActionResult(foreground); + } + default: throw new NativeFailure("UNSUPPORTED", "Unknown native CUA operation"); + } + } + finally { queue.Release(); } + } + + public async ValueTask DisposeAsync() + { + try { await capture.DisposeAsync().AsTask().WaitAsync(TimeSpan.FromMilliseconds(graceMs)); } + catch (TimeoutException) { NativeServer.Fatal("NATIVE_CLEANUP", "The idle desktop service could not release capture resources"); } + queue.Dispose(); + } +} diff --git a/packages/experimental/cua-windows/native/src/DesktopSession.cs b/packages/experimental/cua-windows/native/src/DesktopSession.cs new file mode 100644 index 0000000000..d9969a3a56 --- /dev/null +++ b/packages/experimental/cua-windows/native/src/DesktopSession.cs @@ -0,0 +1,45 @@ +// Observations stop when the interactive input desktop is unavailable. +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Security.Principal; +using System.Text; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal static class DesktopSession +{ + internal static bool? Locked() + { + using var process = Process.GetCurrentProcess(); + if (!Win32.WTSQuerySessionInformation(0, process.SessionId, 8, out var state, out var bytes)) return null; + try { if (bytes < sizeof(int) || Marshal.ReadInt32(state) != 0) return true; } + finally { Win32.WTSFreeMemory(state); } + var desktop = Win32.OpenInputDesktop(0, false, 1); + if (desktop == 0) return Marshal.GetLastWin32Error() == 5 ? true : null; + try + { + var name = new StringBuilder(256); + if (!Win32.GetUserObjectInformation(desktop, 2, name, name.Capacity * sizeof(char), out _)) return null; + return !string.Equals(name.ToString(), "Default", StringComparison.OrdinalIgnoreCase); + } + finally { Win32.CloseDesktop(desktop); } + } + + internal static void RequireInteractive() + { + if (Locked() != false) throw new NativeFailure("SESSION_LOCKED", "Unlock Windows and return to an interactive desktop before observing or sending input"); + } + + internal static object Status(bool captureAvailable) + { + using var identity = WindowsIdentity.GetCurrent(); + return new + { + platform = "windows", sessionLocked = Locked(), + captureAvailable, + elevated = new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator), + helper = new { pid = 4, path = Environment.ProcessPath, name = "dsh-cua-windows" }, + }; + } +} diff --git a/packages/experimental/cua-windows/native/src/DesktopWindows.cs b/packages/experimental/cua-windows/native/src/DesktopWindows.cs new file mode 100644 index 0000000000..e70b1b1d1e --- /dev/null +++ b/packages/experimental/cua-windows/native/src/DesktopWindows.cs @@ -0,0 +1,109 @@ +// Discovery IDs are connection-owned and never reused for another HWND lifetime. +using System.Security.Cryptography; +using System.Text; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal sealed record DiscoveredWindow(WindowState Window, RunningApplication Process, string Selector); + +internal sealed class DesktopWindows +{ + private readonly Dictionary windows = []; + private uint nextId; + + internal object[] ListApps(RequestContext context) + { + var result = new List(); + foreach (var entry in Discover(context)) + { + context.Check(); + try + { + using var owner = Owner(entry, false, context); + entry.Window.Geometry(owner, context); + result.Add(new { pid = 4, name = owner.Authorization.Name, id = entry.Selector }); + } + catch (NativeFailure error) when (error.Code is "STALE_APP" or "PERMISSION_DENIED" or "APP_IDENTITY_UNAVAILABLE" or "UNSUPPORTED_SESSION" or "WINDOW_CHANGED") + { + // A disappearing window cannot remain selectable from this connection. + windows.Remove(entry.Window.Handle); + } + } + return result.ToArray(); + } + + internal AppState Select(string selector, RequestContext context) + { + if (string.IsNullOrEmpty(selector)) throw new NativeFailure("INVALID_ARGUMENT", "A window selector from listApps is required"); + Discover(context); + var entry = windows.Values.SingleOrDefault(value => string.Equals(value.Selector, selector, StringComparison.Ordinal)) + ?? throw new NativeFailure("WINDOW_CHANGED", "Discover applications again; this window selector belongs to another connection or an expired window"); + var app = Owner(entry, true, context); + try { entry.Window.Geometry(app, context); return app; } + catch { app.Dispose(); throw; } + } + + private List Discover(RequestContext context) + { + var current = new List(); + Win32.EnumWindows((handle, _) => + { + var extended = Win32.GetWindowLongPtr(handle, -20).ToInt64(); + if (Win32.IsWindowVisible(handle) && (extended & 0x80) == 0 + && Win32.GetWindowRect(handle, out var bounds) && bounds.Width > 0 && bounds.Height > 0) + current.Add(handle); + return true; + }, 0); + var result = new List(); + foreach (var handle in current) + { + context.Check(); + try + { + Win32.GetWindowThreadProcessId(handle, out var pid); + var process = Applications.Running(checked((int)pid)); + var epoch = context.Sta.WindowEpoch(handle); + if (!windows.TryGetValue(handle, out var entry) || entry.Process.Pid != process.Pid + || entry.Process.Started != process.Started || entry.Window.Epoch != epoch) + { + if (nextId == uint.MaxValue) throw new NativeFailure("NATIVE_LIMIT", "Reconnect before discovering more windows"); + entry = new(new(++nextId, handle, epoch), process, Guid.NewGuid().ToString("N")); + windows[handle] = entry; + } + using var owner = Owner(entry, false, context); + entry.Window.Geometry(owner, context); + result.Add(entry); + } + catch (NativeFailure error) when (error.Code is "STALE_APP" or "PERMISSION_DENIED" or "APP_IDENTITY_UNAVAILABLE" or "UNSUPPORTED_SESSION" or "WINDOW_CHANGED") + { + // A disappearing or inaccessible window cannot be selected from this discovery. + windows.Remove(handle); + } + } + foreach (var handle in windows.Keys.Where(handle => !current.Contains(handle)).ToArray()) windows.Remove(handle); + return result; + } + + private static AppState Owner(DiscoveredWindow entry, bool authorize, RequestContext context) + { + var window = entry.Window; + var process = entry.Process; + var length = Win32.GetWindowTextLength(window.Handle); + if (length > context.Config.MaxResponseBytes) throw new NativeFailure("NATIVE_RESPONSE_LIMIT", "Window title exceeds the response limit"); + var title = new StringBuilder(length + 1); + Win32.GetWindowText(window.Handle, title, title.Capacity); + var name = $"Window: {title} ({process.Name})"; + var id = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes( + $"window\0{process.Pid}\0{process.Started}\0{window.Handle}\0{window.Epoch}"))); + var identity = new ApplicationIdentity(id, name, process.Path, false); + var app = new AppState(Guid.NewGuid().ToString("N"), identity, "", process); + if (authorize) + { + var selected = new WindowState(window.Id, window.Handle, window.Epoch); + app.SelectedWindow = selected; + app.Windows.Add(window.Handle, selected); + } + return app; + } +} diff --git a/packages/experimental/cua-windows/native/src/Dispatchers.cs b/packages/experimental/cua-windows/native/src/Dispatchers.cs new file mode 100644 index 0000000000..3bc7785457 --- /dev/null +++ b/packages/experimental/cua-windows/native/src/Dispatchers.cs @@ -0,0 +1,178 @@ +// UI Automation and clipboard COM objects each stay on their owning apartment. +using System.Collections.Concurrent; +using System.Runtime.InteropServices; +using System.Text.Json; +using DeepSeek.Cua.Protocol; +using Forms = System.Windows.Forms; +using Timer = System.Threading.Timer; + +namespace DeepSeek.Cua.Windows; + +internal sealed record NativeConfig(int MaxRequestBytes, int MaxResponseBytes, int AxTimeoutMs, + double TextEventIntervalMs, int ScreenshotTimeoutMs, int TimeoutMs, int GraceMs, int PollIntervalMs, int MaxClickHoldMs) +{ + internal static NativeConfig Parse(JsonElement value) + { + string[] fields = ["maxRequestBytes", "maxResponseBytes", "axTimeoutMs", "textEventIntervalMs", "screenshotTimeoutMs", "timeoutMs", "graceMs", "pollIntervalMs", "maxClickHoldMs"]; + if (value.ValueKind != JsonValueKind.Object || value.EnumerateObject().Any(item => !fields.Contains(item.Name)) + || fields.Any(field => !value.TryGetProperty(field, out _))) throw new NativeFailure("INVALID_CONFIG", "Expected explicit native resource limits"); + int Positive(string field) + { + if (!value.GetProperty(field).TryGetInt32(out var number) || number <= 0) throw new NativeFailure("INVALID_CONFIG", field + " must be a positive Int32"); + return number; + } + var interval = value.GetProperty("textEventIntervalMs").GetDouble(); + if (!double.IsFinite(interval) || interval < 0 || interval > 1000) throw new NativeFailure("INVALID_CONFIG", "Invalid text event interval"); + return new(Positive("maxRequestBytes"), Positive("maxResponseBytes"), Positive("axTimeoutMs"), interval, + Positive("screenshotTimeoutMs"), Positive("timeoutMs"), Positive("graceMs"), Positive("pollIntervalMs"), Positive("maxClickHoldMs")); + } +} + +internal sealed class MtaDispatcher : IAsyncDisposable +{ + private readonly BlockingCollection queue = new(); + private readonly TaskCompletionSource stopped = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource ready = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly Thread thread; + + internal MtaDispatcher() + { + thread = new Thread(() => + { + var initialized = false; + try + { + Marshal.ThrowExceptionForHR(Win32.RoInitialize(1)); + initialized = true; + Win32.SetThreadDpiAwarenessContext(-4); + ready.SetResult(); + foreach (var work in queue.GetConsumingEnumerable()) work(); + } + catch (Exception error) { ready.TrySetException(error); } + finally { if (initialized) Win32.RoUninitialize(); stopped.TrySetResult(); } + }) { IsBackground = true, Name = "dsh-cua-uia" }; + thread.SetApartmentState(ApartmentState.MTA); + thread.Start(); + } + + internal async Task Invoke(Func work, CancellationToken cancellation) + { + await ready.Task.WaitAsync(cancellation); + var result = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + queue.Add(() => + { + try { cancellation.ThrowIfCancellationRequested(); var value = work(); cancellation.ThrowIfCancellationRequested(); result.TrySetResult(value); } + catch (OperationCanceledException) { result.TrySetCanceled(cancellation); } + catch (Exception error) { result.TrySetException(error); } + }); + return await result.Task; + } + + public async ValueTask DisposeAsync() + { + queue.CompleteAdding(); + await stopped.Task; + queue.Dispose(); + } +} + +internal sealed class ServiceControl : Forms.Control +{ + internal Func? ClipboardMessage; + protected override Forms.CreateParams CreateParams + { + get { var value = base.CreateParams; value.Parent = -3; return value; } + } + protected override void WndProc(ref Forms.Message message) + { + if (ClipboardMessage?.Invoke(message.Msg, message.WParam) == true) return; + base.WndProc(ref message); + } +} + +internal sealed class StaDispatcher : IAsyncDisposable +{ + private readonly TaskCompletionSource ready = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource stopped = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly ConcurrentDictionary epochs = new(); + private readonly Thread thread; + private Win32.WinEvent? windowEvents; + + internal StaDispatcher() + { + thread = new Thread(() => + { + nint hook = 0; + try + { + Win32.SetThreadDpiAwarenessContext(-4); + using var control = new ServiceControl(); + _ = control.Handle; + windowEvents = (_, eventType, window, objectId, childId, _, _) => + { + if (eventType == 0x8001 && objectId == 0 && childId == 0 && epochs.TryGetValue(window, out var epoch)) + epochs.TryUpdate(window, epoch + 1, epoch); + }; + hook = Win32.SetWinEventHook(0x8001, 0x8001, 0, windowEvents, 0, 0, 0); + if (hook == 0) throw new NativeFailure("NATIVE_STARTUP", "Window lifecycle observation could not start"); + ready.SetResult(control); + Forms.Application.Run(); + } + catch (Exception error) { ready.TrySetException(error); } + finally + { + if (hook != 0) Win32.UnhookWinEvent(hook); + stopped.TrySetResult(); + } + }) { IsBackground = true, Name = "dsh-cua-clipboard" }; + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); + } + + internal long WindowEpoch(nint window) => epochs.GetOrAdd(window, 0); + + internal async Task Invoke(Func work, CancellationToken cancellation) + { + var control = await ready.Task.WaitAsync(cancellation); + var result = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + control.BeginInvoke(() => + { + try { cancellation.ThrowIfCancellationRequested(); var value = work(control); result.TrySetResult(value); } + catch (OperationCanceledException) { result.TrySetCanceled(cancellation); } + catch (Exception error) { result.TrySetException(error); } + }); + return await result.Task; + } + + internal Task Invoke(Action work, CancellationToken cancellation) => Invoke(_ => { work(); return true; }, cancellation); + + public async ValueTask DisposeAsync() + { + try { await ready.Task; } + catch (Exception error) { _ = error; await stopped.Task; return; } + await Invoke(() => Forms.Application.ExitThread(), CancellationToken.None); + await stopped.Task; + } +} + +internal sealed class RequestContext(NativeConfig config, CancellationToken cancellation, MtaDispatcher mta, StaDispatcher sta) +{ + internal NativeConfig Config { get; } = config; + internal CancellationToken Cancellation { get; } = cancellation; + internal MtaDispatcher Mta { get; } = mta; + internal StaDispatcher Sta { get; } = sta; + internal void Check() => Cancellation.ThrowIfCancellationRequested(); + + internal T Ax(Func call) + { + Check(); + var completed = 0; + using var timer = new Timer(_ => + { + if (Interlocked.Exchange(ref completed, 1) == 0) + NativeServer.Fatal("AX_TIMEOUT", "A Windows accessibility call did not return within its configured deadline"); + }, null, Config.AxTimeoutMs, Timeout.Infinite); + try { var result = call(); Cancellation.ThrowIfCancellationRequested(); return result; } + finally { Interlocked.Exchange(ref completed, 1); } + } +} diff --git a/packages/experimental/cua-windows/native/src/GlobalUsings.cs b/packages/experimental/cua-windows/native/src/GlobalUsings.cs new file mode 100644 index 0000000000..30f1415d24 --- /dev/null +++ b/packages/experimental/cua-windows/native/src/GlobalUsings.cs @@ -0,0 +1 @@ +global using System.IO; diff --git a/packages/experimental/cua-windows/native/src/Input.cs b/packages/experimental/cua-windows/native/src/Input.cs new file mode 100644 index 0000000000..ec6570591d --- /dev/null +++ b/packages/experimental/cua-windows/native/src/Input.cs @@ -0,0 +1,263 @@ +// Global key and pointer injection requires an explicitly foregrounded target. +using System.Runtime.InteropServices; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal static class Input +{ + private static readonly int[] ModifierKeys = [0x10, 0x11, 0x12, 0x5B, 0x5C]; + private static ushort Modifier(string name) => name switch + { + "shift" => 0x10, "control" => 0x11, "option" => 0x12, + "command" => throw new NativeFailure("UNSUPPORTED", "Windows-key shortcuts act outside the selected application; use Control for application shortcuts"), + "fn" => throw new NativeFailure("UNSUPPORTED", "Windows does not expose a portable Fn input event"), + _ => throw new NativeFailure("INVALID_ARGUMENT", "Unknown key modifier"), + }; + private static Win32.Input Keyboard(ushort key, ushort scan = 0, uint flags = 0) => new() + { Type = 1, Data = new() { Keyboard = new() { Key = key, Scan = scan, Flags = flags } } }; + private static Win32.Input Mouse(uint flags, int x = 0, int y = 0, uint data = 0) => new() + { Type = 0, Data = new() { Mouse = new() { X = x, Y = y, Data = data, Flags = flags } } }; + + private static void Send(params Win32.Input[] events) + { + if (Win32.SendInput((uint)events.Length, events, Marshal.SizeOf()) != events.Length) + throw new NativeFailure("INPUT_BLOCKED", "Windows did not dispatch all input; privileges or user input may have intervened. Observe before retrying"); + } + + private static void Release(Win32.Input input) => Win32.SendInput(1, [input], Marshal.SizeOf()); + + private static void RequireIdleModifiers() + { + if (ModifierKeys.Concat([0x01, 0x02, 0x04, 0x05, 0x06]).Any(key => (Win32.GetAsyncKeyState(key) & 0x8000) != 0)) + throw new NativeFailure("INPUT_BUSY", "A modifier or mouse button is already held; wait for the user to release it before sending input"); + } + + private static void WithModifiers(IEnumerable modifiers, Action action) + { + var keys = modifiers.Select(KeyChord.NormalizeModifier).Select(Modifier).Distinct().ToArray(); + RequireIdleModifiers(); + var attempted = new List(); + try + { + foreach (var key in keys) { attempted.Add(key); Send(Keyboard(key, flags: key == 0x5B ? 1u : 0)); } + action(); + } + finally { foreach (var key in attempted.AsEnumerable().Reverse()) Release(Keyboard(key, flags: 2u | (key == 0x5B ? 1u : 0))); } + } + + private static (ushort Key, bool Extended, string[] Modifiers) ResolveKey(string name, AppState app) + { + var key = name.ToLowerInvariant(); + if (key.StartsWith("kp_", StringComparison.Ordinal)) + { + var keypad = key[3..]; + if (keypad.Length == 1 && char.IsAsciiDigit(keypad[0])) return ((ushort)(0x60 + keypad[0] - '0'), false, []); + return keypad switch + { + "enter" => (0x0D, true, []), "add" or "plus" => (0x6B, false, []), "subtract" or "minus" => (0x6D, false, []), + "multiply" => (0x6A, false, []), "divide" => (0x6F, true, []), "decimal" or "period" => (0x6E, false, []), + _ => throw new NativeFailure("UNSUPPORTED", "Unknown numeric-keypad key"), + }; + } + if (key.Length > 1 && key[0] == 'f' && int.TryParse(key[1..], out var function) && function is >= 1 and <= 24) + return ((ushort)(0x70 + function - 1), false, []); + ushort named = key switch + { + "enter" or "return" => 0x0D, "tab" => 0x09, "escape" or "esc" => 0x1B, "backspace" => 0x08, + "delete" or "forwarddelete" => 0x2E, "insert" => 0x2D, "home" => 0x24, "end" => 0x23, + "pageup" => 0x21, "pagedown" => 0x22, "left" or "arrowleft" => 0x25, "up" or "arrowup" => 0x26, + "right" or "arrowright" => 0x27, "down" or "arrowdown" => 0x28, "space" => 0x20, + "capslock" => 0x14, "numlock" => 0x90, "scrolllock" => 0x91, "printscreen" => 0x2C, + _ => 0, + }; + if (named != 0) return (named, named is >= 0x21 and <= 0x2E || named == 0x90, []); + var character = key == "plus" ? '+' : name.Length == 1 ? char.IsAsciiLetter(name[0]) ? char.ToLowerInvariant(name[0]) : name[0] : '\0'; + if (character == '\0') throw new NativeFailure("UNSUPPORTED", "Unknown key name; use typeText for text input"); + var foreground = Win32.GetForegroundWindow(); + var thread = Win32.GetWindowThreadProcessId(foreground, out _); + var mapped = Win32.VkKeyScanEx(character, Win32.GetKeyboardLayout(thread)); + if (mapped == -1) throw new NativeFailure("UNSUPPORTED", "This character has no key in the target keyboard layout; use typeText"); + var modifiers = new List(); + if ((mapped & 0x100) != 0) modifiers.Add("shift"); + if ((mapped & 0x200) != 0) modifiers.Add("control"); + if ((mapped & 0x400) != 0) modifiers.Add("option"); + return ((ushort)(mapped & 0xFF), false, modifiers.ToArray()); + } + + internal static void Press(AppState app, string key, string[] modifiers, RequestContext context) + { + Windows.RequireForeground(app, null, context); + var chord = new KeyChord(key, modifiers.Select(KeyChord.NormalizeModifier).Distinct().ToArray()); + var name = chord.Key.ToLowerInvariant(); + if (name == "printscreen" || chord.Modifiers.Contains("option") && name is "tab" or "escape" or "esc" + || chord.Modifiers.Contains("control") && name is "escape" or "esc" + || chord.Modifiers.Contains("control") && chord.Modifiers.Contains("option") && name == "delete") + throw new NativeFailure("UNSUPPORTED", "This shortcut acts on the system rather than the selected application"); + var resolved = ResolveKey(chord.Key, app); + WithModifiers(chord.Modifiers.Concat(resolved.Modifiers), () => + { + Windows.RequireForeground(app, null, context); + var flags = resolved.Extended ? 1u : 0; + try { Send(Keyboard(resolved.Key, flags: flags), Keyboard(resolved.Key, flags: flags | 2)); } + catch { Release(Keyboard(resolved.Key, flags: flags | 2)); throw; } + }); + } + + internal static async Task Type(AppState app, string text, RequestContext context) + { + if (text.Contains('\0')) throw new NativeFailure("INVALID_ARGUMENT", "Text input cannot contain NUL"); + RequireIdleModifiers(); + for (var index = 0; index < text.Length; index++) + { + Windows.RequireForeground(app, null, context); + RequireIdleModifiers(); + var character = text[index]; + if (character is '\r' or '\n' or '\t') + { + if (character == '\r' && index + 1 < text.Length && text[index + 1] == '\n') index++; + Press(app, character == '\t' ? "Tab" : "Enter", [], context); + } + else + { + try { Send(Keyboard(0, character, 4), Keyboard(0, character, 6)); } + catch { Release(Keyboard(0, character, 6)); throw; } + } + if (context.Config.TextEventIntervalMs > 0) + await Task.Delay(TimeSpan.FromMilliseconds(context.Config.TextEventIntervalMs * 2), context.Cancellation); + } + } + + private static Win32.Input Move(Win32.Point point) + { + int left = Win32.GetSystemMetrics(76), top = Win32.GetSystemMetrics(77); + int width = Win32.GetSystemMetrics(78), height = Win32.GetSystemMetrics(79); + if (width <= 1 || height <= 1) throw new NativeFailure("SESSION_LOCKED", "The virtual desktop has no usable bounds"); + return Mouse(0x8000 | 0x4000 | 0x0001, + (int)Math.Round((point.X - left) * 65535d / (width - 1)), (int)Math.Round((point.Y - top) * 65535d / (height - 1))); + } + + private static (uint Down, uint Up) Button(string button) => button switch + { + "left" => (0x0002, 0x0004), "right" => (0x0008, 0x0010), "middle" => (0x0020, 0x0040), + _ => throw new NativeFailure("INVALID_ARGUMENT", "Unknown mouse button"), + }; + + private static void Hit(AppState app, WindowState window, Win32.Point point, RequestContext context) + { + Windows.RequireForeground(app, window, context); + if (Win32.GetAncestor(Win32.WindowFromPoint(point), 2) != window.Handle) + throw new NativeFailure("WINDOW_OBSCURED", "Another window covers the target coordinate; restore or raise the selected window and observe again"); + } + + internal static object MouseMove(AppState app, WindowState window, double x, double y, RequestContext context) + { + var point = WindowState.Point(window.RequireObservation(app, context), x, y); + Hit(app, window, point, context); + RequireIdleModifiers(); + if (!Win32.GetCursorPos(out var before)) throw new NativeFailure("INPUT_UNAVAILABLE", "The current pointer position is unavailable"); + Send(Move(point)); + return new { dispatched = true, hoverRoute = "system-pointer", systemPointerMoved = before.X != point.X || before.Y != point.Y }; + } + + internal static void Click(AppState app, WindowState window, double x, double y, string button, int count, string[] modifiers, RequestContext context) + { + if (button != "left" && count != 1) throw new NativeFailure("UNSUPPORTED", "Only left clicks support double-click"); + var geometry = window.RequireObservation(app, context); + var point = WindowState.Point(geometry, x, y); + var flags = Button(button); + Hit(app, window, point, context); + WithModifiers(modifiers, () => + { + point = WindowState.Point(window.RequireObservation(app, context), x, y); + Hit(app, window, point, context); + var events = new List { Move(point) }; + for (var click = 0; click < count; click++) { events.Add(Mouse(flags.Down)); events.Add(Mouse(flags.Up)); } + try { Send(events.ToArray()); } catch { Release(Mouse(flags.Up)); throw; } + }); + } + + internal static async Task HoldClick(AppState app, WindowState window, double x, double y, string button, int count, string[] modifiers, int holdMs, RequestContext context) + { + if (button != "left" && count != 1) throw new NativeFailure("UNSUPPORTED", "Only left clicks support double-click"); + var point = WindowState.Point(window.RequireObservation(app, context), x, y); + var flags = Button(button); + var keys = modifiers.Select(KeyChord.NormalizeModifier).Select(Modifier).Distinct().ToArray(); + Hit(app, window, point, context); + RequireIdleModifiers(); + var attempted = new List(); + var buttonAttempted = false; + try + { + foreach (var key in keys) { attempted.Add(key); Send(Keyboard(key)); } + point = WindowState.Point(window.RequireObservation(app, context), x, y); + Hit(app, window, point, context); + Send(Move(point)); + for (var click = 0; click < count; click++) + { + Hit(app, window, point, context); + buttonAttempted = true; + Send(Mouse(flags.Down)); + await Task.Delay(holdMs, context.Cancellation); + Windows.RequireForeground(app, window, context); + Send(Mouse(flags.Up)); + buttonAttempted = false; + } + } + finally + { + if (buttonAttempted) Release(Mouse(flags.Up)); + foreach (var key in attempted.AsEnumerable().Reverse()) Release(Keyboard(key, flags: 2)); + } + } + + internal static void Scroll(AppState app, WindowState window, double x, double y, int deltaX, int deltaY, RequestContext context) + { + var point = WindowState.Point(window.RequireObservation(app, context), x, y); + Hit(app, window, point, context); + RequireIdleModifiers(); + uint lines = 1, columns = 1; + if (deltaY != 0 && (!Win32.SystemParametersInfo(0x0068, 0, out lines, 0) || lines == uint.MaxValue || lines == 0) + || deltaX != 0 && (!Win32.SystemParametersInfo(0x006C, 0, out columns, 0) || columns == 0)) + throw new NativeFailure("UNSUPPORTED", "Windows wheel scrolling does not currently use line/character units"); + var events = new List { Move(point) }; + if (deltaY != 0) events.Add(Mouse(0x0800, data: unchecked((uint)(int)Math.Round(deltaY * 120d / lines)))); + if (deltaX != 0) events.Add(Mouse(0x1000, data: unchecked((uint)(int)Math.Round(-deltaX * 120d / columns)))); + Send(events.ToArray()); + } + + internal static async Task Drag(AppState app, WindowState window, double fromX, double fromY, double toX, double toY, + string button, string[] modifiers, int durationMs, int steps, RequestContext context) + { + var geometry = window.RequireObservation(app, context); + var from = WindowState.Point(geometry, fromX, fromY); + _ = WindowState.Point(geometry, toX, toY); + Hit(app, window, from, context); + var flags = Button(button); + var keys = modifiers.Select(KeyChord.NormalizeModifier).Select(Modifier).Distinct().ToArray(); + RequireIdleModifiers(); + var attempted = new List(); + var buttonAttempted = false; + try + { + foreach (var key in keys) { attempted.Add(key); Send(Keyboard(key, flags: key == 0x5B ? 1u : 0)); } + geometry = window.RequireObservation(app, context); + from = WindowState.Point(geometry, fromX, fromY); + Hit(app, window, from, context); + buttonAttempted = true; + Send(Move(from), Mouse(flags.Down)); + for (var step = 1; step <= steps; step++) + { + await Task.Delay(TimeSpan.FromMilliseconds(durationMs / (double)steps), context.Cancellation); + geometry = window.RequireObservation(app, context); + Windows.RequireForeground(app, window, context); + Send(Move(WindowState.Point(geometry, fromX + (toX - fromX) * step / steps, fromY + (toY - fromY) * step / steps))); + } + } + finally + { + if (buttonAttempted) Release(Mouse(flags.Up)); + foreach (var key in attempted.AsEnumerable().Reverse()) Release(Keyboard(key, flags: 2u | (key == 0x5B ? 1u : 0))); + } + } +} diff --git a/packages/experimental/cua-windows/native/src/LaunchEntries.cs b/packages/experimental/cua-windows/native/src/LaunchEntries.cs new file mode 100644 index 0000000000..cc97dfd8bf --- /dev/null +++ b/packages/experimental/cua-windows/native/src/LaunchEntries.cs @@ -0,0 +1,88 @@ +// Shell namespace enumeration and activation run on the existing STA dispatcher. +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal sealed record LaunchEntry(string Id, string DisplayName, string Kind, string? Path); +internal sealed class PreparedLaunch(LaunchEntry entry, ApplicationIdentity authorization, string? digest) +{ + internal string Handle { get; } = Guid.NewGuid().ToString("N"); + internal ApplicationIdentity Authorization { get; } = authorization; + private bool dispatched; + + internal void Dispatch() + { + if (dispatched) throw new NativeFailure("LAUNCH_ALREADY_DISPATCHED", "Discover windows before deciding whether another launch is needed"); + if (entry.Kind == "executable") + { + if (Applications.CanonicalPath(entry.Id) != entry.Id || Applications.Digest(entry.Id) != digest) + throw new NativeFailure("STALE_APP", "The approved executable changed; select it again"); + } + else if (!LaunchEntries.All().Any(current => current.Id == entry.Id)) + throw new NativeFailure("STALE_APP", "The Shell entry disappeared; discover launch entries again"); + // Dispatch may succeed even if Explorer subsequently reports a failure. Never replay this selection. + dispatched = true; + ShellBroker.Launch(entry.Id, show: 1); + } +} + +internal static class LaunchEntries +{ + internal static LaunchEntry[] All() + { + var owned = new List(); + object Own(object value) { owned.Add(value); return value; } + try + { + dynamic shell = Own(Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("13709620-C279-11CE-A49E-444553540000"), true)!)!); + dynamic folder = Own((object)shell.NameSpace("shell:AppsFolder")); + dynamic items = Own((object)folder.Items()); + var result = new List(); + for (var index = 0; index < (int)items.Count; index++) + { + dynamic item = Own((object)items.Item(index)); + string parsingName = item.Path; + string name = item.Name; + if (string.IsNullOrWhiteSpace(parsingName) || string.IsNullOrWhiteSpace(name)) continue; + var target = parsingName.StartsWith("::", StringComparison.Ordinal) ? parsingName : "shell:AppsFolder\\" + parsingName; + result.Add(new(target, name, "shell", null)); + } + return result.DistinctBy(entry => entry.Id, StringComparer.OrdinalIgnoreCase).ToArray(); + } + catch (Exception error) when (error is COMException or Microsoft.CSharp.RuntimeBinder.RuntimeBinderException) + { + throw new NativeFailure("APP_DISCOVERY_FAILED", "Windows Shell could not enumerate AppsFolder; retry discovery after Explorer is available"); + } + finally + { + foreach (var item in owned.AsEnumerable().Reverse()) + if (Marshal.IsComObject(item)) Marshal.ReleaseComObject(item); + } + } + + internal static LaunchEntry[] Find(string query, int maximum) + { + var matches = All().Where(entry => entry.DisplayName.Contains(query, StringComparison.OrdinalIgnoreCase) + || entry.Id.Contains(query, StringComparison.OrdinalIgnoreCase)).OrderBy(entry => entry.DisplayName, StringComparer.OrdinalIgnoreCase).ToArray(); + if (matches.Length > maximum) throw new NativeFailure("TOO_MANY_APPS", "Use a more specific launch entry name"); + return matches; + } + + internal static PreparedLaunch Prepare(string target) + { + if (Path.IsPathFullyQualified(target) && target.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) + { + var path = Applications.CanonicalPath(target); + var name = Path.GetFileNameWithoutExtension(path); + var identity = Applications.Identify(path, "Launch: " + name, null); + return new(new(path, name, "executable", path), identity.Identity with { Persistable = false }, identity.Digest); + } + var shell = All().SingleOrDefault(entry => string.Equals(entry.Id, target, StringComparison.OrdinalIgnoreCase)) + ?? throw new NativeFailure("APP_NOT_FOUND", "Use an ID from findApps or a user-specified absolute executable path"); + var id = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes("launch\0" + shell.Id))); + return new(shell, new(id, "Launch: " + shell.DisplayName, shell.Id, false), null); + } +} diff --git a/packages/experimental/cua-windows/native/src/NativeServer.cs b/packages/experimental/cua-windows/native/src/NativeServer.cs new file mode 100644 index 0000000000..866cc0588b --- /dev/null +++ b/packages/experimental/cua-windows/native/src/NativeServer.cs @@ -0,0 +1,196 @@ +// The per-user service serves isolated Agent connections and Host leases on a private named pipe. +using System.Collections.Concurrent; +using System.Diagnostics.CodeAnalysis; +using System.IO.Pipes; +using System.Security.Cryptography; +using System.Text.Json; +using System.Windows.Automation; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal static class NativeServer +{ + [DoesNotReturn] + internal static void Fatal(string code, string message) + { + Console.Error.WriteLine($"{code}: {message}; native handles are no longer usable"); + Environment.Exit(70); + throw new InvalidOperationException("Process exit returned"); + } + + internal static async Task Run(string instance, string expectedRuntime, int connectTimeoutMs, int graceMs) + { + if (!Guid.TryParseExact(instance, "N", out _)) throw new NativeFailure("INVALID_ARGUMENT", "A Host instance identifier is required"); + var executable = Environment.ProcessPath ?? throw new NativeFailure("NATIVE_STARTUP", "The executable identity is unavailable"); + using var source = File.OpenRead(executable); + var runtime = Convert.ToHexStringLower(SHA256.HashData(source)); + if (runtime != expectedRuntime) throw new NativeFailure("NATIVE_STARTUP", "The helper executable changed before startup"); + var pipeName = SharedRuntime.PipeName(runtime); + using var lifetime = new CancellationTokenSource(); + lifetime.CancelAfter(connectTimeoutMs); + await using var mta = new MtaDispatcher(); + await using var sta = new StaDispatcher(); + await sta.Invoke(() => { }, lifetime.Token); + await mta.Invoke(() => true, lifetime.Token); + await using var executor = new DesktopExecutor(mta, sta, graceMs); + var clients = new ConcurrentDictionary(); + NamedPipeServerStream? listener = NewPipe(pipeName); + var membership = new object(); + var connections = 0; + try + { + while (!lifetime.IsCancellationRequested) + { + await listener.WaitForConnectionAsync(lifetime.Token); + var connected = listener; + lock (membership) + { + lifetime.Token.ThrowIfCancellationRequested(); + connections++; + lifetime.CancelAfter(Timeout.Infinite); + } + listener = NewPipe(pipeName); + var task = Serve(connected, executor, instance, runtime, connectTimeoutMs, lifetime.Token); + clients.TryAdd(task, 0); + _ = task.ContinueWith(completed => + { + clients.TryRemove(completed, out _); + if (completed.IsFaulted) { _ = completed.Exception; Console.Error.WriteLine("NATIVE_CONNECTION: Connection cleanup failed"); } + lock (membership) { if (--connections == 0) lifetime.Cancel(); } + }, CancellationToken.None, + TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + } + } + catch (OperationCanceledException error) when (lifetime.IsCancellationRequested) { _ = error; /* Host shutdown cancels the pending read. */ } + finally + { + lifetime.Cancel(); + listener?.Dispose(); + await Task.WhenAll(clients.Keys); + } + } + + private static NamedPipeServerStream NewPipe(string name) => new(name, PipeDirection.InOut, + NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); + + private static async Task Serve(NamedPipeServerStream pipe, DesktopExecutor executor, + string instance, string runtime, int connectTimeoutMs, CancellationToken serverLifetime) + { + using (pipe) + using (var lifetime = CancellationTokenSource.CreateLinkedTokenSource(serverLifetime)) + using (var writer = new SemaphoreSlim(1)) + { + var state = new ClientState(); + Task? active = null; + CancellationTokenSource? cancellation = null; + string? latestRequestId = null; + var closeRequested = false; + var cleanupTimeoutMs = connectTimeoutMs; + try + { + var reader = new FrameReader(pipe); + string? line; + using (var greeting = CancellationTokenSource.CreateLinkedTokenSource(lifetime.Token)) + { + greeting.CancelAfter(connectTimeoutMs); + line = await reader.ReadAsync(8192, greeting.Token) ?? throw new NativeFailure("INVALID_REQUEST", "A native hello is required"); + } + var hello = WireJson.Parse(line); + if (hello.ValueKind == JsonValueKind.Object && hello.EnumerateObject().Select(item => item.Name).Order().SequenceEqual(["runtimeKey", "type"]) + && hello.GetProperty("type").GetString() == "lease" && hello.GetProperty("runtimeKey").GetString() == runtime) + { + await Write(pipe, writer, new { type = "ready", protocol = 1, runtimeKey = runtime, pid = Environment.ProcessId, instanceId = instance }, + 8192, connectTimeoutMs, lifetime.Token); + if (await reader.ReadAsync(8192, lifetime.Token) is not null) throw new NativeFailure("INVALID_REQUEST", "A service lease cannot send desktop operations"); + return; + } + if (hello.ValueKind != JsonValueKind.Object || hello.EnumerateObject().Select(item => item.Name).Order().SequenceEqual(["config", "protocol", "runtimeKey", "type"]) == false + || hello.GetProperty("type").GetString() != "hello" || hello.GetProperty("protocol").GetInt32() != 1 || hello.GetProperty("runtimeKey").GetString() != runtime) + throw new NativeFailure("INVALID_REQUEST", "The native handshake did not match this helper"); + var config = NativeConfig.Parse(hello.GetProperty("config")); + cleanupTimeoutMs = config.GraceMs; + await Write(pipe, writer, new { type = "ready", protocol = 1, runtimeKey = runtime, pid = Environment.ProcessId, instanceId = instance }, 8192, config.GraceMs, lifetime.Token); + while ((line = await reader.ReadAsync(config.MaxRequestBytes, lifetime.Token)) is not null) + { + var value = WireJson.Parse(line); + if (value.ValueKind == JsonValueKind.Object && value.TryGetProperty("type", out _)) + { + var control = NativeControlFrame.Parse(value, latestRequestId, active?.IsCompleted != false); + if (control == NativeControl.Close) { closeRequested = true; break; } + if (control == NativeControl.Cancel) cancellation!.Cancel(); + continue; + } + var request = NativeRequest.Parse(value); + if (active is { IsCompleted: false }) throw new NativeFailure("NATIVE_BUSY", "Native requests must be sequential"); + if (active is not null) await active; + cancellation?.Dispose(); + cancellation = CancellationTokenSource.CreateLinkedTokenSource(lifetime.Token); + cancellation.CancelAfter(request.Method == "screenshot" ? Math.Min(config.TimeoutMs, config.ScreenshotTimeoutMs) : config.TimeoutMs); + latestRequestId = request.Id; + active = Dispatch(request, state, executor, config, pipe, writer, cancellation.Token, lifetime.Token); + } + } + catch (Exception error) + { + if (error is not (IOException or OperationCanceledException)) Console.Error.WriteLine($"NATIVE_CONNECTION: {error.GetType().Name}"); + } + finally + { + lifetime.Cancel(); + cancellation?.Cancel(); + if (active is not null) + { + try { await active; } + catch (Exception error) { Console.Error.WriteLine($"NATIVE_CONNECTION: {error.GetType().Name}"); } + } + cancellation?.Dispose(); + state.Clear(); + if (closeRequested) + await Write(pipe, writer, new { type = "closed" }, 8192, cleanupTimeoutMs, CancellationToken.None); + } + } + } + + private static async Task Dispatch(NativeRequest request, ClientState state, DesktopExecutor executor, NativeConfig config, + Stream pipe, SemaphoreSlim writer, CancellationToken cancellation, CancellationToken connection) + { + var operation = executor.Execute(request, state, config, cancellation); + using var monitorStop = CancellationTokenSource.CreateLinkedTokenSource(cancellation); + var monitor = WatchOperation(operation, monitorStop.Token, config.GraceMs); + object response; + try { response = new { id = request.Id, result = await operation }; } + catch (OperationCanceledException) { response = Failure(request.Id, "NATIVE_CANCELLED", "Native operation cancelled; observe before deciding on further input"); } + catch (NativeFailure error) { response = Failure(request.Id, error.Code, error.Message); } + catch (ElementNotAvailableException) { response = Failure(request.Id, "STALE_SNAPSHOT", "An accessibility element disappeared; read fresh state"); } + catch (ElementNotEnabledException) { response = Failure(request.Id, "ELEMENT_DISABLED", "The selected control is disabled"); } + catch (UnauthorizedAccessException) { response = Failure(request.Id, "PERMISSION_DENIED", "Windows refused access to the selected application"); } + catch (Exception error) { response = Failure(request.Id, "NATIVE_OPERATION", $"Windows operation failed (0x{error.HResult:X8}); observe before retrying"); } + finally { monitorStop.Cancel(); await monitor; } + var bytes = JsonSerializer.SerializeToUtf8Bytes(response, WireJson.Options); + if (bytes.Length + 1 > config.MaxResponseBytes) response = Failure(request.Id, "NATIVE_RESPONSE_LIMIT", "Native response exceeded its configured byte limit"); + await Write(pipe, writer, response, config.MaxResponseBytes, config.GraceMs, connection); + } + + private static object Failure(string id, string code, string message) => new { id, error = new { code, message } }; + + private static async Task WatchOperation(Task operation, CancellationToken cancellation, int graceMs) + { + await Task.WhenAny(operation, Task.Delay(Timeout.Infinite, cancellation)); + if (operation.IsCompleted) return; + try { await operation.WaitAsync(TimeSpan.FromMilliseconds(graceMs)); } + catch (TimeoutException) { Fatal("NATIVE_CLEANUP", "A cancelled desktop operation did not stop before the grace deadline"); } + catch (Exception error) when (operation.IsCompleted) { _ = error; /* Dispatch owns the operation result. */ } + } + + private static async Task Write(Stream pipe, SemaphoreSlim writer, object value, int maximum, int timeoutMs, CancellationToken cancellation) + { + var bytes = JsonSerializer.SerializeToUtf8Bytes(value, WireJson.Options); + if (bytes.Length + 1 > maximum) throw new NativeFailure("NATIVE_RESPONSE_LIMIT", "The native frame exceeds its byte limit"); + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellation); + deadline.CancelAfter(timeoutMs); + await writer.WaitAsync(deadline.Token); + try { await pipe.WriteAsync(bytes, deadline.Token); await pipe.WriteAsync("\n"u8.ToArray(), deadline.Token); await pipe.FlushAsync(deadline.Token); } + finally { writer.Release(); } + } +} diff --git a/packages/experimental/cua-windows/native/src/Program.cs b/packages/experimental/cua-windows/native/src/Program.cs new file mode 100644 index 0000000000..d46db4479c --- /dev/null +++ b/packages/experimental/cua-windows/native/src/Program.cs @@ -0,0 +1,35 @@ +// The executable is a private helper launched by the dsh Windows provider. +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal static class Program +{ + private static int Main(string[] args) + { + try + { + if (!OperatingSystem.IsWindowsVersionAtLeast(10, 0, 19041)) throw new NativeFailure("UNSUPPORTED", "Windows CUA requires Windows 10 build 19041 or later"); + var server = args.Length == 7 && args[0] == "--shared-server"; + var bridge = args.Length == 7 && args[0] == "--bridge"; + var connector = args.Length == 9 && args[0] == "--serve" && args[1] == "--instance-id" && Guid.TryParseExact(args[2], "N", out _); + var offset = server || bridge ? 1 : 3; + if ((!server && !connector && !bridge) || args[offset] != "--runtime-key" || args[offset + 2] != "--connect-timeout-ms" + || args[offset + 4] != "--grace-ms" + || !int.TryParse(args[offset + 3], out var connectTimeoutMs) || connectTimeoutMs <= 0 + || !int.TryParse(args[offset + 5], out var graceMs) || graceMs <= 0) + throw new NativeFailure("INVALID_ARGUMENT", "The helper must be launched by the dsh Windows provider"); + var runtime = Applications.Digest(Environment.ProcessPath!); + if (runtime != args[offset + 1]) throw new NativeFailure("NATIVE_STARTUP", "The helper executable changed before startup"); + if (server) SharedRuntime.Serve(runtime, connectTimeoutMs, graceMs); + else if (bridge) SharedRuntime.Bridge(runtime, connectTimeoutMs).GetAwaiter().GetResult(); + else SharedRuntime.Connect(args[2], runtime, connectTimeoutMs, graceMs).GetAwaiter().GetResult(); + return 0; + } + catch (Exception error) + { + Console.Error.WriteLine(error is NativeFailure failure ? $"{failure.Code}: {failure.Message}" : $"NATIVE_STARTUP: {error.Message}"); + return 1; + } + } +} diff --git a/packages/experimental/cua-windows/native/src/SharedRuntime.cs b/packages/experimental/cua-windows/native/src/SharedRuntime.cs new file mode 100644 index 0000000000..974adf160b --- /dev/null +++ b/packages/experimental/cua-windows/native/src/SharedRuntime.cs @@ -0,0 +1,110 @@ +// A managed Host connector leases an Explorer-launched service outside the Host's kill-on-close Job. +using System.Diagnostics; +using System.IO.Pipes; +using System.Runtime.InteropServices; +using System.Security.Principal; +using System.Text; +using System.Text.Json; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal static class SharedRuntime +{ + internal static string PipeName(string runtime) + { + using var identity = WindowsIdentity.GetCurrent(); + using var process = Process.GetCurrentProcess(); + var user = identity.User?.Value ?? throw new NativeFailure("NATIVE_STARTUP", "The Windows user identity is unavailable"); + var scope = Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(Encoding.UTF8.GetBytes($"{user}:{process.SessionId}"))); + return $"dsh-cua-{scope}-{runtime}"; + } + + internal static async Task Connect(string launcherId, string runtime, int timeoutMs, int graceMs) + { + using var deadline = new CancellationTokenSource(timeoutMs); + using var pipe = new NamedPipeClientStream(".", PipeName(runtime), PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); + try { pipe.Connect(0); } + catch (TimeoutException) + { + await using var sta = new StaDispatcher(); + var executable = Environment.ProcessPath!; + await sta.Invoke(() => ShellBroker.Launch(executable, + $"--shared-server --runtime-key {runtime} --connect-timeout-ms {timeoutMs} --grace-ms {graceMs}", 0), deadline.Token); + await pipe.ConnectAsync(deadline.Token); + } + var pid = VerifyServer(pipe, runtime); + var hello = JsonSerializer.SerializeToUtf8Bytes(new { type = "lease", runtimeKey = runtime }, WireJson.Options); + await pipe.WriteAsync(hello, deadline.Token); + await pipe.WriteAsync("\n"u8.ToArray(), deadline.Token); + var reader = new FrameReader(pipe); + var line = await reader.ReadAsync(8192, deadline.Token) + ?? throw new NativeFailure("NATIVE_EOF", "The shared service exited during connection"); + var ready = WireJson.Parse(line); + if (ready.GetProperty("runtimeKey").GetString() != runtime || ready.GetProperty("pid").GetInt32() != pid) + throw new NativeFailure("NATIVE_PROTOCOL", "The shared service returned a different process identity"); + Console.WriteLine(JsonSerializer.Serialize(new + { + type = "ready", protocol = 1, runtimeKey = runtime, pid, + instanceId = ready.GetProperty("instanceId").GetString(), launcherId, endpoint = @"\\.\pipe\" + PipeName(runtime), + }, WireJson.Options)); + await Console.Out.FlushAsync(); + // Console.In's synchronized reader can block before it returns an asynchronous result. + var parent = Task.Run(() => Console.In.ReadLine()); + var stopped = reader.ReadAsync(8192, CancellationToken.None); + if (await Task.WhenAny(parent, stopped) == stopped) + throw new NativeFailure("NATIVE_EXITED", "The shared desktop service stopped; select applications again"); + await parent; + } + + // Windows owns the named pipe; WSL forwards the unchanged protocol over standard streams. + internal static async Task Bridge(string runtime, int timeoutMs) + { + using var deadline = new CancellationTokenSource(timeoutMs); + using var pipe = new NamedPipeClientStream(".", PipeName(runtime), PipeDirection.InOut, + PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); + await pipe.ConnectAsync(deadline.Token); + VerifyServer(pipe, runtime); + using var input = Console.OpenStandardInput(); + using var output = Console.OpenStandardOutput(); + // Inherited standard-input handles can be synchronous; never block pipe output on their reads. + var upload = Task.Run(() => input.CopyToAsync(pipe)); + var download = pipe.CopyToAsync(output); + try + { + var completed = await Task.WhenAny(upload, download); + await completed; + await output.FlushAsync(); + } + finally + { + // Process exit ends a pending synchronous stdin read; it must not delay pipe cleanup. + pipe.Dispose(); + } + } + + private static uint VerifyServer(NamedPipeClientStream pipe, string runtime) + { + if (!GetNamedPipeServerProcessId(pipe.SafePipeHandle, out var pid)) + throw new NativeFailure("NATIVE_PROTOCOL", "The Windows pipe server identity is unavailable"); + var server = Applications.Running(checked((int)pid)); + if (Applications.Digest(server.Path) != runtime) + throw new NativeFailure("NATIVE_PROTOCOL", "The Windows pipe belongs to another executable"); + return pid; + } + + internal static void Serve(string runtime, int timeoutMs, int graceMs) + { + using var mutex = new Mutex(false, PipeName(runtime), new NamedWaitHandleOptions { CurrentUserOnly = true, CurrentSessionOnly = true }); + bool acquired; + try { acquired = mutex.WaitOne(0); } + catch (AbandonedMutexException) { acquired = true; } + if (!acquired) return; + try { NativeServer.Run(Guid.NewGuid().ToString("N"), runtime, timeoutMs, graceMs).GetAwaiter().GetResult(); } + finally { mutex.ReleaseMutex(); } + } + + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetNamedPipeServerProcessId(Microsoft.Win32.SafeHandles.SafePipeHandle pipe, out uint serverProcessId); +} diff --git a/packages/experimental/cua-windows/native/src/ShellBroker.cs b/packages/experimental/cua-windows/native/src/ShellBroker.cs new file mode 100644 index 0000000000..291833ac1c --- /dev/null +++ b/packages/experimental/cua-windows/native/src/ShellBroker.cs @@ -0,0 +1,111 @@ +// Explorer owns user-launched applications, independently of the helper's managed process Job. +using System.Reflection; +using System.Runtime.InteropServices; +using System.Runtime.InteropServices.ComTypes; +using System.Text; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal static class ShellBroker +{ + internal static void Launch(string path, string arguments = "", int show = 4) + { + var owned = new List(); + T Own(T value) where T : class { owned.Add(value); return value; } + try + { + dynamic windows = Own(Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("9BA05972-F6A8-11CF-A442-00A0C90A8F39"), true)!)!); + object location = 0, root = null!; + int handle; + object desktop = Own((object)windows.FindWindowSW(ref location, ref root, 8, out handle, 1)); + var service = new Guid("4C96BE40-915C-11CF-99D3-00AA004AE837"); + var browserId = typeof(IShellBrowser).GUID; + Marshal.ThrowExceptionForHR(((IServiceProvider)desktop).QueryService(ref service, ref browserId, out var rawBrowser)); + var browser = (IShellBrowser)Own(rawBrowser); + Marshal.ThrowExceptionForHR(browser.QueryActiveShellView(out var view)); + Own(view); + var dispatchId = new Guid("00020400-0000-0000-C000-000000000046"); + Marshal.ThrowExceptionForHR(view.GetItemObject(0, ref dispatchId, out var folder)); + Own(folder); + var shell = Own(folder.GetType().InvokeMember("Application", BindingFlags.GetProperty, null, folder, null)!); + shell.GetType().InvokeMember("ShellExecute", BindingFlags.InvokeMethod, null, shell, + [path, arguments, Path.IsPathFullyQualified(path) ? Path.GetDirectoryName(path)! : "", "open", show]); + } + catch (Exception error) when (error is COMException or TargetInvocationException or Microsoft.CSharp.RuntimeBinder.RuntimeBinderException) + { + throw new NativeFailure("LAUNCH_FAILED", "Windows Explorer could not launch this executable; open the application and select its observed PID"); + } + finally + { + var released = new HashSet(ReferenceEqualityComparer.Instance); + foreach (var value in owned.AsEnumerable().Reverse()) + if (released.Add(value) && Marshal.IsComObject(value)) Marshal.FinalReleaseComObject(value); + } + } + + internal static string? ShortcutTarget(string path) + { + object? instance = null; + try + { + instance = Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("00021401-0000-0000-C000-000000000046"), true)!); + ((IPersistFile)instance!).Load(path, 0); + var target = new StringBuilder(32768); + ((IShellLink)instance).GetPath(target, target.Capacity, 0, 4); + return target.Length == 0 ? null : Environment.ExpandEnvironmentVariables(target.ToString()); + } + catch (COMException) { return null; } + finally { if (instance is not null) Marshal.FinalReleaseComObject(instance); } + } + + [ComImport, Guid("6D5140C1-7436-11CE-8034-00AA006009FA"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IServiceProvider + { + [PreserveSig] int QueryService(ref Guid service, ref Guid id, [MarshalAs(UnmanagedType.Interface)] out object value); + } + + [ComImport, Guid("000214E2-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IShellBrowser + { + [PreserveSig] int GetWindow(out nint window); + [PreserveSig] int ContextSensitiveHelp([MarshalAs(UnmanagedType.Bool)] bool enter); + [PreserveSig] int InsertMenusSB(nint menu, nint widths); + [PreserveSig] int SetMenuSB(nint menu, nint holemenu, nint active); + [PreserveSig] int RemoveMenusSB(nint menu); + [PreserveSig] int SetStatusTextSB([MarshalAs(UnmanagedType.LPWStr)] string text); + [PreserveSig] int EnableModelessSB([MarshalAs(UnmanagedType.Bool)] bool enable); + [PreserveSig] int TranslateAcceleratorSB(nint message, ushort command); + [PreserveSig] int BrowseObject(nint list, uint flags); + [PreserveSig] int GetViewStateStream(uint mode, out nint stream); + [PreserveSig] int GetControlWindow(uint id, out nint window); + [PreserveSig] int SendControlMsg(uint id, uint message, nuint wparam, nint lparam, out nint result); + [PreserveSig] int QueryActiveShellView(out IShellView view); + [PreserveSig] int OnViewWindowActive(IShellView view); + [PreserveSig] int SetToolbarItems(nint buttons, uint count, uint flags); + } + + [ComImport, Guid("000214E3-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IShellView + { + [PreserveSig] int GetWindow(out nint window); + [PreserveSig] int ContextSensitiveHelp([MarshalAs(UnmanagedType.Bool)] bool enter); + [PreserveSig] int TranslateAccelerator(nint message); + [PreserveSig] int EnableModeless([MarshalAs(UnmanagedType.Bool)] bool enable); + [PreserveSig] int UIActivate(uint state); + [PreserveSig] int Refresh(); + [PreserveSig] int CreateViewWindow(nint previous, nint settings, nint browser, nint bounds, out nint window); + [PreserveSig] int DestroyViewWindow(); + [PreserveSig] int GetCurrentInfo(nint settings); + [PreserveSig] int AddPropertySheetPages(uint reserved, nint callback, nint parameter); + [PreserveSig] int SaveViewState(); + [PreserveSig] int SelectItem(nint list, uint flags); + [PreserveSig] int GetItemObject(uint item, ref Guid id, [MarshalAs(UnmanagedType.Interface)] out object value); + } + + [ComImport, Guid("000214F9-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IShellLink + { + void GetPath([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder path, int capacity, nint findData, uint flags); + } +} diff --git a/packages/experimental/cua-windows/native/src/Win32.cs b/packages/experimental/cua-windows/native/src/Win32.cs new file mode 100644 index 0000000000..957e3bcb98 --- /dev/null +++ b/packages/experimental/cua-windows/native/src/Win32.cs @@ -0,0 +1,136 @@ +// Native desktop operations keep physical pixels and process identity at the Windows edge. +using System.Runtime.InteropServices; +using System.Text; + +namespace DeepSeek.Cua.Windows; + +internal static class Win32 +{ + [DllImport("combase.dll")] internal static extern int RoInitialize(uint initialization); + [DllImport("combase.dll")] internal static extern void RoUninitialize(); + [DllImport("user32.dll", EntryPoint = "GetWindowLongPtrW")] internal static extern nint GetWindowLongPtr(nint window, int index); + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetCursorPos(out Point point); + internal delegate bool WindowVisitor(nint window, nint parameter); + internal delegate void WinEvent(nint hook, uint eventType, nint window, int objectId, int childId, uint threadId, uint time); + + [StructLayout(LayoutKind.Sequential)] internal struct Point { internal int X, Y; } + [StructLayout(LayoutKind.Sequential)] internal struct Rect + { + internal int Left, Top, Right, Bottom; + internal int Width => Right - Left; + internal int Height => Bottom - Top; + } + [StructLayout(LayoutKind.Sequential)] internal struct GuiThreadInfo + { + internal uint Size, Flags; + internal nint Active, Focus, Capture, MenuOwner, MoveSize, Caret; + internal Rect CaretRect; + } + [StructLayout(LayoutKind.Sequential)] internal struct Input { internal uint Type; internal InputData Data; } + [StructLayout(LayoutKind.Explicit)] internal struct InputData + { + [FieldOffset(0)] internal MouseInput Mouse; + [FieldOffset(0)] internal KeyboardInput Keyboard; + } + [StructLayout(LayoutKind.Sequential)] internal struct MouseInput + { + internal int X, Y; + internal uint Data, Flags, Time; + internal nuint Extra; + } + [StructLayout(LayoutKind.Sequential)] internal struct KeyboardInput + { + internal ushort Key, Scan; + internal uint Flags, Time; + internal nuint Extra; + } + + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool EnumWindows(WindowVisitor visitor, nint parameter); + [DllImport("user32.dll")] internal static extern uint GetWindowThreadProcessId(nint window, out uint processId); + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool IsWindow(nint window); + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool IsWindowVisible(nint window); + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool IsIconic(nint window); + [DllImport("user32.dll")] internal static extern nint GetForegroundWindow(); + [DllImport("user32.dll")] internal static extern nint GetAncestor(nint window, uint flags); + [DllImport("user32.dll", CharSet = CharSet.Unicode)] internal static extern int GetWindowText(nint window, StringBuilder text, int maximum); + [DllImport("user32.dll", CharSet = CharSet.Unicode)] internal static extern int GetWindowTextLength(nint window); + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetWindowRect(nint window, out Rect rectangle); + [DllImport("dwmapi.dll")] internal static extern int DwmGetWindowAttribute(nint window, int attribute, out Rect rectangle, int size); + [DllImport("dwmapi.dll")] internal static extern int DwmGetWindowAttribute(nint window, int attribute, out int value, int size); + [DllImport("user32.dll")] internal static extern uint GetDpiForWindow(nint window); + [DllImport("user32.dll")] internal static extern nint SetThreadDpiAwarenessContext(nint context); + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SetForegroundWindow(nint window); + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool ShowWindowAsync(nint window, int command); + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetGUIThreadInfo(uint thread, ref GuiThreadInfo info); + [DllImport("user32.dll", SetLastError = true)] internal static extern uint SendInput(uint count, Input[] inputs, int size); + [DllImport("user32.dll")] internal static extern short GetAsyncKeyState(int key); + [DllImport("user32.dll")] internal static extern nint GetKeyboardLayout(uint thread); + [DllImport("user32.dll", CharSet = CharSet.Unicode)] internal static extern short VkKeyScanEx(char character, nint layout); + [DllImport("user32.dll")] internal static extern int GetSystemMetrics(int index); + [DllImport("user32.dll")] internal static extern nint WindowFromPoint(Point point); + [DllImport("user32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SystemParametersInfo(uint action, uint parameter, out uint value, uint flags); + [DllImport("user32.dll", SetLastError = true)] internal static extern nint OpenInputDesktop(uint flags, [MarshalAs(UnmanagedType.Bool)] bool inherit, uint access); + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CloseDesktop(nint desktop); + [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetUserObjectInformation(nint handle, int index, StringBuilder value, int length, out int needed); + [DllImport("wtsapi32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool WTSQuerySessionInformation(nint server, int session, int information, out nint buffer, out int bytes); + [DllImport("wtsapi32.dll")] internal static extern void WTSFreeMemory(nint memory); + [DllImport("user32.dll", SetLastError = true)] internal static extern nint SetWinEventHook(uint minimum, uint maximum, nint module, WinEvent callback, uint process, uint thread, uint flags); + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool UnhookWinEvent(nint hook); + + [DllImport("user32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool OpenClipboard(nint owner); + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CloseClipboard(); + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool EmptyClipboard(); + [DllImport("user32.dll")] internal static extern nint GetClipboardOwner(); + [DllImport("user32.dll")] internal static extern nint GetOpenClipboardWindow(); + [DllImport("user32.dll")] internal static extern uint GetClipboardSequenceNumber(); + [DllImport("user32.dll", SetLastError = true)] internal static extern uint EnumClipboardFormats(uint previous); + [DllImport("user32.dll", SetLastError = true)] internal static extern nint GetClipboardData(uint format); + [DllImport("user32.dll", SetLastError = true)] internal static extern nint SetClipboardData(uint format, nint data); + [DllImport("user32.dll", CharSet = CharSet.Unicode)] internal static extern uint RegisterClipboardFormat(string name); + [DllImport("kernel32.dll", SetLastError = true)] internal static extern nint GlobalAlloc(uint flags, nuint bytes); + [DllImport("kernel32.dll", SetLastError = true)] internal static extern nint GlobalLock(nint memory); + [DllImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GlobalUnlock(nint memory); + [DllImport("kernel32.dll", SetLastError = true)] internal static extern nuint GlobalSize(nint memory); + [DllImport("kernel32.dll")] internal static extern nint GlobalFree(nint memory); + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] internal static extern uint GetFinalPathNameByHandle(Microsoft.Win32.SafeHandles.SafeFileHandle file, StringBuilder path, uint length, uint flags); + [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetProcessTimes(Microsoft.Win32.SafeHandles.SafeProcessHandle process, out long created, out long exited, out long kernel, out long user); + [DllImport("wintrust.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] internal static extern int WinVerifyTrust(nint window, ref Guid action, ref TrustData data); + [DllImport("wintrust.dll")] internal static extern nint WTHelperProvDataFromStateData(nint state); + [DllImport("wintrust.dll")] internal static extern nint WTHelperGetProvSignerFromChain(nint provider, uint signer, [MarshalAs(UnmanagedType.Bool)] bool counterSigner, uint counter); + + [StructLayout(LayoutKind.Sequential)] internal struct ProviderSigner + { + internal uint Size, VerifyTimeLow, VerifyTimeHigh, CertificateCount; + internal nint Certificates; + } + [StructLayout(LayoutKind.Sequential)] internal struct ProviderCertificate + { + internal uint Size; + internal nint Certificate; + } + [StructLayout(LayoutKind.Sequential)] internal struct CertificateContext + { + internal uint Encoding; + internal nint Encoded; + internal uint EncodedSize; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct TrustFile + { + internal uint Size; + [MarshalAs(UnmanagedType.LPWStr)] internal string Path; + internal nint Handle, Subject; + } + [StructLayout(LayoutKind.Sequential)] internal struct TrustData + { + internal uint Size; + internal nint PolicyCallback, SipClient; + internal uint UiChoice, RevocationChecks, UnionChoice; + internal nint File; + internal uint StateAction; + internal nint StateData, UrlReference; + internal uint ProviderFlags, UiContext; + internal nint SignatureSettings; + } +} diff --git a/packages/experimental/cua-windows/native/src/WindowCapture.cs b/packages/experimental/cua-windows/native/src/WindowCapture.cs new file mode 100644 index 0000000000..b72a219b3f --- /dev/null +++ b/packages/experimental/cua-windows/native/src/WindowCapture.cs @@ -0,0 +1,243 @@ +// Windows Graphics Capture returns the selected window even when another window covers it. +using System.Drawing; +using System.Drawing.Imaging; +using System.Runtime.InteropServices; +using DeepSeek.Cua.Protocol; +using Vortice.Direct3D; +using Vortice.Direct3D11; +using Vortice.DXGI; +using WinRT; +using global::Windows.Graphics.Capture; +using global::Windows.Graphics.DirectX; +using global::Windows.Graphics.DirectX.Direct3D11; + +namespace DeepSeek.Cua.Windows; + +internal sealed class WindowCapture : IAsyncDisposable +{ + private readonly MtaDispatcher dispatcher = new(); + private readonly CaptureAdmission admission = new(); + private ID3D11Device? device; + private ID3D11DeviceContext? immediate; + private IDirect3DDevice? captureDevice; + + internal Task IsSupported(CancellationToken cancellation) + => dispatcher.Invoke(GraphicsCaptureSession.IsSupported, cancellation); + + private void EnsureDevice() + { + if (device is not null) return; + var created = D3D11.D3D11CreateDevice(DriverType.Hardware, DeviceCreationFlags.BgraSupport); + try + { + using var dxgi = created.QueryInterface(); + Marshal.ThrowExceptionForHR(CreateDirect3D11DeviceFromDXGIDevice(dxgi.NativePointer, out var pointer)); + try { captureDevice = MarshalInterface.FromAbi(pointer); } + finally { Marshal.Release(pointer); } + immediate = created.ImmediateContext; + device = created; + } + catch { created.Dispose(); throw; } + } + + internal async Task Capture(AppState app, WindowState window, RequestContext context) + { + if (!await IsSupported(context.Cancellation)) throw new NativeFailure("UNSUPPORTED", "Windows Graphics Capture is unavailable on this desktop"); + var geometry = window.Geometry(app, context); + if (!window.IsOnScreen()) throw new NativeFailure("WINDOW_NOT_VISIBLE", "Restore the selected window with show and observe again before capturing"); + try + { + var operation = admission.Start(() => CaptureOwned(window.Handle, geometry, context)); + var data = await operation.WaitAsync(context.Cancellation); + var current = window.Geometry(app, context); + if (current.Pixels.Width != geometry.Pixels.Width || current.Pixels.Height != geometry.Pixels.Height || current.Dpi != geometry.Dpi) + throw new NativeFailure("WINDOW_CHANGED", "The window changed during capture; observe again"); + DesktopSession.RequireInteractive(); + window.Observe(current); + return new { mimeType = "image/png", data = Convert.ToBase64String(data), pixelWidth = geometry.Pixels.Width, + pixelHeight = geometry.Pixels.Height, windowId = window.Id, bounds = current.Bounds, coordinateSpace = "window-pixels" }; + } + catch (COMException error) + { + throw new NativeFailure(error.HResult == unchecked((int)0x80070005) ? "PERMISSION_DENIED" : "CAPTURE_FAILED", + $"Windows refused the selected window capture (0x{error.HResult:X8}); restore the window and read fresh state"); + } + } + + private async Task CaptureOwned(nint window, WindowGeometry geometry, RequestContext context) + { + CaptureRequest? request = null; + try + { + await dispatcher.Invoke(() => + { + EnsureDevice(); + request = new CaptureRequest(this, window, geometry, context); + return true; + }, context.Cancellation); + return await request!.Result.WaitAsync(context.Cancellation); + } + finally + { + if (request is not null) await dispatcher.Invoke(() => { request.Dispose(); return true; }, CancellationToken.None); + } + } + + private sealed class CaptureRequest : IDisposable + { + private readonly object gate = new(); + private readonly TaskCompletionSource result = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly WindowCapture owner; + private readonly WindowGeometry geometry; + private readonly RequestContext context; + private readonly GraphicsCaptureItem item; + private Direct3D11CaptureFramePool? pool; + private GraphicsCaptureSession? session; + private bool disposed; + + internal Task Result => result.Task; + + internal CaptureRequest(WindowCapture owner, nint window, WindowGeometry geometry, RequestContext context) + { + this.owner = owner; this.geometry = geometry; this.context = context; + item = ItemForWindow(window); + if (item.Size.Width != geometry.Pixels.Width || item.Size.Height != geometry.Pixels.Height) + throw new NativeFailure("WINDOW_CHANGED", "Windows capture bounds differ from the observed window; restore it and observe again"); + try + { + pool = Direct3D11CaptureFramePool.CreateFreeThreaded(owner.captureDevice!, DirectXPixelFormat.B8G8R8A8UIntNormalized, 2, item.Size); + pool.FrameArrived += Frame; + item.Closed += Closed; + session = pool.CreateCaptureSession(item); + session.IsCursorCaptureEnabled = false; + session.StartCapture(); + } + catch { Dispose(); throw; } + } + + private void Closed(GraphicsCaptureItem sender, object args) => result.TrySetException(new NativeFailure("WINDOW_CHANGED", "The selected window closed during capture")); + + private void Frame(Direct3D11CaptureFramePool sender, object args) + { + lock (gate) + { + if (disposed || result.Task.IsCompleted) return; + try + { + context.Check(); + using var frame = sender.TryGetNextFrame(); + if (frame is null) return; + if (frame.ContentSize.Width != geometry.Pixels.Width || frame.ContentSize.Height != geometry.Pixels.Height) + throw new NativeFailure("WINDOW_CHANGED", "The capture frame dimensions changed"); + result.TrySetResult(owner.Encode(frame.Surface, geometry.Pixels.Width, geometry.Pixels.Height, context)); + } + catch (Exception error) { result.TrySetException(error); } + } + } + + public void Dispose() + { + lock (gate) + { + if (disposed) return; + disposed = true; + item.Closed -= Closed; + if (pool is not null) pool.FrameArrived -= Frame; + } + // Native disposal can wait for callbacks; queued callbacks must be able to observe disposed. + session?.Dispose(); + pool?.Dispose(); + } + } + + private byte[] Encode(IDirect3DSurface surface, int width, int height, RequestContext context) + { + var access = surface.As(); + var textureId = typeof(ID3D11Texture2D).GUID; + Marshal.ThrowExceptionForHR(access.GetInterface(ref textureId, out var pointer)); + using var texture = new ID3D11Texture2D(pointer); + if (texture.Description.Width != width || texture.Description.Height != height || texture.Description.Format != Format.B8G8R8A8_UNorm) + throw new NativeFailure("WINDOW_CHANGED", "The captured texture differs from the selected window geometry"); + var description = new Texture2DDescription(Format.B8G8R8A8_UNorm, (uint)width, (uint)height, + mipLevels: 1, bindFlags: BindFlags.None, usage: ResourceUsage.Staging, cpuAccessFlags: CpuAccessFlags.Read); + using var staging = device!.CreateTexture2D(description); + immediate!.CopyResource(staging, texture); + var mapped = immediate.Map(staging, 0, MapMode.Read); + using var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb); + try + { + var pixels = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); + try + { + var row = new byte[checked(width * 4)]; + for (var y = 0; y < height; y++) + { + context.Check(); + Marshal.Copy(mapped.DataPointer + checked(y * (int)mapped.RowPitch), row, 0, row.Length); + Marshal.Copy(row, 0, pixels.Scan0 + y * pixels.Stride, row.Length); + } + } + finally { bitmap.UnlockBits(pixels); } + } + finally { immediate.Unmap(staging, 0); } + context.Check(); + using var output = new MemoryStream(); + bitmap.Save(output, ImageFormat.Png); + if (output.Length * 4 / 3 > context.Config.MaxResponseBytes) + throw new NativeFailure("NATIVE_RESPONSE_LIMIT", "The screenshot exceeds the response byte limit"); + return output.ToArray(); + } + + private static GraphicsCaptureItem ItemForWindow(nint window) + { + const string className = "Windows.Graphics.Capture.GraphicsCaptureItem"; + Marshal.ThrowExceptionForHR(WindowsCreateString(className, className.Length, out var name)); + nint factoryPointer = 0; + object? factory = null; + try + { + var factoryId = typeof(IGraphicsCaptureItemInterop).GUID; + Marshal.ThrowExceptionForHR(RoGetActivationFactory(name, ref factoryId, out factoryPointer)); + factory = Marshal.GetObjectForIUnknown(factoryPointer); + var itemId = new Guid("79C3F95B-31F7-4EC2-A464-632EF5D30760"); + Marshal.ThrowExceptionForHR(((IGraphicsCaptureItemInterop)factory).CreateForWindow(window, ref itemId, out var item)); + try { return MarshalInterface.FromAbi(item); } + finally { Marshal.Release(item); } + } + finally + { + if (factory is not null) Marshal.FinalReleaseComObject(factory); + if (factoryPointer != 0) Marshal.Release(factoryPointer); + WindowsDeleteString(name); + } + } + + public async ValueTask DisposeAsync() + { + await admission.Join(); + await dispatcher.Invoke(() => + { + captureDevice?.Dispose(); + immediate?.Dispose(); + device?.Dispose(); + return true; + }, CancellationToken.None); + await dispatcher.DisposeAsync(); + } + + [ComImport, Guid("3628E81B-3CAC-4C60-B7F4-23CE0E0C3356"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IGraphicsCaptureItemInterop + { + [PreserveSig] int CreateForWindow(nint window, ref Guid id, out nint item); + [PreserveSig] int CreateForMonitor(nint monitor, ref Guid id, out nint item); + } + [ComImport, Guid("A9B3D012-3DF2-4EE3-B8D1-8695F457D3C1"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IDirect3DDxgiInterfaceAccess + { + [PreserveSig] int GetInterface(ref Guid id, out nint value); + } + [DllImport("d3d11.dll", ExactSpelling = true)] private static extern int CreateDirect3D11DeviceFromDXGIDevice(nint device, out nint result); + [DllImport("combase.dll", CharSet = CharSet.Unicode)] private static extern int WindowsCreateString(string source, int length, out nint value); + [DllImport("combase.dll")] private static extern int WindowsDeleteString(nint value); + [DllImport("combase.dll")] private static extern int RoGetActivationFactory(nint name, ref Guid id, out nint value); +} diff --git a/packages/experimental/cua-windows/native/src/Windows.cs b/packages/experimental/cua-windows/native/src/Windows.cs new file mode 100644 index 0000000000..08ec60d145 --- /dev/null +++ b/packages/experimental/cua-windows/native/src/Windows.cs @@ -0,0 +1,176 @@ +// Public window IDs never expose or revive a reused HWND. +using System.Runtime.InteropServices; +using System.Text; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal readonly record struct Bounds(double X, double Y, double Width, double Height); +internal readonly record struct WindowGeometry(Win32.Rect Pixels, uint Dpi) +{ + internal Bounds Bounds => new(Pixels.Left, Pixels.Top, Pixels.Width, Pixels.Height); +} + +internal sealed class WindowState(uint id, nint handle, long epoch) +{ + internal uint Id { get; } = id; + internal nint Handle { get; } = handle; + internal long Epoch { get; } = epoch; + private WindowGeometry? observation; + + internal WindowGeometry Geometry(AppState app, RequestContext context) + { + context.Check(); + var process = app.RequireProcess(); + Win32.GetWindowThreadProcessId(Handle, out var pid); + if (!Win32.IsWindow(Handle) || pid != process.Pid || context.Sta.WindowEpoch(Handle) != Epoch) + throw new NativeFailure("WINDOW_CHANGED", "The selected window was destroyed or replaced; read fresh application state"); + if (Win32.DwmGetWindowAttribute(Handle, 9, out Win32.Rect rectangle, Marshal.SizeOf()) != 0 + && !Win32.GetWindowRect(Handle, out rectangle)) throw new NativeFailure("WINDOW_CHANGED", "The selected window geometry is unavailable"); + var dpi = Win32.GetDpiForWindow(Handle); + if (dpi == 0 || rectangle.Width <= 0 || rectangle.Height <= 0) + throw new NativeFailure("WINDOW_CHANGED", "The selected window has no usable bounds"); + return new(rectangle, dpi); + } + + internal void Observe(WindowGeometry value) => observation = value; + + internal WindowGeometry RequireObservation(AppState app, RequestContext context) + { + var current = Geometry(app, context); + if (observation is not { } previous) throw new NativeFailure("OBSERVATION_REQUIRED", "Read AX state or capture this window before using coordinates"); + if (current.Pixels.Width != previous.Pixels.Width || current.Pixels.Height != previous.Pixels.Height || current.Dpi != previous.Dpi) + throw new NativeFailure("WINDOW_CHANGED", "The window size or display scale changed; read fresh state before input"); + return current; + } + + internal static Win32.Point Point(WindowGeometry geometry, double x, double y) + { + if (!double.IsFinite(x) || !double.IsFinite(y) || x < 0 || y < 0 || x >= geometry.Bounds.Width || y >= geometry.Bounds.Height) + throw new NativeFailure("INVALID_ARGUMENT", "Coordinates must be inside the observed window"); + return new() + { + X = geometry.Pixels.Left + Math.Min(geometry.Pixels.Width - 1, (int)Math.Round(x)), + Y = geometry.Pixels.Top + Math.Min(geometry.Pixels.Height - 1, (int)Math.Round(y)), + }; + } + + internal object Describe(AppState app, RequestContext context) + { + var geometry = Geometry(app, context); + var length = Win32.GetWindowTextLength(Handle); + if (length > context.Config.MaxResponseBytes) throw new NativeFailure("NATIVE_RESPONSE_LIMIT", "The window title exceeds the response limit"); + var title = new StringBuilder(length + 1); + Win32.GetWindowText(Handle, title, title.Capacity); + return new + { + windowId = Id, pid = 4, appName = app.RequireProcess().Name, + title = title.ToString(), bounds = geometry.Bounds, isOnScreen = IsOnScreen(), onCurrentSpace = (bool?)null, + }; + } + + internal bool IsOnScreen() => Win32.IsWindowVisible(Handle) && !Win32.IsIconic(Handle) + && (Win32.DwmGetWindowAttribute(Handle, 14, out int cloaked, sizeof(int)) != 0 || cloaked == 0); +} + +internal static class Windows +{ + internal static WindowState[] Refresh(AppState app, RequestContext context) + { + var process = app.RequireProcess(); + if (app.SelectedWindow is { } selected) { selected.Geometry(app, context); return [selected]; } + var handles = new List(); + Win32.EnumWindows((window, _) => + { + Win32.GetWindowThreadProcessId(window, out var pid); + var style = Win32.GetWindowLongPtr(window, -16).ToInt64(); + var extended = Win32.GetWindowLongPtr(window, -20).ToInt64(); + if (pid == process.Pid && (extended & 0x80) == 0 + && (Win32.IsWindowVisible(window) || (style & 0x00C00000) == 0x00C00000) + && Win32.GetWindowRect(window, out var bounds) && bounds.Width > 0 && bounds.Height > 0) handles.Add(window); + return true; + }, 0); + foreach (var pair in app.Windows.ToArray()) + { + if (handles.Contains(pair.Key) && pair.Value.Epoch == context.Sta.WindowEpoch(pair.Key)) continue; + app.Windows.Remove(pair.Key); + foreach (var scope in app.Snapshots.Where(item => item.Value.Windows.Any(window => window.Id == pair.Value.Id)).Select(item => item.Key).ToArray()) + app.Snapshots.Remove(scope); + } + foreach (var handle in handles) + { + if (!app.Windows.ContainsKey(handle)) + { + app.Windows.Add(handle, new(app.AllocateWindowId(), handle, context.Sta.WindowEpoch(handle))); + } + } + return handles.Select(handle => app.Windows[handle]).ToArray(); + } + + internal static WindowState Resolve(AppState app, uint id, RequestContext context) => Refresh(app, context) + .SingleOrDefault(window => window.Id == id) ?? throw new NativeFailure("WINDOW_CHANGED", "Select a current window from getWindows"); + + internal static WindowState? Focused(AppState app, WindowState[] windows) + { + var foreground = Win32.GetAncestor(Win32.GetForegroundWindow(), 2); + var front = windows.FirstOrDefault(window => window.Handle == foreground); + if (front is not null) return front; + var roots = new HashSet(); + foreach (var thread in windows.Select(window => Win32.GetWindowThreadProcessId(window.Handle, out _)).Distinct()) + { + var info = new Win32.GuiThreadInfo { Size = (uint)Marshal.SizeOf() }; + if (Win32.GetGUIThreadInfo(thread, ref info)) + { + var focused = Win32.GetAncestor(info.Focus != 0 ? info.Focus : info.Active, 2); + if (focused != 0) roots.Add(focused); + } + } + var matches = windows.Where(window => roots.Contains(window.Handle)).ToArray(); + return matches.Length == 1 ? matches[0] : null; + } + + internal static WindowState? Default(AppState app, WindowState[] windows) + { + var visible = windows.Where(window => window.IsOnScreen()).ToArray(); + var focused = Focused(app, visible); + if (focused is not null) return focused; + if (visible.Length == 1) return visible[0]; + if (visible.Length == 0 && windows.Length <= 1) return windows.SingleOrDefault(); + throw new NativeFailure("AMBIGUOUS_WINDOW", "Select a window explicitly from getWindows"); + } + + internal static object Show(AppState app, uint? id, RequestContext context) + { + var target = id is { } selected ? Resolve(app, selected, context) : Default(app, Refresh(app, context)); + var before = Win32.GetForegroundWindow(); + if (target is not null) + { + target.Geometry(app, context); + if (!Win32.ShowWindowAsync(target.Handle, 4)) throw new NativeFailure("UNSUPPORTED", "Windows refused background restoration; explicitly activate the application if needed"); + } + var after = Win32.GetForegroundWindow(); + return new { dispatched = true, windowId = (uint?)target?.Id, + foregroundChanged = before == 0 || after == 0 ? (bool?)null : before != after }; + } + + internal static void Activate(AppState app, WindowState? target, RequestContext context) + { + target ??= Default(app, Refresh(app, context)) ?? throw new NativeFailure("WINDOW_NOT_FOUND", "The application has no window to activate"); + target.Geometry(app, context); + if (Win32.IsIconic(target.Handle)) Win32.ShowWindowAsync(target.Handle, 9); + if (Win32.GetForegroundWindow() != target.Handle && !Win32.SetForegroundWindow(target.Handle)) + throw new NativeFailure("FOREGROUND_DENIED", "Windows refused foreground access; ask the user to focus the target window"); + } + + internal static void RequireForeground(AppState app, WindowState? target, RequestContext context) + { + context.Check(); + DesktopSession.RequireInteractive(); + target ??= app.SelectedWindow; + target?.Geometry(app, context); + var foreground = Win32.GetForegroundWindow(); + Win32.GetWindowThreadProcessId(foreground, out var pid); + if (pid != app.RequireProcess().Pid || target is not null && Win32.GetAncestor(foreground, 2) != target.Handle) + throw new NativeFailure("FOREGROUND_REQUIRED", "This input needs the target in front; explain why, explicitly activate or raise it, then observe again"); + } +} diff --git a/packages/experimental/cua-windows/native/tests/Program.cs b/packages/experimental/cua-windows/native/tests/Program.cs new file mode 100644 index 0000000000..b12458997a --- /dev/null +++ b/packages/experimental/cua-windows/native/tests/Program.cs @@ -0,0 +1,96 @@ +// Portable checks exercise admission, framing, text offsets, and model-visible formatting. +using System.Text; +using DeepSeek.Cua.Protocol; +using DeepSeek.Cua.Windows; + +var checks = 0; +void Check(bool condition, string message) +{ + if (!condition) throw new Exception(message); + checks++; +} +void Refuses(Action action, string code) +{ + try { action(); throw new Exception("Expected refusal: " + code); } + catch (NativeFailure failure) { Check(failure.Code == code, "Unexpected refusal: " + failure.Code); } +} + +var request = NativeRequest.Parse(WireJson.Parse("""{"id":"one","method":"getState","params":{"appHandle":"app","maxElements":20,"maxDepth":5}}""")); +Check(request.Method == "getState" && request.Id == "one", "Valid requests retain correlation and method"); +Refuses(() => NativeRequest.Parse(WireJson.Parse("""{"id":"one","method":"click","params":{"appHandle":"app","windowId":1,"x":-1,"y":2}}""")), "INVALID_ARGUMENT"); +Refuses(() => NativeRequest.Parse(WireJson.Parse("""{"id":"one","method":"getState","params":{"appHandle":"app","maxElements":0,"maxDepth":5}}""")), "INVALID_ARGUMENT"); +Refuses(() => NativeRequest.Parse(WireJson.Parse("""{"id":"one","method":"typeText","params":{"appHandle":"app","text":"hello","unowned":1}}""")), "INVALID_ARGUMENT"); +Refuses(() => WireJson.Parse("""{"id":"one","id":"two"}"""), "INVALID_REQUEST"); +Refuses(() => WireJson.Parse("""{"params":{"x":1,"x":2}}"""), "INVALID_REQUEST"); +Check(NativeRequest.Parse(WireJson.Parse("""{"id":"launch","method":"launchApp","params":{"appHandle":"pending"}}""")).Method == "launchApp", "Host launch continuation remains admitted"); + +Check(NativeControlFrame.Parse(WireJson.Parse("""{"type":"close"}"""), null) == NativeControl.Close, "Connection close needs no active operation"); +Check(NativeControlFrame.Parse(WireJson.Parse("""{"type":"cancel","id":"one"}"""), "one") == NativeControl.Cancel, "Cancellation matches the live operation"); +Check(NativeControlFrame.Parse(WireJson.Parse("""{"type":"cancel","id":"one"}"""), "one", completed: true) == NativeControl.CompletedCancel, + "Cancellation arriving after the matching response is a no-op"); +foreach (var frame in new[] { "null", "[]", "{}", "{\"type\":1}", + "{\"type\":\"close\",\"extra\":1}", "{\"type\":\"cancel\"}", + "{\"type\":\"cancel\",\"id\":null}", "{\"type\":\"cancel\",\"id\":1}", + "{\"type\":\"cancel\",\"id\":\"other\"}", "{\"type\":\"cancel\",\"id\":\"one\",\"extra\":1}" }) + Refuses(() => NativeControlFrame.Parse(WireJson.Parse(frame), "one"), "INVALID_REQUEST"); +Refuses(() => NativeControlFrame.Parse(WireJson.Parse("""{"type":"cancel","id":null}"""), null), "INVALID_REQUEST"); +Refuses(() => NativeControlFrame.Parse(WireJson.Parse("""{"type":"cancel","id":"one"}"""), null), "INVALID_REQUEST"); + +var bytes = Encoding.UTF8.GetBytes("你好\nnext\n"); +var reader = new FrameReader(new MemoryStream(bytes)); +Check(await reader.ReadAsync(7, CancellationToken.None) == "你好", "Frame limits count UTF-8 bytes including newline"); +Check(await reader.ReadAsync(5, CancellationToken.None) == "next", "Buffered next frames remain readable"); +Check(await reader.ReadAsync(1, CancellationToken.None) is null, "Clean EOF is distinct from a partial frame"); +try { await new FrameReader(new MemoryStream(bytes)).ReadAsync(6, CancellationToken.None); throw new Exception("Oversized frame accepted"); } +catch (NativeFailure failure) { Check(failure.Code == "NATIVE_REQUEST_LIMIT", "Oversized UTF-8 frames fail before parsing"); } +try { await new FrameReader(new MemoryStream("partial"u8.ToArray())).ReadAsync(20, CancellationToken.None); throw new Exception("Partial frame accepted"); } +catch (NativeFailure failure) { Check(failure.Code == "INVALID_REQUEST", "Partial EOF is rejected"); } +try { await new FrameReader(new MemoryStream([0xff, 0x0a])).ReadAsync(2, CancellationToken.None); throw new Exception("Invalid UTF-8 accepted"); } +catch (DecoderFallbackException) { checks++; } + +Check(TextSelection.Find("😀 first repeat; second repeat", "repeat", "second ", null) == new TextMatch(24, 6), "Offsets use UTF-16 including surrogate pairs"); +Refuses(() => TextSelection.Find("repeat repeat", "repeat", null, null), "AMBIGUOUS_TEXT"); +Refuses(() => TextSelection.Find("repeat", "other", null, null), "TEXT_NOT_FOUND"); +Refuses(() => TextSelection.Find("text", "", null, null), "INVALID_ARGUMENT"); +Check(TextSelection.Find("aaaa", "aa", "aa", null) == new TextMatch(2, 2), "Overlapping literal matches retain adjacent context"); + +var html = HtmlClipboard.Encode("你好😀"); +var header = Encoding.UTF8.GetString(html); +int Offset(string name) => int.Parse(header.Split('\n').Single(line => line.StartsWith(name + ':')).Split(':')[1].Trim()); +Check(Encoding.UTF8.GetString(html, Offset("StartFragment"), Offset("EndFragment") - Offset("StartFragment")) == "你好😀", "CF_HTML byte offsets preserve Unicode"); +Check(Offset("EndHTML") == html.Length - 1, "CF_HTML excludes the terminating NUL"); + +Check(KeyChord.Parse("ctrl++", []).Key == "+", "Plus key remains a key after chord parsing"); +Check(KeyChord.Parse("+", []).Modifiers.Length == 0, "Bare plus has no modifier"); +Check(KeyChord.Parse("Control+a", ["ctrl"]).Modifiers.SequenceEqual(["control"]), "Equivalent modifiers deduplicate"); +Refuses(() => KeyChord.Parse("ctrl+", []), "INVALID_ARGUMENT"); +Refuses(() => KeyChord.Parse("fn+a", []), "UNSUPPORTED"); + +var node = new AccessibilityNode { Role = "AXTextField", Name = "Title", Value = "", HasValue = true, Placeholder = "Title", ValueWritable = "true", Actions = ["Press", "Focus"] }; +var text = AccessibilityText.Format(node, 3, false); +Check(text.Contains("= \"\" placeholder=\"Title\""), "Empty values and placeholders remain distinct"); +Check(!text.Contains("\"Press\"") && text.Contains("\"Focus\""), "Common actions compact without hiding secondary actions"); +Check(AccessibilityText.Format(node, 3, true).Contains("\"Press\""), "Details retain complete action names"); +Check(!AccessibilityText.Retain(new() { Role = "AXGroup" }), "Empty structural containers can collapse"); +Check(AccessibilityText.Retain(new() { Role = "AXGroup", Actions = ["Copy"] }), "Actionable containers retain their row"); +Check(AccessibilityText.Format(new() { Role = "AXTextArea", Value = "abc", HasValue = true, HasSelection = true, Selection = new(2, 5) }, 0, false) + .Contains("selection=unavailable"), "Out-of-range selections do not describe valid text"); +var captures = new CaptureAdmission(); +var cleanup = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); +var ownedCapture = captures.Start(() => cleanup.Task); +using var cancelled = new CancellationTokenSource(); +cancelled.Cancel(); +try { await ownedCapture.WaitAsync(cancelled.Token); throw new Exception("Cancelled capture caller remained attached"); } +catch (OperationCanceledException) { checks++; } +Refuses(() => captures.Start(() => Task.FromResult(new byte[] { 2 })), "CAPTURE_BUSY"); +var joined = captures.Join(); +Check(!joined.IsCompleted, "Native cleanup retains ownership after its caller stops waiting"); +cleanup.SetResult([1]); +await joined; +Check((await captures.Start(() => Task.FromResult(new byte[] { 2 })))[0] == 2, "Completed cleanup admits a fresh capture"); +var failed = captures.Start(() => Task.FromException(new NativeFailure("CAPTURE_FAILED", "device lost"))); +try { await failed; throw new Exception("Capture error disappeared"); } +catch (NativeFailure failure) { Check(failure.Code == "CAPTURE_FAILED", "Capture failure remains attached to its requesting connection"); } +await captures.Join(); +Check((await captures.Start(() => Task.FromResult(new byte[] { 3 })))[0] == 3, "A settled capture failure does not reserve a permanent slot"); +Console.WriteLine($"{checks} portable CUA checks passed"); diff --git a/packages/experimental/cua-windows/native/tests/Protocol.Tests.csproj b/packages/experimental/cua-windows/native/tests/Protocol.Tests.csproj new file mode 100644 index 0000000000..9ad2abfcee --- /dev/null +++ b/packages/experimental/cua-windows/native/tests/Protocol.Tests.csproj @@ -0,0 +1,11 @@ + + + Exe + net10.0 + enable + enable + true + + + + diff --git a/packages/experimental/cua-windows/native/tests/packages.lock.json b/packages/experimental/cua-windows/native/tests/packages.lock.json new file mode 100644 index 0000000000..f693fbd9af --- /dev/null +++ b/packages/experimental/cua-windows/native/tests/packages.lock.json @@ -0,0 +1,40 @@ +{ + "version": 1, + "dependencies": { + "net10.0": { + "Humanizer.Core": { + "type": "Transitive", + "resolved": "3.0.10", + "contentHash": "yZIhtw8sYuvsONzQbZxWpR60tMWYHXoo0DL6nyOqSFiU5POjBTSEyWFpTQtJEZuy+oqiYTXKXY/Mjx7KnqIQFw==" + }, + "Json.More.Net": { + "type": "Transitive", + "resolved": "3.0.1", + "contentHash": "fRctF2J2SILYG6wqP21drmeEODmCVkVQ/b3MndDu2fT1swfySyUgq7ePCk+aENGlDcIm05fyfjh9vcuqDEfv3w==" + }, + "JsonPointer.Net": { + "type": "Transitive", + "resolved": "7.0.2", + "contentHash": "oClYHv2ooeRrtPZyC9sb/Za/ie5pGhjTbNHlAyFg4XOCyU+606FdoZKS7UdaWvtsPlrF+U2w0Ja3TRvn5+spyA==", + "dependencies": { + "Humanizer.Core": "3.0.10", + "Json.More.Net": "3.0.1" + } + }, + "JsonSchema.Net": { + "type": "Transitive", + "resolved": "9.4.0", + "contentHash": "muE4nPuzbD9x5XA1mkXJNqX4mhz47oF3EY8qFLY1pyUY7lhXFKq65t/dSKIHeNSLBV17zwZuq24MD1em90rMNg==", + "dependencies": { + "JsonPointer.Net": "7.0.2" + } + }, + "cuaprotocol": { + "type": "Project", + "dependencies": { + "JsonSchema.Net": "[9.4.0, )" + } + } + } + } +} diff --git a/packages/experimental/cua-windows/package.json b/packages/experimental/cua-windows/package.json new file mode 100644 index 0000000000..b2779ebe25 --- /dev/null +++ b/packages/experimental/cua-windows/package.json @@ -0,0 +1,95 @@ +{ + "name": "@deepseek-ai/dsh-cua-windows", + "description": "Windows C# computer use through shared application and window objects", + "version": "0.2.2-rc.1", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/experimental/cua-windows" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-computer-use": "workspace:*", + "@deepseek-ai/dsh-system-prompt": "workspace:*", + "@deepseek-ai/dsh-tools": "workspace:*", + "@deepseek-ai/dsh-agent": "workspace:*", + "@deepseek-ai/dsh-subprocess": "workspace:*", + "@deepseek-ai/dsh-user-questions": "workspace:*" + }, + "dependencies": { + "zod": "4.6.6", + "@deepseek-ai/dsh-cua": "workspace:*", + "@deepseek-ai/schemastery": "workspace:~", + "@deepseek-ai/dsh-native-command": "workspace:*", + "@deepseek-ai/dsh-atomic-write": "workspace:*" + }, + "devDependencies": { + "@deepseek-ai/dsh-working-directory": "workspace:*", + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/cordis-plugin-include": "workspace:~", + "@deepseek-ai/cordis-plugin-loader": "workspace:~", + "@deepseek-ai/dsh-agent": "workspace:*", + "@deepseek-ai/dsh-agent-loop": "workspace:*", + "@deepseek-ai/dsh-agent-loop-testkit": "workspace:*", + "@deepseek-ai/dsh-attachment": "workspace:*", + "@deepseek-ai/dsh-attachment-local": "workspace:*", + "@deepseek-ai/dsh-computer-use": "workspace:*", + "@deepseek-ai/dsh-llm": "workspace:*", + "@deepseek-ai/dsh-session": "workspace:*", + "@deepseek-ai/dsh-session-projection": "workspace:*", + "@deepseek-ai/dsh-system-prompt": "workspace:*", + "@deepseek-ai/dsh-tools": "workspace:*", + "@deepseek-ai/dsh-subprocess": "workspace:*", + "@deepseek-ai/dsh-subprocess-local": "workspace:*", + "@deepseek-ai/dsh-fs-local": "workspace:*", + "@deepseek-ai/dsh-llm-deepseek": "workspace:*", + "@deepseek-ai/dsh-ptc-runtime-node": "workspace:*", + "@deepseek-ai/dsh-sandbox-local": "workspace:*", + "@deepseek-ai/dsh-sandbox-policy": "workspace:*", + "sharp": "^0.35.3", + "@deepseek-ai/dsh-ptc-runtime": "workspace:*", + "@deepseek-ai/dsh-user-questions": "workspace:*", + "@deepseek-ai/dsh-settings": "workspace:*", + "@deepseek-ai/dsh-app-boot": "workspace:*", + "@deepseek-ai/dsh-config-editor": "workspace:*", + "@deepseek-ai/dsh-hmr": "workspace:*", + "@deepseek-ai/cordis-plugin-timer": "workspace:~" + }, + "files": [ + "lib/index.js", + "native/bin", + "native/CuaWindows.csproj", + "native/Directory.Build.props", + "native/app.manifest", + "native/src", + "native/protocol", + "native/protocol.schema.json", + "native/packages.lock.json", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "lib/**/*.js.map", + "src" + ], + "scripts": { + "build:native": "dotnet publish native/CuaWindows.csproj --configuration Release --runtime win-x64 --self-contained true -p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true -p:EnableWindowsTargeting=true" + }, + "os": [ + "win32", + "linux" + ] +} diff --git a/packages/experimental/cua-windows/src/guidance.ts b/packages/experimental/cua-windows/src/guidance.ts new file mode 100644 index 0000000000..7c844eb1a0 --- /dev/null +++ b/packages/experimental/cua-windows/src/guidance.ts @@ -0,0 +1,2 @@ +/** TODO: Windows platform guidance after the interface migration. */ +export const GUIDANCE = 'TODO: Windows Computer Use guidance.' diff --git a/packages/experimental/cua-windows/src/index.ts b/packages/experimental/cua-windows/src/index.ts new file mode 100644 index 0000000000..f74f61b539 --- /dev/null +++ b/packages/experimental/cua-windows/src/index.ts @@ -0,0 +1,91 @@ +/** Windows C# provider for the shared Computer Use application and window API. */ +import { isAbsolute, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' +import type { Context } from '@deepseek-ai/cordis' +import Schema from '@deepseek-ai/schemastery' +import { CuaConfig, installCua, type CuaStartupCapabilities } from '@deepseek-ai/dsh-cua' +import { CuaConfigFields } from '@deepseek-ai/dsh-cua/config' +import { prepareNativeExecutable, nativeHostArchitecture } from './native-build.ts' +import { WindowsNativeRuntime } from './native-runtime.ts' +import { GUIDANCE } from './guidance.ts' +import { windowsHost, prepareWsl, retainWslHelper } from './windows-host.ts' + +const CAPABILITIES: CuaStartupCapabilities = { + platform: 'windows', + methods: [ + 'getCapabilities', 'listApps', 'getApp', 'activate', 'show', 'listWindows', 'getState', + 'listActions', 'performAction', 'invoke', 'mouseMove', 'click', 'setValue', 'selectText', + 'typeText', 'paste', 'pressKey', 'scroll', 'drag', 'screenshot', + ], + appLevelAccessibility: false, + keyboard: ['window'], + browser: false, + coordinateSpace: 'screenshot-pixels', +} + +/** Loader identity of the Windows provider. */ +export const name = 'cua-windows' +/** Services required by shared CUA execution and managed native preparation. */ +export const inject = ['computerUse', 'tools', 'systemPrompt', 'subprocess', 'agents'] + +/** Windows compiler and native waiting policy, alongside shared CUA resource limits. */ +export interface Config extends CuaConfig { + /** .NET SDK executable used for source preparation; installed payloads do not require it. */ + dotnetPath: string + /** Windows PowerShell executable used to query WSL interoperation and the Windows architecture. */ + windowsPowerShellPath: string + /** Milliseconds between application-readiness and clipboard-release observations. */ + pollIntervalMs: number +} + +/** Validate platform configuration before launching the compiler or helper. */ +export const Config = Schema.object({ + ...CuaConfigFields, + connectTimeoutMs: CuaConfigFields.connectTimeoutMs.default(30_000), + dotnetPath: Schema.string().min(1).default('dotnet'), + windowsPowerShellPath: Schema.string().min(1).default('powershell.exe'), + pollIntervalMs: Schema.number().step(1).min(1).max(2 ** 31 - 1).default(25), + textEventIntervalMs: CuaConfigFields.textEventIntervalMs.default(0), + maxRequestBytes: CuaConfigFields.maxRequestBytes.max(2 ** 31 - 1), + maxResponseBytes: CuaConfigFields.maxResponseBytes.max(2 ** 31 - 1), + maxClipboardBytes: CuaConfigFields.maxClipboardBytes.max(2 ** 31 - 1), +}) satisfies Schema, Config> + +/** + * Prepare the Windows payload and install the shared authorized operation pipeline. + * @param ctx - Owning provider context. + * @param config - Validated compiler, operation bounds, and application grants. + * @returns Completion after preparation and reversible registrations. + */ +export async function apply(ctx: Context, config: Config): Promise { + const host = windowsHost() + if (config.helperPath !== undefined && !isAbsolute(config.helperPath)) throw new Error('Windows CUA helperPath must be absolute') + const controller = new AbortController() + const prepare = async () => { + const wsl = host === 'wsl' ? await prepareWsl({ subprocess: ctx.subprocess, signal: controller.signal, + timeoutMs: config.connectTimeoutMs, graceMs: config.graceMs, powershellPath: config.windowsPowerShellPath }) : undefined + let helperPath = config.helperPath + if (helperPath === undefined) { + const architecture = wsl?.architecture ?? nativeHostArchitecture(process.platform, process.arch) + helperPath = await prepareNativeExecutable({ + packageRoot: resolve(fileURLToPath(new URL('..', import.meta.url))), architecture, dotnetPath: config.dotnetPath, + subprocess: ctx.subprocess, signal: controller.signal, timeoutMs: config.buildTimeoutMs, graceMs: config.graceMs, + }) + } + return wsl ? retainWslHelper(helperPath, wsl.cacheDirectory, controller.signal) : helperPath + } + const prepared = prepare() + ctx.effect(() => async () => { + controller.abort() + // Activation owns preparation failures; disposal joins the same operation. + await prepared.catch(() => {}) + }, 'cua-windows.native-preparation') + const helperPath = await prepared + controller.signal.throwIfAborted() + const runtime = new WindowsNativeRuntime(ctx, config.pollIntervalMs, host === 'wsl' ? 'stdio' : 'pipe') + ctx.effect(() => () => runtime.dispose(), 'cua-windows.native-runtime') + installCua(ctx, config, { + helperPath, createChannel: (_owner, native) => runtime.connect(native), guidance: GUIDANCE, capabilities: CAPABILITIES, + permissionParameters: (_method, permission) => ({ permission }), + }) +} diff --git a/packages/experimental/cua-windows/src/native-build.ts b/packages/experimental/cua-windows/src/native-build.ts new file mode 100644 index 0000000000..f87e93390f --- /dev/null +++ b/packages/experimental/cua-windows/src/native-build.ts @@ -0,0 +1,73 @@ +/** Source compilation and installed Windows C# helper resolution. */ +import { constants } from 'node:fs' +import { access } from 'node:fs/promises' +import { join } from 'node:path' +import type { SubprocessRuntime } from '@deepseek-ai/dsh-subprocess' +import { buildNativeExecutable as compileExecutable, sourceNativePackage } from '@deepseek-ai/dsh-cua/native-build' + +/** Architectures supported by the Windows helper payload. */ +export type NativeArchitecture = 'arm64' | 'x64' + +/** Compiler invocation and resource ownership for one Windows payload. */ +export interface NativeBuildSpec { + packageRoot: string + architecture: NativeArchitecture + dotnetPath: string + subprocess: Pick + signal: AbortSignal + timeoutMs: number + graceMs: number +} + +/** + * Validate the runtime host before preparing Windows native code. + * @param platform - Node host platform. + * @param architecture - Node process architecture. + * @returns Supported Windows architecture. + */ +export function nativeHostArchitecture(platform: string, architecture: string): NativeArchitecture { + if (platform !== 'win32' || (architecture !== 'arm64' && architecture !== 'x64')) + throw new Error('The Windows Computer Use provider requires Windows on x64 or ARM64') + return architecture +} + +/** + * Locate the package-owned Windows executable. + * @param packageRoot - Directory containing the Windows provider manifest. + * @param architecture - Architecture of the process running the helper. + * @returns Absolute payload path. + */ +export function nativeExecutablePath(packageRoot: string, architecture: NativeArchitecture): string { + return join(packageRoot, 'native', 'bin', `win-${architecture}`, 'dsh-cua-windows.exe') +} + +/** + * Publish a self-contained C# executable; the build can run on macOS with Windows targeting enabled. + * @param spec - SDK command, target, compiler ownership, and deadlines. + * @returns Immutable content-addressed executable after compiler cleanup. + */ +export function buildNativeExecutable(spec: NativeBuildSpec): Promise { + const native = join(spec.packageRoot, 'native') + const output = join(native, '.build', `win-${spec.architecture}`) + return compileExecutable({ ...spec, + argv: [spec.dotnetPath, 'publish', join(native, 'CuaWindows.csproj'), '--configuration', 'Release', + '--runtime', `win-${spec.architecture}`, '--self-contained', 'true', '--output', output, + '-p:EnableWindowsTargeting=true'], + outputPath: join(output, 'dsh-cua-windows.exe'), executablePath: nativeExecutablePath(spec.packageRoot, spec.architecture), + lockPath: join(native, '.build', 'publish'), + retainedDirectory: join(native, '.build', 'prepared', spec.architecture), binaryName: 'dsh-cua-windows.exe', + }) +} + +/** + * Compile only source checkouts; installed packages require their packaged native payload. + * @param spec - Source build and runtime target inputs. + * @returns The ready executable path. + */ +export async function prepareNativeExecutable(spec: NativeBuildSpec): Promise { + if (await sourceNativePackage(spec.packageRoot, 'packages/experimental/cua-windows')) return buildNativeExecutable(spec) + const executable = nativeExecutablePath(spec.packageRoot, spec.architecture) + await access(executable, constants.X_OK) + spec.signal.throwIfAborted() + return executable +} diff --git a/packages/experimental/cua-windows/src/native-runtime.ts b/packages/experimental/cua-windows/src/native-runtime.ts new file mode 100644 index 0000000000..bf5da9aff3 --- /dev/null +++ b/packages/experimental/cua-windows/src/native-runtime.ts @@ -0,0 +1,354 @@ +/** Host-owned connector and independently disposable Agent connections to a shared Windows helper. */ +import { createHash, randomUUID } from 'node:crypto' +import { createReadStream } from 'node:fs' +import { addAbortListener } from 'node:events' +import { realpath } from 'node:fs/promises' +import { PassThrough, Writable, type Readable, type Duplex } from 'node:stream' +import assert from 'node:assert/strict' +import type { SubprocessHandle, SubprocessRuntime } from '@deepseek-ai/dsh-subprocess' +import { NativeError, type NativeChannel, type NativeClientConfig } from '@deepseek-ai/dsh-cua/native-client' +import { z } from 'zod' +import { connectWindowsPipe, type WindowsConnection, type WindowsTransport } from './native-transport.ts' + +const Ready = z.object({ + type: z.literal('ready'), protocol: z.literal(1), runtimeKey: z.string(), instanceId: z.string().min(1), +}).strict() +const Started = Ready.extend({ endpoint: z.string().min(1), launcherId: z.string().min(1) }).strict() +// Private transport control frames have fixed encoding; operation replies pass through unchanged. +const closedFrame = Buffer.from('{"type":"closed"}\n') +type Owner = { subprocess: Pick } + +function failure(error: unknown): Error { return error instanceof Error ? error : new Error(String(error)) } + +async function interruptible(operation: Promise, signal: AbortSignal): Promise { + const cancelled = Promise.withResolvers() + using _listener = addAbortListener(signal, () => { cancelled.reject(signal.reason) }) + return await Promise.race([operation, cancelled.promise]) +} + +function firstFrame(stream: Readable, signal: AbortSignal): Promise<{ value: unknown; rest: Buffer }> { + signal.throwIfAborted() + return new Promise((resolve, reject) => { + let bytes = Buffer.alloc(0) + const clean = () => { + stream.off('data', data).off('error', rejectFrame).off('end', ended).off('close', ended) + signal.removeEventListener('abort', aborted) + } + const rejectFrame = (error: Error) => { clean(); reject(error) } + const ended = () => { rejectFrame(new NativeError('NATIVE_EOF', 'Helper ended before native readiness')) } + const aborted = () => { rejectFrame(failure(signal.reason)) } + const data = (chunk: Buffer) => { + const newline = chunk.indexOf(10) + const size = newline < 0 ? chunk.length : newline + 1 + if (bytes.length + size > 8192) { rejectFrame(new NativeError('NATIVE_PROTOCOL', 'Native readiness exceeded its byte limit')); return } + bytes = Buffer.concat([bytes, chunk.subarray(0, size)]) + if (newline < 0) return + stream.pause() + clean() + try { + resolve({ value: JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes.subarray(0, -1))), rest: chunk.subarray(size) }) + } catch (error) { reject(new NativeError('NATIVE_PROTOCOL', 'Invalid native readiness frame', { cause: error })) } + } + stream.on('data', data).on('error', rejectFrame).on('end', ended).on('close', ended) + signal.addEventListener('abort', aborted, { once: true }) + }) +} + +class WindowsHelper { + readonly ready: Promise> + readonly done: Promise + readonly sockets = new Set() + private readonly readiness = Promise.withResolvers>() + private readonly startup = new AbortController() + private handle: SubprocessHandle | undefined + private phase: 'starting' | 'ready' | 'closing' | 'closed' = 'starting' + private stopTimer: ReturnType | undefined + private error: Error | undefined + + constructor(private readonly owner: Owner, private readonly config: NativeClientConfig) { + this.ready = this.readiness.promise + void this.ready.catch(() => {}) + this.done = this.run() + void this.done.catch(() => {}) + } + + get ended(): boolean { return this.phase === 'closing' || this.phase === 'closed' } + + async stop(): Promise { + if (!this.ended) { + this.phase = 'closing' + this.startup.abort(new NativeError('NATIVE_CLOSED', 'Computer Use is shutting down')) + this.handle?.stdin?.end() + this.stopTimer = setTimeout(() => { this.handle?.terminate() }, this.config.graceMs) + } + await this.done + } + + private async run(): Promise { + const startupTimer = setTimeout(() => { + this.startup.abort(new NativeError('NATIVE_CONNECT_TIMEOUT', 'Windows helper did not become ready before connectTimeoutMs; check helper diagnostics and Windows application-control policy')) + }, this.config.connectTimeoutMs) + try { + const helperPath = await realpath(this.config.helperPath) + const digest = createHash('sha256') + for await (const chunk of createReadStream(helperPath, { signal: this.startup.signal })) digest.update(chunk as Buffer) + const runtimeKey = digest.digest('hex') + const instanceId = randomUUID().replaceAll('-', '') + this.startup.signal.throwIfAborted() + const handle = this.owner.subprocess.spawn({ + argv: [helperPath, '--serve', '--instance-id', instanceId, '--runtime-key', runtimeKey, + '--connect-timeout-ms', String(this.config.connectTimeoutMs), '--grace-ms', String(this.config.graceMs)], + cwd: this.config.cwd, graceMs: this.config.graceMs, + stdio: { stdin: 'pipe', stdout: 'pipe', stderr: { maxBytes: 65_536 } }, + }) + this.handle = handle + assert(handle.stdin && handle.stdout, 'The helper requested piped control and readiness streams') + handle.stdout.on('error', (error: Error) => { this.error ??= error; this.startup.abort(error) }) + const exit = handle.done.then((outcome) => { + const diagnostic = handle.collected.stderr?.readFrom(0).text.trim() || 'no diagnostic output' + throw new NativeError('NATIVE_EXITED', + `Windows helper exited before readiness (${String(outcome.exitCode)}): ${diagnostic}. Check Windows application-control policy and helper signing.`) + }) + let frame: Awaited> + try { frame = await Promise.race([firstFrame(handle.stdout, this.startup.signal), exit]) } catch (error) { + // EOF can precede process settlement and its final collected stderr. + if (error instanceof NativeError && error.code === 'NATIVE_EOF') await interruptible(exit, this.startup.signal) + throw error + } + const ready = Started.parse(frame.value) + if (ready.runtimeKey !== runtimeKey || ready.launcherId !== instanceId || frame.rest.length !== 0) + throw new NativeError('NATIVE_PROTOCOL', 'Windows helper readiness has another identity or unexpected output') + this.startup.signal.throwIfAborted() + handle.stdout.on('data', () => { + this.error ??= new NativeError('NATIVE_PROTOCOL', 'Windows helper wrote unsolicited readiness data') + void this.stop().catch((error: unknown) => { this.error ??= failure(error) }) + }) + handle.stdout.resume() + clearTimeout(startupTimer) + this.phase = 'ready' + this.readiness.resolve(ready) + const outcome = await handle.done + if (!this.ended) this.error ??= new NativeError('NATIVE_EXITED', + `Windows helper stopped (${String(outcome.exitCode)}, ${String(outcome.signal)}); select applications again`) + } catch (error) { this.error ??= failure(error) } + finally { + clearTimeout(startupTimer) + this.phase = 'closing' + const error = this.error ?? new NativeError('NATIVE_CLOSED', 'Windows helper closed; select applications again') + for (const socket of this.sockets) socket.destroy(error) + const handle = this.handle + try { + if (handle) { + handle.stdin?.end() + const timer = setTimeout(() => { handle.terminate() }, this.config.graceMs) + try { + await handle.done + if (!await handle.waitForExit()) throw new NativeError('NATIVE_CLEANUP', 'Windows helper process range did not exit') + } finally { clearTimeout(timer) } + } + } finally { + clearTimeout(this.stopTimer) + this.phase = 'closed' + this.readiness.reject(error) + } + } + } +} + +class WindowsChannel implements NativeChannel { + readonly stdout = new PassThrough() + readonly stdin: Writable + readonly done: Promise + private readonly startup = new AbortController() + private readonly readiness = Promise.withResolvers() + private readonly closed: PromiseWithResolvers = Promise.withResolvers() + private socket: Duplex | undefined + private closing = false + private closeTimer: ReturnType | undefined + + constructor(helper: Promise, config: NativeClientConfig, pollIntervalMs: number, + owner: Owner, transport: WindowsTransport) { + this.stdin = new Writable({ + write: (chunk: Buffer, _encoding, callback) => { + void this.readiness.promise.then((socket) => { + if (this.closing) { callback(new NativeError('NATIVE_CLOSED', 'Native connection is closing')); return } + socket.write(chunk, callback) + }, callback) + }, + final: (callback) => { this.close(); callback() }, + destroy: (error, callback) => { this.close(); callback(error) }, + }) + for (const stream of [this.stdin, this.stdout]) stream.on('error', () => {}) + void this.readiness.promise.catch(() => {}) + void this.closed.promise.catch(() => {}) + this.done = this.run(helper, config, pollIntervalMs, owner, transport) + void this.done.catch(() => {}) + } + + close(): void { + if (this.closing) return + this.closing = true + this.startup.abort(new NativeError('NATIVE_CLOSED', 'Native connection closed before readiness')) + if (this.socket && !this.socket.destroyed) this.socket.write('{"type":"close"}\n') + } + + waitForClose(): Promise { return this.closed.promise } + + private async run(helperPromise: Promise, config: NativeClientConfig, pollIntervalMs: number, + owner: Owner, transport: WindowsTransport): Promise { + let helper: WindowsHelper | undefined + let connection: WindowsConnection | undefined + let closed: Promise | undefined + let caught: Error | undefined + let admitted = false + const observation = { acknowledged: false } + const timer = setTimeout(() => { + this.startup.abort(new NativeError('NATIVE_CONNECT_TIMEOUT', 'Windows native connection exceeded connectTimeoutMs; check helper diagnostics and Windows application-control policy')) + }, config.connectTimeoutMs) + try { + helper = await interruptible(helperPromise, this.startup.signal) + const ready = await interruptible(helper.ready, this.startup.signal) + this.startup.signal.throwIfAborted() + connection = connectWindowsPipe(owner.subprocess, config, ready.endpoint, ready.runtimeKey, transport) + const socket = connection.stream + this.socket = socket + helper.sockets.add(socket) + let socketError: Error | undefined + closed = new Promise((resolve, reject) => { + socket.on('error', (error: Error) => { socketError = error }) + socket.on('close', () => { + if (socketError) reject(socketError) + else if (!observation.acknowledged) reject(new NativeError('NATIVE_EOF', 'Windows pipe closed without cleanup acknowledgement')) + else resolve() + }) + }) + void closed.catch(() => {}) + const abort = () => { socket.destroy(failure(this.startup.signal.reason)) } + this.startup.signal.addEventListener('abort', abort, { once: true }) + try { + const frame = firstFrame(socket, this.startup.signal) + void frame.catch(() => {}) + await connection.connected + this.startup.signal.throwIfAborted() + { + const { maxRequestBytes, maxResponseBytes, axTimeoutMs, textEventIntervalMs, + screenshotTimeoutMs, timeoutMs, graceMs, maxClickHoldMs } = config + socket.write(JSON.stringify({ type: 'hello', protocol: 1, runtimeKey: ready.runtimeKey, + config: { maxRequestBytes, maxResponseBytes, axTimeoutMs, textEventIntervalMs, screenshotTimeoutMs, timeoutMs, graceMs, pollIntervalMs, maxClickHoldMs } }) + '\n') + } + const response = await frame + const accepted = Ready.parse(response.value) + if (accepted.runtimeKey !== ready.runtimeKey || accepted.instanceId !== ready.instanceId || accepted.pid !== ready.pid) + throw new NativeError('NATIVE_PROTOCOL', 'Windows pipe belongs to another helper instance') + this.startup.signal.throwIfAborted() + admitted = true + this.startup.signal.removeEventListener('abort', abort) + clearTimeout(timer) + const close = () => { + this.closeTimer ??= setTimeout(() => { socket.destroy(new NativeError('NATIVE_CLEANUP', 'Windows pipe did not acknowledge cleanup')) }, config.graceMs) + } + this.startup.signal.addEventListener('abort', close, { once: true }) + let prefix: Buffer | undefined = Buffer.alloc(0) + const receive = (chunk: Buffer) => { + let offset = 0 + while (offset < chunk.length) { + const newline = chunk.indexOf(10, offset) + const end = newline < 0 ? chunk.length : newline + 1 + const piece = chunk.subarray(offset, end) + if (prefix !== undefined) prefix = prefix.length + piece.length <= closedFrame.length + ? Buffer.concat([prefix, piece]) : undefined + if (newline >= 0) { + if (prefix?.equals(closedFrame)) { + if (!this.closing) { + socket.destroy(new NativeError('NATIVE_PROTOCOL', 'Unexpected Windows cleanup acknowledgement')) + return + } + observation.acknowledged = true + } + prefix = Buffer.alloc(0) + } + offset = end + } + if (!this.closing) this.stdout.write(chunk) + } + socket.on('data', receive) + if (response.rest.length !== 0) receive(response.rest) + socket.resume() + this.readiness.resolve(socket) + try { await closed } finally { this.startup.signal.removeEventListener('abort', close) } + } finally { this.startup.signal.removeEventListener('abort', abort) } + } catch (error) { + const cause = failure(error) + if (!this.closing || admitted) caught = cause + this.readiness.reject(cause) + } + finally { + clearTimeout(timer) + clearTimeout(this.closeTimer) + this.closing = true + this.socket?.destroy() + if (closed) { + try { await closed } catch (error) { if (admitted) caught ??= failure(error) } + } + if (this.socket) helper?.sockets.delete(this.socket) + let cleanupError: Error | undefined + try { await connection?.dispose() } catch (error) { cleanupError = failure(error); caught ??= cleanupError } + if (admitted && !observation.acknowledged) { + cleanupError = new NativeError('NATIVE_CLEANUP', 'Windows pipe ended without native cleanup acknowledgement') + } + this.stdin.destroy() + if (caught) this.stdout.destroy(caught) + else this.stdout.end() + if (cleanupError) this.closed.reject(cleanupError) + else this.closed.resolve() + } + if (caught) throw caught + } +} + +/** One provider owns a service lease; Agent connections own only their application and snapshot state. */ +export class WindowsNativeRuntime { + private helper: WindowsHelper | undefined + private disposal: Promise | undefined + private readonly channels = new Set() + + /** + * @param owner Managed subprocess provider. + * @param pollIntervalMs Clipboard and application-readiness polling interval. + * @param transport Resolved native Windows or WSL connection method. + */ + constructor(private readonly owner: Owner, private readonly pollIntervalMs: number, private readonly transport: WindowsTransport = 'pipe') {} + + /** + * Connect one Agent without transferring process ownership to that Agent. + * @param config Executable identity and per-connection limits. + * @returns The byte stream used by the shared native request client. + */ + connect(config: NativeClientConfig): NativeChannel { + if (this.disposal) throw new NativeError('NATIVE_CLOSED', 'Windows Computer Use is disposed') + const acquire = async () => { + if (this.helper?.ended) await this.helper.done + if (this.disposal) throw new NativeError('NATIVE_CLOSED', 'Windows Computer Use is disposed') + if (!this.helper || this.helper.ended) this.helper = new WindowsHelper(this.owner, config) + return this.helper + } + const channel = new WindowsChannel(acquire(), config, this.pollIntervalMs, this.owner, this.transport) + this.channels.add(channel) + void channel.done.then(() => this.channels.delete(channel), () => this.channels.delete(channel)) + return channel + } + + /** Close Agent pipes and join this Host's connector; other Hosts retain their service leases. */ + dispose(): Promise { + return this.disposal ??= (async () => { + for (const channel of this.channels) channel.close() + const channels = await Promise.allSettled([...this.channels].map(channel => channel.waitForClose())) + let processError: unknown + try { await this.helper?.stop() } catch (error) { processError = error } + const errors: unknown[] = [] + for (const result of channels) { if (result.status === 'rejected') errors.push(result.reason) } + if (processError !== undefined) errors.push(processError) + if (errors.length) throw new AggregateError(errors, 'Windows Computer Use cleanup failed') + })() + } +} diff --git a/packages/experimental/cua-windows/src/native-transport.ts b/packages/experimental/cua-windows/src/native-transport.ts new file mode 100644 index 0000000000..d72b47b4eb --- /dev/null +++ b/packages/experimental/cua-windows/src/native-transport.ts @@ -0,0 +1,65 @@ +/** Direct Windows pipes and WSL subprocess streams for the same native protocol. */ +import { Socket } from 'node:net' +import { Duplex } from 'node:stream' +import assert from 'node:assert/strict' +import type { SubprocessRuntime } from '@deepseek-ai/dsh-subprocess' +import { NativeError, type NativeClientConfig } from '@deepseek-ai/dsh-cua/native-client' + +/** Transport selected from the resolved Host environment. */ +export type WindowsTransport = 'pipe' | 'stdio' + +/** One connection owns its stream and, for WSL, a Windows bridge process. */ +export interface WindowsConnection { + stream: Duplex + connected: Promise + dispose(): Promise +} + +/** + * Connect to a Windows desktop service without exposing a network listener. + * @param subprocess Managed process owner for the WSL bridge. + * @param config Helper executable and connection/cleanup limits. + * @param endpoint Named pipe reported by the verified service lease. + * @param runtimeKey Expected executable digest, verified again by the Windows bridge. + * @param transport Native pipe or standard streams through WSL interoperation. + * @returns Owned connection; disposal joins the bridge process after stream closure. + */ +export function connectWindowsPipe(subprocess: Pick, config: NativeClientConfig, + endpoint: string, runtimeKey: string, transport: WindowsTransport): WindowsConnection { + if (transport === 'pipe') { + const stream = new Socket() + const connected = new Promise((resolve, reject) => { + stream.once('connect', resolve) + stream.once('error', reject) + }) + void connected.catch(() => {}) + stream.connect(endpoint) + return { stream, connected, dispose: async () => {} } + } + const handle = subprocess.spawn({ + argv: [config.helperPath, '--bridge', '--runtime-key', runtimeKey, + '--connect-timeout-ms', String(config.connectTimeoutMs), '--grace-ms', String(config.graceMs)], + cwd: config.cwd, graceMs: config.graceMs, + stdio: { stdin: 'pipe', stdout: 'pipe', stderr: { maxBytes: 65_536 } }, + }) + assert(handle.stdin && handle.stdout, 'The Windows bridge requires standard input and output') + const stream = Duplex.from({ readable: handle.stdout, writable: handle.stdin }) + stream.once('end', () => { stream.end() }) + void handle.done.then((outcome) => { + if (outcome.exitCode !== 0 || outcome.signal !== null) + stream.destroy(new NativeError('NATIVE_EXITED', `Windows bridge failed: ${handle.collected.stderr?.readFrom(0).text ?? String(outcome.exitCode)}`)) + }, (error: unknown) => { stream.destroy(error instanceof Error ? error : new Error(String(error))) }) + return { + stream, connected: Promise.resolve(), + async dispose() { + handle.stdin?.end() + const timer = setTimeout(() => { handle.terminate() }, config.graceMs) + try { + const outcome = await handle.done + if (!await handle.waitForExit()) throw new NativeError('NATIVE_CLEANUP', 'Windows bridge process did not exit') + if (outcome.exitCode !== 0 || outcome.signal !== null) + throw new NativeError('NATIVE_CLEANUP', `Windows bridge exited unsuccessfully (${String(outcome.exitCode)}, ${String(outcome.signal)})`) + } finally { clearTimeout(timer) } + }, + } +} diff --git a/packages/experimental/cua-windows/src/windows-host.ts b/packages/experimental/cua-windows/src/windows-host.ts new file mode 100644 index 0000000000..584b53f2d1 --- /dev/null +++ b/packages/experimental/cua-windows/src/windows-host.ts @@ -0,0 +1,93 @@ +/** Windows desktop execution from native Windows or a WSL process. */ +import { createHash } from 'node:crypto' +import { mkdir, readFile } from 'node:fs/promises' +import { join, win32 } from 'node:path' +import { isWsl, type HostEnvironmentFacts } from '@deepseek-ai/dsh-native-command' +import { writeFileAtomic } from '@deepseek-ai/dsh-atomic-write' +import { NativeError } from '@deepseek-ai/dsh-cua/native-client' +import type { SubprocessRuntime } from '@deepseek-ai/dsh-subprocess' +import { z } from 'zod' +import type { NativeArchitecture } from './native-build.ts' + +/** DSH execution environment, independently of the Windows desktop it controls. */ +export type WindowsHost = 'windows' | 'wsl' + +/** + * Resolve the Host before compiling or launching native code. + * @param facts Process and kernel facts; omitted fields use the current Host. + * @returns Native Windows or WSL; ordinary Linux has no Windows desktop provider. + */ +export function windowsHost(facts: HostEnvironmentFacts = {}): WindowsHost { + if ((facts.platform ?? process.platform) === 'win32') return 'windows' + if (isWsl(facts)) return 'wsl' + throw new NativeError('UNSUPPORTED', 'Windows Computer Use requires native Windows or WSL; ordinary Linux is unsupported') +} + +/** Managed command lifetime for WSL capability and path queries. */ +export interface WslPreparation { + subprocess: Pick + signal: AbortSignal + timeoutMs: number + graceMs: number + powershellPath: string +} + +async function command(spec: WslPreparation, argv: string[]): Promise { + spec.signal.throwIfAborted() + const signal = AbortSignal.any([spec.signal, AbortSignal.timeout(spec.timeoutMs)]) + const handle = spec.subprocess.spawn({ argv, cwd: process.cwd(), signal, graceMs: spec.graceMs, + stdio: { stdin: 'ignore', stdout: { maxBytes: 8192 }, stderr: { maxBytes: 8192 } } }) + try { + const outcome = await handle.done + signal.throwIfAborted() + if (outcome.exitCode !== 0 || outcome.signal !== null) + throw new NativeError('WSL_INTEROP', `Windows interoperation failed: ${handle.collected.stderr?.readFrom(0).text ?? outcome.exitCode}`) + return handle.collected.stdout?.readFrom(0).text.trim() ?? '' + } finally { + handle.terminate() + if (!await handle.waitForExit()) throw new NativeError('NATIVE_CLEANUP', 'Windows preparation process did not exit') + } +} + +/** + * Verify that WSL can start Windows programs and resolve the Windows runtime architecture. + * @param spec Managed process policy and Windows PowerShell executable. + * @returns Windows architecture and a WSL-visible cache directory on the Windows filesystem. + */ +export async function prepareWsl(spec: WslPreparation): Promise<{ architecture: NativeArchitecture; cacheDirectory: string }> { + const script = "[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false); @{ architecture = [Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString().ToLowerInvariant(); cache = [IO.Path]::Combine([Environment]::GetFolderPath('LocalApplicationData'), 'DeepSeekHarness', 'cua') } | ConvertTo-Json -Compress" + try { + const output = await command(spec, [spec.powershellPath, '-NoProfile', '-NonInteractive', '-Command', script]) + const result = z.object({ architecture: z.enum(['x64', 'arm64']), cache: z.string().refine(value => win32.isAbsolute(value)) }).strict().parse(JSON.parse(output)) + const cacheDirectory = await command(spec, ['wslpath', '-u', result.cache]) + if (!cacheDirectory.startsWith('/')) throw new NativeError('WSL_INTEROP', 'wslpath did not return an absolute cache directory') + return { architecture: result.architecture, cacheDirectory } + } catch (error) { + spec.signal.throwIfAborted() + throw new NativeError('WSL_INTEROP', 'WSL cannot prepare Windows Computer Use; check Windows interoperation and windowsPowerShellPath', { cause: error }) + } +} + +/** + * Retain the helper on the Windows filesystem so Explorer can launch the shared desktop service. + * @param helperPath Absolute executable path visible to WSL. + * @param cacheDirectory Windows user cache translated to a WSL path. + * @param signal Provider preparation lifetime. + * @returns Content-addressed executable path, without modifying the source payload. + */ +export async function retainWslHelper(helperPath: string, cacheDirectory: string, signal: AbortSignal): Promise { + const bytes = await readFile(helperPath, { signal }) + const digest = createHash('sha256').update(bytes).digest('hex') + const directory = join(cacheDirectory, digest) + const retained = join(directory, 'dsh-cua-windows.exe') + await mkdir(directory, { recursive: true }) + let existing: Buffer | undefined + try { existing = await readFile(retained, { signal }) } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error + } + signal.throwIfAborted() + if (existing && !existing.equals(bytes)) throw new NativeError('NATIVE_STARTUP', 'The cached Windows helper does not match its executable digest') + if (!existing) await writeFileAtomic(retained, bytes, { mode: 0o755 }) + signal.throwIfAborted() + return retained +} diff --git a/packages/experimental/cua-windows/tests/desktop-runtime.spec.ts b/packages/experimental/cua-windows/tests/desktop-runtime.spec.ts new file mode 100644 index 0000000000..369fd2f546 --- /dev/null +++ b/packages/experimental/cua-windows/tests/desktop-runtime.spec.ts @@ -0,0 +1,22 @@ +/** Opt-in real desktop admission through the shipped managed subprocess provider. */ +import { Context } from '@deepseek-ai/cordis' +import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local' +import { NativeClient } from '@deepseek-ai/dsh-cua/native-client' +import { expect, it, onTestFinished } from 'vitest' +import { Config } from '../src/index.ts' +import { WindowsNativeRuntime } from '../src/native-runtime.ts' + +const helperPath = process.env.DSH_CUA_DESKTOP_TEST_HELPER +it.skipIf(!helperPath)('admits Windows desktop requests through managed WSL or native Windows processes', async () => { + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + await ctx.plugin(LocalSubprocessRuntime) + const runtime = new WindowsNativeRuntime(ctx, 25, process.platform === 'win32' ? 'pipe' : 'stdio') + onTestFinished(() => runtime.dispose()) + const client = new NativeClient(ctx, { ...Config({}), helperPath: helperPath!, cwd: process.cwd() }, + (_owner, config) => runtime.connect(config)) + onTestFinished(() => client.dispose()) + expect(await client.request('getCapabilities', {}, new AbortController().signal)).toMatchObject({ + permissions: { accessibility: expect.any(Boolean), screenRecording: expect.any(Boolean) }, + }) +}, 60_000) diff --git a/packages/experimental/cua-windows/tests/desktop-smoke.mjs b/packages/experimental/cua-windows/tests/desktop-smoke.mjs new file mode 100644 index 0000000000..2a476cc65d --- /dev/null +++ b/packages/experimental/cua-windows/tests/desktop-smoke.mjs @@ -0,0 +1,285 @@ +/** Real Windows acceptance against private fixture windows; no existing document is modified. */ +// TODO: migrate this old window-RPC smoke (discoverWindows/prepareWindows/prepareLaunch) to the listApps/getApp facade before running it again. +import assert from 'node:assert/strict' +import { spawn } from 'node:child_process' +import { createHash, randomUUID } from 'node:crypto' +import { readFile, writeFile } from 'node:fs/promises' +import { createConnection } from 'node:net' +import { Duplex } from 'node:stream' +import { release } from 'node:os' +import { createInterface } from 'node:readline' +import { once } from 'node:events' +import { resolve } from 'node:path' +import { setTimeout as delay } from 'node:timers/promises' + +const wsl = process.platform === 'linux' && (process.env.WSL_DISTRO_NAME || release().toLowerCase().includes('microsoft')) +assert(process.platform === 'win32' || wsl, 'Run with native Windows Node or WSL on an interactive Windows desktop') +const [helperFile, fixtureFile, outputFile] = process.argv.slice(2).map(path => resolve(path)) +assert(helperFile && fixtureFile && outputFile, 'Expected helper, fixture, and evidence file paths') +const resources = [] +const results = [] + +function lines(stream) { + const reader = createInterface({ input: stream }) + const iterator = reader[Symbol.asyncIterator]() + return async () => { + const result = await iterator.next() + assert(!result.done, 'The native stream ended before a response') + return JSON.parse(result.value) + } +} + +function child(file, args = []) { + const process = spawn(file, args, { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true }) + const exit = once(process, 'exit') + const read = args.includes('--bridge') ? undefined : lines(process.stdout) + process.stderr.pipe(globalThis.process.stderr) + const resource = { process, exit, read } + resources.push(resource) + return resource +} + +async function checked(name, operation) { + const start = performance.now() + const detail = await operation() + results.push({ name, elapsedMs: Math.round(performance.now() - start), detail }) + console.log(JSON.stringify(results.at(-1))) + return detail +} + +const deadline = setTimeout(() => { + console.error('Desktop smoke exceeded its 90-second deadline') + process.exitCode = 1 + for (const resource of resources) resource.process.kill() +}, 90_000) +let socket +let bridge +try { + const fixture = child(fixtureFile) + const initial = await fixture.read() + const inspect = async command => { fixture.process.stdin.write(command + '\n'); return await fixture.read() } + const sentinel = child(fixtureFile) + const sentinelReady = await sentinel.read() + const cover = async () => { + await inspect(`allow:${sentinelReady.pid}`) + sentinel.process.stdin.write('focus\n') + const focused = await sentinel.read() + assert.equal(focused.foreground, focused.window, 'The sentinel needs foreground access') + return await inspect('inspect') + } + await cover() + const runtimeKey = createHash('sha256').update(await readFile(helperFile)).digest('hex') + const instanceId = randomUUID().replaceAll('-', '') + const helper = child(helperFile, ['--serve', '--instance-id', instanceId, '--runtime-key', runtimeKey, '--connect-timeout-ms', '10000', '--grace-ms', '3000']) + const other = child(helperFile, ['--serve', '--instance-id', randomUUID().replaceAll('-', ''), '--runtime-key', runtimeKey, '--connect-timeout-ms', '10000', '--grace-ms', '3000']) + const [ready] = await checked('Concurrent Host connectors share one desktop service', async () => { + const pair = await Promise.all([helper.read(), other.read()]) + assert.equal(pair[0].pid, pair[1].pid) + assert.equal(pair[0].instanceId, pair[1].instanceId) + return pair + }) + assert.equal(ready.runtimeKey, runtimeKey) + if (wsl) { + bridge = child(helperFile, ['--bridge', '--runtime-key', runtimeKey, '--connect-timeout-ms', '10000', '--grace-ms', '3000']) + socket = Duplex.from({ readable: bridge.process.stdout, writable: bridge.process.stdin }) + socket.once('end', () => { socket?.end() }) + } else { + socket = createConnection(ready.endpoint) + await once(socket, 'connect') + } + const read = lines(socket) + const exchange = async value => { socket.write(JSON.stringify(value) + '\n'); return await read() } + const hello = await exchange({ type: 'hello', protocol: 1, runtimeKey, config: { + maxRequestBytes: 1_048_576, maxResponseBytes: 33_554_432, axTimeoutMs: 5000, textEventIntervalMs: 0, + screenshotTimeoutMs: 10000, timeoutMs: 15000, graceMs: 3000, pollIntervalMs: 25, maxClickHoldMs: 1000, + } }) + assert.equal(hello.instanceId, ready.instanceId) + other.process.stdin.end() + assert.deepEqual(await other.exit, [0, null]) + let sequence = 0 + const request = async (method, params = {}) => { + const response = await exchange({ id: String(++sequence), method, params }) + if (response.error) throw Object.assign(new Error(response.error.message), { code: response.error.code }) + return response.result + } + await checked('AppsFolder discovery and launch reach the Settings window', async () => { + const entries = await request('findApps', { query: 'immersivecontrolpanel', maxAppMatches: 20 }) + const entry = entries.find(entry => entry.kind === 'shell') + assert(entry, 'AppsFolder must expose the system Settings entry') + const prepared = await request('prepareLaunch', { target: entry.id }) + assert.equal(prepared.authorization.persistable, false) + assert.deepEqual(await request('dispatchLaunch', { appHandle: prepared.appHandle }), { dispatched: true, verified: false }) + await assert.rejects(request('dispatchLaunch', { appHandle: prepared.appHandle }), { code: 'LAUNCH_ALREADY_DISPATCHED' }) + const until = performance.now() + 10000 + let target + do { + target = (await request('discoverWindows')).find(window => window.title === entry.displayName) + assert(performance.now() < until, 'Settings did not expose a selectable window') + if (!target) await delay(25) + } while (!target) + const [selected] = await request('prepareWindows', { ids: [target.windowId] }) + const observed = await request('getState', { appHandle: selected.appHandle, windowId: target.windowId, maxElements: 100, maxDepth: 20 }) + assert.equal(observed.windowId, target.windowId) + assert(observed.tree.length > 0) + return { entry: entry.id, window: target.title, axLength: observed.tree.length } + }) + await checked('An explicit executable path dispatches independently of Shell discovery', async () => { + const prepared = await request('prepareLaunch', { target: 'C:\\Windows\\System32\\notepad.exe' }) + assert.equal(prepared.authorization.persistable, false) + assert.deepEqual(await request('dispatchLaunch', { appHandle: prepared.appHandle }), { dispatched: true, verified: false }) + return { target: prepared.authorization.executablePath } + }) + const windows = await request('discoverWindows') + const selected = windows.filter(window => window.pid === initial.pid && window.title === 'DSH CUA owned test window') + assert.equal(selected.length, 1) + assert.equal(selected[0].appName, 'dsh-cua-desktop-fixture') + const windowId = selected[0].windowId + const [app] = await request('prepareWindows', { ids: [windowId] }) + const appHandle = app.appHandle + const state = () => request('getState', { appHandle, windowId, maxElements: 100, maxDepth: 20, details: true }) + const baseline = await cover() + let observation = await checked('UIA observation without foreground change', async () => { + const result = await state() + const after = await inspect('inspect') + assert.equal(after.foreground, baseline.foreground) + assert.deepEqual(after.cursor, baseline.cursor) + return result + }) + const index = (text) => { + const row = observation.tree.split('\n').find(row => row.includes(text)) + assert(row, `Missing UIA row for ${text}`) + const match = row.match(/\[(\d+)\]/) + assert(match, `Missing actionable index for ${text}`) + return Number(match[1]) + } + await checked('Background UIA value and invoke affect the target', async () => { + const valueResult = await request('setValue', { appHandle, snapshotId: observation.snapshotId, elementIndex: index('CUA test text'), value: '你好 😀 Windows' }) + const valued = await inspect('inspect') + assert.equal(typeof valueResult.foregroundChanged, 'boolean') + const clickResult = await request('click', { appHandle, snapshotId: observation.snapshotId, elementIndex: index('Record click') }) + const after = await inspect('inspect') + assert.equal(after.text, '你好 😀 Windows') + assert.equal(after.clicks, 1) + // UIA providers can activate after dispatch returns; later observations are separate samples. + assert.equal(typeof clickResult.foregroundChanged, 'boolean') + assert.deepEqual(after.cursor, baseline.cursor) + return { valueResult, clickResult, foregroundBefore: baseline.foreground, foregroundAfterValue: valued.foreground, after } + }) + for (const command of ['minimize', 'hide']) { + await checked(`show restores a ${command} window without activation`, async () => { + const foreground = (await cover()).foreground + const hidden = await inspect(command) + assert(command === 'minimize' ? hidden.minimized : !hidden.visible) + const restored = await request('show', { appHandle, windowId }) + assert.equal(restored.windowId, windowId) + const until = performance.now() + 5000 + let current + do { + current = await inspect('inspect') + assert(performance.now() < until, 'show did not restore the window') + } while (current.minimized || !current.visible) + assert.equal(current.foreground, foreground) + observation = await state() + return { restored, state: current } + }) + } + const covered = await cover() + await checked('Window capture without foreground change', async () => { + const capture = await request('screenshot', { appHandle, windowId }) + const after = await inspect('inspect') + assert.equal(after.foreground, covered.foreground) + assert.deepEqual(after.cursor, covered.cursor) + assert(capture.pixelWidth > 0 && capture.pixelHeight > 0) + assert(Buffer.from(capture.data, 'base64').subarray(0, 8).equals(Buffer.from('89504e470d0a1a0a', 'hex'))) + return { width: capture.pixelWidth, height: capture.pixelHeight, bounds: capture.bounds } + }) + await checked('Background global input refuses before typing', async () => { + const before = await inspect('inspect') + assert.notEqual(before.foreground, before.window, 'Fixture must be in the background for this check') + await assert.rejects(request('typeText', { appHandle, text: 'MUST NOT TYPE' }), { code: 'FOREGROUND_REQUIRED' }) + assert.equal((await inspect('inspect')).text, before.text) + }) + await checked('Explicit fixture focus permits Unicode input', async () => { + sentinel.process.stdin.write(`allow:${initial.pid}\n`) + assert.equal((await sentinel.read()).allowed, true) + const focused = await inspect('focus') + assert.equal(focused.foreground, focused.window) + await request('pressKey', { appHandle, key: 'Control+a' }) + await request('typeText', { appHandle, text: '实机 😀\r\nsecond line' }) + assert.equal((await inspect('inspect')).text, '实机 😀\r\nsecond line') + }) + await checked('Paste waits for consumption and updates the focused editor', async () => { + const previousClipboard = await inspect('clipboard-digest') + await request('pressKey', { appHandle, key: 'Control+a' }) + await request('paste', { appHandle, text: '剪贴板 😀', format: 'text', maxClipboardBytes: 4_194_304, + pasteReadTimeoutMs: 1000, maxElements: 100, maxDepth: 20 }) + // Clipboard consumption can precede the editor applying the retrieved text. + const until = performance.now() + 5000 + while ((await inspect('inspect')).text !== '剪贴板 😀') { + assert(performance.now() < until, 'The editor did not apply the pasted text') + await delay(25) + } + assert.deepEqual(await inspect('clipboard-digest'), previousClipboard, 'Paste must restore the prior clipboard text') + }) + observation = await state() + await checked('Hover remains in place through observation and capture', async () => { + const result = await request('hover', { appHandle, snapshotId: observation.snapshotId, elementIndex: index('Record click') }) + assert.equal(result.hoverRoute, 'system-pointer') + const hovered = await inspect('inspect') + await state() + await request('screenshot', { appHandle, windowId }) + assert.deepEqual((await inspect('inspect')).cursor, hovered.cursor) + }) + observation = await state() + await checked('Cancelled timed click releases its button before replying', async () => { + const id = String(++sequence) + socket.write(JSON.stringify({ id, method: 'click', params: { + appHandle, snapshotId: observation.snapshotId, elementIndex: index('Record click'), holdMs: 1000, + } }) + '\n') + const until = performance.now() + 5000 + while ((await inspect('inspect')).buttons !== 'Left') { + assert(performance.now() < until, 'Timed click never pressed its button') + } + socket.write(JSON.stringify({ type: 'cancel', id }) + '\n') + const cancelled = await read() + assert.equal(cancelled.error?.code, 'NATIVE_CANCELLED') + assert.equal((await inspect('inspect')).buttons, 'None') + }) + await checked('A sibling window in the same process cannot borrow the selected window grant', async () => { + const sibling = await inspect('sibling') + assert.equal(sibling.foreground, sibling.window) + await assert.rejects(request('typeText', { appHandle, text: 'must not arrive' }), { code: 'FOREGROUND_REQUIRED' }) + const entries = await request('discoverWindows') + const otherWindow = entries.find(window => window.pid === initial.pid && window.title === 'DSH CUA sibling test window') + assert(otherWindow) + await assert.rejects(request('getState', { appHandle, windowId: otherWindow.windowId, maxElements: 100, maxDepth: 20 }), { code: 'WINDOW_CHANGED' }) + await inspect('focus') + return { siblingWindowId: otherWindow.windowId, selectedWindowId: windowId } + }) + await checked('Resize invalidates coordinates before pointer input', async () => { + await inspect('resize') + await assert.rejects(request('click', { appHandle, windowId, x: 20, y: 20 }), { code: 'WINDOW_CHANGED' }) + }) + const closed = once(socket, 'close') + await checked('Agent cleanup returns an explicit acknowledgement before EOF', async () => { + assert.deepEqual(await exchange({ type: 'close' }), { type: 'closed' }) + await closed + if (bridge) assert.deepEqual(await bridge.exit, [0, null]) + }) + socket = undefined + helper.process.stdin.end() + assert.deepEqual(await helper.exit, [0, null]) + fixture.process.stdin.write('close\n') + assert.deepEqual(await fixture.exit, [0, null]) + sentinel.process.stdin.write('close\n') + assert.deepEqual(await sentinel.exit, [0, null]) +} finally { + socket?.destroy() + for (const resource of resources) { + resource.process.stdin.end() + if (resource.process.exitCode === null && resource.process.signalCode === null) resource.process.kill() + } + await Promise.allSettled(resources.map(resource => resource.exit)) + clearTimeout(deadline) + await writeFile(outputFile, JSON.stringify({ platform: process.platform, environment: wsl ? 'wsl' : 'windows', results }, null, 2) + '\n') +} diff --git a/packages/experimental/cua-windows/tests/desktop-tool.spec.ts b/packages/experimental/cua-windows/tests/desktop-tool.spec.ts new file mode 100644 index 0000000000..5fcb5c3c6d --- /dev/null +++ b/packages/experimental/cua-windows/tests/desktop-tool.spec.ts @@ -0,0 +1,71 @@ +/** Opt-in desktop screenshots through the actual CUA tool and attachment store. */ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { Context } from '@deepseek-ai/cordis' +import { mountAgentLoopTestDependencies, mountAgentLoopTestHarness } from '@deepseek-ai/dsh-agent-loop-testkit' +import ComputerUseRegistry from '@deepseek-ai/dsh-computer-use' +import LocalAttachmentStore from '@deepseek-ai/dsh-attachment-local' +import SubprocessLocal from '@deepseek-ai/dsh-subprocess-local' +import UserQuestions from '@deepseek-ai/dsh-user-questions' +import { LlmAdapter, ToolCallId, type LlmResolvedModelInfo, type StreamChunk } from '@deepseek-ai/dsh-llm' +import { SessionId } from '@deepseek-ai/dsh-session' +import { expect, it, onTestFinished } from 'vitest' +import { createCuaApi } from '@deepseek-ai/dsh-cua/api' +import sharp from 'sharp' +import * as Provider from '../src/index.ts' + +class ImageAdapter extends LlmAdapter { + override resolveModel(provider: string, model: string): Promise { + return Promise.resolve({ provider, id: model, name: model, inputModalities: ['text', 'image'] }) + } + stream(): AsyncIterable { throw new Error('Desktop tests do not request model generation') } +} +const helperPath = process.env.DSH_CUA_DESKTOP_TEST_HELPER +const selector = process.env.DSH_CUA_DESKTOP_TEST_APP +it.skipIf(!helperPath || !selector)('admits real application screenshots through the CUA tool', async () => { + const root = await mkdtemp(join(tmpdir(), 'dsh-cua-desktop-tool-')) + const ctx = new Context() + onTestFinished(async () => { try { await ctx.fiber.dispose() } finally { await rm(root, { recursive: true, force: true }) } }) + await mountAgentLoopTestDependencies(ctx) + await mountAgentLoopTestHarness(ctx) + await ctx.plugin(ComputerUseRegistry) + await ctx.plugin(SubprocessLocal) + await ctx.plugin(LocalAttachmentStore, { dshHome: root }) + await ctx.plugin(UserQuestions) + ctx.on('user-questions/request', async () => ({ answers: [{ id: 'cua-app-access', selected: ['Allow for this session'] }] })) + await ctx.plugin(Provider, { helperPath: helperPath!, agentPreset: false }) + ctx.llm.registerAdapter(['desktop-test'], new ImageAdapter()) + const owner = await ctx.agents.create({ sessionId: SessionId('desktop-screenshot'), agentOptions: { provider: 'desktop-test', model: 'vision' } }) + let sequence = 0 + const dispatch: Parameters[0] = async (operation) => { + const batch = await ctx.tools.execute({ agent: owner.agent, signal: new AbortController().signal, + calls: [{ type: 'tool-call', id: ToolCallId(`desktop-${++sequence}`), name: 'cua', arguments: JSON.stringify(operation) }] }) + expect(batch.results).toHaveLength(1) + const result = batch.results[0]!.result + expect(result.isError, JSON.stringify(result.content)).toBe(false) + return result.value! + } + const emitted: string[] = [] + const api = createCuaApi(dispatch, { + text: (text) => { emitted.push(text) }, + image: (image) => { expect(image.bytes.byteLength).toBeGreaterThan(0) }, + }) + const discovered = (await api.listApps({ emit: false })).find(app => + app.id === selector || app.displayName.toLowerCase() === selector?.toLowerCase()) + expect(discovered).toBeDefined() + const app = await api.getApp(discovered!.id) + const target = (await app.getWindows({ emit: false })).find(window => + window.isOnScreen && window.bounds.width > 0 && window.bounds.height > 0) + expect(target).toBeDefined() + const window = await app.getWindow(target!.windowId) + expect(emitted).toEqual([]) + await window.getAccessibilityTree() + expect(emitted).toHaveLength(1) + for (let i = 0; i < 5; ++i) { + const screenshot = await window.getScreenshot() + const decoded = await sharp(screenshot.bytes).raw().toBuffer({ resolveWithObject: true }) + expect(decoded.info.width).toBe(screenshot.pixelWidth) + expect(decoded.info.height).toBe(screenshot.pixelHeight) + } +}, 60_000) diff --git a/packages/experimental/cua-windows/tests/native-build.spec.ts b/packages/experimental/cua-windows/tests/native-build.spec.ts new file mode 100644 index 0000000000..9c9eb60aa9 --- /dev/null +++ b/packages/experimental/cua-windows/tests/native-build.spec.ts @@ -0,0 +1,61 @@ +/** The Windows compiler publishes one immutable executable and installed packages need no SDK. */ +import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it, onTestFinished, vi } from 'vitest' +import type { SubprocessHandle, SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess' +import { buildNativeExecutable, nativeExecutablePath, nativeHostArchitecture, prepareNativeExecutable } from '../src/native-build.ts' + +async function fixture() { + const root = await mkdtemp(join(tmpdir(), 'cua-windows-build-')) + onTestFinished(() => rm(root, { recursive: true, force: true })) + const packageRoot = join(root, 'packages/experimental/cua-windows') + await mkdir(packageRoot, { recursive: true }) + const bytes = Buffer.from('MZ Windows executable fixture') + const spawn = vi.fn((request: SubprocessSpawnSpec): SubprocessHandle => ({ + stdin: undefined, stdout: undefined, stderr: undefined, control: undefined, collected: {}, + done: (async () => { + const output = request.argv[request.argv.indexOf('--output') + 1]! + await mkdir(output, { recursive: true }) + await writeFile(join(output, 'dsh-cua-windows.exe'), bytes) + return { exitCode: 0, signal: null } + })(), + terminate: vi.fn(), waitForExit: async () => true, + })) + const spec = { packageRoot, architecture: 'x64' as const, dotnetPath: 'fixture-dotnet', subprocess: { spawn }, + signal: new AbortController().signal, timeoutMs: 60_000, graceMs: 1000 } + return { root, spec, spawn, bytes } +} + +it.each(['x64', 'arm64'])('accepts the Windows %s process target', (architecture) => { + expect(nativeHostArchitecture('win32', architecture)).toBe(architecture) +}) +it.each([['darwin', 'arm64'], ['linux', 'x64'], ['win32', 'ia32']])('rejects unsupported %s/%s runtime targets', (platform, architecture) => { + expect(() => nativeHostArchitecture(platform, architecture)).toThrow('requires Windows') +}) + +it('passes an explicit Windows RID and SDK to the managed compiler and retains the bytes', async () => { + const f = await fixture() + const output = await buildNativeExecutable(f.spec) + expect(await readFile(output)).toEqual(f.bytes) + expect(await readFile(nativeExecutablePath(f.spec.packageRoot, 'x64'))).toEqual(f.bytes) + expect(f.spawn.mock.calls[0]![0].argv).toEqual(expect.arrayContaining([ + 'fixture-dotnet', '--runtime', 'win-x64', '--self-contained', 'true', '-p:EnableWindowsTargeting=true', + ])) + expect(await buildNativeExecutable(f.spec)).toBe(output) +}) + +it('compiles a recognized source package and resolves an installed payload without a compiler', async () => { + const f = await fixture() + await writeFile(join(f.root, 'package.json'), JSON.stringify({ name: '@deepseek-ai/dsh-root' })) + expect(await prepareNativeExecutable(f.spec)).toContain('prepared') + expect(f.spawn).toHaveBeenCalledOnce() + await rm(join(f.root, 'package.json')) + expect(await prepareNativeExecutable(f.spec)).toBe(nativeExecutablePath(f.spec.packageRoot, 'x64')) + expect(f.spawn).toHaveBeenCalledOnce() + const controller = new AbortController() + controller.abort() + await expect(prepareNativeExecutable({ ...f.spec, signal: controller.signal })).rejects.toThrow() + await rm(nativeExecutablePath(f.spec.packageRoot, 'x64')) + await expect(prepareNativeExecutable(f.spec)).rejects.toThrow() +}) diff --git a/packages/experimental/cua-windows/tests/native-runtime.spec.ts b/packages/experimental/cua-windows/tests/native-runtime.spec.ts new file mode 100644 index 0000000000..b3eb03caf2 --- /dev/null +++ b/packages/experimental/cua-windows/tests/native-runtime.spec.ts @@ -0,0 +1,448 @@ +/** Real local pipes exercise Host ownership, Agent isolation, cancellation, and startup admission. */ +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { createConnection, createServer, type Socket } from 'node:net' +import { PassThrough } from 'node:stream' +import { randomUUID } from 'node:crypto' +import { once } from 'node:events' +import { expect, it, onTestFinished, vi } from 'vitest' +import type { SubprocessHandle, SubprocessOutcome, SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess' +import { NativeClient, type NativeClientConfig } from '@deepseek-ai/dsh-cua/native-client' +import { WindowsNativeRuntime } from '../src/native-runtime.ts' + +interface Frame { type?: string; id?: string; method?: string; runtimeKey?: string; config?: Record } +interface FixtureOptions { + transport?: 'pipe' | 'stdio' + startupDiagnostic?: string + startup?: 'wrong-runtime' | 'wrong-instance' | 'extra' | 'malformed' | 'oversized' | 'invalid-utf8' | 'exit' | 'silent' | 'stdout-error' | 'stdout-close' + handshake?: 'wrong-instance' | 'wrong-pid' | 'extra' | 'malformed' | 'oversized' | 'silent' | 'initial-result' + ignoreClose?: boolean + eofOnClose?: boolean + connectionCleanup?: Promise + ignoreParent?: boolean + processCleanup?: false | 'reject' + cleanupGate?: Promise + onSpawn?: () => void + split?: boolean +} + +async function fixture(options: FixtureOptions = {}) { + const directory = await mkdtemp(join(tmpdir(), 'cua-windows-pipes-')) + const clients: NativeClient[] = [] + const generations: Array<{ stop: () => Promise; stdout: PassThrough; received: Frame[]; peers: Set; endpoint: string }> = [] + const resources: { runtime?: WindowsNativeRuntime } = {} + onTestFinished(async () => { + await Promise.allSettled(clients.map(client => client.dispose())) + try { await resources.runtime?.dispose().catch(() => {}) } finally { + await Promise.all(generations.map(generation => generation.stop())) + await rm(directory, { recursive: true, force: true }) + } + }) + const helperPath = join(directory, 'helper.exe') + await writeFile(helperPath, 'Windows helper identity fixture') + const spawn = vi.fn((request: SubprocessSpawnSpec): SubprocessHandle => { + if (request.argv.includes('--bridge')) { + const socket = createConnection(generations.at(-1)!.endpoint) + const stdin = new PassThrough(), stdout = new PassThrough() + const done = Promise.withResolvers() + stdin.pipe(socket).pipe(stdout) + socket.on('error', (error) => { stdout.destroy(error) }) + socket.on('close', () => { done.resolve({ exitCode: 0, signal: null }) }) + return { stdin, stdout, stderr: undefined, control: undefined, collected: {}, done: done.promise, + terminate: () => { socket.destroy() }, waitForExit: async () => { await done.promise; return true } } + } + const instanceId = request.argv[request.argv.indexOf('--instance-id') + 1]! + const runtimeKey = request.argv[request.argv.indexOf('--runtime-key') + 1]! + const endpoint = process.platform === 'win32' ? `\\\\.\\pipe\\cua-test-${randomUUID()}` : join(directory, `${generations.length}.sock`) + const pid = 100 + generations.length + const stdin = new PassThrough(), stdout = new PassThrough() + const exited = Promise.withResolvers() + const ready: PromiseWithResolvers = Promise.withResolvers() + const peers = new Set() + const received: Frame[] = [] + let stopped: Promise | undefined + let diagnostic = '' + let nextConnection = 0 + const server = createServer({ allowHalfOpen: true }, (socket) => { + peers.add(socket) + socket.on('end', () => { socket.end() }) + const connection = ++nextConnection + socket.on('error', () => {}) + socket.on('close', () => { peers.delete(socket) }) + let buffered = '' + socket.on('data', (chunk: Buffer) => { + buffered += chunk.toString('utf8') + for (;;) { + const newline = buffered.indexOf('\n') + if (newline < 0) return + const frame = JSON.parse(buffered.slice(0, newline)) as Frame + buffered = buffered.slice(newline + 1) + received.push(frame) + if (frame.type === 'hello') { + if (options.handshake === 'silent') return + const response = { type: 'ready', protocol: 1, runtimeKey, instanceId: options.handshake === 'wrong-instance' ? 'other' : instanceId, + pid: options.handshake === 'wrong-pid' ? pid + 1 : pid, ...options.handshake === 'extra' ? { extra: true } : {} } + const text = options.handshake === 'malformed' ? '{bad}\n' : options.handshake === 'oversized' ? 'x'.repeat(8193) : JSON.stringify(response) + '\n' + if (options.split) { socket.write(text.slice(0, 4)); socket.write(text.slice(4)) } + else socket.write(text + (options.handshake === 'initial-result' ? '{"id":"early","result":true}\n' : '')) + } else if (frame.type === 'close') { + if (!options.ignoreClose) void (async () => { + await options.connectionCleanup + if (!options.eofOnClose) { + if (options.split) { socket.write('{"type":'); socket.write('"closed"}\n') } + else socket.write('{"type":"closed"}\n') + } + socket.end() + })() + } else if (frame.type === 'cancel') socket.write(JSON.stringify({ id: frame.id, error: { code: 'NATIVE_CANCELLED', message: 'Cancelled' } }) + '\n') + else if (frame.method !== 'hold') socket.write(JSON.stringify({ id: frame.id, result: { connection, pid, method: frame.method } }) + '\n') + } + }) + }) + const stop = (): Promise => stopped ??= (async () => { + await ready.promise + const closedPeers = [...peers].map(peer => once(peer, 'close')) + for (const peer of peers) peer.destroy() + await Promise.all(closedPeers) + await new Promise((resolve, reject) => server.close((error) => { if (error) reject(error); else resolve() })) + const ended = options.startup === 'exit' ? once(stdout, 'end') : undefined + stdout.end() + await ended + diagnostic = options.startupDiagnostic ?? '' + exited.resolve({ exitCode: options.startup === 'exit' ? 1 : 0, signal: null }) + })() + stdin.on('finish', () => { if (!options.ignoreParent) void stop() }) + server.on('error', (error) => { ready.reject(error); exited.reject(error) }) + server.listen(endpoint, () => { + ready.resolve() + if (options.startup === 'silent') return + if (options.startup === 'stdout-error') { stdout.destroy(new Error('readiness IO failure')); return } + if (options.startup === 'stdout-close') { stdout.end(); return } + if (options.startup === 'exit') { void stop(); return } + const response = { type: 'ready', protocol: 1, endpoint, pid, + runtimeKey: options.startup === 'wrong-runtime' ? 'other' : runtimeKey, + instanceId, launcherId: options.startup === 'wrong-instance' ? 'other' : instanceId } + const text = options.startup === 'malformed' ? '{bad}\n' : options.startup === 'oversized' ? 'x'.repeat(8193) + : JSON.stringify(response) + '\n' + (options.startup === 'extra' ? 'extra' : '') + if (options.startup === 'invalid-utf8') stdout.write(Buffer.from([255, 10])) + else if (options.split) { stdout.write(text.slice(0, 5)); stdout.write(text.slice(5)) } + else stdout.write(text) + }) + generations.push({ stop, stdout, received, peers, endpoint }) + options.onSpawn?.() + return { stdin, stdout, stderr: undefined, control: undefined, + collected: { stderr: { readFrom: () => ({ text: diagnostic, nextOffset: Buffer.byteLength(diagnostic), lossy: false }) } }, + done: exited.promise, + terminate: () => { void stop() }, waitForExit: async () => { await exited.promise; await options.cleanupGate; if (options.processCleanup === 'reject') throw new Error('cleanup failed'); return options.processCleanup !== false } } + }) + const owner = { subprocess: { spawn } } + const runtime = new WindowsNativeRuntime(owner, 25, options.transport) + resources.runtime = runtime + const activeRuntime = runtime + const config: NativeClientConfig = { helperPath, cwd: directory, timeoutMs: 30_000, connectTimeoutMs: 5000, + screenshotTimeoutMs: 5000, axTimeoutMs: 3000, maxRequestBytes: 1_048_576, maxResponseBytes: 1_048_576, + graceMs: 3000, textEventIntervalMs: 0, maxClickHoldMs: 10_000 } + const client = () => { + const value = new NativeClient(owner, config, (_owner, native) => activeRuntime.connect(native)) + clients.push(value) + return value + } + return { directory, config, spawn, generations, runtime, client } +} + +it('shares one Host helper while closing only the selected Agent connection', async () => { + const f = await fixture({ split: true }) + const a = f.client(), b = f.client(), signal = new AbortController().signal + expect(await a.request('one', {}, signal)).toMatchObject({ connection: 1, pid: 100 }) + expect(await b.request('two', {}, signal)).toMatchObject({ connection: 2, pid: 100 }) + expect(f.spawn).toHaveBeenCalledOnce() + expect(f.generations[0]!.received[0]?.config?.pollIntervalMs).toBe(25) + await a.dispose() + expect(await b.request('after-close', {}, signal)).toMatchObject({ connection: 2 }) + await b.dispose() + await vi.waitFor(() => { expect(f.generations[0]!.peers.size).toBe(0) }) + await f.runtime.dispose() + expect(() => f.runtime.connect(f.config)).toThrow('disposed') +}) + +it('cancels a request without replacing the connection or replaying input', async () => { + const f = await fixture() + const client = f.client(), controller = new AbortController() + const pending = client.request('hold', {}, controller.signal) + const refused = expect(pending).rejects.toThrow('cancelled') + await vi.waitFor(() => { expect(f.generations[0]?.received.some(frame => frame.method === 'hold')).toBe(true) }) + controller.abort() + await refused + expect(client.disposed).toBe(false) + expect(await client.request('next', {}, new AbortController().signal)).toMatchObject({ connection: 1 }) + expect(f.generations[0]!.received.filter(frame => frame.method === 'hold')).toHaveLength(1) +}) + +it('starts a fresh helper after process loss and makes the old client unusable', async () => { + const f = await fixture(), signal = new AbortController().signal + const first = f.client() + await first.request('first', {}, signal) + await f.generations[0]!.stop() + await vi.waitFor(() => { expect(first.disposed).toBe(true) }) + await expect(first.dispose()).rejects.toThrow('cleanup acknowledgement') + const next = f.client() + expect(await next.request('fresh', {}, signal)).toMatchObject({ pid: 101, connection: 1 }) + expect(f.spawn).toHaveBeenCalledTimes(2) +}) + +it.each(['wrong-runtime', 'wrong-instance', 'extra', 'malformed', 'oversized', 'invalid-utf8', 'exit'] as const)( + 'rejects %s startup before sending any desktop request', async (startup) => { + const f = await fixture({ startup }) + await expect(f.client().request('input', {}, new AbortController().signal)).rejects.toThrow() + expect(f.generations[0]!.received.filter(frame => frame.method)).toEqual([]) + }, +) + +it.each(['wrong-instance', 'wrong-pid', 'extra', 'malformed', 'oversized'] as const)( + 'rejects a %s Agent handshake before dispatch', async (handshake) => { + const f = await fixture({ handshake }) + await expect(f.client().request('input', {}, new AbortController().signal)).rejects.toThrow() + expect(f.generations[0]!.received.filter(frame => frame.method)).toEqual([]) + }, +) + +it('reports the helper exit diagnostic when stdout ends before process settlement', async () => { + const f = await fixture({ startup: 'exit', startupDiagnostic: 'Application-control policy refused the executable' }) + const pending = f.client().request('getCapabilities', {}, new AbortController().signal) + await expect(pending).rejects.toMatchObject({ code: 'NATIVE_EXITED' }) + await expect(pending).rejects.toThrow('Application-control policy refused the executable') + expect(f.generations[0]!.received).toEqual([]) + await f.runtime.dispose() +}) + +it('joins a connection closed before helper readiness', async () => { + const f = await fixture() + const client = f.client() + await client.dispose() + expect(client.disposed).toBe(true) + await f.runtime.dispose() +}) + +it('settles a queued write when its connection is closed before readiness', async () => { + const f = await fixture() + const channel = f.runtime.connect(f.config) + const written = new Promise(resolve => channel.stdin.write('input\n', resolve)) + channel.close() + expect(await written).toBeInstanceOf(Error) + await channel.waitForClose() +}) + +it('ends the native connection when its writable stream is finalized', async () => { + const f = await fixture() + const channel = f.runtime.connect(f.config) + channel.stdin.end() + await channel.done + await channel.waitForClose() +}) + +it('rejects unsolicited process output and closes the admitted Agent', async () => { + const f = await fixture() + const client = f.client() + await client.request('ready', {}, new AbortController().signal) + f.generations[0]!.stdout.write('unexpected\n') + await vi.waitFor(() =>{ expect(client.disposed).toBe(true) }) + await expect(client.dispose()).rejects.toThrow('cleanup acknowledgement') +}) + +it('closes all active Agent connections when the Host unloads', async () => { + const f = await fixture() + const client = f.client() + await client.request('ready', {}, new AbortController().signal) + await f.runtime.dispose() + await vi.waitFor(() =>{ expect(client.disposed).toBe(true) }) +}) + +it.each(['silent', 'stdout-error', 'stdout-close'] as const)('settles %s process startup and joins cleanup', async (startup) => { + const f = await fixture({ startup }) + f.config.connectTimeoutMs = 100 + await expect(f.client().request('input', {}, new AbortController().signal)).rejects.toThrow() + await f.runtime.dispose() + expect(f.generations[0]!.received).toEqual([]) +}) + +it('bounds a silent Agent handshake without sending desktop input', async () => { + const f = await fixture({ handshake: 'silent' }) + f.config.connectTimeoutMs = 100 + await expect(f.client().request('input', {}, new AbortController().signal)).rejects.toThrow() + expect(f.generations[0]!.received.map(frame => frame.type)).toEqual(['hello']) +}) + +it('preserves bytes after pipe readiness for the request parser', async () => { + const f = await fixture({ handshake: 'initial-result' }) + const channel = f.runtime.connect(f.config) + const data = new Promise(resolve => channel.stdout.once('data', (chunk) =>{ resolve(String(chunk)) })) + expect(await data).toContain('"id":"early"') + channel.close() + await channel.waitForClose() +}) + +it('rejects a connection cleanup deadline and stops the Host process', async () => { + const f = await fixture({ ignoreClose: true, ignoreParent: true }) + f.config.graceMs = 100 + const channel = f.runtime.connect(f.config) + const response = new Promise(resolve => channel.stdout.once('data', () =>{ resolve() })) + channel.stdin.write('{"id":"one","method":"probe"}\n') + await response + await expect(f.runtime.dispose()).rejects.toThrow('cleanup failed') + await expect(channel.done).rejects.toThrow('cleanup') + await expect(channel.waitForClose()).rejects.toThrow('cleanup acknowledgement') +}) + +it.each([false, 'reject'] as const)('reports unsuccessful process-range cleanup: %s', async (processCleanup) => { + const f = await fixture({ processCleanup }) + await f.client().request('one', {}, new AbortController().signal) + await expect(f.runtime.dispose()).rejects.toThrow('cleanup failed') +}) + +it('refuses writes after a ready connection starts closing', async () => { + const f = await fixture() + const channel = f.runtime.connect(f.config) + const response = new Promise(resolve => channel.stdout.once('data', () =>{ resolve() })) + channel.stdin.write('{"id":"one","method":"probe"}\n') + await response + channel.close() + const error = await new Promise(resolve => channel.stdin.write('late\n', resolve)) + expect(error?.message).toContain('closing') + await channel.waitForClose() +}) + +it('joins shutdown requested synchronously while the subprocess is being acquired', async () => { + const options: FixtureOptions = {} + const f = await fixture(options) + let closing: Promise | undefined + options.onSpawn = () => { closing = f.runtime.dispose() } + await expect(f.client().request('input', {}, new AbortController().signal)).rejects.toThrow() + await closing +}) + +it('reports an untyped subprocess rejection as a request failure', async () => { + const f = await fixture() + f.spawn.mockImplementationOnce(() => { throw 'subprocess failure' }) + const channel = f.runtime.connect(f.config) + await expect(channel.done).rejects.toThrow('subprocess failure') + await channel.waitForClose() +}) + +it('forces a helper that ignores parent closure to stop after malformed readiness', async () => { + const f = await fixture({ startup: 'malformed', ignoreParent: true }) + f.config.graceMs = 100 + await expect(f.client().request('input', {}, new AbortController().signal)).rejects.toThrow() + await f.runtime.dispose() +}) + +it('contains a cleanup failure after unsolicited process output', async () => { + const f = await fixture({ processCleanup: 'reject' }) + const client = f.client() + await client.request('ready', {}, new AbortController().signal) + f.generations[0]!.stdout.write('unexpected\n') + await vi.waitFor(() =>{ expect(client.disposed).toBe(true) }) + await expect(f.runtime.dispose()).rejects.toThrow('cleanup failed') +}) + +it('does not restart a stopped helper while the Host is unloading', async () => { + const release: PromiseWithResolvers = Promise.withResolvers() + onTestFinished(() =>{ release.resolve() }) + const f = await fixture({ cleanupGate: release.promise }) + await f.client().request('ready', {}, new AbortController().signal) + await f.generations[0]!.stop() + await vi.waitFor(() =>{ expect(f.generations[0]!.stdout.readableEnded).toBe(true) }) + const channel = f.runtime.connect(f.config) + const done = expect(channel.done).resolves.toBeUndefined() + const closing = f.runtime.dispose() + release.resolve() + await Promise.all([done, closing]) + expect(f.spawn).toHaveBeenCalledOnce() +}) + +it('waits for the native cleanup frame even after an operation has completed', async () => { + const release: PromiseWithResolvers = Promise.withResolvers() + const f = await fixture({ connectionCleanup: release.promise }) + const client = f.client() + await client.request('one', {}, new AbortController().signal) + let settled = false + const closing = client.dispose().then(() => { settled = true }) + try { + await vi.waitFor(() => { expect(f.generations[0]!.received.some(frame => frame.type === 'close')).toBe(true) }) + expect(settled).toBe(false) + } finally { release.resolve() } + await closing + expect(settled).toBe(true) +}) + +it('refuses EOF as evidence that native connection cleanup completed', async () => { + const f = await fixture({ eofOnClose: true }) + const client = f.client() + await client.request('one', {}, new AbortController().signal) + await expect(client.dispose()).rejects.toThrow('cleanup acknowledgement') +}) + +it('rejects an unsolicited cleanup frame while an Agent is still active', async () => { + const f = await fixture() + const client = f.client() + await client.request('one', {}, new AbortController().signal) + for (const peer of f.generations[0]!.peers) peer.write('{"type":"closed"}\n') + await vi.waitFor(() => { expect(client.disposed).toBe(true) }) + await expect(client.dispose()).rejects.toThrow('cleanup acknowledgement') +}) + +it('recognizes fragmented cleanup controls without buffering operation payloads', async () => { + const f = await fixture({ ignoreClose: true }) + const channel = f.runtime.connect(f.config) + const ready = once(channel.stdout, 'data') + channel.stdin.write('{"id":"one","method":"probe"}\n') + await ready + const peer = [...f.generations[0]!.peers][0]! + const send = async (part: string) => { + const received = once(channel.stdout, 'data') + peer.write(part) + expect(String((await received)[0])).toBe(part) + } + await send('{"id":') + await send('"two","result":"a long ') + await send('fragmented operation payload') + await send('"}\n') + channel.close() + peer.write('{"type":') + peer.end('"closed"}\n') + await channel.waitForClose() +}) + + +it('joins WSL bridge EOF after cleanup while keeping other Agents usable', async () => { + const f = await fixture({ transport: 'stdio', split: true }) + const a = f.client(), b = f.client(), signal = new AbortController().signal + expect(await a.request('first', {}, signal)).toMatchObject({ connection: 1 }) + expect(await b.request('second', {}, signal)).toMatchObject({ connection: 2 }) + expect(f.spawn.mock.calls.filter(([spec]) => spec.argv.includes('--serve'))).toHaveLength(1) + expect(f.spawn.mock.calls.filter(([spec]) => spec.argv.includes('--bridge'))).toHaveLength(2) + await a.dispose() + expect(await b.request('still-open', {}, signal)).toMatchObject({ connection: 2 }) + await b.dispose() + await f.runtime.dispose() + expect(f.generations[0]!.peers.size).toBe(0) +}) + +it('forwards cancellation over WSL without replaying the request', async () => { + const f = await fixture({ transport: 'stdio' }) + const client = f.client(), controller = new AbortController() + const pending = client.request('hold', {}, controller.signal) + const rejected = expect(pending).rejects.toThrow('cancelled') + await vi.waitFor(() => { expect(f.generations[0]?.received.some(frame => frame.method === 'hold')).toBe(true) }) + controller.abort() + await rejected + expect(await client.request('next', {}, new AbortController().signal)).toMatchObject({ connection: 1 }) + expect(f.generations[0]!.received.filter(frame => frame.method === 'hold')).toHaveLength(1) +}) + +it('rejects WSL EOF without a desktop cleanup acknowledgement', async () => { + const f = await fixture({ transport: 'stdio', eofOnClose: true }) + const client = f.client() + await client.request('ready', {}, new AbortController().signal) + await expect(client.dispose()).rejects.toThrow('cleanup acknowledgement') +}) diff --git a/packages/experimental/cua-windows/tests/native-transport.spec.ts b/packages/experimental/cua-windows/tests/native-transport.spec.ts new file mode 100644 index 0000000000..276b5ad786 --- /dev/null +++ b/packages/experimental/cua-windows/tests/native-transport.spec.ts @@ -0,0 +1,29 @@ +/** WSL bridge exit is part of native connection cleanup, independently of protocol EOF. */ +import { PassThrough } from 'node:stream' +import { expect, it, onTestFinished } from 'vitest' +import type { NativeClientConfig } from '@deepseek-ai/dsh-cua/native-client' +import type { SubprocessHandle, SubprocessOutcome } from '@deepseek-ai/dsh-subprocess' +import { connectWindowsPipe } from '../src/native-transport.ts' + +it.each([ + { exitCode: 0, signal: null, joined: true, error: undefined }, + { exitCode: 1, signal: null, joined: true, error: 'exited unsuccessfully' }, + { exitCode: 0, signal: null, joined: false, error: 'did not exit' }, +] as const)('joins bridge exit $exitCode with process cleanup $joined', async ({ exitCode, signal, joined, error }) => { + const stdin = new PassThrough(), stdout = new PassThrough() + const done = Promise.withResolvers() + const handle: SubprocessHandle = { stdin, stdout, stderr: undefined, control: undefined, collected: {}, + done: done.promise, terminate: () => { done.resolve({ exitCode: null, signal: 'SIGTERM' }) }, + waitForExit: async () => joined } + const config: NativeClientConfig = { helperPath: '/fixture.exe', cwd: '/', timeoutMs: 30_000, connectTimeoutMs: 5000, + screenshotTimeoutMs: 5000, axTimeoutMs: 3000, maxRequestBytes: 1_048_576, maxResponseBytes: 1_048_576, + graceMs: 3000, textEventIntervalMs: 0, maxClickHoldMs: 10_000 } + const connection = connectWindowsPipe({ spawn: () => handle }, config, 'pipe', 'digest', 'stdio') + connection.stream.on('error', () => {}) + onTestFinished(() => { connection.stream.destroy(); stdin.destroy(); stdout.destroy() }) + const closing = connection.dispose() + expect(stdin.writableEnded).toBe(true) + done.resolve({ exitCode, signal }) + if (error) await expect(closing).rejects.toThrow(error) + else await closing +}) diff --git a/packages/experimental/cua-windows/tests/protocol.spec.ts b/packages/experimental/cua-windows/tests/protocol.spec.ts new file mode 100644 index 0000000000..0064d22ccb --- /dev/null +++ b/packages/experimental/cua-windows/tests/protocol.spec.ts @@ -0,0 +1,30 @@ +/** Both native languages admit the same generated model and Host operation fields. */ +import { readFile } from 'node:fs/promises' +import { expect, it } from 'vitest' +import { nativeProtocol } from '@deepseek-ai/dsh-cua/native-schema' +import { ActionResult, NativeScreenshotResult } from '@deepseek-ai/dsh-cua/protocol' +import { Config } from '../src/index.ts' + +it('keeps the C# admission schema identical to the shared generated schema', async () => { + expect(await readFile(new URL('../native/protocol.schema.json', import.meta.url), 'utf8')).toBe(nativeProtocol().json) +}) + +it('preserves Windows physical capture units and observed foreground changes', () => { + const image = { mimeType: 'image/png', data: 'AAAA', pixelWidth: 1200, pixelHeight: 800, windowId: 1, + bounds: { x: -1200, y: 0, width: 1200, height: 800 }, coordinateSpace: 'window-pixels' } + expect(NativeScreenshotResult.parse(image).coordinateSpace).toBe('window-pixels') + expect(() => NativeScreenshotResult.parse({ ...image, coordinateSpace: 'screen-pixels' })).toThrow() + expect(ActionResult.parse({ dispatched: true, verified: false, foregroundChanged: true })).toEqual({ + dispatched: true, foregroundChanged: true, + }) +}) + +it('resolves Windows compiler and input defaults while rejecting unsupported numeric limits', () => { + const resolved = Config({}) + expect(resolved.dotnetPath).toBe('dotnet') + expect(resolved.pollIntervalMs).toBe(25) + expect(resolved.textEventIntervalMs).toBe(0) + expect(() => Config({ dotnetPath: '' })).toThrow() + expect(() => Config({ pollIntervalMs: 0 })).toThrow() + expect(() => Config({ maxResponseBytes: 2 ** 31 })).toThrow() +}) diff --git a/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts new file mode 100644 index 0000000000..4b1f2bf622 --- /dev/null +++ b/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts @@ -0,0 +1,108 @@ +/** Provider preparation must finish before installation and join cancellation on unload. */ +import { resolve } from 'node:path' +import { Context } from '@deepseek-ai/cordis' +import type { WslPreparation } from '../src/windows-host.ts' +import type { NativeBuildSpec } from '../src/native-build.ts' +import type { installCua } from '@deepseek-ai/dsh-cua' +import { beforeEach, expect, it, onTestFinished, vi } from 'vitest' +import { apply, Config } from '../src/index.ts' +import { GUIDANCE } from '../src/guidance.ts' + +const native = vi.hoisted(() => ({ + prepare: vi.fn<(spec: NativeBuildSpec) => Promise>(), + host: vi.fn<() => 'windows' | 'wsl'>(() => 'windows'), + wsl: vi.fn<(spec: WslPreparation) => Promise<{ architecture: 'arm64'; cacheDirectory: string }>>(), + retain: vi.fn<(path: string, cache: string, signal: AbortSignal) => Promise>(), + architecture: vi.fn(() => 'x64' as const), + install: vi.fn(), connect: vi.fn(), dispose: vi.fn(), construct: vi.fn(), +})) +vi.mock('../src/windows-host.ts', () => ({ windowsHost: native.host, prepareWsl: native.wsl, retainWslHelper: native.retain })) +vi.mock('../src/native-build.ts', async original => ({ + ...await original(), + prepareNativeExecutable: native.prepare, nativeHostArchitecture: native.architecture, +})) +vi.mock('@deepseek-ai/dsh-cua', async original => ({ + ...await original(), installCua: native.install, +})) +vi.mock('../src/native-runtime.ts', () => ({ WindowsNativeRuntime: class { + constructor(...args: unknown[]) { native.construct(...args) } + connect = native.connect + dispose = native.dispose +} })) +beforeEach(() => { vi.clearAllMocks(); native.host.mockReturnValue('windows'); native.prepare.mockResolvedValue(resolve('prepared-helper')); native.dispose.mockResolvedValue(undefined) }) +function owner() { const ctx = new Context(); onTestFinished(() => ctx.fiber.dispose()); return ctx } + +it('rejects relative overrides before installing a native provider', async () => { + await expect(apply(owner(), Config({ helperPath: 'relative.exe' }))).rejects.toThrow('must be absolute') + expect(native.install).not.toHaveBeenCalled() +}) +it('uses an absolute fixture without compiling and disposes the Host runtime', async () => { + const ctx = owner(), config = Config({ helperPath: resolve('fixture.exe'), pollIntervalMs: 13 }) + await apply(ctx, config) + expect(native.prepare).not.toHaveBeenCalled() + expect(native.construct).toHaveBeenCalledWith(ctx, 13, 'pipe') + const backend = native.install.mock.calls[0]![2] + expect(backend.guidance).toBe(GUIDANCE) + expect(backend.capabilities).toMatchObject({ platform: 'windows', appLevelAccessibility: false, keyboard: ['window'] }) + const channel = { marker: 'native stream' } + native.connect.mockReturnValue(channel) + const options = { ...config, helperPath: backend.helperPath, cwd: process.cwd() } + expect(backend.createChannel(ctx, options)).toBe(channel) + expect(native.connect).toHaveBeenCalledWith(options) + await ctx.fiber.dispose() + expect(native.dispose).toHaveBeenCalledOnce() +}) +it('prepares before installation and aborts the completed preparation scope on unload', async () => { + const ctx = owner(), prepared = Promise.withResolvers() + native.prepare.mockReturnValueOnce(prepared.promise) + const pending = apply(ctx, Config({})) + expect(native.install).not.toHaveBeenCalled() + prepared.resolve(resolve('compiled.exe')) + await pending + expect(native.install.mock.calls[0]![2].helperPath).toBe(resolve('compiled.exe')) + await ctx.fiber.dispose() + expect(native.prepare.mock.calls[0]![0].signal.aborted).toBe(true) +}) +it('reports compiler failure without installing tool registrations', async () => { + native.prepare.mockRejectedValueOnce(new Error('compiler unavailable')) + const ctx = owner() + await expect(apply(ctx, Config({}))).rejects.toThrow('compiler unavailable') + await ctx.fiber.dispose() + expect(native.install).not.toHaveBeenCalled() +}) +it('joins canceled preparation and rejects its late success', async () => { + const ctx = owner(), prepared = Promise.withResolvers() + onTestFinished(() =>{ prepared.resolve(resolve('late.exe')) }) + native.prepare.mockReturnValueOnce(prepared.promise) + const starting = apply(ctx, Config({})) + const rejected = expect(starting).rejects.toThrow() + const signal = native.prepare.mock.calls[0]![0].signal + const aborted = new Promise((resolve) =>{ signal.addEventListener('abort', () =>{ resolve() }, { once: true }) }) + let closed = false + const closing = ctx.fiber.dispose().then(() => { closed = true }) + await aborted + expect(closed).toBe(false) + prepared.resolve(resolve('late.exe')) + await Promise.all([rejected, closing]) + expect(native.install).not.toHaveBeenCalled() +}) + +it('prepares the Windows architecture and stdio transport for WSL', async () => { + native.host.mockReturnValue('wsl') + native.wsl.mockResolvedValue({ architecture: 'arm64', cacheDirectory: '/mnt/c/cache' }) + native.retain.mockResolvedValue('/mnt/c/cache/helper.exe') + const ctx = owner() + await apply(ctx, Config({})) + expect(native.prepare.mock.calls[0]![0].architecture).toBe('arm64') + expect(native.architecture).not.toHaveBeenCalled() + expect(native.construct).toHaveBeenCalledWith(ctx, 25, 'stdio') + expect(native.install.mock.calls[0]![2].helperPath).toBe('/mnt/c/cache/helper.exe') +}) + +it('does not compile or register CUA when WSL interoperation fails', async () => { + native.host.mockReturnValue('wsl') + native.wsl.mockRejectedValue(new Error('Windows interoperation unavailable')) + await expect(apply(owner(), Config({}))).rejects.toThrow('interoperation unavailable') + expect(native.prepare).not.toHaveBeenCalled() + expect(native.install).not.toHaveBeenCalled() +}) diff --git a/packages/experimental/cua-windows/tests/windows-host.spec.ts b/packages/experimental/cua-windows/tests/windows-host.spec.ts new file mode 100644 index 0000000000..3d27b5d1dc --- /dev/null +++ b/packages/experimental/cua-windows/tests/windows-host.spec.ts @@ -0,0 +1,66 @@ +/** WSL classification is independent of Windows interoperation and executable preparation. */ +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it, onTestFinished, vi } from 'vitest' +import type { SubprocessHandle, SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess' +import { prepareWsl, retainWslHelper, windowsHost } from '../src/windows-host.ts' + +it('distinguishes Windows Node, WSL Linux Node, and ordinary Linux', () => { + expect(windowsHost({ platform: 'win32', env: { WSL_DISTRO_NAME: 'Ubuntu' } })).toBe('windows') + expect(windowsHost({ platform: 'linux', env: {}, osRelease: '6.6.87-microsoft-standard-WSL2' })).toBe('wsl') + expect(() => windowsHost({ platform: 'linux', env: {}, osRelease: '6.8.0-generic' })).toThrow('ordinary Linux') +}) + +function fixture(output = '{"architecture":"arm64","cache":"C:\\\\Users\\\\test user\\\\AppData\\\\Local\\\\DeepSeekHarness\\\\cua"}', exitCode = 0) { + const terminate = vi.fn(), waitForExit = vi.fn(async () => true) + const spawn = vi.fn((spec: SubprocessSpawnSpec): SubprocessHandle => { + const text = spec.argv[0] === 'wslpath' ? '/mnt/c/Users/test user/AppData/Local/DeepSeekHarness/cua\n' : output + return { stdin: undefined, stdout: undefined, stderr: undefined, control: undefined, + collected: { stdout: { readFrom: () => ({ text, nextOffset: Buffer.byteLength(text), lossy: false }) } }, + done: Promise.resolve({ exitCode, signal: null }), terminate, waitForExit } + }) + return { spec: { subprocess: { spawn }, signal: new AbortController().signal, timeoutMs: 10_000, graceMs: 1000, powershellPath: 'powershell.exe' }, spawn, terminate, waitForExit } +} + +it('uses the Windows architecture and translates the cache without shell interpolation', async () => { + const f = fixture() + expect(await prepareWsl(f.spec)).toEqual({ architecture: 'arm64', cacheDirectory: '/mnt/c/Users/test user/AppData/Local/DeepSeekHarness/cua' }) + expect(f.spawn.mock.calls[1]![0].argv).toEqual(['wslpath', '-u', 'C:\\Users\\test user\\AppData\\Local\\DeepSeekHarness\\cua']) + expect(f.waitForExit).toHaveBeenCalledTimes(2) +}) + +it.each(['not json', '{"architecture":"ia32","cache":"C:\\\\cache"}', '{"architecture":"x64","cache":"relative"}'])( + 'rejects invalid Windows capability output %s before using it as a path', async (output) => { + const f = fixture(output) + await expect(prepareWsl(f.spec)).rejects.toThrow('WSL cannot prepare') + expect(f.spawn).toHaveBeenCalledOnce() + expect(f.waitForExit).toHaveBeenCalledOnce() + }, +) + +it('reports unavailable interoperation and does not launch path conversion', async () => { + const f = fixture('', 1) + await expect(prepareWsl(f.spec)).rejects.toThrow('WSL cannot prepare') + expect(f.spawn).toHaveBeenCalledOnce() +}) + +it('rejects canceled preparation before starting a Windows command', async () => { + const f = fixture(), controller = new AbortController() + controller.abort(new Error('provider unloaded')) + await expect(prepareWsl({ ...f.spec, signal: controller.signal })).rejects.toThrow('provider unloaded') + expect(f.spawn).not.toHaveBeenCalled() +}) + +it('retains exact helper bytes once and rejects a changed cached executable', async () => { + const directory = await mkdtemp(join(tmpdir(), 'cua-wsl-cache-')) + onTestFinished(() => rm(directory, { recursive: true, force: true })) + const helper = join(directory, 'source.exe'), signal = new AbortController().signal + const bytes = Buffer.from('signed payload bytes') + await writeFile(helper, bytes) + const result = await retainWslHelper(helper, join(directory, 'cache'), signal) + expect(await readFile(result)).toEqual(bytes) + expect(await retainWslHelper(helper, join(directory, 'cache'), signal)).toBe(result) + await writeFile(result, 'changed') + await expect(retainWslHelper(helper, join(directory, 'cache'), signal)).rejects.toThrow('digest') +}) diff --git a/packages/experimental/cua-windows/tsconfig.json b/packages/experimental/cua-windows/tsconfig.json new file mode 100644 index 0000000000..0d2d829073 --- /dev/null +++ b/packages/experimental/cua-windows/tsconfig.json @@ -0,0 +1,30 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../cua/tsconfig.host.json" + }, + { + "path": "../../subprocess/subprocess" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../../util/native-command" + }, + { + "path": "../../util/atomic-write" + } + ] +} diff --git a/packages/experimental/cua/src/access-types.ts b/packages/experimental/cua/src/access-types.ts index 4679f7ba14..0a587124d4 100644 --- a/packages/experimental/cua/src/access-types.ts +++ b/packages/experimental/cua/src/access-types.ts @@ -10,7 +10,7 @@ export interface CuaPermissionProcess { path?: string | undefined name?: string | undefined } -/** Native access observations tagged with Node platform identifiers; distinct from model capability platform names. */ +/** Native access observations tagged with the provider's CUA platform; distinct from Node process.platform values. */ export type CuaSystemPermissionState = { platform: 'darwin' accessibility: boolean @@ -20,7 +20,7 @@ export type CuaSystemPermissionState = { /** Application macOS reports as responsible for the helper, captured at startup; absent when it cannot be identified. */ launchApplication?: { name: string; path: string; icon?: string | undefined } | undefined } | { - platform: 'win32' + platform: 'windows' sessionLocked: boolean | null captureAvailable: boolean elevated: boolean diff --git a/packages/experimental/cua/src/access.ts b/packages/experimental/cua/src/access.ts index 35fe5a60a1..535bfe84fb 100644 --- a/packages/experimental/cua/src/access.ts +++ b/packages/experimental/cua/src/access.ts @@ -24,7 +24,7 @@ const systemPermissions = z.discriminatedUnion('platform', [z.object({ platform: z.literal('darwin'), accessibility: z.boolean(), screenRecording: z.boolean(), helper: permissionProcess, parent: permissionProcess, launchApplication: z.object({ name: z.string().min(1), path: z.string().min(1), icon: ApplicationIcon.optional() }).optional(), }), z.object({ - platform: z.literal('win32'), sessionLocked: z.boolean().nullable(), captureAvailable: z.boolean(), + platform: z.literal('windows'), sessionLocked: z.boolean().nullable(), captureAvailable: z.boolean(), elevated: z.boolean(), helper: permissionProcess, })]) diff --git a/packages/experimental/cua/src/client/PermissionPanel.tsx b/packages/experimental/cua/src/client/PermissionPanel.tsx index 699fd8b413..fdc43b5e7c 100644 --- a/packages/experimental/cua/src/client/PermissionPanel.tsx +++ b/packages/experimental/cua/src/client/PermissionPanel.tsx @@ -142,7 +142,7 @@ function UnknownStatus({ loading, t }: Pick & { loading: b } function WindowsStatus({ system, uncertain, t }: Pick & { - system: Extract + system: Extract uncertain: boolean }) { const unlocked = system.sessionLocked === false @@ -161,7 +161,7 @@ function WindowsStatus({ system, uncertain, t }: Pick & { function systemReady(system: CuaSystemPermissionState): boolean { switch (system.platform) { case 'darwin': return system.accessibility && system.screenRecording - case 'win32': return system.sessionLocked === false && system.captureAvailable + case 'windows': return system.sessionLocked === false && system.captureAvailable /* v8 ignore next -- Native permission responses validate the closed platform union. */ default: return assertNever(system) } @@ -195,7 +195,7 @@ export function PermissionPanel(props: PermissionPanelProps) { } {observed === null ? - : observed.platform === 'win32' ? + : observed.platform === 'windows' ? : (['accessibility', 'screenRecording'] as const).map(permission =>
@@ -207,7 +207,7 @@ export function PermissionPanel(props: PermissionPanelProps) { busy={busy} request={props.request} openSettings={props.openSettings} t={t} />
)}
-

{observed?.platform === 'win32' +

{observed?.platform === 'windows' ? <>{t('windowsInstructions')} {t(observed.elevated ? 'elevated' : 'standardPrivileges')} : t('permissionHint')}

@@ -241,12 +241,12 @@ export function PermissionSetup({ t, refresh, useCuaPermissions, onDismiss, onOp && systemReady(state.value) useEffect(() => { if (ready && !state.busy) onDismiss() }, [ready, state.busy, onDismiss]) return }> -

{t(state.error !== null ? 'setupQueryFailed' : state.value?.platform !== 'win32' ? 'setupBody' +

{t(state.error !== null ? 'setupQueryFailed' : state.value?.platform !== 'windows' ? 'setupBody' : state.value.sessionLocked === null ? 'windowsSessionUnknown' : state.value.sessionLocked ? 'windowsSetupBody' : 'windowsCaptureUnavailable')}

diff --git a/packages/experimental/cua/src/guidance.ts b/packages/experimental/cua/src/guidance.ts index 93947ad32c..df935f6525 100644 --- a/packages/experimental/cua/src/guidance.ts +++ b/packages/experimental/cua/src/guidance.ts @@ -4,7 +4,7 @@ export const COMMON_GUIDANCE = `Use cua to observe and operate native applicatio In persistent PTC, use the host-provided bridge initialization once and retain the returned objects; cua comes from that bridge and is not a preinstalled global. Use void await for observations that emit, and never stringify screenshot image bytes. -Signatures show resolved return values after await. ActionResult = { dispatched: boolean, foregroundChanged?: boolean | null }; foregroundChanged is omitted when not sampled and null when the sample is unavailable. JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue }; numbers must be finite. App is the application object with readonly app.appHandle: string (opaque) and the methods listed below for app level. Window is the window object with readonly window.windowId: number and the methods listed below for window level. Neither object carries pid. +Signatures show resolved return values after await. ActionResult = { dispatched: boolean, foregroundChanged?: boolean | null }; foregroundChanged is omitted when not sampled and null when the sample is unavailable. JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue }; numbers must be finite. App is the application object with readonly app.appHandle: string (opaque) and the methods listed below for app level. Window is the window object with readonly window.windowId: number and the methods listed below for window level. Setup and discovery: - cua.getCapabilities(options?: { emit?: boolean }) -> { platform: string, permissions: { accessibility: boolean, screenRecording: boolean }, appLevelAccessibility: 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. diff --git a/packages/experimental/cua/tests/panel.client.spec.tsx b/packages/experimental/cua/tests/panel.client.spec.tsx index 6558fd06d4..613f24fce3 100644 --- a/packages/experimental/cua/tests/panel.client.spec.tsx +++ b/packages/experimental/cua/tests/panel.client.spec.tsx @@ -439,7 +439,7 @@ it('retains a known read-only configuration and query failure throughout managem it.each([true, false, null] as const)('shows Windows desktop access for lock state %s without macOS permission actions', (sessionLocked) => { const f = fixture() - f.publish({ ...observe(value), system: { value: { platform: 'win32', sessionLocked, captureAvailable: true, + f.publish({ ...observe(value), system: { value: { platform: 'windows', sessionLocked, captureAvailable: true, elevated: false, helper: { pid: 9, path: 'C:\\helper.exe' } }, error: null, busy: false } }) render() const desktop = screen.getByRole('group', { name: en.windowsDesktop }) @@ -451,7 +451,7 @@ it.each([true, false, null] as const)('shows Windows desktop access for lock sta expect(screen.queryByRole('button', { name: en.request })).toBeNull() expect(screen.queryByRole('button', { name: en.granted })).toBeNull() expect(screen.queryByText('C:\\helper.exe')).toBeNull() - f.publish({ system: { value: { platform: 'win32', sessionLocked: false, captureAvailable: false, + f.publish({ system: { value: { platform: 'windows', sessionLocked: false, captureAvailable: false, elevated: true, helper: { pid: 9 } }, error: null, busy: false } }) expect(within(capture).getByText(en.unavailable)).toBeTruthy() expect(screen.getByText(en.elevated, { exact: false })).toBeTruthy() @@ -461,7 +461,7 @@ it.each([true, false, null] as const)('shows Windows desktop access for lock sta it.each([[true, true], [false, true], [false, false], [null, true]] as const)('offers Windows setup for lock=%s and capture=%s', (sessionLocked, captureAvailable) => { const f = fixture(), onDismiss = vi.fn() - f.publish({ system: { value: { platform: 'win32', sessionLocked, captureAvailable, + f.publish({ system: { value: { platform: 'windows', sessionLocked, captureAvailable, elevated: false, helper: { pid: 9 } }, error: null, busy: false } }) render() const needsSetup = sessionLocked !== false || !captureAvailable diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ca94685474..f910604ac9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -45,6 +45,9 @@ importers: '@deepseek-ai/dsh-cua-bundle': specifier: workspace:* version: link:packages/experimental/cua-bundle + '@deepseek-ai/dsh-cua-windows': + specifier: workspace:* + version: link:packages/experimental/cua-windows '@deepseek-ai/dsh-experimental-browser-use-chrome-devtools-mcp': specifier: workspace:* version: link:packages/experimental/browser-use-chrome-devtools-mcp @@ -9965,6 +9968,9 @@ importers: specifier: ^4.2.0 version: 4.3.2 optionalDependencies: + '@deepseek-ai/dsh-cua-windows': + specifier: workspace:* + version: link:../cua-windows '@deepseek-ai/dsh-experimental-cua-macos': specifier: workspace:* version: link:../cua-macos @@ -10093,6 +10099,115 @@ importers: specifier: ^0.35.3 version: 0.35.5(@types/node@22.20.1) + packages/experimental/cua-windows: + dependencies: + '@deepseek-ai/dsh-atomic-write': + specifier: workspace:* + version: link:../../util/atomic-write + '@deepseek-ai/dsh-cua': + specifier: workspace:* + version: link:../cua + '@deepseek-ai/dsh-native-command': + specifier: workspace:* + version: link:../../util/native-command + '@deepseek-ai/schemastery': + specifier: link:../../../vendor/schemastery + version: link:../../../vendor/schemastery + zod: + specifier: ^4.4.3 + version: 4.6.6 + devDependencies: + '@deepseek-ai/cordis': + specifier: workspace:~ + version: link:../../../vendor/cordis + '@deepseek-ai/cordis-plugin-include': + specifier: workspace:~ + version: link:../../../vendor/include + '@deepseek-ai/cordis-plugin-loader': + specifier: workspace:~ + version: link:../../../vendor/loader + '@deepseek-ai/cordis-plugin-timer': + specifier: workspace:~ + version: link:../../../vendor/timer + '@deepseek-ai/dsh-agent': + specifier: workspace:* + version: link:../../core/agent + '@deepseek-ai/dsh-agent-loop': + specifier: workspace:* + version: link:../../core/agent-loop + '@deepseek-ai/dsh-agent-loop-testkit': + specifier: workspace:* + version: link:../../test-support/agent-loop-testkit + '@deepseek-ai/dsh-app-boot': + specifier: workspace:* + version: link:../../boot/app-boot + '@deepseek-ai/dsh-attachment': + specifier: workspace:* + version: link:../../attachment/attachment + '@deepseek-ai/dsh-attachment-local': + specifier: workspace:* + version: link:../../attachment/attachment-local + '@deepseek-ai/dsh-computer-use': + specifier: workspace:* + version: link:../../computer-use/computer-use + '@deepseek-ai/dsh-config-editor': + specifier: workspace:* + version: link:../../boot/config-editor + '@deepseek-ai/dsh-fs-local': + specifier: workspace:* + version: link:../../fs/fs-local + '@deepseek-ai/dsh-hmr': + specifier: workspace:* + version: link:../../boot/hmr + '@deepseek-ai/dsh-llm': + specifier: workspace:* + version: link:../../llm/llm + '@deepseek-ai/dsh-llm-deepseek': + specifier: workspace:* + version: link:../../llm/llm-deepseek + '@deepseek-ai/dsh-ptc-runtime': + specifier: workspace:* + version: link:../../ptc-runtime/ptc-runtime + '@deepseek-ai/dsh-ptc-runtime-node': + specifier: workspace:* + version: link:../../ptc-runtime/ptc-runtime-node + '@deepseek-ai/dsh-sandbox-local': + specifier: workspace:* + version: link:../../sandbox/sandbox-local + '@deepseek-ai/dsh-sandbox-policy': + specifier: workspace:* + version: link:../../sandbox/sandbox-policy + '@deepseek-ai/dsh-session': + specifier: workspace:* + version: link:../../core/session + '@deepseek-ai/dsh-session-projection': + specifier: workspace:* + version: link:../../session/session-projection + '@deepseek-ai/dsh-settings': + specifier: workspace:* + version: link:../../settings/settings + '@deepseek-ai/dsh-subprocess': + specifier: workspace:* + version: link:../../subprocess/subprocess + '@deepseek-ai/dsh-subprocess-local': + specifier: workspace:* + version: link:../../subprocess/subprocess-local + '@deepseek-ai/dsh-system-prompt': + specifier: workspace:* + version: link:../../core/system-prompt + '@deepseek-ai/dsh-tools': + specifier: workspace:* + version: link:../../core/tools + '@deepseek-ai/dsh-user-questions': + specifier: workspace:* + version: link:../../interaction/user-questions + '@deepseek-ai/dsh-working-directory': + specifier: workspace:* + version: link:../../session/working-directory + sharp: + specifier: ^0.35.3 + version: 0.35.5(@types/node@22.20.1) + packages/experimental/forge: dependencies: '@deepseek-ai/dsh-brand': diff --git a/scripts/check-workspace-constraints.ts b/scripts/check-workspace-constraints.ts index f759eca7ec..a9ec59f11b 100644 --- a/scripts/check-workspace-constraints.ts +++ b/scripts/check-workspace-constraints.ts @@ -190,6 +190,7 @@ const packageFileExtras: Readonly> = { // CUA publishes its client API and attributed native source for local macOS builds. '@deepseek-ai/dsh-cua': ['lib/remote-types.js', 'lib/api.js', 'lib/bridge.js', 'lib/native-client.js', 'lib/protocol.js', 'lib/config.js', 'lib/native-schema.js', 'lib/native-build.js', 'lib/guidance.js'], '@deepseek-ai/dsh-experimental-cua-macos': ['native/bin', 'cua-helper.json', 'native/Package.swift', 'native/Info.plist', 'native/DSHComputerUse.icns', 'native/build_app.py', 'native/Sources', 'native/tests/swift', 'native/tests/test_swift.py', 'native/LICENSE.cua-driver', 'native/LICENSE.computer-use-icon', 'native/upstream.json', 'native/README.md', 'native/README.zh.md', 'native/protocol.schema.json'], + '@deepseek-ai/dsh-cua-windows': ['native/bin', 'native/CuaWindows.csproj', 'native/Directory.Build.props', 'native/app.manifest', 'native/src', 'native/protocol', 'native/protocol.schema.json', 'native/packages.lock.json'], '@deepseek-ai/dsh-webhook-github': ['examples/github-review/cordis.yml', 'examples/github-review/github-ready-review-rule.mjs'], // Liveshare publishes its built Relay gateway entry and the shared runtime // chunk that entry imports. Its `./types` export is a type-only module, so diff --git a/scripts/experimental-package-policy.ts b/scripts/experimental-package-policy.ts index df85af1620..705eab4ec0 100644 --- a/scripts/experimental-package-policy.ts +++ b/scripts/experimental-package-policy.ts @@ -8,6 +8,7 @@ export const EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS: Readonly> = { 'packages/experimental/cua': '@deepseek-ai/dsh-cua', 'packages/experimental/cua-bundle': '@deepseek-ai/dsh-cua-bundle', + 'packages/experimental/cua-windows': '@deepseek-ai/dsh-cua-windows', 'packages/experimental/tool-session-query': '@deepseek-ai/dsh-tool-session-query', 'packages/experimental/session-title-all-prompts-llm': '@deepseek-ai/dsh-session-title-all-prompts-llm', 'packages/experimental/tool-terminal': '@deepseek-ai/dsh-tool-terminal', diff --git a/scripts/release/families.spec.ts b/scripts/release/families.spec.ts index feed57673f..1f15a4de89 100644 --- a/scripts/release/families.spec.ts +++ b/scripts/release/families.spec.ts @@ -72,6 +72,7 @@ describe('release families', () => { '@deepseek-ai/dsh-creation-recommendations', '@deepseek-ai/dsh-cua-bundle', '@deepseek-ai/dsh-experimental-cua-macos', + '@deepseek-ai/dsh-cua-windows', '@deepseek-ai/dsh-cua', '@deepseek-ai/dsh-experimental-forge-bundle', '@deepseek-ai/dsh-experimental-forge-github', diff --git a/tsconfig.base.json b/tsconfig.base.json index cfecbdc02b..ba550bee2d 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -113,6 +113,7 @@ "@deepseek-ai/dsh-computer-use/brand": ["./packages/computer-use/computer-use/src/brand.ts"], "@deepseek-ai/dsh-experimental-computer-use-cua-driver-mcp": ["./packages/experimental/computer-use-cua-driver-mcp/src/index.ts"], "@deepseek-ai/dsh-experimental-cua-macos": ["./packages/experimental/cua-macos/src/index.ts"], + "@deepseek-ai/dsh-cua-windows": ["./packages/experimental/cua-windows/src/index.ts"], "@deepseek-ai/dsh-cua/config": ["./packages/experimental/cua/src/config.ts"], "@deepseek-ai/dsh-cua/native-schema": ["./packages/experimental/cua/src/native-schema.ts"], "@deepseek-ai/dsh-cua/native-build": ["./packages/experimental/cua/src/native-build.ts"], diff --git a/tsconfig.host.json b/tsconfig.host.json index ea675b53ba..e82ffd9f53 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -251,6 +251,7 @@ "benchmarks/**/*.ts", "packages/*/*/tests/**/*.ts", "packages/experimental/cua-macos/native/generate-protocol.ts", + "packages/experimental/cua-windows/native/generate-protocol.ts", "packages/experimental/claude-code-mods/examples/*/index.ts", "packages/experimental/inspector/scripts/**/*.ts", "packages/llm/llm-pi-ai/scripts/**/*.ts", @@ -322,6 +323,7 @@ { "path": "./packages/experimental/cua/tsconfig.host.json" }, { "path": "./packages/experimental/cua-bundle" }, { "path": "./packages/experimental/cua-macos" }, + { "path": "./packages/experimental/cua-windows" }, { "path": "./packages/client/ui-sidebar-documentpreview/tsconfig.host.json" }, { "path": "./packages/client/ui-sidebar-browser/tsconfig.host.json" }, { "path": "./packages/client/ui-settings-general/tsconfig.host.json" }, From 8a5ebd2351a1d1b58fff676fe5be576411f07e83 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Fri, 6 Nov 2026 18:07:56 +0800 Subject: [PATCH 010/184] refactor(cua): derive NativeError from HarnessError Use the shared coded-error base while preserving the NativeError constructor, name, code, message and cause. Add the error dependency, compiler reference and error-type assertions. --- packages/experimental/cua/package.json | 2 ++ packages/experimental/cua/src/native-client.ts | 8 ++++---- packages/experimental/cua/tests/native-client.spec.ts | 3 +++ packages/experimental/cua/tsconfig.host.json | 3 +++ 4 files changed, 12 insertions(+), 4 deletions(-) diff --git a/packages/experimental/cua/package.json b/packages/experimental/cua/package.json index 440f321935..c74c702566 100644 --- a/packages/experimental/cua/package.json +++ b/packages/experimental/cua/package.json @@ -96,6 +96,7 @@ "license": "MIT", "peerDependencies": { "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-error": "workspace:*", "@deepseek-ai/dsh-user-questions": "workspace:*", "@deepseek-ai/dsh-attachment": "workspace:*", "@deepseek-ai/dsh-scope": "workspace:*", @@ -119,6 +120,7 @@ "@deepseek-ai/dsh-agent-loop-testkit": "workspace:*", "@deepseek-ai/dsh-attachment": "workspace:*", "@deepseek-ai/dsh-attachment-local": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-session-projection": "workspace:*", diff --git a/packages/experimental/cua/src/native-client.ts b/packages/experimental/cua/src/native-client.ts index 25c93e15ce..25b5f4e5a9 100644 --- a/packages/experimental/cua/src/native-client.ts +++ b/packages/experimental/cua/src/native-client.ts @@ -1,6 +1,7 @@ /** Agent-scoped JSONL requests over a connection to the shared native helper. */ import { randomUUID } from 'node:crypto' import assert from 'node:assert/strict' +import { HarnessError } from '@deepseek-ai/dsh-error' import type { SubprocessRuntime } from '@deepseek-ai/dsh-subprocess' import type { ToolExecution } from '@deepseek-ai/dsh-tools' import type { JsonValue } from '@deepseek-ai/dsh-util-values' @@ -19,15 +20,14 @@ const ScreenshotDiagnostic = z.object({ const WireReply = z.union([Reply, ScreenshotDiagnostic.extend({ type: z.literal('diagnostic') })]) /** Native refusal or transport failure with a stable machine-readable code. */ -export class NativeError extends Error { +export class NativeError extends HarnessError { /** * @param code - Native error code or a transport-owned NATIVE_* code. * @param message - Actionable diagnostic, without its code prefix. * @param options - Original failure when available. */ - constructor(readonly code: string, message: string, options?: ErrorOptions) { - super(`${code}: ${message}`, options) - this.name = 'NativeError' + constructor(code: string, message: string, options?: ErrorOptions) { + super(`${code}: ${message}`, code, options) } } diff --git a/packages/experimental/cua/tests/native-client.spec.ts b/packages/experimental/cua/tests/native-client.spec.ts index f7a9007f42..b23f4bb48c 100644 --- a/packages/experimental/cua/tests/native-client.spec.ts +++ b/packages/experimental/cua/tests/native-client.spec.ts @@ -1,5 +1,6 @@ /** Controlled connection streams exercise the platform-independent native protocol client. */ import { PassThrough, Writable } from 'node:stream' +import { HarnessError } from '@deepseek-ai/dsh-error' import { ToolCallId } from '@deepseek-ai/dsh-llm' import type { NativeChannel } from '../src/native-client.ts' import { describe, expect, it, onTestFinished, vi } from 'vitest' @@ -391,6 +392,8 @@ describe('native helper transport', () => { it('keeps native codes available to callers and in the model-visible diagnostic', () => { const error = new NativeError('PERMISSION_DENIED', 'Enable Accessibility') + expect(error).toBeInstanceOf(HarnessError) + expect(error.name).toBe('NativeError') expect(error.code).toBe('PERMISSION_DENIED') expect(error.message).toBe('PERMISSION_DENIED: Enable Accessibility') }) diff --git a/packages/experimental/cua/tsconfig.host.json b/packages/experimental/cua/tsconfig.host.json index 2386f83640..91b18de2b9 100644 --- a/packages/experimental/cua/tsconfig.host.json +++ b/packages/experimental/cua/tsconfig.host.json @@ -36,6 +36,9 @@ { "path": "../../util/brand" }, + { + "path": "../../util/error" + }, { "path": "../../util/atomic-write" }, From b42e744c3cc3b80bef241e2b4da57e6dafbf78b0 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Sat, 7 Nov 2026 12:02:29 +0800 Subject: [PATCH 011/184] refactor(cua): ignore native PID metadata in TypeScript Remove PID fields and dependencies from TypeScript discovery, permission metadata and helper handshakes while preserving native implementations and responses. Accept unused response fields, select applications by provider ID, bundle ID or name, and update consumers, guidance and fixtures. --- .../cua-macos/src/shared-native.ts | 4 +-- .../cua-macos/tests/guidance.spec.ts | 4 +-- .../cua-windows/src/native-runtime.ts | 8 +++--- .../cua-windows/tests/native-runtime.spec.ts | 7 ++++- packages/experimental/cua/src/access-types.ts | 1 - packages/experimental/cua/src/access.ts | 2 +- packages/experimental/cua/src/api.ts | 2 +- packages/experimental/cua/src/guidance.ts | 8 +++--- packages/experimental/cua/src/protocol.ts | 12 ++++----- packages/experimental/cua/src/types.ts | 6 ++--- .../experimental/cua/tests/access.spec.ts | 3 ++- packages/experimental/cua/tests/api.spec.ts | 27 ++++++++++++++----- .../experimental/cua/tests/bridge.spec.ts | 6 ++--- .../cua/tests/controller.client.spec.ts | 2 +- .../cua/tests/mount.client.spec.ts | 2 +- .../cua/tests/panel.client.spec.tsx | 10 +++---- .../extensions/tool-cordis/src/api-catalog.ts | 4 +-- 17 files changed, 63 insertions(+), 45 deletions(-) diff --git a/packages/experimental/cua-macos/src/shared-native.ts b/packages/experimental/cua-macos/src/shared-native.ts index 0fe2cf6436..7539276a8c 100644 --- a/packages/experimental/cua-macos/src/shared-native.ts +++ b/packages/experimental/cua-macos/src/shared-native.ts @@ -13,8 +13,8 @@ export type { NativeChannel } from '@deepseek-ai/dsh-cua/native-client' const Ready = z.object({ type: z.literal('ready'), protocol: z.literal(1), runtimeKey: z.string(), - pid: z.number().int().positive(), instanceId: z.string().min(1), -}).strict() + instanceId: z.string().min(1), +}) const Refusal = z.object({ type: z.literal('error'), code: z.string().min(1), message: z.string() }).strict() const handshakeByteLimit = 8192 type LauncherExit = [PromiseSettledResult, PromiseSettledResult] diff --git a/packages/experimental/cua-macos/tests/guidance.spec.ts b/packages/experimental/cua-macos/tests/guidance.spec.ts index f0f5679623..ae947d7ab7 100644 --- a/packages/experimental/cua-macos/tests/guidance.spec.ts +++ b/packages/experimental/cua-macos/tests/guidance.spec.ts @@ -56,8 +56,8 @@ it('inlines discovery, restoration, screenshot, and mouse-move return records', expect(lines.find(line => line.startsWith(`- ${name}(`))).toMatch(/ -> \(?\{ /) } expect(COMMON_GUIDANCE).toContain("{ platform: string, permissions: { accessibility: boolean, screenRecording: boolean }, appLevelAccessibility: boolean, keyboard: ('app' | 'window')[], sessionLocked: boolean | null, methods: string[], coordinateSpace: 'screenshot-pixels', browser: false }") - expect(COMMON_GUIDANCE).toContain('{ id: string, displayName: string, isRunning: true, pid: number }[]') - expect(COMMON_GUIDANCE).toContain('({ id: string, displayName: string, path: string } & ({ isRunning: true, pid: number } | { isRunning: false }))[]') + expect(COMMON_GUIDANCE).toContain('{ id: string, displayName: string, isRunning: true }[]') + expect(COMMON_GUIDANCE).toContain('{ id: string, displayName: string, path: string, isRunning: boolean }[]') expect(COMMON_GUIDANCE).toContain('bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null') }) diff --git a/packages/experimental/cua-windows/src/native-runtime.ts b/packages/experimental/cua-windows/src/native-runtime.ts index bf5da9aff3..0386d60f19 100644 --- a/packages/experimental/cua-windows/src/native-runtime.ts +++ b/packages/experimental/cua-windows/src/native-runtime.ts @@ -11,9 +11,9 @@ import { z } from 'zod' import { connectWindowsPipe, type WindowsConnection, type WindowsTransport } from './native-transport.ts' const Ready = z.object({ - type: z.literal('ready'), protocol: z.literal(1), runtimeKey: z.string(), instanceId: z.string().min(1), -}).strict() -const Started = Ready.extend({ endpoint: z.string().min(1), launcherId: z.string().min(1) }).strict() + type: z.literal('ready'), protocol: z.literal(1), runtimeKey: z.string().min(1), instanceId: z.string().min(1), +}) +const Started = Ready.extend({ endpoint: z.string().min(1), launcherId: z.string().min(1) }) // Private transport control frames have fixed encoding; operation replies pass through unchanged. const closedFrame = Buffer.from('{"type":"closed"}\n') type Owner = { subprocess: Pick } @@ -238,7 +238,7 @@ class WindowsChannel implements NativeChannel { } const response = await frame const accepted = Ready.parse(response.value) - if (accepted.runtimeKey !== ready.runtimeKey || accepted.instanceId !== ready.instanceId || accepted.pid !== ready.pid) + if (accepted.runtimeKey !== ready.runtimeKey || accepted.instanceId !== ready.instanceId) throw new NativeError('NATIVE_PROTOCOL', 'Windows pipe belongs to another helper instance') this.startup.signal.throwIfAborted() admitted = true diff --git a/packages/experimental/cua-windows/tests/native-runtime.spec.ts b/packages/experimental/cua-windows/tests/native-runtime.spec.ts index b3eb03caf2..5e526ab4d7 100644 --- a/packages/experimental/cua-windows/tests/native-runtime.spec.ts +++ b/packages/experimental/cua-windows/tests/native-runtime.spec.ts @@ -199,7 +199,12 @@ it.each(['wrong-runtime', 'wrong-instance', 'extra', 'malformed', 'oversized', ' }, ) -it.each(['wrong-instance', 'wrong-pid', 'extra', 'malformed', 'oversized'] as const)( +it.each(['wrong-pid', 'extra'] as const)('ignores unused %s handshake metadata', async (handshake) => { + const f = await fixture({ handshake }) + await expect(f.client().request('input', {}, new AbortController().signal)).resolves.toMatchObject({ connection: 1 }) +}) + +it.each(['wrong-instance', 'malformed', 'oversized'] as const)( 'rejects a %s Agent handshake before dispatch', async (handshake) => { const f = await fixture({ handshake }) await expect(f.client().request('input', {}, new AbortController().signal)).rejects.toThrow() diff --git a/packages/experimental/cua/src/access-types.ts b/packages/experimental/cua/src/access-types.ts index 0a587124d4..f37a5ea679 100644 --- a/packages/experimental/cua/src/access-types.ts +++ b/packages/experimental/cua/src/access-types.ts @@ -6,7 +6,6 @@ export type { CuaApplicationGrant, CuaApplicationId } from './application-types. export type CuaSystemPermission = 'accessibility' | 'screenRecording' /** Observed process; neither the helper nor its parent is assumed to be the TCC owner. */ export interface CuaPermissionProcess { - pid: number path?: string | undefined name?: string | undefined } diff --git a/packages/experimental/cua/src/access.ts b/packages/experimental/cua/src/access.ts index 535bfe84fb..507d628024 100644 --- a/packages/experimental/cua/src/access.ts +++ b/packages/experimental/cua/src/access.ts @@ -19,7 +19,7 @@ interface ControlOptions extends AccessOptions { permissionParameters: (method: 'requestPermission' | 'openPermissionSettings', permission: CuaSystemPermission, locale: string) => Record } type Control = (method: string, params: Record) => Promise -const permissionProcess = z.object({ pid: z.number().int().positive(), path: z.string().optional(), name: z.string().optional() }) +const permissionProcess = z.object({ path: z.string().optional(), name: z.string().optional() }) const systemPermissions = z.discriminatedUnion('platform', [z.object({ platform: z.literal('darwin'), accessibility: z.boolean(), screenRecording: z.boolean(), helper: permissionProcess, parent: permissionProcess, launchApplication: z.object({ name: z.string().min(1), path: z.string().min(1), icon: ApplicationIcon.optional() }).optional(), diff --git a/packages/experimental/cua/src/api.ts b/packages/experimental/cua/src/api.ts index 22039c6591..f41a4f61e4 100644 --- a/packages/experimental/cua/src/api.ts +++ b/packages/experimental/cua/src/api.ts @@ -59,7 +59,7 @@ export function createCuaApi(dispatch: CuaDispatch, sink?: CuaObservationSink): }, async listApps(options) { const result = AppsResult.parse(await call('listApps', {})).map(app => ({ - id: app.bundleId || String(app.pid), displayName: app.name, isRunning: true as const, pid: app.pid, + id: app.id ?? (app.bundleId || app.name), displayName: app.name, isRunning: true as const, })) await emit(sink, result, options) return result diff --git a/packages/experimental/cua/src/guidance.ts b/packages/experimental/cua/src/guidance.ts index df935f6525..a28de6d0ca 100644 --- a/packages/experimental/cua/src/guidance.ts +++ b/packages/experimental/cua/src/guidance.ts @@ -8,10 +8,10 @@ Signatures show resolved return values after await. ActionResult = { dispatched: Setup and discovery: - cua.getCapabilities(options?: { emit?: boolean }) -> { platform: string, permissions: { accessibility: boolean, screenRecording: boolean }, appLevelAccessibility: 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(options?: { emit?: boolean }) -> { id: string, displayName: string, isRunning: true, pid: number }[] — enumerate running applications. -- cua.findApps(query: string, options?: { emit?: boolean }) -> ({ id: string, displayName: string, path: string } & ({ isRunning: true, pid: number } | { isRunning: false }))[] — search installed applications, including stopped matches; only running matches carry pid. -- cua.getState(options?: { emit?: boolean }) -> { apps: { id: string, displayName: string, isRunning: true, pid: number }[], browsers: [] } — summarize running applications; this is not an accessibility observation. -- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and read initial AX state silently; it does not activate the app. +- cua.listApps(options?: { emit?: boolean }) -> { id: string, displayName: string, isRunning: true }[] — enumerate running applications. +- cua.findApps(query: string, options?: { emit?: boolean }) -> { id: string, displayName: string, path: string, isRunning: boolean }[] — search installed applications, including stopped matches. +- cua.getState(options?: { emit?: boolean }) -> { apps: { id: string, displayName: string, isRunning: true }[], browsers: [] } — summarize running applications; this is not an accessibility observation. +- cua.getApp(selector: string) -> App — select an application by provider-issued discovery ID, name, bundle ID, or absolute path where supported, obtain consent, launch in the background if needed, and read initial AX state silently; it does not activate the app. - app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership. - app.getWindow(windowId: number) -> Window — select one window and read its initial AX state silently; do this before any window screenshot or coordinate input. - app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required. diff --git a/packages/experimental/cua/src/protocol.ts b/packages/experimental/cua/src/protocol.ts index 538c95cfe6..ad54407c51 100644 --- a/packages/experimental/cua/src/protocol.ts +++ b/packages/experimental/cua/src/protocol.ts @@ -4,7 +4,6 @@ import { z } from 'zod' import type { CuaAppHandle, CuaSnapshotId } from './types.ts' const id = z.number().int().positive().max(2 ** 32 - 1) -const pid = z.number().int().positive().max(2 ** 31 - 1) const point = z.number().nonnegative() const relativePoint = z.number().int().min(0).max(999) const app = { appHandle: z.string().min(1) } @@ -101,11 +100,12 @@ export const AppResult = z.object({ appHandle: z.string().min(1).transform(value => value as CuaAppHandle), name: z.string(), bundleId: z.string().optional(), running: z.boolean(), }) -/** Running application records from the helper. */ -export const AppsResult = z.array(z.object({ pid, name: z.string(), bundleId: z.string().optional() })) -/** Installed application matches keep running and stopped records distinct. */ -export const FoundAppsResult = z.array(z.intersection(z.object({ id: z.string().min(1), displayName: z.string(), path: z.string().min(1) }), - z.discriminatedUnion('isRunning', [z.object({ isRunning: z.literal(true), pid }), z.object({ isRunning: z.literal(false) })]))) +/** Running application metadata used for selection; other native fields are ignored. */ +export const AppsResult = z.array(z.object({ id: z.string().min(1).optional(), name: z.string(), bundleId: z.string().optional() })) +/** Installed application matches and their current running state. */ +export const FoundAppsResult = z.array(z.object({ + id: z.string().min(1), displayName: z.string(), path: z.string().min(1), isRunning: z.boolean(), +})) /** Current windows and their global native bounds. */ export const WindowsResult = z.array(z.object({ windowId: id, appName: z.string(), title: z.string(), bounds, diff --git a/packages/experimental/cua/src/types.ts b/packages/experimental/cua/src/types.ts index c059a546f2..f35c839abf 100644 --- a/packages/experimental/cua/src/types.ts +++ b/packages/experimental/cua/src/types.ts @@ -51,8 +51,8 @@ export type CuaStartupCapabilities = Pick< 'platform' | 'methods' | 'appLevelAccessibility' | 'keyboard' | 'browser' | 'coordinateSpace' > /** App discovery result accepted by getApp. */ -export type CuaAppInfo = Pick, 'id' | 'displayName' | 'isRunning' | 'pid'> -/** An installed application match; running matches include a process identifier. */ +export type CuaAppInfo = Pick & { isRunning: true } +/** An installed application match with its current running state. */ export type CuaFoundAppInfo = z.output[number] /** Window bounds in the provider's global native units. Local operations use an origin of [0,0]. */ export type CuaBounds = CuaWindowInfo['bounds'] @@ -273,7 +273,7 @@ export interface CuaApi { getState(options?: CuaObservationOptions): Promise<{ apps: CuaAppInfo[]; browsers: [] }> /** * Select an app, obtain consent, launch it in the background if necessary, and silently retain initial AX state. - * @param selector - Exact name, bundle ID, absolute application path or running PID string; ambiguous names reject. + * @param selector - Provider-issued identifier, exact name, bundle ID or absolute application path; ambiguous selectors reject. * @returns An application handle tied to this process lifetime; its initial tree read becomes the current snapshot. */ getApp(selector: string): Promise diff --git a/packages/experimental/cua/tests/access.spec.ts b/packages/experimental/cua/tests/access.spec.ts index ef6f6c203f..74dea0c738 100644 --- a/packages/experimental/cua/tests/access.spec.ts +++ b/packages/experimental/cua/tests/access.spec.ts @@ -398,7 +398,8 @@ it('preserves captured launch metadata separately from the current helper parent const launchApplication = { name: 'Visual Studio Code', path: '/Applications/Visual Studio Code.app', icon: 'data:image/png;base64,aWNvbg==' } control.request.mockResolvedValueOnce({ platform: 'darwin' as const, accessibility: false, screenRecording: false, helper: { pid: 9 }, parent: { pid: 1, path: '/sbin/launchd' }, launchApplication }) - expect(await f.ctx.cuaAccess.systemStatus()).toMatchObject({ parent: { pid: 1 }, launchApplication }) + expect(await f.ctx.cuaAccess.systemStatus()).toEqual({ platform: 'darwin', accessibility: false, screenRecording: false, + helper: {}, parent: { path: '/sbin/launchd' }, launchApplication }) }) diff --git a/packages/experimental/cua/tests/api.spec.ts b/packages/experimental/cua/tests/api.spec.ts index cbaa419951..707bfc7089 100644 --- a/packages/experimental/cua/tests/api.spec.ts +++ b/packages/experimental/cua/tests/api.spec.ts @@ -27,7 +27,7 @@ function fixture(withSink = true) { const dispatch = vi.fn(async ({ method, params }: CuaOperation): Promise => { switch (method) { case 'getCapabilities': return currentCapabilities - case 'listApps': return [selected, { pid: 18, name: 'Utility' }] + case 'listApps': return [selected, { id: 'utility-selector', pid: 4, name: 'Utility' }] case 'getApp': return selected case 'listWindows': return windows case 'mouseMove': return { ...delivered, hoverRoute: 'accessibility', systemPointerMoved: false } @@ -59,12 +59,12 @@ function screenshot(overrides: Record = {}): JsonValue { } describe('application discovery', () => { - it('reports permissions and discovers both bundle and PID selectors without activating an app', async () => { + it('reports permissions and discovers provider-issued selectors without activating an app', async () => { const f = fixture() expect(await f.api.getCapabilities()).toEqual(capabilities) expect(await f.api.getState()).toEqual({ apps: [ - { id: 'test.editor', displayName: 'Editor', isRunning: true, pid: 17 }, - { id: '18', displayName: 'Utility', isRunning: true, pid: 18 }, + { id: 'test.editor', displayName: 'Editor', isRunning: true }, + { id: 'utility-selector', displayName: 'Utility', isRunning: true }, ], browsers: [] }) expect(f.dispatch.mock.calls.map(([operation]) => operation.method)).toEqual(['getCapabilities', 'listApps']) const emitted = f.sink.text.mock.calls.map(([text]): unknown => JSON.parse(text)) @@ -72,6 +72,19 @@ describe('application discovery', () => { expect(f.sink.text).toHaveBeenCalledTimes(2) }) + it('passes a discovered selector unchanged to application selection', async () => { + const f = fixture() + const apps = await f.api.listApps({ emit: false }) + await f.api.getApp(apps[1]!.id) + expect(f.dispatch).toHaveBeenCalledWith({ method: 'getApp', params: { selector: 'utility-selector' } }) + }) + + it('uses the application name when discovery has no identifier', async () => { + const f = fixture() + f.dispatch.mockResolvedValueOnce([{ pid: 18, name: 'Utility' }]) + expect(await f.api.listApps({ emit: false })).toEqual([{ id: 'Utility', displayName: 'Utility', isRunning: true }]) + }) + it('returns observations without requiring an output sink', async () => { const f = fixture(false) expect(await f.api.getCapabilities({ emit: false })).toEqual(capabilities) @@ -94,9 +107,9 @@ describe('application discovery', () => { const f = fixture() const matches = [ { id: 'test.stopped', displayName: 'Stopped', path: '/Applications/Stopped.app', isRunning: false }, - { id: 'test.running', displayName: 'Running', path: '/Applications/Running.app', isRunning: true, pid: 17 }, + { id: 'test.running', displayName: 'Running', path: '/Applications/Running.app', isRunning: true }, ] - f.dispatch.mockResolvedValueOnce(matches) + f.dispatch.mockResolvedValueOnce([matches[0]!, { ...matches[1]!, pid: 17 }]) expect(await f.api.findApps('Editor')).toEqual(matches) expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'findApps', params: { query: 'Editor' } }) expect(f.sink.text).toHaveBeenLastCalledWith(JSON.stringify(matches)) @@ -113,7 +126,7 @@ describe('application discovery', () => { const f = fixture() f.dispatch.mockResolvedValueOnce({ platform: 'macos' }) await expect(f.api.getCapabilities()).rejects.toThrow() - f.dispatch.mockResolvedValueOnce([{ pid: 0, name: 'Invalid' }]) + f.dispatch.mockResolvedValueOnce([{ id: '', name: 'Invalid' }]) await expect(f.api.listApps()).rejects.toThrow() f.dispatch.mockResolvedValueOnce({ ...selected, appHandle: '' }) await expect(f.api.getApp('Editor')).rejects.toThrow() diff --git a/packages/experimental/cua/tests/bridge.spec.ts b/packages/experimental/cua/tests/bridge.spec.ts index 14a36baaba..f9deb49f7f 100644 --- a/packages/experimental/cua/tests/bridge.spec.ts +++ b/packages/experimental/cua/tests/bridge.spec.ts @@ -16,7 +16,7 @@ const capabilities: CuaCapabilities = { keyboard: ['app'], sessionLocked: false, methods: ['getCapabilities', 'getApp', 'getState', 'screenshot'], coordinateSpace: 'screenshot-pixels', browser: false, } -const selected = { appHandle: 'app-17', pid: 17, name: 'Editor', running: true } +const selected = { appHandle: 'app-17', name: 'Editor', running: true } const bounds = { x: 0, y: 0, width: 640, height: 480 } const snapshot = { appHandle: 'app-17', windowId: null, snapshotId: 'snapshot-1', tree: '0 button', truncated: false, @@ -56,8 +56,8 @@ it('propagates a denied action without retrying it', async () => { }) it('supports callers that retain observations without a text callback', async () => { - const cua = connectCua(() => async () => [{ pid: 17, name: 'Editor' }]) - await expect(cua.listApps()).resolves.toEqual([{ id: '17', displayName: 'Editor', isRunning: true, pid: 17 }]) + const cua = connectCua(() => async () => [{ id: 'editor-selector', name: 'Editor' }]) + await expect(cua.listApps()).resolves.toEqual([{ id: 'editor-selector', displayName: 'Editor', isRunning: true }]) }) it.each([null, 'text only', { content: [{ type: 'text', text: '{}' }] }])('rejects an unusable tool result %j', async (result) => { diff --git a/packages/experimental/cua/tests/controller.client.spec.ts b/packages/experimental/cua/tests/controller.client.spec.ts index 81575d1eb8..31b402fdfd 100644 --- a/packages/experimental/cua/tests/controller.client.spec.ts +++ b/packages/experimental/cua/tests/controller.client.spec.ts @@ -7,7 +7,7 @@ import { expect, it, onTestFinished, vi } from 'vitest' import type { CuaApplicationId, CuaApplicationState, CuaSystemPermissionState } from '../src/access-types.ts' import { PermissionController } from '../src/client/controller.ts' -const value: CuaSystemPermissionState = { platform: 'darwin' as const, accessibility: true, screenRecording: false, helper: { pid: 9 }, parent: { pid: 8 } } +const value: CuaSystemPermissionState = { platform: 'darwin' as const, accessibility: true, screenRecording: false, helper: {}, parent: {} } const applications: CuaApplicationState = { allowedApps: [], blockedApps: [], persistentAvailable: true } type CuaRemote = Context['remote']['cuaAccess'] diff --git a/packages/experimental/cua/tests/mount.client.spec.ts b/packages/experimental/cua/tests/mount.client.spec.ts index dcbd253ae6..bd39c2623f 100644 --- a/packages/experimental/cua/tests/mount.client.spec.ts +++ b/packages/experimental/cua/tests/mount.client.spec.ts @@ -14,7 +14,7 @@ import type { ApplicationApprovalProps } from '../src/client/ApplicationApproval const contribution: TypertRemoteContribution = { package: '@deepseek-ai/dsh-cua', descriptors: [] } const value: CuaApplicationState & { system: CuaSystemPermissionState } = { - system: { platform: 'darwin' as const, accessibility: false, screenRecording: false, helper: { pid: 2 }, parent: { pid: 1 } }, + system: { platform: 'darwin' as const, accessibility: false, screenRecording: false, helper: {}, parent: {} }, allowedApps: [], blockedApps: [], persistentAvailable: true } function actionsOf(value: Record): asserts value is Record & PermissionFace { diff --git a/packages/experimental/cua/tests/panel.client.spec.tsx b/packages/experimental/cua/tests/panel.client.spec.tsx index 613f24fce3..c3b9d083fb 100644 --- a/packages/experimental/cua/tests/panel.client.spec.tsx +++ b/packages/experimental/cua/tests/panel.client.spec.tsx @@ -12,7 +12,7 @@ import { en, zh } from '../src/client/locales.ts' afterEach(() => { cleanup(); vi.useRealTimers() }) const value: CuaApplicationState & { system: Extract } = { system: { platform: 'darwin' as const, accessibility: false, screenRecording: true, - helper: { pid: 9, path: '/native/helper' }, parent: { pid: 8, path: '/host/node' } }, + helper: { path: '/native/helper' }, parent: { path: '/host/node' } }, allowedApps: [], blockedApps: [], persistentAvailable: true } function observe(value: CuaApplicationState & { system: CuaSystemPermissionState }) { @@ -232,7 +232,7 @@ it.each([en, zh])('shows four requirements with the target application beside ea const f = fixture() render() const application = { name: 'Visual Studio Code.app', path: '/Applications/Visual Studio Code.app', icon: 'data:image/png;base64,aWNvbg==' } - f.publish({ ...observe({ ...value, system: { ...value.system, parent: { pid: 1, path: '/sbin/launchd' }, launchApplication: application } }) }) + f.publish({ ...observe({ ...value, system: { ...value.system, parent: { path: '/sbin/launchd' }, launchApplication: application } }) }) const requirements = screen.getByRole('region', { name: dictionary.title }) expect(within(requirements).getAllByRole('group')).toHaveLength(4) expect(screen.getByRole('region', { name: dictionary.applicationsTitle })).toBeTruthy() @@ -440,7 +440,7 @@ it('retains a known read-only configuration and query failure throughout managem it.each([true, false, null] as const)('shows Windows desktop access for lock state %s without macOS permission actions', (sessionLocked) => { const f = fixture() f.publish({ ...observe(value), system: { value: { platform: 'windows', sessionLocked, captureAvailable: true, - elevated: false, helper: { pid: 9, path: 'C:\\helper.exe' } }, error: null, busy: false } }) + elevated: false, helper: { path: 'C:\\helper.exe' } }, error: null, busy: false } }) render() const desktop = screen.getByRole('group', { name: en.windowsDesktop }) const capture = screen.getByRole('group', { name: en.windowsCapture }) @@ -452,7 +452,7 @@ it.each([true, false, null] as const)('shows Windows desktop access for lock sta expect(screen.queryByRole('button', { name: en.granted })).toBeNull() expect(screen.queryByText('C:\\helper.exe')).toBeNull() f.publish({ system: { value: { platform: 'windows', sessionLocked: false, captureAvailable: false, - elevated: true, helper: { pid: 9 } }, error: null, busy: false } }) + elevated: true, helper: {} }, error: null, busy: false } }) expect(within(capture).getByText(en.unavailable)).toBeTruthy() expect(screen.getByText(en.elevated, { exact: false })).toBeTruthy() f.publish({ system: { ...f.state.getSnapshot().system, error: 'offline' } }) @@ -462,7 +462,7 @@ it.each([true, false, null] as const)('shows Windows desktop access for lock sta it.each([[true, true], [false, true], [false, false], [null, true]] as const)('offers Windows setup for lock=%s and capture=%s', (sessionLocked, captureAvailable) => { const f = fixture(), onDismiss = vi.fn() f.publish({ system: { value: { platform: 'windows', sessionLocked, captureAvailable, - elevated: false, helper: { pid: 9 } }, error: null, busy: false } }) + elevated: false, helper: {} }, error: null, busy: false } }) render() const needsSetup = sessionLocked !== false || !captureAvailable expect(screen.queryByRole('dialog') !== null).toBe(needsSetup) diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 74a5703129..e182793ce2 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -6324,7 +6324,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'CuaPermissionProcess', - declaration: 'export interface CuaPermissionProcess {\n pid: number;\n path?: string | undefined;\n name?: string | undefined;\n}', + declaration: 'export interface CuaPermissionProcess {\n path?: string | undefined;\n name?: string | undefined;\n}', }, { name: 'CuaSystemPermission', @@ -6332,7 +6332,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'CuaSystemPermissionState', - declaration: 'export type CuaSystemPermissionState = {\n platform: \'darwin\';\n accessibility: boolean;\n screenRecording: boolean;\n helper: CuaPermissionProcess;\n parent: CuaPermissionProcess;\n launchApplication?: {\n name: string;\n path: string;\n icon?: string | undefined;\n } | undefined;\n} | {\n platform: \'win32\';\n sessionLocked: boolean | null;\n captureAvailable: boolean;\n elevated: boolean;\n helper: CuaPermissionProcess;\n};', + declaration: 'export type CuaSystemPermissionState = {\n platform: \'darwin\';\n accessibility: boolean;\n screenRecording: boolean;\n helper: CuaPermissionProcess;\n parent: CuaPermissionProcess;\n launchApplication?: {\n name: string;\n path: string;\n icon?: string | undefined;\n } | undefined;\n} | {\n platform: \'windows\';\n sessionLocked: boolean | null;\n captureAvailable: boolean;\n elevated: boolean;\n helper: CuaPermissionProcess;\n};', }, { name: 'DailyInput', From 2ef5f9dc534bcc935f3dfbcebdd39d9280f078a6 Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Sat, 7 Nov 2026 12:20:20 +0800 Subject: [PATCH 012/184] fix(cua): select applications and windows without reading AX --- ...05-cua-scoped-surfaces-and-input.i18n.yaml | 4 +- ...026-11-05-cua-scoped-surfaces-and-input.md | 2 +- ...-11-05-cua-scoped-surfaces-and-input.zh.md | 2 +- .../cua-native-platform/guide.i18n.yaml | 4 +- .../v0.2.2-rc.1/cua-native-platform/guide.md | 2 +- .../cua-native-platform/guide.zh.md | 2 +- .../experimental/cua-macos/README.i18n.yaml | 8 +- packages/experimental/cua-macos/README.md | 14 +- packages/experimental/cua-macos/README.zh.md | 14 +- .../tests/loader-composition.spec.ts | 2 +- .../tests/persistent-bridge.built.e2e.ts | 2 +- packages/experimental/cua/README.i18n.yaml | 8 +- packages/experimental/cua/README.md | 4 +- packages/experimental/cua/README.zh.md | 4 +- packages/experimental/cua/package.json | 3 +- packages/experimental/cua/src/api.ts | 15 +- packages/experimental/cua/src/guidance.ts | 8 +- packages/experimental/cua/src/types.ts | 8 +- packages/experimental/cua/tests/api.spec.ts | 145 ++++++++++++++++-- .../experimental/cua/tests/bridge.spec.ts | 5 +- packages/experimental/cua/tsconfig.host.json | 3 + pnpm-lock.yaml | 3 + .../cua-native/system-prompt.expected.md | 8 +- .../cua-native/workspace/native-helper.mjs | 1 + snapshots/session/cua-ptc/consent-fixture.mjs | 6 +- .../session/cua-ptc/replay.override.json | 35 ++++- snapshots/session/cua-ptc/session.v4.jsonl | 26 +++- .../session/cua-ptc/system-prompt.expected.md | 8 +- .../system-prompt.expected.md | 8 +- 29 files changed, 276 insertions(+), 78 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml index f3a0d8f1d3..5f1ff64a4d 100644 --- a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml @@ -9,8 +9,8 @@ en: f72db0b79aa02fb5 zh: b91c1f177dc93ab4 /agent-note-cua-scoped-surfaces-and-separated-input-capabilities/decision: - en: ec115e11f96ffe60 - zh: c1fe9eb2866196d0 + en: 4fa61247fe33edb0 + zh: afa76f74841eb586 /agent-note-cua-scoped-surfaces-and-separated-input-capabilities/alternatives-considered: en: 32c970ae153e0f6c zh: 8431be0a10ffed15 diff --git a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md index 609e5bf901..3888527013 100644 --- a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md +++ b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md @@ -16,7 +16,7 @@ Provider startup capabilities are static. Platform, supported methods, applicati Keyboard input keeps keys and modifiers separate: `pressKey(key, modifiers?)` presses and releases one key while holding the listed modifiers, and its keyboard modifier list is a plain string array defined by the provider. `sendKeyEvent(key, direction)` sends exactly one key-down or key-up without an implicit counterpart. A caller can therefore hold a modifier or split a gesture; neither method packs a chord string, and the shared schema does not enumerate platform key names. -Within one API instance, the object facade keeps one current accessibility snapshot per application handle, shared by every application and window object for that handle, including repeated selections of the same application. `getWindow` reads its initial tree silently; `getApp` does the same when the provider reports application-level accessibility. A later `getAccessibilityTree` read invalidates the previous snapshot before dispatch. The facade automatically attaches the latest snapshot ID to element operations; callers use element IDs from the latest tree and do not assume an older ID still identifies the same control. Element IDs are opaque provider strings. Only an explicit `CuaWindow` captures screenshots or sends pointer input. The native helper retains its own application and optional-window snapshots behind that facade; the native layer and the facade snapshot remain separate. The external runtime continues to own variable persistence and completion serialization; the facade adds no evaluator. The [native object decision](2026-09-17-experimental-cua-object-api.md) owns evaluator independence, and the [shared helper decision](2026-10-09-cua-shared-native-helper.md) owns connection lifetime. +Within one API instance, the object facade keeps one current accessibility snapshot per application handle, shared by every application and window object for that handle, including repeated selections of the same application. `getApp` and `getWindow` select objects without reading accessibility or replacing that snapshot; `getWindow` validates membership in the application’s current window list. An explicit `getAccessibilityTree` read invalidates the previous snapshot before dispatch. The facade automatically attaches the latest snapshot ID to element operations; callers use element IDs from the latest tree and do not assume an older ID still identifies the same control. Element IDs are opaque provider strings. Only an explicit `CuaWindow` captures screenshots or sends pointer input. The native helper retains its own application and optional-window snapshots behind that facade; the native layer and the facade snapshot remain separate. The external runtime continues to own variable persistence and completion serialization; the facade adds no evaluator. The [native object decision](2026-09-17-experimental-cua-object-api.md) owns evaluator independence, and the [shared helper decision](2026-10-09-cua-shared-native-helper.md) owns connection lifetime. ## Alternatives considered diff --git a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md index 081f02986e..8a3f152e67 100644 --- a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md @@ -16,7 +16,7 @@ Provider 的启动能力是静态的。平台、支持的方法、应用级辅 键盘输入把按键与修饰键分开:`pressKey(key, modifiers?)` 在按住所列修饰键时按下并释放一个键,其键盘修饰键列表是 provider 定义的普通字符串数组。`sendKeyEvent(key, direction)` 只发送一次按下或抬起,不隐式发送相反事件。因此调用方可以保持修饰键或拆分手势;两个方法都不接受组合键字符串,共享 schema 也不枚举平台按键名。 -在单个 API 实例内,对象门面按应用句柄保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享这份快照,包括对同一应用的重复选择。`getWindow` 静默执行首次树读取;当 provider 报告应用级辅助功能时,`getApp` 也静默读取。之后的 `getAccessibilityTree` 读取会在分派前使上一份快照失效。门面会为元素操作自动附加最新快照 ID;调用方应使用最新树中的元素 ID,不应假定旧 ID 仍指向同一控件。元素 ID 是 provider 定义的不透明字符串。只有显式 `CuaWindow` 可以截图或发送指针输入。原生 helper 在该门面之后保留自己的应用快照和可选窗口快照;原生层与门面快照相互独立。外部运行时继续负责变量持久化和最终表达式序列化;门面不加入 evaluator。[原生对象决定](2026-09-17-experimental-cua-object-api.zh.md)负责 evaluator 独立性,[共享 helper 决定](2026-10-09-cua-shared-native-helper.zh.md)负责连接生命期。 +在单个 API 实例内,对象门面按应用句柄保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享这份快照,包括对同一应用的重复选择。`getApp` 和 `getWindow` 只选择对象,不读取辅助功能或替换该快照;`getWindow` 会核验窗口属于应用的当前窗口列表。显式 `getAccessibilityTree` 读取会在分派前使上一份快照失效。门面会为元素操作自动附加最新快照 ID;调用方应使用最新树中的元素 ID,不应假定旧 ID 仍指向同一控件。元素 ID 是 provider 定义的不透明字符串。只有显式 `CuaWindow` 可以截图或发送指针输入。原生 helper 在该门面之后保留自己的应用快照和可选窗口快照;原生层与门面快照相互独立。外部运行时继续负责变量持久化和最终表达式序列化;门面不加入 evaluator。[原生对象决定](2026-09-17-experimental-cua-object-api.zh.md)负责 evaluator 独立性,[共享 helper 决定](2026-10-09-cua-shared-native-helper.zh.md)负责连接生命期。 ## 考虑过的替代方案 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml index a76d4de320..c907006371 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml @@ -12,5 +12,5 @@ en: e5d1027faa55adba zh: 4b88ad6a70977fb3 /native-cua-application-and-window-api/migration: - en: b09e3dde32391786 - zh: f702e1e25b260b29 + en: b4d5bf5c30f42dfb + zh: 7ec59dc6a90165ef diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md index 3179dae0d9..a49a251c37 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md @@ -16,7 +16,7 @@ Providers supply startup capabilities alongside their platform guidance. The nat ## Migration 1. After `cua.getApp(selector)`, select the target from `app.getWindows()` with `app.getWindow(windowId)`. Use `window.getScreenshot()`, `window.click()`, `window.scroll()`, and `window.drag()`. Replace `hover` with `window.mouseMove()`. On macOS, `window.click(id)` sends mouse events at the element center. Switch to `invoke(id)` for the default accessibility action, or `performAction(id, "AXShowMenu")` to request an advertised menu action. -2. Replace `getAXState()` with `getAccessibilityTree()`. Replace `getAXStateAndScreenshot()` with separate tree and screenshot reads. Selection reads the initial tree silently for a window, and for an app when `appLevelAccessibility` is true. Read the tree explicitly to display it. +2. Replace `getAXState()` with `getAccessibilityTree()`. Replace `getAXStateAndScreenshot()` with separate tree and screenshot reads. Application and window selection no longer read AX implicitly. Before using element IDs, call `getAccessibilityTree()` explicitly; use `{ emit: false }` to retain the snapshot without displaying it. A screenshot does not require a successful AX read. 3. Pass the opaque string ID from the latest tree wherever you passed a numeric element index. In raw requests use `elementId` with `snapshotId`. Replace `performSecondaryAction` with `listActions(id)` and `performAction(id, exactName, argument?)`, or use `invoke(id)` for the default action. `setValue` accepts the provider’s supported JSON values. On macOS, `performAction(id, 'AXRaise')` performs the advertised raise action. Call `app.activate()` first when the application must become active. 4. Replace a packed chord such as `pressKey('shift+Tab')` with `pressKey('Tab', ['shift'])`. Check `(await cua.getCapabilities()).methods` before using `sendKeyEvent`: macOS supports complete keystrokes and rejects directional events with `NOT_IMPLEMENTED`. 5. Read `dispatched` from action results, then observe the application to verify the outcome. `invoke` returns `dispatched: false` when the element has no default action. Remove reads of the old `verified` field and of `pid` on selected objects or window records. Use `listApps()` or running `findApps()` matches when you need a PID. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md index f0a4a905e0..fae92008f1 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md @@ -16,7 +16,7 @@ CUA 脚本在指定窗口上截图和操作鼠标。App 和 Window 对象共享 ## 迁移 1. 调用 `cua.getApp(selector)` 后,从 `app.getWindows()` 返回的列表选定目标,再调用 `app.getWindow(windowId)`。在窗口上调用 `getScreenshot()`、`click()`、`scroll()` 和 `drag()`,将原有的 `hover` 调用改为 `window.mouseMove()`。在 macOS 上,`window.click(id)` 在元素中心发送鼠标事件。需要执行默认辅助功能动作时,改用 `invoke(id)`。需要打开控件菜单且控件声明了 `AXShowMenu` 时,调用 `performAction(id, "AXShowMenu")`。 -2. 将 `getAXState()` 改为 `getAccessibilityTree()`,将 `getAXStateAndScreenshot()` 拆成读取树和截图两次调用。选择窗口时会静默读取初始树。选择应用时,只有 `appLevelAccessibility` 为真才读取。要显示树,请显式读取。 +2. 将 `getAXState()` 改为 `getAccessibilityTree()`,将 `getAXStateAndScreenshot()` 拆成读取树和截图两次调用。选择应用或窗口不再隐式读取 AX。使用元素 ID 前须显式调用 `getAccessibilityTree()`;使用 `{ emit: false }` 可保留快照但不显示树。截图不要求 AX 读取成功。 3. 将数字元素索引改为从最新树中取得的字符串 ID。直接发送请求时使用 `elementId` 和 `snapshotId`。原先调用 `performSecondaryAction` 的地方,先用 `listActions(id)` 取得完整动作名,再调用 `performAction(id, exactName, argument?)`。要执行默认动作,可调用 `invoke(id)`。`setValue` 接受提供方支持的 JSON 值。 在 macOS 上,`performAction(id, 'AXRaise')` 只执行元素声明的抬起窗口动作。需要把应用切到前台时先调用 `app.activate()`。 4. 将 `pressKey('shift+Tab')` 之类的组合键写法改为 `pressKey('Tab', ['shift'])`。调用 `sendKeyEvent` 前检查 `(await cua.getCapabilities()).methods`。macOS 支持完整按键,单独发送按下或松开事件会返回 `NOT_IMPLEMENTED`。 5. 从动作结果读取 `dispatched`,再观察应用确认效果。元素没有默认动作时,`invoke` 返回 `dispatched: false`。移除读取旧字段 `verified` 的代码,以及对已选对象和窗口记录中 `pid` 的读取。需要 PID 时,使用 `listApps()` 或 `findApps()` 返回的运行中应用记录。 diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index 0d83c6e538..7571c8004d 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-experimental-cua-macos/use-this-package: - en: 533ed4dd11af5126 - zh: 03036e8c949d6aca + en: e9c78a8cbd68147c + zh: 98c64b09f858edf7 /deepseek-ai-dsh-experimental-cua-macos/use-this-package/connect-an-external-execution-environment: - en: b734a0907747580e - zh: 8110c5951b70e100 + en: 7c460511bb1cee4c + zh: 2eba4fc997427e18 /deepseek-ai-dsh-experimental-cua-macos/understand-the-implementation: en: 4e82b85a5aa72eee zh: 4e004b7a205d8688 diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index 46b035112e..d139d988a3 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -41,7 +41,7 @@ For repository Web use, enable [Computer Use](../cua-bundle/README.md) in Plugin pnpm dsh headless --patch packages/experimental/cua-macos/examples/macos.cordis.yml --dump-config ``` -The dump command checks profile composition without a model request. For a real task, replace `--dump-config` with a prompt and configure the profile’s model credentials. The overlay mounts the computer-use registry and this provider; remove an existing competing provider before using it. The helper needs Accessibility permission for AX/input and Screen Recording permission for capture; use the Computer Use permission page to open System Settings and add the helper. Source builds use the bundle filename `DSH Computer Use Dev.app` and declare `DSH Computer Use Dev` in Info.plist; select the development entry when granting access. `getCapabilities` returns the provider’s declared capabilities with observed permissions and session lock state. Locked or unavailable desktop sessions reject UI observations and input before dispatch; the user must unlock macOS before resuming. `listApps` and `cua.getState` list running applications. `findApps(query)` searches standard macOS application directories by name, bundle ID or absolute path. `getApp` selects a unique name, bundle ID, path or running PID, obtains application consent, and launches a stopped app in the background when needed. A stopped application’s bundle identifier and executable path are read from disk before approval and rechecked before and after launch; applications without a bundle identifier use their canonical executable path for reusable consent. Selecting a stopped installation requests a new instance of that copy. The helper waits for launch to complete before reporting the running state. A post-launch verification failure expires the pending handle but can leave the process running; inspect running applications before selecting a fresh handle. The returned object reads initial AX silently without activating the app. Launch cancellation may leave the application running. Model guidance starts with background observation and input, without activation during initialization or before each action. For hidden or minimized windows, try `app.show()` or `window.show()` and read fresh state. This requests unhide and unminimize without activation, raising or switching Spaces; app-level restoration selects the focused, main or sole AX window. The result names the selected `windowId`, or null when no window was selected, and reports `foregroundChanged` by comparing the front app and top window before and after the request. Null means foreground evidence was unavailable; later focus changes remain possible. If restoration fails or the window remains unusable, explain the needed foreground step, call `app.activate()` or an observed window’s advertised `AXRaise` action, then observe again. Necessary foreground access takes priority over preserving focus. Applications may change focus after input; background delivery does not guarantee an undisturbed user session. +The dump command checks profile composition without a model request. For a real task, replace `--dump-config` with a prompt and configure the profile’s model credentials. The overlay mounts the computer-use registry and this provider; remove an existing competing provider before using it. The helper needs Accessibility permission for AX/input and Screen Recording permission for capture; use the Computer Use permission page to open System Settings and add the helper. Source builds use the bundle filename `DSH Computer Use Dev.app` and declare `DSH Computer Use Dev` in Info.plist; select the development entry when granting access. `getCapabilities` returns the provider’s declared capabilities with observed permissions and session lock state. Locked or unavailable desktop sessions reject UI observations and input before dispatch; the user must unlock macOS before resuming. `listApps` and `cua.getState` list running applications. `findApps(query)` searches standard macOS application directories by name, bundle ID or absolute path. `getApp` selects a unique name, bundle ID, path or running PID, obtains application consent, and launches a stopped app in the background when needed. A stopped application’s bundle identifier and executable path are read from disk before approval and rechecked before and after launch; applications without a bundle identifier use their canonical executable path for reusable consent. Selecting a stopped installation requests a new instance of that copy. The helper waits for launch to complete before reporting the running state. A post-launch verification failure expires the pending handle but can leave the process running; inspect running applications before selecting a fresh handle. The returned object does not read AX or activate the app. Launch cancellation may leave the application running. Model guidance starts with background observation and input, without activation during initialization or before each action. For hidden or minimized windows, try `app.show()` or `window.show()` and read fresh state. This requests unhide and unminimize without activation, raising or switching Spaces; app-level restoration selects the focused, main or sole AX window. The result names the selected `windowId`, or null when no window was selected, and reports `foregroundChanged` by comparing the front app and top window before and after the request. Null means foreground evidence was unavailable; later focus changes remain possible. If restoration fails or the window remains unusable, explain the needed foreground step, call `app.activate()` or an observed window’s advertised `AXRaise` action, then observe again. Necessary foreground access takes priority over preserving focus. Applications may change focus after input; background delivery does not guarantee an undisturbed user session. Source builds default to `sourceSigning: ad-hoc`, without creating certificates or keychains. Changed binaries can require new permission grants. To reduce repeated grants during rebuilds and across worktrees, select an existing certificate and its absolute keychain path in the DSH home’s `cordis.patch.yml`; `cua` is the entry ID loading `@deepseek-ai/dsh-experimental-cua-macos`: @@ -111,9 +111,9 @@ const window = await app.getWindow(windows[0].windowId) void await window.getScreenshot() ``` -Use the `cua` API to discover and select the application (`listApps`, `getState`, `findApps`, `getApp`); use the selected app to activate it, enumerate its windows, and select one. Window selection is required for screenshots and pointer input, not only when several windows exist. `getApp` and `app.getWindow(windowId)` read their initial trees silently; choose the window by its observed title and bounds. +Use the `cua` API to discover and select the application (`listApps`, `getState`, `findApps`, `getApp`); use the selected app to activate it, enumerate its windows, and select one. Window selection is required for screenshots and pointer input, not only when several windows exist. `getApp` and `app.getWindow(windowId)` return without reading AX; choose the window from `getWindows()` by its title and bounds. -`getWindow` reads its initial tree silently. An owned window without an AX surface returns an empty snapshot and remains available for screenshots and coordinate input. 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. A failed read publishes no partial snapshot; read again without repeating the preceding input. Window objects own screenshots and pointer input. Keyboard methods stay on `app` because input follows the app’s current focus. +`getWindow` validates the ID against the current application window list. Read `getAccessibilityTree()` explicitly before element operations. Screenshots and coordinate input do not require a successful AX read; absolute pixel coordinates require a delivered screenshot. An owned window without an AX surface returns an empty snapshot when explicitly observed. 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. A failed read publishes no partial snapshot; read again without repeating the preceding input. Window objects own screenshots and pointer input. Keyboard methods stay on `app` because input follows the app’s current focus. `mouseMove(target)` defaults to AX hover. An enabled target or ancestor must advertise both `AXShowAlternateUI` and `AXShowDefaultUI`. Moving into its descendants keeps the UI open, and leaving restores it. Without an AX route the helper returns `HOVER_UNAVAILABLE` before sending input. Click a visible control or use `performAction` with an advertised action. For browser content without these AX actions, use browser tools. Enable `systemPointerHover` only when moving the user’s visible cursor is acceptable. That route requires a foreground, unobscured target and leaves the cursor at the destination. @@ -189,9 +189,9 @@ Setup and discovery: - cua.listApps(options?: { emit?: boolean }) -> { id: string, displayName: string, isRunning: true, pid: number }[] — enumerate running applications. - cua.findApps(query: string, options?: { emit?: boolean }) -> ({ id: string, displayName: string, path: string } & ({ isRunning: true, pid: number } | { isRunning: false }))[] — search installed applications, including stopped matches; only running matches carry pid. - cua.getState(options?: { emit?: boolean }) -> { apps: { id: string, displayName: string, isRunning: true, pid: number }[], browsers: [] } — summarize running applications; this is not an accessibility observation. -- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and read initial AX state silently; it does not activate the app. +- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and return without reading AX or activating the app. - app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership. -- app.getWindow(windowId: number) -> Window — select one window and read its initial AX state silently; do this before any window screenshot or coordinate input. +- app.getWindow(windowId: number) -> Window — select a window from the application’s current window list without reading AX; do this before any window screenshot or coordinate input. - app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required. - app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation. - window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation. @@ -199,7 +199,7 @@ Setup and discovery: ## Accessibility tree Available at app or window level depending on the platform. -Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. +Read getAccessibilityTree explicitly before using element ids. Selection and screenshots do not read or replace the current AX snapshot. Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. - getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the full tree text; includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. - listActions(elementId: string) -> string[] — list the actions an element advertises. - invoke(elementId: string) -> ActionResult — invoke the element's default action; dispatched is false when it has none. @@ -223,7 +223,7 @@ Available at app or window level depending on the platform. - 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?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. +Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree maps to getState; getWindow validates against listWindows; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. ``` #### Token effect diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 341796b8c4..f8fed7b624 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -41,7 +41,7 @@ provider 按当前界面语言生成引导和恢复文案,不支持的语言 pnpm dsh headless --patch packages/experimental/cua-macos/examples/macos.cordis.yml --dump-config ``` -配置输出命令不发起模型请求。执行真实任务时,将 `--dump-config` 替换为任务提示,并配置该 profile 的模型凭据。配置挂载 computer-use 注册表和本 provider;使用前需移除已有的竞争 provider。helper 需要辅助功能权限来读取 AX 和输入,需要屏幕录制权限来截图;通过 Computer Use 权限页打开系统设置并添加 helper。源码构建的应用包名为 `DSH Computer Use Dev.app`,Info.plist 声明名称 `DSH Computer Use Dev`;授权时选择开发版条目。`getCapabilities` 返回提供方声明的平台能力,以及实际查询的权限和锁屏状态。桌面会话锁定或不可用时,界面观察与输入会在分派前拒绝,需由用户解锁 macOS 后继续。`listApps` 和 `cua.getState` 列出运行中的应用。`findApps(query)` 按名称、bundle ID 或绝对路径搜索 macOS 标准应用目录。`getApp` 按唯一名称、bundle ID、路径或运行中的 PID 选择应用,取得应用许可后,在需要时后台启动尚未运行的应用。授权前从磁盘读取应用的 Bundle ID 和可执行路径,在启动前后重新读取并核对;没有 Bundle ID 的应用使用规范化的可执行路径复用授权。选择尚未运行的安装副本时,会请求为该副本创建新实例。helper 等待应用完成启动后返回运行状态。启动后验证失败会使待启动句柄失效,但进程可能仍在运行;应先查看运行中的应用,再取得新句柄。返回的对象静默读取初始 AX,不自动激活应用。启动被取消时,应用可能已经运行。模型指引要求先在后台观察和输入,不在初始化或每次动作前激活应用。窗口隐藏或最小化时,先尝试 `app.show()` 或 `window.show()`,再重新观察。它请求取消隐藏和恢复最小化,不主动激活、抬起窗口或切换桌面空间;应用级恢复选择焦点窗口、主窗口或唯一 AX 窗口。结果通过 `windowId` 指明选中的窗口,未选中时为 null;`foregroundChanged` 比较操作前后的前台应用和最上层窗口,无法取得完整观察时为 null,返回后仍可能发生焦点变化。恢复失败或窗口仍不可用时,说明需要前台的步骤,再调用 `app.activate()` 或窗口声明的 `AXRaise` 动作并重新观察。必须使用前台时,以完成任务为先。应用收到输入后仍可能改变焦点,后台投递不保证用户操作始终不受干扰。 +配置输出命令不发起模型请求。执行真实任务时,将 `--dump-config` 替换为任务提示,并配置该 profile 的模型凭据。配置挂载 computer-use 注册表和本 provider;使用前需移除已有的竞争 provider。helper 需要辅助功能权限来读取 AX 和输入,需要屏幕录制权限来截图;通过 Computer Use 权限页打开系统设置并添加 helper。源码构建的应用包名为 `DSH Computer Use Dev.app`,Info.plist 声明名称 `DSH Computer Use Dev`;授权时选择开发版条目。`getCapabilities` 返回提供方声明的平台能力,以及实际查询的权限和锁屏状态。桌面会话锁定或不可用时,界面观察与输入会在分派前拒绝,需由用户解锁 macOS 后继续。`listApps` 和 `cua.getState` 列出运行中的应用。`findApps(query)` 按名称、bundle ID 或绝对路径搜索 macOS 标准应用目录。`getApp` 按唯一名称、bundle ID、路径或运行中的 PID 选择应用,取得应用许可后,在需要时后台启动尚未运行的应用。授权前从磁盘读取应用的 Bundle ID 和可执行路径,在启动前后重新读取并核对;没有 Bundle ID 的应用使用规范化的可执行路径复用授权。选择尚未运行的安装副本时,会请求为该副本创建新实例。helper 等待应用完成启动后返回运行状态。启动后验证失败会使待启动句柄失效,但进程可能仍在运行;应先查看运行中的应用,再取得新句柄。返回对象时不读取 AX,也不激活应用。启动被取消时,应用可能已经运行。模型指引要求先在后台观察和输入,不在初始化或每次动作前激活应用。窗口隐藏或最小化时,先尝试 `app.show()` 或 `window.show()`,再重新观察。它请求取消隐藏和恢复最小化,不主动激活、抬起窗口或切换桌面空间;应用级恢复选择焦点窗口、主窗口或唯一 AX 窗口。结果通过 `windowId` 指明选中的窗口,未选中时为 null;`foregroundChanged` 比较操作前后的前台应用和最上层窗口,无法取得完整观察时为 null,返回后仍可能发生焦点变化。恢复失败或窗口仍不可用时,说明需要前台的步骤,再调用 `app.activate()` 或窗口声明的 `AXRaise` 动作并重新观察。必须使用前台时,以完成任务为先。应用收到输入后仍可能改变焦点,后台投递不保证用户操作始终不受干扰。 源码构建默认使用 `sourceSigning: ad-hoc` 临时签名,不创建证书或钥匙串。二进制变化后可能需要重新授权。需要减少开发重建和跨 worktree 的授权次数时,在 DSH home 的 `cordis.patch.yml` 中选择已有证书及其钥匙串绝对路径;`cua` 是加载 `@deepseek-ai/dsh-experimental-cua-macos` 的节点 ID: @@ -111,9 +111,9 @@ const window = await app.getWindow(windows[0].windowId) void await window.getScreenshot() ``` -使用 `cua` API 发现并选择应用(`listApps`、`getState`、`findApps`、`getApp`);使用选定的应用来激活它、枚举其窗口并选择窗口。截图和指针输入都要求选择窗口,不只在存在多个窗口时才需要。`getApp` 和 `app.getWindow(windowId)` 静默读取初始树;根据观察到的标题与位置选择窗口。 +使用 `cua` API 发现并选择应用(`listApps`、`getState`、`findApps`、`getApp`);使用选定的应用来激活它、枚举其窗口并选择窗口。截图和指针输入都要求选择窗口,不只在存在多个窗口时才需要。`getApp` 和 `app.getWindow(windowId)` 返回时不读取 AX;根据 `getWindows()` 中的标题与位置选择窗口。 -`getWindow` 静默读取初始树。已确认归属但没有 AX 界面的窗口返回空快照,仍可截图和发送坐标输入。在单个 API 实例内,门面按应用句柄保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享它,包括重复选择。读取任一窗口都会替换该快照;元素操作使用最新快照 ID,因此应使用最新树中的元素 ID,不应假定旧 ID 仍指向同一控件。读取失败不会发布部分快照;可以重新读取,但不要重复此前的输入。窗口对象负责截图和指针输入。键盘方法保留在 `app` 上,因为输入跟随应用的当前焦点。 +`getWindow` 根据当前应用窗口清单验证 ID。元素操作前须显式读取 `getAccessibilityTree()`。截图和坐标输入不要求 AX 读取成功;绝对像素坐标要求已交付的截图。已确认归属但没有 AX 界面的窗口在显式观察时返回空快照。在单个 API 实例内,门面按应用句柄保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享它,包括重复选择。读取任一窗口都会替换该快照;元素操作使用最新快照 ID,因此应使用最新树中的元素 ID,不应假定旧 ID 仍指向同一控件。读取失败不会发布部分快照;可以重新读取,但不要重复此前的输入。窗口对象负责截图和指针输入。键盘方法保留在 `app` 上,因为输入跟随应用的当前焦点。 `mouseMove(target)` 默认通过 AX 悬停。目标或其祖先必须已启用,并同时声明 `AXShowAlternateUI` 和 `AXShowDefaultUI`。进入子控件会保持展开,离开后恢复默认界面。如果没有可用的 AX 路径,helper 返回 `HOVER_UNAVAILABLE`,不发送输入。可点击已经可见的控件,或用 `performAction` 执行控件声明的动作。浏览器内容缺少这些 AX 动作时,请使用浏览器工具。只有允许移动用户可见光标时才开启 `systemPointerHover`。这条路径要求目标在前台且未被遮挡,操作后光标停在目标位置。 @@ -189,9 +189,9 @@ Setup and discovery: - cua.listApps(options?: { emit?: boolean }) -> { id: string, displayName: string, isRunning: true, pid: number }[] — enumerate running applications. - cua.findApps(query: string, options?: { emit?: boolean }) -> ({ id: string, displayName: string, path: string } & ({ isRunning: true, pid: number } | { isRunning: false }))[] — search installed applications, including stopped matches; only running matches carry pid. - cua.getState(options?: { emit?: boolean }) -> { apps: { id: string, displayName: string, isRunning: true, pid: number }[], browsers: [] } — summarize running applications; this is not an accessibility observation. -- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and read initial AX state silently; it does not activate the app. +- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and return without reading AX or activating the app. - app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership. -- app.getWindow(windowId: number) -> Window — select one window and read its initial AX state silently; do this before any window screenshot or coordinate input. +- app.getWindow(windowId: number) -> Window — select a window from the application’s current window list without reading AX; do this before any window screenshot or coordinate input. - app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required. - app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation. - window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation. @@ -199,7 +199,7 @@ Setup and discovery: ## Accessibility tree Available at app or window level depending on the platform. -Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. +Read getAccessibilityTree explicitly before using element ids. Selection and screenshots do not read or replace the current AX snapshot. Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. - getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the full tree text; includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. - listActions(elementId: string) -> string[] — list the actions an element advertises. - invoke(elementId: string) -> ActionResult — invoke the element's default action; dispatched is false when it has none. @@ -223,7 +223,7 @@ Available at app or window level depending on the platform. - 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?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. +Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree maps to getState; getWindow validates against listWindows; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. ``` #### Token 影响 diff --git a/packages/experimental/cua-macos/tests/loader-composition.spec.ts b/packages/experimental/cua-macos/tests/loader-composition.spec.ts index e92f138d87..e1395145d4 100644 --- a/packages/experimental/cua-macos/tests/loader-composition.spec.ts +++ b/packages/experimental/cua-macos/tests/loader-composition.spec.ts @@ -181,7 +181,7 @@ it.skipIf(process.platform === 'win32')('shares one application between retained const screenshot = await peerWindow.getScreenshot({ emit: false }) expect(screenshot).toMatchObject({ mimeType: 'image/png', pixelWidth: 1, pixelHeight: 1, windowId: 7 }) expect(Buffer.from(screenshot.bytes).toString('base64')).toBe(png) - await peerApp.getWindow(8) + await (await peerApp.getWindow(8)).getAccessibilityTree({ emit: false }) const recovery = 'Snapshot belongs to window 8; read getAccessibilityTree on window 7' await expect(peerWindow.click(element('0'))).rejects.toThrow(recovery) await expect(peerWindow.mouseMove(element('0'))).rejects.toThrow(recovery) diff --git a/packages/experimental/cua-macos/tests/persistent-bridge.built.e2e.ts b/packages/experimental/cua-macos/tests/persistent-bridge.built.e2e.ts index b37b79b6c1..61fe3b3bdb 100644 --- a/packages/experimental/cua-macos/tests/persistent-bridge.built.e2e.ts +++ b/packages/experimental/cua-macos/tests/persistent-bridge.built.e2e.ts @@ -74,7 +74,7 @@ it.skipIf(process.platform === 'win32' || !existsSync(bridge) || !existsSync(boo const section = (await ctx.systemPrompt.assemble()).sections.find(value => value.name === 'computer-use:dsh-cua') const initialization = section?.text.match(/Persistent PTC initialization:\n\n```ts\n([\s\S]*?)\n```/u)?.[1] expect(initialization).toContain('/lib/bridge.js') - const first = await run(`${initialization}\nvar app = await cua.getApp("test.fixture"); var win = await app.getWindow(7); await win.click("0"); var shot = await win.getScreenshot(); ({ mimeType: shot.mimeType, pixelWidth: shot.pixelWidth, pixelHeight: shot.pixelHeight, windowId: shot.windowId, byteLength: shot.bytes.length });`, 'first') + const first = await run(`${initialization}\nvar app = await cua.getApp("test.fixture"); var win = await app.getWindow(7); await win.getAccessibilityTree({emit:false}); await win.click("0"); var shot = await win.getScreenshot(); ({ mimeType: shot.mimeType, pixelWidth: shot.pixelWidth, pixelHeight: shot.pixelHeight, windowId: shot.windowId, byteLength: shot.bytes.length });`, 'first') expect(first.error).toBeUndefined() expect(first.value).toEqual({ mimeType: 'image/png', pixelWidth: 1, pixelHeight: 1, windowId: 7, byteLength: 90 }) expect(images).toBe(1) diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index f4abb13c43..fffdfaa5c6 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: ba1f8e6ae51f69d7 - zh: 8f4fde9857bae319 + en: 77dbaaa91d5b92c8 + zh: 94c3a758a91476bd /deepseek-ai-dsh-cua/use-this-package/permission-controls: en: d92d5948a7941e8d zh: d43491ae6521b87e /deepseek-ai-dsh-cua/understand-the-implementation: - en: 2ab74a1ff120459e - zh: 39b3ef198989f133 + en: fbd52f5ae2ca44f8 + zh: 386fb22fa7f7703d /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 c95e4ae8ec..0b3d39fdd1 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -31,7 +31,7 @@ Application consent supplies English, Chinese, and Japanese display text from `s Mount the [macOS provider](../cua-macos/README.md) to enable native operations on macOS. 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 `cua.getApp(selector)` to select an application; it obtains consent, optionally launches a stopped application in the background, and reads its initial accessibility tree silently when the provider supports application-level accessibility. `cua.listApps` and `cua.getState` list running applications; `cua.findApps(query)` searches installed applications, including stopped ones. `app.activate()`, `app.getWindows()`, and `app.getWindow(windowId)` operate on the selected application; `getWindow` returns the object for screenshots and pointer input. Select an application and one of its windows before any capture or pointer input. Call `app.getAccessibilityTree()` to emit the tree. Within one API instance, the facade keeps one current accessibility snapshot per application handle across app and window objects, including repeated selections; each new read invalidates the previous snapshot. Element operations use the latest snapshot ID, so callers use IDs from the latest tree and do not assume an older ID still identifies the same control. Element IDs are opaque strings. +Use `cua.getApp(selector)` to select an application; it obtains consent and optionally launches a stopped application in the background, without reading its accessibility tree. `cua.listApps` and `cua.getState` list running applications; `cua.findApps(query)` searches installed applications, including stopped ones. `app.activate()`, `app.getWindows()`, and `app.getWindow(windowId)` operate on the selected application; `getWindow` validates the ID against the current application window list and returns the object without reading AX. Select an application and one of its windows before any capture or pointer input. Read `app.getAccessibilityTree()` or `window.getAccessibilityTree()` explicitly before element operations. Screenshots remain available when AX reading fails. Within one API instance, the facade keeps one current accessibility snapshot per application handle across app and window objects, including repeated selections; each new read invalidates the previous snapshot. Element operations use the latest snapshot ID, so callers use IDs from the latest tree and do not assume an older ID still identifies the same control. Element IDs are opaque strings. Keyboard methods are available in the scopes a provider declares; the provider owns how input is delivered within each scope. A lost connection invalidates its handles and coordinates. Failed cleanup is reported before that connection is retired; select the application again and inspect fresh state, because earlier input may have partially executed. Screenshot image errors retain the failing stage and attachment error code. Invalid request arguments reject before dispatch with a readable method, parameter and requirement. @@ -87,7 +87,7 @@ The provider calls [installCua](src/index.ts) with its prepared helper, connecti [The operation schema](src/protocol.ts) is the authority for model parameters and separately declared Host-only fields. Native implementations enforce target identity, window geometry, resource limits, and operating-system access at execution. The permission store owns durable consent separately from the native protocol. -One object facade ([src/api.ts](src/api.ts)) builds a shared `CuaSurface` and derives `CuaApp` and `CuaWindow` from it. The derived factories inject scope parameters and the accessibility and keyboard checks for their scope; the shared base does not branch on application-only capabilities. Within one API instance, the facade keeps one current accessibility snapshot per `appHandle` across every app and window object for that handle. `getWindow` reads its initial tree silently; `getApp` does the same when the provider reports application-level accessibility. Each later `getAccessibilityTree()` invalidates the previous snapshot before dispatch, and element operations use the latest snapshot ID. Only a `CuaWindow` captures screenshots or sends pointer input. +One object facade ([src/api.ts](src/api.ts)) builds a shared `CuaSurface` and derives `CuaApp` and `CuaWindow` from it. The derived factories inject scope parameters and the accessibility and keyboard checks for their scope; the shared base does not branch on application-only capabilities. Within one API instance, the facade keeps one current accessibility snapshot per `appHandle` across every app and window object for that handle. Selection leaves the current accessibility snapshot unchanged. Each explicit `getAccessibilityTree()` invalidates the previous snapshot before dispatch, and element operations use the latest snapshot ID. Only a `CuaWindow` captures screenshots or sends pointer input. Provider startup capabilities are fixed at installation: platform, methods, app-level accessibility, keyboard scopes, browser support, and coordinate space. The native `getCapabilities` RPC reports runtime permissions and session lock only; `installCua` merges both layers for the model-visible result. The raw RPC remains a common operation representation rather than a capability inventory, so provider guidance states the actions its platform supports. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index c1c5ed863c..b79cc6fdb5 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -31,7 +31,7 @@ kind: "package-reference" 挂载 [macOS 提供方](../cua-macos/README.zh.md)以在 macOS 上启用原生操作。外部 PTC 宿主从 `@deepseek-ai/dsh-cua/bridge` 导入 `connectCua`,并提供当前 `tools.cua` 绑定。源码组合与原生组件准备由提供方负责。 -使用 `cua.getApp(selector)` 选择应用;它会获取授权、按需在后台启动已停止的应用,并在 provider 支持应用级辅助功能时静默读取初始辅助功能树。`cua.listApps` 和 `cua.getState` 列出运行中的应用;`cua.findApps(query)` 搜索已安装应用,包括未运行的应用。`app.activate()`、`app.getWindows()` 和 `app.getWindow(windowId)` 操作选定的应用;`getWindow` 返回用于截图和指针输入的对象。进行任何截图或指针输入前,必须选择应用及其一个窗口。调用 `app.getAccessibilityTree()` 输出树。在单个 API 实例内,门面按应用句柄保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享它,包括重复选择;每次新读取都会使上一份快照失效。元素操作使用最新快照 ID,因此调用方应使用最新树中的元素 ID,不应假定旧 ID 仍指向同一控件。元素 ID 是不透明字符串。 +使用 `cua.getApp(selector)` 选择应用;它会获取授权、按需在后台启动已停止的应用,不读取辅助功能树。`cua.listApps` 和 `cua.getState` 列出运行中的应用;`cua.findApps(query)` 搜索已安装应用,包括未运行的应用。`app.activate()`、`app.getWindows()` 和 `app.getWindow(windowId)` 操作选定的应用;`getWindow` 根据当前应用窗口清单验证 ID,然后返回对象,不读取 AX。进行任何截图或指针输入前,必须选择应用及其一个窗口。元素操作前须显式读取 `app.getAccessibilityTree()` 或 `window.getAccessibilityTree()`。AX 读取失败时仍可截图。在单个 API 实例内,门面按应用句柄保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享它,包括重复选择;每次新读取都会使上一份快照失效。元素操作使用最新快照 ID,因此调用方应使用最新树中的元素 ID,不应假定旧 ID 仍指向同一控件。元素 ID 是不透明字符串。 键盘方法可在 provider 声明的作用域中使用;每个作用域内的输入投递由 provider 负责。连接丢失会使其句柄和坐标失效。清理失败会先报告,再释放该连接;应重新选择应用并读取新状态,因为先前的输入可能已部分执行。截图图像错误会保留失败阶段和附件错误码。请求参数校验失败时,在分派前返回包含方法、参数和要求的可读消息。 @@ -87,7 +87,7 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边 [操作 schema](src/protocol.ts) 定义模型参数,并单独声明 Host 专用字段。原生实现在执行时检查目标身份、窗口几何、资源上限和操作系统访问条件。授权存储独立于原生协议保存持久许可。 -对象门面([src/api.ts](src/api.ts))构建共享的 `CuaSurface`,并从它派生 `CuaApp` 和 `CuaWindow`。派生工厂注入作用域参数以及该作用域的辅助功能和键盘检查;共享基类不为仅属于应用的能力分支。在单个 API 实例内,门面按 `appHandle` 保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享它。`getWindow` 静默读取初始树;当 provider 报告应用级辅助功能时,`getApp` 也静默读取。之后每次 `getAccessibilityTree()` 在分派前使上一份快照失效,元素操作使用最新快照 ID。只有 `CuaWindow` 可以截图或发送指针输入。 +对象门面([src/api.ts](src/api.ts))构建共享的 `CuaSurface`,并从它派生 `CuaApp` 和 `CuaWindow`。派生工厂注入作用域参数以及该作用域的辅助功能和键盘检查;共享基类不为仅属于应用的能力分支。在单个 API 实例内,门面按 `appHandle` 保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享它。选择对象不改变当前辅助功能快照。每次显式调用 `getAccessibilityTree()` 在分派前使上一份快照失效,元素操作使用最新快照 ID。只有 `CuaWindow` 可以截图或发送指针输入。 提供方启动能力在安装时固定:平台、方法、应用级辅助功能、键盘作用域、浏览器支持和坐标空间。原生 `getCapabilities` RPC 只报告运行时权限和会话锁定状态;`installCua` 为模型可见结果合并两层。原生 RPC 仍是通用操作表示,而不是能力清单,因此 provider 指引说明其平台支持的动作。 diff --git a/packages/experimental/cua/package.json b/packages/experimental/cua/package.json index 440f321935..0d62908a8a 100644 --- a/packages/experimental/cua/package.json +++ b/packages/experimental/cua/package.json @@ -107,7 +107,8 @@ "@deepseek-ai/dsh-atomic-write": "workspace:*", "@deepseek-ai/dsh-typert-protocol": "workspace:*", "@deepseek-ai/dsh-computer-use": "workspace:*", - "@deepseek-ai/dsh-storage-domain": "workspace:*" + "@deepseek-ai/dsh-storage-domain": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" }, "devDependencies": { "@deepseek-ai/dsh-working-directory": "workspace:*", diff --git a/packages/experimental/cua/src/api.ts b/packages/experimental/cua/src/api.ts index 22039c6591..509b9b8676 100644 --- a/packages/experimental/cua/src/api.ts +++ b/packages/experimental/cua/src/api.ts @@ -1,5 +1,6 @@ /** Object facade over logged native operations; its caller owns evaluator persistence. */ import { Buffer } from 'node:buffer' +import { HarnessError } from '@deepseek-ai/dsh-error' import type { z } from 'zod' import type { JsonValue } from '@deepseek-ai/dsh-util-values' import { ActionNamesResult, ActionResult, AppResult, AppsResult, CapabilitiesResult, FoundAppsResult, HoverResult, Request, ScreenshotResult, ShowResult, StateResult, WindowsResult } from './protocol.ts' @@ -79,9 +80,7 @@ export function createCuaApi(dispatch: CuaDispatch, sink?: CuaObservationSink): if (!request.success) throw new Error(`getApp ${requestIssueMessage(request.error.issues)}`) const capabilities = await currentCapabilities() const { appHandle } = AppResult.parse(await call('getApp', { selector })) - const app = objects.createCuaApp(appHandle, capabilities) - if (capabilities.appLevelAccessibility) await app.getAccessibilityTree({ emit: false }) - return app + return objects.createCuaApp(appHandle, capabilities) }, } return api @@ -259,9 +258,13 @@ function createCuaObjects(call: ReturnType, sink: CuaObser return windows }, async getWindow(windowId): Promise { - const window = createCuaWindow(appHandle, windowId, capabilities) - await window.getAccessibilityTree({ emit: false }) - return window + const parsed = WindowsResult.element.shape.windowId.safeParse(windowId) + if (!parsed.success) throw new HarnessError(`getWindow ${requestIssueMessage(parsed.error.issues, ['params', 'windowId'])}`, 'INVALID_ARGS') + const windows = WindowsResult.parse(await base.call('listWindows', {})) + if (!windows.some(window => window.windowId === windowId)) { + throw new HarnessError('Selected window is unavailable for this application; read getWindows again', 'CUA_WINDOW_UNAVAILABLE') + } + return createCuaWindow(appHandle, windowId, capabilities) }, } } diff --git a/packages/experimental/cua/src/guidance.ts b/packages/experimental/cua/src/guidance.ts index 745ccfe9be..89a32bd21a 100644 --- a/packages/experimental/cua/src/guidance.ts +++ b/packages/experimental/cua/src/guidance.ts @@ -11,9 +11,9 @@ Setup and discovery: - cua.listApps(options?: { emit?: boolean }) -> { id: string, displayName: string, isRunning: true, pid: number }[] — enumerate running applications. - cua.findApps(query: string, options?: { emit?: boolean }) -> ({ id: string, displayName: string, path: string } & ({ isRunning: true, pid: number } | { isRunning: false }))[] — search installed applications, including stopped matches; only running matches carry pid. - cua.getState(options?: { emit?: boolean }) -> { apps: { id: string, displayName: string, isRunning: true, pid: number }[], browsers: [] } — summarize running applications; this is not an accessibility observation. -- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and read initial AX state silently; it does not activate the app. +- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and return without reading AX or activating the app. - app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership. -- app.getWindow(windowId: number) -> Window — select one window and read its initial AX state silently; do this before any window screenshot or coordinate input. +- app.getWindow(windowId: number) -> Window — select a window from the application’s current window list without reading AX; do this before any window screenshot or coordinate input. - app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required. - app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation. - window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation. @@ -21,7 +21,7 @@ Setup and discovery: ## Accessibility tree Available at app or window level depending on the platform. -Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. +Read getAccessibilityTree explicitly before using element ids. Selection and screenshots do not read or replace the current AX snapshot. Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. - getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the full tree text; includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. - listActions(elementId: string) -> string[] — list the actions an element advertises. - invoke(elementId: string) -> ActionResult — invoke the element's default action; dispatched is false when it has none. @@ -45,4 +45,4 @@ Available at app or window level depending on the platform. - 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?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name.` +Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree maps to getState; getWindow validates against listWindows; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name.` diff --git a/packages/experimental/cua/src/types.ts b/packages/experimental/cua/src/types.ts index b84663f9e2..0e8624b6ea 100644 --- a/packages/experimental/cua/src/types.ts +++ b/packages/experimental/cua/src/types.ts @@ -238,9 +238,9 @@ export interface CuaApp extends CuaSurface { */ getWindows(options?: CuaObservationOptions): Promise /** - * Observe a specific window. + * Select a specific window. * @param windowId - ID obtained from getWindows. - * @returns A window object with its initial accessibility tree read silently; this updates the application's current snapshot. + * @returns A window object from the app’s current window list, without reading or replacing its accessibility snapshot. */ getWindow(windowId: number): Promise } @@ -272,9 +272,9 @@ export interface CuaApi { */ getState(options?: CuaObservationOptions): Promise<{ apps: CuaAppInfo[]; browsers: [] }> /** - * Select an app, obtain consent, launch it in the background if necessary, and silently retain initial AX state. + * Select an app, obtain consent, and launch it in the background if necessary, without reading AX. * @param selector - Exact name, bundle ID, absolute application path or running PID string; ambiguous names reject. - * @returns An application handle tied to this process lifetime; its initial tree read becomes the current snapshot. + * @returns An application handle tied to this process lifetime; call getAccessibilityTree explicitly before element operations. */ getApp(selector: string): Promise } diff --git a/packages/experimental/cua/tests/api.spec.ts b/packages/experimental/cua/tests/api.spec.ts index cbaa419951..fb2bf5a204 100644 --- a/packages/experimental/cua/tests/api.spec.ts +++ b/packages/experimental/cua/tests/api.spec.ts @@ -83,7 +83,7 @@ describe('application discovery', () => { const window = await app.getWindow(23) expect(await window.getScreenshot()).toEqual({ bytes: Uint8Array.from(Buffer.from(PNG, 'base64')), mimeType: 'image/png', pixelWidth: 1, pixelHeight: 1, windowId: 23 }) expect(f.dispatch.mock.calls.map(([operation]) => operation.method)).toEqual([ - 'getCapabilities', 'listApps', 'getApp', 'getState', 'getState', 'screenshot', + 'getCapabilities', 'listApps', 'getApp', 'listWindows', 'screenshot', ]) expect(await app.getWindows()).toEqual([windowInfo(23)]) expect(f.sink.text).not.toHaveBeenCalled() @@ -124,8 +124,11 @@ describe('application discovery', () => { describe('background window restoration', () => { it('shows an app or selected window without dispatching activation or AXRaise', async () => { const f = fixture() + f.setWindows([23, 24]) const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(24) + await window.getAccessibilityTree({ emit: false }) f.dispatch.mockClear() expect(await app.show()).toEqual({ ...delivered, windowId: 23, foregroundChanged: false }) expect(await window.show()).toEqual({ ...delivered, windowId: 24, foregroundChanged: false }) @@ -138,6 +141,7 @@ describe('background window restoration', () => { it.each([true, null])('preserves foreground change evidence %j without switching focus back', async (foregroundChanged) => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) f.dispatch.mockClear() f.dispatch.mockResolvedValueOnce({ ...delivered, windowId: null, foregroundChanged }) expect(await app.show()).toEqual({ ...delivered, windowId: null, foregroundChanged }) @@ -147,6 +151,7 @@ describe('background window restoration', () => { it('leaves foreground fallback to the caller after restoration fails', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) f.dispatch.mockClear() f.dispatch.mockRejectedValueOnce(new Error('UNSUPPORTED: Window cannot be restored')) await expect(app.show()).rejects.toThrow('UNSUPPORTED') @@ -157,8 +162,11 @@ describe('background window restoration', () => { describe('mouseMove across observations', () => { it('moves to an AX element then into a popup without inserting clicks or restoring a point', async () => { const f = fixture() + f.setWindows([23, 24]) const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) f.dispatch.mockClear() expect(await window.mouseMove(element('0'))).toEqual({ ...delivered, hoverRoute: 'accessibility', systemPointerMoved: false }) await window.getAccessibilityTree({ emit: false }) @@ -171,13 +179,14 @@ describe('mouseMove across observations', () => { { method: 'mouseMove', params: { appHandle: 'app-17', snapshotId: 'snapshot-3', windowId: 23, x: 30, y: 40 } }, ]) const other = await app.getWindow(24) + await other.getAccessibilityTree({ emit: false }) await other.mouseMove([5, 6]) expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'mouseMove', params: { appHandle: 'app-17', snapshotId: 'snapshot-4', windowId: 24, x: 5, y: 6, } }) f.dispatch.mockRejectedValueOnce(new Error('WINDOW_CHANGED')) await expect(other.mouseMove([5, 6])).rejects.toThrow('WINDOW_CHANGED') - expect(f.dispatch).toHaveBeenCalledTimes(7) + expect(f.dispatch).toHaveBeenCalledTimes(8) }) }) @@ -185,7 +194,9 @@ describe('pointer buttons and modifiers', () => { it.each([0, 800])('preserves %d ms for window clicks at elements and coordinates', async (holdMs) => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) for (const target of [element('0'), [10, 20] as const]) { await window.click(target, { holdMs, mouseButton: 'right' }) expect(f.dispatch.mock.calls.at(-1)?.[0]).toMatchObject({ method: 'click', params: { holdMs, mouseButton: 'right' } }) @@ -198,7 +209,9 @@ describe('pointer buttons and modifiers', () => { it('retains middle-button and modifier intent through click and drag dispatch', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) await window.click(element('0'), { mouseButton: 'middle', modifiers: ['shift'] }) expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'click', params: { appHandle: 'app-17', snapshotId: 'snapshot-2', elementId: '0', windowId: 23, mouseButton: 'middle', modifiers: ['shift'], @@ -223,6 +236,7 @@ describe('text selections', () => { it('binds literal text and optional disambiguation to the latest observed control', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) await app.selectText(element('1'), 'target') expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'selectText', params: { appHandle: 'app-17', snapshotId: 'snapshot-1', elementId: '1', text: 'target', @@ -242,6 +256,7 @@ describe('element action queries', () => { it('returns raw provider action names including attribute-setting operations without reading new state', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) f.dispatch.mockClear() expect(await app.listActions(element('42.12345'))).toEqual(['AXPress', 'AXShowMenu', 'AXTextArea.AXValue.Set']) expect(f.dispatch.mock.calls.map(([operation]) => operation)).toEqual([ @@ -257,6 +272,7 @@ describe('element actions', () => { it('dispatches advertised actions with omitted, null or direct values without wrapping the value', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) f.dispatch.mockClear() expect(await app.performAction(element('42.12345'), 'AXPress')).toEqual(delivered) expect(await app.performAction(element('42.12345'), 'AXPress', null)).toEqual(delivered) @@ -274,6 +290,7 @@ describe('element actions', () => { it('rejects an empty action before dispatch', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) f.dispatch.mockClear() await expect(app.performAction(element('0'), '')).rejects.toThrow('performAction action') expect(f.dispatch).not.toHaveBeenCalled() @@ -284,6 +301,7 @@ describe('element default invocation', () => { it('uses the latest snapshot and opaque element id without reading fresh state', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) f.dispatch.mockClear() expect(await app.invoke(element('42.12345'))).toEqual(delivered) expect(f.dispatch.mock.calls.map(([operation]) => operation)).toEqual([ @@ -295,6 +313,7 @@ describe('element default invocation', () => { it('returns confirmed absence of a default action as un-dispatched evidence', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) f.dispatch.mockResolvedValueOnce({ dispatched: false }) await expect(app.invoke(element('9'))).resolves.toEqual({ dispatched: false }) }) @@ -302,6 +321,7 @@ describe('element default invocation', () => { it('rejects provider failures and malformed dispatch evidence', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const failure = new Error('PERMISSION_DENIED') f.dispatch.mockRejectedValueOnce(failure) await expect(app.invoke(element('0'))).rejects.toBe(failure) @@ -316,9 +336,12 @@ describe('application and window observations', () => { const f = fixture() f.setWindows([23, 24]) const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) expect(await app.getWindows({ emit: false })).toEqual([windowInfo(23), windowInfo(24)]) const first = await app.getWindow(23) + await first.getAccessibilityTree({ emit: false }) const second = await app.getWindow(24) + await second.getAccessibilityTree({ emit: false }) await app.setValue(element('1'), 'First document') await first.click(element('2')) await second.click(element('3')) @@ -342,9 +365,11 @@ describe('application and window observations', () => { it('keeps separate snapshots for different application handles', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) f.dispatch.mockResolvedValueOnce({ appHandle: 'app-18', name: 'Utility', running: true }) f.dispatch.mockResolvedValueOnce(state({ appHandle: 'app-18', snapshotId: 'other', windows: [] })) const other = await f.api.getApp('Utility') + await other.getAccessibilityTree({ emit: false }) await app.setValue(element('0'), 'Editor') await other.setValue(element('0'), 'Utility') expect(f.dispatch.mock.calls.slice(-2).map(([operation]) => operation)).toEqual([ @@ -356,7 +381,15 @@ describe('application and window observations', () => { it('shares one current snapshot between repeated handles for the same application', async () => { const f = fixture() const first = await f.api.getApp('Editor') + await first.getAccessibilityTree({ emit: false }) const second = await f.api.getApp('Editor') + const window = await second.getWindow(23) + await window.getScreenshot({ emit: false }) + await first.setValue(element('1'), 'Preserved') + expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'setValue', params: { + appHandle: 'app-17', snapshotId: 'snapshot-1', elementId: '1', value: 'Preserved', + } }) + await second.getAccessibilityTree({ emit: false }) expect(second.appHandle).toBe(first.appHandle) await first.setValue(element('1'), 'Shared') expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'setValue', params: { @@ -367,9 +400,11 @@ describe('application and window observations', () => { it('exposes screenshots and pointer input only on explicit windows', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) expect(app).toHaveProperty('getAccessibilityTree') for (const method of ['getScreenshot', 'click', 'mouseMove', 'scroll', 'drag']) expect(app).not.toHaveProperty(method) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) for (const method of ['getScreenshot', 'click', 'mouseMove', 'scroll', 'drag']) expect(window).toHaveProperty(method) expect(window).not.toHaveProperty('hover') expect(window).toHaveProperty('mouseMove') @@ -377,13 +412,17 @@ describe('application and window observations', () => { it('attaches the shared snapshot to coordinates only within its window scope', async () => { const f = fixture() + f.setWindows([23, 24]) const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const first = await app.getWindow(23) + await first.getAccessibilityTree({ emit: false }) await first.click([10, 20]) expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'click', params: { appHandle: 'app-17', windowId: 23, snapshotId: 'snapshot-2', x: 10, y: 20, mouseButton: 'left', clickCount: 1, } }) const second = await app.getWindow(24) + await second.getAccessibilityTree({ emit: false }) await first.click([10, 20]) expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'click', params: { appHandle: 'app-17', windowId: 23, x: 10, y: 20, mouseButton: 'left', clickCount: 1, @@ -398,8 +437,10 @@ describe('application and window observations', () => { it('keeps a validated AXless window usable for screenshots and coordinate input', async () => { const f = fixture() const app = await f.api.getApp('Editor') - f.dispatch.mockResolvedValueOnce(state({ windowId: 23, snapshotId: 'axless', tree: '', elements: [] })) + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + f.dispatch.mockResolvedValueOnce(state({ windowId: 23, snapshotId: 'axless', tree: '', elements: [] })) + await window.getAccessibilityTree({ emit: false }) expect(f.sink.text).not.toHaveBeenCalled() await expect(window.getScreenshot()).resolves.toEqual({ bytes: Uint8Array.from(Buffer.from(PNG, 'base64')), mimeType: 'image/png', pixelWidth: 1, pixelHeight: 1, windowId: 23 }) await window.click([10, 20]) @@ -414,11 +455,12 @@ describe('application and window observations', () => { it.each(['WINDOW_UNAVAILABLE', 'PERMISSION_DENIED', 'STALE_APP', 'SESSION_LOCKED'])('propagates %s while selecting a window without attempting image or input fallback', async (code) => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const failure = new Error(code) f.dispatch.mockRejectedValueOnce(failure) const calls = f.dispatch.mock.calls.length await expect(app.getWindow(23)).rejects.toBe(failure) - expect(f.dispatch.mock.calls.slice(calls).map(([operation]) => operation.method)).toEqual(['getState']) + expect(f.dispatch.mock.calls.slice(calls).map(([operation]) => operation.method)).toEqual(['listWindows']) }) it('captures and clicks the explicitly selected window among several', async () => { @@ -431,8 +473,10 @@ describe('application and window observations', () => { ] f.setWindowRecords(windows) const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) expect(await app.getWindows({ emit: false })).toEqual(windows) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) await window.getScreenshot() expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'screenshot', params: { appHandle: 'app-17', windowId: 23 } }) await window.click([10, 20]) @@ -440,6 +484,7 @@ describe('application and window observations', () => { appHandle: 'app-17', windowId: 23, snapshotId: 'snapshot-2', x: 10, y: 20, mouseButton: 'left', clickCount: 1, } }) const hidden = await app.getWindow(25) + await hidden.getAccessibilityTree({ emit: false }) await hidden.click([10, 20]) expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'click', params: { appHandle: 'app-17', windowId: 25, snapshotId: 'snapshot-3', x: 10, y: 20, mouseButton: 'left', clickCount: 1, @@ -471,6 +516,7 @@ describe('application and window observations', () => { it('returns provider window records without process filtering', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const observed = windowInfo(24) f.dispatch.mockResolvedValueOnce(state({ windows: [observed] })) await expect(app.getAccessibilityTree()).resolves.toBe('Changed tree') @@ -496,11 +542,11 @@ describe('application and window observations', () => { { method: 'typeText', params: { appHandle: 'app-17', text: 'keyboard without accessibility' } }, ]) const window = await app.getWindow(23) - await expect(window.getAccessibilityTree({ emit: false })).resolves.toBe('Tree 2') + await expect(window.getAccessibilityTree({ emit: false })).resolves.toBe('Tree 1') await expect(app.getAccessibilityTree()).rejects.toThrow('Application-level accessibility is not supported on current platform; observe a window instead.') await expect(window.invoke(element('0'))).resolves.toEqual(delivered) expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'invoke', params: { - appHandle: 'app-17', windowId: 23, snapshotId: 'snapshot-2', elementId: '0', + appHandle: 'app-17', windowId: 23, snapshotId: 'snapshot-1', elementId: '0', } }) }) @@ -508,7 +554,9 @@ describe('application and window observations', () => { const f = fixture() f.setCapabilities({ ...capabilities, keyboard: ['app', 'window'] }) const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) f.dispatch.mockClear() await window.typeText('hello') await window.paste('bold', { format: 'html' }) @@ -530,7 +578,9 @@ describe('application and window observations', () => { const f = fixture() f.setCapabilities({ ...capabilities, keyboard: ['window'] }) const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) f.dispatch.mockClear() await expect(app.typeText('app text')).rejects.toThrow('App-scoped keyboard input is not supported on current platform.') await expect(app.paste('app text')).rejects.toThrow('App-scoped keyboard input is not supported on current platform.') @@ -544,7 +594,9 @@ describe('application and window observations', () => { it('accepts coordinate input without a current snapshot', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) f.dispatch.mockRejectedValueOnce(new Error('Native app is busy')) await expect(window.getAccessibilityTree()).rejects.toThrow('Native app is busy') await window.click([10, 20]) @@ -556,7 +608,9 @@ describe('application and window observations', () => { it('clears a failed refresh and requires a new read before element operations', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) const failure = new Error('Native app is busy') f.dispatch.mockRejectedValueOnce(failure) await expect(app.getAccessibilityTree()).rejects.toBe(failure) @@ -575,11 +629,54 @@ describe('application and window observations', () => { }) describe('screenshots', () => { + it('rejects a missing or foreign window without reading AX or taking a screenshot', async () => { + const f = fixture() + const app = await f.api.getApp('Editor') + await expect(app.getWindow(24)).rejects.toMatchObject({ name: 'HarnessError', code: 'CUA_WINDOW_UNAVAILABLE' }) + f.setWindows([]) + await expect(app.getWindow(23)).rejects.toMatchObject({ name: 'HarnessError', code: 'CUA_WINDOW_UNAVAILABLE' }) + expect(f.dispatch.mock.calls.map(([request]) => request.method)).toEqual(['getCapabilities', 'getApp', 'listWindows', 'listWindows']) + await expect(app.getWindow(0)).rejects.toMatchObject({ name: 'HarnessError', code: 'INVALID_ARGS', message: 'getWindow windowId: Too small: expected number to be >0' }) + expect(f.dispatch).toHaveBeenCalledTimes(4) + }) + + it.each(['APP_ACCESS_REVOKED', 'WINDOW_UNAVAILABLE', 'STALE_APP'])('preserves %s when capturing a previously selected window', async (code) => { + const f = fixture() + const app = await f.api.getApp('Editor') + const window = await app.getWindow(23) + f.dispatch.mockRejectedValueOnce(new Error(code)) + await expect(window.getScreenshot()).rejects.toThrow(code) + expect(f.sink.image).not.toHaveBeenCalled() + }) + + it.each(['application', 'window'])('captures the first screenshot when %s AX reads fail', async (scope) => { + const f = fixture() + const dispatch = f.dispatch.getMockImplementation()! + const failure = new Error('AX read failed') + f.dispatch.mockImplementation(async (request) => { + if (request.method === 'getState' && (scope === 'application' ? request.params.windowId === undefined : request.params.windowId !== undefined)) throw failure + return dispatch(request) + }) + const app = await f.api.getApp('Editor') + expect(await app.getWindows({ emit: false })).toEqual([windowInfo(23)]) + const window = await app.getWindow(23) + const target = scope === 'application' ? app : window + await expect(target.getAccessibilityTree()).rejects.toBe(failure) + await expect(window.getScreenshot()).resolves.toMatchObject({ windowId: 23, pixelWidth: 1 }) + await expect(window.invoke(element('0'))).rejects.toThrow('Read getAccessibilityTree') + await window.click([0, 0]) + expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'click', params: { + appHandle: 'app-17', windowId: 23, x: 0, y: 0, mouseButton: 'left', clickCount: 1, + } }) + }) + it('returns screenshot metadata independently of input point bounds and supports selective output', async () => { const f = fixture() f.setWindows([23, 24]) const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(24) + await window.getAccessibilityTree({ emit: false }) f.sink.text.mockClear() const tree = await window.getAccessibilityTree() const image = await window.getScreenshot() @@ -597,7 +694,9 @@ describe('screenshots', () => { it('rejects a screenshot from another window before emitting its image', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) f.dispatch.mockResolvedValueOnce(screenshot({ windowId: 24 })) await expect(window.getScreenshot()).rejects.toThrow('belongs to another window') expect(f.sink.image).not.toHaveBeenCalled() @@ -606,7 +705,9 @@ describe('screenshots', () => { it.each(['image/jpeg', 'image/webp', 'image/gif'])('preserves Host-admitted %s bytes and metadata in the return value and image sink', async (mimeType) => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) const data = Buffer.from('admitted request image').toString('base64') f.dispatch.mockResolvedValueOnce(screenshot({ mimeType, data, pixelWidth: 320, pixelHeight: 240 })) const image = await window.getScreenshot() @@ -620,7 +721,9 @@ describe('input actions', () => { it('passes explicit relative mode to every coordinate gesture and rejects it on element ids', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) await window.click([500, 250], { relative: true }) await window.mouseMove([500, 250], { relative: true }) await window.drag([0, 0], [999, 999], { relative: true }) @@ -638,7 +741,9 @@ describe('input actions', () => { it('keeps the selected window when scroll options include another target identity', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) const options = { x: 10, y: 20, deltaLinesX: 0, deltaLinesY: 1, appHandle: 'another-app', snapshotId: 'another-snapshot', windowId: 24, @@ -654,7 +759,9 @@ describe('input actions', () => { it('dispatches window-point gestures and reports delivery without claiming the action succeeded', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) expect(await window.click([10, 20], { mouseButton: 'right' })).toEqual(delivered) expect(await window.click([11, 21], { clickCount: 2 })).toEqual(delivered) expect(await window.scroll({ x: 10, y: 20, deltaLinesX: -2, deltaLinesY: 3 })).toEqual(delivered) @@ -685,7 +792,6 @@ describe('input actions', () => { ['empty key', ({ app }) => app.pressKey('')], ] it.each<[string, (surfaces: Surfaces) => Promise]>([ - ['getState windowId: Too small: expected number to be >0', ({ app }) => app.getWindow(0)], ['selectText text: Too small: expected string to have >=1 characters', ({ app }) => app.selectText(element('0'), '')], ['mouseMove x: Invalid input: expected number, received NaN', ({ window }) => window.mouseMove([NaN, 0])], ['mouseMove x: Too big: expected number to be <=999', ({ window }) => window.mouseMove([1000, 0], { relative: true })], @@ -693,7 +799,9 @@ describe('input actions', () => { ])('reports a readable validation failure: %s', async (message, run) => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) f.dispatch.mockClear() await expect(run({ app, window })).rejects.toMatchObject({ name: 'Error', message }) expect(f.dispatch).not.toHaveBeenCalled() @@ -702,7 +810,9 @@ describe('input actions', () => { it.each(invalidActions)('rejects %s without invoking native input', async (_label, run) => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) const calls = f.dispatch.mock.calls.length await expect(run({ app, window })).rejects.toThrow() expect(f.dispatch).toHaveBeenCalledTimes(calls) @@ -716,6 +826,7 @@ describe('input actions', () => { ])('forwards literal key %s with modifiers %j without splitting', async (key, modifiers, expected) => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) if (modifiers === undefined) await app.pressKey(key) else await app.pressKey(key, modifiers) expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'pressKey', params: { appHandle: 'app-17', key, modifiers: expected } }) @@ -724,6 +835,7 @@ describe('input actions', () => { it('forwards the literal key unsplit in one RPC without mutating modifiers', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const modifiers: string[] = ['control', 'shift'] f.dispatch.mockClear() await app.pressKey('+', modifiers) @@ -737,6 +849,7 @@ describe('input actions', () => { it('forwards arbitrary provider-defined key and modifier names in one RPC', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) f.dispatch.mockClear() await app.pressKey('PlatformKey', ['platform-modifier']) expect(f.dispatch).toHaveBeenCalledTimes(1) @@ -748,6 +861,7 @@ describe('input actions', () => { it('passes literal text and keys to the selected app identity', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) await app.typeText('中文\nline two') await app.paste('粘贴\nplain text') await app.paste('bold', { format: 'html' }) @@ -765,7 +879,9 @@ describe('input actions', () => { it('rejects keyboard input on a window surface without dispatching an app-level fallback', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) f.dispatch.mockClear() for (const run of [ () => window.typeText('hello'), @@ -787,6 +903,7 @@ describe('input actions', () => { const f = fixture() f.setCapabilities({ ...capabilities, keyboard: ['app', 'window'] }) const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const surface = scope === 'window' ? await app.getWindow(23) : app f.dispatch.mockClear() f.dispatch.mockResolvedValueOnce(delivered) @@ -800,6 +917,7 @@ describe('input actions', () => { it('returns an un-dispatched key-event result from one RPC without retrying', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) f.dispatch.mockClear() f.dispatch.mockResolvedValueOnce({ dispatched: false }) await expect(app.sendKeyEvent('Command', 'down')).resolves.toEqual({ dispatched: false }) @@ -829,7 +947,9 @@ describe('input actions', () => { it('retains the snapshot identity for element right and double clicks', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) await window.click(element('12'), { mouseButton: 'right' }) await window.click(element('13'), { clickCount: 2 }) expect(f.dispatch.mock.calls.slice(-2).map(([operation]) => operation)).toEqual([ @@ -841,7 +961,9 @@ describe('input actions', () => { it('dispatches an opaque provider element id unchanged', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) await window.click(element('42.12345')) await window.mouseMove(element('42.12345')) expect(f.dispatch.mock.calls.slice(-2).map(([operation]) => operation)).toEqual([ @@ -853,7 +975,7 @@ describe('input actions', () => { it('does not activate on selection and dispatches only an explicit activation request', async () => { const f = fixture() const app = await f.api.getApp('Editor') - expect(f.dispatch.mock.calls.map(([call]) => call.method)).toEqual(['getCapabilities', 'getApp', 'getState']) + expect(f.dispatch.mock.calls.map(([call]) => call.method)).toEqual(['getCapabilities', 'getApp']) await app.activate() expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'activate', params: { appHandle: 'app-17' } }) }) @@ -861,14 +983,16 @@ describe('input actions', () => { it('propagates native failures once and rejects malformed delivery claims', async () => { const f = fixture() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) const failure = new Error('Application was restarted; select it again') f.dispatch.mockRejectedValueOnce(failure) await expect(app.typeText('hello')).rejects.toBe(failure) - expect(f.dispatch).toHaveBeenCalledTimes(5) + expect(f.dispatch).toHaveBeenCalledTimes(6) f.dispatch.mockResolvedValueOnce({ dispatched: 'yes' }) await expect(window.click(element('0'))).rejects.toThrow() - expect(f.dispatch).toHaveBeenCalledTimes(6) + expect(f.dispatch).toHaveBeenCalledTimes(7) }) it('rejects invalid selection inputs before dispatch', async () => { @@ -876,6 +1000,7 @@ describe('input actions', () => { await expect(f.api.getApp('')).rejects.toThrow() expect(f.dispatch).not.toHaveBeenCalled() const app = await f.api.getApp('Editor') + await app.getAccessibilityTree({ emit: false }) const calls = f.dispatch.mock.calls.length await expect(app.getWindow(0)).rejects.toThrow() expect(f.dispatch).toHaveBeenCalledTimes(calls) diff --git a/packages/experimental/cua/tests/bridge.spec.ts b/packages/experimental/cua/tests/bridge.spec.ts index 14a36baaba..7bba3c4e0b 100644 --- a/packages/experimental/cua/tests/bridge.spec.ts +++ b/packages/experimental/cua/tests/bridge.spec.ts @@ -27,6 +27,7 @@ it('uses the current tool binding when a retained app is called by another execu const first = vi.fn(async (operation: CuaOperation): Promise => { if (operation.method === 'getCapabilities') return capabilities if (operation.method === 'getApp') return selected + if (operation.method === 'listWindows') return snapshot.windows if (operation.method === 'getState') return { ...snapshot, windowId: operation.params.windowId ?? null } return snapshot }) @@ -35,6 +36,7 @@ it('uses the current tool binding when a retained app is called by another execu const cua = connectCua(() => current, text) const app = await cua.getApp('Editor') const window = await app.getWindow(23) + await window.getAccessibilityTree({ emit: false }) const second = vi.fn(async (): Promise => ({ dispatched: true })) current = second @@ -69,6 +71,7 @@ it('returns screenshot bytes and metadata with one image-bearing tool call and n const tool = vi.fn(async (operation: CuaOperation): Promise => { if (operation.method === 'getCapabilities') return capabilities if (operation.method === 'getApp') return selected + if (operation.method === 'listWindows') return snapshot.windows if (operation.method === 'getState') return { ...snapshot, windowId: operation.params.windowId ?? null } return { mimeType: 'image/png', data: PNG, pixelWidth: 1, pixelHeight: 1, windowId: 23, bounds, coordinateSpace: 'screenshot-pixels', @@ -80,6 +83,6 @@ it('returns screenshot bytes and metadata with one image-bearing tool call and n text.mockClear() expect(await window.getScreenshot()).toEqual({ bytes: Uint8Array.from(Buffer.from(PNG, 'base64')), mimeType: 'image/png', pixelWidth: 1, pixelHeight: 1, windowId: 23 }) - expect(tool.mock.calls.map(([operation]) => operation.method)).toEqual(['getCapabilities', 'getApp', 'getState', 'getState', 'screenshot']) + expect(tool.mock.calls.map(([operation]) => operation.method)).toEqual(['getCapabilities', 'getApp', 'listWindows', 'screenshot']) expect(text).not.toHaveBeenCalled() }) diff --git a/packages/experimental/cua/tsconfig.host.json b/packages/experimental/cua/tsconfig.host.json index 2386f83640..4bf0b7ddda 100644 --- a/packages/experimental/cua/tsconfig.host.json +++ b/packages/experimental/cua/tsconfig.host.json @@ -74,6 +74,9 @@ }, { "path": "../../boot/config-editor" + }, + { + "path": "../../util/error" } ], "exclude": [ diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d016fe8deb..83d9bd763d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -9800,6 +9800,9 @@ importers: '@deepseek-ai/dsh-computer-use': specifier: workspace:* version: link:../../computer-use/computer-use + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-storage-domain': specifier: workspace:* version: link:../../storage/storage-domain diff --git a/snapshots/session/cua-native/system-prompt.expected.md b/snapshots/session/cua-native/system-prompt.expected.md index 0b9c1b29f6..04fb520f49 100644 --- a/snapshots/session/cua-native/system-prompt.expected.md +++ b/snapshots/session/cua-native/system-prompt.expected.md @@ -46,9 +46,9 @@ Setup and discovery: - cua.listApps(options?: { emit?: boolean }) -> { id: string, displayName: string, isRunning: true, pid: number }[] — enumerate running applications. - cua.findApps(query: string, options?: { emit?: boolean }) -> ({ id: string, displayName: string, path: string } & ({ isRunning: true, pid: number } | { isRunning: false }))[] — search installed applications, including stopped matches; only running matches carry pid. - cua.getState(options?: { emit?: boolean }) -> { apps: { id: string, displayName: string, isRunning: true, pid: number }[], browsers: [] } — summarize running applications; this is not an accessibility observation. -- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and read initial AX state silently; it does not activate the app. +- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and return without reading AX or activating the app. - app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership. -- app.getWindow(windowId: number) -> Window — select one window and read its initial AX state silently; do this before any window screenshot or coordinate input. +- app.getWindow(windowId: number) -> Window — select a window from the application’s current window list without reading AX; do this before any window screenshot or coordinate input. - app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required. - app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation. - window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation. @@ -56,7 +56,7 @@ Setup and discovery: ## Accessibility tree Available at app or window level depending on the platform. -Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. +Read getAccessibilityTree explicitly before using element ids. Selection and screenshots do not read or replace the current AX snapshot. Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. - getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the full tree text; includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. - listActions(elementId: string) -> string[] — list the actions an element advertises. - invoke(elementId: string) -> ActionResult — invoke the element's default action; dispatched is false when it has none. @@ -80,6 +80,6 @@ Available at app or window level depending on the platform. - 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?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. +Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree maps to getState; getWindow validates against listWindows; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. Maximum click holdMs: 5000 ms. diff --git a/snapshots/session/cua-native/workspace/native-helper.mjs b/snapshots/session/cua-native/workspace/native-helper.mjs index 1e148d7ab5..c39f62f769 100755 --- a/snapshots/session/cua-native/workspace/native-helper.mjs +++ b/snapshots/session/cua-native/workspace/native-helper.mjs @@ -162,6 +162,7 @@ function createApplicationState(socket, record, application, captureBroker, conn if (method === 'listWindows') return [window, axlessWindow] if (method === 'getState') { snapshots.delete(params.windowId ?? null) + if (existsSync(new URL('./fixture-ax-failure', import.meta.url))) refuse('NATIVE_ERROR', 'Fixture accessibility read failed') if (observationChanged) { observationChanged = false refuse('STALE_SNAPSHOT', 'Accessibility tree changed during observation; read fresh getAccessibilityTree') diff --git a/snapshots/session/cua-ptc/consent-fixture.mjs b/snapshots/session/cua-ptc/consent-fixture.mjs index 85e83bcf69..6fdbdbbfc2 100644 --- a/snapshots/session/cua-ptc/consent-fixture.mjs +++ b/snapshots/session/cua-ptc/consent-fixture.mjs @@ -1,5 +1,5 @@ /** Own a private native substitute for the PTC result replay. */ -import { chmod, copyFile, unlink } from 'node:fs/promises' +import { chmod, copyFile, unlink, writeFile } from 'node:fs/promises' import { join } from 'node:path' import { startFixtureHost } from '../cua-native/fixture-host.mjs' export const name = 'cua-ptc-fixture' @@ -7,6 +7,10 @@ export const inject = ['userQuestions'] /** Prepare the helper and retire its service before removing the private executable. */ export async function apply(ctx) { + const bridge = join(process.cwd(), 'cua-bridge.mjs') + const face = process.env.DSH_EXAMPLE_MODE === 'src' ? 'src/bridge.ts' : 'lib/bridge.js' + await writeFile(bridge, `export { connectCua } from ${JSON.stringify(new URL('../../../packages/experimental/cua/' + face, import.meta.url).href)}\n`) + ctx.effect(() => () => unlink(bridge)) const helper = join(process.cwd(), 'native-helper.mjs') await copyFile(new URL('../cua-native/workspace/native-helper.mjs', import.meta.url), helper) await chmod(helper, 0o700) diff --git a/snapshots/session/cua-ptc/replay.override.json b/snapshots/session/cua-ptc/replay.override.json index 63e4009990..5ea62fee03 100644 --- a/snapshots/session/cua-ptc/replay.override.json +++ b/snapshots/session/cua-ptc/replay.override.json @@ -32,6 +32,39 @@ } ] }, + { + "kind": "chunks", + "chunks": [ + { + "type": "block-start", + "index": 0, + "blockType": "tool-call" + }, + { + "type": "block-end", + "index": 0, + "block": { + "type": "tool-call", + "id": "cua-ptc-ax-failure", + "name": "run_code", + "arguments": "{\"code\":\"const { writeFile, unlink } = await import('node:fs/promises');\\nconst { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nawait writeFile('fixture-ax-failure', '');\\ntry {\\n const cua = connectCua(() => tools.cua);\\n const app = await cua.getApp('test.fixture');\\n const windows = await app.getWindows({ emit: false });\\n const window = await app.getWindow(windows[0].windowId);\\n const failures = [];\\n for (const surface of [app, window]) {\\n try { await surface.getAccessibilityTree(); throw new Error('Expected AX failure'); }\\n catch (error) { if (!error.message.includes('Fixture accessibility read failed')) throw error; failures.push(error.message); }\\n }\\n const shot = await window.getScreenshot();\\n let elementRefused = false;\\n try { await window.invoke('0'); }\\n catch (error) { if (!error.message.includes('Read getAccessibilityTree')) throw error; elementRefused = true; }\\n if (!elementRefused) throw new Error('Element input accepted without an AX snapshot');\\n return { axFailures: failures.length, screenshotWindow: shot.windowId, pngBytes: shot.bytes.length, elementRefused };\\n} finally { await unlink('fixture-ax-failure'); }\",\"description\":\"Capture through the object API despite application and window AX failures\"}" + } + }, + { + "type": "usage", + "usage": { + "inputTokens": 3, + "outputTokens": 3 + } + }, + { + "type": "finish", + "reason": { + "kind": "tool-calls" + } + } + ] + }, { "kind": "chunks", "chunks": [ @@ -45,7 +78,7 @@ "index": 0, "block": { "type": "text", - "text": "Received native CUA values and one PNG screenshot through PTC. The PNG is 90 bytes with signature 89504e470d0a1a0a." + "text": "Received native CUA values and PNG screenshots through PTC. The object API captured a 90-byte PNG after two AX read failures and refused element input without an accessibility snapshot." } }, { diff --git a/snapshots/session/cua-ptc/session.v4.jsonl b/snapshots/session/cua-ptc/session.v4.jsonl index 87791413b2..f9d25d914b 100644 --- a/snapshots/session/cua-ptc/session.v4.jsonl +++ b/snapshots/session/cua-ptc/session.v4.jsonl @@ -12,7 +12,7 @@ {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"}} {"type":"session/title","data":{"title":"Use tools.cua from Node PTC","messageSeqs":[8],"source":{"kind":"fallback"}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-ptc-native-result","name":"run_code","arguments":"{\"code\":\"const { Buffer } = await import('node:buffer');\\nconst app = await tools.cua({ method: 'getApp', params: { selector: 'test.fixture' } });\\nconst state = await tools.cua({ method: 'getState', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst shot = await tools.cua({ method: 'screenshot', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst bytes = Buffer.from(shot.data, 'base64');\\nreturn { appHandle: app.appHandle, hasIncrement: state.tree.includes('Increment'), pngBytes: bytes.length, signature: bytes.subarray(0, 8).toString('hex'), imageWidth: shot.attachment.width, imageHeight: shot.attachment.height };\",\"description\":\"Read native CUA values and receive one screenshot\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791864698727,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791864698727,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-ptc-native-result","name":"run_code","arguments":"{\"code\":\"const { Buffer } = await import('node:buffer');\\nconst app = await tools.cua({ method: 'getApp', params: { selector: 'test.fixture' } });\\nconst state = await tools.cua({ method: 'getState', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst shot = await tools.cua({ method: 'screenshot', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst bytes = Buffer.from(shot.data, 'base64');\\nreturn { appHandle: app.appHandle, hasIncrement: state.tree.includes('Increment'), pngBytes: bytes.length, signature: bytes.subarray(0, 8).toString('hex'), imageWidth: shot.attachment.width, imageHeight: shot.attachment.height };\",\"description\":\"Read native CUA values and receive one screenshot\"}"}}},{"type":"chunk","time":1791864698727,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791864698727,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-ptc-native-result","name":"run_code","arguments":"{\"code\":\"const { Buffer } = await import('node:buffer');\\nconst app = await tools.cua({ method: 'getApp', params: { selector: 'test.fixture' } });\\nconst state = await tools.cua({ method: 'getState', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst shot = await tools.cua({ method: 'screenshot', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst bytes = Buffer.from(shot.data, 'base64');\\nreturn { appHandle: app.appHandle, hasIncrement: state.tree.includes('Increment'), pngBytes: bytes.length, signature: bytes.subarray(0, 8).toString('hex'), imageWidth: shot.attachment.width, imageHeight: shot.attachment.height };\",\"description\":\"Read native CUA values and receive one screenshot\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794024973829,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794024973829,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-ptc-native-result","name":"run_code","arguments":"{\"code\":\"const { Buffer } = await import('node:buffer');\\nconst app = await tools.cua({ method: 'getApp', params: { selector: 'test.fixture' } });\\nconst state = await tools.cua({ method: 'getState', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst shot = await tools.cua({ method: 'screenshot', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst bytes = Buffer.from(shot.data, 'base64');\\nreturn { appHandle: app.appHandle, hasIncrement: state.tree.includes('Increment'), pngBytes: bytes.length, signature: bytes.subarray(0, 8).toString('hex'), imageWidth: shot.attachment.width, imageHeight: shot.attachment.height };\",\"description\":\"Read native CUA values and receive one screenshot\"}"}}},{"type":"chunk","time":1794024973829,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794024973829,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua-ptc-native-result","name":"run_code","arguments":"{\"code\":\"const { Buffer } = await import('node:buffer');\\nconst app = await tools.cua({ method: 'getApp', params: { selector: 'test.fixture' } });\\nconst state = await tools.cua({ method: 'getState', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst shot = await tools.cua({ method: 'screenshot', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst bytes = Buffer.from(shot.data, 'base64');\\nreturn { appHandle: app.appHandle, hasIncrement: state.tree.includes('Increment'), pngBytes: bytes.length, signature: bytes.subarray(0, 8).toString('hex'), imageWidth: shot.attachment.width, imageHeight: shot.attachment.height };\",\"description\":\"Read native CUA values and receive one screenshot\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-native-result","parentCallId":"cua-ptc-native-result","subCallId":"cua-ptc-native-result:ptc:1","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-native-result","parentCallId":"cua-ptc-native-result","subCallId":"cua-ptc-native-result:ptc:1","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"name\":\"Fixture\",\"bundleId\":\"test.fixture\",\"running\":true}"}]}} @@ -26,6 +26,28 @@ {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":1,"step":2}} {"type":"user/message","data":{"content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"source":{"kind":"ptc-mode"},"role":"user","id":"{{message:6}}"},"surfaceOp":"append"} -{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"text","text":"Received native CUA values and one PNG screenshot through PTC. The PNG is 90 bytes with signature 89504e470d0a1a0a."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:7}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791864699463,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1791864699463,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Received native CUA values and one PNG screenshot through PTC. The PNG is 90 bytes with signature 89504e470d0a1a0a."}}},{"type":"chunk","time":1791864699463,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791864699463,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-ptc-ax-failure","name":"run_code","arguments":"{\"code\":\"const { writeFile, unlink } = await import('node:fs/promises');\\nconst { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nawait writeFile('fixture-ax-failure', '');\\ntry {\\n const cua = connectCua(() => tools.cua);\\n const app = await cua.getApp('test.fixture');\\n const windows = await app.getWindows({ emit: false });\\n const window = await app.getWindow(windows[0].windowId);\\n const failures = [];\\n for (const surface of [app, window]) {\\n try { await surface.getAccessibilityTree(); throw new Error('Expected AX failure'); }\\n catch (error) { if (!error.message.includes('Fixture accessibility read failed')) throw error; failures.push(error.message); }\\n }\\n const shot = await window.getScreenshot();\\n let elementRefused = false;\\n try { await window.invoke('0'); }\\n catch (error) { if (!error.message.includes('Read getAccessibilityTree')) throw error; elementRefused = true; }\\n if (!elementRefused) throw new Error('Element input accepted without an AX snapshot');\\n return { axFailures: failures.length, screenshotWindow: shot.windowId, pngBytes: shot.bytes.length, elementRefused };\\n} finally { await unlink('fixture-ax-failure'); }\",\"description\":\"Capture through the object API despite application and window AX failures\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:7}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794024974646,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794024974646,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-ptc-ax-failure","name":"run_code","arguments":"{\"code\":\"const { writeFile, unlink } = await import('node:fs/promises');\\nconst { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nawait writeFile('fixture-ax-failure', '');\\ntry {\\n const cua = connectCua(() => tools.cua);\\n const app = await cua.getApp('test.fixture');\\n const windows = await app.getWindows({ emit: false });\\n const window = await app.getWindow(windows[0].windowId);\\n const failures = [];\\n for (const surface of [app, window]) {\\n try { await surface.getAccessibilityTree(); throw new Error('Expected AX failure'); }\\n catch (error) { if (!error.message.includes('Fixture accessibility read failed')) throw error; failures.push(error.message); }\\n }\\n const shot = await window.getScreenshot();\\n let elementRefused = false;\\n try { await window.invoke('0'); }\\n catch (error) { if (!error.message.includes('Read getAccessibilityTree')) throw error; elementRefused = true; }\\n if (!elementRefused) throw new Error('Element input accepted without an AX snapshot');\\n return { axFailures: failures.length, screenshotWindow: shot.windowId, pngBytes: shot.bytes.length, elementRefused };\\n} finally { await unlink('fixture-ax-failure'); }\",\"description\":\"Capture through the object API despite application and window AX failures\"}"}}},{"type":"chunk","time":1794024974646,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794024974646,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":2,"callId":"cua-ptc-ax-failure","name":"run_code","arguments":"{\"code\":\"const { writeFile, unlink } = await import('node:fs/promises');\\nconst { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nawait writeFile('fixture-ax-failure', '');\\ntry {\\n const cua = connectCua(() => tools.cua);\\n const app = await cua.getApp('test.fixture');\\n const windows = await app.getWindows({ emit: false });\\n const window = await app.getWindow(windows[0].windowId);\\n const failures = [];\\n for (const surface of [app, window]) {\\n try { await surface.getAccessibilityTree(); throw new Error('Expected AX failure'); }\\n catch (error) { if (!error.message.includes('Fixture accessibility read failed')) throw error; failures.push(error.message); }\\n }\\n const shot = await window.getScreenshot();\\n let elementRefused = false;\\n try { await window.invoke('0'); }\\n catch (error) { if (!error.message.includes('Read getAccessibilityTree')) throw error; elementRefused = true; }\\n if (!elementRefused) throw new Error('Element input accepted without an AX snapshot');\\n return { axFailures: failures.length, screenshotWindow: shot.windowId, pngBytes: shot.bytes.length, elementRefused };\\n} finally { await unlink('fixture-ax-failure'); }\",\"description\":\"Capture through the object API despite application and window AX failures\"}"}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"methods\":[\"activate\",\"click\",\"drag\",\"findApps\",\"getApp\",\"getCapabilities\",\"getState\",\"invoke\",\"listActions\",\"listApps\",\"listWindows\",\"mouseMove\",\"paste\",\"performAction\",\"pressKey\",\"screenshot\",\"scroll\",\"selectText\",\"setValue\",\"show\",\"typeText\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"name\":\"Fixture\",\"bundleId\":\"test.fixture\",\"running\":true}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:3","name":"cua","arguments":{"method":"listWindows","params":{"appHandle":"fixture-app"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:3","name":"cua","arguments":{"method":"listWindows","params":{"appHandle":"fixture-app"}},"isError":false,"content":[{"type":"text","text":"[{\"windowId\":7,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}]"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:4","name":"cua","arguments":{"method":"listWindows","params":{"appHandle":"fixture-app"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:4","name":"cua","arguments":{"method":"listWindows","params":{"appHandle":"fixture-app"}},"isError":false,"content":[{"type":"text","text":"[{\"windowId\":7,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}]"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:5","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:5","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app"}},"isError":true,"content":[{"type":"text","text":"Error: NATIVE_ERROR: Fixture accessibility read failed"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:6","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":7}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:6","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":7}},"isError":true,"content":[{"type":"text","text":"Error: NATIVE_ERROR: Fixture accessibility read failed"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:7","name":"cua","arguments":{"method":"screenshot","params":{"appHandle":"fixture-app","windowId":7}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:7","name":"cua","arguments":{"method":"screenshot","params":{"appHandle":"fixture-app","windowId":7}},"isError":false,"content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}]}} +{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-ptc-ax-failure"},"toolCallId":"cua-ptc-ax-failure","content":[{"type":"text","text":"{\n \"axFailures\": 2,\n \"screenshotWindow\": 7,\n \"pngBytes\": 90,\n \"elementRefused\": true\n}"}],"isError":false,"id":"{{message:8}}"}},"sourceEventSeqs":[28],"surfaceOp":"append"} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"source":{"kind":"ptc-mode"},"role":"user","id":"{{message:9}}"}]}} {"type":"step/end","data":{"turn":1,"step":2}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} +{"type":"step/start","data":{"turn":1,"step":3}} +{"type":"user/message","data":{"content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"source":{"kind":"ptc-mode"},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"text","text":"Received native CUA values and PNG screenshots through PTC. The object API captured a 90-byte PNG after two AX read failures and refused element input without an accessibility snapshot."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:10}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794024974851,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1794024974851,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Received native CUA values and PNG screenshots through PTC. The object API captured a 90-byte PNG after two AX read failures and refused element input without an accessibility snapshot."}}},{"type":"chunk","time":1794024974851,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794024974851,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":3}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index 587436227a..be8ab5aed8 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -48,9 +48,9 @@ Setup and discovery: - cua.listApps(options?: { emit?: boolean }) -> { id: string, displayName: string, isRunning: true, pid: number }[] — enumerate running applications. - cua.findApps(query: string, options?: { emit?: boolean }) -> ({ id: string, displayName: string, path: string } & ({ isRunning: true, pid: number } | { isRunning: false }))[] — search installed applications, including stopped matches; only running matches carry pid. - cua.getState(options?: { emit?: boolean }) -> { apps: { id: string, displayName: string, isRunning: true, pid: number }[], browsers: [] } — summarize running applications; this is not an accessibility observation. -- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and read initial AX state silently; it does not activate the app. +- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and return without reading AX or activating the app. - app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership. -- app.getWindow(windowId: number) -> Window — select one window and read its initial AX state silently; do this before any window screenshot or coordinate input. +- app.getWindow(windowId: number) -> Window — select a window from the application’s current window list without reading AX; do this before any window screenshot or coordinate input. - app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required. - app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation. - window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation. @@ -58,7 +58,7 @@ Setup and discovery: ## Accessibility tree Available at app or window level depending on the platform. -Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. +Read getAccessibilityTree explicitly before using element ids. Selection and screenshots do not read or replace the current AX snapshot. Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. - getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the full tree text; includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. - listActions(elementId: string) -> string[] — list the actions an element advertises. - invoke(elementId: string) -> ActionResult — invoke the element's default action; dispatched is false when it has none. @@ -82,7 +82,7 @@ Available at app or window level depending on the platform. - 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?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. +Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree maps to getState; getWindow validates against listWindows; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. Maximum click holdMs: 5000 ms. diff --git a/snapshots/session/ptc-script-retained/system-prompt.expected.md b/snapshots/session/ptc-script-retained/system-prompt.expected.md index dd88fa8d9e..63e91315c0 100644 --- a/snapshots/session/ptc-script-retained/system-prompt.expected.md +++ b/snapshots/session/ptc-script-retained/system-prompt.expected.md @@ -48,9 +48,9 @@ Setup and discovery: - cua.listApps(options?: { emit?: boolean }) -> { id: string, displayName: string, isRunning: true, pid: number }[] — enumerate running applications. - cua.findApps(query: string, options?: { emit?: boolean }) -> ({ id: string, displayName: string, path: string } & ({ isRunning: true, pid: number } | { isRunning: false }))[] — search installed applications, including stopped matches; only running matches carry pid. - cua.getState(options?: { emit?: boolean }) -> { apps: { id: string, displayName: string, isRunning: true, pid: number }[], browsers: [] } — summarize running applications; this is not an accessibility observation. -- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and read initial AX state silently; it does not activate the app. +- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and return without reading AX or activating the app. - app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership. -- app.getWindow(windowId: number) -> Window — select one window and read its initial AX state silently; do this before any window screenshot or coordinate input. +- app.getWindow(windowId: number) -> Window — select a window from the application’s current window list without reading AX; do this before any window screenshot or coordinate input. - app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required. - app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation. - window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation. @@ -58,7 +58,7 @@ Setup and discovery: ## Accessibility tree Available at app or window level depending on the platform. -Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. +Read getAccessibilityTree explicitly before using element ids. Selection and screenshots do not read or replace the current AX snapshot. Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. - getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the full tree text; includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. - listActions(elementId: string) -> string[] — list the actions an element advertises. - invoke(elementId: string) -> ActionResult — invoke the element's default action; dispatched is false when it has none. @@ -82,7 +82,7 @@ Available at app or window level depending on the platform. - 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?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. +Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree maps to getState; getWindow validates against listWindows; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. Maximum click holdMs: 5000 ms. From f2dc7347adbcb37322265e727ce09b134018b3fd Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Sat, 7 Nov 2026 12:29:31 +0800 Subject: [PATCH 013/184] fix(cua): share HarnessError through a peer dependency --- packages/experimental/cua/package.json | 9 +++++---- pnpm-lock.yaml | 6 +++--- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/packages/experimental/cua/package.json b/packages/experimental/cua/package.json index 0d62908a8a..410dd23cf7 100644 --- a/packages/experimental/cua/package.json +++ b/packages/experimental/cua/package.json @@ -99,7 +99,8 @@ "@deepseek-ai/dsh-user-questions": "workspace:*", "@deepseek-ai/dsh-attachment": "workspace:*", "@deepseek-ai/dsh-scope": "workspace:*", - "@deepseek-ai/dsh-ptc-runtime-node": "workspace:*" + "@deepseek-ai/dsh-ptc-runtime-node": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" }, "dependencies": { "@deepseek-ai/schemastery": "workspace:~", @@ -107,8 +108,7 @@ "@deepseek-ai/dsh-atomic-write": "workspace:*", "@deepseek-ai/dsh-typert-protocol": "workspace:*", "@deepseek-ai/dsh-computer-use": "workspace:*", - "@deepseek-ai/dsh-storage-domain": "workspace:*", - "@deepseek-ai/dsh-error": "workspace:*" + "@deepseek-ai/dsh-storage-domain": "workspace:*" }, "devDependencies": { "@deepseek-ai/dsh-working-directory": "workspace:*", @@ -162,7 +162,8 @@ "@deepseek-ai/dsh-storage-json": "workspace:*", "@deepseek-ai/dsh-client-ui-user-questions": "workspace:*", "@deepseek-ai/dsh-client-ui-approval": "workspace:*", - "@deepseek-ai/dsh-client-ui-conversation": "workspace:*" + "@deepseek-ai/dsh-client-ui-conversation": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" }, "dsh": { "client": { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 83d9bd763d..f33fef7d42 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -9800,9 +9800,6 @@ importers: '@deepseek-ai/dsh-computer-use': specifier: workspace:* version: link:../../computer-use/computer-use - '@deepseek-ai/dsh-error': - specifier: workspace:* - version: link:../../util/error '@deepseek-ai/dsh-storage-domain': specifier: workspace:* version: link:../../storage/storage-domain @@ -9897,6 +9894,9 @@ importers: '@deepseek-ai/dsh-config-editor': specifier: workspace:* version: link:../../boot/config-editor + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-fs-local': specifier: workspace:* version: link:../../fs/fs-local From 67561b163eebf322d39f6f87c27eac93b4ebaf39 Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Sat, 7 Nov 2026 12:35:17 +0800 Subject: [PATCH 014/184] docs(cua): regenerate shared dependency graph --- docs/module-graph.md | 3 ++- docs/module-graph.zh.md | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/module-graph.md b/docs/module-graph.md index a3a28f92fc..cc0d1e4f2c 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -952,6 +952,7 @@ flowchart TD pkg_creation_recommendations --> pkg_skill pkg_creation_recommendations --> pkg_tools pkg_cua --> pkg_attachment + pkg_cua --> pkg_error pkg_cua --> pkg_ptc_runtime_node pkg_cua --> pkg_scope pkg_cua --> pkg_user_questions @@ -1821,7 +1822,7 @@ flowchart TD | [`workspace-changes`](../packages/deliverables/workspace-changes) | `deliverables` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools) | | [`action-cards`](../packages/experimental/action-cards) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) | | [`creation-recommendations`](../packages/experimental/creation-recommendations) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`skill`](../packages/skill/skill), [`tools`](../packages/core/tools) | -| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`user-questions`](../packages/interaction/user-questions) | +| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`user-questions`](../packages/interaction/user-questions) | | [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index 9e337229b4..c9cf1d8d93 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -954,6 +954,7 @@ flowchart TD pkg_creation_recommendations --> pkg_skill pkg_creation_recommendations --> pkg_tools pkg_cua --> pkg_attachment + pkg_cua --> pkg_error pkg_cua --> pkg_ptc_runtime_node pkg_cua --> pkg_scope pkg_cua --> pkg_user_questions @@ -1823,7 +1824,7 @@ flowchart TD | [`workspace-changes`](../packages/deliverables/workspace-changes) | `deliverables` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools) | | [`action-cards`](../packages/experimental/action-cards) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) | | [`creation-recommendations`](../packages/experimental/creation-recommendations) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`skill`](../packages/skill/skill), [`tools`](../packages/core/tools) | -| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`user-questions`](../packages/interaction/user-questions) | +| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`user-questions`](../packages/interaction/user-questions) | | [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | From 6229d26d770f6ef69fddef487a6f2823c53cdc02 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Sat, 7 Nov 2026 13:17:06 +0800 Subject: [PATCH 015/184] Commit missed pnpm lock --- pnpm-lock.yaml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f910604ac9..11fbc7039f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -9870,6 +9870,9 @@ importers: '@deepseek-ai/dsh-config-editor': specifier: workspace:* version: link:../../boot/config-editor + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-fs-local': specifier: workspace:* version: link:../../fs/fs-local @@ -10114,7 +10117,7 @@ importers: specifier: link:../../../vendor/schemastery version: link:../../../vendor/schemastery zod: - specifier: ^4.4.3 + specifier: 4.6.6 version: 4.6.6 devDependencies: '@deepseek-ai/cordis': From facebeb270d44d5d20143e850c7605b09b23ab29 Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Sat, 7 Nov 2026 14:12:45 +0800 Subject: [PATCH 016/184] fix(cua): let native window operations own window validation getWindow now creates the window object without a listWindows request. Screenshots and pointer input already reject closed and foreign windows natively, so the facade keeps only local windowId validation and drops the dsh-error dependency and CUA_WINDOW_UNAVAILABLE code. --- ...05-cua-scoped-surfaces-and-input.i18n.yaml | 4 +-- ...026-11-05-cua-scoped-surfaces-and-input.md | 2 +- ...-11-05-cua-scoped-surfaces-and-input.zh.md | 2 +- docs/module-graph.md | 3 +-- docs/module-graph.zh.md | 3 +-- .../experimental/cua-macos/README.i18n.yaml | 4 +-- packages/experimental/cua-macos/README.md | 6 ++--- packages/experimental/cua-macos/README.zh.md | 6 ++--- packages/experimental/cua/README.i18n.yaml | 4 +-- packages/experimental/cua/README.md | 2 +- packages/experimental/cua/README.zh.md | 2 +- packages/experimental/cua/package.json | 6 ++--- packages/experimental/cua/src/api.ts | 14 ++++------ packages/experimental/cua/src/guidance.ts | 4 +-- packages/experimental/cua/src/types.ts | 3 ++- packages/experimental/cua/tests/api.spec.ts | 27 +++++++++---------- .../experimental/cua/tests/bridge.spec.ts | 6 ++--- packages/experimental/cua/tsconfig.host.json | 3 --- pnpm-lock.yaml | 3 --- .../cua-native/system-prompt.expected.md | 4 +-- snapshots/session/cua-ptc/session.v4.jsonl | 20 +++++++------- .../session/cua-ptc/system-prompt.expected.md | 4 +-- .../system-prompt.expected.md | 4 +-- 23 files changed, 58 insertions(+), 78 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml index 5f1ff64a4d..53d7ee394c 100644 --- a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml @@ -9,8 +9,8 @@ en: f72db0b79aa02fb5 zh: b91c1f177dc93ab4 /agent-note-cua-scoped-surfaces-and-separated-input-capabilities/decision: - en: 4fa61247fe33edb0 - zh: afa76f74841eb586 + en: 41fd533d5be7642b + zh: c6fcbabec22bdbb7 /agent-note-cua-scoped-surfaces-and-separated-input-capabilities/alternatives-considered: en: 32c970ae153e0f6c zh: 8431be0a10ffed15 diff --git a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md index 3888527013..23780d7e88 100644 --- a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md +++ b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md @@ -16,7 +16,7 @@ Provider startup capabilities are static. Platform, supported methods, applicati Keyboard input keeps keys and modifiers separate: `pressKey(key, modifiers?)` presses and releases one key while holding the listed modifiers, and its keyboard modifier list is a plain string array defined by the provider. `sendKeyEvent(key, direction)` sends exactly one key-down or key-up without an implicit counterpart. A caller can therefore hold a modifier or split a gesture; neither method packs a chord string, and the shared schema does not enumerate platform key names. -Within one API instance, the object facade keeps one current accessibility snapshot per application handle, shared by every application and window object for that handle, including repeated selections of the same application. `getApp` and `getWindow` select objects without reading accessibility or replacing that snapshot; `getWindow` validates membership in the application’s current window list. An explicit `getAccessibilityTree` read invalidates the previous snapshot before dispatch. The facade automatically attaches the latest snapshot ID to element operations; callers use element IDs from the latest tree and do not assume an older ID still identifies the same control. Element IDs are opaque provider strings. Only an explicit `CuaWindow` captures screenshots or sends pointer input. The native helper retains its own application and optional-window snapshots behind that facade; the native layer and the facade snapshot remain separate. The external runtime continues to own variable persistence and completion serialization; the facade adds no evaluator. The [native object decision](2026-09-17-experimental-cua-object-api.md) owns evaluator independence, and the [shared helper decision](2026-10-09-cua-shared-native-helper.md) owns connection lifetime. +Within one API instance, the object facade keeps one current accessibility snapshot per application handle, shared by every application and window object for that handle, including repeated selections of the same application. `getApp` and `getWindow` select objects without reading accessibility or replacing that snapshot; native window operations reject closed or foreign windows. An explicit `getAccessibilityTree` read invalidates the previous snapshot before dispatch. The facade automatically attaches the latest snapshot ID to element operations; callers use element IDs from the latest tree and do not assume an older ID still identifies the same control. Element IDs are opaque provider strings. Only an explicit `CuaWindow` captures screenshots or sends pointer input. The native helper retains its own application and optional-window snapshots behind that facade; the native layer and the facade snapshot remain separate. The external runtime continues to own variable persistence and completion serialization; the facade adds no evaluator. The [native object decision](2026-09-17-experimental-cua-object-api.md) owns evaluator independence, and the [shared helper decision](2026-10-09-cua-shared-native-helper.md) owns connection lifetime. ## Alternatives considered diff --git a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md index 8a3f152e67..f65ec242cb 100644 --- a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md @@ -16,7 +16,7 @@ Provider 的启动能力是静态的。平台、支持的方法、应用级辅 键盘输入把按键与修饰键分开:`pressKey(key, modifiers?)` 在按住所列修饰键时按下并释放一个键,其键盘修饰键列表是 provider 定义的普通字符串数组。`sendKeyEvent(key, direction)` 只发送一次按下或抬起,不隐式发送相反事件。因此调用方可以保持修饰键或拆分手势;两个方法都不接受组合键字符串,共享 schema 也不枚举平台按键名。 -在单个 API 实例内,对象门面按应用句柄保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享这份快照,包括对同一应用的重复选择。`getApp` 和 `getWindow` 只选择对象,不读取辅助功能或替换该快照;`getWindow` 会核验窗口属于应用的当前窗口列表。显式 `getAccessibilityTree` 读取会在分派前使上一份快照失效。门面会为元素操作自动附加最新快照 ID;调用方应使用最新树中的元素 ID,不应假定旧 ID 仍指向同一控件。元素 ID 是 provider 定义的不透明字符串。只有显式 `CuaWindow` 可以截图或发送指针输入。原生 helper 在该门面之后保留自己的应用快照和可选窗口快照;原生层与门面快照相互独立。外部运行时继续负责变量持久化和最终表达式序列化;门面不加入 evaluator。[原生对象决定](2026-09-17-experimental-cua-object-api.zh.md)负责 evaluator 独立性,[共享 helper 决定](2026-10-09-cua-shared-native-helper.zh.md)负责连接生命期。 +在单个 API 实例内,对象门面按应用句柄保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享这份快照,包括对同一应用的重复选择。`getApp` 和 `getWindow` 只选择对象,不读取辅助功能或替换该快照;原生窗口操作会拒绝已关闭或属于其他应用的窗口。显式 `getAccessibilityTree` 读取会在分派前使上一份快照失效。门面会为元素操作自动附加最新快照 ID;调用方应使用最新树中的元素 ID,不应假定旧 ID 仍指向同一控件。元素 ID 是 provider 定义的不透明字符串。只有显式 `CuaWindow` 可以截图或发送指针输入。原生 helper 在该门面之后保留自己的应用快照和可选窗口快照;原生层与门面快照相互独立。外部运行时继续负责变量持久化和最终表达式序列化;门面不加入 evaluator。[原生对象决定](2026-09-17-experimental-cua-object-api.zh.md)负责 evaluator 独立性,[共享 helper 决定](2026-10-09-cua-shared-native-helper.zh.md)负责连接生命期。 ## 考虑过的替代方案 diff --git a/docs/module-graph.md b/docs/module-graph.md index cc0d1e4f2c..a3a28f92fc 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -952,7 +952,6 @@ flowchart TD pkg_creation_recommendations --> pkg_skill pkg_creation_recommendations --> pkg_tools pkg_cua --> pkg_attachment - pkg_cua --> pkg_error pkg_cua --> pkg_ptc_runtime_node pkg_cua --> pkg_scope pkg_cua --> pkg_user_questions @@ -1822,7 +1821,7 @@ flowchart TD | [`workspace-changes`](../packages/deliverables/workspace-changes) | `deliverables` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools) | | [`action-cards`](../packages/experimental/action-cards) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) | | [`creation-recommendations`](../packages/experimental/creation-recommendations) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`skill`](../packages/skill/skill), [`tools`](../packages/core/tools) | -| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`user-questions`](../packages/interaction/user-questions) | +| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`user-questions`](../packages/interaction/user-questions) | | [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index c9cf1d8d93..9e337229b4 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -954,7 +954,6 @@ flowchart TD pkg_creation_recommendations --> pkg_skill pkg_creation_recommendations --> pkg_tools pkg_cua --> pkg_attachment - pkg_cua --> pkg_error pkg_cua --> pkg_ptc_runtime_node pkg_cua --> pkg_scope pkg_cua --> pkg_user_questions @@ -1824,7 +1823,7 @@ flowchart TD | [`workspace-changes`](../packages/deliverables/workspace-changes) | `deliverables` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools) | | [`action-cards`](../packages/experimental/action-cards) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) | | [`creation-recommendations`](../packages/experimental/creation-recommendations) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`skill`](../packages/skill/skill), [`tools`](../packages/core/tools) | -| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`user-questions`](../packages/interaction/user-questions) | +| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`user-questions`](../packages/interaction/user-questions) | | [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index 7571c8004d..6ddbd9a57f 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -18,8 +18,8 @@ en: e9c78a8cbd68147c zh: 98c64b09f858edf7 /deepseek-ai-dsh-experimental-cua-macos/use-this-package/connect-an-external-execution-environment: - en: 7c460511bb1cee4c - zh: 2eba4fc997427e18 + en: 3cd638c0c59fd9cc + zh: 594bacf314d4cd08 /deepseek-ai-dsh-experimental-cua-macos/understand-the-implementation: en: 4e82b85a5aa72eee zh: 4e004b7a205d8688 diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index d139d988a3..2e57fbaf13 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -113,7 +113,7 @@ void await window.getScreenshot() Use the `cua` API to discover and select the application (`listApps`, `getState`, `findApps`, `getApp`); use the selected app to activate it, enumerate its windows, and select one. Window selection is required for screenshots and pointer input, not only when several windows exist. `getApp` and `app.getWindow(windowId)` return without reading AX; choose the window from `getWindows()` by its title and bounds. -`getWindow` validates the ID against the current application window list. Read `getAccessibilityTree()` explicitly before element operations. Screenshots and coordinate input do not require a successful AX read; absolute pixel coordinates require a delivered screenshot. An owned window without an AX surface returns an empty snapshot when explicitly observed. 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. A failed read publishes no partial snapshot; read again without repeating the preceding input. Window objects own screenshots and pointer input. Keyboard methods stay on `app` because input follows the app’s current focus. +`getWindow` sends no native request; screenshots and pointer input reject a closed or foreign window. Read `getAccessibilityTree()` explicitly before element operations. Screenshots and coordinate input do not require a successful AX read; absolute pixel coordinates require a delivered screenshot. An owned window without an AX surface returns an empty snapshot when explicitly observed. 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. A failed read publishes no partial snapshot; read again without repeating the preceding input. Window objects own screenshots and pointer input. Keyboard methods stay on `app` because input follows the app’s current focus. `mouseMove(target)` defaults to AX hover. An enabled target or ancestor must advertise both `AXShowAlternateUI` and `AXShowDefaultUI`. Moving into its descendants keeps the UI open, and leaving restores it. Without an AX route the helper returns `HOVER_UNAVAILABLE` before sending input. Click a visible control or use `performAction` with an advertised action. For browser content without these AX actions, use browser tools. Enable `systemPointerHover` only when moving the user’s visible cursor is acceptable. That route requires a foreground, unobscured target and leaves the cursor at the destination. @@ -191,7 +191,7 @@ Setup and discovery: - cua.getState(options?: { emit?: boolean }) -> { apps: { id: string, displayName: string, isRunning: true, pid: number }[], browsers: [] } — summarize running applications; this is not an accessibility observation. - cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and return without reading AX or activating the app. - app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership. -- app.getWindow(windowId: number) -> Window — select a window from the application’s current window list without reading AX; do this before any window screenshot or coordinate input. +- app.getWindow(windowId: number) -> Window — select a window by an ID from getWindows without reading AX; do this before any window screenshot or coordinate input, which rejects a closed or foreign window. - app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required. - app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation. - window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation. @@ -223,7 +223,7 @@ Available at app or window level depending on the platform. - 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?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree maps to getState; getWindow validates against listWindows; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. +Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. 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. ``` #### Token effect diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index f8fed7b624..4a6be7b8ef 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -113,7 +113,7 @@ void await window.getScreenshot() 使用 `cua` API 发现并选择应用(`listApps`、`getState`、`findApps`、`getApp`);使用选定的应用来激活它、枚举其窗口并选择窗口。截图和指针输入都要求选择窗口,不只在存在多个窗口时才需要。`getApp` 和 `app.getWindow(windowId)` 返回时不读取 AX;根据 `getWindows()` 中的标题与位置选择窗口。 -`getWindow` 根据当前应用窗口清单验证 ID。元素操作前须显式读取 `getAccessibilityTree()`。截图和坐标输入不要求 AX 读取成功;绝对像素坐标要求已交付的截图。已确认归属但没有 AX 界面的窗口在显式观察时返回空快照。在单个 API 实例内,门面按应用句柄保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享它,包括重复选择。读取任一窗口都会替换该快照;元素操作使用最新快照 ID,因此应使用最新树中的元素 ID,不应假定旧 ID 仍指向同一控件。读取失败不会发布部分快照;可以重新读取,但不要重复此前的输入。窗口对象负责截图和指针输入。键盘方法保留在 `app` 上,因为输入跟随应用的当前焦点。 +`getWindow` 不发送原生请求;截图和指针输入会拒绝已关闭或属于其他应用的窗口。元素操作前须显式读取 `getAccessibilityTree()`。截图和坐标输入不要求 AX 读取成功;绝对像素坐标要求已交付的截图。已确认归属但没有 AX 界面的窗口在显式观察时返回空快照。在单个 API 实例内,门面按应用句柄保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享它,包括重复选择。读取任一窗口都会替换该快照;元素操作使用最新快照 ID,因此应使用最新树中的元素 ID,不应假定旧 ID 仍指向同一控件。读取失败不会发布部分快照;可以重新读取,但不要重复此前的输入。窗口对象负责截图和指针输入。键盘方法保留在 `app` 上,因为输入跟随应用的当前焦点。 `mouseMove(target)` 默认通过 AX 悬停。目标或其祖先必须已启用,并同时声明 `AXShowAlternateUI` 和 `AXShowDefaultUI`。进入子控件会保持展开,离开后恢复默认界面。如果没有可用的 AX 路径,helper 返回 `HOVER_UNAVAILABLE`,不发送输入。可点击已经可见的控件,或用 `performAction` 执行控件声明的动作。浏览器内容缺少这些 AX 动作时,请使用浏览器工具。只有允许移动用户可见光标时才开启 `systemPointerHover`。这条路径要求目标在前台且未被遮挡,操作后光标停在目标位置。 @@ -191,7 +191,7 @@ Setup and discovery: - cua.getState(options?: { emit?: boolean }) -> { apps: { id: string, displayName: string, isRunning: true, pid: number }[], browsers: [] } — summarize running applications; this is not an accessibility observation. - cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and return without reading AX or activating the app. - app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership. -- app.getWindow(windowId: number) -> Window — select a window from the application’s current window list without reading AX; do this before any window screenshot or coordinate input. +- app.getWindow(windowId: number) -> Window — select a window by an ID from getWindows without reading AX; do this before any window screenshot or coordinate input, which rejects a closed or foreign window. - app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required. - app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation. - window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation. @@ -223,7 +223,7 @@ Available at app or window level depending on the platform. - 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?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree maps to getState; getWindow validates against listWindows; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. +Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. 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. ``` #### Token 影响 diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index fffdfaa5c6..dee3c61085 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: 77dbaaa91d5b92c8 - zh: 94c3a758a91476bd + en: 01344bd3eba672cd + zh: e26f37a224899a46 /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 0b3d39fdd1..dd262aede7 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -31,7 +31,7 @@ Application consent supplies English, Chinese, and Japanese display text from `s Mount the [macOS provider](../cua-macos/README.md) to enable native operations on macOS. 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 `cua.getApp(selector)` to select an application; it obtains consent and optionally launches a stopped application in the background, without reading its accessibility tree. `cua.listApps` and `cua.getState` list running applications; `cua.findApps(query)` searches installed applications, including stopped ones. `app.activate()`, `app.getWindows()`, and `app.getWindow(windowId)` operate on the selected application; `getWindow` validates the ID against the current application window list and returns the object without reading AX. Select an application and one of its windows before any capture or pointer input. Read `app.getAccessibilityTree()` or `window.getAccessibilityTree()` explicitly before element operations. Screenshots remain available when AX reading fails. Within one API instance, the facade keeps one current accessibility snapshot per application handle across app and window objects, including repeated selections; each new read invalidates the previous snapshot. Element operations use the latest snapshot ID, so callers use IDs from the latest tree and do not assume an older ID still identifies the same control. Element IDs are opaque strings. +Use `cua.getApp(selector)` to select an application; it obtains consent and optionally launches a stopped application in the background, without reading its accessibility tree. `cua.listApps` and `cua.getState` list running applications; `cua.findApps(query)` searches installed applications, including stopped ones. `app.activate()`, `app.getWindows()`, and `app.getWindow(windowId)` operate on the selected application; `getWindow` returns the object without a native request; window operations reject closed or foreign windows. Select an application and one of its windows before any capture or pointer input. Read `app.getAccessibilityTree()` or `window.getAccessibilityTree()` explicitly before element operations. Screenshots remain available when AX reading fails. Within one API instance, the facade keeps one current accessibility snapshot per application handle across app and window objects, including repeated selections; each new read invalidates the previous snapshot. Element operations use the latest snapshot ID, so callers use IDs from the latest tree and do not assume an older ID still identifies the same control. Element IDs are opaque strings. Keyboard methods are available in the scopes a provider declares; the provider owns how input is delivered within each scope. A lost connection invalidates its handles and coordinates. Failed cleanup is reported before that connection is retired; select the application again and inspect fresh state, because earlier input may have partially executed. Screenshot image errors retain the failing stage and attachment error code. Invalid request arguments reject before dispatch with a readable method, parameter and requirement. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index b79cc6fdb5..ee274413ef 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -31,7 +31,7 @@ kind: "package-reference" 挂载 [macOS 提供方](../cua-macos/README.zh.md)以在 macOS 上启用原生操作。外部 PTC 宿主从 `@deepseek-ai/dsh-cua/bridge` 导入 `connectCua`,并提供当前 `tools.cua` 绑定。源码组合与原生组件准备由提供方负责。 -使用 `cua.getApp(selector)` 选择应用;它会获取授权、按需在后台启动已停止的应用,不读取辅助功能树。`cua.listApps` 和 `cua.getState` 列出运行中的应用;`cua.findApps(query)` 搜索已安装应用,包括未运行的应用。`app.activate()`、`app.getWindows()` 和 `app.getWindow(windowId)` 操作选定的应用;`getWindow` 根据当前应用窗口清单验证 ID,然后返回对象,不读取 AX。进行任何截图或指针输入前,必须选择应用及其一个窗口。元素操作前须显式读取 `app.getAccessibilityTree()` 或 `window.getAccessibilityTree()`。AX 读取失败时仍可截图。在单个 API 实例内,门面按应用句柄保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享它,包括重复选择;每次新读取都会使上一份快照失效。元素操作使用最新快照 ID,因此调用方应使用最新树中的元素 ID,不应假定旧 ID 仍指向同一控件。元素 ID 是不透明字符串。 +使用 `cua.getApp(selector)` 选择应用;它会获取授权、按需在后台启动已停止的应用,不读取辅助功能树。`cua.listApps` 和 `cua.getState` 列出运行中的应用;`cua.findApps(query)` 搜索已安装应用,包括未运行的应用。`app.activate()`、`app.getWindows()` 和 `app.getWindow(windowId)` 操作选定的应用;`getWindow` 返回对象时不发送原生请求;窗口操作会拒绝已关闭或属于其他应用的窗口。进行任何截图或指针输入前,必须选择应用及其一个窗口。元素操作前须显式读取 `app.getAccessibilityTree()` 或 `window.getAccessibilityTree()`。AX 读取失败时仍可截图。在单个 API 实例内,门面按应用句柄保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享它,包括重复选择;每次新读取都会使上一份快照失效。元素操作使用最新快照 ID,因此调用方应使用最新树中的元素 ID,不应假定旧 ID 仍指向同一控件。元素 ID 是不透明字符串。 键盘方法可在 provider 声明的作用域中使用;每个作用域内的输入投递由 provider 负责。连接丢失会使其句柄和坐标失效。清理失败会先报告,再释放该连接;应重新选择应用并读取新状态,因为先前的输入可能已部分执行。截图图像错误会保留失败阶段和附件错误码。请求参数校验失败时,在分派前返回包含方法、参数和要求的可读消息。 diff --git a/packages/experimental/cua/package.json b/packages/experimental/cua/package.json index 410dd23cf7..440f321935 100644 --- a/packages/experimental/cua/package.json +++ b/packages/experimental/cua/package.json @@ -99,8 +99,7 @@ "@deepseek-ai/dsh-user-questions": "workspace:*", "@deepseek-ai/dsh-attachment": "workspace:*", "@deepseek-ai/dsh-scope": "workspace:*", - "@deepseek-ai/dsh-ptc-runtime-node": "workspace:*", - "@deepseek-ai/dsh-error": "workspace:*" + "@deepseek-ai/dsh-ptc-runtime-node": "workspace:*" }, "dependencies": { "@deepseek-ai/schemastery": "workspace:~", @@ -162,8 +161,7 @@ "@deepseek-ai/dsh-storage-json": "workspace:*", "@deepseek-ai/dsh-client-ui-user-questions": "workspace:*", "@deepseek-ai/dsh-client-ui-approval": "workspace:*", - "@deepseek-ai/dsh-client-ui-conversation": "workspace:*", - "@deepseek-ai/dsh-error": "workspace:*" + "@deepseek-ai/dsh-client-ui-conversation": "workspace:*" }, "dsh": { "client": { diff --git a/packages/experimental/cua/src/api.ts b/packages/experimental/cua/src/api.ts index 509b9b8676..b28d4e9f1c 100644 --- a/packages/experimental/cua/src/api.ts +++ b/packages/experimental/cua/src/api.ts @@ -1,6 +1,5 @@ /** Object facade over logged native operations; its caller owns evaluator persistence. */ import { Buffer } from 'node:buffer' -import { HarnessError } from '@deepseek-ai/dsh-error' import type { z } from 'zod' import type { JsonValue } from '@deepseek-ai/dsh-util-values' import { ActionNamesResult, ActionResult, AppResult, AppsResult, CapabilitiesResult, FoundAppsResult, HoverResult, Request, ScreenshotResult, ShowResult, StateResult, WindowsResult } from './protocol.ts' @@ -257,14 +256,11 @@ function createCuaObjects(call: ReturnType, sink: CuaObser await emit(sink, windows, options) return windows }, - async getWindow(windowId): Promise { - const parsed = WindowsResult.element.shape.windowId.safeParse(windowId) - if (!parsed.success) throw new HarnessError(`getWindow ${requestIssueMessage(parsed.error.issues, ['params', 'windowId'])}`, 'INVALID_ARGS') - const windows = WindowsResult.parse(await base.call('listWindows', {})) - if (!windows.some(window => window.windowId === windowId)) { - throw new HarnessError('Selected window is unavailable for this application; read getWindows again', 'CUA_WINDOW_UNAVAILABLE') - } - return createCuaWindow(appHandle, windowId, capabilities) + getWindow(windowId): Promise { + // Native window operations reject closed and foreign windows; selection only admits the ID they accept. + const request = Request.safeParse({ method: 'screenshot', params: { appHandle, windowId } }) + if (!request.success) return Promise.reject(new Error(`getWindow ${requestIssueMessage(request.error.issues)}`)) + return Promise.resolve(createCuaWindow(appHandle, windowId, capabilities)) }, } } diff --git a/packages/experimental/cua/src/guidance.ts b/packages/experimental/cua/src/guidance.ts index 89a32bd21a..c1ede9f30b 100644 --- a/packages/experimental/cua/src/guidance.ts +++ b/packages/experimental/cua/src/guidance.ts @@ -13,7 +13,7 @@ Setup and discovery: - cua.getState(options?: { emit?: boolean }) -> { apps: { id: string, displayName: string, isRunning: true, pid: number }[], browsers: [] } — summarize running applications; this is not an accessibility observation. - cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and return without reading AX or activating the app. - app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership. -- app.getWindow(windowId: number) -> Window — select a window from the application’s current window list without reading AX; do this before any window screenshot or coordinate input. +- app.getWindow(windowId: number) -> Window — select a window by an ID from getWindows without reading AX; do this before any window screenshot or coordinate input, which rejects a closed or foreign window. - app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required. - app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation. - window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation. @@ -45,4 +45,4 @@ Available at app or window level depending on the platform. - 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?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree maps to getState; getWindow validates against listWindows; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name.` +Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. 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.` diff --git a/packages/experimental/cua/src/types.ts b/packages/experimental/cua/src/types.ts index 0e8624b6ea..a9c4776acf 100644 --- a/packages/experimental/cua/src/types.ts +++ b/packages/experimental/cua/src/types.ts @@ -240,7 +240,8 @@ export interface CuaApp extends CuaSurface { /** * Select a specific window. * @param windowId - ID obtained from getWindows. - * @returns A window object from the app’s current window list, without reading or replacing its accessibility snapshot. + * @returns A window object without a native request; selection leaves the accessibility snapshot unchanged. + * Window operations reject a closed or foreign window. */ getWindow(windowId: number): Promise } diff --git a/packages/experimental/cua/tests/api.spec.ts b/packages/experimental/cua/tests/api.spec.ts index fb2bf5a204..2b023db37d 100644 --- a/packages/experimental/cua/tests/api.spec.ts +++ b/packages/experimental/cua/tests/api.spec.ts @@ -83,7 +83,7 @@ describe('application discovery', () => { const window = await app.getWindow(23) expect(await window.getScreenshot()).toEqual({ bytes: Uint8Array.from(Buffer.from(PNG, 'base64')), mimeType: 'image/png', pixelWidth: 1, pixelHeight: 1, windowId: 23 }) expect(f.dispatch.mock.calls.map(([operation]) => operation.method)).toEqual([ - 'getCapabilities', 'listApps', 'getApp', 'listWindows', 'screenshot', + 'getCapabilities', 'listApps', 'getApp', 'screenshot', ]) expect(await app.getWindows()).toEqual([windowInfo(23)]) expect(f.sink.text).not.toHaveBeenCalled() @@ -186,7 +186,7 @@ describe('mouseMove across observations', () => { } }) f.dispatch.mockRejectedValueOnce(new Error('WINDOW_CHANGED')) await expect(other.mouseMove([5, 6])).rejects.toThrow('WINDOW_CHANGED') - expect(f.dispatch).toHaveBeenCalledTimes(8) + expect(f.dispatch).toHaveBeenCalledTimes(7) }) }) @@ -452,15 +452,15 @@ describe('application and window observations', () => { } }) - it.each(['WINDOW_UNAVAILABLE', 'PERMISSION_DENIED', 'STALE_APP', 'SESSION_LOCKED'])('propagates %s while selecting a window without attempting image or input fallback', async (code) => { + it.each(['WINDOW_UNAVAILABLE', 'PERMISSION_DENIED', 'STALE_APP', 'SESSION_LOCKED'])('propagates %s from coordinate input on a selected window without image or input fallback', async (code) => { const f = fixture() const app = await f.api.getApp('Editor') - await app.getAccessibilityTree({ emit: false }) + const window = await app.getWindow(23) const failure = new Error(code) f.dispatch.mockRejectedValueOnce(failure) const calls = f.dispatch.mock.calls.length - await expect(app.getWindow(23)).rejects.toBe(failure) - expect(f.dispatch.mock.calls.slice(calls).map(([operation]) => operation.method)).toEqual(['listWindows']) + await expect(window.click([1, 2])).rejects.toBe(failure) + expect(f.dispatch.mock.calls.slice(calls).map(([operation]) => operation.method)).toEqual(['click']) }) it('captures and clicks the explicitly selected window among several', async () => { @@ -629,15 +629,12 @@ describe('application and window observations', () => { }) describe('screenshots', () => { - it('rejects a missing or foreign window without reading AX or taking a screenshot', async () => { + it('selects windows without a native request and rejects invalid IDs locally', async () => { const f = fixture() const app = await f.api.getApp('Editor') - await expect(app.getWindow(24)).rejects.toMatchObject({ name: 'HarnessError', code: 'CUA_WINDOW_UNAVAILABLE' }) - f.setWindows([]) - await expect(app.getWindow(23)).rejects.toMatchObject({ name: 'HarnessError', code: 'CUA_WINDOW_UNAVAILABLE' }) - expect(f.dispatch.mock.calls.map(([request]) => request.method)).toEqual(['getCapabilities', 'getApp', 'listWindows', 'listWindows']) - await expect(app.getWindow(0)).rejects.toMatchObject({ name: 'HarnessError', code: 'INVALID_ARGS', message: 'getWindow windowId: Too small: expected number to be >0' }) - expect(f.dispatch).toHaveBeenCalledTimes(4) + expect((await app.getWindow(24)).windowId).toBe(24) + await expect(app.getWindow(0)).rejects.toThrow('getWindow windowId: Too small: expected number to be >0') + expect(f.dispatch.mock.calls.map(([request]) => request.method)).toEqual(['getCapabilities', 'getApp']) }) it.each(['APP_ACCESS_REVOKED', 'WINDOW_UNAVAILABLE', 'STALE_APP'])('preserves %s when capturing a previously selected window', async (code) => { @@ -989,10 +986,10 @@ describe('input actions', () => { const failure = new Error('Application was restarted; select it again') f.dispatch.mockRejectedValueOnce(failure) await expect(app.typeText('hello')).rejects.toBe(failure) - expect(f.dispatch).toHaveBeenCalledTimes(6) + expect(f.dispatch).toHaveBeenCalledTimes(5) f.dispatch.mockResolvedValueOnce({ dispatched: 'yes' }) await expect(window.click(element('0'))).rejects.toThrow() - expect(f.dispatch).toHaveBeenCalledTimes(7) + expect(f.dispatch).toHaveBeenCalledTimes(6) }) it('rejects invalid selection inputs before dispatch', async () => { diff --git a/packages/experimental/cua/tests/bridge.spec.ts b/packages/experimental/cua/tests/bridge.spec.ts index 7bba3c4e0b..be2edddb9f 100644 --- a/packages/experimental/cua/tests/bridge.spec.ts +++ b/packages/experimental/cua/tests/bridge.spec.ts @@ -27,7 +27,6 @@ it('uses the current tool binding when a retained app is called by another execu const first = vi.fn(async (operation: CuaOperation): Promise => { if (operation.method === 'getCapabilities') return capabilities if (operation.method === 'getApp') return selected - if (operation.method === 'listWindows') return snapshot.windows if (operation.method === 'getState') return { ...snapshot, windowId: operation.params.windowId ?? null } return snapshot }) @@ -41,7 +40,7 @@ it('uses the current tool binding when a retained app is called by another execu current = second await expect(window.click(element('0'))).resolves.toEqual({ dispatched: true }) - expect(first).toHaveBeenCalledTimes(4) + expect(first).toHaveBeenCalledTimes(3) expect(second).toHaveBeenCalledWith({ method: 'click', params: { appHandle: 'app-17', snapshotId: 'snapshot-1', elementId: '0', windowId: 23 } }) expect(text).not.toHaveBeenCalled() current = first @@ -71,7 +70,6 @@ it('returns screenshot bytes and metadata with one image-bearing tool call and n const tool = vi.fn(async (operation: CuaOperation): Promise => { if (operation.method === 'getCapabilities') return capabilities if (operation.method === 'getApp') return selected - if (operation.method === 'listWindows') return snapshot.windows if (operation.method === 'getState') return { ...snapshot, windowId: operation.params.windowId ?? null } return { mimeType: 'image/png', data: PNG, pixelWidth: 1, pixelHeight: 1, windowId: 23, bounds, coordinateSpace: 'screenshot-pixels', @@ -83,6 +81,6 @@ it('returns screenshot bytes and metadata with one image-bearing tool call and n text.mockClear() expect(await window.getScreenshot()).toEqual({ bytes: Uint8Array.from(Buffer.from(PNG, 'base64')), mimeType: 'image/png', pixelWidth: 1, pixelHeight: 1, windowId: 23 }) - expect(tool.mock.calls.map(([operation]) => operation.method)).toEqual(['getCapabilities', 'getApp', 'listWindows', 'screenshot']) + expect(tool.mock.calls.map(([operation]) => operation.method)).toEqual(['getCapabilities', 'getApp', 'screenshot']) expect(text).not.toHaveBeenCalled() }) diff --git a/packages/experimental/cua/tsconfig.host.json b/packages/experimental/cua/tsconfig.host.json index 4bf0b7ddda..2386f83640 100644 --- a/packages/experimental/cua/tsconfig.host.json +++ b/packages/experimental/cua/tsconfig.host.json @@ -74,9 +74,6 @@ }, { "path": "../../boot/config-editor" - }, - { - "path": "../../util/error" } ], "exclude": [ diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f33fef7d42..d016fe8deb 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -9894,9 +9894,6 @@ importers: '@deepseek-ai/dsh-config-editor': specifier: workspace:* version: link:../../boot/config-editor - '@deepseek-ai/dsh-error': - specifier: workspace:* - version: link:../../util/error '@deepseek-ai/dsh-fs-local': specifier: workspace:* version: link:../../fs/fs-local diff --git a/snapshots/session/cua-native/system-prompt.expected.md b/snapshots/session/cua-native/system-prompt.expected.md index 04fb520f49..e8dfa822c9 100644 --- a/snapshots/session/cua-native/system-prompt.expected.md +++ b/snapshots/session/cua-native/system-prompt.expected.md @@ -48,7 +48,7 @@ Setup and discovery: - cua.getState(options?: { emit?: boolean }) -> { apps: { id: string, displayName: string, isRunning: true, pid: number }[], browsers: [] } — summarize running applications; this is not an accessibility observation. - cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and return without reading AX or activating the app. - app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership. -- app.getWindow(windowId: number) -> Window — select a window from the application’s current window list without reading AX; do this before any window screenshot or coordinate input. +- app.getWindow(windowId: number) -> Window — select a window by an ID from getWindows without reading AX; do this before any window screenshot or coordinate input, which rejects a closed or foreign window. - app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required. - app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation. - window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation. @@ -80,6 +80,6 @@ Available at app or window level depending on the platform. - 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?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree maps to getState; getWindow validates against listWindows; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. +Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. 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. Maximum click holdMs: 5000 ms. diff --git a/snapshots/session/cua-ptc/session.v4.jsonl b/snapshots/session/cua-ptc/session.v4.jsonl index f9d25d914b..dd3c7c5ffa 100644 --- a/snapshots/session/cua-ptc/session.v4.jsonl +++ b/snapshots/session/cua-ptc/session.v4.jsonl @@ -12,7 +12,7 @@ {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"}} {"type":"session/title","data":{"title":"Use tools.cua from Node PTC","messageSeqs":[8],"source":{"kind":"fallback"}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-ptc-native-result","name":"run_code","arguments":"{\"code\":\"const { Buffer } = await import('node:buffer');\\nconst app = await tools.cua({ method: 'getApp', params: { selector: 'test.fixture' } });\\nconst state = await tools.cua({ method: 'getState', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst shot = await tools.cua({ method: 'screenshot', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst bytes = Buffer.from(shot.data, 'base64');\\nreturn { appHandle: app.appHandle, hasIncrement: state.tree.includes('Increment'), pngBytes: bytes.length, signature: bytes.subarray(0, 8).toString('hex'), imageWidth: shot.attachment.width, imageHeight: shot.attachment.height };\",\"description\":\"Read native CUA values and receive one screenshot\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794024973829,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794024973829,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-ptc-native-result","name":"run_code","arguments":"{\"code\":\"const { Buffer } = await import('node:buffer');\\nconst app = await tools.cua({ method: 'getApp', params: { selector: 'test.fixture' } });\\nconst state = await tools.cua({ method: 'getState', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst shot = await tools.cua({ method: 'screenshot', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst bytes = Buffer.from(shot.data, 'base64');\\nreturn { appHandle: app.appHandle, hasIncrement: state.tree.includes('Increment'), pngBytes: bytes.length, signature: bytes.subarray(0, 8).toString('hex'), imageWidth: shot.attachment.width, imageHeight: shot.attachment.height };\",\"description\":\"Read native CUA values and receive one screenshot\"}"}}},{"type":"chunk","time":1794024973829,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794024973829,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-ptc-native-result","name":"run_code","arguments":"{\"code\":\"const { Buffer } = await import('node:buffer');\\nconst app = await tools.cua({ method: 'getApp', params: { selector: 'test.fixture' } });\\nconst state = await tools.cua({ method: 'getState', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst shot = await tools.cua({ method: 'screenshot', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst bytes = Buffer.from(shot.data, 'base64');\\nreturn { appHandle: app.appHandle, hasIncrement: state.tree.includes('Increment'), pngBytes: bytes.length, signature: bytes.subarray(0, 8).toString('hex'), imageWidth: shot.attachment.width, imageHeight: shot.attachment.height };\",\"description\":\"Read native CUA values and receive one screenshot\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794031895518,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794031895518,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-ptc-native-result","name":"run_code","arguments":"{\"code\":\"const { Buffer } = await import('node:buffer');\\nconst app = await tools.cua({ method: 'getApp', params: { selector: 'test.fixture' } });\\nconst state = await tools.cua({ method: 'getState', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst shot = await tools.cua({ method: 'screenshot', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst bytes = Buffer.from(shot.data, 'base64');\\nreturn { appHandle: app.appHandle, hasIncrement: state.tree.includes('Increment'), pngBytes: bytes.length, signature: bytes.subarray(0, 8).toString('hex'), imageWidth: shot.attachment.width, imageHeight: shot.attachment.height };\",\"description\":\"Read native CUA values and receive one screenshot\"}"}}},{"type":"chunk","time":1794031895518,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794031895518,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua-ptc-native-result","name":"run_code","arguments":"{\"code\":\"const { Buffer } = await import('node:buffer');\\nconst app = await tools.cua({ method: 'getApp', params: { selector: 'test.fixture' } });\\nconst state = await tools.cua({ method: 'getState', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst shot = await tools.cua({ method: 'screenshot', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst bytes = Buffer.from(shot.data, 'base64');\\nreturn { appHandle: app.appHandle, hasIncrement: state.tree.includes('Increment'), pngBytes: bytes.length, signature: bytes.subarray(0, 8).toString('hex'), imageWidth: shot.attachment.width, imageHeight: shot.attachment.height };\",\"description\":\"Read native CUA values and receive one screenshot\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-native-result","parentCallId":"cua-ptc-native-result","subCallId":"cua-ptc-native-result:ptc:1","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-native-result","parentCallId":"cua-ptc-native-result","subCallId":"cua-ptc-native-result:ptc:1","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"name\":\"Fixture\",\"bundleId\":\"test.fixture\",\"running\":true}"}]}} @@ -26,7 +26,7 @@ {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":1,"step":2}} {"type":"user/message","data":{"content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"source":{"kind":"ptc-mode"},"role":"user","id":"{{message:6}}"},"surfaceOp":"append"} -{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-ptc-ax-failure","name":"run_code","arguments":"{\"code\":\"const { writeFile, unlink } = await import('node:fs/promises');\\nconst { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nawait writeFile('fixture-ax-failure', '');\\ntry {\\n const cua = connectCua(() => tools.cua);\\n const app = await cua.getApp('test.fixture');\\n const windows = await app.getWindows({ emit: false });\\n const window = await app.getWindow(windows[0].windowId);\\n const failures = [];\\n for (const surface of [app, window]) {\\n try { await surface.getAccessibilityTree(); throw new Error('Expected AX failure'); }\\n catch (error) { if (!error.message.includes('Fixture accessibility read failed')) throw error; failures.push(error.message); }\\n }\\n const shot = await window.getScreenshot();\\n let elementRefused = false;\\n try { await window.invoke('0'); }\\n catch (error) { if (!error.message.includes('Read getAccessibilityTree')) throw error; elementRefused = true; }\\n if (!elementRefused) throw new Error('Element input accepted without an AX snapshot');\\n return { axFailures: failures.length, screenshotWindow: shot.windowId, pngBytes: shot.bytes.length, elementRefused };\\n} finally { await unlink('fixture-ax-failure'); }\",\"description\":\"Capture through the object API despite application and window AX failures\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:7}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794024974646,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794024974646,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-ptc-ax-failure","name":"run_code","arguments":"{\"code\":\"const { writeFile, unlink } = await import('node:fs/promises');\\nconst { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nawait writeFile('fixture-ax-failure', '');\\ntry {\\n const cua = connectCua(() => tools.cua);\\n const app = await cua.getApp('test.fixture');\\n const windows = await app.getWindows({ emit: false });\\n const window = await app.getWindow(windows[0].windowId);\\n const failures = [];\\n for (const surface of [app, window]) {\\n try { await surface.getAccessibilityTree(); throw new Error('Expected AX failure'); }\\n catch (error) { if (!error.message.includes('Fixture accessibility read failed')) throw error; failures.push(error.message); }\\n }\\n const shot = await window.getScreenshot();\\n let elementRefused = false;\\n try { await window.invoke('0'); }\\n catch (error) { if (!error.message.includes('Read getAccessibilityTree')) throw error; elementRefused = true; }\\n if (!elementRefused) throw new Error('Element input accepted without an AX snapshot');\\n return { axFailures: failures.length, screenshotWindow: shot.windowId, pngBytes: shot.bytes.length, elementRefused };\\n} finally { await unlink('fixture-ax-failure'); }\",\"description\":\"Capture through the object API despite application and window AX failures\"}"}}},{"type":"chunk","time":1794024974646,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794024974646,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-ptc-ax-failure","name":"run_code","arguments":"{\"code\":\"const { writeFile, unlink } = await import('node:fs/promises');\\nconst { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nawait writeFile('fixture-ax-failure', '');\\ntry {\\n const cua = connectCua(() => tools.cua);\\n const app = await cua.getApp('test.fixture');\\n const windows = await app.getWindows({ emit: false });\\n const window = await app.getWindow(windows[0].windowId);\\n const failures = [];\\n for (const surface of [app, window]) {\\n try { await surface.getAccessibilityTree(); throw new Error('Expected AX failure'); }\\n catch (error) { if (!error.message.includes('Fixture accessibility read failed')) throw error; failures.push(error.message); }\\n }\\n const shot = await window.getScreenshot();\\n let elementRefused = false;\\n try { await window.invoke('0'); }\\n catch (error) { if (!error.message.includes('Read getAccessibilityTree')) throw error; elementRefused = true; }\\n if (!elementRefused) throw new Error('Element input accepted without an AX snapshot');\\n return { axFailures: failures.length, screenshotWindow: shot.windowId, pngBytes: shot.bytes.length, elementRefused };\\n} finally { await unlink('fixture-ax-failure'); }\",\"description\":\"Capture through the object API despite application and window AX failures\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:7}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794031896364,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794031896364,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-ptc-ax-failure","name":"run_code","arguments":"{\"code\":\"const { writeFile, unlink } = await import('node:fs/promises');\\nconst { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nawait writeFile('fixture-ax-failure', '');\\ntry {\\n const cua = connectCua(() => tools.cua);\\n const app = await cua.getApp('test.fixture');\\n const windows = await app.getWindows({ emit: false });\\n const window = await app.getWindow(windows[0].windowId);\\n const failures = [];\\n for (const surface of [app, window]) {\\n try { await surface.getAccessibilityTree(); throw new Error('Expected AX failure'); }\\n catch (error) { if (!error.message.includes('Fixture accessibility read failed')) throw error; failures.push(error.message); }\\n }\\n const shot = await window.getScreenshot();\\n let elementRefused = false;\\n try { await window.invoke('0'); }\\n catch (error) { if (!error.message.includes('Read getAccessibilityTree')) throw error; elementRefused = true; }\\n if (!elementRefused) throw new Error('Element input accepted without an AX snapshot');\\n return { axFailures: failures.length, screenshotWindow: shot.windowId, pngBytes: shot.bytes.length, elementRefused };\\n} finally { await unlink('fixture-ax-failure'); }\",\"description\":\"Capture through the object API despite application and window AX failures\"}"}}},{"type":"chunk","time":1794031896364,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794031896364,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"cua-ptc-ax-failure","name":"run_code","arguments":"{\"code\":\"const { writeFile, unlink } = await import('node:fs/promises');\\nconst { resolve } = await import('node:path');\\nconst { pathToFileURL } = await import('node:url');\\nconst { connectCua } = await import(pathToFileURL(resolve('cua-bridge.mjs')).href);\\nawait writeFile('fixture-ax-failure', '');\\ntry {\\n const cua = connectCua(() => tools.cua);\\n const app = await cua.getApp('test.fixture');\\n const windows = await app.getWindows({ emit: false });\\n const window = await app.getWindow(windows[0].windowId);\\n const failures = [];\\n for (const surface of [app, window]) {\\n try { await surface.getAccessibilityTree(); throw new Error('Expected AX failure'); }\\n catch (error) { if (!error.message.includes('Fixture accessibility read failed')) throw error; failures.push(error.message); }\\n }\\n const shot = await window.getScreenshot();\\n let elementRefused = false;\\n try { await window.invoke('0'); }\\n catch (error) { if (!error.message.includes('Read getAccessibilityTree')) throw error; elementRefused = true; }\\n if (!elementRefused) throw new Error('Element input accepted without an AX snapshot');\\n return { axFailures: failures.length, screenshotWindow: shot.windowId, pngBytes: shot.bytes.length, elementRefused };\\n} finally { await unlink('fixture-ax-failure'); }\",\"description\":\"Capture through the object API despite application and window AX failures\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"methods\":[\"activate\",\"click\",\"drag\",\"findApps\",\"getApp\",\"getCapabilities\",\"getState\",\"invoke\",\"listActions\",\"listApps\",\"listWindows\",\"mouseMove\",\"paste\",\"performAction\",\"pressKey\",\"screenshot\",\"scroll\",\"selectText\",\"setValue\",\"show\",\"typeText\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} @@ -34,20 +34,18 @@ {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"name\":\"Fixture\",\"bundleId\":\"test.fixture\",\"running\":true}"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:3","name":"cua","arguments":{"method":"listWindows","params":{"appHandle":"fixture-app"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:3","name":"cua","arguments":{"method":"listWindows","params":{"appHandle":"fixture-app"}},"isError":false,"content":[{"type":"text","text":"[{\"windowId\":7,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}]"}]}} -{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:4","name":"cua","arguments":{"method":"listWindows","params":{"appHandle":"fixture-app"}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:4","name":"cua","arguments":{"method":"listWindows","params":{"appHandle":"fixture-app"}},"isError":false,"content":[{"type":"text","text":"[{\"windowId\":7,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}]"}]}} -{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:5","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app"}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:5","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app"}},"isError":true,"content":[{"type":"text","text":"Error: NATIVE_ERROR: Fixture accessibility read failed"}]}} -{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:6","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":7}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:6","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":7}},"isError":true,"content":[{"type":"text","text":"Error: NATIVE_ERROR: Fixture accessibility read failed"}]}} -{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:7","name":"cua","arguments":{"method":"screenshot","params":{"appHandle":"fixture-app","windowId":7}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:7","name":"cua","arguments":{"method":"screenshot","params":{"appHandle":"fixture-app","windowId":7}},"isError":false,"content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:4","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:4","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app"}},"isError":true,"content":[{"type":"text","text":"Error: NATIVE_ERROR: Fixture accessibility read failed"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:5","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":7}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:5","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":7}},"isError":true,"content":[{"type":"text","text":"Error: NATIVE_ERROR: Fixture accessibility read failed"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:6","name":"cua","arguments":{"method":"screenshot","params":{"appHandle":"fixture-app","windowId":7}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-ax-failure","parentCallId":"cua-ptc-ax-failure","subCallId":"cua-ptc-ax-failure:ptc:6","name":"cua","arguments":{"method":"screenshot","params":{"appHandle":"fixture-app","windowId":7}},"isError":false,"content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}]}} {"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-ptc-ax-failure"},"toolCallId":"cua-ptc-ax-failure","content":[{"type":"text","text":"{\n \"axFailures\": 2,\n \"screenshotWindow\": 7,\n \"pngBytes\": 90,\n \"elementRefused\": true\n}"}],"isError":false,"id":"{{message:8}}"}},"sourceEventSeqs":[28],"surfaceOp":"append"} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"source":{"kind":"ptc-mode"},"role":"user","id":"{{message:9}}"}]}} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":1,"step":3}} {"type":"user/message","data":{"content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"source":{"kind":"ptc-mode"},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} -{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"text","text":"Received native CUA values and PNG screenshots through PTC. The object API captured a 90-byte PNG after two AX read failures and refused element input without an accessibility snapshot."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:10}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794024974851,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1794024974851,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Received native CUA values and PNG screenshots through PTC. The object API captured a 90-byte PNG after two AX read failures and refused element input without an accessibility snapshot."}}},{"type":"chunk","time":1794024974851,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794024974851,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"text","text":"Received native CUA values and PNG screenshots through PTC. The object API captured a 90-byte PNG after two AX read failures and refused element input without an accessibility snapshot."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:10}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1794031896552,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1794031896552,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Received native CUA values and PNG screenshots through PTC. The object API captured a 90-byte PNG after two AX read failures and refused element input without an accessibility snapshot."}}},{"type":"chunk","time":1794031896552,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794031896552,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":3}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index be8ab5aed8..26186e4c92 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -50,7 +50,7 @@ Setup and discovery: - cua.getState(options?: { emit?: boolean }) -> { apps: { id: string, displayName: string, isRunning: true, pid: number }[], browsers: [] } — summarize running applications; this is not an accessibility observation. - cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and return without reading AX or activating the app. - app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership. -- app.getWindow(windowId: number) -> Window — select a window from the application’s current window list without reading AX; do this before any window screenshot or coordinate input. +- app.getWindow(windowId: number) -> Window — select a window by an ID from getWindows without reading AX; do this before any window screenshot or coordinate input, which rejects a closed or foreign window. - app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required. - app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation. - window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation. @@ -82,7 +82,7 @@ Available at app or window level depending on the platform. - 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?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree maps to getState; getWindow validates against listWindows; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. +Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. 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. Maximum click holdMs: 5000 ms. diff --git a/snapshots/session/ptc-script-retained/system-prompt.expected.md b/snapshots/session/ptc-script-retained/system-prompt.expected.md index 63e91315c0..e61732cc68 100644 --- a/snapshots/session/ptc-script-retained/system-prompt.expected.md +++ b/snapshots/session/ptc-script-retained/system-prompt.expected.md @@ -50,7 +50,7 @@ Setup and discovery: - cua.getState(options?: { emit?: boolean }) -> { apps: { id: string, displayName: string, isRunning: true, pid: number }[], browsers: [] } — summarize running applications; this is not an accessibility observation. - cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and return without reading AX or activating the app. - app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership. -- app.getWindow(windowId: number) -> Window — select a window from the application’s current window list without reading AX; do this before any window screenshot or coordinate input. +- app.getWindow(windowId: number) -> Window — select a window by an ID from getWindows without reading AX; do this before any window screenshot or coordinate input, which rejects a closed or foreign window. - app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required. - app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation. - window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation. @@ -82,7 +82,7 @@ Available at app or window level depending on the platform. - 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?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree maps to getState; getWindow validates against listWindows; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. +Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. 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. Maximum click holdMs: 5000 ms. From 662fb47ff2cd5d24f9057f0401d44cda162dd721 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Sat, 7 Nov 2026 15:29:08 +0800 Subject: [PATCH 017/184] Convert native helper to .NET Framework --- .../cua-windows/native/.gitignore | 1 + .../cua-windows/native/CuaWindows.csproj | 7 +- .../cua-windows/native/Directory.Build.props | 7 + .../cua-windows/native/cua-windows.slnx | 12 + .../desktop-tests/DesktopFixture.csproj | 5 +- .../desktop-tests/DesktopFixture.csproj.user | 9 + .../cua-windows/native/packages.lock.json | 156 ++++++++--- .../native/protocol/AccessibilityText.cs | 4 +- .../native/protocol/CuaProtocol.csproj | 3 +- .../cua-windows/native/protocol/KeyChord.cs | 4 +- .../native/protocol/NativeRequest.cs | 2 +- .../native/protocol/packages.lock.json | 137 +++++++++- .../native/src/CaptureAdmission.cs | 34 --- .../cua-windows/native/src/ClipboardPaste.cs | 4 +- .../cua-windows/native/src/DesktopExecutor.cs | 11 +- .../cua-windows/native/src/Dispatchers.cs | 12 +- .../cua-windows/native/src/NativeServer.cs | 3 +- .../cua-windows/native/src/WindowCapture.cs | 242 +----------------- .../cua-windows/native/tests/Program.cs | 19 -- .../native/tests/Protocol.Tests.csproj | 3 +- .../native/tests/packages.lock.json | 139 +++++++++- .../experimental/cua-windows/package.json | 2 +- 22 files changed, 434 insertions(+), 382 deletions(-) create mode 100644 packages/experimental/cua-windows/native/cua-windows.slnx create mode 100644 packages/experimental/cua-windows/native/desktop-tests/DesktopFixture.csproj.user delete mode 100644 packages/experimental/cua-windows/native/src/CaptureAdmission.cs diff --git a/packages/experimental/cua-windows/native/.gitignore b/packages/experimental/cua-windows/native/.gitignore index d519714059..afc10cfbc5 100644 --- a/packages/experimental/cua-windows/native/.gitignore +++ b/packages/experimental/cua-windows/native/.gitignore @@ -1,3 +1,4 @@ **/bin/ **/obj/ .build/ +**/.vs diff --git a/packages/experimental/cua-windows/native/CuaWindows.csproj b/packages/experimental/cua-windows/native/CuaWindows.csproj index 0cc65b6907..014cb6e37a 100644 --- a/packages/experimental/cua-windows/native/CuaWindows.csproj +++ b/packages/experimental/cua-windows/native/CuaWindows.csproj @@ -1,8 +1,7 @@ Exe - net10.0-windows10.0.19041.0 - true + net48 true true false @@ -12,15 +11,11 @@ dsh-cua-windows app.manifest true - win-x64;win-arm64 - true - true none false - diff --git a/packages/experimental/cua-windows/native/Directory.Build.props b/packages/experimental/cua-windows/native/Directory.Build.props index b4fbcbc808..f68224faae 100644 --- a/packages/experimental/cua-windows/native/Directory.Build.props +++ b/packages/experimental/cua-windows/native/Directory.Build.props @@ -1,6 +1,13 @@ + 14.0 + true $(MSBuildThisFileDirectory).build/$(MSBuildProjectName)/bin/ $(MSBuildThisFileDirectory).build/$(MSBuildProjectName)/obj/ + + + + + diff --git a/packages/experimental/cua-windows/native/cua-windows.slnx b/packages/experimental/cua-windows/native/cua-windows.slnx new file mode 100644 index 0000000000..efe33b9414 --- /dev/null +++ b/packages/experimental/cua-windows/native/cua-windows.slnx @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/packages/experimental/cua-windows/native/desktop-tests/DesktopFixture.csproj b/packages/experimental/cua-windows/native/desktop-tests/DesktopFixture.csproj index cb0fda00a0..77c960608e 100644 --- a/packages/experimental/cua-windows/native/desktop-tests/DesktopFixture.csproj +++ b/packages/experimental/cua-windows/native/desktop-tests/DesktopFixture.csproj @@ -1,13 +1,10 @@ Exe - net10.0-windows + net48 true - true enable enable dsh-cua-desktop-fixture - true - true diff --git a/packages/experimental/cua-windows/native/desktop-tests/DesktopFixture.csproj.user b/packages/experimental/cua-windows/native/desktop-tests/DesktopFixture.csproj.user new file mode 100644 index 0000000000..191764a929 --- /dev/null +++ b/packages/experimental/cua-windows/native/desktop-tests/DesktopFixture.csproj.user @@ -0,0 +1,9 @@ + + + + + + Form + + + \ No newline at end of file diff --git a/packages/experimental/cua-windows/native/packages.lock.json b/packages/experimental/cua-windows/native/packages.lock.json index dee2e0c44b..f2cf154da0 100644 --- a/packages/experimental/cua-windows/native/packages.lock.json +++ b/packages/experimental/cua-windows/native/packages.lock.json @@ -1,32 +1,56 @@ { "version": 1, "dependencies": { - "net10.0-windows10.0.19041": { - "Microsoft.NET.ILLink.Tasks": { + ".NETFramework,Version=v4.8": { + "Microsoft.NETFramework.ReferenceAssemblies": { "type": "Direct", - "requested": "[10.0.14, )", - "resolved": "10.0.14", - "contentHash": "YlTamXppEQls6DYWt7RdUuwWDb0lyw/vXCaGeQpLCpsLmfwGuCkOz/vIGgMTV7ECsJcavkCOkxZXv9s8rdAHkQ==" - }, - "Vortice.Direct3D11": { - "type": "Direct", - "requested": "[3.8.3, )", - "resolved": "3.8.3", - "contentHash": "JgFUswu2mgrSwcd0KRF2AnfeE5VbMEgcicmxPD1g2yXyomPIHbnX3wldBNHPOzzD0URC1WJ/pO1ymfi3imZwvg==", + "requested": "[1.0.3, )", + "resolved": "1.0.3", + "contentHash": "vUc9Npcs14QsyOD01tnv/m8sQUnGTGOw1BCmKcv77LBJY7OxhJ+zJF7UD/sCL3lYNFuqmQEVlkfS4Quif6FyYg==", "dependencies": { - "SharpGen.Runtime": "2.4.2-beta", - "Vortice.DXGI": "3.8.3" + "Microsoft.NETFramework.ReferenceAssemblies.net48": "1.0.3" + } + }, + "PolySharp": { + "type": "Direct", + "requested": "[1.15.0, )", + "resolved": "1.15.0", + "contentHash": "FbU0El+EEjdpuIX4iDbeS7ki1uzpJPx8vbqOzEtqnl1GZeAGJfq+jCbxeJL2y0EPnUNk8dRnnqR2xnYXg9Tf+g==" + }, + "System.Text.Json": { + "type": "Direct", + "requested": "[10.0.14, 10.0.14]", + "resolved": "10.0.14", + "contentHash": "JSSLGJTJJDvS76VnLdY1X289rFcHuYApk7QGw0hCoP5wVR1mk7BvJbOYxQLXq4x1qK/Ml9OHa/AKaAbBVCfSSQ==", + "dependencies": { + "Microsoft.Bcl.AsyncInterfaces": "10.0.14", + "System.Buffers": "4.6.1", + "System.IO.Pipelines": "10.0.14", + "System.Memory": "4.6.3", + "System.Runtime.CompilerServices.Unsafe": "6.1.2", + "System.Text.Encodings.Web": "10.0.14", + "System.Threading.Tasks.Extensions": "4.6.3", + "System.ValueTuple": "4.6.2" } }, "Humanizer.Core": { "type": "Transitive", "resolved": "3.0.10", - "contentHash": "yZIhtw8sYuvsONzQbZxWpR60tMWYHXoo0DL6nyOqSFiU5POjBTSEyWFpTQtJEZuy+oqiYTXKXY/Mjx7KnqIQFw==" + "contentHash": "yZIhtw8sYuvsONzQbZxWpR60tMWYHXoo0DL6nyOqSFiU5POjBTSEyWFpTQtJEZuy+oqiYTXKXY/Mjx7KnqIQFw==", + "dependencies": { + "System.Collections.Immutable": "9.0.10", + "System.ComponentModel.Annotations": "5.0.0", + "System.Memory": "4.6.3" + } }, "Json.More.Net": { "type": "Transitive", "resolved": "3.0.1", - "contentHash": "fRctF2J2SILYG6wqP21drmeEODmCVkVQ/b3MndDu2fT1swfySyUgq7ePCk+aENGlDcIm05fyfjh9vcuqDEfv3w==" + "contentHash": "fRctF2J2SILYG6wqP21drmeEODmCVkVQ/b3MndDu2fT1swfySyUgq7ePCk+aENGlDcIm05fyfjh9vcuqDEfv3w==", + "dependencies": { + "System.Collections.Immutable": "10.0.5", + "System.Text.Json": "10.0.5" + } }, "JsonPointer.Net": { "type": "Transitive", @@ -45,51 +69,99 @@ "JsonPointer.Net": "7.0.2" } }, - "SharpGen.Runtime": { + "Microsoft.Bcl.AsyncInterfaces": { "type": "Transitive", - "resolved": "2.4.2-beta", - "contentHash": "niTtWAUov1F7wZGAlVeEvW+Tnqvg5yTmhI7rxmYu2Utoyu2TbC9tWWpUpMs0PQg5lu5svoYpCAztNjxCqMFP/w==" - }, - "SharpGen.Runtime.COM": { - "type": "Transitive", - "resolved": "2.4.2-beta", - "contentHash": "9lxDFMiepqo3lJQzMSjECCIONeCc2f3Drokgj6HtrTLZcJSftNgcLbD6/iXYj2iphkwgrZb1oLsDOZxoFZkawQ==", + "resolved": "10.0.14", + "contentHash": "HCu9NbiXDh9++j4eRNRHCOiKPw/7I5UEJlFIRaDM3v0+ttZaH8p8rjxSWfNgP2cGv5JAa4EZnmc/nlcUOTFlpA==", "dependencies": { - "SharpGen.Runtime": "2.4.2-beta" + "System.Threading.Tasks.Extensions": "4.6.3" } }, - "Vortice.DirectX": { + "Microsoft.NETFramework.ReferenceAssemblies.net48": { "type": "Transitive", - "resolved": "3.8.3", - "contentHash": "nKwSavv0w5rDF7prSefqAVPDcTyqrfZxKFMVfttiXPfm62VdA/1d+b3PhCZpW4xO7jXczXDwjQdWgD1zGsvM8w==", + "resolved": "1.0.3", + "contentHash": "zMk4D+9zyiEWByyQ7oPImPN/Jhpj166Ky0Nlla4eXlNL8hI/BtSJsgR8Inldd4NNpIAH3oh8yym0W2DrhXdSLQ==" + }, + "System.Buffers": { + "type": "Transitive", + "resolved": "4.6.1", + "contentHash": "N8GXpmiLMtljq7gwvyS+1QvKT/W2J8sNAvx+HVg4NGmsG/H+2k/y9QI23auLJRterrzCiDH+IWAw4V/GPwsMlw==" + }, + "System.Collections.Immutable": { + "type": "Transitive", + "resolved": "10.0.5", + "contentHash": "nozrOKfEgfrvvswkCfxaumY68RA/x1F3ZYwtwRvva8ul91NCnUzb6MKpl5/P7u9v/nIagVL4OXXj8d007tucxw==", "dependencies": { - "SharpGen.Runtime": "2.4.2-beta", - "SharpGen.Runtime.COM": "2.4.2-beta", - "Vortice.Mathematics": "2.1.0" + "System.Memory": "4.6.3", + "System.Runtime.CompilerServices.Unsafe": "6.1.2" } }, - "Vortice.DXGI": { + "System.ComponentModel.Annotations": { "type": "Transitive", - "resolved": "3.8.3", - "contentHash": "MbAUnTeQ6WD99ctAdrj5CQO2I7oaax0Kt2eVdWSUj0bYP9Ed0726+s7dIHe4+tqhpmINW/dcPt0mNtc72o+E0w==", + "resolved": "5.0.0", + "contentHash": "dMkqfy2el8A8/I76n2Hi1oBFEbG1SfxD2l5nhwXV3XjlnOmwxJlQbYpJH4W51odnU9sARCSAgv7S3CyAFMkpYg==" + }, + "System.IO.Pipelines": { + "type": "Transitive", + "resolved": "10.0.14", + "contentHash": "pLVClkIC4XfXhcOQXNtNDJl5LYJOS4XAQAdzbqF8rj6sk2zdXO/5uikBsZqgqnAAb07z9Fmtu0sMj3TwEiBtIw==", "dependencies": { - "SharpGen.Runtime": "2.4.2-beta", - "Vortice.DirectX": "3.8.3" + "System.Buffers": "4.6.1", + "System.Memory": "4.6.3", + "System.Threading.Tasks.Extensions": "4.6.3" } }, - "Vortice.Mathematics": { + "System.Memory": { "type": "Transitive", - "resolved": "2.1.0", - "contentHash": "KK+SjNSuKdP+zbavekubi+vaeb1Jo4k87ZF6CMkVWjr6RjJwc8peVtmgzXXDIMy4ZC3ZISyk3llY3q65ISOkBQ==" + "resolved": "4.6.3", + "contentHash": "qdcDOgnFZY40+Q9876JUHnlHu7bosOHX8XISRoH94fwk6hgaeQGSgfZd8srWRZNt5bV9ZW2TljcegDNxsf+96A==", + "dependencies": { + "System.Buffers": "4.6.1", + "System.Numerics.Vectors": "4.6.1", + "System.Runtime.CompilerServices.Unsafe": "6.1.2" + } + }, + "System.Numerics.Vectors": { + "type": "Transitive", + "resolved": "4.6.1", + "contentHash": "sQxefTnhagrhoq2ReR0D/6K0zJcr9Hrd6kikeXsA1I8kOCboTavcUC4r7TSfpKFeE163uMuxZcyfO1mGO3EN8Q==" + }, + "System.Runtime.CompilerServices.Unsafe": { + "type": "Transitive", + "resolved": "6.1.2", + "contentHash": "2hBr6zdbIBTDE3EhK7NSVNdX58uTK6iHW/P/Axmm9sl1xoGSLqDvMtpecn226TNwHByFokYwJmt/aQQNlO5CRw==" + }, + "System.Text.Encodings.Web": { + "type": "Transitive", + "resolved": "10.0.14", + "contentHash": "+aDpFLtsHyft9ZVx9pZQ9MILqwrr8LK1te1L39VMKQYhoYDbs+RUqBhCT3Zydb5ymi2Buo4Cn+3Wi208IxD6rw==", + "dependencies": { + "System.Buffers": "4.6.1", + "System.Memory": "4.6.3", + "System.Runtime.CompilerServices.Unsafe": "6.1.2" + } + }, + "System.Threading.Tasks.Extensions": { + "type": "Transitive", + "resolved": "4.6.3", + "contentHash": "7sCiwilJLYbTZELaKnc7RecBBXWXA+xMLQWZKWawBxYjp6DBlSE3v9/UcvKBvr1vv2tTOhipiogM8rRmxlhrVA==", + "dependencies": { + "System.Runtime.CompilerServices.Unsafe": "6.1.2" + } + }, + "System.ValueTuple": { + "type": "Transitive", + "resolved": "4.6.2", + "contentHash": "yQgmjfFximrNm9LIV3mL6T5MzjeC+epeE5rl4hXxAlYmxby7RM1dPSkIKXk9HNkl6G54h2JHOmLD46+Pey+IRg==" }, "cuaprotocol": { "type": "Project", "dependencies": { - "JsonSchema.Net": "[9.4.0, )" + "JsonSchema.Net": "[9.4.0, )", + "System.Text.Json": "[10.0.14, 10.0.14]" } } }, - "net10.0-windows10.0.19041/win-arm64": {}, - "net10.0-windows10.0.19041/win-x64": {} + ".NETFramework,Version=v4.8/win-x86": {} } -} \ No newline at end of file +} diff --git a/packages/experimental/cua-windows/native/protocol/AccessibilityText.cs b/packages/experimental/cua-windows/native/protocol/AccessibilityText.cs index 35c6acdb75..ded98aa1cd 100644 --- a/packages/experimental/cua-windows/native/protocol/AccessibilityText.cs +++ b/packages/experimental/cua-windows/native/protocol/AccessibilityText.cs @@ -64,9 +64,9 @@ public static class AccessibilityText if (actions.Length != 0) text.Append(" actions=[").Append(string.Join(", ", actions.Select(Quote))).Append(']'); if (details) { - if (!string.IsNullOrEmpty(node.Identifier)) text.Append(" id=").Append(Quote(node.Identifier)); + if (node.Identifier is { Length: > 0 } identifier) text.Append(" id=").Append(Quote(identifier)); if (index.HasValue && node.Bounds is { } bounds) - text.Append(" bounds=[").Append(string.Join(',', new[] { bounds.X, bounds.Y, bounds.Width, bounds.Height } + text.Append(" bounds=[").Append(string.Join(",", new[] { bounds.X, bounds.Y, bounds.Width, bounds.Height } .Select(number => number.ToString("G", CultureInfo.InvariantCulture)))).Append(']'); } return text.ToString(); diff --git a/packages/experimental/cua-windows/native/protocol/CuaProtocol.csproj b/packages/experimental/cua-windows/native/protocol/CuaProtocol.csproj index 353ac1afa7..adab284210 100644 --- a/packages/experimental/cua-windows/native/protocol/CuaProtocol.csproj +++ b/packages/experimental/cua-windows/native/protocol/CuaProtocol.csproj @@ -1,10 +1,9 @@ - net10.0 + net48 enable enable true - win-x64;win-arm64 false diff --git a/packages/experimental/cua-windows/native/protocol/KeyChord.cs b/packages/experimental/cua-windows/native/protocol/KeyChord.cs index 74d375ab35..9c0e307d00 100644 --- a/packages/experimental/cua-windows/native/protocol/KeyChord.cs +++ b/packages/experimental/cua-windows/native/protocol/KeyChord.cs @@ -6,10 +6,10 @@ public sealed record KeyChord(string Key, string[] Modifiers) { if (text.Length == 0) throw new NativeFailure("INVALID_ARGUMENT", "A key name is required"); var plus = text == "+" || text.EndsWith("++", StringComparison.Ordinal); - var parts = plus ? text[..^1].TrimEnd('+').Split('+', StringSplitOptions.RemoveEmptyEntries) : text.Split('+'); + var parts = plus ? text[..^1].TrimEnd('+').Split(new[] { '+' }, StringSplitOptions.RemoveEmptyEntries) : text.Split('+'); var key = plus ? "+" : parts[^1]; if (key.Length == 0) throw new NativeFailure("INVALID_ARGUMENT", "A key chord must end with a key"); - var modifiers = (plus ? parts : parts[..^1]).Concat(extra).Select(NormalizeModifier).Distinct().ToArray(); + var modifiers = (plus ? parts : parts.Take(parts.Length - 1)).Concat(extra).Select(NormalizeModifier).Distinct().ToArray(); return new(key, modifiers); } diff --git a/packages/experimental/cua-windows/native/protocol/NativeRequest.cs b/packages/experimental/cua-windows/native/protocol/NativeRequest.cs index 8cdd6a3293..86c1029f15 100644 --- a/packages/experimental/cua-windows/native/protocol/NativeRequest.cs +++ b/packages/experimental/cua-windows/native/protocol/NativeRequest.cs @@ -80,7 +80,7 @@ public sealed class FrameReader(Stream stream) { if (start == end) { - end = await stream.ReadAsync(buffer, cancellation); + end = await stream.ReadAsync(buffer, 0, buffer.Length, cancellation); start = 0; if (end == 0) { diff --git a/packages/experimental/cua-windows/native/protocol/packages.lock.json b/packages/experimental/cua-windows/native/protocol/packages.lock.json index 4118720b93..2edb96ae39 100644 --- a/packages/experimental/cua-windows/native/protocol/packages.lock.json +++ b/packages/experimental/cua-windows/native/protocol/packages.lock.json @@ -1,7 +1,7 @@ { "version": 1, "dependencies": { - "net10.0": { + ".NETFramework,Version=v4.8": { "JsonSchema.Net": { "type": "Direct", "requested": "[9.4.0, )", @@ -11,15 +11,55 @@ "JsonPointer.Net": "7.0.2" } }, + "Microsoft.NETFramework.ReferenceAssemblies": { + "type": "Direct", + "requested": "[1.0.3, )", + "resolved": "1.0.3", + "contentHash": "vUc9Npcs14QsyOD01tnv/m8sQUnGTGOw1BCmKcv77LBJY7OxhJ+zJF7UD/sCL3lYNFuqmQEVlkfS4Quif6FyYg==", + "dependencies": { + "Microsoft.NETFramework.ReferenceAssemblies.net48": "1.0.3" + } + }, + "PolySharp": { + "type": "Direct", + "requested": "[1.15.0, )", + "resolved": "1.15.0", + "contentHash": "FbU0El+EEjdpuIX4iDbeS7ki1uzpJPx8vbqOzEtqnl1GZeAGJfq+jCbxeJL2y0EPnUNk8dRnnqR2xnYXg9Tf+g==" + }, + "System.Text.Json": { + "type": "Direct", + "requested": "[10.0.14, 10.0.14]", + "resolved": "10.0.14", + "contentHash": "JSSLGJTJJDvS76VnLdY1X289rFcHuYApk7QGw0hCoP5wVR1mk7BvJbOYxQLXq4x1qK/Ml9OHa/AKaAbBVCfSSQ==", + "dependencies": { + "Microsoft.Bcl.AsyncInterfaces": "10.0.14", + "System.Buffers": "4.6.1", + "System.IO.Pipelines": "10.0.14", + "System.Memory": "4.6.3", + "System.Runtime.CompilerServices.Unsafe": "6.1.2", + "System.Text.Encodings.Web": "10.0.14", + "System.Threading.Tasks.Extensions": "4.6.3", + "System.ValueTuple": "4.6.2" + } + }, "Humanizer.Core": { "type": "Transitive", "resolved": "3.0.10", - "contentHash": "yZIhtw8sYuvsONzQbZxWpR60tMWYHXoo0DL6nyOqSFiU5POjBTSEyWFpTQtJEZuy+oqiYTXKXY/Mjx7KnqIQFw==" + "contentHash": "yZIhtw8sYuvsONzQbZxWpR60tMWYHXoo0DL6nyOqSFiU5POjBTSEyWFpTQtJEZuy+oqiYTXKXY/Mjx7KnqIQFw==", + "dependencies": { + "System.Collections.Immutable": "9.0.10", + "System.ComponentModel.Annotations": "5.0.0", + "System.Memory": "4.6.3" + } }, "Json.More.Net": { "type": "Transitive", "resolved": "3.0.1", - "contentHash": "fRctF2J2SILYG6wqP21drmeEODmCVkVQ/b3MndDu2fT1swfySyUgq7ePCk+aENGlDcIm05fyfjh9vcuqDEfv3w==" + "contentHash": "fRctF2J2SILYG6wqP21drmeEODmCVkVQ/b3MndDu2fT1swfySyUgq7ePCk+aENGlDcIm05fyfjh9vcuqDEfv3w==", + "dependencies": { + "System.Collections.Immutable": "10.0.5", + "System.Text.Json": "10.0.5" + } }, "JsonPointer.Net": { "type": "Transitive", @@ -29,9 +69,92 @@ "Humanizer.Core": "3.0.10", "Json.More.Net": "3.0.1" } + }, + "Microsoft.Bcl.AsyncInterfaces": { + "type": "Transitive", + "resolved": "10.0.14", + "contentHash": "HCu9NbiXDh9++j4eRNRHCOiKPw/7I5UEJlFIRaDM3v0+ttZaH8p8rjxSWfNgP2cGv5JAa4EZnmc/nlcUOTFlpA==", + "dependencies": { + "System.Threading.Tasks.Extensions": "4.6.3" + } + }, + "Microsoft.NETFramework.ReferenceAssemblies.net48": { + "type": "Transitive", + "resolved": "1.0.3", + "contentHash": "zMk4D+9zyiEWByyQ7oPImPN/Jhpj166Ky0Nlla4eXlNL8hI/BtSJsgR8Inldd4NNpIAH3oh8yym0W2DrhXdSLQ==" + }, + "System.Buffers": { + "type": "Transitive", + "resolved": "4.6.1", + "contentHash": "N8GXpmiLMtljq7gwvyS+1QvKT/W2J8sNAvx+HVg4NGmsG/H+2k/y9QI23auLJRterrzCiDH+IWAw4V/GPwsMlw==" + }, + "System.Collections.Immutable": { + "type": "Transitive", + "resolved": "10.0.5", + "contentHash": "nozrOKfEgfrvvswkCfxaumY68RA/x1F3ZYwtwRvva8ul91NCnUzb6MKpl5/P7u9v/nIagVL4OXXj8d007tucxw==", + "dependencies": { + "System.Memory": "4.6.3", + "System.Runtime.CompilerServices.Unsafe": "6.1.2" + } + }, + "System.ComponentModel.Annotations": { + "type": "Transitive", + "resolved": "5.0.0", + "contentHash": "dMkqfy2el8A8/I76n2Hi1oBFEbG1SfxD2l5nhwXV3XjlnOmwxJlQbYpJH4W51odnU9sARCSAgv7S3CyAFMkpYg==" + }, + "System.IO.Pipelines": { + "type": "Transitive", + "resolved": "10.0.14", + "contentHash": "pLVClkIC4XfXhcOQXNtNDJl5LYJOS4XAQAdzbqF8rj6sk2zdXO/5uikBsZqgqnAAb07z9Fmtu0sMj3TwEiBtIw==", + "dependencies": { + "System.Buffers": "4.6.1", + "System.Memory": "4.6.3", + "System.Threading.Tasks.Extensions": "4.6.3" + } + }, + "System.Memory": { + "type": "Transitive", + "resolved": "4.6.3", + "contentHash": "qdcDOgnFZY40+Q9876JUHnlHu7bosOHX8XISRoH94fwk6hgaeQGSgfZd8srWRZNt5bV9ZW2TljcegDNxsf+96A==", + "dependencies": { + "System.Buffers": "4.6.1", + "System.Numerics.Vectors": "4.6.1", + "System.Runtime.CompilerServices.Unsafe": "6.1.2" + } + }, + "System.Numerics.Vectors": { + "type": "Transitive", + "resolved": "4.6.1", + "contentHash": "sQxefTnhagrhoq2ReR0D/6K0zJcr9Hrd6kikeXsA1I8kOCboTavcUC4r7TSfpKFeE163uMuxZcyfO1mGO3EN8Q==" + }, + "System.Runtime.CompilerServices.Unsafe": { + "type": "Transitive", + "resolved": "6.1.2", + "contentHash": "2hBr6zdbIBTDE3EhK7NSVNdX58uTK6iHW/P/Axmm9sl1xoGSLqDvMtpecn226TNwHByFokYwJmt/aQQNlO5CRw==" + }, + "System.Text.Encodings.Web": { + "type": "Transitive", + "resolved": "10.0.14", + "contentHash": "+aDpFLtsHyft9ZVx9pZQ9MILqwrr8LK1te1L39VMKQYhoYDbs+RUqBhCT3Zydb5ymi2Buo4Cn+3Wi208IxD6rw==", + "dependencies": { + "System.Buffers": "4.6.1", + "System.Memory": "4.6.3", + "System.Runtime.CompilerServices.Unsafe": "6.1.2" + } + }, + "System.Threading.Tasks.Extensions": { + "type": "Transitive", + "resolved": "4.6.3", + "contentHash": "7sCiwilJLYbTZELaKnc7RecBBXWXA+xMLQWZKWawBxYjp6DBlSE3v9/UcvKBvr1vv2tTOhipiogM8rRmxlhrVA==", + "dependencies": { + "System.Runtime.CompilerServices.Unsafe": "6.1.2" + } + }, + "System.ValueTuple": { + "type": "Transitive", + "resolved": "4.6.2", + "contentHash": "yQgmjfFximrNm9LIV3mL6T5MzjeC+epeE5rl4hXxAlYmxby7RM1dPSkIKXk9HNkl6G54h2JHOmLD46+Pey+IRg==" } - }, - "net10.0/win-arm64": {}, - "net10.0/win-x64": {} + } } -} +} \ No newline at end of file diff --git a/packages/experimental/cua-windows/native/src/CaptureAdmission.cs b/packages/experimental/cua-windows/native/src/CaptureAdmission.cs deleted file mode 100644 index 5014f34f85..0000000000 --- a/packages/experimental/cua-windows/native/src/CaptureAdmission.cs +++ /dev/null @@ -1,34 +0,0 @@ -// The native operation owns its capture slot until cleanup finishes, independently of the caller's await. -using DeepSeek.Cua.Protocol; - -namespace DeepSeek.Cua.Windows; - -internal sealed class CaptureAdmission -{ - private readonly object gate = new(); - private Task? pending; - - internal Task Start(Func> operation) - { - lock (gate) - { - if (pending is { IsCompleted: false }) - throw new NativeFailure("CAPTURE_BUSY", "The previous Windows capture is still releasing its resources; UIA and input remain available"); - pending = operation(); - _ = pending.ContinueWith(completed => { _ = completed.Exception; }, CancellationToken.None, - TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); - return pending; - } - } - - internal async Task Join() - { - Task? active; - lock (gate) active = pending; - if (active is not null) - { - try { await active; } - catch (Exception error) { _ = error; /* The requesting connection owns the capture failure. */ } - } - } -} diff --git a/packages/experimental/cua-windows/native/src/ClipboardPaste.cs b/packages/experimental/cua-windows/native/src/ClipboardPaste.cs index 6244fc9fa7..ad166b5bd2 100644 --- a/packages/experimental/cua-windows/native/src/ClipboardPaste.cs +++ b/packages/experimental/cua-windows/native/src/ClipboardPaste.cs @@ -10,7 +10,7 @@ internal sealed class ClipboardPaste { private sealed class Transaction(ServiceControl control, int targetPid, uint format, byte[] payload, List<(uint Format, byte[] Data)> previous, uint originalSequence) { - internal readonly TaskCompletionSource Consumed = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource Consumed = new(TaskCreationOptions.RunContinuationsAsynchronously); private uint sequence = originalSequence; private bool replaced; private bool restoring; @@ -68,7 +68,7 @@ internal sealed class ClipboardPaste rendered = true; sequence = Win32.GetClipboardSequenceNumber(); if (changed) Consumed.TrySetException(new NativeFailure("CLIPBOARD_CHANGED", "Another writer changed the clipboard during paste")); - else if (message == 0x0305) Consumed.TrySetResult(); + else if (message == 0x0305) Consumed.TrySetResult(null); } catch (Exception error) { Consumed.TrySetException(error); } finally { if (opened) Win32.CloseClipboard(); } diff --git a/packages/experimental/cua-windows/native/src/DesktopExecutor.cs b/packages/experimental/cua-windows/native/src/DesktopExecutor.cs index 7e9b33a9e0..88dd5c0aef 100644 --- a/packages/experimental/cua-windows/native/src/DesktopExecutor.cs +++ b/packages/experimental/cua-windows/native/src/DesktopExecutor.cs @@ -14,7 +14,7 @@ internal sealed class ClientState internal void Clear() { foreach (var app in Apps.Values) app.Dispose(); Apps.Clear(); Launches.Clear(); } } -internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta, int graceMs) : IAsyncDisposable +internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IAsyncDisposable { private readonly WindowCapture capture = new(); private readonly ClipboardPaste clipboard = new(); @@ -75,13 +75,13 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta, int var context = new RequestContext(config, cancellation, mta, sta); context.Check(); var parameters = request.Params; - if (request.Method == "permissionStatus") return DesktopSession.Status(await capture.IsSupported(cancellation)); + if (request.Method == "permissionStatus") return DesktopSession.Status(false); if (request.Method == "applicationIcons") return await sta.Invoke(_ => Applications.Icons(parameters, context), cancellation); if (request.Method == "getCapabilities") { var locked = DesktopSession.Locked(); return new { permissions = new { accessibility = locked == false, - screenRecording = locked == false && await capture.IsSupported(cancellation) }, + screenRecording = false }, sessionLocked = locked }; } if (request.Method is "requestPermission" or "openPermissionSettings") @@ -255,10 +255,9 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta, int finally { queue.Release(); } } - public async ValueTask DisposeAsync() + public ValueTask DisposeAsync() { - try { await capture.DisposeAsync().AsTask().WaitAsync(TimeSpan.FromMilliseconds(graceMs)); } - catch (TimeoutException) { NativeServer.Fatal("NATIVE_CLEANUP", "The idle desktop service could not release capture resources"); } queue.Dispose(); + return default; } } diff --git a/packages/experimental/cua-windows/native/src/Dispatchers.cs b/packages/experimental/cua-windows/native/src/Dispatchers.cs index 3bc7785457..a8d4fb180e 100644 --- a/packages/experimental/cua-windows/native/src/Dispatchers.cs +++ b/packages/experimental/cua-windows/native/src/Dispatchers.cs @@ -31,8 +31,8 @@ internal sealed record NativeConfig(int MaxRequestBytes, int MaxResponseBytes, i internal sealed class MtaDispatcher : IAsyncDisposable { private readonly BlockingCollection queue = new(); - private readonly TaskCompletionSource stopped = new(TaskCreationOptions.RunContinuationsAsynchronously); - private readonly TaskCompletionSource ready = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource stopped = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource ready = new(TaskCreationOptions.RunContinuationsAsynchronously); private readonly Thread thread; internal MtaDispatcher() @@ -45,11 +45,11 @@ internal sealed class MtaDispatcher : IAsyncDisposable Marshal.ThrowExceptionForHR(Win32.RoInitialize(1)); initialized = true; Win32.SetThreadDpiAwarenessContext(-4); - ready.SetResult(); + ready.SetResult(null); foreach (var work in queue.GetConsumingEnumerable()) work(); } catch (Exception error) { ready.TrySetException(error); } - finally { if (initialized) Win32.RoUninitialize(); stopped.TrySetResult(); } + finally { if (initialized) Win32.RoUninitialize(); stopped.TrySetResult(null); } }) { IsBackground = true, Name = "dsh-cua-uia" }; thread.SetApartmentState(ApartmentState.MTA); thread.Start(); @@ -93,7 +93,7 @@ internal sealed class ServiceControl : Forms.Control internal sealed class StaDispatcher : IAsyncDisposable { private readonly TaskCompletionSource ready = new(TaskCreationOptions.RunContinuationsAsynchronously); - private readonly TaskCompletionSource stopped = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource stopped = new(TaskCreationOptions.RunContinuationsAsynchronously); private readonly ConcurrentDictionary epochs = new(); private readonly Thread thread; private Win32.WinEvent? windowEvents; @@ -122,7 +122,7 @@ internal sealed class StaDispatcher : IAsyncDisposable finally { if (hook != 0) Win32.UnhookWinEvent(hook); - stopped.TrySetResult(); + stopped.TrySetResult(null); } }) { IsBackground = true, Name = "dsh-cua-clipboard" }; thread.SetApartmentState(ApartmentState.STA); diff --git a/packages/experimental/cua-windows/native/src/NativeServer.cs b/packages/experimental/cua-windows/native/src/NativeServer.cs index 866cc0588b..2821df97ea 100644 --- a/packages/experimental/cua-windows/native/src/NativeServer.cs +++ b/packages/experimental/cua-windows/native/src/NativeServer.cs @@ -33,7 +33,7 @@ internal static class NativeServer await using var sta = new StaDispatcher(); await sta.Invoke(() => { }, lifetime.Token); await mta.Invoke(() => true, lifetime.Token); - await using var executor = new DesktopExecutor(mta, sta, graceMs); + await using var executor = new DesktopExecutor(mta, sta); var clients = new ConcurrentDictionary(); NamedPipeServerStream? listener = NewPipe(pipeName); var membership = new object(); @@ -162,6 +162,7 @@ internal static class NativeServer try { response = new { id = request.Id, result = await operation }; } catch (OperationCanceledException) { response = Failure(request.Id, "NATIVE_CANCELLED", "Native operation cancelled; observe before deciding on further input"); } catch (NativeFailure error) { response = Failure(request.Id, error.Code, error.Message); } + catch (NotImplementedException error) { response = Failure(request.Id, "NOT_IMPLEMENTED", error.Message); } catch (ElementNotAvailableException) { response = Failure(request.Id, "STALE_SNAPSHOT", "An accessibility element disappeared; read fresh state"); } catch (ElementNotEnabledException) { response = Failure(request.Id, "ELEMENT_DISABLED", "The selected control is disabled"); } catch (UnauthorizedAccessException) { response = Failure(request.Id, "PERMISSION_DENIED", "Windows refused access to the selected application"); } diff --git a/packages/experimental/cua-windows/native/src/WindowCapture.cs b/packages/experimental/cua-windows/native/src/WindowCapture.cs index b72a219b3f..4a3e4f6e5f 100644 --- a/packages/experimental/cua-windows/native/src/WindowCapture.cs +++ b/packages/experimental/cua-windows/native/src/WindowCapture.cs @@ -1,243 +1,7 @@ -// Windows Graphics Capture returns the selected window even when another window covers it. -using System.Drawing; -using System.Drawing.Imaging; -using System.Runtime.InteropServices; -using DeepSeek.Cua.Protocol; -using Vortice.Direct3D; -using Vortice.Direct3D11; -using Vortice.DXGI; -using WinRT; -using global::Windows.Graphics.Capture; -using global::Windows.Graphics.DirectX; -using global::Windows.Graphics.DirectX.Direct3D11; - namespace DeepSeek.Cua.Windows; -internal sealed class WindowCapture : IAsyncDisposable +internal sealed class WindowCapture { - private readonly MtaDispatcher dispatcher = new(); - private readonly CaptureAdmission admission = new(); - private ID3D11Device? device; - private ID3D11DeviceContext? immediate; - private IDirect3DDevice? captureDevice; - - internal Task IsSupported(CancellationToken cancellation) - => dispatcher.Invoke(GraphicsCaptureSession.IsSupported, cancellation); - - private void EnsureDevice() - { - if (device is not null) return; - var created = D3D11.D3D11CreateDevice(DriverType.Hardware, DeviceCreationFlags.BgraSupport); - try - { - using var dxgi = created.QueryInterface(); - Marshal.ThrowExceptionForHR(CreateDirect3D11DeviceFromDXGIDevice(dxgi.NativePointer, out var pointer)); - try { captureDevice = MarshalInterface.FromAbi(pointer); } - finally { Marshal.Release(pointer); } - immediate = created.ImmediateContext; - device = created; - } - catch { created.Dispose(); throw; } - } - - internal async Task Capture(AppState app, WindowState window, RequestContext context) - { - if (!await IsSupported(context.Cancellation)) throw new NativeFailure("UNSUPPORTED", "Windows Graphics Capture is unavailable on this desktop"); - var geometry = window.Geometry(app, context); - if (!window.IsOnScreen()) throw new NativeFailure("WINDOW_NOT_VISIBLE", "Restore the selected window with show and observe again before capturing"); - try - { - var operation = admission.Start(() => CaptureOwned(window.Handle, geometry, context)); - var data = await operation.WaitAsync(context.Cancellation); - var current = window.Geometry(app, context); - if (current.Pixels.Width != geometry.Pixels.Width || current.Pixels.Height != geometry.Pixels.Height || current.Dpi != geometry.Dpi) - throw new NativeFailure("WINDOW_CHANGED", "The window changed during capture; observe again"); - DesktopSession.RequireInteractive(); - window.Observe(current); - return new { mimeType = "image/png", data = Convert.ToBase64String(data), pixelWidth = geometry.Pixels.Width, - pixelHeight = geometry.Pixels.Height, windowId = window.Id, bounds = current.Bounds, coordinateSpace = "window-pixels" }; - } - catch (COMException error) - { - throw new NativeFailure(error.HResult == unchecked((int)0x80070005) ? "PERMISSION_DENIED" : "CAPTURE_FAILED", - $"Windows refused the selected window capture (0x{error.HResult:X8}); restore the window and read fresh state"); - } - } - - private async Task CaptureOwned(nint window, WindowGeometry geometry, RequestContext context) - { - CaptureRequest? request = null; - try - { - await dispatcher.Invoke(() => - { - EnsureDevice(); - request = new CaptureRequest(this, window, geometry, context); - return true; - }, context.Cancellation); - return await request!.Result.WaitAsync(context.Cancellation); - } - finally - { - if (request is not null) await dispatcher.Invoke(() => { request.Dispose(); return true; }, CancellationToken.None); - } - } - - private sealed class CaptureRequest : IDisposable - { - private readonly object gate = new(); - private readonly TaskCompletionSource result = new(TaskCreationOptions.RunContinuationsAsynchronously); - private readonly WindowCapture owner; - private readonly WindowGeometry geometry; - private readonly RequestContext context; - private readonly GraphicsCaptureItem item; - private Direct3D11CaptureFramePool? pool; - private GraphicsCaptureSession? session; - private bool disposed; - - internal Task Result => result.Task; - - internal CaptureRequest(WindowCapture owner, nint window, WindowGeometry geometry, RequestContext context) - { - this.owner = owner; this.geometry = geometry; this.context = context; - item = ItemForWindow(window); - if (item.Size.Width != geometry.Pixels.Width || item.Size.Height != geometry.Pixels.Height) - throw new NativeFailure("WINDOW_CHANGED", "Windows capture bounds differ from the observed window; restore it and observe again"); - try - { - pool = Direct3D11CaptureFramePool.CreateFreeThreaded(owner.captureDevice!, DirectXPixelFormat.B8G8R8A8UIntNormalized, 2, item.Size); - pool.FrameArrived += Frame; - item.Closed += Closed; - session = pool.CreateCaptureSession(item); - session.IsCursorCaptureEnabled = false; - session.StartCapture(); - } - catch { Dispose(); throw; } - } - - private void Closed(GraphicsCaptureItem sender, object args) => result.TrySetException(new NativeFailure("WINDOW_CHANGED", "The selected window closed during capture")); - - private void Frame(Direct3D11CaptureFramePool sender, object args) - { - lock (gate) - { - if (disposed || result.Task.IsCompleted) return; - try - { - context.Check(); - using var frame = sender.TryGetNextFrame(); - if (frame is null) return; - if (frame.ContentSize.Width != geometry.Pixels.Width || frame.ContentSize.Height != geometry.Pixels.Height) - throw new NativeFailure("WINDOW_CHANGED", "The capture frame dimensions changed"); - result.TrySetResult(owner.Encode(frame.Surface, geometry.Pixels.Width, geometry.Pixels.Height, context)); - } - catch (Exception error) { result.TrySetException(error); } - } - } - - public void Dispose() - { - lock (gate) - { - if (disposed) return; - disposed = true; - item.Closed -= Closed; - if (pool is not null) pool.FrameArrived -= Frame; - } - // Native disposal can wait for callbacks; queued callbacks must be able to observe disposed. - session?.Dispose(); - pool?.Dispose(); - } - } - - private byte[] Encode(IDirect3DSurface surface, int width, int height, RequestContext context) - { - var access = surface.As(); - var textureId = typeof(ID3D11Texture2D).GUID; - Marshal.ThrowExceptionForHR(access.GetInterface(ref textureId, out var pointer)); - using var texture = new ID3D11Texture2D(pointer); - if (texture.Description.Width != width || texture.Description.Height != height || texture.Description.Format != Format.B8G8R8A8_UNorm) - throw new NativeFailure("WINDOW_CHANGED", "The captured texture differs from the selected window geometry"); - var description = new Texture2DDescription(Format.B8G8R8A8_UNorm, (uint)width, (uint)height, - mipLevels: 1, bindFlags: BindFlags.None, usage: ResourceUsage.Staging, cpuAccessFlags: CpuAccessFlags.Read); - using var staging = device!.CreateTexture2D(description); - immediate!.CopyResource(staging, texture); - var mapped = immediate.Map(staging, 0, MapMode.Read); - using var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb); - try - { - var pixels = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); - try - { - var row = new byte[checked(width * 4)]; - for (var y = 0; y < height; y++) - { - context.Check(); - Marshal.Copy(mapped.DataPointer + checked(y * (int)mapped.RowPitch), row, 0, row.Length); - Marshal.Copy(row, 0, pixels.Scan0 + y * pixels.Stride, row.Length); - } - } - finally { bitmap.UnlockBits(pixels); } - } - finally { immediate.Unmap(staging, 0); } - context.Check(); - using var output = new MemoryStream(); - bitmap.Save(output, ImageFormat.Png); - if (output.Length * 4 / 3 > context.Config.MaxResponseBytes) - throw new NativeFailure("NATIVE_RESPONSE_LIMIT", "The screenshot exceeds the response byte limit"); - return output.ToArray(); - } - - private static GraphicsCaptureItem ItemForWindow(nint window) - { - const string className = "Windows.Graphics.Capture.GraphicsCaptureItem"; - Marshal.ThrowExceptionForHR(WindowsCreateString(className, className.Length, out var name)); - nint factoryPointer = 0; - object? factory = null; - try - { - var factoryId = typeof(IGraphicsCaptureItemInterop).GUID; - Marshal.ThrowExceptionForHR(RoGetActivationFactory(name, ref factoryId, out factoryPointer)); - factory = Marshal.GetObjectForIUnknown(factoryPointer); - var itemId = new Guid("79C3F95B-31F7-4EC2-A464-632EF5D30760"); - Marshal.ThrowExceptionForHR(((IGraphicsCaptureItemInterop)factory).CreateForWindow(window, ref itemId, out var item)); - try { return MarshalInterface.FromAbi(item); } - finally { Marshal.Release(item); } - } - finally - { - if (factory is not null) Marshal.FinalReleaseComObject(factory); - if (factoryPointer != 0) Marshal.Release(factoryPointer); - WindowsDeleteString(name); - } - } - - public async ValueTask DisposeAsync() - { - await admission.Join(); - await dispatcher.Invoke(() => - { - captureDevice?.Dispose(); - immediate?.Dispose(); - device?.Dispose(); - return true; - }, CancellationToken.None); - await dispatcher.DisposeAsync(); - } - - [ComImport, Guid("3628E81B-3CAC-4C60-B7F4-23CE0E0C3356"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - private interface IGraphicsCaptureItemInterop - { - [PreserveSig] int CreateForWindow(nint window, ref Guid id, out nint item); - [PreserveSig] int CreateForMonitor(nint monitor, ref Guid id, out nint item); - } - [ComImport, Guid("A9B3D012-3DF2-4EE3-B8D1-8695F457D3C1"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - private interface IDirect3DDxgiInterfaceAccess - { - [PreserveSig] int GetInterface(ref Guid id, out nint value); - } - [DllImport("d3d11.dll", ExactSpelling = true)] private static extern int CreateDirect3D11DeviceFromDXGIDevice(nint device, out nint result); - [DllImport("combase.dll", CharSet = CharSet.Unicode)] private static extern int WindowsCreateString(string source, int length, out nint value); - [DllImport("combase.dll")] private static extern int WindowsDeleteString(nint value); - [DllImport("combase.dll")] private static extern int RoGetActivationFactory(nint name, ref Guid id, out nint value); + internal Task Capture(AppState app, WindowState window, RequestContext context) + => throw new NotImplementedException("Windows screenshots are not implemented."); } diff --git a/packages/experimental/cua-windows/native/tests/Program.cs b/packages/experimental/cua-windows/native/tests/Program.cs index b12458997a..d352580306 100644 --- a/packages/experimental/cua-windows/native/tests/Program.cs +++ b/packages/experimental/cua-windows/native/tests/Program.cs @@ -1,7 +1,6 @@ // Portable checks exercise admission, framing, text offsets, and model-visible formatting. using System.Text; using DeepSeek.Cua.Protocol; -using DeepSeek.Cua.Windows; var checks = 0; void Check(bool condition, string message) @@ -75,22 +74,4 @@ Check(!AccessibilityText.Retain(new() { Role = "AXGroup" }), "Empty structural c Check(AccessibilityText.Retain(new() { Role = "AXGroup", Actions = ["Copy"] }), "Actionable containers retain their row"); Check(AccessibilityText.Format(new() { Role = "AXTextArea", Value = "abc", HasValue = true, HasSelection = true, Selection = new(2, 5) }, 0, false) .Contains("selection=unavailable"), "Out-of-range selections do not describe valid text"); -var captures = new CaptureAdmission(); -var cleanup = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); -var ownedCapture = captures.Start(() => cleanup.Task); -using var cancelled = new CancellationTokenSource(); -cancelled.Cancel(); -try { await ownedCapture.WaitAsync(cancelled.Token); throw new Exception("Cancelled capture caller remained attached"); } -catch (OperationCanceledException) { checks++; } -Refuses(() => captures.Start(() => Task.FromResult(new byte[] { 2 })), "CAPTURE_BUSY"); -var joined = captures.Join(); -Check(!joined.IsCompleted, "Native cleanup retains ownership after its caller stops waiting"); -cleanup.SetResult([1]); -await joined; -Check((await captures.Start(() => Task.FromResult(new byte[] { 2 })))[0] == 2, "Completed cleanup admits a fresh capture"); -var failed = captures.Start(() => Task.FromException(new NativeFailure("CAPTURE_FAILED", "device lost"))); -try { await failed; throw new Exception("Capture error disappeared"); } -catch (NativeFailure failure) { Check(failure.Code == "CAPTURE_FAILED", "Capture failure remains attached to its requesting connection"); } -await captures.Join(); -Check((await captures.Start(() => Task.FromResult(new byte[] { 3 })))[0] == 3, "A settled capture failure does not reserve a permanent slot"); Console.WriteLine($"{checks} portable CUA checks passed"); diff --git a/packages/experimental/cua-windows/native/tests/Protocol.Tests.csproj b/packages/experimental/cua-windows/native/tests/Protocol.Tests.csproj index 9ad2abfcee..99d820c0d3 100644 --- a/packages/experimental/cua-windows/native/tests/Protocol.Tests.csproj +++ b/packages/experimental/cua-windows/native/tests/Protocol.Tests.csproj @@ -1,11 +1,10 @@ Exe - net10.0 + net48 enable enable true - diff --git a/packages/experimental/cua-windows/native/tests/packages.lock.json b/packages/experimental/cua-windows/native/tests/packages.lock.json index f693fbd9af..44acac2f65 100644 --- a/packages/experimental/cua-windows/native/tests/packages.lock.json +++ b/packages/experimental/cua-windows/native/tests/packages.lock.json @@ -1,16 +1,56 @@ { "version": 1, "dependencies": { - "net10.0": { + ".NETFramework,Version=v4.8": { + "Microsoft.NETFramework.ReferenceAssemblies": { + "type": "Direct", + "requested": "[1.0.3, )", + "resolved": "1.0.3", + "contentHash": "vUc9Npcs14QsyOD01tnv/m8sQUnGTGOw1BCmKcv77LBJY7OxhJ+zJF7UD/sCL3lYNFuqmQEVlkfS4Quif6FyYg==", + "dependencies": { + "Microsoft.NETFramework.ReferenceAssemblies.net48": "1.0.3" + } + }, + "PolySharp": { + "type": "Direct", + "requested": "[1.15.0, )", + "resolved": "1.15.0", + "contentHash": "FbU0El+EEjdpuIX4iDbeS7ki1uzpJPx8vbqOzEtqnl1GZeAGJfq+jCbxeJL2y0EPnUNk8dRnnqR2xnYXg9Tf+g==" + }, + "System.Text.Json": { + "type": "Direct", + "requested": "[10.0.14, 10.0.14]", + "resolved": "10.0.14", + "contentHash": "JSSLGJTJJDvS76VnLdY1X289rFcHuYApk7QGw0hCoP5wVR1mk7BvJbOYxQLXq4x1qK/Ml9OHa/AKaAbBVCfSSQ==", + "dependencies": { + "Microsoft.Bcl.AsyncInterfaces": "10.0.14", + "System.Buffers": "4.6.1", + "System.IO.Pipelines": "10.0.14", + "System.Memory": "4.6.3", + "System.Runtime.CompilerServices.Unsafe": "6.1.2", + "System.Text.Encodings.Web": "10.0.14", + "System.Threading.Tasks.Extensions": "4.6.3", + "System.ValueTuple": "4.6.2" + } + }, "Humanizer.Core": { "type": "Transitive", "resolved": "3.0.10", - "contentHash": "yZIhtw8sYuvsONzQbZxWpR60tMWYHXoo0DL6nyOqSFiU5POjBTSEyWFpTQtJEZuy+oqiYTXKXY/Mjx7KnqIQFw==" + "contentHash": "yZIhtw8sYuvsONzQbZxWpR60tMWYHXoo0DL6nyOqSFiU5POjBTSEyWFpTQtJEZuy+oqiYTXKXY/Mjx7KnqIQFw==", + "dependencies": { + "System.Collections.Immutable": "9.0.10", + "System.ComponentModel.Annotations": "5.0.0", + "System.Memory": "4.6.3" + } }, "Json.More.Net": { "type": "Transitive", "resolved": "3.0.1", - "contentHash": "fRctF2J2SILYG6wqP21drmeEODmCVkVQ/b3MndDu2fT1swfySyUgq7ePCk+aENGlDcIm05fyfjh9vcuqDEfv3w==" + "contentHash": "fRctF2J2SILYG6wqP21drmeEODmCVkVQ/b3MndDu2fT1swfySyUgq7ePCk+aENGlDcIm05fyfjh9vcuqDEfv3w==", + "dependencies": { + "System.Collections.Immutable": "10.0.5", + "System.Text.Json": "10.0.5" + } }, "JsonPointer.Net": { "type": "Transitive", @@ -29,12 +69,99 @@ "JsonPointer.Net": "7.0.2" } }, + "Microsoft.Bcl.AsyncInterfaces": { + "type": "Transitive", + "resolved": "10.0.14", + "contentHash": "HCu9NbiXDh9++j4eRNRHCOiKPw/7I5UEJlFIRaDM3v0+ttZaH8p8rjxSWfNgP2cGv5JAa4EZnmc/nlcUOTFlpA==", + "dependencies": { + "System.Threading.Tasks.Extensions": "4.6.3" + } + }, + "Microsoft.NETFramework.ReferenceAssemblies.net48": { + "type": "Transitive", + "resolved": "1.0.3", + "contentHash": "zMk4D+9zyiEWByyQ7oPImPN/Jhpj166Ky0Nlla4eXlNL8hI/BtSJsgR8Inldd4NNpIAH3oh8yym0W2DrhXdSLQ==" + }, + "System.Buffers": { + "type": "Transitive", + "resolved": "4.6.1", + "contentHash": "N8GXpmiLMtljq7gwvyS+1QvKT/W2J8sNAvx+HVg4NGmsG/H+2k/y9QI23auLJRterrzCiDH+IWAw4V/GPwsMlw==" + }, + "System.Collections.Immutable": { + "type": "Transitive", + "resolved": "10.0.5", + "contentHash": "nozrOKfEgfrvvswkCfxaumY68RA/x1F3ZYwtwRvva8ul91NCnUzb6MKpl5/P7u9v/nIagVL4OXXj8d007tucxw==", + "dependencies": { + "System.Memory": "4.6.3", + "System.Runtime.CompilerServices.Unsafe": "6.1.2" + } + }, + "System.ComponentModel.Annotations": { + "type": "Transitive", + "resolved": "5.0.0", + "contentHash": "dMkqfy2el8A8/I76n2Hi1oBFEbG1SfxD2l5nhwXV3XjlnOmwxJlQbYpJH4W51odnU9sARCSAgv7S3CyAFMkpYg==" + }, + "System.IO.Pipelines": { + "type": "Transitive", + "resolved": "10.0.14", + "contentHash": "pLVClkIC4XfXhcOQXNtNDJl5LYJOS4XAQAdzbqF8rj6sk2zdXO/5uikBsZqgqnAAb07z9Fmtu0sMj3TwEiBtIw==", + "dependencies": { + "System.Buffers": "4.6.1", + "System.Memory": "4.6.3", + "System.Threading.Tasks.Extensions": "4.6.3" + } + }, + "System.Memory": { + "type": "Transitive", + "resolved": "4.6.3", + "contentHash": "qdcDOgnFZY40+Q9876JUHnlHu7bosOHX8XISRoH94fwk6hgaeQGSgfZd8srWRZNt5bV9ZW2TljcegDNxsf+96A==", + "dependencies": { + "System.Buffers": "4.6.1", + "System.Numerics.Vectors": "4.6.1", + "System.Runtime.CompilerServices.Unsafe": "6.1.2" + } + }, + "System.Numerics.Vectors": { + "type": "Transitive", + "resolved": "4.6.1", + "contentHash": "sQxefTnhagrhoq2ReR0D/6K0zJcr9Hrd6kikeXsA1I8kOCboTavcUC4r7TSfpKFeE163uMuxZcyfO1mGO3EN8Q==" + }, + "System.Runtime.CompilerServices.Unsafe": { + "type": "Transitive", + "resolved": "6.1.2", + "contentHash": "2hBr6zdbIBTDE3EhK7NSVNdX58uTK6iHW/P/Axmm9sl1xoGSLqDvMtpecn226TNwHByFokYwJmt/aQQNlO5CRw==" + }, + "System.Text.Encodings.Web": { + "type": "Transitive", + "resolved": "10.0.14", + "contentHash": "+aDpFLtsHyft9ZVx9pZQ9MILqwrr8LK1te1L39VMKQYhoYDbs+RUqBhCT3Zydb5ymi2Buo4Cn+3Wi208IxD6rw==", + "dependencies": { + "System.Buffers": "4.6.1", + "System.Memory": "4.6.3", + "System.Runtime.CompilerServices.Unsafe": "6.1.2" + } + }, + "System.Threading.Tasks.Extensions": { + "type": "Transitive", + "resolved": "4.6.3", + "contentHash": "7sCiwilJLYbTZELaKnc7RecBBXWXA+xMLQWZKWawBxYjp6DBlSE3v9/UcvKBvr1vv2tTOhipiogM8rRmxlhrVA==", + "dependencies": { + "System.Runtime.CompilerServices.Unsafe": "6.1.2" + } + }, + "System.ValueTuple": { + "type": "Transitive", + "resolved": "4.6.2", + "contentHash": "yQgmjfFximrNm9LIV3mL6T5MzjeC+epeE5rl4hXxAlYmxby7RM1dPSkIKXk9HNkl6G54h2JHOmLD46+Pey+IRg==" + }, "cuaprotocol": { "type": "Project", "dependencies": { - "JsonSchema.Net": "[9.4.0, )" + "JsonSchema.Net": "[9.4.0, )", + "System.Text.Json": "[10.0.14, 10.0.14]" } } - } + }, + ".NETFramework,Version=v4.8/win-x86": {} } -} +} \ No newline at end of file diff --git a/packages/experimental/cua-windows/package.json b/packages/experimental/cua-windows/package.json index b2779ebe25..770a6c2baf 100644 --- a/packages/experimental/cua-windows/package.json +++ b/packages/experimental/cua-windows/package.json @@ -86,7 +86,7 @@ "src" ], "scripts": { - "build:native": "dotnet publish native/CuaWindows.csproj --configuration Release --runtime win-x64 --self-contained true -p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true -p:EnableWindowsTargeting=true" + "build:native": "dotnet build native/CuaWindows.csproj --configuration Release --framework net48" }, "os": [ "win32", From 32209999ca825c795e56d72e17cf0d3584549eee Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Sat, 7 Nov 2026 15:37:44 +0800 Subject: [PATCH 018/184] Fix project structure --- .../cua-windows/native/Directory.Build.props | 1 + .../cua-windows/native/cua-windows.slnx | 14 +- .../desktop-tests/DesktopFixture.csproj | 2 + .../native/desktop-tests/packages.lock.json | 110 ++++++++++++ .../native/{src => entry}/Accessibility.cs | 0 .../{src => entry}/AccessibilityActions.cs | 0 .../native/{src => entry}/Applications.cs | 0 .../native/{src => entry}/ClipboardPaste.cs | 0 .../native/{ => entry}/CuaWindows.csproj | 10 +- .../native/{src => entry}/DesktopExecutor.cs | 0 .../native/{src => entry}/DesktopSession.cs | 0 .../native/{src => entry}/DesktopWindows.cs | 0 .../native/{src => entry}/Dispatchers.cs | 0 .../native/{src => entry}/GlobalUsings.cs | 0 .../native/{src => entry}/Input.cs | 0 .../native/{src => entry}/LaunchEntries.cs | 0 .../native/{src => entry}/NativeServer.cs | 0 .../native/{src => entry}/Program.cs | 0 .../native/{src => entry}/SharedRuntime.cs | 0 .../native/{src => entry}/ShellBroker.cs | 0 .../native/{src => entry}/Win32.cs | 0 .../native/{src => entry}/WindowCapture.cs | 0 .../native/{src => entry}/Windows.cs | 0 .../native/{ => entry}/app.manifest | 0 .../native/entry/packages.lock.json | 167 ++++++++++++++++++ .../native/protocol/CuaProtocol.csproj | 6 +- .../native/tests/Protocol.Tests.csproj | 10 +- 27 files changed, 300 insertions(+), 20 deletions(-) create mode 100644 packages/experimental/cua-windows/native/desktop-tests/packages.lock.json rename packages/experimental/cua-windows/native/{src => entry}/Accessibility.cs (100%) rename packages/experimental/cua-windows/native/{src => entry}/AccessibilityActions.cs (100%) rename packages/experimental/cua-windows/native/{src => entry}/Applications.cs (100%) rename packages/experimental/cua-windows/native/{src => entry}/ClipboardPaste.cs (100%) rename packages/experimental/cua-windows/native/{ => entry}/CuaWindows.csproj (61%) rename packages/experimental/cua-windows/native/{src => entry}/DesktopExecutor.cs (100%) rename packages/experimental/cua-windows/native/{src => entry}/DesktopSession.cs (100%) rename packages/experimental/cua-windows/native/{src => entry}/DesktopWindows.cs (100%) rename packages/experimental/cua-windows/native/{src => entry}/Dispatchers.cs (100%) rename packages/experimental/cua-windows/native/{src => entry}/GlobalUsings.cs (100%) rename packages/experimental/cua-windows/native/{src => entry}/Input.cs (100%) rename packages/experimental/cua-windows/native/{src => entry}/LaunchEntries.cs (100%) rename packages/experimental/cua-windows/native/{src => entry}/NativeServer.cs (100%) rename packages/experimental/cua-windows/native/{src => entry}/Program.cs (100%) rename packages/experimental/cua-windows/native/{src => entry}/SharedRuntime.cs (100%) rename packages/experimental/cua-windows/native/{src => entry}/ShellBroker.cs (100%) rename packages/experimental/cua-windows/native/{src => entry}/Win32.cs (100%) rename packages/experimental/cua-windows/native/{src => entry}/WindowCapture.cs (100%) rename packages/experimental/cua-windows/native/{src => entry}/Windows.cs (100%) rename packages/experimental/cua-windows/native/{ => entry}/app.manifest (100%) create mode 100644 packages/experimental/cua-windows/native/entry/packages.lock.json diff --git a/packages/experimental/cua-windows/native/Directory.Build.props b/packages/experimental/cua-windows/native/Directory.Build.props index f68224faae..b3496ce767 100644 --- a/packages/experimental/cua-windows/native/Directory.Build.props +++ b/packages/experimental/cua-windows/native/Directory.Build.props @@ -4,6 +4,7 @@ true $(MSBuildThisFileDirectory).build/$(MSBuildProjectName)/bin/ $(MSBuildThisFileDirectory).build/$(MSBuildProjectName)/obj/ + true diff --git a/packages/experimental/cua-windows/native/cua-windows.slnx b/packages/experimental/cua-windows/native/cua-windows.slnx index efe33b9414..9dbe0b4fd9 100644 --- a/packages/experimental/cua-windows/native/cua-windows.slnx +++ b/packages/experimental/cua-windows/native/cua-windows.slnx @@ -1,12 +1,6 @@ - - - - - - - - - - + + + + diff --git a/packages/experimental/cua-windows/native/desktop-tests/DesktopFixture.csproj b/packages/experimental/cua-windows/native/desktop-tests/DesktopFixture.csproj index 77c960608e..e4311b169f 100644 --- a/packages/experimental/cua-windows/native/desktop-tests/DesktopFixture.csproj +++ b/packages/experimental/cua-windows/native/desktop-tests/DesktopFixture.csproj @@ -1,4 +1,5 @@ + Exe net48 @@ -7,4 +8,5 @@ enable dsh-cua-desktop-fixture + diff --git a/packages/experimental/cua-windows/native/desktop-tests/packages.lock.json b/packages/experimental/cua-windows/native/desktop-tests/packages.lock.json new file mode 100644 index 0000000000..f06b45c40a --- /dev/null +++ b/packages/experimental/cua-windows/native/desktop-tests/packages.lock.json @@ -0,0 +1,110 @@ +{ + "version": 1, + "dependencies": { + ".NETFramework,Version=v4.8": { + "Microsoft.NETFramework.ReferenceAssemblies": { + "type": "Direct", + "requested": "[1.0.3, )", + "resolved": "1.0.3", + "contentHash": "vUc9Npcs14QsyOD01tnv/m8sQUnGTGOw1BCmKcv77LBJY7OxhJ+zJF7UD/sCL3lYNFuqmQEVlkfS4Quif6FyYg==", + "dependencies": { + "Microsoft.NETFramework.ReferenceAssemblies.net48": "1.0.3" + } + }, + "PolySharp": { + "type": "Direct", + "requested": "[1.15.0, )", + "resolved": "1.15.0", + "contentHash": "FbU0El+EEjdpuIX4iDbeS7ki1uzpJPx8vbqOzEtqnl1GZeAGJfq+jCbxeJL2y0EPnUNk8dRnnqR2xnYXg9Tf+g==" + }, + "System.Text.Json": { + "type": "Direct", + "requested": "[10.0.14, 10.0.14]", + "resolved": "10.0.14", + "contentHash": "JSSLGJTJJDvS76VnLdY1X289rFcHuYApk7QGw0hCoP5wVR1mk7BvJbOYxQLXq4x1qK/Ml9OHa/AKaAbBVCfSSQ==", + "dependencies": { + "Microsoft.Bcl.AsyncInterfaces": "10.0.14", + "System.Buffers": "4.6.1", + "System.IO.Pipelines": "10.0.14", + "System.Memory": "4.6.3", + "System.Runtime.CompilerServices.Unsafe": "6.1.2", + "System.Text.Encodings.Web": "10.0.14", + "System.Threading.Tasks.Extensions": "4.6.3", + "System.ValueTuple": "4.6.2" + } + }, + "Microsoft.Bcl.AsyncInterfaces": { + "type": "Transitive", + "resolved": "10.0.14", + "contentHash": "HCu9NbiXDh9++j4eRNRHCOiKPw/7I5UEJlFIRaDM3v0+ttZaH8p8rjxSWfNgP2cGv5JAa4EZnmc/nlcUOTFlpA==", + "dependencies": { + "System.Threading.Tasks.Extensions": "4.6.3" + } + }, + "Microsoft.NETFramework.ReferenceAssemblies.net48": { + "type": "Transitive", + "resolved": "1.0.3", + "contentHash": "zMk4D+9zyiEWByyQ7oPImPN/Jhpj166Ky0Nlla4eXlNL8hI/BtSJsgR8Inldd4NNpIAH3oh8yym0W2DrhXdSLQ==" + }, + "System.Buffers": { + "type": "Transitive", + "resolved": "4.6.1", + "contentHash": "N8GXpmiLMtljq7gwvyS+1QvKT/W2J8sNAvx+HVg4NGmsG/H+2k/y9QI23auLJRterrzCiDH+IWAw4V/GPwsMlw==" + }, + "System.IO.Pipelines": { + "type": "Transitive", + "resolved": "10.0.14", + "contentHash": "pLVClkIC4XfXhcOQXNtNDJl5LYJOS4XAQAdzbqF8rj6sk2zdXO/5uikBsZqgqnAAb07z9Fmtu0sMj3TwEiBtIw==", + "dependencies": { + "System.Buffers": "4.6.1", + "System.Memory": "4.6.3", + "System.Threading.Tasks.Extensions": "4.6.3" + } + }, + "System.Memory": { + "type": "Transitive", + "resolved": "4.6.3", + "contentHash": "qdcDOgnFZY40+Q9876JUHnlHu7bosOHX8XISRoH94fwk6hgaeQGSgfZd8srWRZNt5bV9ZW2TljcegDNxsf+96A==", + "dependencies": { + "System.Buffers": "4.6.1", + "System.Numerics.Vectors": "4.6.1", + "System.Runtime.CompilerServices.Unsafe": "6.1.2" + } + }, + "System.Numerics.Vectors": { + "type": "Transitive", + "resolved": "4.6.1", + "contentHash": "sQxefTnhagrhoq2ReR0D/6K0zJcr9Hrd6kikeXsA1I8kOCboTavcUC4r7TSfpKFeE163uMuxZcyfO1mGO3EN8Q==" + }, + "System.Runtime.CompilerServices.Unsafe": { + "type": "Transitive", + "resolved": "6.1.2", + "contentHash": "2hBr6zdbIBTDE3EhK7NSVNdX58uTK6iHW/P/Axmm9sl1xoGSLqDvMtpecn226TNwHByFokYwJmt/aQQNlO5CRw==" + }, + "System.Text.Encodings.Web": { + "type": "Transitive", + "resolved": "10.0.14", + "contentHash": "+aDpFLtsHyft9ZVx9pZQ9MILqwrr8LK1te1L39VMKQYhoYDbs+RUqBhCT3Zydb5ymi2Buo4Cn+3Wi208IxD6rw==", + "dependencies": { + "System.Buffers": "4.6.1", + "System.Memory": "4.6.3", + "System.Runtime.CompilerServices.Unsafe": "6.1.2" + } + }, + "System.Threading.Tasks.Extensions": { + "type": "Transitive", + "resolved": "4.6.3", + "contentHash": "7sCiwilJLYbTZELaKnc7RecBBXWXA+xMLQWZKWawBxYjp6DBlSE3v9/UcvKBvr1vv2tTOhipiogM8rRmxlhrVA==", + "dependencies": { + "System.Runtime.CompilerServices.Unsafe": "6.1.2" + } + }, + "System.ValueTuple": { + "type": "Transitive", + "resolved": "4.6.2", + "contentHash": "yQgmjfFximrNm9LIV3mL6T5MzjeC+epeE5rl4hXxAlYmxby7RM1dPSkIKXk9HNkl6G54h2JHOmLD46+Pey+IRg==" + } + }, + ".NETFramework,Version=v4.8/win-x86": {} + } +} \ No newline at end of file diff --git a/packages/experimental/cua-windows/native/src/Accessibility.cs b/packages/experimental/cua-windows/native/entry/Accessibility.cs similarity index 100% rename from packages/experimental/cua-windows/native/src/Accessibility.cs rename to packages/experimental/cua-windows/native/entry/Accessibility.cs diff --git a/packages/experimental/cua-windows/native/src/AccessibilityActions.cs b/packages/experimental/cua-windows/native/entry/AccessibilityActions.cs similarity index 100% rename from packages/experimental/cua-windows/native/src/AccessibilityActions.cs rename to packages/experimental/cua-windows/native/entry/AccessibilityActions.cs diff --git a/packages/experimental/cua-windows/native/src/Applications.cs b/packages/experimental/cua-windows/native/entry/Applications.cs similarity index 100% rename from packages/experimental/cua-windows/native/src/Applications.cs rename to packages/experimental/cua-windows/native/entry/Applications.cs diff --git a/packages/experimental/cua-windows/native/src/ClipboardPaste.cs b/packages/experimental/cua-windows/native/entry/ClipboardPaste.cs similarity index 100% rename from packages/experimental/cua-windows/native/src/ClipboardPaste.cs rename to packages/experimental/cua-windows/native/entry/ClipboardPaste.cs diff --git a/packages/experimental/cua-windows/native/CuaWindows.csproj b/packages/experimental/cua-windows/native/entry/CuaWindows.csproj similarity index 61% rename from packages/experimental/cua-windows/native/CuaWindows.csproj rename to packages/experimental/cua-windows/native/entry/CuaWindows.csproj index 014cb6e37a..64093d02e4 100644 --- a/packages/experimental/cua-windows/native/CuaWindows.csproj +++ b/packages/experimental/cua-windows/native/entry/CuaWindows.csproj @@ -1,21 +1,21 @@ - + + Exe net48 true true - false enable enable true dsh-cua-windows app.manifest - true none false + - - + + diff --git a/packages/experimental/cua-windows/native/src/DesktopExecutor.cs b/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs similarity index 100% rename from packages/experimental/cua-windows/native/src/DesktopExecutor.cs rename to packages/experimental/cua-windows/native/entry/DesktopExecutor.cs diff --git a/packages/experimental/cua-windows/native/src/DesktopSession.cs b/packages/experimental/cua-windows/native/entry/DesktopSession.cs similarity index 100% rename from packages/experimental/cua-windows/native/src/DesktopSession.cs rename to packages/experimental/cua-windows/native/entry/DesktopSession.cs diff --git a/packages/experimental/cua-windows/native/src/DesktopWindows.cs b/packages/experimental/cua-windows/native/entry/DesktopWindows.cs similarity index 100% rename from packages/experimental/cua-windows/native/src/DesktopWindows.cs rename to packages/experimental/cua-windows/native/entry/DesktopWindows.cs diff --git a/packages/experimental/cua-windows/native/src/Dispatchers.cs b/packages/experimental/cua-windows/native/entry/Dispatchers.cs similarity index 100% rename from packages/experimental/cua-windows/native/src/Dispatchers.cs rename to packages/experimental/cua-windows/native/entry/Dispatchers.cs diff --git a/packages/experimental/cua-windows/native/src/GlobalUsings.cs b/packages/experimental/cua-windows/native/entry/GlobalUsings.cs similarity index 100% rename from packages/experimental/cua-windows/native/src/GlobalUsings.cs rename to packages/experimental/cua-windows/native/entry/GlobalUsings.cs diff --git a/packages/experimental/cua-windows/native/src/Input.cs b/packages/experimental/cua-windows/native/entry/Input.cs similarity index 100% rename from packages/experimental/cua-windows/native/src/Input.cs rename to packages/experimental/cua-windows/native/entry/Input.cs diff --git a/packages/experimental/cua-windows/native/src/LaunchEntries.cs b/packages/experimental/cua-windows/native/entry/LaunchEntries.cs similarity index 100% rename from packages/experimental/cua-windows/native/src/LaunchEntries.cs rename to packages/experimental/cua-windows/native/entry/LaunchEntries.cs diff --git a/packages/experimental/cua-windows/native/src/NativeServer.cs b/packages/experimental/cua-windows/native/entry/NativeServer.cs similarity index 100% rename from packages/experimental/cua-windows/native/src/NativeServer.cs rename to packages/experimental/cua-windows/native/entry/NativeServer.cs diff --git a/packages/experimental/cua-windows/native/src/Program.cs b/packages/experimental/cua-windows/native/entry/Program.cs similarity index 100% rename from packages/experimental/cua-windows/native/src/Program.cs rename to packages/experimental/cua-windows/native/entry/Program.cs diff --git a/packages/experimental/cua-windows/native/src/SharedRuntime.cs b/packages/experimental/cua-windows/native/entry/SharedRuntime.cs similarity index 100% rename from packages/experimental/cua-windows/native/src/SharedRuntime.cs rename to packages/experimental/cua-windows/native/entry/SharedRuntime.cs diff --git a/packages/experimental/cua-windows/native/src/ShellBroker.cs b/packages/experimental/cua-windows/native/entry/ShellBroker.cs similarity index 100% rename from packages/experimental/cua-windows/native/src/ShellBroker.cs rename to packages/experimental/cua-windows/native/entry/ShellBroker.cs diff --git a/packages/experimental/cua-windows/native/src/Win32.cs b/packages/experimental/cua-windows/native/entry/Win32.cs similarity index 100% rename from packages/experimental/cua-windows/native/src/Win32.cs rename to packages/experimental/cua-windows/native/entry/Win32.cs diff --git a/packages/experimental/cua-windows/native/src/WindowCapture.cs b/packages/experimental/cua-windows/native/entry/WindowCapture.cs similarity index 100% rename from packages/experimental/cua-windows/native/src/WindowCapture.cs rename to packages/experimental/cua-windows/native/entry/WindowCapture.cs diff --git a/packages/experimental/cua-windows/native/src/Windows.cs b/packages/experimental/cua-windows/native/entry/Windows.cs similarity index 100% rename from packages/experimental/cua-windows/native/src/Windows.cs rename to packages/experimental/cua-windows/native/entry/Windows.cs diff --git a/packages/experimental/cua-windows/native/app.manifest b/packages/experimental/cua-windows/native/entry/app.manifest similarity index 100% rename from packages/experimental/cua-windows/native/app.manifest rename to packages/experimental/cua-windows/native/entry/app.manifest diff --git a/packages/experimental/cua-windows/native/entry/packages.lock.json b/packages/experimental/cua-windows/native/entry/packages.lock.json new file mode 100644 index 0000000000..44acac2f65 --- /dev/null +++ b/packages/experimental/cua-windows/native/entry/packages.lock.json @@ -0,0 +1,167 @@ +{ + "version": 1, + "dependencies": { + ".NETFramework,Version=v4.8": { + "Microsoft.NETFramework.ReferenceAssemblies": { + "type": "Direct", + "requested": "[1.0.3, )", + "resolved": "1.0.3", + "contentHash": "vUc9Npcs14QsyOD01tnv/m8sQUnGTGOw1BCmKcv77LBJY7OxhJ+zJF7UD/sCL3lYNFuqmQEVlkfS4Quif6FyYg==", + "dependencies": { + "Microsoft.NETFramework.ReferenceAssemblies.net48": "1.0.3" + } + }, + "PolySharp": { + "type": "Direct", + "requested": "[1.15.0, )", + "resolved": "1.15.0", + "contentHash": "FbU0El+EEjdpuIX4iDbeS7ki1uzpJPx8vbqOzEtqnl1GZeAGJfq+jCbxeJL2y0EPnUNk8dRnnqR2xnYXg9Tf+g==" + }, + "System.Text.Json": { + "type": "Direct", + "requested": "[10.0.14, 10.0.14]", + "resolved": "10.0.14", + "contentHash": "JSSLGJTJJDvS76VnLdY1X289rFcHuYApk7QGw0hCoP5wVR1mk7BvJbOYxQLXq4x1qK/Ml9OHa/AKaAbBVCfSSQ==", + "dependencies": { + "Microsoft.Bcl.AsyncInterfaces": "10.0.14", + "System.Buffers": "4.6.1", + "System.IO.Pipelines": "10.0.14", + "System.Memory": "4.6.3", + "System.Runtime.CompilerServices.Unsafe": "6.1.2", + "System.Text.Encodings.Web": "10.0.14", + "System.Threading.Tasks.Extensions": "4.6.3", + "System.ValueTuple": "4.6.2" + } + }, + "Humanizer.Core": { + "type": "Transitive", + "resolved": "3.0.10", + "contentHash": "yZIhtw8sYuvsONzQbZxWpR60tMWYHXoo0DL6nyOqSFiU5POjBTSEyWFpTQtJEZuy+oqiYTXKXY/Mjx7KnqIQFw==", + "dependencies": { + "System.Collections.Immutable": "9.0.10", + "System.ComponentModel.Annotations": "5.0.0", + "System.Memory": "4.6.3" + } + }, + "Json.More.Net": { + "type": "Transitive", + "resolved": "3.0.1", + "contentHash": "fRctF2J2SILYG6wqP21drmeEODmCVkVQ/b3MndDu2fT1swfySyUgq7ePCk+aENGlDcIm05fyfjh9vcuqDEfv3w==", + "dependencies": { + "System.Collections.Immutable": "10.0.5", + "System.Text.Json": "10.0.5" + } + }, + "JsonPointer.Net": { + "type": "Transitive", + "resolved": "7.0.2", + "contentHash": "oClYHv2ooeRrtPZyC9sb/Za/ie5pGhjTbNHlAyFg4XOCyU+606FdoZKS7UdaWvtsPlrF+U2w0Ja3TRvn5+spyA==", + "dependencies": { + "Humanizer.Core": "3.0.10", + "Json.More.Net": "3.0.1" + } + }, + "JsonSchema.Net": { + "type": "Transitive", + "resolved": "9.4.0", + "contentHash": "muE4nPuzbD9x5XA1mkXJNqX4mhz47oF3EY8qFLY1pyUY7lhXFKq65t/dSKIHeNSLBV17zwZuq24MD1em90rMNg==", + "dependencies": { + "JsonPointer.Net": "7.0.2" + } + }, + "Microsoft.Bcl.AsyncInterfaces": { + "type": "Transitive", + "resolved": "10.0.14", + "contentHash": "HCu9NbiXDh9++j4eRNRHCOiKPw/7I5UEJlFIRaDM3v0+ttZaH8p8rjxSWfNgP2cGv5JAa4EZnmc/nlcUOTFlpA==", + "dependencies": { + "System.Threading.Tasks.Extensions": "4.6.3" + } + }, + "Microsoft.NETFramework.ReferenceAssemblies.net48": { + "type": "Transitive", + "resolved": "1.0.3", + "contentHash": "zMk4D+9zyiEWByyQ7oPImPN/Jhpj166Ky0Nlla4eXlNL8hI/BtSJsgR8Inldd4NNpIAH3oh8yym0W2DrhXdSLQ==" + }, + "System.Buffers": { + "type": "Transitive", + "resolved": "4.6.1", + "contentHash": "N8GXpmiLMtljq7gwvyS+1QvKT/W2J8sNAvx+HVg4NGmsG/H+2k/y9QI23auLJRterrzCiDH+IWAw4V/GPwsMlw==" + }, + "System.Collections.Immutable": { + "type": "Transitive", + "resolved": "10.0.5", + "contentHash": "nozrOKfEgfrvvswkCfxaumY68RA/x1F3ZYwtwRvva8ul91NCnUzb6MKpl5/P7u9v/nIagVL4OXXj8d007tucxw==", + "dependencies": { + "System.Memory": "4.6.3", + "System.Runtime.CompilerServices.Unsafe": "6.1.2" + } + }, + "System.ComponentModel.Annotations": { + "type": "Transitive", + "resolved": "5.0.0", + "contentHash": "dMkqfy2el8A8/I76n2Hi1oBFEbG1SfxD2l5nhwXV3XjlnOmwxJlQbYpJH4W51odnU9sARCSAgv7S3CyAFMkpYg==" + }, + "System.IO.Pipelines": { + "type": "Transitive", + "resolved": "10.0.14", + "contentHash": "pLVClkIC4XfXhcOQXNtNDJl5LYJOS4XAQAdzbqF8rj6sk2zdXO/5uikBsZqgqnAAb07z9Fmtu0sMj3TwEiBtIw==", + "dependencies": { + "System.Buffers": "4.6.1", + "System.Memory": "4.6.3", + "System.Threading.Tasks.Extensions": "4.6.3" + } + }, + "System.Memory": { + "type": "Transitive", + "resolved": "4.6.3", + "contentHash": "qdcDOgnFZY40+Q9876JUHnlHu7bosOHX8XISRoH94fwk6hgaeQGSgfZd8srWRZNt5bV9ZW2TljcegDNxsf+96A==", + "dependencies": { + "System.Buffers": "4.6.1", + "System.Numerics.Vectors": "4.6.1", + "System.Runtime.CompilerServices.Unsafe": "6.1.2" + } + }, + "System.Numerics.Vectors": { + "type": "Transitive", + "resolved": "4.6.1", + "contentHash": "sQxefTnhagrhoq2ReR0D/6K0zJcr9Hrd6kikeXsA1I8kOCboTavcUC4r7TSfpKFeE163uMuxZcyfO1mGO3EN8Q==" + }, + "System.Runtime.CompilerServices.Unsafe": { + "type": "Transitive", + "resolved": "6.1.2", + "contentHash": "2hBr6zdbIBTDE3EhK7NSVNdX58uTK6iHW/P/Axmm9sl1xoGSLqDvMtpecn226TNwHByFokYwJmt/aQQNlO5CRw==" + }, + "System.Text.Encodings.Web": { + "type": "Transitive", + "resolved": "10.0.14", + "contentHash": "+aDpFLtsHyft9ZVx9pZQ9MILqwrr8LK1te1L39VMKQYhoYDbs+RUqBhCT3Zydb5ymi2Buo4Cn+3Wi208IxD6rw==", + "dependencies": { + "System.Buffers": "4.6.1", + "System.Memory": "4.6.3", + "System.Runtime.CompilerServices.Unsafe": "6.1.2" + } + }, + "System.Threading.Tasks.Extensions": { + "type": "Transitive", + "resolved": "4.6.3", + "contentHash": "7sCiwilJLYbTZELaKnc7RecBBXWXA+xMLQWZKWawBxYjp6DBlSE3v9/UcvKBvr1vv2tTOhipiogM8rRmxlhrVA==", + "dependencies": { + "System.Runtime.CompilerServices.Unsafe": "6.1.2" + } + }, + "System.ValueTuple": { + "type": "Transitive", + "resolved": "4.6.2", + "contentHash": "yQgmjfFximrNm9LIV3mL6T5MzjeC+epeE5rl4hXxAlYmxby7RM1dPSkIKXk9HNkl6G54h2JHOmLD46+Pey+IRg==" + }, + "cuaprotocol": { + "type": "Project", + "dependencies": { + "JsonSchema.Net": "[9.4.0, )", + "System.Text.Json": "[10.0.14, 10.0.14]" + } + } + }, + ".NETFramework,Version=v4.8/win-x86": {} + } +} \ No newline at end of file diff --git a/packages/experimental/cua-windows/native/protocol/CuaProtocol.csproj b/packages/experimental/cua-windows/native/protocol/CuaProtocol.csproj index adab284210..601dbc0b0e 100644 --- a/packages/experimental/cua-windows/native/protocol/CuaProtocol.csproj +++ b/packages/experimental/cua-windows/native/protocol/CuaProtocol.csproj @@ -1,13 +1,15 @@ - + + net48 enable enable - true false + + diff --git a/packages/experimental/cua-windows/native/tests/Protocol.Tests.csproj b/packages/experimental/cua-windows/native/tests/Protocol.Tests.csproj index 99d820c0d3..1263d8cf13 100644 --- a/packages/experimental/cua-windows/native/tests/Protocol.Tests.csproj +++ b/packages/experimental/cua-windows/native/tests/Protocol.Tests.csproj @@ -1,10 +1,14 @@ - + + Exe net48 enable enable - true - + + + + + From e5ba59e751ebb94bbd4dd8e774625b338f11a7dc Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Sat, 7 Nov 2026 16:43:27 +0800 Subject: [PATCH 019/184] Use System.CommandLine for entry point parsing --- .../native/entry/CuaWindows.csproj | 5 ++ .../cua-windows/native/entry/Program.cs | 80 ++++++++++++------- .../native/entry/packages.lock.json | 9 +++ 3 files changed, 66 insertions(+), 28 deletions(-) diff --git a/packages/experimental/cua-windows/native/entry/CuaWindows.csproj b/packages/experimental/cua-windows/native/entry/CuaWindows.csproj index 64093d02e4..64233ba671 100644 --- a/packages/experimental/cua-windows/native/entry/CuaWindows.csproj +++ b/packages/experimental/cua-windows/native/entry/CuaWindows.csproj @@ -12,8 +12,13 @@ app.manifest none false + DeepSeek.Cua.Windows + + + + diff --git a/packages/experimental/cua-windows/native/entry/Program.cs b/packages/experimental/cua-windows/native/entry/Program.cs index d46db4479c..6e2910a72d 100644 --- a/packages/experimental/cua-windows/native/entry/Program.cs +++ b/packages/experimental/cua-windows/native/entry/Program.cs @@ -1,35 +1,59 @@ // The executable is a private helper launched by the dsh Windows provider. +using System.CommandLine; using DeepSeek.Cua.Protocol; +using DeepSeek.Cua.Windows; -namespace DeepSeek.Cua.Windows; - -internal static class Program +try { - private static int Main(string[] args) +#if NETFRAMEWORK + if (Environment.OSVersion.Version.Build < 19041) { - try - { - if (!OperatingSystem.IsWindowsVersionAtLeast(10, 0, 19041)) throw new NativeFailure("UNSUPPORTED", "Windows CUA requires Windows 10 build 19041 or later"); - var server = args.Length == 7 && args[0] == "--shared-server"; - var bridge = args.Length == 7 && args[0] == "--bridge"; - var connector = args.Length == 9 && args[0] == "--serve" && args[1] == "--instance-id" && Guid.TryParseExact(args[2], "N", out _); - var offset = server || bridge ? 1 : 3; - if ((!server && !connector && !bridge) || args[offset] != "--runtime-key" || args[offset + 2] != "--connect-timeout-ms" - || args[offset + 4] != "--grace-ms" - || !int.TryParse(args[offset + 3], out var connectTimeoutMs) || connectTimeoutMs <= 0 - || !int.TryParse(args[offset + 5], out var graceMs) || graceMs <= 0) - throw new NativeFailure("INVALID_ARGUMENT", "The helper must be launched by the dsh Windows provider"); - var runtime = Applications.Digest(Environment.ProcessPath!); - if (runtime != args[offset + 1]) throw new NativeFailure("NATIVE_STARTUP", "The helper executable changed before startup"); - if (server) SharedRuntime.Serve(runtime, connectTimeoutMs, graceMs); - else if (bridge) SharedRuntime.Bridge(runtime, connectTimeoutMs).GetAwaiter().GetResult(); - else SharedRuntime.Connect(args[2], runtime, connectTimeoutMs, graceMs).GetAwaiter().GetResult(); - return 0; - } - catch (Exception error) - { - Console.Error.WriteLine(error is NativeFailure failure ? $"{failure.Code}: {failure.Message}" : $"NATIVE_STARTUP: {error.Message}"); - return 1; - } + throw new NativeFailure("UNSUPPORTED", "Windows CUA requires Windows 10 build 19041 or later"); } +#endif + + var serve = new Option("--serve") { Arity = ArgumentArity.Zero }; + var sharedServer = new Option("--shared-server") { Arity = ArgumentArity.Zero }; + var bridge = new Option("--bridge") { Arity = ArgumentArity.Zero }; + var instanceId = new Option("--instance-id"); + var runtimeKey = new Option("--runtime-key") { Required = true }; + var connectTimeoutMs = new Option("--connect-timeout-ms") { Required = true }; + var graceMs = new Option("--grace-ms") ; + + var rootCommand = new RootCommand + { + Options = + { + serve, + sharedServer, + bridge, + instanceId, + runtimeKey, + connectTimeoutMs, + graceMs, + } + }; + + var parseResult = rootCommand.Parse(args); + if (parseResult.Errors.Count != 0) + throw new NativeFailure("INVALID_ARGUMENT", "The helper must be launched by the dsh Windows provider"); + + var runtime = Applications.Digest(Environment.ProcessPath!); + if (runtime != parseResult.GetValue(runtimeKey)) throw new NativeFailure("NATIVE_STARTUP", "The helper executable changed before startup"); + + if (parseResult.GetValue(sharedServer)) + SharedRuntime.Serve(runtime, parseResult.GetRequiredValue(connectTimeoutMs), parseResult.GetRequiredValue(graceMs)); + else if (parseResult.GetValue(bridge)) + await SharedRuntime.Bridge(runtime, parseResult.GetRequiredValue(connectTimeoutMs)); + else if (parseResult.GetValue(serve)) + await SharedRuntime.Connect(parseResult.GetRequiredValue(instanceId).ToString("N"), runtime, parseResult.GetRequiredValue(connectTimeoutMs), parseResult.GetRequiredValue(graceMs)); + else + throw new NativeFailure("INVALID_ARGUMENT", "The helper must be launched by the dsh Windows provider"); + + return 0; +} +catch (Exception error) +{ + Console.Error.WriteLine(error is NativeFailure failure ? $"{failure.Code}: {failure.Message}" : $"NATIVE_STARTUP: {error.Message}"); + return -1; } diff --git a/packages/experimental/cua-windows/native/entry/packages.lock.json b/packages/experimental/cua-windows/native/entry/packages.lock.json index 44acac2f65..32ee8aad59 100644 --- a/packages/experimental/cua-windows/native/entry/packages.lock.json +++ b/packages/experimental/cua-windows/native/entry/packages.lock.json @@ -17,6 +17,15 @@ "resolved": "1.15.0", "contentHash": "FbU0El+EEjdpuIX4iDbeS7ki1uzpJPx8vbqOzEtqnl1GZeAGJfq+jCbxeJL2y0EPnUNk8dRnnqR2xnYXg9Tf+g==" }, + "System.CommandLine": { + "type": "Direct", + "requested": "[2.0.14, )", + "resolved": "2.0.14", + "contentHash": "15fyVO4aG6poR6IKmhM74zf7PUzaU6FZAGm2d3SQSO9yIyGAeo44e6t9qeKjjaqyMEqYdqcb2G1B0gpLoDU2cA==", + "dependencies": { + "System.Memory": "4.5.5" + } + }, "System.Text.Json": { "type": "Direct", "requested": "[10.0.14, 10.0.14]", From 5e75c3009fb2f17a842971d104cf7296ca3c1b6e Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Sat, 7 Nov 2026 18:11:26 +0800 Subject: [PATCH 020/184] Switch back to .NET 10 --- .../cua-windows/native/Directory.Build.props | 5 +- .../desktop-tests/DesktopFixture.csproj | 4 +- .../native/desktop-tests/packages.lock.json | 101 +------------ .../native/entry/CuaWindows.csproj | 2 +- .../cua-windows/native/entry/Program.cs | 4 +- .../native/entry/packages.lock.json | 136 +----------------- .../native/protocol/CuaProtocol.csproj | 2 +- .../native/protocol/packages.lock.json | 125 +--------------- .../native/tests/Protocol.Tests.csproj | 2 +- .../native/tests/packages.lock.json | 131 +---------------- .../experimental/cua-windows/package.json | 11 +- .../cua-windows/src/native-build.ts | 18 +-- .../cua-windows/tests/native-build.spec.ts | 51 +++++-- packages/experimental/cua/README.i18n.yaml | 4 +- packages/experimental/cua/README.md | 2 +- packages/experimental/cua/README.zh.md | 2 +- packages/experimental/cua/src/native-build.ts | 50 ++----- .../cua/tests/native-build.spec.ts | 60 ++++---- scripts/check-workspace-constraints.ts | 2 +- 19 files changed, 117 insertions(+), 595 deletions(-) diff --git a/packages/experimental/cua-windows/native/Directory.Build.props b/packages/experimental/cua-windows/native/Directory.Build.props index b3496ce767..ce3106d4b4 100644 --- a/packages/experimental/cua-windows/native/Directory.Build.props +++ b/packages/experimental/cua-windows/native/Directory.Build.props @@ -1,4 +1,5 @@ + 14.0 true @@ -6,9 +7,9 @@ $(MSBuildThisFileDirectory).build/$(MSBuildProjectName)/obj/ true + - - + diff --git a/packages/experimental/cua-windows/native/desktop-tests/DesktopFixture.csproj b/packages/experimental/cua-windows/native/desktop-tests/DesktopFixture.csproj index e4311b169f..f2ffe5c419 100644 --- a/packages/experimental/cua-windows/native/desktop-tests/DesktopFixture.csproj +++ b/packages/experimental/cua-windows/native/desktop-tests/DesktopFixture.csproj @@ -1,8 +1,8 @@ - + Exe - net48 + net10.0-windows10.0.19041 true enable enable diff --git a/packages/experimental/cua-windows/native/desktop-tests/packages.lock.json b/packages/experimental/cua-windows/native/desktop-tests/packages.lock.json index f06b45c40a..d56cf7c387 100644 --- a/packages/experimental/cua-windows/native/desktop-tests/packages.lock.json +++ b/packages/experimental/cua-windows/native/desktop-tests/packages.lock.json @@ -1,110 +1,13 @@ { "version": 1, "dependencies": { - ".NETFramework,Version=v4.8": { - "Microsoft.NETFramework.ReferenceAssemblies": { - "type": "Direct", - "requested": "[1.0.3, )", - "resolved": "1.0.3", - "contentHash": "vUc9Npcs14QsyOD01tnv/m8sQUnGTGOw1BCmKcv77LBJY7OxhJ+zJF7UD/sCL3lYNFuqmQEVlkfS4Quif6FyYg==", - "dependencies": { - "Microsoft.NETFramework.ReferenceAssemblies.net48": "1.0.3" - } - }, + "net10.0-windows10.0.19041": { "PolySharp": { "type": "Direct", "requested": "[1.15.0, )", "resolved": "1.15.0", "contentHash": "FbU0El+EEjdpuIX4iDbeS7ki1uzpJPx8vbqOzEtqnl1GZeAGJfq+jCbxeJL2y0EPnUNk8dRnnqR2xnYXg9Tf+g==" - }, - "System.Text.Json": { - "type": "Direct", - "requested": "[10.0.14, 10.0.14]", - "resolved": "10.0.14", - "contentHash": "JSSLGJTJJDvS76VnLdY1X289rFcHuYApk7QGw0hCoP5wVR1mk7BvJbOYxQLXq4x1qK/Ml9OHa/AKaAbBVCfSSQ==", - "dependencies": { - "Microsoft.Bcl.AsyncInterfaces": "10.0.14", - "System.Buffers": "4.6.1", - "System.IO.Pipelines": "10.0.14", - "System.Memory": "4.6.3", - "System.Runtime.CompilerServices.Unsafe": "6.1.2", - "System.Text.Encodings.Web": "10.0.14", - "System.Threading.Tasks.Extensions": "4.6.3", - "System.ValueTuple": "4.6.2" - } - }, - "Microsoft.Bcl.AsyncInterfaces": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "HCu9NbiXDh9++j4eRNRHCOiKPw/7I5UEJlFIRaDM3v0+ttZaH8p8rjxSWfNgP2cGv5JAa4EZnmc/nlcUOTFlpA==", - "dependencies": { - "System.Threading.Tasks.Extensions": "4.6.3" - } - }, - "Microsoft.NETFramework.ReferenceAssemblies.net48": { - "type": "Transitive", - "resolved": "1.0.3", - "contentHash": "zMk4D+9zyiEWByyQ7oPImPN/Jhpj166Ky0Nlla4eXlNL8hI/BtSJsgR8Inldd4NNpIAH3oh8yym0W2DrhXdSLQ==" - }, - "System.Buffers": { - "type": "Transitive", - "resolved": "4.6.1", - "contentHash": "N8GXpmiLMtljq7gwvyS+1QvKT/W2J8sNAvx+HVg4NGmsG/H+2k/y9QI23auLJRterrzCiDH+IWAw4V/GPwsMlw==" - }, - "System.IO.Pipelines": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "pLVClkIC4XfXhcOQXNtNDJl5LYJOS4XAQAdzbqF8rj6sk2zdXO/5uikBsZqgqnAAb07z9Fmtu0sMj3TwEiBtIw==", - "dependencies": { - "System.Buffers": "4.6.1", - "System.Memory": "4.6.3", - "System.Threading.Tasks.Extensions": "4.6.3" - } - }, - "System.Memory": { - "type": "Transitive", - "resolved": "4.6.3", - "contentHash": "qdcDOgnFZY40+Q9876JUHnlHu7bosOHX8XISRoH94fwk6hgaeQGSgfZd8srWRZNt5bV9ZW2TljcegDNxsf+96A==", - "dependencies": { - "System.Buffers": "4.6.1", - "System.Numerics.Vectors": "4.6.1", - "System.Runtime.CompilerServices.Unsafe": "6.1.2" - } - }, - "System.Numerics.Vectors": { - "type": "Transitive", - "resolved": "4.6.1", - "contentHash": "sQxefTnhagrhoq2ReR0D/6K0zJcr9Hrd6kikeXsA1I8kOCboTavcUC4r7TSfpKFeE163uMuxZcyfO1mGO3EN8Q==" - }, - "System.Runtime.CompilerServices.Unsafe": { - "type": "Transitive", - "resolved": "6.1.2", - "contentHash": "2hBr6zdbIBTDE3EhK7NSVNdX58uTK6iHW/P/Axmm9sl1xoGSLqDvMtpecn226TNwHByFokYwJmt/aQQNlO5CRw==" - }, - "System.Text.Encodings.Web": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "+aDpFLtsHyft9ZVx9pZQ9MILqwrr8LK1te1L39VMKQYhoYDbs+RUqBhCT3Zydb5ymi2Buo4Cn+3Wi208IxD6rw==", - "dependencies": { - "System.Buffers": "4.6.1", - "System.Memory": "4.6.3", - "System.Runtime.CompilerServices.Unsafe": "6.1.2" - } - }, - "System.Threading.Tasks.Extensions": { - "type": "Transitive", - "resolved": "4.6.3", - "contentHash": "7sCiwilJLYbTZELaKnc7RecBBXWXA+xMLQWZKWawBxYjp6DBlSE3v9/UcvKBvr1vv2tTOhipiogM8rRmxlhrVA==", - "dependencies": { - "System.Runtime.CompilerServices.Unsafe": "6.1.2" - } - }, - "System.ValueTuple": { - "type": "Transitive", - "resolved": "4.6.2", - "contentHash": "yQgmjfFximrNm9LIV3mL6T5MzjeC+epeE5rl4hXxAlYmxby7RM1dPSkIKXk9HNkl6G54h2JHOmLD46+Pey+IRg==" } - }, - ".NETFramework,Version=v4.8/win-x86": {} + } } } \ No newline at end of file diff --git a/packages/experimental/cua-windows/native/entry/CuaWindows.csproj b/packages/experimental/cua-windows/native/entry/CuaWindows.csproj index 64233ba671..094bd57d3d 100644 --- a/packages/experimental/cua-windows/native/entry/CuaWindows.csproj +++ b/packages/experimental/cua-windows/native/entry/CuaWindows.csproj @@ -2,7 +2,7 @@ Exe - net48 + net10.0-windows10.0.19041 true true enable diff --git a/packages/experimental/cua-windows/native/entry/Program.cs b/packages/experimental/cua-windows/native/entry/Program.cs index 6e2910a72d..ec178f82d3 100644 --- a/packages/experimental/cua-windows/native/entry/Program.cs +++ b/packages/experimental/cua-windows/native/entry/Program.cs @@ -5,12 +5,10 @@ using DeepSeek.Cua.Windows; try { -#if NETFRAMEWORK - if (Environment.OSVersion.Version.Build < 19041) + if (OperatingSystem.IsWindowsVersionAtLeast(10, 0, 19041)) { throw new NativeFailure("UNSUPPORTED", "Windows CUA requires Windows 10 build 19041 or later"); } -#endif var serve = new Option("--serve") { Arity = ArgumentArity.Zero }; var sharedServer = new Option("--shared-server") { Arity = ArgumentArity.Zero }; diff --git a/packages/experimental/cua-windows/native/entry/packages.lock.json b/packages/experimental/cua-windows/native/entry/packages.lock.json index 32ee8aad59..a378a2fdcc 100644 --- a/packages/experimental/cua-windows/native/entry/packages.lock.json +++ b/packages/experimental/cua-windows/native/entry/packages.lock.json @@ -1,16 +1,7 @@ { "version": 1, "dependencies": { - ".NETFramework,Version=v4.8": { - "Microsoft.NETFramework.ReferenceAssemblies": { - "type": "Direct", - "requested": "[1.0.3, )", - "resolved": "1.0.3", - "contentHash": "vUc9Npcs14QsyOD01tnv/m8sQUnGTGOw1BCmKcv77LBJY7OxhJ+zJF7UD/sCL3lYNFuqmQEVlkfS4Quif6FyYg==", - "dependencies": { - "Microsoft.NETFramework.ReferenceAssemblies.net48": "1.0.3" - } - }, + "net10.0-windows10.0.19041": { "PolySharp": { "type": "Direct", "requested": "[1.15.0, )", @@ -21,45 +12,17 @@ "type": "Direct", "requested": "[2.0.14, )", "resolved": "2.0.14", - "contentHash": "15fyVO4aG6poR6IKmhM74zf7PUzaU6FZAGm2d3SQSO9yIyGAeo44e6t9qeKjjaqyMEqYdqcb2G1B0gpLoDU2cA==", - "dependencies": { - "System.Memory": "4.5.5" - } - }, - "System.Text.Json": { - "type": "Direct", - "requested": "[10.0.14, 10.0.14]", - "resolved": "10.0.14", - "contentHash": "JSSLGJTJJDvS76VnLdY1X289rFcHuYApk7QGw0hCoP5wVR1mk7BvJbOYxQLXq4x1qK/Ml9OHa/AKaAbBVCfSSQ==", - "dependencies": { - "Microsoft.Bcl.AsyncInterfaces": "10.0.14", - "System.Buffers": "4.6.1", - "System.IO.Pipelines": "10.0.14", - "System.Memory": "4.6.3", - "System.Runtime.CompilerServices.Unsafe": "6.1.2", - "System.Text.Encodings.Web": "10.0.14", - "System.Threading.Tasks.Extensions": "4.6.3", - "System.ValueTuple": "4.6.2" - } + "contentHash": "15fyVO4aG6poR6IKmhM74zf7PUzaU6FZAGm2d3SQSO9yIyGAeo44e6t9qeKjjaqyMEqYdqcb2G1B0gpLoDU2cA==" }, "Humanizer.Core": { "type": "Transitive", "resolved": "3.0.10", - "contentHash": "yZIhtw8sYuvsONzQbZxWpR60tMWYHXoo0DL6nyOqSFiU5POjBTSEyWFpTQtJEZuy+oqiYTXKXY/Mjx7KnqIQFw==", - "dependencies": { - "System.Collections.Immutable": "9.0.10", - "System.ComponentModel.Annotations": "5.0.0", - "System.Memory": "4.6.3" - } + "contentHash": "yZIhtw8sYuvsONzQbZxWpR60tMWYHXoo0DL6nyOqSFiU5POjBTSEyWFpTQtJEZuy+oqiYTXKXY/Mjx7KnqIQFw==" }, "Json.More.Net": { "type": "Transitive", "resolved": "3.0.1", - "contentHash": "fRctF2J2SILYG6wqP21drmeEODmCVkVQ/b3MndDu2fT1swfySyUgq7ePCk+aENGlDcIm05fyfjh9vcuqDEfv3w==", - "dependencies": { - "System.Collections.Immutable": "10.0.5", - "System.Text.Json": "10.0.5" - } + "contentHash": "fRctF2J2SILYG6wqP21drmeEODmCVkVQ/b3MndDu2fT1swfySyUgq7ePCk+aENGlDcIm05fyfjh9vcuqDEfv3w==" }, "JsonPointer.Net": { "type": "Transitive", @@ -78,99 +41,12 @@ "JsonPointer.Net": "7.0.2" } }, - "Microsoft.Bcl.AsyncInterfaces": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "HCu9NbiXDh9++j4eRNRHCOiKPw/7I5UEJlFIRaDM3v0+ttZaH8p8rjxSWfNgP2cGv5JAa4EZnmc/nlcUOTFlpA==", - "dependencies": { - "System.Threading.Tasks.Extensions": "4.6.3" - } - }, - "Microsoft.NETFramework.ReferenceAssemblies.net48": { - "type": "Transitive", - "resolved": "1.0.3", - "contentHash": "zMk4D+9zyiEWByyQ7oPImPN/Jhpj166Ky0Nlla4eXlNL8hI/BtSJsgR8Inldd4NNpIAH3oh8yym0W2DrhXdSLQ==" - }, - "System.Buffers": { - "type": "Transitive", - "resolved": "4.6.1", - "contentHash": "N8GXpmiLMtljq7gwvyS+1QvKT/W2J8sNAvx+HVg4NGmsG/H+2k/y9QI23auLJRterrzCiDH+IWAw4V/GPwsMlw==" - }, - "System.Collections.Immutable": { - "type": "Transitive", - "resolved": "10.0.5", - "contentHash": "nozrOKfEgfrvvswkCfxaumY68RA/x1F3ZYwtwRvva8ul91NCnUzb6MKpl5/P7u9v/nIagVL4OXXj8d007tucxw==", - "dependencies": { - "System.Memory": "4.6.3", - "System.Runtime.CompilerServices.Unsafe": "6.1.2" - } - }, - "System.ComponentModel.Annotations": { - "type": "Transitive", - "resolved": "5.0.0", - "contentHash": "dMkqfy2el8A8/I76n2Hi1oBFEbG1SfxD2l5nhwXV3XjlnOmwxJlQbYpJH4W51odnU9sARCSAgv7S3CyAFMkpYg==" - }, - "System.IO.Pipelines": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "pLVClkIC4XfXhcOQXNtNDJl5LYJOS4XAQAdzbqF8rj6sk2zdXO/5uikBsZqgqnAAb07z9Fmtu0sMj3TwEiBtIw==", - "dependencies": { - "System.Buffers": "4.6.1", - "System.Memory": "4.6.3", - "System.Threading.Tasks.Extensions": "4.6.3" - } - }, - "System.Memory": { - "type": "Transitive", - "resolved": "4.6.3", - "contentHash": "qdcDOgnFZY40+Q9876JUHnlHu7bosOHX8XISRoH94fwk6hgaeQGSgfZd8srWRZNt5bV9ZW2TljcegDNxsf+96A==", - "dependencies": { - "System.Buffers": "4.6.1", - "System.Numerics.Vectors": "4.6.1", - "System.Runtime.CompilerServices.Unsafe": "6.1.2" - } - }, - "System.Numerics.Vectors": { - "type": "Transitive", - "resolved": "4.6.1", - "contentHash": "sQxefTnhagrhoq2ReR0D/6K0zJcr9Hrd6kikeXsA1I8kOCboTavcUC4r7TSfpKFeE163uMuxZcyfO1mGO3EN8Q==" - }, - "System.Runtime.CompilerServices.Unsafe": { - "type": "Transitive", - "resolved": "6.1.2", - "contentHash": "2hBr6zdbIBTDE3EhK7NSVNdX58uTK6iHW/P/Axmm9sl1xoGSLqDvMtpecn226TNwHByFokYwJmt/aQQNlO5CRw==" - }, - "System.Text.Encodings.Web": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "+aDpFLtsHyft9ZVx9pZQ9MILqwrr8LK1te1L39VMKQYhoYDbs+RUqBhCT3Zydb5ymi2Buo4Cn+3Wi208IxD6rw==", - "dependencies": { - "System.Buffers": "4.6.1", - "System.Memory": "4.6.3", - "System.Runtime.CompilerServices.Unsafe": "6.1.2" - } - }, - "System.Threading.Tasks.Extensions": { - "type": "Transitive", - "resolved": "4.6.3", - "contentHash": "7sCiwilJLYbTZELaKnc7RecBBXWXA+xMLQWZKWawBxYjp6DBlSE3v9/UcvKBvr1vv2tTOhipiogM8rRmxlhrVA==", - "dependencies": { - "System.Runtime.CompilerServices.Unsafe": "6.1.2" - } - }, - "System.ValueTuple": { - "type": "Transitive", - "resolved": "4.6.2", - "contentHash": "yQgmjfFximrNm9LIV3mL6T5MzjeC+epeE5rl4hXxAlYmxby7RM1dPSkIKXk9HNkl6G54h2JHOmLD46+Pey+IRg==" - }, "cuaprotocol": { "type": "Project", "dependencies": { - "JsonSchema.Net": "[9.4.0, )", - "System.Text.Json": "[10.0.14, 10.0.14]" + "JsonSchema.Net": "[9.4.0, )" } } - }, - ".NETFramework,Version=v4.8/win-x86": {} + } } } \ No newline at end of file diff --git a/packages/experimental/cua-windows/native/protocol/CuaProtocol.csproj b/packages/experimental/cua-windows/native/protocol/CuaProtocol.csproj index 601dbc0b0e..d25f117a5c 100644 --- a/packages/experimental/cua-windows/native/protocol/CuaProtocol.csproj +++ b/packages/experimental/cua-windows/native/protocol/CuaProtocol.csproj @@ -1,7 +1,7 @@  - net48 + net10.0-windows10.0.19041 enable enable false diff --git a/packages/experimental/cua-windows/native/protocol/packages.lock.json b/packages/experimental/cua-windows/native/protocol/packages.lock.json index 2edb96ae39..777f43007e 100644 --- a/packages/experimental/cua-windows/native/protocol/packages.lock.json +++ b/packages/experimental/cua-windows/native/protocol/packages.lock.json @@ -1,7 +1,7 @@ { "version": 1, "dependencies": { - ".NETFramework,Version=v4.8": { + "net10.0-windows10.0.19041": { "JsonSchema.Net": { "type": "Direct", "requested": "[9.4.0, )", @@ -11,55 +11,21 @@ "JsonPointer.Net": "7.0.2" } }, - "Microsoft.NETFramework.ReferenceAssemblies": { - "type": "Direct", - "requested": "[1.0.3, )", - "resolved": "1.0.3", - "contentHash": "vUc9Npcs14QsyOD01tnv/m8sQUnGTGOw1BCmKcv77LBJY7OxhJ+zJF7UD/sCL3lYNFuqmQEVlkfS4Quif6FyYg==", - "dependencies": { - "Microsoft.NETFramework.ReferenceAssemblies.net48": "1.0.3" - } - }, "PolySharp": { "type": "Direct", "requested": "[1.15.0, )", "resolved": "1.15.0", "contentHash": "FbU0El+EEjdpuIX4iDbeS7ki1uzpJPx8vbqOzEtqnl1GZeAGJfq+jCbxeJL2y0EPnUNk8dRnnqR2xnYXg9Tf+g==" }, - "System.Text.Json": { - "type": "Direct", - "requested": "[10.0.14, 10.0.14]", - "resolved": "10.0.14", - "contentHash": "JSSLGJTJJDvS76VnLdY1X289rFcHuYApk7QGw0hCoP5wVR1mk7BvJbOYxQLXq4x1qK/Ml9OHa/AKaAbBVCfSSQ==", - "dependencies": { - "Microsoft.Bcl.AsyncInterfaces": "10.0.14", - "System.Buffers": "4.6.1", - "System.IO.Pipelines": "10.0.14", - "System.Memory": "4.6.3", - "System.Runtime.CompilerServices.Unsafe": "6.1.2", - "System.Text.Encodings.Web": "10.0.14", - "System.Threading.Tasks.Extensions": "4.6.3", - "System.ValueTuple": "4.6.2" - } - }, "Humanizer.Core": { "type": "Transitive", "resolved": "3.0.10", - "contentHash": "yZIhtw8sYuvsONzQbZxWpR60tMWYHXoo0DL6nyOqSFiU5POjBTSEyWFpTQtJEZuy+oqiYTXKXY/Mjx7KnqIQFw==", - "dependencies": { - "System.Collections.Immutable": "9.0.10", - "System.ComponentModel.Annotations": "5.0.0", - "System.Memory": "4.6.3" - } + "contentHash": "yZIhtw8sYuvsONzQbZxWpR60tMWYHXoo0DL6nyOqSFiU5POjBTSEyWFpTQtJEZuy+oqiYTXKXY/Mjx7KnqIQFw==" }, "Json.More.Net": { "type": "Transitive", "resolved": "3.0.1", - "contentHash": "fRctF2J2SILYG6wqP21drmeEODmCVkVQ/b3MndDu2fT1swfySyUgq7ePCk+aENGlDcIm05fyfjh9vcuqDEfv3w==", - "dependencies": { - "System.Collections.Immutable": "10.0.5", - "System.Text.Json": "10.0.5" - } + "contentHash": "fRctF2J2SILYG6wqP21drmeEODmCVkVQ/b3MndDu2fT1swfySyUgq7ePCk+aENGlDcIm05fyfjh9vcuqDEfv3w==" }, "JsonPointer.Net": { "type": "Transitive", @@ -69,91 +35,6 @@ "Humanizer.Core": "3.0.10", "Json.More.Net": "3.0.1" } - }, - "Microsoft.Bcl.AsyncInterfaces": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "HCu9NbiXDh9++j4eRNRHCOiKPw/7I5UEJlFIRaDM3v0+ttZaH8p8rjxSWfNgP2cGv5JAa4EZnmc/nlcUOTFlpA==", - "dependencies": { - "System.Threading.Tasks.Extensions": "4.6.3" - } - }, - "Microsoft.NETFramework.ReferenceAssemblies.net48": { - "type": "Transitive", - "resolved": "1.0.3", - "contentHash": "zMk4D+9zyiEWByyQ7oPImPN/Jhpj166Ky0Nlla4eXlNL8hI/BtSJsgR8Inldd4NNpIAH3oh8yym0W2DrhXdSLQ==" - }, - "System.Buffers": { - "type": "Transitive", - "resolved": "4.6.1", - "contentHash": "N8GXpmiLMtljq7gwvyS+1QvKT/W2J8sNAvx+HVg4NGmsG/H+2k/y9QI23auLJRterrzCiDH+IWAw4V/GPwsMlw==" - }, - "System.Collections.Immutable": { - "type": "Transitive", - "resolved": "10.0.5", - "contentHash": "nozrOKfEgfrvvswkCfxaumY68RA/x1F3ZYwtwRvva8ul91NCnUzb6MKpl5/P7u9v/nIagVL4OXXj8d007tucxw==", - "dependencies": { - "System.Memory": "4.6.3", - "System.Runtime.CompilerServices.Unsafe": "6.1.2" - } - }, - "System.ComponentModel.Annotations": { - "type": "Transitive", - "resolved": "5.0.0", - "contentHash": "dMkqfy2el8A8/I76n2Hi1oBFEbG1SfxD2l5nhwXV3XjlnOmwxJlQbYpJH4W51odnU9sARCSAgv7S3CyAFMkpYg==" - }, - "System.IO.Pipelines": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "pLVClkIC4XfXhcOQXNtNDJl5LYJOS4XAQAdzbqF8rj6sk2zdXO/5uikBsZqgqnAAb07z9Fmtu0sMj3TwEiBtIw==", - "dependencies": { - "System.Buffers": "4.6.1", - "System.Memory": "4.6.3", - "System.Threading.Tasks.Extensions": "4.6.3" - } - }, - "System.Memory": { - "type": "Transitive", - "resolved": "4.6.3", - "contentHash": "qdcDOgnFZY40+Q9876JUHnlHu7bosOHX8XISRoH94fwk6hgaeQGSgfZd8srWRZNt5bV9ZW2TljcegDNxsf+96A==", - "dependencies": { - "System.Buffers": "4.6.1", - "System.Numerics.Vectors": "4.6.1", - "System.Runtime.CompilerServices.Unsafe": "6.1.2" - } - }, - "System.Numerics.Vectors": { - "type": "Transitive", - "resolved": "4.6.1", - "contentHash": "sQxefTnhagrhoq2ReR0D/6K0zJcr9Hrd6kikeXsA1I8kOCboTavcUC4r7TSfpKFeE163uMuxZcyfO1mGO3EN8Q==" - }, - "System.Runtime.CompilerServices.Unsafe": { - "type": "Transitive", - "resolved": "6.1.2", - "contentHash": "2hBr6zdbIBTDE3EhK7NSVNdX58uTK6iHW/P/Axmm9sl1xoGSLqDvMtpecn226TNwHByFokYwJmt/aQQNlO5CRw==" - }, - "System.Text.Encodings.Web": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "+aDpFLtsHyft9ZVx9pZQ9MILqwrr8LK1te1L39VMKQYhoYDbs+RUqBhCT3Zydb5ymi2Buo4Cn+3Wi208IxD6rw==", - "dependencies": { - "System.Buffers": "4.6.1", - "System.Memory": "4.6.3", - "System.Runtime.CompilerServices.Unsafe": "6.1.2" - } - }, - "System.Threading.Tasks.Extensions": { - "type": "Transitive", - "resolved": "4.6.3", - "contentHash": "7sCiwilJLYbTZELaKnc7RecBBXWXA+xMLQWZKWawBxYjp6DBlSE3v9/UcvKBvr1vv2tTOhipiogM8rRmxlhrVA==", - "dependencies": { - "System.Runtime.CompilerServices.Unsafe": "6.1.2" - } - }, - "System.ValueTuple": { - "type": "Transitive", - "resolved": "4.6.2", - "contentHash": "yQgmjfFximrNm9LIV3mL6T5MzjeC+epeE5rl4hXxAlYmxby7RM1dPSkIKXk9HNkl6G54h2JHOmLD46+Pey+IRg==" } } } diff --git a/packages/experimental/cua-windows/native/tests/Protocol.Tests.csproj b/packages/experimental/cua-windows/native/tests/Protocol.Tests.csproj index 1263d8cf13..010afdeb6b 100644 --- a/packages/experimental/cua-windows/native/tests/Protocol.Tests.csproj +++ b/packages/experimental/cua-windows/native/tests/Protocol.Tests.csproj @@ -2,7 +2,7 @@ Exe - net48 + net10.0-windows10.0.19041 enable enable diff --git a/packages/experimental/cua-windows/native/tests/packages.lock.json b/packages/experimental/cua-windows/native/tests/packages.lock.json index 44acac2f65..2728b9ea8f 100644 --- a/packages/experimental/cua-windows/native/tests/packages.lock.json +++ b/packages/experimental/cua-windows/native/tests/packages.lock.json @@ -1,56 +1,22 @@ { "version": 1, "dependencies": { - ".NETFramework,Version=v4.8": { - "Microsoft.NETFramework.ReferenceAssemblies": { - "type": "Direct", - "requested": "[1.0.3, )", - "resolved": "1.0.3", - "contentHash": "vUc9Npcs14QsyOD01tnv/m8sQUnGTGOw1BCmKcv77LBJY7OxhJ+zJF7UD/sCL3lYNFuqmQEVlkfS4Quif6FyYg==", - "dependencies": { - "Microsoft.NETFramework.ReferenceAssemblies.net48": "1.0.3" - } - }, + "net10.0-windows10.0.19041": { "PolySharp": { "type": "Direct", "requested": "[1.15.0, )", "resolved": "1.15.0", "contentHash": "FbU0El+EEjdpuIX4iDbeS7ki1uzpJPx8vbqOzEtqnl1GZeAGJfq+jCbxeJL2y0EPnUNk8dRnnqR2xnYXg9Tf+g==" }, - "System.Text.Json": { - "type": "Direct", - "requested": "[10.0.14, 10.0.14]", - "resolved": "10.0.14", - "contentHash": "JSSLGJTJJDvS76VnLdY1X289rFcHuYApk7QGw0hCoP5wVR1mk7BvJbOYxQLXq4x1qK/Ml9OHa/AKaAbBVCfSSQ==", - "dependencies": { - "Microsoft.Bcl.AsyncInterfaces": "10.0.14", - "System.Buffers": "4.6.1", - "System.IO.Pipelines": "10.0.14", - "System.Memory": "4.6.3", - "System.Runtime.CompilerServices.Unsafe": "6.1.2", - "System.Text.Encodings.Web": "10.0.14", - "System.Threading.Tasks.Extensions": "4.6.3", - "System.ValueTuple": "4.6.2" - } - }, "Humanizer.Core": { "type": "Transitive", "resolved": "3.0.10", - "contentHash": "yZIhtw8sYuvsONzQbZxWpR60tMWYHXoo0DL6nyOqSFiU5POjBTSEyWFpTQtJEZuy+oqiYTXKXY/Mjx7KnqIQFw==", - "dependencies": { - "System.Collections.Immutable": "9.0.10", - "System.ComponentModel.Annotations": "5.0.0", - "System.Memory": "4.6.3" - } + "contentHash": "yZIhtw8sYuvsONzQbZxWpR60tMWYHXoo0DL6nyOqSFiU5POjBTSEyWFpTQtJEZuy+oqiYTXKXY/Mjx7KnqIQFw==" }, "Json.More.Net": { "type": "Transitive", "resolved": "3.0.1", - "contentHash": "fRctF2J2SILYG6wqP21drmeEODmCVkVQ/b3MndDu2fT1swfySyUgq7ePCk+aENGlDcIm05fyfjh9vcuqDEfv3w==", - "dependencies": { - "System.Collections.Immutable": "10.0.5", - "System.Text.Json": "10.0.5" - } + "contentHash": "fRctF2J2SILYG6wqP21drmeEODmCVkVQ/b3MndDu2fT1swfySyUgq7ePCk+aENGlDcIm05fyfjh9vcuqDEfv3w==" }, "JsonPointer.Net": { "type": "Transitive", @@ -69,99 +35,12 @@ "JsonPointer.Net": "7.0.2" } }, - "Microsoft.Bcl.AsyncInterfaces": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "HCu9NbiXDh9++j4eRNRHCOiKPw/7I5UEJlFIRaDM3v0+ttZaH8p8rjxSWfNgP2cGv5JAa4EZnmc/nlcUOTFlpA==", - "dependencies": { - "System.Threading.Tasks.Extensions": "4.6.3" - } - }, - "Microsoft.NETFramework.ReferenceAssemblies.net48": { - "type": "Transitive", - "resolved": "1.0.3", - "contentHash": "zMk4D+9zyiEWByyQ7oPImPN/Jhpj166Ky0Nlla4eXlNL8hI/BtSJsgR8Inldd4NNpIAH3oh8yym0W2DrhXdSLQ==" - }, - "System.Buffers": { - "type": "Transitive", - "resolved": "4.6.1", - "contentHash": "N8GXpmiLMtljq7gwvyS+1QvKT/W2J8sNAvx+HVg4NGmsG/H+2k/y9QI23auLJRterrzCiDH+IWAw4V/GPwsMlw==" - }, - "System.Collections.Immutable": { - "type": "Transitive", - "resolved": "10.0.5", - "contentHash": "nozrOKfEgfrvvswkCfxaumY68RA/x1F3ZYwtwRvva8ul91NCnUzb6MKpl5/P7u9v/nIagVL4OXXj8d007tucxw==", - "dependencies": { - "System.Memory": "4.6.3", - "System.Runtime.CompilerServices.Unsafe": "6.1.2" - } - }, - "System.ComponentModel.Annotations": { - "type": "Transitive", - "resolved": "5.0.0", - "contentHash": "dMkqfy2el8A8/I76n2Hi1oBFEbG1SfxD2l5nhwXV3XjlnOmwxJlQbYpJH4W51odnU9sARCSAgv7S3CyAFMkpYg==" - }, - "System.IO.Pipelines": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "pLVClkIC4XfXhcOQXNtNDJl5LYJOS4XAQAdzbqF8rj6sk2zdXO/5uikBsZqgqnAAb07z9Fmtu0sMj3TwEiBtIw==", - "dependencies": { - "System.Buffers": "4.6.1", - "System.Memory": "4.6.3", - "System.Threading.Tasks.Extensions": "4.6.3" - } - }, - "System.Memory": { - "type": "Transitive", - "resolved": "4.6.3", - "contentHash": "qdcDOgnFZY40+Q9876JUHnlHu7bosOHX8XISRoH94fwk6hgaeQGSgfZd8srWRZNt5bV9ZW2TljcegDNxsf+96A==", - "dependencies": { - "System.Buffers": "4.6.1", - "System.Numerics.Vectors": "4.6.1", - "System.Runtime.CompilerServices.Unsafe": "6.1.2" - } - }, - "System.Numerics.Vectors": { - "type": "Transitive", - "resolved": "4.6.1", - "contentHash": "sQxefTnhagrhoq2ReR0D/6K0zJcr9Hrd6kikeXsA1I8kOCboTavcUC4r7TSfpKFeE163uMuxZcyfO1mGO3EN8Q==" - }, - "System.Runtime.CompilerServices.Unsafe": { - "type": "Transitive", - "resolved": "6.1.2", - "contentHash": "2hBr6zdbIBTDE3EhK7NSVNdX58uTK6iHW/P/Axmm9sl1xoGSLqDvMtpecn226TNwHByFokYwJmt/aQQNlO5CRw==" - }, - "System.Text.Encodings.Web": { - "type": "Transitive", - "resolved": "10.0.14", - "contentHash": "+aDpFLtsHyft9ZVx9pZQ9MILqwrr8LK1te1L39VMKQYhoYDbs+RUqBhCT3Zydb5ymi2Buo4Cn+3Wi208IxD6rw==", - "dependencies": { - "System.Buffers": "4.6.1", - "System.Memory": "4.6.3", - "System.Runtime.CompilerServices.Unsafe": "6.1.2" - } - }, - "System.Threading.Tasks.Extensions": { - "type": "Transitive", - "resolved": "4.6.3", - "contentHash": "7sCiwilJLYbTZELaKnc7RecBBXWXA+xMLQWZKWawBxYjp6DBlSE3v9/UcvKBvr1vv2tTOhipiogM8rRmxlhrVA==", - "dependencies": { - "System.Runtime.CompilerServices.Unsafe": "6.1.2" - } - }, - "System.ValueTuple": { - "type": "Transitive", - "resolved": "4.6.2", - "contentHash": "yQgmjfFximrNm9LIV3mL6T5MzjeC+epeE5rl4hXxAlYmxby7RM1dPSkIKXk9HNkl6G54h2JHOmLD46+Pey+IRg==" - }, "cuaprotocol": { "type": "Project", "dependencies": { - "JsonSchema.Net": "[9.4.0, )", - "System.Text.Json": "[10.0.14, 10.0.14]" + "JsonSchema.Net": "[9.4.0, )" } } - }, - ".NETFramework,Version=v4.8/win-x86": {} + } } } \ No newline at end of file diff --git a/packages/experimental/cua-windows/package.json b/packages/experimental/cua-windows/package.json index 770a6c2baf..ef50f44eb4 100644 --- a/packages/experimental/cua-windows/package.json +++ b/packages/experimental/cua-windows/package.json @@ -73,20 +73,15 @@ "files": [ "lib/index.js", "native/bin", - "native/CuaWindows.csproj", - "native/Directory.Build.props", - "native/app.manifest", - "native/src", - "native/protocol", - "native/protocol.schema.json", - "native/packages.lock.json", "lib/types/**/*.d.ts", "lib/types/**/*.d.ts.map", "lib/**/*.js.map", "src" ], "scripts": { - "build:native": "dotnet build native/CuaWindows.csproj --configuration Release --framework net48" + "build:native": "dotnet publish native/entry/CuaWindows.csproj --configuration Release --self-contained false --output native/bin/local -p:EnableWindowsTargeting=true", + "build:native:x64": "dotnet publish native/entry/CuaWindows.csproj --configuration Release --runtime win-x64 --self-contained true --output native/bin/win-x64 -p:EnableWindowsTargeting=true", + "build:native:arm64": "dotnet publish native/entry/CuaWindows.csproj --configuration Release --runtime win-arm64 --self-contained true --output native/bin/win-arm64 -p:EnableWindowsTargeting=true" }, "os": [ "win32", diff --git a/packages/experimental/cua-windows/src/native-build.ts b/packages/experimental/cua-windows/src/native-build.ts index f87e93390f..78feafdebd 100644 --- a/packages/experimental/cua-windows/src/native-build.ts +++ b/packages/experimental/cua-windows/src/native-build.ts @@ -1,7 +1,7 @@ /** Source compilation and installed Windows C# helper resolution. */ import { constants } from 'node:fs' import { access } from 'node:fs/promises' -import { join } from 'node:path' +import { dirname, join } from 'node:path' import type { SubprocessRuntime } from '@deepseek-ai/dsh-subprocess' import { buildNativeExecutable as compileExecutable, sourceNativePackage } from '@deepseek-ai/dsh-cua/native-build' @@ -42,20 +42,22 @@ export function nativeExecutablePath(packageRoot: string, architecture: NativeAr } /** - * Publish a self-contained C# executable; the build can run on macOS with Windows targeting enabled. + * Publish the self-contained C# application directly into the package payload directory. * @param spec - SDK command, target, compiler ownership, and deadlines. - * @returns Immutable content-addressed executable after compiler cleanup. + * @returns Package executable path after compiler cleanup; existing output files can be overwritten. */ export function buildNativeExecutable(spec: NativeBuildSpec): Promise { const native = join(spec.packageRoot, 'native') - const output = join(native, '.build', `win-${spec.architecture}`) + const executable = nativeExecutablePath(spec.packageRoot, spec.architecture) return compileExecutable({ ...spec, - argv: [spec.dotnetPath, 'publish', join(native, 'CuaWindows.csproj'), '--configuration', 'Release', - '--runtime', `win-${spec.architecture}`, '--self-contained', 'true', '--output', output, + argv: [spec.dotnetPath, 'publish', join(native, 'entry', 'CuaWindows.csproj'), '--configuration', 'Release', + '--runtime', `win-${spec.architecture}`, '--self-contained', 'true', '--output', dirname(executable), '-p:EnableWindowsTargeting=true'], - outputPath: join(output, 'dsh-cua-windows.exe'), executablePath: nativeExecutablePath(spec.packageRoot, spec.architecture), lockPath: join(native, '.build', 'publish'), - retainedDirectory: join(native, '.build', 'prepared', spec.architecture), binaryName: 'dsh-cua-windows.exe', + resolveExecutable: async () => { + await access(executable, constants.X_OK) + return executable + }, }) } diff --git a/packages/experimental/cua-windows/tests/native-build.spec.ts b/packages/experimental/cua-windows/tests/native-build.spec.ts index 9c9eb60aa9..b9688080fc 100644 --- a/packages/experimental/cua-windows/tests/native-build.spec.ts +++ b/packages/experimental/cua-windows/tests/native-build.spec.ts @@ -1,7 +1,7 @@ -/** The Windows compiler publishes one immutable executable and installed packages need no SDK. */ +/** Windows publishes its executable and dependencies directly into the package payload. */ import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' -import { join } from 'node:path' +import { dirname, join } from 'node:path' import { expect, it, onTestFinished, vi } from 'vitest' import type { SubprocessHandle, SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess' import { buildNativeExecutable, nativeExecutablePath, nativeHostArchitecture, prepareNativeExecutable } from '../src/native-build.ts' @@ -12,19 +12,29 @@ async function fixture() { const packageRoot = join(root, 'packages/experimental/cua-windows') await mkdir(packageRoot, { recursive: true }) const bytes = Buffer.from('MZ Windows executable fixture') + const files = new Map([ + ['dsh-cua-windows.dll', 'managed code'], + ['dsh-cua-windows.runtimeconfig.json', '{"runtimeOptions":{}}'], + ['dsh-cua-windows.deps.json', '{}'], + ['resources/zh-CN/messages.dll', 'localized resources'], + ]) const spawn = vi.fn((request: SubprocessSpawnSpec): SubprocessHandle => ({ stdin: undefined, stdout: undefined, stderr: undefined, control: undefined, collected: {}, done: (async () => { const output = request.argv[request.argv.indexOf('--output') + 1]! await mkdir(output, { recursive: true }) - await writeFile(join(output, 'dsh-cua-windows.exe'), bytes) + await writeFile(join(output, 'dsh-cua-windows.exe'), bytes, { mode: 0o755 }) + for (const [name, content] of files) { + await mkdir(dirname(join(output, name)), { recursive: true }) + await writeFile(join(output, name), content) + } return { exitCode: 0, signal: null } })(), terminate: vi.fn(), waitForExit: async () => true, })) const spec = { packageRoot, architecture: 'x64' as const, dotnetPath: 'fixture-dotnet', subprocess: { spawn }, signal: new AbortController().signal, timeoutMs: 60_000, graceMs: 1000 } - return { root, spec, spawn, bytes } + return { root, spec, spawn, bytes, files } } it.each(['x64', 'arm64'])('accepts the Windows %s process target', (architecture) => { @@ -34,21 +44,44 @@ it.each([['darwin', 'arm64'], ['linux', 'x64'], ['win32', 'ia32']])('rejects uns expect(() => nativeHostArchitecture(platform, architecture)).toThrow('requires Windows') }) -it('passes an explicit Windows RID and SDK to the managed compiler and retains the bytes', async () => { +it('publishes all dependencies and nested resources without single-file bundling', async () => { const f = await fixture() const output = await buildNativeExecutable(f.spec) + const packaged = nativeExecutablePath(f.spec.packageRoot, 'x64') + expect(output).toBe(packaged) expect(await readFile(output)).toEqual(f.bytes) - expect(await readFile(nativeExecutablePath(f.spec.packageRoot, 'x64'))).toEqual(f.bytes) - expect(f.spawn.mock.calls[0]![0].argv).toEqual(expect.arrayContaining([ - 'fixture-dotnet', '--runtime', 'win-x64', '--self-contained', 'true', '-p:EnableWindowsTargeting=true', + for (const [name, content] of f.files) + expect(await readFile(join(dirname(output), name), 'utf8')).toBe(content) + const argv = f.spawn.mock.calls[0]![0].argv + expect(argv.slice(0, 3)).toEqual(['fixture-dotnet', 'publish', join(f.spec.packageRoot, 'native', 'entry', 'CuaWindows.csproj')]) + expect(argv).toEqual(expect.arrayContaining([ + '--runtime', 'win-x64', '--self-contained', 'true', '-p:EnableWindowsTargeting=true', ])) + expect(argv.some(arg => arg.includes('PublishSingleFile') || arg.includes('IncludeNativeLibrariesForSelfExtract'))).toBe(false) + expect(argv[argv.indexOf('--output') + 1]).toBe(dirname(packaged)) expect(await buildNativeExecutable(f.spec)).toBe(output) }) +it('publishes dependency updates at the same package path', async () => { + const f = await fixture() + const first = await buildNativeExecutable(f.spec) + f.files.set('dsh-cua-windows.dll', 'updated managed code') + expect(await buildNativeExecutable(f.spec)).toBe(first) + expect(await readFile(join(dirname(first), 'dsh-cua-windows.dll'), 'utf8')).toBe('updated managed code') +}) + +it('rejects canceled preparation without starting the compiler', async () => { + const f = await fixture() + const controller = new AbortController() + controller.abort(new Error('provider unloaded')) + await expect(buildNativeExecutable({ ...f.spec, signal: controller.signal })).rejects.toThrow('provider unloaded') + expect(f.spawn).not.toHaveBeenCalled() +}) + it('compiles a recognized source package and resolves an installed payload without a compiler', async () => { const f = await fixture() await writeFile(join(f.root, 'package.json'), JSON.stringify({ name: '@deepseek-ai/dsh-root' })) - expect(await prepareNativeExecutable(f.spec)).toContain('prepared') + expect(await prepareNativeExecutable(f.spec)).toBe(nativeExecutablePath(f.spec.packageRoot, 'x64')) expect(f.spawn).toHaveBeenCalledOnce() await rm(join(f.root, 'package.json')) expect(await prepareNativeExecutable(f.spec)).toBe(nativeExecutablePath(f.spec.packageRoot, 'x64')) diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index f4abb13c43..f895c22d61 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -21,8 +21,8 @@ en: d92d5948a7941e8d zh: d43491ae6521b87e /deepseek-ai-dsh-cua/understand-the-implementation: - en: 2ab74a1ff120459e - zh: 39b3ef198989f133 + en: 6d5c4add9dc90671 + zh: 856ccdf99a5dd446 /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 c95e4ae8ec..b925e88b4d 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -68,7 +68,7 @@ The Host marker has no configurable fields; platform providers own native config ## Understand the implementation -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. Standalone executables are retained by digest. The macOS provider reads its signed application receipt after compilation completes under the same lock. +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.
Shared execution and platform ownership diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index c1c5ed863c..91f7c0ab94 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -68,7 +68,7 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边 ## 理解实现 -权限响应标识所属平台,并且只报告该平台能够观察到的状态。共享页面显示这些观察结果支持的控件。平台尚未确认时显示通用观察和输入项,不提供系统操作。原生提供方共用编译锁和编译进程清理逻辑。独立可执行文件按内容摘要保存。macOS 提供方在锁内等待编译完成,再读取签名应用的构建回执。 +权限响应标识所属平台,并且只报告该平台能够观察到的状态。共享页面显示这些观察结果支持的控件。平台尚未确认时显示通用观察和输入项,不提供系统操作。原生提供方共用编译锁和编译进程清理逻辑。macOS 提供方在锁内等待编译完成,再读取签名应用的构建回执。
共享执行与平台职责 diff --git a/packages/experimental/cua/src/native-build.ts b/packages/experimental/cua/src/native-build.ts index a38cf5b00e..687357ca15 100644 --- a/packages/experimental/cua/src/native-build.ts +++ b/packages/experimental/cua/src/native-build.ts @@ -1,9 +1,7 @@ -/** Managed native compilation and immutable executable publication shared by platform providers. */ -import { constants } from 'node:fs' -import { createHash } from 'node:crypto' -import { access, mkdir, readFile } from 'node:fs/promises' +/** Managed native compilation and platform-owned executable resolution. */ +import { mkdir, readFile } from 'node:fs/promises' import { dirname, join, resolve } from 'node:path' -import { withFileLock, writeFileAtomic } from '@deepseek-ai/dsh-atomic-write' +import { withFileLock } from '@deepseek-ai/dsh-atomic-write' import type { SubprocessOutcome, SubprocessRuntime } from '@deepseek-ai/dsh-subprocess' /** Compiler invocation and lock shared by preparations using the same scratch files. */ @@ -18,14 +16,6 @@ interface NativeCompilerBuild { lockPath: string } -/** Locations for publishing a standalone executable by content digest. */ -export interface NativeExecutableBuild extends NativeCompilerBuild { - outputPath: string - executablePath: string - retainedDirectory: string - binaryName: string -} - /** * Recognize a declared package directory inside a DSH source checkout. * @param packageRoot - Real directory containing the platform package. @@ -45,20 +35,19 @@ export async function sourceNativePackage(packageRoot: string, directory: string } /** - * Run the compiler under its build lock, then publish the binary or resolve the executable from the built application. - * @param spec - Compiler and resource limits, with standalone binary paths or a callback reading the signed application receipt. - * @returns Content-addressed runtime path after managed process cleanup. + * Run the compiler under its build lock, then resolve the platform-owned executable. + * @param spec - Compiler and resource limits, with a callback locating the built executable. + * @returns Platform executable path after managed process cleanup. */ export async function buildNativeExecutable( - spec: NativeExecutableBuild | (NativeCompilerBuild & { resolveExecutable: () => Promise }), + spec: NativeCompilerBuild & { resolveExecutable: () => Promise }, ): Promise { spec.signal.throwIfAborted() - if ('executablePath' in spec) await mkdir(dirname(spec.executablePath), { recursive: true }) await mkdir(dirname(spec.lockPath), { recursive: true }) const signal = AbortSignal.any([spec.signal, AbortSignal.timeout(spec.timeoutMs)]) return withFileLock(spec.lockPath, async () => { await compileNative(spec, signal) - return 'resolveExecutable' in spec ? spec.resolveExecutable() : publishExecutable(spec, signal) + return spec.resolveExecutable() }, { waitMs: spec.timeoutMs, signal }) } @@ -80,26 +69,3 @@ async function compileNative(spec: NativeCompilerBuild, signal: AbortSignal): Pr throw new Error(`Computer Use native preparation failed (${String(outcome.exitCode)}, ${String(outcome.signal)}): ${diagnostics}`) } } - -async function publishExecutable(spec: NativeExecutableBuild, signal: AbortSignal): Promise { - const executable = spec.executablePath - const built = await readFile(spec.outputPath) - let previous: Buffer | undefined - try { previous = await readFile(executable) } catch (error) { - if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error - } - signal.throwIfAborted() - if (!previous?.equals(built)) await writeFileAtomic(executable, built, { mode: 0o755 }) - const digest = createHash('sha256').update(built).digest('hex') - const runtime = join(spec.retainedDirectory, digest, spec.binaryName) - await mkdir(dirname(runtime), { recursive: true }) - let retained: Buffer | undefined - try { retained = await readFile(runtime) } catch (error) { - if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error - } - if (retained && !retained.equals(built)) throw new Error('Computer Use retained executable does not match its content digest') - signal.throwIfAborted() - if (!retained) await writeFileAtomic(runtime, built, { mode: 0o755 }) - await access(runtime, constants.X_OK) - return runtime -} diff --git a/packages/experimental/cua/tests/native-build.spec.ts b/packages/experimental/cua/tests/native-build.spec.ts index 03f04598a9..0468f90f46 100644 --- a/packages/experimental/cua/tests/native-build.spec.ts +++ b/packages/experimental/cua/tests/native-build.spec.ts @@ -1,54 +1,42 @@ -/** Standalone helper generations remain immutable across rebuilds and publication failures. */ -import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises' +/** Native compilation resolves the platform executable only after successful process cleanup. */ +import { mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import type { SubprocessHandle } from '@deepseek-ai/dsh-subprocess' import { expect, it, onTestFinished, vi } from 'vitest' -import { buildNativeExecutable, type NativeExecutableBuild } from '../src/native-build.ts' +import { buildNativeExecutable } from '../src/native-build.ts' -async function fixture() { +async function fixture(exitCode = 0, exited = true) { const root = await mkdtemp(join(tmpdir(), 'cua-build-')) onTestFinished(() => rm(root, { recursive: true, force: true })) const handle: SubprocessHandle = { stdin: undefined, stdout: undefined, stderr: undefined, control: undefined, collected: {}, - done: Promise.resolve({ exitCode: 0, signal: null }), terminate: vi.fn(), waitForExit: async () => true, + done: Promise.resolve({ exitCode, signal: null }), terminate: vi.fn(), waitForExit: vi.fn(async () => exited), } - const spec: NativeExecutableBuild = { + const executable = join(root, 'bin', 'helper.exe') + const resolveExecutable = vi.fn(async () => { + expect(handle.waitForExit).toHaveBeenCalledOnce() + return executable + }) + const spec = { packageRoot: root, subprocess: { spawn: () => handle }, signal: new AbortController().signal, timeoutMs: 60_000, graceMs: 100, argv: ['fixture-compiler'], - outputPath: join(root, 'compiled'), executablePath: join(root, 'bin', 'helper.exe'), - retainedDirectory: join(root, 'generations'), binaryName: 'helper.exe', lockPath: join(root, 'locks', 'compiler'), + lockPath: join(root, 'locks', 'compiler'), resolveExecutable, } - await writeFile(spec.outputPath, 'first build') - return spec + return { spec, handle, executable, resolveExecutable } } -it('reuses an identical helper and retains the old generation when publishing different bytes', async () => { - const spec = await fixture() - const first = await buildNativeExecutable(spec) - expect(await buildNativeExecutable(spec)).toBe(first) - await writeFile(spec.outputPath, 'second build') - const second = await buildNativeExecutable(spec) - expect(second).not.toBe(first) - expect(await readFile(first, 'utf8')).toBe('first build') - expect(await readFile(second, 'utf8')).toBe('second build') - expect(await readFile(spec.executablePath, 'utf8')).toBe('second build') +it('returns the platform executable after the compiler exits', async () => { + const f = await fixture() + expect(await buildNativeExecutable(f.spec)).toBe(f.executable) + expect(f.handle.terminate).toHaveBeenCalledOnce() + expect(f.resolveExecutable).toHaveBeenCalledOnce() }) -it('refuses to overwrite a retained generation containing other bytes', async () => { - const spec = await fixture() - const first = await buildNativeExecutable(spec) - await writeFile(first, 'corrupted') - await expect(buildNativeExecutable(spec)).rejects.toThrow('does not match its content digest') - expect(await readFile(first, 'utf8')).toBe('corrupted') -}) - -it.each(['published', 'retained'] as const)('preserves an unreadable %s location', async (role) => { - const spec = await fixture() - const retained = await buildNativeExecutable(spec) - const path = role === 'published' ? spec.executablePath : retained - await rm(path) - await mkdir(path) - await expect(buildNativeExecutable(spec)).rejects.toMatchObject({ code: 'EISDIR' }) - expect((await stat(path)).isDirectory()).toBe(true) +it.each([{ exitCode: 1, exited: true }, { exitCode: 0, exited: false }])('does not resolve output after compiler failure or incomplete cleanup ($exitCode, $exited)', async ({ exitCode, exited }) => { + const f = await fixture(exitCode, exited) + await expect(buildNativeExecutable(f.spec)).rejects.toThrow() + expect(f.handle.terminate).toHaveBeenCalledOnce() + expect(f.handle.waitForExit).toHaveBeenCalledOnce() + expect(f.resolveExecutable).not.toHaveBeenCalled() }) diff --git a/scripts/check-workspace-constraints.ts b/scripts/check-workspace-constraints.ts index a9ec59f11b..910276384f 100644 --- a/scripts/check-workspace-constraints.ts +++ b/scripts/check-workspace-constraints.ts @@ -190,7 +190,7 @@ const packageFileExtras: Readonly> = { // CUA publishes its client API and attributed native source for local macOS builds. '@deepseek-ai/dsh-cua': ['lib/remote-types.js', 'lib/api.js', 'lib/bridge.js', 'lib/native-client.js', 'lib/protocol.js', 'lib/config.js', 'lib/native-schema.js', 'lib/native-build.js', 'lib/guidance.js'], '@deepseek-ai/dsh-experimental-cua-macos': ['native/bin', 'cua-helper.json', 'native/Package.swift', 'native/Info.plist', 'native/DSHComputerUse.icns', 'native/build_app.py', 'native/Sources', 'native/tests/swift', 'native/tests/test_swift.py', 'native/LICENSE.cua-driver', 'native/LICENSE.computer-use-icon', 'native/upstream.json', 'native/README.md', 'native/README.zh.md', 'native/protocol.schema.json'], - '@deepseek-ai/dsh-cua-windows': ['native/bin', 'native/CuaWindows.csproj', 'native/Directory.Build.props', 'native/app.manifest', 'native/src', 'native/protocol', 'native/protocol.schema.json', 'native/packages.lock.json'], + '@deepseek-ai/dsh-cua-windows': ['native/bin', 'native/entry', 'native/Directory.Build.props', 'native/protocol', 'native/protocol.schema.json'], '@deepseek-ai/dsh-webhook-github': ['examples/github-review/cordis.yml', 'examples/github-review/github-ready-review-rule.mjs'], // Liveshare publishes its built Relay gateway entry and the shared runtime // chunk that entry imports. Its `./types` export is a type-only module, so From f50feeef9fa2af763a4f928236f1263131c89abc Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Sat, 7 Nov 2026 22:23:13 +0800 Subject: [PATCH 021/184] Align Windows local build --- .../experimental/cua-windows/src/index.ts | 13 +- .../cua-windows/src/native-build.ts | 74 +++++----- .../cua-windows/tests/native-build.spec.ts | 139 +++++++++--------- .../cua-windows/tests/protocol.spec.ts | 5 +- .../tests/provider-lifecycle.spec.ts | 14 +- scripts/check-workspace-constraints.ts | 2 +- 6 files changed, 124 insertions(+), 123 deletions(-) diff --git a/packages/experimental/cua-windows/src/index.ts b/packages/experimental/cua-windows/src/index.ts index f74f61b539..ee77a148ad 100644 --- a/packages/experimental/cua-windows/src/index.ts +++ b/packages/experimental/cua-windows/src/index.ts @@ -28,21 +28,18 @@ export const name = 'cua-windows' /** Services required by shared CUA execution and managed native preparation. */ export const inject = ['computerUse', 'tools', 'systemPrompt', 'subprocess', 'agents'] -/** Windows compiler and native waiting policy, alongside shared CUA resource limits. */ +/** Windows native waiting policy, alongside shared CUA resource limits. */ export interface Config extends CuaConfig { - /** .NET SDK executable used for source preparation; installed payloads do not require it. */ - dotnetPath: string /** Windows PowerShell executable used to query WSL interoperation and the Windows architecture. */ windowsPowerShellPath: string /** Milliseconds between application-readiness and clipboard-release observations. */ pollIntervalMs: number } -/** Validate platform configuration before launching the compiler or helper. */ +/** Validate platform configuration before locating and launching the helper. */ export const Config = Schema.object({ ...CuaConfigFields, connectTimeoutMs: CuaConfigFields.connectTimeoutMs.default(30_000), - dotnetPath: Schema.string().min(1).default('dotnet'), windowsPowerShellPath: Schema.string().min(1).default('powershell.exe'), pollIntervalMs: Schema.number().step(1).min(1).max(2 ** 31 - 1).default(25), textEventIntervalMs: CuaConfigFields.textEventIntervalMs.default(0), @@ -54,7 +51,7 @@ export const Config = Schema.object({ /** * Prepare the Windows payload and install the shared authorized operation pipeline. * @param ctx - Owning provider context. - * @param config - Validated compiler, operation bounds, and application grants. + * @param config - Validated helper override, operation bounds, and application grants. * @returns Completion after preparation and reversible registrations. */ export async function apply(ctx: Context, config: Config): Promise { @@ -68,8 +65,8 @@ export async function apply(ctx: Context, config: Config): Promise { if (helperPath === undefined) { const architecture = wsl?.architecture ?? nativeHostArchitecture(process.platform, process.arch) helperPath = await prepareNativeExecutable({ - packageRoot: resolve(fileURLToPath(new URL('..', import.meta.url))), architecture, dotnetPath: config.dotnetPath, - subprocess: ctx.subprocess, signal: controller.signal, timeoutMs: config.buildTimeoutMs, graceMs: config.graceMs, + packageRoot: resolve(fileURLToPath(new URL('..', import.meta.url))), architecture, + subprocess: ctx.subprocess, timeoutMs: config.buildTimeoutMs, graceMs: config.graceMs, signal: controller.signal, }) } return wsl ? retainWslHelper(helperPath, wsl.cacheDirectory, controller.signal) : helperPath diff --git a/packages/experimental/cua-windows/src/native-build.ts b/packages/experimental/cua-windows/src/native-build.ts index 78feafdebd..364fa99c94 100644 --- a/packages/experimental/cua-windows/src/native-build.ts +++ b/packages/experimental/cua-windows/src/native-build.ts @@ -1,28 +1,27 @@ -/** Source compilation and installed Windows C# helper resolution. */ +/** Source-checkout compilation and installed Windows helper resolution. */ import { constants } from 'node:fs' import { access } from 'node:fs/promises' -import { dirname, join } from 'node:path' -import type { SubprocessRuntime } from '@deepseek-ai/dsh-subprocess' +import { join } from 'node:path' import { buildNativeExecutable as compileExecutable, sourceNativePackage } from '@deepseek-ai/dsh-cua/native-build' +import type { SubprocessRuntime } from '@deepseek-ai/dsh-subprocess' /** Architectures supported by the Windows helper payload. */ export type NativeArchitecture = 'arm64' | 'x64' -/** Compiler invocation and resource ownership for one Windows payload. */ +/** Package location, architecture and managed source-build lifetime. */ export interface NativeBuildSpec { packageRoot: string architecture: NativeArchitecture - dotnetPath: string subprocess: Pick - signal: AbortSignal timeoutMs: number graceMs: number + signal: AbortSignal } /** - * Validate the runtime host before preparing Windows native code. - * @param platform - Node host platform. - * @param architecture - Node process architecture. + * Validate the native Windows runtime host. + * @param platform Node host platform. + * @param architecture Node process architecture. * @returns Supported Windows architecture. */ export function nativeHostArchitecture(platform: string, architecture: string): NativeArchitecture { @@ -32,44 +31,49 @@ export function nativeHostArchitecture(platform: string, architecture: string): } /** - * Locate the package-owned Windows executable. - * @param packageRoot - Directory containing the Windows provider manifest. - * @param architecture - Architecture of the process running the helper. + * Locate an installed package's helper, using Electron's unpacked payload when applicable. + * @param packageRoot Directory containing the Windows provider manifest. + * @param architecture Architecture of the process running the helper. * @returns Absolute payload path. */ export function nativeExecutablePath(packageRoot: string, architecture: NativeArchitecture): string { - return join(packageRoot, 'native', 'bin', `win-${architecture}`, 'dsh-cua-windows.exe') + // TODO: Installed-package paths are placeholders until the Windows package layout is finalized. + const root = packageRoot.replace(/([\\/])app\.asar(?=[\\/])/u, '$1app.asar.unpacked') + return join(root, 'native', 'bin', `win-${architecture}`, 'dsh-cua-windows.exe') +} + +async function checkedExecutable(executable: string, signal: AbortSignal): Promise { + await access(executable, constants.X_OK) + signal.throwIfAborted() + return executable } /** - * Publish the self-contained C# application directly into the package payload directory. - * @param spec - SDK command, target, compiler ownership, and deadlines. - * @returns Package executable path after compiler cleanup; existing output files can be overwritten. + * Publish the source helper with dotnet from PATH under the shared compiler lock. + * @param spec Checkout, target architecture and managed process limits. + * @returns Published executable after compiler cleanup; build or output validation failures reject. */ -export function buildNativeExecutable(spec: NativeBuildSpec): Promise { - const native = join(spec.packageRoot, 'native') - const executable = nativeExecutablePath(spec.packageRoot, spec.architecture) - return compileExecutable({ ...spec, - argv: [spec.dotnetPath, 'publish', join(native, 'entry', 'CuaWindows.csproj'), '--configuration', 'Release', - '--runtime', `win-${spec.architecture}`, '--self-contained', 'true', '--output', dirname(executable), - '-p:EnableWindowsTargeting=true'], - lockPath: join(native, '.build', 'publish'), - resolveExecutable: async () => { - await access(executable, constants.X_OK) - return executable - }, +export async function buildNativeExecutable(spec: NativeBuildSpec): Promise { + const nativeRoot = join(spec.packageRoot, 'native') + const runtime = `win-${spec.architecture}` + const directory = join(nativeRoot, 'bin', runtime) + return compileExecutable({ + ...spec, + lockPath: join(nativeRoot, '.build', 'compiler'), + argv: ['dotnet', 'publish', join(nativeRoot, 'entry', 'CuaWindows.csproj'), + '--configuration', 'Release', '--runtime', runtime, '--self-contained', 'true', + '--output', directory, '-p:EnableWindowsTargeting=true'], + resolveExecutable: () => checkedExecutable(join(directory, 'dsh-cua-windows.exe'), spec.signal), }) } /** - * Compile only source checkouts; installed packages require their packaged native payload. - * @param spec - Source build and runtime target inputs. - * @returns The ready executable path. + * Build source helpers on activation; installed packages only resolve their payload. + * @param spec Package location, architecture and cancellation/deadline limits. + * @returns Existing executable after preparation; failures reject without fallback to another payload. */ export async function prepareNativeExecutable(spec: NativeBuildSpec): Promise { - if (await sourceNativePackage(spec.packageRoot, 'packages/experimental/cua-windows')) return buildNativeExecutable(spec) - const executable = nativeExecutablePath(spec.packageRoot, spec.architecture) - await access(executable, constants.X_OK) spec.signal.throwIfAborted() - return executable + if (await sourceNativePackage(spec.packageRoot, 'packages/experimental/cua-windows')) return buildNativeExecutable(spec) + return checkedExecutable(nativeExecutablePath(spec.packageRoot, spec.architecture), spec.signal) } diff --git a/packages/experimental/cua-windows/tests/native-build.spec.ts b/packages/experimental/cua-windows/tests/native-build.spec.ts index b9688080fc..3dfa08b08b 100644 --- a/packages/experimental/cua-windows/tests/native-build.spec.ts +++ b/packages/experimental/cua-windows/tests/native-build.spec.ts @@ -1,94 +1,89 @@ -/** Windows publishes its executable and dependencies directly into the package payload. */ -import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises' +/** Source preparation publishes for the selected Windows architecture; installed helpers never compile. */ +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' +import type { SubprocessHandle, SubprocessRuntime } from '@deepseek-ai/dsh-subprocess' import { expect, it, onTestFinished, vi } from 'vitest' -import type { SubprocessHandle, SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess' -import { buildNativeExecutable, nativeExecutablePath, nativeHostArchitecture, prepareNativeExecutable } from '../src/native-build.ts' +import { nativeExecutablePath, nativeHostArchitecture, prepareNativeExecutable, type NativeArchitecture } from '../src/native-build.ts' -async function fixture() { - const root = await mkdtemp(join(tmpdir(), 'cua-windows-build-')) +async function fixture(source: boolean, architecture: NativeArchitecture = 'x64', asar = false, exitCode = 0) { + const root = await mkdtemp(join(tmpdir(), 'cua-native-build-')) onTestFinished(() => rm(root, { recursive: true, force: true })) - const packageRoot = join(root, 'packages/experimental/cua-windows') - await mkdir(packageRoot, { recursive: true }) - const bytes = Buffer.from('MZ Windows executable fixture') - const files = new Map([ - ['dsh-cua-windows.dll', 'managed code'], - ['dsh-cua-windows.runtimeconfig.json', '{"runtimeOptions":{}}'], - ['dsh-cua-windows.deps.json', '{}'], - ['resources/zh-CN/messages.dll', 'localized resources'], - ]) - const spawn = vi.fn((request: SubprocessSpawnSpec): SubprocessHandle => ({ + const packageRoot = source ? join(root, 'packages', 'experimental', 'cua-windows') + : join(root, ...(asar ? ['app.asar'] : []), 'node_modules', '@deepseek-ai', 'dsh-cua-windows') + const executable = nativeExecutablePath(packageRoot, architecture) + const local = join(packageRoot, 'native', 'bin', 'local', 'dsh-cua-windows.exe') + const otherArchitecture = nativeExecutablePath(packageRoot, architecture === 'x64' ? 'arm64' : 'x64') + for (const path of [executable, local, otherArchitecture]) { + await mkdir(dirname(path), { recursive: true }) + await writeFile(path, 'helper', { mode: 0o755 }) + } + if (source) await writeFile(join(root, 'package.json'), JSON.stringify({ name: '@deepseek-ai/dsh-root' })) + const handle: SubprocessHandle = { stdin: undefined, stdout: undefined, stderr: undefined, control: undefined, collected: {}, - done: (async () => { - const output = request.argv[request.argv.indexOf('--output') + 1]! - await mkdir(output, { recursive: true }) - await writeFile(join(output, 'dsh-cua-windows.exe'), bytes, { mode: 0o755 }) - for (const [name, content] of files) { - await mkdir(dirname(join(output, name)), { recursive: true }) - await writeFile(join(output, name), content) - } - return { exitCode: 0, signal: null } - })(), - terminate: vi.fn(), waitForExit: async () => true, - })) - const spec = { packageRoot, architecture: 'x64' as const, dotnetPath: 'fixture-dotnet', subprocess: { spawn }, - signal: new AbortController().signal, timeoutMs: 60_000, graceMs: 1000 } - return { root, spec, spawn, bytes, files } + done: Promise.resolve({ exitCode, signal: null }), terminate: vi.fn(), waitForExit: vi.fn(async () => true), + } + const spawn = vi.fn(() => handle) + return { executable, handle, spawn, spec: { + packageRoot, architecture, subprocess: { spawn }, + timeoutMs: 60_000, graceMs: 100, signal: new AbortController().signal, + } } } -it.each(['x64', 'arm64'])('accepts the Windows %s process target', (architecture) => { +it.each(['x64', 'arm64'])('accepts the Windows %s runtime', (architecture) => { expect(nativeHostArchitecture('win32', architecture)).toBe(architecture) }) -it.each([['darwin', 'arm64'], ['linux', 'x64'], ['win32', 'ia32']])('rejects unsupported %s/%s runtime targets', (platform, architecture) => { +it.each([['darwin', 'arm64'], ['linux', 'x64'], ['win32', 'ia32']])('rejects unsupported %s/%s runtimes', (platform, architecture) => { expect(() => nativeHostArchitecture(platform, architecture)).toThrow('requires Windows') }) -it('publishes all dependencies and nested resources without single-file bundling', async () => { - const f = await fixture() - const output = await buildNativeExecutable(f.spec) - const packaged = nativeExecutablePath(f.spec.packageRoot, 'x64') - expect(output).toBe(packaged) - expect(await readFile(output)).toEqual(f.bytes) - for (const [name, content] of f.files) - expect(await readFile(join(dirname(output), name), 'utf8')).toBe(content) - const argv = f.spawn.mock.calls[0]![0].argv - expect(argv.slice(0, 3)).toEqual(['fixture-dotnet', 'publish', join(f.spec.packageRoot, 'native', 'entry', 'CuaWindows.csproj')]) - expect(argv).toEqual(expect.arrayContaining([ - '--runtime', 'win-x64', '--self-contained', 'true', '-p:EnableWindowsTargeting=true', - ])) - expect(argv.some(arg => arg.includes('PublishSingleFile') || arg.includes('IncludeNativeLibrariesForSelfExtract'))).toBe(false) - expect(argv[argv.indexOf('--output') + 1]).toBe(dirname(packaged)) - expect(await buildNativeExecutable(f.spec)).toBe(output) +it.each(['x64', 'arm64'] as const)('publishes source output for %s even when that output exists', async (architecture) => { + const f = await fixture(true, architecture) + expect(await prepareNativeExecutable(f.spec)).toBe(f.executable) + const nativeRoot = join(f.spec.packageRoot, 'native') + expect(f.spawn).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ + argv: ['dotnet', 'publish', join(nativeRoot, 'entry', 'CuaWindows.csproj'), + '--configuration', 'Release', '--runtime', `win-${architecture}`, '--self-contained', 'true', + '--output', join(nativeRoot, 'bin', `win-${architecture}`), '-p:EnableWindowsTargeting=true'], + cwd: f.spec.packageRoot, graceMs: f.spec.graceMs, + })) + expect(f.handle.terminate).toHaveBeenCalledOnce() + expect(f.handle.waitForExit).toHaveBeenCalledOnce() }) -it('publishes dependency updates at the same package path', async () => { - const f = await fixture() - const first = await buildNativeExecutable(f.spec) - f.files.set('dsh-cua-windows.dll', 'updated managed code') - expect(await buildNativeExecutable(f.spec)).toBe(first) - expect(await readFile(join(dirname(first), 'dsh-cua-windows.dll'), 'utf8')).toBe('updated managed code') +it('rejects missing published output without falling back to local or another architecture', async () => { + const f = await fixture(true) + await rm(f.executable) + await expect(prepareNativeExecutable(f.spec)).rejects.toMatchObject({ code: 'ENOENT' }) + expect(f.spawn).toHaveBeenCalledOnce() }) -it('rejects canceled preparation without starting the compiler', async () => { - const f = await fixture() - const controller = new AbortController() - controller.abort(new Error('provider unloaded')) - await expect(buildNativeExecutable({ ...f.spec, signal: controller.signal })).rejects.toThrow('provider unloaded') +it('rejects build failure even when previous output exists', async () => { + const f = await fixture(true, 'x64', false, 1) + await expect(prepareNativeExecutable(f.spec)).rejects.toThrow('native preparation failed') + expect(f.handle.waitForExit).toHaveBeenCalledOnce() +}) + +it.each(['x64', 'arm64'] as const)('uses the placeholder installed-package path for %s', async (architecture) => { + const f = await fixture(false, architecture) + expect(await prepareNativeExecutable(f.spec)).toBe(f.executable) + expect(f.spawn).not.toHaveBeenCalled() + await rm(f.executable) + await expect(prepareNativeExecutable(f.spec)).rejects.toMatchObject({ code: 'ENOENT' }) expect(f.spawn).not.toHaveBeenCalled() }) -it('compiles a recognized source package and resolves an installed payload without a compiler', async () => { - const f = await fixture() - await writeFile(join(f.root, 'package.json'), JSON.stringify({ name: '@deepseek-ai/dsh-root' })) - expect(await prepareNativeExecutable(f.spec)).toBe(nativeExecutablePath(f.spec.packageRoot, 'x64')) - expect(f.spawn).toHaveBeenCalledOnce() - await rm(join(f.root, 'package.json')) - expect(await prepareNativeExecutable(f.spec)).toBe(nativeExecutablePath(f.spec.packageRoot, 'x64')) - expect(f.spawn).toHaveBeenCalledOnce() +it('uses the unpacked Electron payload for the placeholder installed layout', async () => { + const f = await fixture(false, 'x64', true) + expect(await prepareNativeExecutable(f.spec)).toBe(f.executable) + expect(f.spawn).not.toHaveBeenCalled() + expect(f.executable).toContain('app.asar.unpacked') +}) + +it('rejects canceled helper preparation before compilation', async () => { + const f = await fixture(true) const controller = new AbortController() - controller.abort() - await expect(prepareNativeExecutable({ ...f.spec, signal: controller.signal })).rejects.toThrow() - await rm(nativeExecutablePath(f.spec.packageRoot, 'x64')) - await expect(prepareNativeExecutable(f.spec)).rejects.toThrow() + controller.abort(new Error('provider unloaded')) + await expect(prepareNativeExecutable({ ...f.spec, signal: controller.signal })).rejects.toThrow('provider unloaded') + expect(f.spawn).not.toHaveBeenCalled() }) diff --git a/packages/experimental/cua-windows/tests/protocol.spec.ts b/packages/experimental/cua-windows/tests/protocol.spec.ts index 0064d22ccb..18d0ce27bf 100644 --- a/packages/experimental/cua-windows/tests/protocol.spec.ts +++ b/packages/experimental/cua-windows/tests/protocol.spec.ts @@ -19,12 +19,11 @@ it('preserves Windows physical capture units and observed foreground changes', ( }) }) -it('resolves Windows compiler and input defaults while rejecting unsupported numeric limits', () => { +it('resolves Windows input defaults without a compiler path setting', () => { const resolved = Config({}) - expect(resolved.dotnetPath).toBe('dotnet') + expect(resolved).not.toHaveProperty('dotnetPath') expect(resolved.pollIntervalMs).toBe(25) expect(resolved.textEventIntervalMs).toBe(0) - expect(() => Config({ dotnetPath: '' })).toThrow() expect(() => Config({ pollIntervalMs: 0 })).toThrow() expect(() => Config({ maxResponseBytes: 2 ** 31 })).toThrow() }) diff --git a/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts index 4b1f2bf622..063cfc8805 100644 --- a/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts @@ -42,6 +42,8 @@ it('uses an absolute fixture without compiling and disposes the Host runtime', a expect(native.prepare).not.toHaveBeenCalled() expect(native.construct).toHaveBeenCalledWith(ctx, 13, 'pipe') const backend = native.install.mock.calls[0]![2] + expect(backend.helperPath).toBe(config.helperPath) + expect(native.architecture).not.toHaveBeenCalled() expect(backend.guidance).toBe(GUIDANCE) expect(backend.capabilities).toMatchObject({ platform: 'windows', appLevelAccessibility: false, keyboard: ['window'] }) const channel = { marker: 'native stream' } @@ -55,7 +57,11 @@ it('uses an absolute fixture without compiling and disposes the Host runtime', a it('prepares before installation and aborts the completed preparation scope on unload', async () => { const ctx = owner(), prepared = Promise.withResolvers() native.prepare.mockReturnValueOnce(prepared.promise) - const pending = apply(ctx, Config({})) + const config = Config({ buildTimeoutMs: 90_000, graceMs: 250 }) + const pending = apply(ctx, config) + expect(native.prepare.mock.calls[0]![0]).toMatchObject({ + subprocess: ctx.subprocess, timeoutMs: config.buildTimeoutMs, graceMs: config.graceMs, + }) expect(native.install).not.toHaveBeenCalled() prepared.resolve(resolve('compiled.exe')) await pending @@ -63,10 +69,10 @@ it('prepares before installation and aborts the completed preparation scope on u await ctx.fiber.dispose() expect(native.prepare.mock.calls[0]![0].signal.aborted).toBe(true) }) -it('reports compiler failure without installing tool registrations', async () => { - native.prepare.mockRejectedValueOnce(new Error('compiler unavailable')) +it('reports a missing helper without installing tool registrations', async () => { + native.prepare.mockRejectedValueOnce(new Error('helper unavailable')) const ctx = owner() - await expect(apply(ctx, Config({}))).rejects.toThrow('compiler unavailable') + await expect(apply(ctx, Config({}))).rejects.toThrow('helper unavailable') await ctx.fiber.dispose() expect(native.install).not.toHaveBeenCalled() }) diff --git a/scripts/check-workspace-constraints.ts b/scripts/check-workspace-constraints.ts index 910276384f..ea09dab198 100644 --- a/scripts/check-workspace-constraints.ts +++ b/scripts/check-workspace-constraints.ts @@ -190,7 +190,7 @@ const packageFileExtras: Readonly> = { // CUA publishes its client API and attributed native source for local macOS builds. '@deepseek-ai/dsh-cua': ['lib/remote-types.js', 'lib/api.js', 'lib/bridge.js', 'lib/native-client.js', 'lib/protocol.js', 'lib/config.js', 'lib/native-schema.js', 'lib/native-build.js', 'lib/guidance.js'], '@deepseek-ai/dsh-experimental-cua-macos': ['native/bin', 'cua-helper.json', 'native/Package.swift', 'native/Info.plist', 'native/DSHComputerUse.icns', 'native/build_app.py', 'native/Sources', 'native/tests/swift', 'native/tests/test_swift.py', 'native/LICENSE.cua-driver', 'native/LICENSE.computer-use-icon', 'native/upstream.json', 'native/README.md', 'native/README.zh.md', 'native/protocol.schema.json'], - '@deepseek-ai/dsh-cua-windows': ['native/bin', 'native/entry', 'native/Directory.Build.props', 'native/protocol', 'native/protocol.schema.json'], + '@deepseek-ai/dsh-cua-windows': ['native/bin'], '@deepseek-ai/dsh-webhook-github': ['examples/github-review/cordis.yml', 'examples/github-review/github-ready-review-rule.mjs'], // Liveshare publishes its built Relay gateway entry and the shared runtime // chunk that entry imports. Its `./types` export is a type-only module, so From f8f57aa8e0cf8221c15b96dbd564309993ea2a35 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Sat, 7 Nov 2026 22:46:06 +0800 Subject: [PATCH 022/184] Fix OS check --- packages/experimental/cua-windows/native/entry/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/experimental/cua-windows/native/entry/Program.cs b/packages/experimental/cua-windows/native/entry/Program.cs index ec178f82d3..9c1577cfab 100644 --- a/packages/experimental/cua-windows/native/entry/Program.cs +++ b/packages/experimental/cua-windows/native/entry/Program.cs @@ -5,7 +5,7 @@ using DeepSeek.Cua.Windows; try { - if (OperatingSystem.IsWindowsVersionAtLeast(10, 0, 19041)) + if (!OperatingSystem.IsWindowsVersionAtLeast(10, 0, 19041)) { throw new NativeFailure("UNSUPPORTED", "Windows CUA requires Windows 10 build 19041 or later"); } From 05f557bbf6995eb089557a093b54836ffe9ec2eb Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Mon, 9 Nov 2026 00:41:55 +0800 Subject: [PATCH 023/184] Use string for window id --- .../native/Sources/CuaNative/AXWorker.swift | 12 +- .../Sources/CuaNative/NativePlatform.swift | 2 +- .../native/Sources/CuaNative/Protocol.swift | 2 +- .../Sources/CuaNative/RequestAdmission.swift | 9 +- .../cua-macos/native/protocol.schema.json | 90 +++---- .../native/tests/AxlessFixture.swift | 2 +- .../native/tests/CapabilitiesFixture.swift | 2 +- .../cua-macos/native/tests/Fixture.swift | 6 +- .../native/tests/application_consent_e2e.py | 8 +- .../native/tests/capabilities_e2e.py | 2 +- .../cua-macos/native/tests/protocol_e2e.py | 2 +- .../native/tests/swift/ForegroundTests.swift | 8 + .../native/tests/swift/ProtocolTests.swift | 23 +- .../cua-macos/tests/guidance.spec.ts | 2 +- .../cua-macos/tests/large-image-ptc.spec.ts | 2 +- .../tests/loader-composition.spec.ts | 22 +- .../tests/persistent-bridge.built.e2e.ts | 4 +- .../tests/protocol-generation.spec.ts | 2 +- .../tests/provider-lifecycle.spec.ts | 44 ++-- .../native/desktop-tests/Program.cs | 3 +- .../cua-windows/native/entry/Accessibility.cs | 10 +- .../cua-windows/native/entry/Applications.cs | 8 +- .../native/entry/DesktopExecutor.cs | 13 +- .../native/entry/DesktopWindows.cs | 49 ++-- .../cua-windows/native/entry/Dispatchers.cs | 18 +- .../cua-windows/native/entry/Win32.cs | 3 - .../cua-windows/native/entry/Windows.cs | 27 +-- .../cua-windows/native/protocol.schema.json | 90 +++---- .../cua-windows/native/tests/Program.cs | 2 +- .../cua-windows/tests/desktop-tool.spec.ts | 1 + .../cua-windows/tests/protocol.spec.ts | 2 +- packages/experimental/cua/src/api.ts | 8 +- packages/experimental/cua/src/coordinates.ts | 8 +- packages/experimental/cua/src/guidance.ts | 12 +- packages/experimental/cua/src/protocol.ts | 29 +-- packages/experimental/cua/src/types.ts | 7 +- packages/experimental/cua/tests/api.spec.ts | 222 ++++++++++-------- .../experimental/cua/tests/bridge.spec.ts | 12 +- .../cua/tests/coordinates.spec.ts | 42 ++-- .../cua/tests/native-schema.spec.ts | 11 + .../experimental/cua/tests/protocol.spec.ts | 46 +++- .../session/cua-native/replay.override.json | 64 ++--- .../cua-native/workspace/native-helper.mjs | 20 +- .../session/cua-ptc/replay.override.json | 2 +- 44 files changed, 488 insertions(+), 465 deletions(-) diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift index dea2eacb7a..30ed1bf798 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift @@ -41,8 +41,8 @@ struct ForegroundObservation: Sendable { } var json: JSONValue { .object(["frontPid": frontPID.map { .number(Double($0)) } ?? .null, - "focusedWindowId": focusedWindowID.map { .number(Double($0)) } ?? .null, - "frontWindowId": frontWindowID.map { .number(Double($0)) } ?? .null, + "focusedWindowId": focusedWindowID.map { .string(String($0)) } ?? .null, + "frontWindowId": frontWindowID.map { .string(String($0)) } ?? .null, "frontWindowPid": frontWindowPID.map { .number(Double($0)) } ?? .null]) } } @@ -275,7 +275,7 @@ actor AXWorker { let changed = ForegroundObservation.change(beforePID: beforePID, beforeWindow: beforeWindow, afterPID: afterPID, afterWindow: afterWindow) return .result(.object(["dispatched": .bool(true), - "windowId": restored.map { .number(Double($0)) } ?? .null, "foregroundChanged": changed])) + "windowId": restored.map { .string(String($0)) } ?? .null, "foregroundChanged": changed])) case "activate": return .foreground(ForegroundPlan(appHandle: handle, identity: identity)) case "getState": @@ -302,8 +302,8 @@ actor AXWorker { observedWindowBounds[handle, default: [:]][observed.windowID] = observed.bounds } return .result(.object(["appHandle": .string(handle), - "windowId": window.map { .number(Double($0)) } ?? .null, - "focusedWindowId": projection.focusedWindowID.map { .number(Double($0)) } ?? .null, + "windowId": window.map { .string(String($0)) } ?? .null, + "focusedWindowId": projection.focusedWindowID.map { .string(String($0)) } ?? .null, "snapshotId": .string(id), "tree": .string(projection.tree), "elements": .array(projection.elements), "windows": .array(observedWindows.map(\.json)), "truncated": .bool(projection.truncated)])) case "screenshot": @@ -468,7 +468,7 @@ actor AXWorker { trace?.mark("postflight.end") return .object(["mimeType": .string("image/png"), "data": .string(encoded), "pixelWidth": .number(Double(image.width)), "pixelHeight": .number(Double(image.height)), "bounds": after.bounds.json, - "coordinateSpace": .string("window-points"), "windowId": .number(Double(after.windowID))]) + "coordinateSpace": .string("window-points"), "windowId": .string(String(after.windowID))]) } static func mouseMoveResult(route: String, pointerMoved: Bool) -> JSONValue { .object(["dispatched": .bool(true), "hoverRoute": .string(route), "systemPointerMoved": .bool(pointerMoved)]) diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/NativePlatform.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/NativePlatform.swift index d55831132c..b3b4df4bb8 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/NativePlatform.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/NativePlatform.swift @@ -140,7 +140,7 @@ enum NativePlatform { return rows.compactMap { row in let layer = (row[kCGWindowLayer as String] as? NSNumber)?.intValue ?? 0 guard allLayers || layer == 0, - let id = (row[kCGWindowNumber as String] as? NSNumber)?.uint32Value, + let id = (row[kCGWindowNumber as String] as? NSNumber)?.uint32Value, id != 0, let pid = (row[kCGWindowOwnerPID as String] as? NSNumber)?.int32Value else { return nil } let raw = row[kCGWindowBounds as String] as? [String: NSNumber] ?? [:] let bounds = WindowBounds(x: raw["X"]?.doubleValue ?? 0, y: raw["Y"]?.doubleValue ?? 0, diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/Protocol.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/Protocol.swift index cbb0ba577a..b38076fd09 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/Protocol.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/Protocol.swift @@ -141,7 +141,7 @@ struct WindowInfo: Sendable { var json: JSONValue { .object([ - "windowId": .number(Double(windowID)), + "windowId": .string(String(windowID)), "appName": .string(appName), "title": .string(title), "bounds": bounds.json, "isOnScreen": .bool(isOnScreen), "onCurrentSpace": onCurrentSpace.map(JSONValue.bool) ?? .null, ]) diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestAdmission.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestAdmission.swift index 5eb70381e4..3241c782c9 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestAdmission.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestAdmission.swift @@ -22,6 +22,7 @@ struct RequestParameters: Sendable { } } self.values = values + if contains("windowId") { _ = try windowID() } } static func invalid(_ message: String) -> NativeFailure { NativeFailure(code: "INVALID_ARGUMENT", message: message) } func contains(_ key: String) -> Bool { values[key] != nil } @@ -54,7 +55,13 @@ struct RequestParameters: Sendable { } return integer } - func windowID() throws -> UInt32 { UInt32(try integer("windowId", in: 1...Int(UInt32.max))) } + func windowID() throws -> UInt32 { + let text = try string("windowId") + guard let id = UInt32(text), id > 0, String(id) == text else { + throw Self.invalid("windowId must be a canonical decimal string in 1...\(UInt32.max)") + } + return id + } func optionalWindowID() throws -> UInt32? { contains("windowId") ? try windowID() : nil } /// Element ids are opaque strings on the wire; this helper accepts its decimal form and returns the snapshot index. func elementIdIndex() throws -> Int { diff --git a/packages/experimental/cua-macos/native/protocol.schema.json b/packages/experimental/cua-macos/native/protocol.schema.json index 4dda3c8511..7288d8586f 100644 --- a/packages/experimental/cua-macos/native/protocol.schema.json +++ b/packages/experimental/cua-macos/native/protocol.schema.json @@ -168,9 +168,8 @@ "minLength": 1 }, "windowId": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 4294967295 + "type": "string", + "minLength": 1 } }, "required": [ @@ -235,9 +234,8 @@ "minLength": 1 }, "windowId": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 4294967295 + "type": "string", + "minLength": 1 }, "includeMenus": { "description": "Expand menu contents; omitted or false shows menu-bar entries only.", @@ -291,9 +289,8 @@ "minLength": 1 }, "windowId": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 4294967295 + "type": "string", + "minLength": 1 }, "snapshotId": { "type": "string", @@ -338,9 +335,8 @@ "minLength": 1 }, "windowId": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 4294967295 + "type": "string", + "minLength": 1 }, "snapshotId": { "type": "string", @@ -427,9 +423,8 @@ "minLength": 1 }, "windowId": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 4294967295 + "type": "string", + "minLength": 1 }, "snapshotId": { "type": "string", @@ -476,9 +471,8 @@ "minLength": 1 }, "windowId": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 4294967295 + "type": "string", + "minLength": 1 }, "snapshotId": { "type": "string", @@ -505,9 +499,8 @@ "minLength": 1 }, "windowId": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 4294967295 + "type": "string", + "minLength": 1 }, "snapshotId": { "type": "string", @@ -560,9 +553,8 @@ "minLength": 1 }, "windowId": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 4294967295 + "type": "string", + "minLength": 1 }, "snapshotId": { "type": "string", @@ -628,9 +620,8 @@ "minLength": 1 }, "windowId": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 4294967295 + "type": "string", + "minLength": 1 }, "snapshotId": { "type": "string", @@ -720,9 +711,8 @@ "minLength": 1 }, "windowId": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 4294967295 + "type": "string", + "minLength": 1 }, "snapshotId": { "type": "string", @@ -805,9 +795,8 @@ "minLength": 1 }, "windowId": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 4294967295 + "type": "string", + "minLength": 1 }, "snapshotId": { "type": "string", @@ -871,9 +860,8 @@ "minLength": 1 }, "windowId": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 4294967295 + "type": "string", + "minLength": 1 }, "text": { "type": "string" @@ -911,9 +899,8 @@ "minLength": 1 }, "windowId": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 4294967295 + "type": "string", + "minLength": 1 }, "text": { "type": "string" @@ -982,9 +969,8 @@ "minLength": 1 }, "windowId": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 4294967295 + "type": "string", + "minLength": 1 }, "key": { "type": "string", @@ -1029,9 +1015,8 @@ "minLength": 1 }, "windowId": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 4294967295 + "type": "string", + "minLength": 1 }, "key": { "type": "string", @@ -1078,9 +1063,8 @@ "minLength": 1 }, "windowId": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 4294967295 + "type": "string", + "minLength": 1 }, "snapshotId": { "type": "string", @@ -1141,9 +1125,8 @@ "minLength": 1 }, "windowId": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 4294967295 + "type": "string", + "minLength": 1 }, "mouseButton": { "type": "string", @@ -1235,9 +1218,8 @@ "minLength": 1 }, "windowId": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 4294967295 + "type": "string", + "minLength": 1 } }, "required": [ diff --git a/packages/experimental/cua-macos/native/tests/AxlessFixture.swift b/packages/experimental/cua-macos/native/tests/AxlessFixture.swift index bb5f89f452..05bfa4c50c 100644 --- a/packages/experimental/cua-macos/native/tests/AxlessFixture.swift +++ b/packages/experimental/cua-macos/native/tests/AxlessFixture.swift @@ -80,7 +80,7 @@ final class AxlessFixture: NSObject, NSApplicationDelegate, NSWindowDelegate { let rect = button.convert(button.bounds, to: nil) let data = try! JSONSerialization.data(withJSONObject: [ "pid": ProcessInfo.processInfo.processIdentifier, - "windowId": window.windowNumber, + "windowId": window.windowNumber > 0 ? String(window.windowNumber) as Any : NSNull(), "hiddenAX": hiddenAX, "count": count, "resizeCount": resizeCount, "moved": moved, "hidden": NSApplication.shared.isHidden, "minimized": window.isMiniaturized, "active": NSApplication.shared.isActive, diff --git a/packages/experimental/cua-macos/native/tests/CapabilitiesFixture.swift b/packages/experimental/cua-macos/native/tests/CapabilitiesFixture.swift index 8e621fd014..7818e1a0f9 100644 --- a/packages/experimental/cua-macos/native/tests/CapabilitiesFixture.swift +++ b/packages/experimental/cua-macos/native/tests/CapabilitiesFixture.swift @@ -116,7 +116,7 @@ final class CapabilitiesFixture: NSObject, NSApplicationDelegate, NSWindowDelega } let frame = pad.convert(pad.bounds, to: nil) let selection = text.selectedRange() - let result: [String: Any] = ["pid": ProcessInfo.processInfo.processIdentifier, "windowId": window.windowNumber, + let result: [String: Any] = ["pid": ProcessInfo.processInfo.processIdentifier, "windowId": window.windowNumber > 0 ? String(window.windowNumber) as Any : NSNull(), "active": NSApplication.shared.isActive, "keyWindow": window.isKeyWindow, "textFocused": window.firstResponder === text, "pasteAttempts": pasteAttempts, "text": text.string, "selection": [selection.location, selection.length], "runs": runs, "events": events, "axPresses": axPresses, diff --git a/packages/experimental/cua-macos/native/tests/Fixture.swift b/packages/experimental/cua-macos/native/tests/Fixture.swift index 930f7df5d2..a9d81eaafe 100644 --- a/packages/experimental/cua-macos/native/tests/Fixture.swift +++ b/packages/experimental/cua-macos/native/tests/Fixture.swift @@ -209,12 +209,12 @@ final class Fixture: NSObject, NSApplicationDelegate, NSTextFieldDelegate { ? CGWindowListCopyWindowInfo(.optionIncludingWindow, CGWindowID(overlayID)) as? [[String: Any]] : nil let overlayOnScreen = overlayRows?.contains { ($0[kCGWindowIsOnscreen as String] as? Bool) == true } ?? false let state: [String: Any] = ["count": count, "secondaryCount": secondaryCount, "text": field.stringValue, "selectedFile": selectedFile, - "rowCount": rowCount, "primaryWindowId": window.windowNumber, + "rowCount": rowCount, "primaryWindowId": window.windowNumber > 0 ? String(window.windowNumber) as Any : NSNull(), "dragDownCount": dragPad.dragDownCount, "dragCount": dragPad.dragCount, "dragPoint": [dragPad.lastPoint.x, dragPad.lastPoint.y], "hoverVisible": !dragPad.hoverButton.isHidden, "hoverClicks": dragPad.hoverClicks, "cursorSamples": cursorSamples, "cursorChanges": cursorChanges, - "overlayMode": overlayMode, "overlayWindowId": inputOverlay?.windowNumber ?? 0, - "overlayOnScreen": overlayOnScreen, "hoverHitWindow": hoverHitWindow, + "overlayMode": overlayMode, "overlayWindowId": overlayID > 0 ? String(overlayID) as Any : NSNull(), + "overlayOnScreen": overlayOnScreen, "hoverHitWindow": hoverHitWindow > 0 ? String(hoverHitWindow) as Any : NSNull(), "rightDownCount": dragPad.rightDownCount, "rightUpCount": dragPad.rightUpCount, "scrollEventCount": scroll.eventCount, "scrollY": scroll.contentView.bounds.origin.y, "dragBounds": windowPoints(dragPad), "scrollBounds": windowPoints(scroll), "primaryWindowSize": [window.frame.width, window.frame.height], diff --git a/packages/experimental/cua-macos/native/tests/application_consent_e2e.py b/packages/experimental/cua-macos/native/tests/application_consent_e2e.py index f2579584b1..aaec4355ae 100644 --- a/packages/experimental/cua-macos/native/tests/application_consent_e2e.py +++ b/packages/experimental/cua-macos/native/tests/application_consent_e2e.py @@ -40,7 +40,7 @@ def main(): nonlocal checked_windows if not args.desktop: return - state = wait_for_state(state_path, lambda value: value["pid"] == pid and value["windowId"] > 0) + state = wait_for_state(state_path, lambda value: value["pid"] == pid and bool(value["windowId"])) owner = {"appHandle": app["appHandle"], "windowId": state["windowId"]} observed = helper.call("getState", {**owner, "maxElements": 2000, "maxDepth": 25}) pad = next(item for item in observed["elements"] if item["role"] == "AXButton" and item["title"] == "Input receiver") @@ -125,7 +125,7 @@ def main(): pending = helper.call("getApp", {"selector": str(app)}) process = subprocess.Popen([str(executable)], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL) cleanup.callback(stop, process) - wait_for_state(state, lambda value: value["pid"] == process.pid and value["windowId"] > 0) + wait_for_state(state, lambda value: value["pid"] == process.pid and bool(value["windowId"])) running = helper.call("getApp", {"selector": str(process.pid)}) assert running["authorization"]["id"] == pending["authorization"]["id"] == expected, running["authorization"] check_window(running, state, process.pid) @@ -136,7 +136,7 @@ def main(): process = subprocess.Popen([str(binary), str(state), "--background"], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL) cleanup.callback(stop, process) try: - wait_for_state(state, lambda value: value["pid"] == process.pid and value["windowId"] > 0) + wait_for_state(state, lambda value: value["pid"] == process.pid and bool(value["windowId"])) running = helper.call("getApp", {"selector": str(process.pid)}) authorization = running["authorization"] assert running.get("bundleId") is None and authorization["persistable"] is True, authorization @@ -155,7 +155,7 @@ def main(): pending = helper.call("getApp", {"selector": str(app)}) launched = helper.call("launchApp", {"appHandle": pending["appHandle"]}) assert launched["running"] is True, launched - pid = wait_for_state(state, lambda value: value["windowId"] > 0)["pid"] + pid = wait_for_state(state, lambda value: bool(value["windowId"]))["pid"] executable.unlink() buffer = ctypes.create_string_buffer(4096) ctypes.set_errno(0) diff --git a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py index aaf9cd03e7..21cc4e0cc4 100644 --- a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py +++ b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py @@ -152,7 +152,7 @@ def main(): # The Host consent barrier is separately exercised by provider-lifecycle.spec.ts. app = call("launchApp", owner) assert app["running"] is True, app - pid = wait_for_state(state_file, lambda value: value["windowId"] > 0)["pid"] + pid = wait_for_state(state_file, lambda value: bool(value["windowId"]))["pid"] if not args.click_only: call("activate", owner) state = wait_for_state(state_file, lambda value: value["pid"] == pid and value["active"] and value["keyWindow"]) diff --git a/packages/experimental/cua-macos/native/tests/protocol_e2e.py b/packages/experimental/cua-macos/native/tests/protocol_e2e.py index 625df4d577..57022cd881 100644 --- a/packages/experimental/cua-macos/native/tests/protocol_e2e.py +++ b/packages/experimental/cua-macos/native/tests/protocol_e2e.py @@ -59,7 +59,7 @@ def cases(): for method in ("typeText", "pressKey", "paste"): identifier = "window-keyboard-" + method argument = {"key": "Return"} if method == "pressKey" else {"text": "do not dispatch"} - result.append((request(identifier, method, {"appHandle": "never-selected", "windowId": 1, **argument}), + result.append((request(identifier, method, {"appHandle": "never-selected", "windowId": "1", **argument}), identifier, "INVALID_ARGUMENT", "macOS keyboard input follows application focus; use the App object")) for index in range(24): identifier = f"ordered-{index:02d}" diff --git a/packages/experimental/cua-macos/native/tests/swift/ForegroundTests.swift b/packages/experimental/cua-macos/native/tests/swift/ForegroundTests.swift index f784f18eda..232d0b7e3b 100644 --- a/packages/experimental/cua-macos/native/tests/swift/ForegroundTests.swift +++ b/packages/experimental/cua-macos/native/tests/swift/ForegroundTests.swift @@ -7,6 +7,14 @@ import Testing #expect(AXWorker.actionResult == .object(["dispatched": .bool(true)])) } +@Test func emitsForegroundWindowIDsAsStringsAndPIDsAsNumbers() { + let observed = ForegroundObservation(frontPID: 42, focusedWindowID: 7, frontWindowID: 8, frontWindowPID: 43) + #expect(observed.json == .object([ + "frontPid": .number(42), "focusedWindowId": .string("7"), + "frontWindowId": .string("8"), "frontWindowPid": .number(43), + ])) +} + @Test func reportsOnlyObservableForegroundChanges() { #expect(ForegroundObservation.change(beforePID: 1, beforeWindow: nil, afterPID: 2, afterWindow: nil) == .bool(true)) #expect(ForegroundObservation.change(beforePID: nil, beforeWindow: 3, afterPID: nil, afterWindow: 4) == .bool(true)) diff --git a/packages/experimental/cua-macos/native/tests/swift/ProtocolTests.swift b/packages/experimental/cua-macos/native/tests/swift/ProtocolTests.swift index 84a9fec849..a09519ff11 100644 --- a/packages/experimental/cua-macos/native/tests/swift/ProtocolTests.swift +++ b/packages/experimental/cua-macos/native/tests/swift/ProtocolTests.swift @@ -48,7 +48,7 @@ func refusesInvalidRequestEnvelopes(_ source: String) { let encoded = try JSONEncoder().encode(window.json) let object = try #require(JSONSerialization.jsonObject(with: encoded) as? [String: Any]) #expect(object["onCurrentSpace"] is NSNull) - #expect(window.json["windowId"] == .number(7)) + #expect(window.json["windowId"] == .string("7")) #expect(window.json["bounds"]["x"] == .number(-100)) #expect(window.json["isOnScreen"] == .bool(true)) } @@ -74,11 +74,24 @@ func refusesInvalidRequestEnvelopes(_ source: String) { } } -@Test(arguments: ["true", "1.5", "0", "4294967296", "\"7\""]) -func rejectsInvalidWindowIDs(_ value: String) throws { - let request = try NativeRequest(data: Data("{\"id\":\"call\",\"method\":\"screenshot\",\"params\":{\"windowId\":\(value)}}".utf8)) +@Test func acceptsWindowIDStrings() throws { + let request = try NativeRequest(data: Data(#"{"id":"call","method":"screenshot","params":{"windowId":"7"}}"#.utf8)) let params = try RequestParameters(request) - #expect(throws: NativeFailure.self) { try params.windowID() } + #expect(try params.windowID() == 7) + #expect(try params.optionalWindowID() == 7) +} + +@Test(arguments: ["true", "null", "7"]) +func rejectsNonStringWindowIDs(_ value: String) throws { + let request = try NativeRequest(data: Data("{\"id\":\"call\",\"method\":\"screenshot\",\"params\":{\"windowId\":\(value)}}".utf8)) + #expect(throws: NativeFailure.self) { try RequestParameters(request) } +} + +@Test func validatesOptionalWindowIDsBeforeOperationDispatch() throws { + let absent = try RequestParameters(NativeRequest(data: Data(#"{"id":"call","method":"getState","params":{}}"#.utf8))) + #expect(try absent.optionalWindowID() == nil) + let numeric = try NativeRequest(data: Data(#"{"id":"call","method":"listActions","params":{"windowId":7}}"#.utf8)) + #expect(throws: NativeFailure.self) { try RequestParameters(numeric) } } @Test func rejectsRoundedIntegerOverflowWithoutTrapping() throws { diff --git a/packages/experimental/cua-macos/tests/guidance.spec.ts b/packages/experimental/cua-macos/tests/guidance.spec.ts index ae947d7ab7..8537bb3fff 100644 --- a/packages/experimental/cua-macos/tests/guidance.spec.ts +++ b/packages/experimental/cua-macos/tests/guidance.spec.ts @@ -68,7 +68,7 @@ it('defines every non-builtin type name used in method signatures', () => { expect(COMMON_GUIDANCE).toContain('ActionResult = { dispatched: boolean, foregroundChanged?: boolean | null }') expect(COMMON_GUIDANCE).toContain('JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue }') expect(COMMON_GUIDANCE).toContain('App is the application object with readonly app.appHandle: string (opaque) and the methods listed below for app level') - expect(COMMON_GUIDANCE).toContain('Window is the window object with readonly window.windowId: number and the methods listed below for window level') + expect(COMMON_GUIDANCE).toContain('Window is the window object with readonly window.windowId: string and the methods listed below for window level') expect(COMMON_GUIDANCE).toContain('Signatures show resolved return values after await') }) diff --git a/packages/experimental/cua-macos/tests/large-image-ptc.spec.ts b/packages/experimental/cua-macos/tests/large-image-ptc.spec.ts index c042931169..3ba6717b33 100644 --- a/packages/experimental/cua-macos/tests/large-image-ptc.spec.ts +++ b/packages/experimental/cua-macos/tests/large-image-ptc.spec.ts @@ -108,7 +108,7 @@ it.skipIf(process.platform === 'win32')('delivers a valid PNG larger than 4 MiB this.requests.push(options) if (this.requests.length === 1) { const code = 'const app = await tools.cua({ method: "getApp", params: { selector: "9" } }); ' - + 'const result = await tools.cua({ method: "screenshot", params: { appHandle: app.appHandle, windowId: 7 } }); ' + + 'const result = await tools.cua({ method: "screenshot", params: { appHandle: app.appHandle, windowId: "7" } }); ' + 'return { mimeType: result.mimeType, encodedLength: result.data.length };' const call = { type: 'tool-call' as const, id: ToolCallId('large-image-ptc'), name: 'run_code', arguments: JSON.stringify({ code, description: 'Inspect the generated large screenshot' }), diff --git a/packages/experimental/cua-macos/tests/loader-composition.spec.ts b/packages/experimental/cua-macos/tests/loader-composition.spec.ts index cfd7fe4883..95e093b16e 100644 --- a/packages/experimental/cua-macos/tests/loader-composition.spec.ts +++ b/packages/experimental/cua-macos/tests/loader-composition.spec.ts @@ -33,10 +33,10 @@ const png = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAACXBIWXMAAAPoAAAD6AG const calls = [ { method: 'getCapabilities', params: {} }, { method: 'getApp', params: { selector: 'test.fixture' } }, - { method: 'getState', params: { appHandle: 'fixture-app', windowId: 7 } }, + { method: 'getState', params: { appHandle: 'fixture-app', windowId: '7' } }, { method: 'click', params: { appHandle: 'fixture-app', snapshotId: 'fixture-snapshot-1', elementId: '0', holdMs: 800 } }, - { method: 'getState', params: { appHandle: 'fixture-app', windowId: 7 } }, - { method: 'screenshot', params: { appHandle: 'fixture-app', windowId: 7 } }, + { method: 'getState', params: { appHandle: 'fixture-app', windowId: '7' } }, + { method: 'screenshot', params: { appHandle: 'fixture-app', windowId: '7' } }, ] class VisualModel extends LlmAdapter { @@ -139,13 +139,13 @@ it.skipIf(process.platform === 'win32')('shares one application between retained expect(toolCalls[3]?.data.arguments).toBe(JSON.stringify(calls[3])) const direct = await executeToolFixture(context, { agent, signal: new AbortController().signal, - callId: ToolCallId('programmatic-window'), name: 'cua', arguments: { method: 'screenshot', params: { appHandle: 'fixture-app', windowId: 7 } }, + callId: ToolCallId('programmatic-window'), name: 'cua', arguments: { method: 'screenshot', params: { appHandle: 'fixture-app', windowId: '7' } }, }) expect(direct.isError).toBe(false) expect(direct.value).toMatchObject({ mimeType: 'image/png', data: png }) expect(context.computerUse.providerName).toBe('dsh-cua') for (const [callId, activationRequested, beforePid, beforeWindowId] of [ - ['activate-first', true, 42, 99], ['activate-repeat', false, 9, 7], + ['activate-first', true, 42, '99'], ['activate-repeat', false, 9, '7'], ] as const) { const activated = await executeToolFixture(context, { agent, signal: new AbortController().signal, callId: ToolCallId(callId), name: 'cua', @@ -155,8 +155,8 @@ it.skipIf(process.platform === 'win32')('shares one application between retained expect(activated.value).toEqual({ dispatched: true, foregroundChanged: beforePid !== 9, foreground: { requestId: callId, targetPid: 9, activationRequested, - before: { frontPid: beforePid, focusedWindowId: 7, frontWindowId: beforeWindowId, frontWindowPid: beforePid }, - after: { frontPid: 9, focusedWindowId: 7, frontWindowId: 7, frontWindowPid: 9 }, + before: { frontPid: beforePid, focusedWindowId: '7', frontWindowId: beforeWindowId, frontWindowPid: beforePid }, + after: { frontPid: 9, focusedWindowId: '7', frontWindowId: '7', frontWindowPid: 9 }, }, }) expect(JSON.stringify(activated.content)).toContain(callId) @@ -172,14 +172,14 @@ it.skipIf(process.platform === 'win32')('shares one application between retained return z.json().parse(result.value) }) const retainedApp = await objectApi(agent).getApp('test.fixture') - const retainedWindow = await retainedApp.getWindow(7) + const retainedWindow = await retainedApp.getWindow('7') expect(await retainedWindow.getAccessibilityTree({ emit: false })).toContain('Count: 1') const peer = await context.agents.create({ sessionId: SessionId('native-loader-peer'), agentOptions: { provider: 'native-fixture', model: 'vision' } }) const peerApp = await objectApi(peer.agent).getApp('test.fixture') - const peerWindow = await peerApp.getWindow(7) + const peerWindow = await peerApp.getWindow('7') expect(peerApp.appHandle).not.toBe(retainedApp.appHandle) const screenshot = await peerWindow.getScreenshot({ emit: false }) - expect(screenshot).toMatchObject({ mimeType: 'image/png', pixelWidth: 1, pixelHeight: 1, windowId: 7 }) + expect(screenshot).toMatchObject({ mimeType: 'image/png', pixelWidth: 1, pixelHeight: 1, windowId: '7' }) expect(Buffer.from(screenshot.bytes).toString('base64')).toBe(png) await peerWindow.click(element('0')) expect(await retainedWindow.getAccessibilityTree({ emit: false })).toContain('Count: 2') @@ -197,7 +197,7 @@ it.skipIf(process.platform === 'win32')('shares one application between retained const next = await context.agents.create({ sessionId: SessionId('native-loader-next'), agentOptions: { provider: 'native-fixture', model: 'vision' } }) const stale = await executeToolFixture(context, { agent: next.agent, signal: new AbortController().signal, - callId: ToolCallId('stale-window'), name: 'cua', arguments: { method: 'screenshot', params: { appHandle: 'fixture-app', windowId: 7 } }, + callId: ToolCallId('stale-window'), name: 'cua', arguments: { method: 'screenshot', params: { appHandle: 'fixture-app', windowId: '7' } }, }) expect(stale.isError).toBe(true) expect(JSON.stringify(stale.content)).toContain('APP_ACCESS_REQUIRED') diff --git a/packages/experimental/cua-macos/tests/persistent-bridge.built.e2e.ts b/packages/experimental/cua-macos/tests/persistent-bridge.built.e2e.ts index b37b79b6c1..20693bbfa7 100644 --- a/packages/experimental/cua-macos/tests/persistent-bridge.built.e2e.ts +++ b/packages/experimental/cua-macos/tests/persistent-bridge.built.e2e.ts @@ -74,9 +74,9 @@ it.skipIf(process.platform === 'win32' || !existsSync(bridge) || !existsSync(boo const section = (await ctx.systemPrompt.assemble()).sections.find(value => value.name === 'computer-use:dsh-cua') const initialization = section?.text.match(/Persistent PTC initialization:\n\n```ts\n([\s\S]*?)\n```/u)?.[1] expect(initialization).toContain('/lib/bridge.js') - const first = await run(`${initialization}\nvar app = await cua.getApp("test.fixture"); var win = await app.getWindow(7); await win.click("0"); var shot = await win.getScreenshot(); ({ mimeType: shot.mimeType, pixelWidth: shot.pixelWidth, pixelHeight: shot.pixelHeight, windowId: shot.windowId, byteLength: shot.bytes.length });`, 'first') + const first = await run(`${initialization}\nvar app = await cua.getApp("test.fixture"); var win = await app.getWindow("7"); await win.click("0"); var shot = await win.getScreenshot(); ({ mimeType: shot.mimeType, pixelWidth: shot.pixelWidth, pixelHeight: shot.pixelHeight, windowId: shot.windowId, byteLength: shot.bytes.length });`, 'first') expect(first.error).toBeUndefined() - expect(first.value).toEqual({ mimeType: 'image/png', pixelWidth: 1, pixelHeight: 1, windowId: 7, byteLength: 90 }) + expect(first.value).toEqual({ mimeType: 'image/png', pixelWidth: 1, pixelHeight: 1, windowId: '7', byteLength: 90 }) expect(images).toBe(1) expect(JSON.stringify(first)).not.toContain('iVBORw0KGgo') const invalid = await run('await cua.findApps("");', 'invalid') diff --git a/packages/experimental/cua-macos/tests/protocol-generation.spec.ts b/packages/experimental/cua-macos/tests/protocol-generation.spec.ts index dd5a3911c6..7d0ca249be 100644 --- a/packages/experimental/cua-macos/tests/protocol-generation.spec.ts +++ b/packages/experimental/cua-macos/tests/protocol-generation.spec.ts @@ -23,7 +23,7 @@ describe('native protocol generation', () => { it.each([ { method: 'getState', params: { appHandle: 'app', maxElements: 1 } }, - { method: 'drag', params: { appHandle: 'app', windowId: 1, fromX: 1, fromY: 1, toX: 2, toY: 2, steps: 1 } }, + { method: 'drag', params: { appHandle: 'app', windowId: '1', fromX: 1, fromY: 1, toX: 2, toY: 2, steps: 1 } }, { method: 'paste', params: { appHandle: 'app', text: 'text', maxClipboardBytes: 1024 } }, { method: 'paste', params: { appHandle: 'app', text: 'text', pasteReadTimeoutMs: 1000 } }, { method: 'findApps', params: { query: 'Editor', maxAppMatches: 1 } }, diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index 04f5b0dd80..52bad9ab77 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -107,7 +107,7 @@ class ImageAdapter extends LlmAdapter { } const imageData = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAACXBIWXMAAAPoAAAD6AG1e1JrAAAADElEQVQImWNgZGIGAAAOAAeCcsnOAAAAAElFTkSuQmCC' -const imageMetadata = { pixelWidth: 1, pixelHeight: 1, bounds: { x: 2, y: 3, width: 1, height: 1 }, coordinateSpace: 'window-points', windowId: 7 } +const imageMetadata = { pixelWidth: 1, pixelHeight: 1, bounds: { x: 2, y: 3, width: 1, height: 1 }, coordinateSpace: 'window-points', windowId: '7' } async function setup(model?: { provider: string; model: string }) { native.request.mockReset().mockResolvedValue([]) @@ -377,7 +377,7 @@ it('reports failed cleanup after waiting for other owners and releasing their Ag it('rejects malformed and unowned operations before acquiring a helper', async () => { const f = await setup() - expect((await f.execute('screenshot', { pid: 9, windowId: 7 })).isError).toBe(true) + expect((await f.execute('screenshot', { pid: 9, windowId: '7' })).isError).toBe(true) const unowned = await executeToolFixture(f.ctx, { signal: new AbortController().signal, callId: ToolCallId('unowned'), name: 'cua', arguments: { method: 'listApps', params: {} }, }) @@ -402,10 +402,10 @@ it('supplies configured resource bounds and clears registrations on unload', asy const f = await setup() await selectApplication(f) native.request.mockResolvedValueOnce({ appHandle: 'app-one', windowId: null, snapshotId: 's', tree: 'Window', truncated: false, - windows: [{ windowId: 7, appName: 'Fixture', title: 'Window', bounds: imageMetadata.bounds, isOnScreen: true, onCurrentSpace: true }] }) + windows: [{ windowId: '7', appName: 'Fixture', title: 'Window', bounds: imageMetadata.bounds, isOnScreen: true, onCurrentSpace: true }] }) await f.execute('getState', { appHandle: 'app-one' }) expect(native.request).toHaveBeenLastCalledWith('getState', { appHandle: 'app-one', maxElements: 64, maxDepth: 8 }, expect.any(AbortSignal), ToolCallId('lifecycle-2')) - await f.execute('drag', { appHandle: 'app-one', windowId: 7, fromX: 1, fromY: 2, toX: 3, toY: 4, relative: true }) + await f.execute('drag', { appHandle: 'app-one', windowId: '7', fromX: 1, fromY: 2, toX: 3, toY: 4, relative: true }) expect(native.request).toHaveBeenLastCalledWith('drag', expect.objectContaining({ durationMs: 200, steps: 10 }), expect.any(AbortSignal), ToolCallId('lifecycle-3')) await f.execute('paste', { appHandle: 'app-one', text: 'hello', format: 'text' }) expect(native.request).toHaveBeenLastCalledWith('paste', expect.objectContaining({ maxClipboardBytes: 8192, pasteReadTimeoutMs: 1000, maxElements: 64, maxDepth: 8 }), expect.any(AbortSignal), ToolCallId('lifecycle-4')) @@ -441,7 +441,7 @@ it('preserves screenshot attachments and invalidates pixel coordinates when wind const data = imageData const metadata = imageMetadata native.request.mockResolvedValue({ ...metadata, mimeType: 'image/png', data }) - const result = await f.execute('screenshot', { appHandle: 'app-one', windowId: 7 }) + const result = await f.execute('screenshot', { appHandle: 'app-one', windowId: '7' }) expect(result.isError).toBe(false) const text = result.content.find(block => block.type === 'text') if (text?.type !== 'text') throw new Error('Screenshot coordinates were not returned') @@ -451,14 +451,14 @@ it('preserves screenshot attachments and invalidates pixel coordinates when wind const stored = await f.ctx.attachments.readImage(image.attachment) expect(Buffer.from(stored.data).toString('base64')).toBe(data) expect(result.value).toMatchObject({ ...metadata, coordinateSpace: 'screenshot-pixels', mimeType: 'image/png', data }) - const windows = [{ windowId: 7, appName: 'Fixture', title: 'Window', + const windows = [{ windowId: '7', appName: 'Fixture', title: 'Window', bounds: { ...metadata.bounds, width: 2 }, isOnScreen: true, onCurrentSpace: true }] native.request.mockResolvedValueOnce(windows) const listed = await f.execute('listWindows', { appHandle: 'app-one' }) expect(listed.isError).toBe(false) expect(listed.value).toEqual(windows) native.request.mockClear() - const click = await f.execute('click', { appHandle: 'app-one', windowId: 7, x: 0, y: 0 }) + const click = await f.execute('click', { appHandle: 'app-one', windowId: '7', x: 0, y: 0 }) expect(click.isError).toBe(true) expect(JSON.stringify(click.content)).toContain('SCREENSHOT_REQUIRED') expect(native.request).not.toHaveBeenCalled() @@ -480,25 +480,25 @@ it('maps the actual model-request image pixels back to native points without sto const image = await sharp({ create: { width: 40, height: 20, channels: 3, background: '#4488cc' } }).png().toBuffer() native.request.mockResolvedValue({ ...imageMetadata, bounds: { x: 10, y: 20, width: 400, height: 200 }, pixelWidth: 40, pixelHeight: 20, mimeType: 'image/png', data: image.toString('base64') }) - const result = await f.execute('screenshot', { appHandle: 'app-one', windowId: 7 }) + const result = await f.execute('screenshot', { appHandle: 'app-one', windowId: '7' }) expect(result.isError, JSON.stringify(result.content)).toBe(false) expect(result.value).toMatchObject({ pixelWidth: 10, pixelHeight: 5, coordinateSpace: 'screenshot-pixels' }) const value = result.value as { data: string } expect(await sharp(Buffer.from(value.data, 'base64')).metadata()).toMatchObject({ width: 10, height: 5 }) expect(save).toHaveBeenCalledTimes(1) native.request.mockResolvedValue({ dispatched: true }) - expect((await f.execute('click', { appHandle: 'app-one', windowId: 7, x: 5, y: 2.5 })).isError).toBe(false) - expect(native.request).toHaveBeenLastCalledWith('click', { appHandle: 'app-one', windowId: 7, x: 200, y: 100 }, expect.any(AbortSignal), expect.any(String)) - expect((await f.execute('click', { appHandle: 'app-one', windowId: 7, x: 999, y: 999, relative: true })).isError).toBe(false) - expect(native.request).toHaveBeenLastCalledWith('click', { appHandle: 'app-one', windowId: 7, x: 399, y: 199 }, expect.any(AbortSignal), expect.any(String)) + expect((await f.execute('click', { appHandle: 'app-one', windowId: '7', x: 5, y: 2.5 })).isError).toBe(false) + expect(native.request).toHaveBeenLastCalledWith('click', { appHandle: 'app-one', windowId: '7', x: 200, y: 100 }, expect.any(AbortSignal), expect.any(String)) + expect((await f.execute('click', { appHandle: 'app-one', windowId: '7', x: 999, y: 999, relative: true })).isError).toBe(false) + expect(native.request).toHaveBeenLastCalledWith('click', { appHandle: 'app-one', windowId: '7', x: 399, y: 199 }, expect.any(AbortSignal), expect.any(String)) }) -it.each([{ appHandle: 'foreign', windowId: 7 }, { appHandle: 'app-one', windowId: null }])( +it.each([{ appHandle: 'foreign', windowId: '7' }, { appHandle: 'app-one', windowId: null }])( 'rejects a helper observation for the wrong target before releasing its contents: %j', async (identity) => { const f = await setup() await selectApplication(f) native.request.mockResolvedValueOnce({ ...identity, snapshotId: 'other', tree: 'foreign content', truncated: false, windows: [] }) - const result = await f.execute('getState', { appHandle: 'app-one', windowId: 7 }) + const result = await f.execute('getState', { appHandle: 'app-one', windowId: '7' }) expect(result.isError).toBe(true) expect(JSON.stringify(result.content)).toContain('NATIVE_PROTOCOL') expect(JSON.stringify(result.content)).not.toContain('foreign content') @@ -513,8 +513,8 @@ it('rejects a screenshot from another window before attachment admission', async onTestFinished(async () => { try { await f.ctx.fiber.dispose() } finally { await rm(root, { recursive: true, force: true }) } }) await f.ctx.plugin(LocalAttachmentStore, { dshHome: root }) const save = vi.spyOn(f.ctx.attachments, 'saveImages') - native.request.mockResolvedValueOnce({ ...imageMetadata, windowId: 8, mimeType: 'image/png', data: imageData }) - const result = await f.execute('screenshot', { appHandle: 'app-one', windowId: 7 }) + native.request.mockResolvedValueOnce({ ...imageMetadata, windowId: '8', mimeType: 'image/png', data: imageData }) + const result = await f.execute('screenshot', { appHandle: 'app-one', windowId: '7' }) expect(result.isError).toBe(true) expect(JSON.stringify(result.content)).toContain('NATIVE_PROTOCOL') expect(save).not.toHaveBeenCalled() @@ -528,7 +528,7 @@ it.each([{ pixelWidth: 2 }, { pixelHeight: 2 }])('rejects native screenshot dime onTestFinished(async () => { await f.ctx.fiber.dispose(); await rm(root, { recursive: true, force: true }) }) await f.ctx.plugin(LocalAttachmentStore, { dshHome: root }) native.request.mockResolvedValue({ ...imageMetadata, ...invalid, mimeType: 'image/png', data: imageData }) - const result = await f.execute('screenshot', { appHandle: 'app-one', windowId: 7 }) + const result = await f.execute('screenshot', { appHandle: 'app-one', windowId: '7' }) expect(result.isError).toBe(true) expect(JSON.stringify(result.content)).toContain('dimensions disagree') expect(result.content.some(block => block.type === 'image')).toBe(false) @@ -538,7 +538,7 @@ it('refuses screenshot capture when no attachment store is mounted', async () => const f = await setup({ provider: 'image-fixture', model: 'vision' }) await selectApplication(f) native.request.mockClear() - const result = await f.execute('screenshot', { appHandle: 'app-one', windowId: 7 }) + const result = await f.execute('screenshot', { appHandle: 'app-one', windowId: '7' }) expect(result.isError).toBe(true) expect(JSON.stringify(result.content)).toContain('require an attachment store') expect(native.request).not.toHaveBeenCalled() @@ -558,7 +558,7 @@ it.each(['unresolved', 'unknown', 'text-only', 'provider-error'] as const)( ...route === 'text-only' ? { inputModalities: ['text'] } : {}, }) native.request.mockClear() - const result = await f.execute('screenshot', { appHandle: 'app-one', windowId: 7 }) + const result = await f.execute('screenshot', { appHandle: 'app-one', windowId: '7' }) expect(result.isError).toBe(true) expect(JSON.stringify(result.content)).toContain(route === 'unresolved' ? 'model route could not be resolved' : route === 'provider-error' ? 'model lookup failed' : 'declare image input') @@ -579,7 +579,7 @@ it.each([ await f.ctx.plugin(LocalAttachmentStore, { dshHome: root }) vi.spyOn(f.ctx.attachments, 'readImageRequest').mockRejectedValue(failure) native.request.mockResolvedValue({ ...imageMetadata, mimeType: 'image/png', data: imageData }) - const result = await f.execute('screenshot', { appHandle: 'app-one', windowId: 7 }) + const result = await f.execute('screenshot', { appHandle: 'app-one', windowId: '7' }) const content = JSON.stringify(result.content) expect(result.isError).toBe(true) expect(content).toContain('SCREENSHOT_IMAGE_FAILED: Screenshot model image preparation failed for window 7') @@ -595,7 +595,7 @@ it('returns an image-admission failure without emitting a successful screenshot' onTestFinished(async () => { await f.ctx.fiber.dispose(); await rm(root, { recursive: true, force: true }) }) await f.ctx.plugin(LocalAttachmentStore, { dshHome: root }) native.request.mockResolvedValue({ ...imageMetadata, mimeType: 'image/png', data: 'AQ==' }) - const result = await f.execute('screenshot', { appHandle: 'app-one', windowId: 7 }) + const result = await f.execute('screenshot', { appHandle: 'app-one', windowId: '7' }) expect(result.isError).toBe(true) expect(result.content.some(block => block.type === 'image')).toBe(false) expect(JSON.stringify(result.content)).toContain('INVALID_IMAGE: Screenshot image admission failed for window 7') @@ -631,7 +631,7 @@ it.each([ if (stage === 'storage') { entered.resolve(); await release.promise } return saveImages(images) }) - const pending = f.execute('screenshot', { appHandle: 'app-one', windowId: 7 }) + const pending = f.execute('screenshot', { appHandle: 'app-one', windowId: '7' }) let closing: Promise | undefined try { const reached = await Promise.race([entered.promise.then(() => true), pending.then(() => false)]) diff --git a/packages/experimental/cua-windows/native/desktop-tests/Program.cs b/packages/experimental/cua-windows/native/desktop-tests/Program.cs index ed6948f482..58421dec24 100644 --- a/packages/experimental/cua-windows/native/desktop-tests/Program.cs +++ b/packages/experimental/cua-windows/native/desktop-tests/Program.cs @@ -1,4 +1,5 @@ // Private desktop fixture: commands inspect or arrange only the windows owned by this process. +using System.Globalization; using System.Runtime.InteropServices; using System.Text.Json; using System.Security.Cryptography; @@ -26,7 +27,7 @@ internal sealed class FixtureForm : Form internal object Inspect() => new { - text = Editor.Text, clicks, window = Handle.ToInt64(), foreground = GetForegroundWindow().ToInt64(), + text = Editor.Text, clicks, window = Handle.ToString(CultureInfo.InvariantCulture), foreground = GetForegroundWindow().ToString(CultureInfo.InvariantCulture), cursor = new { x = Cursor.Position.X, y = Cursor.Position.Y }, button = new { x = button.Left + button.Width / 2, y = button.Top + button.Height / 2 }, selection = new { start = Editor.SelectionStart, length = Editor.SelectionLength }, diff --git a/packages/experimental/cua-windows/native/entry/Accessibility.cs b/packages/experimental/cua-windows/native/entry/Accessibility.cs index f1068643f2..92327237a2 100644 --- a/packages/experimental/cua-windows/native/entry/Accessibility.cs +++ b/packages/experimental/cua-windows/native/entry/Accessibility.cs @@ -8,7 +8,7 @@ using DeepSeek.Cua.Protocol; namespace DeepSeek.Cua.Windows; internal sealed record ElementReference(AutomationElement Element, WindowState Window); -internal sealed record Snapshot(string Id, uint Scope, WindowState[] Windows, IReadOnlyDictionary Elements); +internal sealed record Snapshot(string Id, nint Scope, WindowState[] Windows, IReadOnlyDictionary Elements); internal static class Accessibility { @@ -25,7 +25,7 @@ internal static class Accessibility TogglePattern.ToggleStateProperty, ExpandCollapsePattern.ExpandCollapseStateProperty, ]; - internal static object State(AppState app, uint selected, int maximumElements, int maximumDepth, + internal static object State(AppState app, nint selected, int maximumElements, int maximumDepth, bool includeMenus, bool details, RequestContext context) { var all = Windows.Refresh(app, context); @@ -68,8 +68,8 @@ internal static class Accessibility var snapshot = new Snapshot(Guid.NewGuid().ToString("N"), scope, targets, elements); var result = new { - appHandle = app.Handle, pid = 4, windowId = selected, - focusedWindowId = (uint?)Windows.Focused(app, all)?.Id, + appHandle = app.Handle, pid = 4, windowId = selected.ToString(CultureInfo.InvariantCulture), + focusedWindowId = Windows.Focused(app, all)?.Id.ToString(CultureInfo.InvariantCulture), snapshotId = snapshot.Id, tree = string.Join('\n', rows), windows = all.Select(window => window.Describe(app, context)).ToArray(), truncated, }; context.Check(); @@ -234,7 +234,7 @@ internal static class Accessibility return element; } - internal static void RequireSnapshot(AppState app, string snapshotId, uint windowId) + internal static void RequireSnapshot(AppState app, string snapshotId, nint windowId) { var selected = app.SelectedWindow; var snapshot = app.Snapshots.Values.SingleOrDefault(value => value.Id == snapshotId); diff --git a/packages/experimental/cua-windows/native/entry/Applications.cs b/packages/experimental/cua-windows/native/entry/Applications.cs index eff65c0497..bad7a32470 100644 --- a/packages/experimental/cua-windows/native/entry/Applications.cs +++ b/packages/experimental/cua-windows/native/entry/Applications.cs @@ -21,14 +21,8 @@ internal sealed class AppState(string handle, ApplicationIdentity authorization, internal string Digest { get; } = digest; internal RunningApplication? Process { get; set; } = process; internal Dictionary Windows { get; } = []; - internal Dictionary Snapshots { get; } = []; - private uint nextWindowId; + internal Dictionary Snapshots { get; } = []; private System.Diagnostics.Process? owner; - internal uint AllocateWindowId() - { - if (nextWindowId == uint.MaxValue) throw new NativeFailure("NATIVE_LIMIT", "Select the application again to allocate new window identifiers"); - return ++nextWindowId; - } internal RunningApplication RequireProcess() { var selected = Process ?? throw new NativeFailure("APP_ACCESS_REQUIRED", "Application launch requires Host authorization"); diff --git a/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs b/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs index 88dd5c0aef..5332f16fba 100644 --- a/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs +++ b/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs @@ -1,4 +1,5 @@ // The shared Host policy authorizes handles before these platform operations execute. +using System.Globalization; using System.Text.Json; using DeepSeek.Cua.Protocol; @@ -6,7 +7,6 @@ namespace DeepSeek.Cua.Windows; internal sealed class ClientState { - internal DesktopWindows Desktop { get; } = new(); internal Dictionary Launches { get; } = new(StringComparer.Ordinal); internal Dictionary Apps { get; } = new(StringComparer.Ordinal); internal AppState App(string handle) => Apps.GetValueOrDefault(handle) @@ -28,7 +28,9 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA private static string String(JsonElement value, string key) => value.GetProperty(key).GetString()!; private static string? OptionalString(JsonElement value, string key) => value.TryGetProperty(key, out var item) ? item.GetString() : null; private static bool Flag(JsonElement value, string key) => value.TryGetProperty(key, out var item) && item.GetBoolean(); - private static uint? WindowId(JsonElement value) => value.TryGetProperty("windowId", out var id) ? id.GetUInt32() : null; + private static nint ParseWindowId(JsonElement value) => nint.TryParse(value.GetString(), CultureInfo.InvariantCulture, out var id) + ? id : throw new NativeFailure("INVALID_ARGUMENT", "windowId is outside the native handle range"); + private static nint? WindowId(JsonElement value) => value.TryGetProperty("windowId", out var id) ? ParseWindowId(id) : null; private static string[] Modifiers(JsonElement value) => value.TryGetProperty("modifiers", out var items) ? items.EnumerateArray().Select(item => item.GetString()!).ToArray() : []; // Window-scoped operations act only on the window authorized at getApp; the request must name it. @@ -36,8 +38,7 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA { if (!parameters.TryGetProperty("windowId", out var raw)) throw new NativeFailure("UNSUPPORTED", "This operation requires a window target; select a window with getApp and pass its windowId"); - if (!raw.TryGetUInt32(out var id)) - throw new NativeFailure("INVALID_ARGUMENT", "windowId must be a non-negative 32-bit identifier"); + var id = ParseWindowId(raw); var selected = app.SelectedWindow ?? throw new NativeFailure("APP_ACCESS_REQUIRED", "Select a window with getApp before this operation"); if (selected.Id != id) throw new NativeFailure("WINDOW_CHANGED", "The request targets another window; select that window with getApp"); @@ -87,12 +88,12 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA if (request.Method is "requestPermission" or "openPermissionSettings") throw new NativeFailure("UNSUPPORTED", "Windows desktop access has no macOS permission switches; inspect the Windows session status"); DesktopSession.RequireInteractive(); - if (request.Method == "listApps") return state.Desktop.ListApps(context); + if (request.Method == "listApps") return DesktopWindows.ListApps(context); if (request.Method == "findApps") throw new NativeFailure("UNSUPPORTED", "Windows discovers selectable windows with listApps; installed launch entries are not part of this selection"); if (request.Method == "getApp") { - var selected = state.Desktop.Select(String(parameters, "selector"), context); + var selected = DesktopWindows.Select(String(parameters, "selector"), context); state.Apps[selected.Handle] = selected; return new { appHandle = selected.Handle, pid = 4, name = selected.Authorization.Name, running = true, authorization = selected.Authorization }; diff --git a/packages/experimental/cua-windows/native/entry/DesktopWindows.cs b/packages/experimental/cua-windows/native/entry/DesktopWindows.cs index e70b1b1d1e..0189021692 100644 --- a/packages/experimental/cua-windows/native/entry/DesktopWindows.cs +++ b/packages/experimental/cua-windows/native/entry/DesktopWindows.cs @@ -1,18 +1,19 @@ -// Discovery IDs are connection-owned and never reused for another HWND lifetime. +// Desktop discovery selects windows by their invariant decimal HWND strings. +using System.Globalization; using System.Security.Cryptography; using System.Text; using DeepSeek.Cua.Protocol; namespace DeepSeek.Cua.Windows; -internal sealed record DiscoveredWindow(WindowState Window, RunningApplication Process, string Selector); - -internal sealed class DesktopWindows +internal sealed record DiscoveredWindow(WindowState Window, RunningApplication Process) { - private readonly Dictionary windows = []; - private uint nextId; + internal string Selector => Window.Id.ToString(CultureInfo.InvariantCulture); +} - internal object[] ListApps(RequestContext context) +internal static class DesktopWindows +{ + internal static object[] ListApps(RequestContext context) { var result = new List(); foreach (var entry in Discover(context)) @@ -26,25 +27,23 @@ internal sealed class DesktopWindows } catch (NativeFailure error) when (error.Code is "STALE_APP" or "PERMISSION_DENIED" or "APP_IDENTITY_UNAVAILABLE" or "UNSUPPORTED_SESSION" or "WINDOW_CHANGED") { - // A disappearing window cannot remain selectable from this connection. - windows.Remove(entry.Window.Handle); + // A disappearing or inaccessible window is omitted from discovery. } } return result.ToArray(); } - internal AppState Select(string selector, RequestContext context) + internal static AppState Select(string selector, RequestContext context) { if (string.IsNullOrEmpty(selector)) throw new NativeFailure("INVALID_ARGUMENT", "A window selector from listApps is required"); - Discover(context); - var entry = windows.Values.SingleOrDefault(value => string.Equals(value.Selector, selector, StringComparison.Ordinal)) - ?? throw new NativeFailure("WINDOW_CHANGED", "Discover applications again; this window selector belongs to another connection or an expired window"); + var entry = Discover(context).SingleOrDefault(value => string.Equals(value.Selector, selector, StringComparison.Ordinal)) + ?? throw new NativeFailure("WINDOW_CHANGED", "Discover applications again; this window is no longer available"); var app = Owner(entry, true, context); try { entry.Window.Geometry(app, context); return app; } catch { app.Dispose(); throw; } } - private List Discover(RequestContext context) + private static List Discover(RequestContext context) { var current = new List(); Win32.EnumWindows((handle, _) => @@ -63,25 +62,16 @@ internal sealed class DesktopWindows { Win32.GetWindowThreadProcessId(handle, out var pid); var process = Applications.Running(checked((int)pid)); - var epoch = context.Sta.WindowEpoch(handle); - if (!windows.TryGetValue(handle, out var entry) || entry.Process.Pid != process.Pid - || entry.Process.Started != process.Started || entry.Window.Epoch != epoch) - { - if (nextId == uint.MaxValue) throw new NativeFailure("NATIVE_LIMIT", "Reconnect before discovering more windows"); - entry = new(new(++nextId, handle, epoch), process, Guid.NewGuid().ToString("N")); - windows[handle] = entry; - } + var entry = new DiscoveredWindow(new(handle), process); using var owner = Owner(entry, false, context); entry.Window.Geometry(owner, context); result.Add(entry); } catch (NativeFailure error) when (error.Code is "STALE_APP" or "PERMISSION_DENIED" or "APP_IDENTITY_UNAVAILABLE" or "UNSUPPORTED_SESSION" or "WINDOW_CHANGED") { - // A disappearing or inaccessible window cannot be selected from this discovery. - windows.Remove(handle); + // A disappearing or inaccessible window is omitted from discovery. } } - foreach (var handle in windows.Keys.Where(handle => !current.Contains(handle)).ToArray()) windows.Remove(handle); return result; } @@ -94,15 +84,14 @@ internal sealed class DesktopWindows var title = new StringBuilder(length + 1); Win32.GetWindowText(window.Handle, title, title.Capacity); var name = $"Window: {title} ({process.Name})"; - var id = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes( - $"window\0{process.Pid}\0{process.Started}\0{window.Handle}\0{window.Epoch}"))); + // Shared consent IDs require a SHA-256 string, including non-persistable window grants. + var id = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes($"window\0{entry.Selector}"))); var identity = new ApplicationIdentity(id, name, process.Path, false); var app = new AppState(Guid.NewGuid().ToString("N"), identity, "", process); if (authorize) { - var selected = new WindowState(window.Id, window.Handle, window.Epoch); - app.SelectedWindow = selected; - app.Windows.Add(window.Handle, selected); + app.SelectedWindow = window; + app.Windows.Add(window.Handle, window); } return app; } diff --git a/packages/experimental/cua-windows/native/entry/Dispatchers.cs b/packages/experimental/cua-windows/native/entry/Dispatchers.cs index a8d4fb180e..758414ed73 100644 --- a/packages/experimental/cua-windows/native/entry/Dispatchers.cs +++ b/packages/experimental/cua-windows/native/entry/Dispatchers.cs @@ -94,43 +94,27 @@ internal sealed class StaDispatcher : IAsyncDisposable { private readonly TaskCompletionSource ready = new(TaskCreationOptions.RunContinuationsAsynchronously); private readonly TaskCompletionSource stopped = new(TaskCreationOptions.RunContinuationsAsynchronously); - private readonly ConcurrentDictionary epochs = new(); private readonly Thread thread; - private Win32.WinEvent? windowEvents; internal StaDispatcher() { thread = new Thread(() => { - nint hook = 0; try { Win32.SetThreadDpiAwarenessContext(-4); using var control = new ServiceControl(); _ = control.Handle; - windowEvents = (_, eventType, window, objectId, childId, _, _) => - { - if (eventType == 0x8001 && objectId == 0 && childId == 0 && epochs.TryGetValue(window, out var epoch)) - epochs.TryUpdate(window, epoch + 1, epoch); - }; - hook = Win32.SetWinEventHook(0x8001, 0x8001, 0, windowEvents, 0, 0, 0); - if (hook == 0) throw new NativeFailure("NATIVE_STARTUP", "Window lifecycle observation could not start"); ready.SetResult(control); Forms.Application.Run(); } catch (Exception error) { ready.TrySetException(error); } - finally - { - if (hook != 0) Win32.UnhookWinEvent(hook); - stopped.TrySetResult(null); - } + finally { stopped.TrySetResult(null); } }) { IsBackground = true, Name = "dsh-cua-clipboard" }; thread.SetApartmentState(ApartmentState.STA); thread.Start(); } - internal long WindowEpoch(nint window) => epochs.GetOrAdd(window, 0); - internal async Task Invoke(Func work, CancellationToken cancellation) { var control = await ready.Task.WaitAsync(cancellation); diff --git a/packages/experimental/cua-windows/native/entry/Win32.cs b/packages/experimental/cua-windows/native/entry/Win32.cs index 957e3bcb98..128123b667 100644 --- a/packages/experimental/cua-windows/native/entry/Win32.cs +++ b/packages/experimental/cua-windows/native/entry/Win32.cs @@ -11,7 +11,6 @@ internal static class Win32 [DllImport("user32.dll", EntryPoint = "GetWindowLongPtrW")] internal static extern nint GetWindowLongPtr(nint window, int index); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetCursorPos(out Point point); internal delegate bool WindowVisitor(nint window, nint parameter); - internal delegate void WinEvent(nint hook, uint eventType, nint window, int objectId, int childId, uint threadId, uint time); [StructLayout(LayoutKind.Sequential)] internal struct Point { internal int X, Y; } [StructLayout(LayoutKind.Sequential)] internal struct Rect @@ -74,8 +73,6 @@ internal static class Win32 [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetUserObjectInformation(nint handle, int index, StringBuilder value, int length, out int needed); [DllImport("wtsapi32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool WTSQuerySessionInformation(nint server, int session, int information, out nint buffer, out int bytes); [DllImport("wtsapi32.dll")] internal static extern void WTSFreeMemory(nint memory); - [DllImport("user32.dll", SetLastError = true)] internal static extern nint SetWinEventHook(uint minimum, uint maximum, nint module, WinEvent callback, uint process, uint thread, uint flags); - [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool UnhookWinEvent(nint hook); [DllImport("user32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool OpenClipboard(nint owner); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CloseClipboard(); diff --git a/packages/experimental/cua-windows/native/entry/Windows.cs b/packages/experimental/cua-windows/native/entry/Windows.cs index 08ec60d145..dbc21a5614 100644 --- a/packages/experimental/cua-windows/native/entry/Windows.cs +++ b/packages/experimental/cua-windows/native/entry/Windows.cs @@ -1,4 +1,5 @@ -// Public window IDs never expose or revive a reused HWND. +// Window state retains HWND values; JSON exposes them as invariant decimal strings. +using System.Globalization; using System.Runtime.InteropServices; using System.Text; using DeepSeek.Cua.Protocol; @@ -11,20 +12,18 @@ internal readonly record struct WindowGeometry(Win32.Rect Pixels, uint Dpi) internal Bounds Bounds => new(Pixels.Left, Pixels.Top, Pixels.Width, Pixels.Height); } -internal sealed class WindowState(uint id, nint handle, long epoch) +internal sealed class WindowState(nint handle) { - internal uint Id { get; } = id; + internal nint Id => Handle; internal nint Handle { get; } = handle; - internal long Epoch { get; } = epoch; private WindowGeometry? observation; internal WindowGeometry Geometry(AppState app, RequestContext context) { context.Check(); - var process = app.RequireProcess(); - Win32.GetWindowThreadProcessId(Handle, out var pid); - if (!Win32.IsWindow(Handle) || pid != process.Pid || context.Sta.WindowEpoch(Handle) != Epoch) - throw new NativeFailure("WINDOW_CHANGED", "The selected window was destroyed or replaced; read fresh application state"); + app.RequireProcess(); + if (!Win32.IsWindow(Handle)) + throw new NativeFailure("WINDOW_CHANGED", "The selected window is no longer available; read fresh application state"); if (Win32.DwmGetWindowAttribute(Handle, 9, out Win32.Rect rectangle, Marshal.SizeOf()) != 0 && !Win32.GetWindowRect(Handle, out rectangle)) throw new NativeFailure("WINDOW_CHANGED", "The selected window geometry is unavailable"); var dpi = Win32.GetDpiForWindow(Handle); @@ -64,7 +63,7 @@ internal sealed class WindowState(uint id, nint handle, long epoch) Win32.GetWindowText(Handle, title, title.Capacity); return new { - windowId = Id, pid = 4, appName = app.RequireProcess().Name, + windowId = Id.ToString(CultureInfo.InvariantCulture), pid = 4, appName = app.RequireProcess().Name, title = title.ToString(), bounds = geometry.Bounds, isOnScreen = IsOnScreen(), onCurrentSpace = (bool?)null, }; } @@ -92,7 +91,7 @@ internal static class Windows }, 0); foreach (var pair in app.Windows.ToArray()) { - if (handles.Contains(pair.Key) && pair.Value.Epoch == context.Sta.WindowEpoch(pair.Key)) continue; + if (handles.Contains(pair.Key)) continue; app.Windows.Remove(pair.Key); foreach (var scope in app.Snapshots.Where(item => item.Value.Windows.Any(window => window.Id == pair.Value.Id)).Select(item => item.Key).ToArray()) app.Snapshots.Remove(scope); @@ -101,13 +100,13 @@ internal static class Windows { if (!app.Windows.ContainsKey(handle)) { - app.Windows.Add(handle, new(app.AllocateWindowId(), handle, context.Sta.WindowEpoch(handle))); + app.Windows.Add(handle, new(handle)); } } return handles.Select(handle => app.Windows[handle]).ToArray(); } - internal static WindowState Resolve(AppState app, uint id, RequestContext context) => Refresh(app, context) + internal static WindowState Resolve(AppState app, nint id, RequestContext context) => Refresh(app, context) .SingleOrDefault(window => window.Id == id) ?? throw new NativeFailure("WINDOW_CHANGED", "Select a current window from getWindows"); internal static WindowState? Focused(AppState app, WindowState[] windows) @@ -139,7 +138,7 @@ internal static class Windows throw new NativeFailure("AMBIGUOUS_WINDOW", "Select a window explicitly from getWindows"); } - internal static object Show(AppState app, uint? id, RequestContext context) + internal static object Show(AppState app, nint? id, RequestContext context) { var target = id is { } selected ? Resolve(app, selected, context) : Default(app, Refresh(app, context)); var before = Win32.GetForegroundWindow(); @@ -149,7 +148,7 @@ internal static class Windows if (!Win32.ShowWindowAsync(target.Handle, 4)) throw new NativeFailure("UNSUPPORTED", "Windows refused background restoration; explicitly activate the application if needed"); } var after = Win32.GetForegroundWindow(); - return new { dispatched = true, windowId = (uint?)target?.Id, + return new { dispatched = true, windowId = target?.Id.ToString(CultureInfo.InvariantCulture), foregroundChanged = before == 0 || after == 0 ? (bool?)null : before != after }; } diff --git a/packages/experimental/cua-windows/native/protocol.schema.json b/packages/experimental/cua-windows/native/protocol.schema.json index c25c65c1e0..56656950de 100644 --- a/packages/experimental/cua-windows/native/protocol.schema.json +++ b/packages/experimental/cua-windows/native/protocol.schema.json @@ -168,9 +168,8 @@ "minLength": 1 }, "windowId": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 4294967295 + "type": "string", + "minLength": 1 } }, "required": [ @@ -235,9 +234,8 @@ "minLength": 1 }, "windowId": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 4294967295 + "type": "string", + "minLength": 1 }, "includeMenus": { "description": "Expand menu contents; omitted or false shows menu-bar entries only.", @@ -291,9 +289,8 @@ "minLength": 1 }, "windowId": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 4294967295 + "type": "string", + "minLength": 1 }, "snapshotId": { "type": "string", @@ -338,9 +335,8 @@ "minLength": 1 }, "windowId": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 4294967295 + "type": "string", + "minLength": 1 }, "snapshotId": { "type": "string", @@ -427,9 +423,8 @@ "minLength": 1 }, "windowId": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 4294967295 + "type": "string", + "minLength": 1 }, "snapshotId": { "type": "string", @@ -476,9 +471,8 @@ "minLength": 1 }, "windowId": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 4294967295 + "type": "string", + "minLength": 1 }, "snapshotId": { "type": "string", @@ -505,9 +499,8 @@ "minLength": 1 }, "windowId": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 4294967295 + "type": "string", + "minLength": 1 }, "snapshotId": { "type": "string", @@ -560,9 +553,8 @@ "minLength": 1 }, "windowId": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 4294967295 + "type": "string", + "minLength": 1 }, "snapshotId": { "type": "string", @@ -628,9 +620,8 @@ "minLength": 1 }, "windowId": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 4294967295 + "type": "string", + "minLength": 1 }, "snapshotId": { "type": "string", @@ -720,9 +711,8 @@ "minLength": 1 }, "windowId": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 4294967295 + "type": "string", + "minLength": 1 }, "snapshotId": { "type": "string", @@ -805,9 +795,8 @@ "minLength": 1 }, "windowId": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 4294967295 + "type": "string", + "minLength": 1 }, "snapshotId": { "type": "string", @@ -871,9 +860,8 @@ "minLength": 1 }, "windowId": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 4294967295 + "type": "string", + "minLength": 1 }, "text": { "type": "string" @@ -911,9 +899,8 @@ "minLength": 1 }, "windowId": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 4294967295 + "type": "string", + "minLength": 1 }, "text": { "type": "string" @@ -982,9 +969,8 @@ "minLength": 1 }, "windowId": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 4294967295 + "type": "string", + "minLength": 1 }, "key": { "type": "string", @@ -1029,9 +1015,8 @@ "minLength": 1 }, "windowId": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 4294967295 + "type": "string", + "minLength": 1 }, "key": { "type": "string", @@ -1078,9 +1063,8 @@ "minLength": 1 }, "windowId": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 4294967295 + "type": "string", + "minLength": 1 }, "snapshotId": { "type": "string", @@ -1141,9 +1125,8 @@ "minLength": 1 }, "windowId": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 4294967295 + "type": "string", + "minLength": 1 }, "mouseButton": { "type": "string", @@ -1235,9 +1218,8 @@ "minLength": 1 }, "windowId": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 4294967295 + "type": "string", + "minLength": 1 } }, "required": [ diff --git a/packages/experimental/cua-windows/native/tests/Program.cs b/packages/experimental/cua-windows/native/tests/Program.cs index d352580306..0f304fe814 100644 --- a/packages/experimental/cua-windows/native/tests/Program.cs +++ b/packages/experimental/cua-windows/native/tests/Program.cs @@ -16,7 +16,7 @@ void Refuses(Action action, string code) var request = NativeRequest.Parse(WireJson.Parse("""{"id":"one","method":"getState","params":{"appHandle":"app","maxElements":20,"maxDepth":5}}""")); Check(request.Method == "getState" && request.Id == "one", "Valid requests retain correlation and method"); -Refuses(() => NativeRequest.Parse(WireJson.Parse("""{"id":"one","method":"click","params":{"appHandle":"app","windowId":1,"x":-1,"y":2}}""")), "INVALID_ARGUMENT"); +Refuses(() => NativeRequest.Parse(WireJson.Parse("""{"id":"one","method":"click","params":{"appHandle":"app","windowId":"1","x":-1,"y":2}}""")), "INVALID_ARGUMENT"); Refuses(() => NativeRequest.Parse(WireJson.Parse("""{"id":"one","method":"getState","params":{"appHandle":"app","maxElements":0,"maxDepth":5}}""")), "INVALID_ARGUMENT"); Refuses(() => NativeRequest.Parse(WireJson.Parse("""{"id":"one","method":"typeText","params":{"appHandle":"app","text":"hello","unowned":1}}""")), "INVALID_ARGUMENT"); Refuses(() => WireJson.Parse("""{"id":"one","id":"two"}"""), "INVALID_REQUEST"); diff --git a/packages/experimental/cua-windows/tests/desktop-tool.spec.ts b/packages/experimental/cua-windows/tests/desktop-tool.spec.ts index 5fcb5c3c6d..338ef5a9a5 100644 --- a/packages/experimental/cua-windows/tests/desktop-tool.spec.ts +++ b/packages/experimental/cua-windows/tests/desktop-tool.spec.ts @@ -58,6 +58,7 @@ it.skipIf(!helperPath || !selector)('admits real application screenshots through const target = (await app.getWindows({ emit: false })).find(window => window.isOnScreen && window.bounds.width > 0 && window.bounds.height > 0) expect(target).toBeDefined() + expect(target!.windowId).toBe(discovered!.id) const window = await app.getWindow(target!.windowId) expect(emitted).toEqual([]) await window.getAccessibilityTree() diff --git a/packages/experimental/cua-windows/tests/protocol.spec.ts b/packages/experimental/cua-windows/tests/protocol.spec.ts index 18d0ce27bf..081906f6fd 100644 --- a/packages/experimental/cua-windows/tests/protocol.spec.ts +++ b/packages/experimental/cua-windows/tests/protocol.spec.ts @@ -10,7 +10,7 @@ it('keeps the C# admission schema identical to the shared generated schema', asy }) it('preserves Windows physical capture units and observed foreground changes', () => { - const image = { mimeType: 'image/png', data: 'AAAA', pixelWidth: 1200, pixelHeight: 800, windowId: 1, + const image = { mimeType: 'image/png', data: 'AAAA', pixelWidth: 1200, pixelHeight: 800, windowId: '1', bounds: { x: -1200, y: 0, width: 1200, height: 800 }, coordinateSpace: 'window-pixels' } expect(NativeScreenshotResult.parse(image).coordinateSpace).toBe('window-pixels') expect(() => NativeScreenshotResult.parse({ ...image, coordinateSpace: 'screen-pixels' })).toThrow() diff --git a/packages/experimental/cua/src/api.ts b/packages/experimental/cua/src/api.ts index f41a4f61e4..ebba5bdc2b 100644 --- a/packages/experimental/cua/src/api.ts +++ b/packages/experimental/cua/src/api.ts @@ -92,19 +92,19 @@ type CuaScopeParams = (params: Record) => Record, sink: CuaObservationSink | undefined): { createCuaApp(appHandle: CuaAppHandle, capabilities: CuaCapabilities): CuaApp } { - const observed = new Map() + const observed = new Map() function currentSnapshot(appHandle: CuaAppHandle): string { const current = observed.get(appHandle) if (current === undefined) throw new Error('Read getAccessibilityTree before using this surface') return current.snapshotId } - function coordinateParams(appHandle: CuaAppHandle, windowId: number): Record { + function coordinateParams(appHandle: CuaAppHandle, windowId: string): Record { const current = observed.get(appHandle) return current !== undefined && (current.windowId === undefined || current.windowId === windowId) ? { snapshotId: current.snapshotId } : {} } function createCuaSurface( - target: { appHandle: CuaAppHandle; windowId?: number }, + target: { appHandle: CuaAppHandle; windowId?: string }, paramsFor: CuaScopeParams, requireAccessibility: () => void, requireKeyboard: () => void, @@ -177,7 +177,7 @@ function createCuaObjects(call: ReturnType, sink: CuaObser } return { surface, call: scopedCall, action, elementParams } } - function createCuaWindow(appHandle: CuaAppHandle, windowId: number, capabilities: CuaCapabilities): CuaWindow { + function createCuaWindow(appHandle: CuaAppHandle, windowId: string, capabilities: CuaCapabilities): CuaWindow { const base = createCuaSurface({ appHandle, windowId }, params => ({ ...params, appHandle, windowId }), () => undefined, () => { if (!capabilities.keyboard.includes('window')) { diff --git a/packages/experimental/cua/src/coordinates.ts b/packages/experimental/cua/src/coordinates.ts index eb868d59e7..2e3050ac98 100644 --- a/packages/experimental/cua/src/coordinates.ts +++ b/packages/experimental/cua/src/coordinates.ts @@ -12,7 +12,7 @@ interface Frame { /** Tracks only the current window geometry and last successfully prepared screenshot. */ export class CuaCoordinates { - private readonly applications = new Map>() + private readonly applications = new Map>() /** * Invalidate screenshot mappings when a window closes or changes size. @@ -20,9 +20,9 @@ export class CuaCoordinates { * @param windows - freshly observed windows. * @param windowId - selected window for a scoped observation; omission means a complete application inventory. */ - observe(appHandle: CuaAppHandle, windows: readonly CuaWindowInfo[], windowId?: number): void { + observe(appHandle: CuaAppHandle, windows: readonly CuaWindowInfo[], windowId?: string): void { const previous = this.applications.get(appHandle) - const current = new Map(windowId === undefined ? [] : previous) + const current = new Map(windowId === undefined ? [] : previous) if (windowId !== undefined && !windows.some(window => window.windowId === windowId)) current.delete(windowId) for (const window of windows) { const { width, height } = window.bounds @@ -40,7 +40,7 @@ export class CuaCoordinates { * @param image - encoded model-request image dimensions. */ screenshot( - appHandle: CuaAppHandle, windowId: number, bounds: { width: number; height: number }, image: { width: number; height: number }, + appHandle: CuaAppHandle, windowId: string, bounds: { width: number; height: number }, image: { width: number; height: number }, ): void { let frames = this.applications.get(appHandle) if (!frames) { frames = new Map(); this.applications.set(appHandle, frames) } diff --git a/packages/experimental/cua/src/guidance.ts b/packages/experimental/cua/src/guidance.ts index a28de6d0ca..a9021944be 100644 --- a/packages/experimental/cua/src/guidance.ts +++ b/packages/experimental/cua/src/guidance.ts @@ -4,7 +4,7 @@ export const COMMON_GUIDANCE = `Use cua to observe and operate native applicatio In persistent PTC, use the host-provided bridge initialization once and retain the returned objects; cua comes from that bridge and is not a preinstalled global. Use void await for observations that emit, and never stringify screenshot image bytes. -Signatures show resolved return values after await. ActionResult = { dispatched: boolean, foregroundChanged?: boolean | null }; foregroundChanged is omitted when not sampled and null when the sample is unavailable. JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue }; numbers must be finite. App is the application object with readonly app.appHandle: string (opaque) and the methods listed below for app level. Window is the window object with readonly window.windowId: number and the methods listed below for window level. +Signatures show resolved return values after await. ActionResult = { dispatched: boolean, foregroundChanged?: boolean | null }; foregroundChanged is omitted when not sampled and null when the sample is unavailable. JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue }; numbers must be finite. App is the application object with readonly app.appHandle: string (opaque) and the methods listed below for app level. Window is the window object with readonly window.windowId: string and the methods listed below for window level. Window IDs are opaque provider-issued strings; preserve them verbatim. Setup and discovery: - cua.getCapabilities(options?: { emit?: boolean }) -> { platform: string, permissions: { accessibility: boolean, screenRecording: boolean }, appLevelAccessibility: 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. @@ -12,11 +12,11 @@ Setup and discovery: - cua.findApps(query: string, options?: { emit?: boolean }) -> { id: string, displayName: string, path: string, isRunning: boolean }[] — search installed applications, including stopped matches. - cua.getState(options?: { emit?: boolean }) -> { apps: { id: string, displayName: string, isRunning: true }[], browsers: [] } — summarize running applications; this is not an accessibility observation. - cua.getApp(selector: string) -> App — select an application by provider-issued discovery ID, name, bundle ID, or absolute path where supported, obtain consent, launch in the background if needed, and read initial AX state silently; it does not activate the app. -- app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership. -- app.getWindow(windowId: number) -> Window — select one window and read its initial AX state silently; do this before any window screenshot or coordinate input. +- app.getWindows(options?: { emit?: boolean }) -> { windowId: string, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership. +- app.getWindow(windowId: string) -> Window — select one window and read its initial AX state silently; do this before any window screenshot or coordinate input. - app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required. -- app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation. -- window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation. +- app.show() -> { dispatched: boolean, windowId: string | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation. +- window.show() -> { dispatched: boolean, windowId: string | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation. ## Accessibility tree Available at app or window level depending on the platform. @@ -31,7 +31,7 @@ Element ids are opaque strings from the latest successful tree; the object facad ## Simulated mouse Use an explicit window for screenshots and pointer input. -- getScreenshot(options?: { emit?: boolean }) -> { bytes: Uint8Array, mimeType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif', pixelWidth: number, pixelHeight: number, windowId: number } — capture the selected window as one encoded image; bytes is a JavaScript byte array, and mimeType identifies its encoding, so do not assume PNG. +- getScreenshot(options?: { emit?: boolean }) -> { bytes: Uint8Array, mimeType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif', pixelWidth: number, pixelHeight: number, windowId: string } — capture the selected window as one encoded image; bytes is a JavaScript byte array, and mimeType identifies its encoding, so do not assume PNG. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — reveal AX alternate UI or move the system pointer without pressing; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], 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. - 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. diff --git a/packages/experimental/cua/src/protocol.ts b/packages/experimental/cua/src/protocol.ts index ad54407c51..8c36d085c0 100644 --- a/packages/experimental/cua/src/protocol.ts +++ b/packages/experimental/cua/src/protocol.ts @@ -3,7 +3,8 @@ import { Buffer } from 'node:buffer' import { z } from 'zod' import type { CuaAppHandle, CuaSnapshotId } from './types.ts' -const id = z.number().int().positive().max(2 ** 32 - 1) +const windowId = z.string().min(1) +const pixelDimension = z.number().int().positive().max(2 ** 32 - 1) const point = z.number().nonnegative() const relativePoint = z.number().int().min(0).max(999) const app = { appHandle: z.string().min(1) } @@ -12,12 +13,12 @@ const pointer = { mouseButton: z.enum(['left', 'right', 'middle']).optional(), const click = { ...pointer, clickCount: z.union([z.literal(1), z.literal(2)]).optional(), holdMs: z.number().int().nonnegative().optional() .describe('Milliseconds between each mouse press and release; omitted for an ordinary click.') } -const window = { ...app, windowId: id } +const window = { ...app, windowId } const jsonValue = z.json() /** Provider-issued element reference from an accessibility observation. */ export const elementId = z.string().min(1) .describe('Opaque string defined by the platform provider, valid for at least the lifetime of one snapshot.') -const snapshot = { ...app, windowId: id.optional(), snapshotId: z.string().min(1), elementId } +const snapshot = { ...app, windowId: windowId.optional(), snapshotId: z.string().min(1), elementId } const coordinate = { ...window, snapshotId: z.string().min(1).optional(), x: point, y: point } const absoluteCoordinate = { ...coordinate, relative: z.literal(false).optional().describe('Omitted or false uses pixels in the latest screenshot returned by this tool.') } const relativeCoordinate = { ...coordinate, relative: z.literal(true).describe('Use integer thousandths of the window width and height, from 0 to 999.'), x: relativePoint, y: relativePoint } @@ -39,9 +40,9 @@ export const Request = z.discriminatedUnion('method', [ operation('findApps', { query: z.string().min(1, 'Expected a non-empty search string').regex(/\S/, 'Expected a non-empty search string') }), operation('getApp', { selector: z.string().min(1) }), operation('activate', app), - operation('show', { ...app, windowId: id.optional() }), + operation('show', { ...app, windowId: windowId.optional() }), operation('listWindows', app), - operation('getState', { ...app, windowId: id.optional(), + operation('getState', { ...app, windowId: windowId.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 native bounds and complete action names.'), }), @@ -59,10 +60,10 @@ export const Request = z.discriminatedUnion('method', [ 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: id.optional(), text: z.string() }), - operation('paste', { ...app, windowId: id.optional(), text: z.string(), format: z.enum(['text', 'html']).optional() }), - operation('pressKey', { ...app, windowId: id.optional(), key: z.string().min(1), modifiers: z.array(z.string()).optional() }), - operation('sendKeyEvent', { ...app, windowId: id.optional(), key: z.string().min(1), direction: z.enum(['down', 'up']) }), + 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']) }), 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(), @@ -108,14 +109,14 @@ export const FoundAppsResult = z.array(z.object({ })) /** Current windows and their global native bounds. */ export const WindowsResult = z.array(z.object({ - windowId: id, appName: z.string(), title: z.string(), bounds, + windowId, appName: z.string(), title: z.string(), bounds, isOnScreen: z.boolean(), onCurrentSpace: z.boolean().nullable(), })) /** Observed state for the selected application or window. */ export const StateResult = z.object({ appHandle: z.string().min(1).transform(value => value as CuaAppHandle), - windowId: id.nullable(), - focusedWindowId: id.nullable().optional(), + windowId: windowId.nullable(), + focusedWindowId: windowId.nullable().optional(), snapshotId: z.string().min(1).transform(value => value as CuaSnapshotId), tree: z.string(), windows: WindowsResult, truncated: z.boolean(), }) @@ -123,7 +124,7 @@ export const StateResult = z.object({ export const ActionNamesResult = z.array(z.string()) /** Original native PNG and platform window geometry before Host image preparation. */ export const NativeScreenshotResult = z.object({ - mimeType: z.literal('image/png'), data: imageBase64, pixelWidth: id, pixelHeight: id, windowId: id, + mimeType: z.literal('image/png'), data: imageBase64, pixelWidth: pixelDimension, pixelHeight: pixelDimension, windowId, bounds: bounds.extend({ width: z.number().positive(), height: z.number().positive() }), coordinateSpace: z.enum(['window-points', 'window-pixels']), }) @@ -151,7 +152,7 @@ export const ActionResult = z.object({ /** Hover reports whether the selected route moved the user's system pointer. */ export const HoverResult = ActionResult.extend({ hoverRoute: z.enum(['accessibility', 'system-pointer']), systemPointerMoved: z.boolean() }) /** Background restoration dispatch and sampled foreground changes; null means the observation was unavailable. */ -export const ShowResult = ActionResult.extend({ windowId: id.nullable(), foregroundChanged: z.boolean().nullable() }) +export const ShowResult = ActionResult.extend({ windowId: windowId.nullable(), foregroundChanged: z.boolean().nullable() }) /** Bounded native PNG thumbnail for human presentation, excluded from model results and saved grants. */ export const ApplicationIcon = z.string().max(65536).regex(/^data:image\/png;base64,[A-Za-z0-9+/]+={0,2}$/) diff --git a/packages/experimental/cua/src/types.ts b/packages/experimental/cua/src/types.ts index f35c839abf..4cd136b630 100644 --- a/packages/experimental/cua/src/types.ts +++ b/packages/experimental/cua/src/types.ts @@ -183,7 +183,8 @@ export interface CuaSurface { * Coordinate input also rejects resizing since the latest successful AX read or screenshot. */ export interface CuaWindow extends CuaSurface { - readonly windowId: number + /** Opaque window identifier issued by the platform provider. */ + readonly windowId: string /** * Capture the selected window. * @param options - emission options. @@ -239,10 +240,10 @@ export interface CuaApp extends CuaSurface { getWindows(options?: CuaObservationOptions): Promise /** * Observe a specific window. - * @param windowId - ID obtained from getWindows. + * @param windowId - Decimal-string ID obtained from getWindows, passed unchanged. * @returns A window object with its initial accessibility tree read silently; this updates the application's current snapshot. */ - getWindow(windowId: number): Promise + getWindow(windowId: string): Promise } /** Native app API; its caller owns global bindings and variable persistence. */ export interface CuaApi { diff --git a/packages/experimental/cua/tests/api.spec.ts b/packages/experimental/cua/tests/api.spec.ts index 707bfc7089..f2c8ab5371 100644 --- a/packages/experimental/cua/tests/api.spec.ts +++ b/packages/experimental/cua/tests/api.spec.ts @@ -15,12 +15,12 @@ const selected = { appHandle: 'app-17', pid: 17, name: 'Editor', bundleId: 'test const delivered = { dispatched: true } const capabilities: CuaCapabilities = { platform: 'macos', sessionLocked: false, permissions: { accessibility: true, screenRecording: false }, appLevelAccessibility: true, keyboard: ['app'], methods: ['getState', 'click'], coordinateSpace: 'screenshot-pixels', browser: false } -function windowInfo(windowId: number) { +function windowInfo(windowId: string) { return { windowId, appName: 'Editor', title: `Document ${windowId}`, bounds, isOnScreen: true, onCurrentSpace: null } } function fixture(withSink = true) { - let windows = [windowInfo(23)] + let windows = [windowInfo('23')] let currentCapabilities: CuaCapabilities = capabilities let generation = 0 const sink = { text: vi.fn<(value: string) => void>(), image: vi.fn<(screenshot: CuaScreenshot) => void>() } @@ -31,7 +31,7 @@ function fixture(withSink = true) { case 'getApp': return selected case 'listWindows': return windows case 'mouseMove': return { ...delivered, hoverRoute: 'accessibility', systemPointerMoved: false } - case 'show': return { ...delivered, windowId: params.windowId ?? 23, foregroundChanged: false } + case 'show': return { ...delivered, windowId: params.windowId ?? '23', foregroundChanged: false } case 'getState': return { appHandle: selected.appHandle, windowId: params.windowId ?? null, snapshotId: `snapshot-${++generation}`, tree: `Tree ${generation}`, truncated: false, @@ -44,18 +44,18 @@ function fixture(withSink = true) { }) return { dispatch, sink, api: createCuaApi(dispatch, withSink ? sink : undefined), - setWindows: (ids: number[]) => { windows = ids.map(windowInfo) }, + setWindows: (ids: string[]) => { windows = ids.map(windowInfo) }, setWindowRecords: (records: ReturnType[]) => { windows = records }, setCapabilities: (value: CuaCapabilities) => { currentCapabilities = value }, } } function state(overrides: Record = {}): JsonValue { - return { appHandle: selected.appHandle, windowId: null, snapshotId: 'changed', tree: 'Changed tree', windows: [windowInfo(23)], truncated: false, ...overrides } + return { appHandle: selected.appHandle, windowId: null, snapshotId: 'changed', tree: 'Changed tree', windows: [windowInfo('23')], truncated: false, ...overrides } } function screenshot(overrides: Record = {}): JsonValue { - return { mimeType: 'image/png', data: PNG, pixelWidth: 1, pixelHeight: 1, windowId: 23, bounds, coordinateSpace: 'screenshot-pixels', ...overrides } + return { mimeType: 'image/png', data: PNG, pixelWidth: 1, pixelHeight: 1, windowId: '23', bounds, coordinateSpace: 'screenshot-pixels', ...overrides } } describe('application discovery', () => { @@ -93,12 +93,12 @@ describe('application discovery', () => { expect(app).not.toHaveProperty('pid') expectTypeOf().not.toHaveProperty('pid') expect(app.appHandle).toBe('app-17') - const window = await app.getWindow(23) - expect(await window.getScreenshot()).toEqual({ bytes: Uint8Array.from(Buffer.from(PNG, 'base64')), mimeType: 'image/png', pixelWidth: 1, pixelHeight: 1, windowId: 23 }) + const window = await app.getWindow('23') + expect(await window.getScreenshot()).toEqual({ bytes: Uint8Array.from(Buffer.from(PNG, 'base64')), mimeType: 'image/png', pixelWidth: 1, pixelHeight: 1, windowId: '23' }) expect(f.dispatch.mock.calls.map(([operation]) => operation.method)).toEqual([ 'getCapabilities', 'listApps', 'getApp', 'getState', 'getState', 'screenshot', ]) - expect(await app.getWindows()).toEqual([windowInfo(23)]) + expect(await app.getWindows()).toEqual([windowInfo('23')]) expect(f.sink.text).not.toHaveBeenCalled() expect(f.sink.image).not.toHaveBeenCalled() }) @@ -138,13 +138,13 @@ describe('background window restoration', () => { it('shows an app or selected window without dispatching activation or AXRaise', async () => { const f = fixture() const app = await f.api.getApp('Editor') - const window = await app.getWindow(24) + const window = await app.getWindow('24') f.dispatch.mockClear() - expect(await app.show()).toEqual({ ...delivered, windowId: 23, foregroundChanged: false }) - expect(await window.show()).toEqual({ ...delivered, windowId: 24, foregroundChanged: false }) + expect(await app.show()).toEqual({ ...delivered, windowId: '23', foregroundChanged: false }) + expect(await window.show()).toEqual({ ...delivered, windowId: '24', foregroundChanged: false }) expect(f.dispatch.mock.calls.map(([operation]) => operation)).toEqual([ { method: 'show', params: { appHandle: 'app-17' } }, - { method: 'show', params: { appHandle: 'app-17', windowId: 24 } }, + { method: 'show', params: { appHandle: 'app-17', windowId: '24' } }, ]) }) @@ -171,22 +171,22 @@ describe('mouseMove across observations', () => { it('moves to an AX element then into a popup without inserting clicks or restoring a point', async () => { const f = fixture() const app = await f.api.getApp('Editor') - const window = await app.getWindow(23) + const window = await app.getWindow('23') f.dispatch.mockClear() expect(await window.mouseMove(element('0'))).toEqual({ ...delivered, hoverRoute: 'accessibility', systemPointerMoved: false }) await window.getAccessibilityTree({ emit: false }) await window.getScreenshot({ emit: false }) expect(await window.mouseMove([30, 40])).toEqual({ ...delivered, hoverRoute: 'accessibility', systemPointerMoved: false }) expect(f.dispatch.mock.calls.map(([operation]) => operation)).toEqual([ - { method: 'mouseMove', params: { appHandle: 'app-17', snapshotId: 'snapshot-2', elementId: '0', windowId: 23 } }, - { method: 'getState', params: { appHandle: 'app-17', windowId: 23 } }, - { method: 'screenshot', params: { appHandle: 'app-17', windowId: 23 } }, - { method: 'mouseMove', params: { appHandle: 'app-17', snapshotId: 'snapshot-3', windowId: 23, x: 30, y: 40 } }, + { method: 'mouseMove', params: { appHandle: 'app-17', snapshotId: 'snapshot-2', elementId: '0', windowId: '23' } }, + { method: 'getState', params: { appHandle: 'app-17', windowId: '23' } }, + { method: 'screenshot', params: { appHandle: 'app-17', windowId: '23' } }, + { method: 'mouseMove', params: { appHandle: 'app-17', snapshotId: 'snapshot-3', windowId: '23', x: 30, y: 40 } }, ]) - const other = await app.getWindow(24) + const other = await app.getWindow('24') await other.mouseMove([5, 6]) expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'mouseMove', params: { - appHandle: 'app-17', snapshotId: 'snapshot-4', windowId: 24, x: 5, y: 6, + appHandle: 'app-17', snapshotId: 'snapshot-4', windowId: '24', x: 5, y: 6, } }) f.dispatch.mockRejectedValueOnce(new Error('WINDOW_CHANGED')) await expect(other.mouseMove([5, 6])).rejects.toThrow('WINDOW_CHANGED') @@ -198,7 +198,7 @@ describe('pointer buttons and modifiers', () => { it.each([0, 800])('preserves %d ms for window clicks at elements and coordinates', async (holdMs) => { const f = fixture() const app = await f.api.getApp('Editor') - const window = await app.getWindow(23) + const window = await app.getWindow('23') for (const target of [element('0'), [10, 20] as const]) { await window.click(target, { holdMs, mouseButton: 'right' }) expect(f.dispatch.mock.calls.at(-1)?.[0]).toMatchObject({ method: 'click', params: { holdMs, mouseButton: 'right' } }) @@ -211,19 +211,19 @@ describe('pointer buttons and modifiers', () => { it('retains middle-button and modifier intent through click and drag dispatch', async () => { const f = fixture() const app = await f.api.getApp('Editor') - const window = await app.getWindow(23) + const window = await app.getWindow('23') await window.click(element('0'), { mouseButton: 'middle', modifiers: ['shift'] }) expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'click', params: { - appHandle: 'app-17', snapshotId: 'snapshot-2', elementId: '0', windowId: 23, mouseButton: 'middle', modifiers: ['shift'], + appHandle: 'app-17', snapshotId: 'snapshot-2', elementId: '0', windowId: '23', mouseButton: 'middle', modifiers: ['shift'], } }) await window.click([10, 20], { modifiers: ['command'] }) expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'click', params: { - appHandle: 'app-17', windowId: 23, snapshotId: 'snapshot-2', x: 10, y: 20, + 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'] }) expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'drag', params: { - appHandle: 'app-17', windowId: 23, snapshotId: 'snapshot-2', fromX: 10, fromY: 20, toX: 30, toY: 40, + appHandle: 'app-17', windowId: '23', snapshotId: 'snapshot-2', fromX: 10, fromY: 20, toX: 30, toY: 40, mouseButton: 'middle', modifiers: ['shift', 'option'], } }) const count = f.dispatch.mock.calls.length @@ -325,30 +325,47 @@ describe('element default invocation', () => { }) describe('application and window observations', () => { + it('preserves an opaque window ID through discovery, observation and screenshot', async () => { + const windowId = 'window-main' + const f = fixture() + f.setWindows([windowId]) + const app = await f.api.getApp('Editor') + expect((await app.getWindows({ emit: false }))[0]!.windowId).toBe(windowId) + const window = await app.getWindow(windowId) + expectTypeOf(window.windowId).toEqualTypeOf() + expect(window.windowId).toBe(windowId) + const screenshot = await window.getScreenshot({ emit: false }) + expect(screenshot.windowId).toBe(windowId) + await window.click([10, 20]) + for (const [operation] of f.dispatch.mock.calls) { + if ('windowId' in operation.params) expect(operation.params.windowId).toBe(windowId) + } + }) + it('shares the latest tree read across an application and each selected window', async () => { const f = fixture() - f.setWindows([23, 24]) + f.setWindows(['23', '24']) const app = await f.api.getApp('Editor') - expect(await app.getWindows({ emit: false })).toEqual([windowInfo(23), windowInfo(24)]) - const first = await app.getWindow(23) - const second = await app.getWindow(24) + expect(await app.getWindows({ emit: false })).toEqual([windowInfo('23'), windowInfo('24')]) + const first = await app.getWindow('23') + const second = await app.getWindow('24') await app.setValue(element('1'), 'First document') await first.click(element('2')) await second.click(element('3')) expect(f.dispatch.mock.calls.slice(-3).map(([operation]) => operation)).toEqual([ { method: 'setValue', params: { appHandle: 'app-17', snapshotId: 'snapshot-3', elementId: '1', value: 'First document' } }, - { method: 'click', params: { appHandle: 'app-17', snapshotId: 'snapshot-3', elementId: '2', windowId: 23 } }, - { method: 'click', params: { appHandle: 'app-17', snapshotId: 'snapshot-3', elementId: '3', windowId: 24 } }, + { method: 'click', params: { appHandle: 'app-17', snapshotId: 'snapshot-3', elementId: '2', windowId: '23' } }, + { method: 'click', params: { appHandle: 'app-17', snapshotId: 'snapshot-3', elementId: '3', windowId: '24' } }, ]) - expect(first.windowId).toBe(23) - expect(second.windowId).toBe(24) + expect(first.windowId).toBe('23') + expect(second.windowId).toBe('24') expect(f.sink.text.mock.calls.map(([text]) => text)).toEqual([]) await expect(second.getAccessibilityTree({ emit: false, disableDiffing: true })).resolves.toBe('Tree 4') await second.click(element('3')) - expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'click', params: { appHandle: 'app-17', snapshotId: 'snapshot-4', elementId: '3', windowId: 24 } }) + expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'click', params: { appHandle: 'app-17', snapshotId: 'snapshot-4', elementId: '3', windowId: '24' } }) await app.getAccessibilityTree({ emit: false }) await first.invoke(element('4')) - expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'invoke', params: { appHandle: 'app-17', snapshotId: 'snapshot-5', elementId: '4', windowId: 23 } }) + expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'invoke', params: { appHandle: 'app-17', snapshotId: 'snapshot-5', elementId: '4', windowId: '23' } }) expect(f.sink.text).not.toHaveBeenCalled() }) @@ -382,7 +399,7 @@ describe('application and window observations', () => { const app = await f.api.getApp('Editor') expect(app).toHaveProperty('getAccessibilityTree') for (const method of ['getScreenshot', 'click', 'mouseMove', 'scroll', 'drag']) expect(app).not.toHaveProperty(method) - const window = await app.getWindow(23) + const window = await app.getWindow('23') for (const method of ['getScreenshot', 'click', 'mouseMove', 'scroll', 'drag']) expect(window).toHaveProperty(method) expect(window).not.toHaveProperty('hover') expect(window).toHaveProperty('mouseMove') @@ -391,36 +408,36 @@ describe('application and window observations', () => { it('attaches the shared snapshot to coordinates only within its window scope', async () => { const f = fixture() const app = await f.api.getApp('Editor') - const first = await app.getWindow(23) + const first = await app.getWindow('23') await first.click([10, 20]) expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'click', params: { - appHandle: 'app-17', windowId: 23, snapshotId: 'snapshot-2', x: 10, y: 20, mouseButton: 'left', clickCount: 1, + appHandle: 'app-17', windowId: '23', snapshotId: 'snapshot-2', x: 10, y: 20, mouseButton: 'left', clickCount: 1, } }) - const second = await app.getWindow(24) + const second = await app.getWindow('24') await first.click([10, 20]) expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'click', params: { - appHandle: 'app-17', windowId: 23, x: 10, y: 20, mouseButton: 'left', clickCount: 1, + appHandle: 'app-17', windowId: '23', x: 10, y: 20, mouseButton: 'left', clickCount: 1, } }) await second.click([10, 20]) - expect(f.dispatch.mock.calls.at(-1)?.[0]).toMatchObject({ params: { snapshotId: 'snapshot-3', windowId: 24 } }) + expect(f.dispatch.mock.calls.at(-1)?.[0]).toMatchObject({ params: { snapshotId: 'snapshot-3', windowId: '24' } }) await app.getAccessibilityTree({ emit: false }) await first.click([10, 20]) - expect(f.dispatch.mock.calls.at(-1)?.[0]).toMatchObject({ params: { snapshotId: 'snapshot-4', windowId: 23 } }) + expect(f.dispatch.mock.calls.at(-1)?.[0]).toMatchObject({ params: { snapshotId: 'snapshot-4', windowId: '23' } }) }) it('keeps a validated AXless window usable for screenshots and coordinate input', async () => { const f = fixture() const app = await f.api.getApp('Editor') - f.dispatch.mockResolvedValueOnce(state({ windowId: 23, snapshotId: 'axless', tree: '', elements: [] })) - const window = await app.getWindow(23) + f.dispatch.mockResolvedValueOnce(state({ windowId: '23', snapshotId: 'axless', tree: '', elements: [] })) + const window = await app.getWindow('23') expect(f.sink.text).not.toHaveBeenCalled() - await expect(window.getScreenshot()).resolves.toEqual({ bytes: Uint8Array.from(Buffer.from(PNG, 'base64')), mimeType: 'image/png', pixelWidth: 1, pixelHeight: 1, windowId: 23 }) + await expect(window.getScreenshot()).resolves.toEqual({ bytes: Uint8Array.from(Buffer.from(PNG, 'base64')), mimeType: 'image/png', pixelWidth: 1, pixelHeight: 1, windowId: '23' }) await window.click([10, 20]) await window.scroll({ x: 10, y: 20, deltaLinesX: 0, deltaLinesY: -1 }) await window.drag([10, 20], [30, 40]) expect(f.dispatch.mock.calls.slice(-4).map(([operation]) => operation.method)).toEqual(['screenshot', 'click', 'scroll', 'drag']) for (const [operation] of f.dispatch.mock.calls.slice(-3)) { - expect(operation.params).toMatchObject({ appHandle: 'app-17', windowId: 23, snapshotId: 'axless' }) + expect(operation.params).toMatchObject({ appHandle: 'app-17', windowId: '23', snapshotId: 'axless' }) } }) @@ -430,47 +447,47 @@ describe('application and window observations', () => { const failure = new Error(code) f.dispatch.mockRejectedValueOnce(failure) const calls = f.dispatch.mock.calls.length - await expect(app.getWindow(23)).rejects.toBe(failure) + await expect(app.getWindow('23')).rejects.toBe(failure) expect(f.dispatch.mock.calls.slice(calls).map(([operation]) => operation.method)).toEqual(['getState']) }) it('captures and clicks the explicitly selected window among several', async () => { const f = fixture() const windows = [ - windowInfo(23), - { ...windowInfo(24), title: 'Menu helper', bounds: { ...bounds, width: 0, height: 0 } }, - { ...windowInfo(25), isOnScreen: false }, - { ...windowInfo(26), bounds: { ...bounds, height: 0 } }, + windowInfo('23'), + { ...windowInfo('24'), title: 'Menu helper', bounds: { ...bounds, width: 0, height: 0 } }, + { ...windowInfo('25'), isOnScreen: false }, + { ...windowInfo('26'), bounds: { ...bounds, height: 0 } }, ] f.setWindowRecords(windows) const app = await f.api.getApp('Editor') expect(await app.getWindows({ emit: false })).toEqual(windows) - const window = await app.getWindow(23) + const window = await app.getWindow('23') await window.getScreenshot() - expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'screenshot', params: { appHandle: 'app-17', windowId: 23 } }) + expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'screenshot', params: { appHandle: 'app-17', windowId: '23' } }) await window.click([10, 20]) expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'click', params: { - appHandle: 'app-17', windowId: 23, snapshotId: 'snapshot-2', x: 10, y: 20, mouseButton: 'left', clickCount: 1, + appHandle: 'app-17', windowId: '23', snapshotId: 'snapshot-2', x: 10, y: 20, mouseButton: 'left', clickCount: 1, } }) - const hidden = await app.getWindow(25) + const hidden = await app.getWindow('25') await hidden.click([10, 20]) expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'click', params: { - appHandle: 'app-17', windowId: 25, snapshotId: 'snapshot-3', x: 10, y: 20, mouseButton: 'left', clickCount: 1, + appHandle: 'app-17', windowId: '25', snapshotId: 'snapshot-3', x: 10, y: 20, mouseButton: 'left', clickCount: 1, } }) }) it('captures a window without reading its accessibility tree', async () => { const f = fixture() const app = await f.api.getApp('Editor') - const window = await app.getWindow(23) + const window = await app.getWindow('23') const calls = f.dispatch.mock.calls.length await window.getScreenshot() expect(f.dispatch).toHaveBeenCalledTimes(calls + 1) - expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'screenshot', params: { appHandle: 'app-17', windowId: 23 } }) + expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'screenshot', params: { appHandle: 'app-17', windowId: '23' } }) }) const providerIdentities: Record[] = [ - { appHandle: 'another-app' }, { windowId: 24 }, + { appHandle: 'another-app' }, { windowId: '24' }, ] it.each(providerIdentities)('rejects provider state from another target and discards the old snapshot: %j', async (identity) => { const f = fixture() @@ -484,7 +501,7 @@ describe('application and window observations', () => { it('returns provider window records without process filtering', async () => { const f = fixture() const app = await f.api.getApp('Editor') - const observed = windowInfo(24) + const observed = windowInfo('24') f.dispatch.mockResolvedValueOnce(state({ windows: [observed] })) await expect(app.getAccessibilityTree()).resolves.toBe('Changed tree') f.dispatch.mockResolvedValueOnce([observed]) @@ -508,12 +525,12 @@ describe('application and window observations', () => { expect(f.dispatch.mock.calls.map(([operation]) => operation)).toEqual([ { method: 'typeText', params: { appHandle: 'app-17', text: 'keyboard without accessibility' } }, ]) - const window = await app.getWindow(23) + const window = await app.getWindow('23') await expect(window.getAccessibilityTree({ emit: false })).resolves.toBe('Tree 2') await expect(app.getAccessibilityTree()).rejects.toThrow('Application-level accessibility is not supported on current platform; observe a window instead.') await expect(window.invoke(element('0'))).resolves.toEqual(delivered) expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'invoke', params: { - appHandle: 'app-17', windowId: 23, snapshotId: 'snapshot-2', elementId: '0', + appHandle: 'app-17', windowId: '23', snapshotId: 'snapshot-2', elementId: '0', } }) }) @@ -521,7 +538,7 @@ describe('application and window observations', () => { const f = fixture() f.setCapabilities({ ...capabilities, keyboard: ['app', 'window'] }) const app = await f.api.getApp('Editor') - const window = await app.getWindow(23) + const window = await app.getWindow('23') f.dispatch.mockClear() await window.typeText('hello') await window.paste('bold', { format: 'html' }) @@ -530,9 +547,9 @@ describe('application and window observations', () => { await app.paste('app paste') await app.pressKey('Tab', ['shift']) expect(f.dispatch.mock.calls.map(([operation]) => operation)).toEqual([ - { method: 'typeText', params: { appHandle: 'app-17', windowId: 23, text: 'hello' } }, - { method: 'paste', params: { appHandle: 'app-17', windowId: 23, text: 'bold', format: 'html' } }, - { method: 'pressKey', params: { appHandle: 'app-17', windowId: 23, key: 'a', modifiers: ['command'] } }, + { method: 'typeText', params: { appHandle: 'app-17', windowId: '23', text: 'hello' } }, + { method: 'paste', params: { appHandle: 'app-17', windowId: '23', text: 'bold', format: 'html' } }, + { method: 'pressKey', params: { appHandle: 'app-17', windowId: '23', key: 'a', modifiers: ['command'] } }, { method: 'typeText', params: { appHandle: 'app-17', text: 'app text' } }, { method: 'paste', params: { appHandle: 'app-17', text: 'app paste' } }, { method: 'pressKey', params: { appHandle: 'app-17', key: 'Tab', modifiers: ['shift'] } }, @@ -543,7 +560,7 @@ describe('application and window observations', () => { const f = fixture() f.setCapabilities({ ...capabilities, keyboard: ['window'] }) const app = await f.api.getApp('Editor') - const window = await app.getWindow(23) + const window = await app.getWindow('23') f.dispatch.mockClear() await expect(app.typeText('app text')).rejects.toThrow('App-scoped keyboard input is not supported on current platform.') await expect(app.paste('app text')).rejects.toThrow('App-scoped keyboard input is not supported on current platform.') @@ -551,25 +568,25 @@ describe('application and window observations', () => { await expect(app.pressKey('', ['command'])).rejects.toThrow('App-scoped keyboard input is not supported on current platform.') expect(f.dispatch).not.toHaveBeenCalled() await expect(window.typeText('window text')).resolves.toEqual(delivered) - expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'typeText', params: { appHandle: 'app-17', windowId: 23, text: 'window text' } }) + expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'typeText', params: { appHandle: 'app-17', windowId: '23', text: 'window text' } }) }) it('accepts coordinate input without a current snapshot', async () => { const f = fixture() const app = await f.api.getApp('Editor') - const window = await app.getWindow(23) + const window = await app.getWindow('23') f.dispatch.mockRejectedValueOnce(new Error('Native app is busy')) await expect(window.getAccessibilityTree()).rejects.toThrow('Native app is busy') await window.click([10, 20]) expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'click', params: { - appHandle: 'app-17', windowId: 23, x: 10, y: 20, mouseButton: 'left', clickCount: 1, + appHandle: 'app-17', windowId: '23', x: 10, y: 20, mouseButton: 'left', clickCount: 1, } }) }) it('clears a failed refresh and requires a new read before element operations', async () => { const f = fixture() const app = await f.api.getApp('Editor') - const window = await app.getWindow(23) + const window = await app.getWindow('23') const failure = new Error('Native app is busy') f.dispatch.mockRejectedValueOnce(failure) await expect(app.getAccessibilityTree()).rejects.toBe(failure) @@ -590,15 +607,15 @@ describe('application and window observations', () => { describe('screenshots', () => { it('returns screenshot metadata independently of input point bounds and supports selective output', async () => { const f = fixture() - f.setWindows([23, 24]) + f.setWindows(['23', '24']) const app = await f.api.getApp('Editor') - const window = await app.getWindow(24) + const window = await app.getWindow('24') f.sink.text.mockClear() const tree = await window.getAccessibilityTree() const image = await window.getScreenshot() expect(tree).toBe('Tree 3') - expect(image).toEqual({ bytes: Uint8Array.from(Buffer.from(PNG, 'base64')), mimeType: 'image/png', pixelWidth: 1, pixelHeight: 1, windowId: 24 }) - expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'screenshot', params: { appHandle: 'app-17', windowId: 24 } }) + expect(image).toEqual({ bytes: Uint8Array.from(Buffer.from(PNG, 'base64')), mimeType: 'image/png', pixelWidth: 1, pixelHeight: 1, windowId: '24' }) + expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'screenshot', params: { appHandle: 'app-17', windowId: '24' } }) expect(f.sink.text).toHaveBeenCalledWith('Tree 3') expect(f.sink.image).toHaveBeenCalledWith(image) await window.getAccessibilityTree({ emit: false }) @@ -610,8 +627,8 @@ describe('screenshots', () => { it('rejects a screenshot from another window before emitting its image', async () => { const f = fixture() const app = await f.api.getApp('Editor') - const window = await app.getWindow(23) - f.dispatch.mockResolvedValueOnce(screenshot({ windowId: 24 })) + const window = await app.getWindow('23') + f.dispatch.mockResolvedValueOnce(screenshot({ windowId: '24' })) await expect(window.getScreenshot()).rejects.toThrow('belongs to another window') expect(f.sink.image).not.toHaveBeenCalled() }) @@ -619,11 +636,11 @@ describe('screenshots', () => { it.each(['image/jpeg', 'image/webp', 'image/gif'])('preserves Host-admitted %s bytes and metadata in the return value and image sink', async (mimeType) => { const f = fixture() const app = await f.api.getApp('Editor') - const window = await app.getWindow(23) + const window = await app.getWindow('23') const data = Buffer.from('admitted request image').toString('base64') f.dispatch.mockResolvedValueOnce(screenshot({ mimeType, data, pixelWidth: 320, pixelHeight: 240 })) const image = await window.getScreenshot() - expect(image).toEqual({ bytes: Uint8Array.from(Buffer.from(data, 'base64')), mimeType, pixelWidth: 320, pixelHeight: 240, windowId: 23 }) + expect(image).toEqual({ bytes: Uint8Array.from(Buffer.from(data, 'base64')), mimeType, pixelWidth: 320, pixelHeight: 240, windowId: '23' }) expect(f.sink.image).toHaveBeenCalledExactlyOnceWith(image) }) @@ -633,7 +650,7 @@ describe('input actions', () => { it('passes explicit relative mode to every coordinate gesture and rejects it on element ids', async () => { const f = fixture() const app = await f.api.getApp('Editor') - const window = await app.getWindow(23) + const window = await app.getWindow('23') await window.click([500, 250], { relative: true }) await window.mouseMove([500, 250], { relative: true }) await window.drag([0, 0], [999, 999], { relative: true }) @@ -651,32 +668,32 @@ describe('input actions', () => { it('keeps the selected window when scroll options include another target identity', async () => { const f = fixture() const app = await f.api.getApp('Editor') - const window = await app.getWindow(23) + const window = await app.getWindow('23') const options = { x: 10, y: 20, deltaLinesX: 0, deltaLinesY: 1, - appHandle: 'another-app', snapshotId: 'another-snapshot', windowId: 24, + appHandle: 'another-app', snapshotId: 'another-snapshot', windowId: '24', } await window.scroll(options) expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'scroll', params: { - appHandle: 'app-17', snapshotId: 'snapshot-2', windowId: 23, x: 10, y: 20, deltaLinesX: 0, deltaLinesY: 1, + appHandle: 'app-17', snapshotId: 'snapshot-2', windowId: '23', x: 10, y: 20, deltaLinesX: 0, deltaLinesY: 1, } }) }) it('dispatches window-point gestures and reports delivery without claiming the action succeeded', async () => { const f = fixture() const app = await f.api.getApp('Editor') - const window = await app.getWindow(23) + const window = await app.getWindow('23') expect(await window.click([10, 20], { mouseButton: 'right' })).toEqual(delivered) expect(await window.click([11, 21], { clickCount: 2 })).toEqual(delivered) expect(await window.scroll({ x: 10, y: 20, deltaLinesX: -2, deltaLinesY: 3 })).toEqual(delivered) expect(await window.drag([1, 2], [30, 40])).toEqual(delivered) expect(f.dispatch.mock.calls.slice(-4).map(([operation]) => operation)).toEqual([ - { method: 'click', params: { appHandle: 'app-17', windowId: 23, snapshotId: 'snapshot-2', x: 10, y: 20, mouseButton: 'right', clickCount: 1 } }, - { method: 'click', params: { appHandle: 'app-17', windowId: 23, snapshotId: 'snapshot-2', x: 11, y: 21, mouseButton: 'left', clickCount: 2 } }, - { method: 'scroll', params: { appHandle: 'app-17', windowId: 23, snapshotId: 'snapshot-2', x: 10, y: 20, deltaLinesX: -2, deltaLinesY: 3 } }, - { method: 'drag', params: { appHandle: 'app-17', windowId: 23, snapshotId: 'snapshot-2', fromX: 1, fromY: 2, toX: 30, toY: 40 } }, + { method: 'click', params: { appHandle: 'app-17', windowId: '23', snapshotId: 'snapshot-2', x: 10, y: 20, mouseButton: 'right', clickCount: 1 } }, + { method: 'click', params: { appHandle: 'app-17', windowId: '23', snapshotId: 'snapshot-2', x: 11, y: 21, mouseButton: 'left', clickCount: 2 } }, + { method: 'scroll', params: { appHandle: 'app-17', windowId: '23', snapshotId: 'snapshot-2', x: 10, y: 20, deltaLinesX: -2, deltaLinesY: 3 } }, + { method: 'drag', params: { appHandle: 'app-17', windowId: '23', snapshotId: 'snapshot-2', fromX: 1, fromY: 2, toX: 30, toY: 40 } }, ]) }) @@ -698,7 +715,6 @@ describe('input actions', () => { ['empty key', ({ app }) => app.pressKey('')], ] it.each<[string, (surfaces: Surfaces) => Promise]>([ - ['getState windowId: Too small: expected number to be >0', ({ app }) => app.getWindow(0)], ['selectText text: Too small: expected string to have >=1 characters', ({ app }) => app.selectText(element('0'), '')], ['mouseMove x: Invalid input: expected number, received NaN', ({ window }) => window.mouseMove([NaN, 0])], ['mouseMove x: Too big: expected number to be <=999', ({ window }) => window.mouseMove([1000, 0], { relative: true })], @@ -706,7 +722,7 @@ describe('input actions', () => { ])('reports a readable validation failure: %s', async (message, run) => { const f = fixture() const app = await f.api.getApp('Editor') - const window = await app.getWindow(23) + const window = await app.getWindow('23') f.dispatch.mockClear() await expect(run({ app, window })).rejects.toMatchObject({ name: 'Error', message }) expect(f.dispatch).not.toHaveBeenCalled() @@ -715,7 +731,7 @@ describe('input actions', () => { it.each(invalidActions)('rejects %s without invoking native input', async (_label, run) => { const f = fixture() const app = await f.api.getApp('Editor') - const window = await app.getWindow(23) + const window = await app.getWindow('23') const calls = f.dispatch.mock.calls.length await expect(run({ app, window })).rejects.toThrow() expect(f.dispatch).toHaveBeenCalledTimes(calls) @@ -778,7 +794,7 @@ describe('input actions', () => { it('rejects keyboard input on a window surface without dispatching an app-level fallback', async () => { const f = fixture() const app = await f.api.getApp('Editor') - const window = await app.getWindow(23) + const window = await app.getWindow('23') f.dispatch.mockClear() for (const run of [ () => window.typeText('hello'), @@ -800,13 +816,13 @@ describe('input actions', () => { const f = fixture() f.setCapabilities({ ...capabilities, keyboard: ['app', 'window'] }) const app = await f.api.getApp('Editor') - const surface = scope === 'window' ? await app.getWindow(23) : app + const surface = scope === 'window' ? await app.getWindow('23') : app f.dispatch.mockClear() f.dispatch.mockResolvedValueOnce(delivered) await expect(surface.sendKeyEvent('Shift', direction)).resolves.toEqual(delivered) expect(f.dispatch).toHaveBeenCalledTimes(1) expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'sendKeyEvent', params: { - appHandle: 'app-17', ...scope === 'window' ? { windowId: 23 } : {}, key: 'Shift', direction, + appHandle: 'app-17', ...scope === 'window' ? { windowId: '23' } : {}, key: 'Shift', direction, } }) }) @@ -833,7 +849,7 @@ describe('input actions', () => { const windowFixture = fixture() windowFixture.setCapabilities({ ...capabilities, keyboard: ['app'] }) const windowApp = await windowFixture.api.getApp('Editor') - const window = await windowApp.getWindow(23) + const window = await windowApp.getWindow('23') windowFixture.dispatch.mockClear() await expect(window.sendKeyEvent('', 'up')).rejects.toThrow('Window-scoped keyboard input is not supported on current platform.') expect(windowFixture.dispatch).not.toHaveBeenCalled() @@ -842,24 +858,24 @@ describe('input actions', () => { it('retains the snapshot identity for element right and double clicks', async () => { const f = fixture() const app = await f.api.getApp('Editor') - const window = await app.getWindow(23) + const window = await app.getWindow('23') await window.click(element('12'), { mouseButton: 'right' }) await window.click(element('13'), { clickCount: 2 }) expect(f.dispatch.mock.calls.slice(-2).map(([operation]) => operation)).toEqual([ - { method: 'click', params: { appHandle: 'app-17', snapshotId: 'snapshot-2', elementId: '12', windowId: 23, mouseButton: 'right' } }, - { method: 'click', params: { appHandle: 'app-17', snapshotId: 'snapshot-2', elementId: '13', windowId: 23, clickCount: 2 } }, + { method: 'click', params: { appHandle: 'app-17', snapshotId: 'snapshot-2', elementId: '12', windowId: '23', mouseButton: 'right' } }, + { method: 'click', params: { appHandle: 'app-17', snapshotId: 'snapshot-2', elementId: '13', windowId: '23', clickCount: 2 } }, ]) }) it('dispatches an opaque provider element id unchanged', async () => { const f = fixture() const app = await f.api.getApp('Editor') - const window = await app.getWindow(23) + const window = await app.getWindow('23') await window.click(element('42.12345')) await window.mouseMove(element('42.12345')) expect(f.dispatch.mock.calls.slice(-2).map(([operation]) => operation)).toEqual([ - { method: 'click', params: { appHandle: 'app-17', snapshotId: 'snapshot-2', elementId: '42.12345', windowId: 23 } }, - { method: 'mouseMove', params: { appHandle: 'app-17', snapshotId: 'snapshot-2', elementId: '42.12345', windowId: 23 } }, + { method: 'click', params: { appHandle: 'app-17', snapshotId: 'snapshot-2', elementId: '42.12345', windowId: '23' } }, + { method: 'mouseMove', params: { appHandle: 'app-17', snapshotId: 'snapshot-2', elementId: '42.12345', windowId: '23' } }, ]) }) @@ -874,7 +890,7 @@ describe('input actions', () => { it('propagates native failures once and rejects malformed delivery claims', async () => { const f = fixture() const app = await f.api.getApp('Editor') - const window = await app.getWindow(23) + const window = await app.getWindow('23') const failure = new Error('Application was restarted; select it again') f.dispatch.mockRejectedValueOnce(failure) await expect(app.typeText('hello')).rejects.toBe(failure) @@ -890,7 +906,7 @@ describe('input actions', () => { expect(f.dispatch).not.toHaveBeenCalled() const app = await f.api.getApp('Editor') const calls = f.dispatch.mock.calls.length - await expect(app.getWindow(0)).rejects.toThrow() + await expect(app.getWindow('0')).rejects.toThrow() expect(f.dispatch).toHaveBeenCalledTimes(calls) }) }) diff --git a/packages/experimental/cua/tests/bridge.spec.ts b/packages/experimental/cua/tests/bridge.spec.ts index f9deb49f7f..27d97eaa01 100644 --- a/packages/experimental/cua/tests/bridge.spec.ts +++ b/packages/experimental/cua/tests/bridge.spec.ts @@ -20,7 +20,7 @@ const selected = { appHandle: 'app-17', name: 'Editor', running: true } const bounds = { x: 0, y: 0, width: 640, height: 480 } const snapshot = { appHandle: 'app-17', windowId: null, snapshotId: 'snapshot-1', tree: '0 button', truncated: false, - windows: [{ windowId: 23, appName: 'Editor', title: 'Document', bounds, isOnScreen: true, onCurrentSpace: null }], + windows: [{ windowId: '23', appName: 'Editor', title: 'Document', bounds, isOnScreen: true, onCurrentSpace: null }], } it('uses the current tool binding when a retained app is called by another execution', async () => { @@ -34,13 +34,13 @@ it('uses the current tool binding when a retained app is called by another execu const text = vi.fn() const cua = connectCua(() => current, text) const app = await cua.getApp('Editor') - const window = await app.getWindow(23) + const window = await app.getWindow('23') const second = vi.fn(async (): Promise => ({ dispatched: true })) current = second await expect(window.click(element('0'))).resolves.toEqual({ dispatched: true }) expect(first).toHaveBeenCalledTimes(4) - expect(second).toHaveBeenCalledWith({ method: 'click', params: { appHandle: 'app-17', snapshotId: 'snapshot-1', elementId: '0', windowId: 23 } }) + expect(second).toHaveBeenCalledWith({ method: 'click', params: { appHandle: 'app-17', snapshotId: 'snapshot-1', elementId: '0', windowId: '23' } }) expect(text).not.toHaveBeenCalled() current = first await app.getAccessibilityTree() @@ -71,15 +71,15 @@ it('returns screenshot bytes and metadata with one image-bearing tool call and n if (operation.method === 'getApp') return selected if (operation.method === 'getState') return { ...snapshot, windowId: operation.params.windowId ?? null } return { - mimeType: 'image/png', data: PNG, pixelWidth: 1, pixelHeight: 1, windowId: 23, bounds, coordinateSpace: 'screenshot-pixels', + mimeType: 'image/png', data: PNG, pixelWidth: 1, pixelHeight: 1, windowId: '23', bounds, coordinateSpace: 'screenshot-pixels', } }) const text = vi.fn() const app = await connectCua(() => tool, text).getApp('Editor') - const window = await app.getWindow(23) + const window = await app.getWindow('23') text.mockClear() - expect(await window.getScreenshot()).toEqual({ bytes: Uint8Array.from(Buffer.from(PNG, 'base64')), mimeType: 'image/png', pixelWidth: 1, pixelHeight: 1, windowId: 23 }) + expect(await window.getScreenshot()).toEqual({ bytes: Uint8Array.from(Buffer.from(PNG, 'base64')), mimeType: 'image/png', pixelWidth: 1, pixelHeight: 1, windowId: '23' }) expect(tool.mock.calls.map(([operation]) => operation.method)).toEqual(['getCapabilities', 'getApp', 'getState', 'getState', 'screenshot']) expect(text).not.toHaveBeenCalled() }) diff --git a/packages/experimental/cua/tests/coordinates.spec.ts b/packages/experimental/cua/tests/coordinates.spec.ts index fbe9b22be7..adbc0f70a0 100644 --- a/packages/experimental/cua/tests/coordinates.spec.ts +++ b/packages/experimental/cua/tests/coordinates.spec.ts @@ -6,14 +6,26 @@ import type { CuaAppHandle, CuaWindowInfo } from '../src/types.ts' const handle = 'app' as CuaAppHandle const window = (width = 640, height = 480, x = 100): CuaWindowInfo => ({ - windowId: 7, appName: 'Fixture', title: 'Window', bounds: { x, y: 200, width, height }, isOnScreen: true, onCurrentSpace: true, + windowId: '7', appName: 'Fixture', title: 'Window', bounds: { x, y: 200, width, height }, isOnScreen: true, onCurrentSpace: true, +}) +const call = (method: string, params: object) => Request.parse({ method, params: { appHandle: handle, windowId: '7', ...params } }) + +it('keeps distinct windows independently mapped and invalidated', () => { + const coordinates = new CuaCoordinates() + const first = 'window-main', second = 'window-secondary' + coordinates.screenshot(handle, first, window(640, 480).bounds, { width: 640, height: 480 }) + coordinates.screenshot(handle, second, window(1280, 960).bounds, { width: 640, height: 480 }) + expect(coordinates.parameters(call('click', { windowId: first, x: 10, y: 20 }))).toMatchObject({ windowId: first, x: 10, y: 20 }) + expect(coordinates.parameters(call('click', { windowId: second, x: 10, y: 20 }))).toMatchObject({ windowId: second, x: 20, y: 40 }) + coordinates.observe(handle, [], first) + expect(() => coordinates.parameters(call('click', { windowId: first, x: 10, y: 20 }))).toThrow('STALE_SNAPSHOT') + expect(coordinates.parameters(call('click', { windowId: second, x: 10, y: 20 }))).toMatchObject({ windowId: second, x: 20, y: 40 }) }) -const call = (method: string, params: object) => Request.parse({ method, params: { appHandle: handle, windowId: 7, ...params } }) it('maps Retina and downscaled screenshot pixels to the same native point', () => { const coordinates = new CuaCoordinates() for (const pixels of [{ width: 1280, height: 960 }, { width: 320, height: 240 }]) { - coordinates.screenshot(handle, 7, window().bounds, pixels) + coordinates.screenshot(handle, '7', window().bounds, pixels) for (const method of ['click', 'mouseMove', 'scroll']) { const request = call(method, { x: pixels.width / 2, y: pixels.height / 4, ...method === 'scroll' ? { deltaLinesX: 0, deltaLinesY: -1 } : {} }) @@ -34,7 +46,7 @@ it.each(['click', 'mouseMove', 'scroll'])('preserves thousandth scaling for %s a } assertPoints() for (const image of [{ width: 2400, height: 1800 }, { width: 300, height: 225 }]) { - coordinates.screenshot(handle, 7, bounds, image) + coordinates.screenshot(handle, '7', bounds, image) assertPoints() } }) @@ -43,7 +55,7 @@ it('maps relative drag endpoints and keeps 999 inside a one-point window', () => const coordinates = new CuaCoordinates() coordinates.observe(handle, [window(1200, 900)]) const params = { fromX: 0, fromY: 250, toX: 999, toY: 500, relative: true } - expect(coordinates.parameters(call('drag', params))).toEqual({ appHandle: handle, windowId: 7, + expect(coordinates.parameters(call('drag', params))).toEqual({ appHandle: handle, windowId: '7', fromX: 0, fromY: 225, toX: 1198.8, toY: 450 }) coordinates.observe(handle, [window(1, 1)]) expect(coordinates.parameters(call('click', { x: 999, y: 999, relative: true }))).toMatchObject({ x: 0, y: 0 }) @@ -51,15 +63,15 @@ it('maps relative drag endpoints and keeps 999 inside a one-point window', () => it('maps both drag endpoints and preserves button, modifiers and snapshot identity', () => { const coordinates = new CuaCoordinates() - coordinates.screenshot(handle, 7, window().bounds, { width: 1280, height: 960 }) + coordinates.screenshot(handle, '7', window().bounds, { width: 1280, height: 960 }) const options = { fromX: 320, fromY: 240, toX: 640, toY: 480, relative: false, snapshotId: 'snapshot', mouseButton: 'right', modifiers: ['shift'] } - expect(coordinates.parameters(call('drag', options))).toEqual({ appHandle: handle, windowId: 7, + expect(coordinates.parameters(call('drag', options))).toEqual({ appHandle: handle, windowId: '7', fromX: 160, fromY: 120, toX: 320, toY: 240, snapshotId: 'snapshot', mouseButton: 'right', modifiers: ['shift'] }) }) it('preserves pixels after movement but requires a new image after resize or close', () => { const coordinates = new CuaCoordinates() - coordinates.screenshot(handle, 7, window().bounds, { width: 1280, height: 960 }) + coordinates.screenshot(handle, '7', window().bounds, { width: 1280, height: 960 }) const request = call('click', { x: 640, y: 480 }) coordinates.observe(handle, [window(640, 480, -900)]) expect(coordinates.parameters(request)).toMatchObject({ x: 320, y: 240 }) @@ -77,15 +89,15 @@ it('rejects unobserved, empty and out-of-image targets without native dispatch', expect(() => coordinates.parameters(call('mouseMove', { x: 0, y: 0, relative: true }))).toThrow('STALE_SNAPSHOT') coordinates.observe(handle, [window(640, 0)]) expect(() => coordinates.parameters(call('mouseMove', { x: 0, y: 0, relative: true }))).toThrow('STALE_SNAPSHOT') - coordinates.screenshot(handle, 7, window().bounds, { width: 320, height: 240 }) + coordinates.screenshot(handle, '7', window().bounds, { width: 320, height: 240 }) for (const [x, y] of [[320, 0], [0, 240]]) expect(() => coordinates.parameters(call('click', { x, y }))).toThrow('INVALID_ARGUMENT') }) it('keeps different application/window mappings independent and leaves element actions unchanged', () => { const coordinates = new CuaCoordinates() coordinates.observe(handle, [window()]) - coordinates.screenshot(handle, 7, window().bounds, { width: 1280, height: 960 }) - coordinates.screenshot('other' as CuaAppHandle, 7, window(100, 100).bounds, { width: 100, height: 100 }) + coordinates.screenshot(handle, '7', window().bounds, { width: 1280, height: 960 }) + coordinates.screenshot('other' as CuaAppHandle, '7', window(100, 100).bounds, { width: 100, height: 100 }) expect(coordinates.parameters(call('click', { x: 640, y: 480 }))).toMatchObject({ x: 320, y: 240 }) const request = Request.parse({ method: 'mouseMove', params: { appHandle: handle, snapshotId: 's', elementId: '2' } }) expect(coordinates.parameters(request)).toEqual(request.params) @@ -93,11 +105,11 @@ it('keeps different application/window mappings independent and leaves element a it('keeps other windows mapped during scoped observations and only removes the scoped closed window', () => { const coordinates = new CuaCoordinates() - coordinates.screenshot(handle, 7, window().bounds, { width: 1280, height: 960 }) - coordinates.observe(handle, [{ ...window(), windowId: 8 }], 8) + coordinates.screenshot(handle, '7', window().bounds, { width: 1280, height: 960 }) + coordinates.observe(handle, [{ ...window(), windowId: '8' }], '8') expect(coordinates.parameters(call('click', { x: 640, y: 480 }))).toMatchObject({ x: 320, y: 240 }) - coordinates.observe(handle, [], 8) + coordinates.observe(handle, [], '8') expect(coordinates.parameters(call('click', { x: 640, y: 480 }))).toMatchObject({ x: 320, y: 240 }) - coordinates.observe(handle, [], 7) + coordinates.observe(handle, [], '7') expect(() => coordinates.parameters(call('click', { x: 0, y: 0 }))).toThrow('STALE_SNAPSHOT') }) diff --git a/packages/experimental/cua/tests/native-schema.spec.ts b/packages/experimental/cua/tests/native-schema.spec.ts index 214eaa889c..74b2075b50 100644 --- a/packages/experimental/cua/tests/native-schema.spec.ts +++ b/packages/experimental/cua/tests/native-schema.spec.ts @@ -32,6 +32,17 @@ it('retains optional resource fields and tuple-valued parameters without inventi expect(generated.enums.get('getState')?.get('choice')).toEqual(new Set(['one'])) }) +it('generates opaque string admission for native window targets', () => { + expect(JSON.parse(nativeProtocol().json)).toMatchObject({ oneOf: expect.arrayContaining([ + expect.objectContaining({ properties: expect.objectContaining({ + method: { const: 'screenshot', type: 'string' }, + params: expect.objectContaining({ properties: expect.objectContaining({ + windowId: { type: 'string' }, + }) }), + }) }), + ]) }) +}) + it('admits only locator fields for default invocation', () => { expect(nativeProtocol().fields.get('invoke')).toEqual(new Set(['appHandle', 'snapshotId', 'elementId', 'windowId'])) }) diff --git a/packages/experimental/cua/tests/protocol.spec.ts b/packages/experimental/cua/tests/protocol.spec.ts index 50fb329c07..4b275c2bf2 100644 --- a/packages/experimental/cua/tests/protocol.spec.ts +++ b/packages/experimental/cua/tests/protocol.spec.ts @@ -1,7 +1,30 @@ /** 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, Request, ScreenshotResult } from '../src/protocol.ts' +import { CapabilitiesResult, NativeScreenshotResult, Request, ScreenshotResult, ShowResult, StateResult, WindowsResult } from '../src/protocol.ts' + +it('preserves opaque window IDs in requests and results', () => { + const windowId = 'window-main' + const request = { method: 'screenshot', params: { appHandle: 'app', windowId } } + expect(Request.parse(request)).toEqual(request) + const windows = [{ windowId, appName: 'Fixture', title: 'Window', + bounds: { x: 0, y: 0, width: 100, height: 80 }, isOnScreen: true, onCurrentSpace: null }] + expect(WindowsResult.parse(windows)).toEqual(windows) + const state = { appHandle: 'app', windowId, focusedWindowId: windowId, snapshotId: 'snapshot', tree: '', windows, truncated: false } + expect(StateResult.parse(state)).toEqual(state) + expect(ShowResult.parse({ dispatched: true, foregroundChanged: false, windowId }).windowId).toBe(windowId) + const nativeImage = { mimeType: 'image/png', data: 'AQ==', pixelWidth: 1, pixelHeight: 1, + windowId, bounds: windows[0]!.bounds, coordinateSpace: 'window-pixels' } + expect(NativeScreenshotResult.parse(nativeImage)).toEqual(nativeImage) + expect(ScreenshotResult.parse({ ...nativeImage, coordinateSpace: 'screenshot-pixels' }).windowId).toBe(windowId) +}) + +it.each([0, -1, 1.5, '1', 2 ** 32])('keeps screenshot pixel dimensions numeric and bounded: %j', (dimension) => { + const image = { mimeType: 'image/png', data: 'AQ==', pixelWidth: 1, pixelHeight: 1, + windowId: 'window-main', bounds: { x: 0, y: 0, width: 100, height: 80 }, coordinateSpace: 'window-pixels' } + expect(NativeScreenshotResult.safeParse({ ...image, pixelWidth: dimension }).success).toBe(false) + expect(NativeScreenshotResult.safeParse({ ...image, pixelHeight: dimension }).success).toBe(false) +}) const rejectedRequests: Array<{ reason: string; request: JsonValue }> = [ { reason: 'raw process ID instead of a selected app handle', request: { method: 'typeText', params: { pid: 17, text: 'hello' } } }, @@ -11,7 +34,8 @@ const rejectedRequests: Array<{ reason: string; request: JsonValue }> = [ { reason: 'element click without an observed snapshot', request: { method: 'click', params: { appHandle: 'app', elementId: '0' } } }, { reason: 'numeric element id', request: { method: 'click', params: { appHandle: 'app', snapshotId: 'snapshot', elementId: 0 } } }, { reason: 'coordinate click without a window', request: { method: 'click', params: { appHandle: 'app', x: 1, y: 2 } } }, - { reason: 'mixed element and coordinate click', request: { method: 'click', params: { appHandle: 'app', snapshotId: 'snapshot', elementId: '0', windowId: 23, x: 1, y: 2 } } }, + { reason: 'numeric window id', request: { method: 'screenshot', params: { appHandle: 'app', windowId: 7 } } }, + { reason: 'mixed element and coordinate click', request: { method: 'click', params: { appHandle: 'app', snapshotId: 'snapshot', elementId: '0', windowId: '23', x: 1, y: 2 } } }, { reason: 'non-string pressKey modifier', request: { method: 'pressKey', params: { appHandle: 'app', key: 'a', modifiers: ['command', 7] } } }, { reason: 'sendKeyEvent modifiers', request: { method: 'sendKeyEvent', params: { appHandle: 'app', key: 'a', direction: 'down', modifiers: [] } } }, { reason: 'sendKeyEvent without direction', request: { method: 'sendKeyEvent', params: { appHandle: 'app', key: 'a' } } }, @@ -29,14 +53,14 @@ it('admits arbitrary provider-defined pressKey modifier names', () => { }) it('admits arbitrary key names with an explicit key-event direction', () => { - const request = { method: 'sendKeyEvent', params: { appHandle: 'app', windowId: 23, key: 'Command', direction: 'down' } } + const request = { method: 'sendKeyEvent', params: { appHandle: 'app', windowId: '23', key: 'Command', direction: 'down' } } expect(Request.parse(request)).toEqual(request) }) it.each([ { appHandle: 'app', snapshotId: 'snapshot', elementId: '0' }, - { appHandle: 'app', windowId: 23, x: 1, y: 2 }, - { appHandle: 'app', windowId: 23, x: 1, y: 2, relative: true }, + { appHandle: 'app', windowId: '23', x: 1, y: 2 }, + { appHandle: 'app', windowId: '23', x: 1, y: 2, relative: true }, ])('validates optional per-press hold duration for %j', (params) => { for (const holdMs of [0, 1, 800, 5000, 7000]) { const request = { method: 'click', params: { ...params, holdMs } } @@ -51,17 +75,17 @@ it.each([ '', 'not base64!', 'AQ', 'AQ===', 'AQ==\n', 'A Q==', 'AQ-_', 'AB==', 'AAF=', ])('rejects noncanonical screenshot base64 %j', (data) => { expect(ScreenshotResult.safeParse({ - mimeType: 'image/png', data, pixelWidth: 1, pixelHeight: 1, windowId: 23, + mimeType: 'image/png', data, pixelWidth: 1, pixelHeight: 1, windowId: '23', bounds: { x: 0, y: 0, width: 10, height: 10 }, coordinateSpace: 'screenshot-pixels', }).success).toBe(false) }) it.each([ - { mimeType: 'application/octet-stream' }, { pixelWidth: 0 }, { pixelHeight: -1 }, { windowId: 0 }, + { mimeType: 'application/octet-stream' }, { pixelWidth: 0 }, { pixelHeight: -1 }, { windowId: '0' }, { bounds: { x: 0, y: 0, width: 0, height: 10 } }, { coordinateSpace: 'screen-pixels' }, ])('retains screenshot metadata validation for %j', (invalid) => { expect(ScreenshotResult.safeParse({ - mimeType: 'image/png', data: 'AQ==', pixelWidth: 1, pixelHeight: 1, windowId: 23, + mimeType: 'image/png', data: 'AQ==', pixelWidth: 1, pixelHeight: 1, windowId: '23', bounds: { x: 0, y: 0, width: 10, height: 10 }, coordinateSpace: 'screenshot-pixels', ...invalid, }).success).toBe(false) }) @@ -75,7 +99,7 @@ it('accepts disclosure options without accepting host traversal limits', () => { it.each([ { appHandle: 'app', snapshotId: 'snapshot', elementId: '0' }, - { appHandle: 'app', windowId: 23, x: 1, y: 2 }, + { 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' }]) { @@ -86,7 +110,7 @@ it.each([ it.each([ { appHandle: 'app', elementId: '0' }, { appHandle: 'app', x: 1, y: 2 }, - { appHandle: 'app', snapshotId: 'snapshot', elementId: '0', windowId: 23, x: 1, y: 2 }, + { appHandle: 'app', snapshotId: 'snapshot', elementId: '0', windowId: '23', x: 1, y: 2 }, ])('rejects incomplete or mixed mouse move targets %j', (params) => { expect(Request.safeParse({ method: 'mouseMove', params }).success).toBe(false) }) @@ -161,7 +185,7 @@ it('requires a setValue value and rejects unknown parameters', () => { }) it.each(['click', 'mouseMove', 'scroll', 'drag'])('validates 0–999 integer coordinates for %s', (method) => { - const params = { appHandle: 'app', windowId: 7, relative: true, + const params = { appHandle: 'app', windowId: '7', relative: true, ...method === 'drag' ? { fromX: 0, fromY: 0, toX: 999, toY: 999 } : { x: 0, y: 999 }, ...method === 'scroll' ? { deltaLinesX: 0, deltaLinesY: -1 } : {}, } diff --git a/snapshots/session/cua-native/replay.override.json b/snapshots/session/cua-native/replay.override.json index 42d5c9d7af..f17e791432 100644 --- a/snapshots/session/cua-native/replay.override.json +++ b/snapshots/session/cua-native/replay.override.json @@ -80,7 +80,7 @@ "type": "tool-call", "id": "cua-unauthorized-screenshot", "name": "cua", - "arguments": "{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}" + "arguments": "{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"7\"}}" } }, { @@ -179,7 +179,7 @@ "type": "tool-call", "id": "cua-native-3", "name": "cua", - "arguments": "{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"includeMenus\":true,\"details\":true}}" + "arguments": "{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"includeMenus\":true,\"details\":true}}" } }, { @@ -245,7 +245,7 @@ "type": "tool-call", "id": "cua-native-5", "name": "cua", - "arguments": "{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}" + "arguments": "{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"7\"}}" } }, { @@ -278,7 +278,7 @@ "type": "tool-call", "id": "cua-native-6", "name": "cua", - "arguments": "{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}" + "arguments": "{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"7\"}}" } }, { @@ -344,7 +344,7 @@ "type": "tool-call", "id": "cua-native-8", "name": "cua", - "arguments": "{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}" + "arguments": "{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"8\"}}" } }, { @@ -377,7 +377,7 @@ "type": "tool-call", "id": "cua-native-9", "name": "cua", - "arguments": "{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}" + "arguments": "{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"8\"}}" } }, { @@ -410,7 +410,7 @@ "type": "tool-call", "id": "cua-native-10", "name": "cua", - "arguments": "{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-3\",\"x\":0,\"y\":0}}" + "arguments": "{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"8\",\"snapshotId\":\"fixture-snapshot-3\",\"x\":0,\"y\":0}}" } }, { @@ -443,7 +443,7 @@ "type": "tool-call", "id": "cua-native-11", "name": "cua", - "arguments": "{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}" + "arguments": "{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"8\"}}" } }, { @@ -476,7 +476,7 @@ "type": "tool-call", "id": "cua-native-show", "name": "cua", - "arguments": "{\"method\":\"show\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}" + "arguments": "{\"method\":\"show\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"7\"}}" } }, { @@ -608,7 +608,7 @@ "type": "tool-call", "id": "cua-native-stale-read", "name": "cua", - "arguments": "{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}" + "arguments": "{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"7\"}}" } }, { @@ -674,7 +674,7 @@ "type": "tool-call", "id": "cua-native-other-window", "name": "cua", - "arguments": "{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-4\",\"x\":0,\"y\":0,\"holdMs\":800}}" + "arguments": "{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"8\",\"snapshotId\":\"fixture-snapshot-4\",\"x\":0,\"y\":0,\"holdMs\":800}}" } }, { @@ -707,7 +707,7 @@ "type": "tool-call", "id": "cua-native-fresh-read", "name": "cua", - "arguments": "{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}" + "arguments": "{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"7\"}}" } }, { @@ -773,7 +773,7 @@ "type": "tool-call", "id": "cua-native-verify", "name": "cua", - "arguments": "{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}" + "arguments": "{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"7\"}}" } }, { @@ -806,7 +806,7 @@ "type": "tool-call", "id": "cua-native-geometry-observe", "name": "cua", - "arguments": "{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}" + "arguments": "{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"9\"}}" } }, { @@ -839,7 +839,7 @@ "type": "tool-call", "id": "cua-native-geometry-capture", "name": "cua", - "arguments": "{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}" + "arguments": "{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"9\"}}" } }, { @@ -872,7 +872,7 @@ "type": "tool-call", "id": "cua-native-geometry-click", "name": "cua", - "arguments": "{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"snapshotId\":\"fixture-snapshot-7\",\"x\":20,\"y\":20,\"relative\":true}}" + "arguments": "{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"9\",\"snapshotId\":\"fixture-snapshot-7\",\"x\":20,\"y\":20,\"relative\":true}}" } }, { @@ -905,7 +905,7 @@ "type": "tool-call", "id": "cua-native-geometry-scroll", "name": "cua", - "arguments": "{\"method\":\"scroll\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"x\":20,\"y\":20,\"deltaLinesX\":0,\"deltaLinesY\":-1,\"relative\":true}}" + "arguments": "{\"method\":\"scroll\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"9\",\"x\":20,\"y\":20,\"deltaLinesX\":0,\"deltaLinesY\":-1,\"relative\":true}}" } }, { @@ -938,7 +938,7 @@ "type": "tool-call", "id": "cua-native-geometry-drag", "name": "cua", - "arguments": "{\"method\":\"drag\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"fromX\":20,\"fromY\":20,\"toX\":30,\"toY\":30,\"relative\":true}}" + "arguments": "{\"method\":\"drag\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"9\",\"fromX\":20,\"fromY\":20,\"toX\":30,\"toY\":30,\"relative\":true}}" } }, { @@ -1004,7 +1004,7 @@ "type": "tool-call", "id": "cua-native-geometry-verify", "name": "cua", - "arguments": "{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}" + "arguments": "{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"9\"}}" } }, { @@ -1070,7 +1070,7 @@ "type": "tool-call", "id": "cua-capture-busy", "name": "cua", - "arguments": "{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}" + "arguments": "{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"7\"}}" } }, { @@ -1103,7 +1103,7 @@ "type": "tool-call", "id": "cua-capture-busy-ax", "name": "cua", - "arguments": "{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}" + "arguments": "{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"7\"}}" } }, { @@ -1169,7 +1169,7 @@ "type": "tool-call", "id": "cua-capture-recovered", "name": "cua", - "arguments": "{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}" + "arguments": "{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"7\"}}" } }, { @@ -1235,7 +1235,7 @@ "type": "tool-call", "id": "cua-hover-observe", "name": "cua", - "arguments": "{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}" + "arguments": "{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"7\"}}" } }, { @@ -1268,7 +1268,7 @@ "type": "tool-call", "id": "cua-hover-capture", "name": "cua", - "arguments": "{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}" + "arguments": "{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"7\"}}" } }, { @@ -1301,7 +1301,7 @@ "type": "tool-call", "id": "cua-hover-popup", "name": "cua", - "arguments": "{\"method\":\"mouseMove\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":100,\"y\":200,\"relative\":true}}" + "arguments": "{\"method\":\"mouseMove\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"x\":100,\"y\":200,\"relative\":true}}" } }, { @@ -1334,7 +1334,7 @@ "type": "tool-call", "id": "cua-hover-click", "name": "cua", - "arguments": "{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-10\",\"x\":100,\"y\":200,\"relative\":true}}" + "arguments": "{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"snapshotId\":\"fixture-snapshot-10\",\"x\":100,\"y\":200,\"relative\":true}}" } }, { @@ -1367,7 +1367,7 @@ "type": "tool-call", "id": "cua-hover-exit", "name": "cua", - "arguments": "{\"method\":\"mouseMove\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":0,\"y\":200,\"relative\":true}}" + "arguments": "{\"method\":\"mouseMove\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"x\":0,\"y\":200,\"relative\":true}}" } }, { @@ -1400,7 +1400,7 @@ "type": "tool-call", "id": "cua-hover-verify", "name": "cua", - "arguments": "{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}" + "arguments": "{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"7\"}}" } }, { @@ -1499,7 +1499,7 @@ "type": "tool-call", "id": "cua-paste-inspect", "name": "cua", - "arguments": "{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}" + "arguments": "{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"7\"}}" } }, { @@ -1565,7 +1565,7 @@ "type": "tool-call", "id": "cua-paste-focus", "name": "cua", - "arguments": "{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}" + "arguments": "{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"7\"}}" } }, { @@ -1631,7 +1631,7 @@ "type": "tool-call", "id": "cua-paste-verify", "name": "cua", - "arguments": "{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}" + "arguments": "{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"7\"}}" } }, { @@ -1697,7 +1697,7 @@ "type": "tool-call", "id": "cua-debug-screenshot", "name": "cua", - "arguments": "{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}" + "arguments": "{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"7\"}}" } }, { diff --git a/snapshots/session/cua-native/workspace/native-helper.mjs b/snapshots/session/cua-native/workspace/native-helper.mjs index 494e7d2c1a..bbfcb8e4e5 100755 --- a/snapshots/session/cua-native/workspace/native-helper.mjs +++ b/snapshots/session/cua-native/workspace/native-helper.mjs @@ -38,7 +38,7 @@ function serve() { } const instanceId = randomUUID() const sockets = new Set() - const application = { count: 0, value: '', visualCount: 0, hovering: false, frontPid: 42, frontWindowId: 99 } + const application = { count: 0, value: '', visualCount: 0, hovering: false, frontPid: 42, frontWindowId: '99' } const captureBroker = { pendingCapture: false } let started = false let hadClient = false @@ -111,9 +111,9 @@ function createApplicationState(socket, record, application, captureBroker, conn const scope = connectionId === 1 ? 'fixture' : `fixture-${connectionId}` const app = { appHandle: `${scope}-app`, pid: 9, name: 'Fixture', bundleId: 'test.fixture', running: true } const bounds = { x: 40, y: 60, width: 320, height: 200 } - const window = { windowId: 7, appName: 'Fixture', title: 'CUA fixture', bounds, isOnScreen: true, onCurrentSpace: true } - const axlessWindow = { ...window, windowId: 8, title: 'AXless canvas' } - const transformedWindow = { ...window, windowId: 9, title: 'Transformed window', bounds: { x: 16, y: 512, width: 131, height: 145 } } + const window = { windowId: '7', appName: 'Fixture', title: 'CUA fixture', bounds, isOnScreen: true, onCurrentSpace: true } + const axlessWindow = { ...window, windowId: '8', title: 'AXless canvas' } + const transformedWindow = { ...window, windowId: '9', title: 'Transformed window', bounds: { x: 16, y: 512, width: 131, height: 145 } } const screenshotConfig = new URL('./fixture-screenshot.json', import.meta.url) const customScreenshot = existsSync(screenshotConfig) ? JSON.parse(readFileSync(screenshotConfig, 'utf8')) : undefined const snapshots = new Map() @@ -165,18 +165,18 @@ function createApplicationState(socket, record, application, captureBroker, conn refuse('STALE_SNAPSHOT', 'Accessibility tree changed during observation; read fresh getAccessibilityTree') } generation++ - const axless = params.windowId === 8 + const axless = params.windowId === '8' const snapshotId = `${scope}-snapshot-${generation}` snapshots.set(params.windowId ?? null, { snapshotId, windowId: params.windowId ?? null, axless }) - if (axless) return { appHandle: app.appHandle, windowId: 8, snapshotId, + if (axless) return { appHandle: app.appHandle, windowId: '8', snapshotId, tree: '', elements: [], windows: [axlessWindow], truncated: false } return { appHandle: app.appHandle, 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: [{ elementId: '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 } + windows: [params.windowId === '9' ? transformedWindow : window], truncated: false } } - if (params.windowId === 9 && ['screenshot', 'mouseMove', 'click', 'scroll', 'drag'].includes(method) && params.elementId === undefined) { + if (params.windowId === '9' && ['screenshot', 'mouseMove', 'click', 'scroll', 'drag'].includes(method) && params.elementId === 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') } if (method === 'screenshot' && captureBroker.pendingCapture) { @@ -200,7 +200,7 @@ function createApplicationState(socket, record, application, captureBroker, conn if (params.windowId !== undefined && observed.windowId !== null && observed.windowId !== params.windowId) refuse('STALE_SNAPSHOT', 'Snapshot belongs to another window') if (observed.axless && params.elementId !== undefined) refuse('INVALID_ARGUMENT', 'Element id is absent from the selected snapshot') if (method === 'mouseMove') application.hovering = params.elementId === '0' || (params.x >= 20 && params.x <= 40) - else if (method === 'click' && params.windowId === 8) application.visualCount++ + else if (method === 'click' && params.windowId === '8') application.visualCount++ else if (method === 'click') application.count++ else application.value = params.value record('state', { count: application.count, value: application.value, visualCount: application.visualCount }) @@ -211,7 +211,7 @@ function createApplicationState(socket, record, application, captureBroker, conn if (method === 'pressKey' && params.key === 'F11') captureBroker.pendingCapture = true if (method === 'pressKey' && params.key === 'F10') captureBroker.pendingCapture = false if (method === 'pressKey' && params.key === 'F12') malformedScreenshot = true - if (method === 'pressKey' && params.key === 'F9') { application.frontPid = 42; application.frontWindowId = 99 } + if (method === 'pressKey' && params.key === 'F9') { application.frontPid = 42; application.frontWindowId = '99' } if (method === 'paste') { if (application.frontPid !== app.pid) refuse('PASTE_NOT_CONSUMED', 'Paste command was dispatched, but clipboard data was not requested within the read deadline. Bring the target app to the foreground and focus its text input. Inspect the contents before deciding whether to retry; a delayed paste may still run.') application.value += params.text diff --git a/snapshots/session/cua-ptc/replay.override.json b/snapshots/session/cua-ptc/replay.override.json index 63e4009990..eb54d151bb 100644 --- a/snapshots/session/cua-ptc/replay.override.json +++ b/snapshots/session/cua-ptc/replay.override.json @@ -14,7 +14,7 @@ "type": "tool-call", "id": "cua-ptc-native-result", "name": "run_code", - "arguments": "{\"code\":\"const { Buffer } = await import('node:buffer');\\nconst app = await tools.cua({ method: 'getApp', params: { selector: 'test.fixture' } });\\nconst state = await tools.cua({ method: 'getState', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst shot = await tools.cua({ method: 'screenshot', params: { appHandle: app.appHandle, windowId: 7 } });\\nconst bytes = Buffer.from(shot.data, 'base64');\\nreturn { appHandle: app.appHandle, hasIncrement: state.tree.includes('Increment'), pngBytes: bytes.length, signature: bytes.subarray(0, 8).toString('hex'), imageWidth: shot.attachment.width, imageHeight: shot.attachment.height };\",\"description\":\"Read native CUA values and receive one screenshot\"}" + "arguments": "{\"code\":\"const { Buffer } = await import('node:buffer');\\nconst app = await tools.cua({ method: 'getApp', params: { selector: 'test.fixture' } });\\nconst state = await tools.cua({ method: 'getState', params: { appHandle: app.appHandle, windowId: '7' } });\\nconst shot = await tools.cua({ method: 'screenshot', params: { appHandle: app.appHandle, windowId: '7' } });\\nconst bytes = Buffer.from(shot.data, 'base64');\\nreturn { appHandle: app.appHandle, hasIncrement: state.tree.includes('Increment'), pngBytes: bytes.length, signature: bytes.subarray(0, 8).toString('hex'), imageWidth: shot.attachment.width, imageHeight: shot.attachment.height };\",\"description\":\"Read native CUA values and receive one screenshot\"}" } }, { From e9f96c2aa854df64b962d01342f5480ebfcc8dcb Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Mon, 9 Nov 2026 01:12:37 +0800 Subject: [PATCH 024/184] feat(cua-windows): implement WGC window screenshots --- .../native/entry/DesktopExecutor.cs | 4 +- .../cua-windows/native/entry/WindowCapture.cs | 186 +++++++++++++++++- 2 files changed, 186 insertions(+), 4 deletions(-) diff --git a/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs b/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs index 5332f16fba..31739fa778 100644 --- a/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs +++ b/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs @@ -76,13 +76,13 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA var context = new RequestContext(config, cancellation, mta, sta); context.Check(); var parameters = request.Params; - if (request.Method == "permissionStatus") return DesktopSession.Status(false); + if (request.Method == "permissionStatus") return DesktopSession.Status(WindowCapture.IsSupported); if (request.Method == "applicationIcons") return await sta.Invoke(_ => Applications.Icons(parameters, context), cancellation); if (request.Method == "getCapabilities") { var locked = DesktopSession.Locked(); return new { permissions = new { accessibility = locked == false, - screenRecording = false }, + screenRecording = locked == false && WindowCapture.IsSupported }, sessionLocked = locked }; } if (request.Method is "requestPermission" or "openPermissionSettings") diff --git a/packages/experimental/cua-windows/native/entry/WindowCapture.cs b/packages/experimental/cua-windows/native/entry/WindowCapture.cs index 4a3e4f6e5f..05c5cbdc79 100644 --- a/packages/experimental/cua-windows/native/entry/WindowCapture.cs +++ b/packages/experimental/cua-windows/native/entry/WindowCapture.cs @@ -1,7 +1,189 @@ +using System.Diagnostics; +using System.Globalization; +using System.Runtime.InteropServices; +using DeepSeek.Cua.Protocol; +using global::Windows.Graphics.Capture; +using global::Windows.Graphics.DirectX; +using global::Windows.Graphics.DirectX.Direct3D11; +using global::Windows.Graphics.Imaging; +using global::Windows.Storage.Streams; +using WinRT; + namespace DeepSeek.Cua.Windows; internal sealed class WindowCapture { - internal Task Capture(AppState app, WindowState window, RequestContext context) - => throw new NotImplementedException("Windows screenshots are not implemented."); + internal static bool IsSupported => GraphicsCaptureSession.IsSupported(); + + internal async Task Capture(AppState app, WindowState window, RequestContext context) + { + var geometry = window.Geometry(app, context); + using var bitmap = await CaptureBitmap(window.Handle, context); + if (bitmap.PixelWidth != geometry.Pixels.Width || bitmap.PixelHeight != geometry.Pixels.Height) + throw new NativeFailure("WINDOW_CHANGED", "The captured size does not match the window bounds; capture the window again"); + + using var stream = new InMemoryRandomAccessStream(); + var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream); + context.Check(); + encoder.SetSoftwareBitmap(bitmap); + await encoder.FlushAsync(); + context.Check(); + if (4 * ((stream.Size + 2) / 3) > (ulong)context.Config.MaxResponseBytes) + throw new NativeFailure("NATIVE_RESPONSE_LIMIT", "The screenshot exceeds the configured response byte limit"); + var bytes = new byte[checked((int)stream.Size)]; + using (var reader = new DataReader(stream.GetInputStreamAt(0))) + { + if (await reader.LoadAsync((uint)bytes.Length) != (uint)bytes.Length) + throw new NativeFailure("NATIVE_OPERATION", "The encoded screenshot could not be read completely"); + reader.ReadBytes(bytes); + } + + DesktopSession.RequireInteractive(); + var current = window.Geometry(app, context); + if (current.Pixels.Width != geometry.Pixels.Width || current.Pixels.Height != geometry.Pixels.Height || current.Dpi != geometry.Dpi) + throw new NativeFailure("WINDOW_CHANGED", "The window size or display scale changed during capture; capture the window again"); + window.Observe(current); + return new + { + mimeType = "image/png", data = Convert.ToBase64String(bytes), + pixelWidth = bitmap.PixelWidth, pixelHeight = bitmap.PixelHeight, + windowId = window.Id.ToString(CultureInfo.InvariantCulture), + bounds = current.Bounds, coordinateSpace = "window-pixels", + }; + } + + // The caller owns the CPU bitmap. The frame wait has its own timeout; request cancellation also covers initialization and encoding. + private static async Task CaptureBitmap(nint hwnd, RequestContext context) + { + context.Check(); + if (!IsSupported) + throw new NativeFailure("UNSUPPORTED", "Windows Graphics Capture is not supported on this system"); + + using var device = CreateCaptureDevice(); + var item = CreateItemForWindow(hwnd); + var size = item.Size; + if (size.Width <= 0 || size.Height <= 0) + throw new NativeFailure("WINDOW_CHANGED", "The window has no usable capture size"); + + using var pool = Direct3D11CaptureFramePool.CreateFreeThreaded( + device, DirectXPixelFormat.B8G8R8A8UIntNormalized, 2, size); + using var session = pool.CreateCaptureSession(item); + session.IsCursorCaptureEnabled = false; + context.Check(); + session.StartCapture(); + + var timer = Stopwatch.StartNew(); + while (timer.Elapsed.TotalMilliseconds < context.Config.ScreenshotTimeoutMs) + { + context.Check(); + using var frame = pool.TryGetNextFrame(); + if (frame is not null) + { + var contentSize = frame.ContentSize; + if (contentSize.Width != size.Width || contentSize.Height != size.Height) + throw new NativeFailure("WINDOW_CHANGED", "The window size changed during capture; capture the window again"); + + // Keep the frame alive until GPU readback settles, even when the request is cancelled. + var bitmap = await SoftwareBitmap.CreateCopyFromSurfaceAsync(frame.Surface); + if (context.Cancellation.IsCancellationRequested) + { + bitmap.Dispose(); + context.Check(); + } + return bitmap; + } + await Task.Delay(context.Config.PollIntervalMs, context.Cancellation).ConfigureAwait(false); + } + throw new NativeFailure("SCREENSHOT_TIMEOUT", "No capture frame arrived before the deadline; the window may be minimized, closed, or unavailable for capture"); + } + + private static GraphicsCaptureItem CreateItemForWindow(nint hwnd) + { + var initHr = RoInitialize(RO_INIT_MULTITHREADED); + if (initHr < 0 && initHr != RPC_E_CHANGED_MODE) + Marshal.ThrowExceptionForHR(initHr); + + nint className = 0; + nint itemPointer = 0; + IGraphicsCaptureItemInterop? factory = null; + try + { + className = MarshalString.FromManaged("Windows.Graphics.Capture.GraphicsCaptureItem"); + var interopIid = typeof(IGraphicsCaptureItemInterop).GUID; + Marshal.ThrowExceptionForHR(RoGetActivationFactory(className, in interopIid, out factory)); + var itemIid = new Guid("79C3F95B-31F7-4EC2-A464-632EF5D30760"); + Marshal.ThrowExceptionForHR(factory.CreateForWindow(hwnd, in itemIid, out itemPointer)); + return MarshalInspectable.FromAbi(itemPointer); + } + finally + { + if (itemPointer != 0) Marshal.Release(itemPointer); + if (factory is not null) Marshal.ReleaseComObject(factory); + if (className != 0) MarshalString.DisposeAbi(className); + // S_OK and S_FALSE require a matching call on this thread; RPC_E_CHANGED_MODE does not. + if (initHr >= 0) RoUninitialize(); + } + } + + private static IDirect3DDevice CreateCaptureDevice() + { + nint d3dDevice = 0; + nint immediateContext = 0; + nint dxgiDevice = 0; + nint winrtDevice = 0; + try + { + Marshal.ThrowExceptionForHR(D3D11CreateDevice( + 0, D3D_DRIVER_TYPE_HARDWARE, 0, D3D11_CREATE_DEVICE_BGRA_SUPPORT, + 0, 0, D3D11_SDK_VERSION, out d3dDevice, out _, out immediateContext)); + var dxgiDeviceIid = new Guid("54EC77FA-1377-44E6-8C32-88FD5F44C84C"); + Marshal.ThrowExceptionForHR(Marshal.QueryInterface(d3dDevice, in dxgiDeviceIid, out dxgiDevice)); + Marshal.ThrowExceptionForHR(CreateDirect3D11DeviceFromDXGIDevice(dxgiDevice, out winrtDevice)); + return MarshalInterface.FromAbi(winrtDevice); + } + finally + { + // The projection owns its references; release only the raw references returned by the native APIs. + if (winrtDevice != 0) Marshal.Release(winrtDevice); + if (dxgiDevice != 0) Marshal.Release(dxgiDevice); + if (immediateContext != 0) Marshal.Release(immediateContext); + if (d3dDevice != 0) Marshal.Release(d3dDevice); + } + } + + private const uint RO_INIT_MULTITHREADED = 1; + private const int RPC_E_CHANGED_MODE = unchecked((int)0x80010106); + private const uint D3D_DRIVER_TYPE_HARDWARE = 1; + private const uint D3D11_CREATE_DEVICE_BGRA_SUPPORT = 0x20; + private const uint D3D11_SDK_VERSION = 7; + + [ComImport] + [Guid("3628E81B-3CAC-4C60-B7F4-23CE0E0C3356")] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IGraphicsCaptureItemInterop + { + [PreserveSig] + int CreateForWindow(nint window, in Guid iid, out nint result); + + [PreserveSig] + int CreateForMonitor(nint monitor, in Guid iid, out nint result); + } + + [DllImport("combase.dll", ExactSpelling = true)] + private static extern int RoInitialize(uint initType); + + [DllImport("combase.dll", ExactSpelling = true)] + private static extern void RoUninitialize(); + + [DllImport("combase.dll", ExactSpelling = true)] + private static extern int RoGetActivationFactory(nint activatableClassId, in Guid iid, + [MarshalAs(UnmanagedType.Interface)] out IGraphicsCaptureItemInterop factory); + + [DllImport("d3d11.dll", ExactSpelling = true)] + private static extern int D3D11CreateDevice(nint pAdapter, uint driverType, nint software, uint flags, + nint pFeatureLevels, uint featureLevels, uint sdkVersion, + out nint ppDevice, out uint pFeatureLevel, out nint ppImmediateContext); + + [DllImport("d3d11.dll", ExactSpelling = true)] + private static extern int CreateDirect3D11DeviceFromDXGIDevice(nint dxgiDevice, out nint graphicsDevice); } From 3d5794a545af4ad6e71a6f0bc8f3eede4c9f430b Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Mon, 9 Nov 2026 01:28:33 +0800 Subject: [PATCH 025/184] Add pipeline for CUA packaging --- .../workflows/cua-helper-package-windows.yml | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 .github/workflows/cua-helper-package-windows.yml diff --git a/.github/workflows/cua-helper-package-windows.yml b/.github/workflows/cua-helper-package-windows.yml new file mode 100644 index 0000000000..193f4fcc6c --- /dev/null +++ b/.github/workflows/cua-helper-package-windows.yml @@ -0,0 +1,45 @@ +name: Package CUA helper · Windows · x64 + +on: + workflow_dispatch: + workflow_call: + outputs: + artifact-id: + description: '包含 win-x64 helper ZIP 的产物编号' + value: ${{ jobs.package.outputs.artifact-id }} + run-id: + description: '产物所属的构建运行编号' + value: ${{ jobs.package.outputs.run-id }} + +permissions: + contents: read + +jobs: + package: + runs-on: windows-latest + timeout-minutes: 30 + defaults: + run: + shell: pwsh + outputs: + artifact-id: ${{ steps.upload.outputs.artifact-id }} + run-id: ${{ github.run_id }} + steps: + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-dotnet@v5 + with: + dotnet-version: '10.0.x' + - name: Publish Windows CUA helper + run: dotnet publish packages/experimental/cua-windows/native/entry/CuaWindows.csproj --configuration Release --runtime win-x64 --self-contained false --output dist/cua-helper-win-x64 + - name: Archive publish output + run: Compress-Archive -Path dist/cua-helper-win-x64/* -DestinationPath dist/cua-helper-win-x64.zip + - uses: actions/upload-artifact@v7.0.1 + id: upload + with: + name: cua-helper-win-x64-${{ github.run_id }}-${{ github.run_attempt }} + path: dist/cua-helper-win-x64.zip + if-no-files-found: error + compression-level: 0 + retention-days: 14 From 3d80f2774d8c08859e2770dc2af4bd2f7b3926ad Mon Sep 17 00:00:00 2001 From: Anlai Lu Date: Mon, 9 Nov 2026 10:04:44 +0800 Subject: [PATCH 026/184] feat(cua-windows): add helper packaging metadata --- .../workflows/cua-helper-package-windows.yml | 44 ++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/.github/workflows/cua-helper-package-windows.yml b/.github/workflows/cua-helper-package-windows.yml index 193f4fcc6c..652686f897 100644 --- a/.github/workflows/cua-helper-package-windows.yml +++ b/.github/workflows/cua-helper-package-windows.yml @@ -10,6 +10,9 @@ on: run-id: description: '产物所属的构建运行编号' value: ${{ jobs.package.outputs.run-id }} + build-key: + description: '源码和构建配置的摘要' + value: ${{ jobs.package.outputs.build-key }} permissions: contents: read @@ -24,6 +27,7 @@ jobs: outputs: artifact-id: ${{ steps.upload.outputs.artifact-id }} run-id: ${{ github.run_id }} + build-key: ${{ steps.metadata.outputs.build-key }} steps: - uses: actions/checkout@v7.0.1 with: @@ -32,7 +36,45 @@ jobs: with: dotnet-version: '10.0.x' - name: Publish Windows CUA helper - run: dotnet publish packages/experimental/cua-windows/native/entry/CuaWindows.csproj --configuration Release --runtime win-x64 --self-contained false --output dist/cua-helper-win-x64 + run: >- + dotnet publish packages/experimental/cua-windows/native/entry/CuaWindows.csproj + --configuration Release + --runtime win-x64 + --self-contained true + --output dist/cua-helper-win-x64 + - name: Add helper metadata + id: metadata + run: | + $ErrorActionPreference = 'Stop' + $directory = 'dist/cua-helper-win-x64' + $exe = Join-Path $directory 'dsh-cua-windows.exe' + if (-not (Test-Path $exe -PathType Leaf)) { throw "helper executable is missing: $exe" } + $version = (Get-Content package.json -Raw | ConvertFrom-Json).version + $commit = '${{ github.sha }}' + $sdk = (& dotnet --version).Trim() + $keyBytes = [Text.Encoding]::UTF8.GetBytes("$commit`n$sdk`nwin-x64") + $buildKey = [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData($keyBytes)).ToLowerInvariant() + $files = @{} + Get-ChildItem $directory -Recurse -File | ForEach-Object { + $relative = [IO.Path]::GetRelativePath($directory, $_.FullName).Replace('\', '/') + $files[$relative] = (Get-FileHash $_.FullName -Algorithm SHA256).Hash.ToLowerInvariant() + } + $metadata = @{ + version = $version + commit = $commit + buildKey = $buildKey + architecture = 'x64' + executable = 'dsh-cua-windows.exe' + sha256 = $files['dsh-cua-windows.exe'] + signing = 'unsigned' + files = $files + } + $metadataPath = Join-Path $directory 'cua-helper.json' + $json = $metadata | ConvertTo-Json -Depth 5 + Set-Content -Path $metadataPath -Value $json -Encoding utf8NoBOM + $outputPath = $env:GITHUB_OUTPUT + $outputLine = "build-key=$buildKey" + Add-Content -Path $outputPath -Value $outputLine -Encoding utf8 - name: Archive publish output run: Compress-Archive -Path dist/cua-helper-win-x64/* -DestinationPath dist/cua-helper-win-x64.zip - uses: actions/upload-artifact@v7.0.1 From 4eb64b67b1dc8805a04062bb6e2e8da67af4c594 Mon Sep 17 00:00:00 2001 From: Anlai Lu Date: Mon, 9 Nov 2026 10:47:31 +0800 Subject: [PATCH 027/184] fix(cua-windows): bind and verify helper packaging metadata --- .../workflows/cua-helper-package-windows.yml | 67 ++++++++++++++++--- scripts/cua-helper-windows/workflow.spec.ts | 20 ++++++ 2 files changed, 79 insertions(+), 8 deletions(-) create mode 100644 scripts/cua-helper-windows/workflow.spec.ts diff --git a/.github/workflows/cua-helper-package-windows.yml b/.github/workflows/cua-helper-package-windows.yml index 652686f897..b8c3db4bcb 100644 --- a/.github/workflows/cua-helper-package-windows.yml +++ b/.github/workflows/cua-helper-package-windows.yml @@ -42,27 +42,54 @@ jobs: --runtime win-x64 --self-contained true --output dist/cua-helper-win-x64 + # Standalone helper zip contract: flat root with cua-helper.json, + # dsh-cua-windows.exe, and its runtime files. Installed providers place + # the same payload under native/bin/win-x64. - name: Add helper metadata id: metadata + env: + GITHUB_SHA: ${{ github.sha }} run: | $ErrorActionPreference = 'Stop' $directory = 'dist/cua-helper-win-x64' $exe = Join-Path $directory 'dsh-cua-windows.exe' if (-not (Test-Path $exe -PathType Leaf)) { throw "helper executable is missing: $exe" } $version = (Get-Content package.json -Raw | ConvertFrom-Json).version - $commit = '${{ github.sha }}' + $commit = $env:GITHUB_SHA $sdk = (& dotnet --version).Trim() - $keyBytes = [Text.Encoding]::UTF8.GetBytes("$commit`n$sdk`nwin-x64") + $sourceFiles = @( + & git ls-files -- ` + 'packages/experimental/cua-windows/native' ` + 'packages/experimental/cua-windows/package.json' ` + 'scripts/cua-helper-windows' ` + '.github/workflows/cua-helper-package-windows.yml' ` + 'package.json' 'pnpm-lock.yaml' 'pnpm-workspace.yaml' + ) | Sort-Object + $sourceBytes = [Collections.Generic.List[byte]]::new() + foreach ($file in $sourceFiles) { + $sourceBytes.AddRange([Text.Encoding]::UTF8.GetBytes("$file`0")) + $sourceBytes.AddRange([IO.File]::ReadAllBytes((Join-Path $PWD $file))) + } + $sourceDigest = [Convert]::ToHexString( + [Security.Cryptography.SHA256]::HashData($sourceBytes.ToArray()) + ).ToLowerInvariant() + $keyBytes = [Text.Encoding]::UTF8.GetBytes("$sourceDigest`n$sdk`nwin-x64") $buildKey = [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData($keyBytes)).ToLowerInvariant() - $files = @{} - Get-ChildItem $directory -Recurse -File | ForEach-Object { + $files = [ordered]@{} + Get-ChildItem $directory -Recurse -File | Sort-Object FullName | ForEach-Object { + if ($_.Name -eq 'cua-helper.json') { return } $relative = [IO.Path]::GetRelativePath($directory, $_.FullName).Replace('\', '/') $files[$relative] = (Get-FileHash $_.FullName -Algorithm SHA256).Hash.ToLowerInvariant() } - $metadata = @{ + # sha256 is the executable alias of files[dsh-cua-windows.exe]. + # signing is an enum: unsigned or authenticode. + $metadata = [ordered]@{ + schemaVersion = 1 + platform = 'windows' + sourceDigest = $sourceDigest + buildKey = $buildKey version = $version commit = $commit - buildKey = $buildKey architecture = 'x64' executable = 'dsh-cua-windows.exe' sha256 = $files['dsh-cua-windows.exe'] @@ -71,16 +98,40 @@ jobs: } $metadataPath = Join-Path $directory 'cua-helper.json' $json = $metadata | ConvertTo-Json -Depth 5 - Set-Content -Path $metadataPath -Value $json -Encoding utf8NoBOM + [IO.File]::WriteAllText($metadataPath, "$json`n", [Text.UTF8Encoding]::new($false)) $outputPath = $env:GITHUB_OUTPUT $outputLine = "build-key=$buildKey" Add-Content -Path $outputPath -Value $outputLine -Encoding utf8 - name: Archive publish output run: Compress-Archive -Path dist/cua-helper-win-x64/* -DestinationPath dist/cua-helper-win-x64.zip + - name: Verify helper archive + run: | + $ErrorActionPreference = 'Stop' + $verify = Join-Path $env:RUNNER_TEMP 'cua-helper-verify' + if (Test-Path $verify) { Remove-Item $verify -Recurse -Force } + Expand-Archive -Path 'dist/cua-helper-win-x64.zip' -DestinationPath $verify + $manifestPath = Join-Path $verify 'cua-helper.json' + if (-not (Test-Path $manifestPath -PathType Leaf)) { throw 'helper archive has no cua-helper.json' } + $manifest = Get-Content $manifestPath -Raw | ConvertFrom-Json + if ($manifest.schemaVersion -ne 1 -or $manifest.platform -ne 'windows') { throw 'helper metadata version or platform is invalid' } + if (-not $manifest.sourceDigest -or -not $manifest.buildKey) { throw 'helper metadata lacks sourceDigest or buildKey' } + $exe = Join-Path $verify 'dsh-cua-windows.exe' + if (-not (Test-Path $exe -PathType Leaf)) { throw 'helper archive has no executable' } + $exeHash = (Get-FileHash $exe -Algorithm SHA256).Hash.ToLowerInvariant() + if ($exeHash -ne $manifest.sha256) { throw 'helper executable hash differs from metadata' } + $actual = @(Get-ChildItem $verify -Recurse -File | Where-Object Name -ne 'cua-helper.json') + if ($actual.Count -ne $manifest.files.PSObject.Properties.Count) { throw 'helper archive file count differs from metadata' } + foreach ($property in $manifest.files.PSObject.Properties) { + $file = Join-Path $verify $property.Name + if (-not (Test-Path $file -PathType Leaf)) { throw "helper archive is missing $($property.Name)" } + $hash = (Get-FileHash $file -Algorithm SHA256).Hash.ToLowerInvariant() + if ($hash -ne $property.Value) { throw "helper archive hash differs for $($property.Name)" } + } + Remove-Item $verify -Recurse -Force - uses: actions/upload-artifact@v7.0.1 id: upload with: - name: cua-helper-win-x64-${{ github.run_id }}-${{ github.run_attempt }} + name: cua-helper-${{ github.run_id }}-${{ github.run_attempt }}-${{ steps.metadata.outputs.build-key }} path: dist/cua-helper-win-x64.zip if-no-files-found: error compression-level: 0 diff --git a/scripts/cua-helper-windows/workflow.spec.ts b/scripts/cua-helper-windows/workflow.spec.ts new file mode 100644 index 0000000000..c6724268f1 --- /dev/null +++ b/scripts/cua-helper-windows/workflow.spec.ts @@ -0,0 +1,20 @@ +import { readFileSync } from 'node:fs' +import { describe, expect, it } from 'vitest' + +const workflow = readFileSync(new URL('../../.github/workflows/cua-helper-package-windows.yml', import.meta.url), 'utf8') + +describe('Windows CUA helper workflow', () => { + it('publishes self-contained metadata before archiving', () => { + expect(workflow).toContain('--self-contained true') + expect(workflow.indexOf('Add helper metadata')).toBeLessThan(workflow.indexOf('Archive publish output')) + expect(workflow).toContain('cua-helper.json') + expect(workflow).toContain('schemaVersion') + expect(workflow).toContain('sourceDigest') + expect(workflow).toContain('Verify helper archive') + }) + + it('names artifacts with the build key and avoids pull request triggers', () => { + expect(workflow).toMatch(/name: cua-helper-\$\{\{ github\.run_id \}\}-\$\{\{ github\.run_attempt \}\}-\$\{\{ steps\.metadata\.outputs\.build-key \}\}/u) + expect(workflow).not.toContain('pull_request') + }) +}) From b02529e520756f2fe7f0a81677d210568b12c9c8 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Mon, 9 Nov 2026 11:21:00 +0800 Subject: [PATCH 028/184] feat(forge): write review threads and the pending review through the provider ForgeProvider gains an optional writeReview for replies, resolution, comment edits and deletions, and the viewer's pending review, which review reads now report with the viewer's permissions. The GitHub provider checks the head and the pending review in one query, then sends one GraphQL mutation on stdin and never retries it; a reply at once is refused while a pending review exists, since GitHub adds it to that review. The forge panel Remote changeRequestReviewWrite drops the kept threads after every write, because resolving a thread does not move a pull request's updatedAt. --- .../experimental/client-ui-forge/src/index.ts | 92 ++++++- .../client-ui-forge/src/review-cache.ts | 43 ++- .../tests/review-cache.host.spec.ts | 37 ++- .../client-ui-forge/tests/review.host.spec.ts | 107 +++++++- .../experimental/forge-github/package.json | 1 + .../experimental/forge-github/src/provider.ts | 15 +- .../forge-github/src/review-writes.ts | 209 +++++++++++++++ .../experimental/forge-github/src/threads.ts | 61 ++++- .../forge-github/tests/review-writes.spec.ts | 253 ++++++++++++++++++ .../forge-github/tests/threads.spec.ts | 63 ++++- .../experimental/forge-github/tsconfig.json | 3 + packages/experimental/forge/src/index.ts | 31 ++- packages/experimental/forge/src/types.ts | 68 ++++- .../experimental/forge/tests/registry.spec.ts | 21 +- .../experimental/forge/tests/watch.spec.ts | 32 ++- pnpm-lock.yaml | 3 + 16 files changed, 987 insertions(+), 52 deletions(-) create mode 100644 packages/experimental/forge-github/src/review-writes.ts create mode 100644 packages/experimental/forge-github/tests/review-writes.spec.ts diff --git a/packages/experimental/client-ui-forge/src/index.ts b/packages/experimental/client-ui-forge/src/index.ts index 6a1baaa71d..aa6e09c9d8 100644 --- a/packages/experimental/client-ui-forge/src/index.ts +++ b/packages/experimental/client-ui-forge/src/index.ts @@ -6,8 +6,8 @@ import type { Agent } from '@deepseek-ai/dsh-agent' import type {} from '@deepseek-ai/dsh-api-remote-access' import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge' import type { - ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure, ForgeCommitList, ForgeFailure, ForgeReviewData, ForgeReviewRequest, - ForgeReviewResult, MergeMethod, + ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure, ForgeCommitList, ForgeFailure, ForgeLineComment, ForgeReviewData, + ForgeReviewRequest, ForgeReviewResult, ForgeReviewWrite, ForgeReviewWriteResult, MergeMethod, } from '@deepseek-ai/dsh-experimental-forge' import type { SessionChangeRequest } from '@deepseek-ai/dsh-experimental-forge-session' import type { WorktreeCleanup } from '@deepseek-ai/dsh-experimental-worktree/types' @@ -466,8 +466,8 @@ export class ForgePanelController extends TypertRemoteService { /** * Read the review threads of a change request of a Session at the head commit of its displayed diff. Threads read * at the same head commit and update time are reused from memory, for any Session, until they are - * `reviewRefreshMs` old or `maxCachedReviewBytes` evicts them; a read again after that age shows threads resolved - * since, which do not change a GitHub pull request's update time. + * `reviewRefreshMs` old, `maxCachedReviewBytes` evicts them, or a review write through this panel drops them; a read + * again after that age shows threads resolved elsewhere since, which do not change a GitHub pull request's update time. * @param session - Session the change request is bound to. * @param url - binding URL of the change request. * @param headSha - head commit of the displayed diff. @@ -493,14 +493,16 @@ export class ForgePanelController extends TypertRemoteService { const readAt = Date.now() const kept = this.reviews.get(key, version, readAt) if (kept !== undefined) return kept + const token = this.reviews.token() const review = await this.home.forge.readReview(ref, headSha, signal) if ('code' in review) throw reviewError(review) - this.reviews.set(key, version, review, readAt) + this.reviews.set(key, version, review, readAt, token) return review } /** - * Publish a line comment or completed review for a visible Session binding. + * Publish a line comment or completed review for a visible Session binding. The threads kept for the change request + * are dropped once the host answers, so the next read shows the comments. * @param session - Session retaining the change request. * @param url - visible binding URL. * @param request - reviewed head, ranges, plain text, and explicit review decision. @@ -511,13 +513,43 @@ export class ForgePanelController extends TypertRemoteService { async submitReview(session: Session, url: string, request: ForgeReviewRequest, signal: AbortSignal): Promise { signal.throwIfAborted() const { ref } = this.bound(session, url) - if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(request.headSha)) throw new Error('Invalid review commit') + if (!isCommit(request.headSha)) throw new Error('Invalid review commit') const comments = request.kind === 'comment' ? [request.comment] : request.comments - if (comments.some(comment => comment.path === '' || comment.body.trim() === '' - || !Number.isSafeInteger(comment.startLine) || comment.startLine < 1 - || !Number.isSafeInteger(comment.endLine) || comment.endLine < comment.startLine)) throw new Error('Invalid review comment') + if (!comments.every(validComment)) throw new Error('Invalid review comment') if (request.kind === 'review' && request.event !== 'approve' && request.body.trim() === '' && comments.length === 0) throw new Error('Empty review') - return await this.home.forge.submitReview(ref, request, signal) + try { + return await this.home.forge.submitReview(ref, request, signal) + } finally { + this.reviews.drop(changeRequestKey(ref)) + } + } + + /** + * Write to the review threads or the pending review of a change request of a Session while its head is still the + * head the user saw. The threads kept for the change request are dropped once the host answers, so the next read + * shows the write, which a resolve does not show through a GitHub pull request's update time. + * @param session - Session the change request is bound to. + * @param url - binding URL of the change request. + * @param write - the write and the head commit of the threads the user saw. + * @param signal - request cancellation. + * @returns whether the host took the write; `stale` once the head moved, which polls the change request again, and + * `unknown` when the outcome must be checked on the host before the write is tried again. + * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; an error + * for a write without text, a head that is not a commit object name, or an invalid line range. + */ + @Remote + async changeRequestReviewWrite( + session: Session, url: string, write: ForgeReviewWrite, signal: AbortSignal, + ): Promise { + signal.throwIfAborted() + const { ref } = this.bound(session, url) + if (!isCommit(write.headSha)) throw new Error('Invalid review commit') + if (!validWrite(write)) throw new Error('Invalid review write') + try { + return await this.home.forge.writeReview(ref, write, signal) + } finally { + this.reviews.drop(changeRequestKey(ref)) + } } /** @@ -851,6 +883,44 @@ export class ForgePanelController extends TypertRemoteService { } } +/** + * Whether a value names a full commit object name. + * @param value - the value from the browser. + * @returns whether it is 40 or 64 hexadecimal digits. + */ +function isCommit(value: string): boolean { + return /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(value) +} + +/** + * Whether a line comment from the browser names a path, consecutive positive lines, and text. + * @param comment - the comment. + * @returns whether a provider may write it. + */ +function validComment(comment: ForgeLineComment): boolean { + return comment.path !== '' && comment.body.trim() !== '' && Number.isSafeInteger(comment.startLine) && comment.startLine >= 1 + && Number.isSafeInteger(comment.endLine) && comment.endLine >= comment.startLine +} + +/** + * Whether a review write from the browser names its target and carries text where the write needs it. + * @param write - the write. + * @returns whether a provider may perform it. + */ +function validWrite(write: ForgeReviewWrite): boolean { + switch (write.kind) { + case 'reply': return write.thread !== '' && write.body.trim() !== '' + case 'resolve': return write.thread !== '' + case 'edit-comment': return write.comment !== '' && write.body.trim() !== '' + case 'delete-comment': return write.comment !== '' + case 'add-pending': return validComment(write.comment) + case 'submit-pending': return write.review !== '' && (write.event !== 'request-changes' || write.body.trim() !== '') + case 'discard-pending': return write.review !== '' + /* v8 ignore next -- closed ForgeReviewWrite kind union exhaustiveness guard */ + default: return assertNever(write, 'ForgeReviewWrite.kind') + } +} + /** * Report why the code host did not provide a diff or file. * @param failure - the provider's failure. diff --git a/packages/experimental/client-ui-forge/src/review-cache.ts b/packages/experimental/client-ui-forge/src/review-cache.ts index 6a8d9f0d1e..fa8c54f53a 100644 --- a/packages/experimental/client-ui-forge/src/review-cache.ts +++ b/packages/experimental/client-ui-forge/src/review-cache.ts @@ -1,6 +1,6 @@ /** * Review threads of change requests kept in memory, so the changes view reads them from the code host again only - * after the change request's head or update time changes or the kept threads reach their age limit. + * after the change request's head or update time changes, the kept threads reach their age limit, or a review write drops them. */ import { Buffer } from 'node:buffer' @@ -18,11 +18,14 @@ interface Entry { /** * One read of review threads per change request, bounded by age and by the total UTF-8 size of the kept reads as - * JSON; the least recently read change request leaves first. + * JSON; the least recently read change request leaves first. A read that started before a drop of any change request + * is not kept, so threads read before a write never replace the drop. */ export class ReviewCache { private readonly entries = new Map() private bytes = 0 + /** Number of drops so far. */ + private drops = 0 /** * @param maxBytes - most UTF-8 bytes kept together; a larger read is not kept. @@ -46,20 +49,26 @@ export class ReviewCache { return entry.review } + /** + * Name the cache's state when a read starts, for {@link ReviewCache.set}. + * @returns the token of the read. + */ + token(): number { + return this.drops + } + /** * Keep a read in place of the change request's earlier one, then drop the least recently read change requests - * until the rest fit within `maxBytes`. + * until the rest fit within `maxBytes`. A read whose token a drop outdated is not kept. * @param key - the change request. * @param version - head commit and update time the threads were read at. * @param review - the threads. * @param readAt - epoch milliseconds when the read started. + * @param token - what {@link ReviewCache.token} returned when the read started. */ - set(key: ChangeRequestKey, version: string, review: ForgeReviewData, readAt: number): void { - const previous = this.entries.get(key) - if (previous !== undefined) { - this.entries.delete(key) - this.bytes -= previous.bytes - } + set(key: ChangeRequestKey, version: string, review: ForgeReviewData, readAt: number, token: number): void { + if (token !== this.drops) return + this.forget(key) const bytes = Buffer.byteLength(JSON.stringify(review)) if (bytes > this.maxBytes) return this.entries.set(key, { version, review, readAt, bytes }) @@ -70,4 +79,20 @@ export class ReviewCache { this.bytes -= entry.bytes } } + + /** + * Forget the threads kept for a change request, and every read in flight, after a write changed them. + * @param key - the change request. + */ + drop(key: ChangeRequestKey): void { + this.drops += 1 + this.forget(key) + } + + private forget(key: ChangeRequestKey): void { + const previous = this.entries.get(key) + if (previous === undefined) return + this.entries.delete(key) + this.bytes -= previous.bytes + } } diff --git a/packages/experimental/client-ui-forge/tests/review-cache.host.spec.ts b/packages/experimental/client-ui-forge/tests/review-cache.host.spec.ts index de498b8bbf..119f69dffd 100644 --- a/packages/experimental/client-ui-forge/tests/review-cache.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/review-cache.host.spec.ts @@ -8,7 +8,7 @@ const b = 'fake:b#2' as ChangeRequestKey const c = 'fake:c#3' as ChangeRequestKey function review(viewer: string): ForgeReviewData { - return { headSha: 'a'.repeat(40), viewer, threads: [], truncated: false } + return { headSha: 'a'.repeat(40), viewer, threads: [], truncated: false, pendingReview: null, viewerCanReview: false } } const size = Buffer.byteLength(JSON.stringify(review('x'))) @@ -16,7 +16,7 @@ const size = Buffer.byteLength(JSON.stringify(review('x'))) describe('ReviewCache', () => { it('returns threads kept at the same version until they reach the age limit', () => { const cache = new ReviewCache(size * 4, 100) - cache.set(a, 'v1', review('x'), 1_000) + cache.set(a, 'v1', review('x'), 1_000, cache.token()) expect(cache.get(a, 'v1', 1_099)).toEqual(review('x')) expect(cache.get(a, 'v2', 1_050)).toBeUndefined() @@ -26,26 +26,45 @@ describe('ReviewCache', () => { it('replaces a change request\'s earlier read and drops the least recently read reads past the byte limit', () => { const cache = new ReviewCache(size * 2, 100) - cache.set(a, 'v1', review('x'), 0) - cache.set(a, 'v2', review('y'), 0) - cache.set(b, 'v1', review('z'), 0) + cache.set(a, 'v1', review('x'), 0, cache.token()) + cache.set(a, 'v2', review('y'), 0, cache.token()) + cache.set(b, 'v1', review('z'), 0, cache.token()) expect(cache.get(a, 'v1', 0)).toBeUndefined() expect(cache.get(a, 'v2', 0)).toEqual(review('y')) - cache.set(c, 'v1', review('w'), 0) + cache.set(c, 'v1', review('w'), 0, cache.token()) expect(cache.get(b, 'v1', 0)).toBeUndefined() expect(cache.get(a, 'v2', 0)).toEqual(review('y')) expect(cache.get(c, 'v1', 0)).toEqual(review('w')) }) + it('forgets a dropped change request and keeps no read that started before any drop', () => { + const cache = new ReviewCache(size * 4, 100) + const early = cache.token() + cache.set(a, 'v1', review('x'), 0, early) + cache.set(b, 'v1', review('y'), 0, early) + cache.drop(a) + cache.drop(c) + + expect(cache.get(a, 'v1', 0)).toBeUndefined() + expect(cache.get(b, 'v1', 0)).toEqual(review('y')) + cache.set(a, 'v1', review('z'), 0, early) + expect(cache.get(a, 'v1', 0)).toBeUndefined() + cache.set(a, 'v1', review('z'), 0, cache.token()) + expect(cache.get(a, 'v1', 0)).toEqual(review('z')) + cache.set(a, 'v2', review('much longer than the others'), 0, cache.token()) + cache.set(c, 'v1', review('w'), 0, cache.token()) + expect(cache.get(c, 'v1', 0)).toEqual(review('w')) + }) + it('keeps no read larger than the byte limit and forgets the read it replaced', () => { const cache = new ReviewCache(size, 100) - cache.set(a, 'v1', review('x'), 0) - cache.set(a, 'v2', review('longer'), 0) + cache.set(a, 'v1', review('x'), 0, cache.token()) + cache.set(a, 'v2', review('longer'), 0, cache.token()) expect(cache.get(a, 'v1', 0)).toBeUndefined() expect(cache.get(a, 'v2', 0)).toBeUndefined() - cache.set(b, 'v1', review('x'), 0) + cache.set(b, 'v1', review('x'), 0, cache.token()) expect(cache.get(b, 'v1', 0)).toEqual(review('x')) }) }) diff --git a/packages/experimental/client-ui-forge/tests/review.host.spec.ts b/packages/experimental/client-ui-forge/tests/review.host.spec.ts index 6869d3acb6..bf34f81384 100644 --- a/packages/experimental/client-ui-forge/tests/review.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/review.host.spec.ts @@ -1,5 +1,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import type { ChangeRequestRef, ForgeFailure, ForgeReviewData, ForgeThreadId } from '@deepseek-ai/dsh-experimental-forge' +import type { + ChangeRequestRef, ForgeCommentId, ForgeFailure, ForgeReviewData, ForgeReviewId, ForgeReviewWrite, ForgeReviewWriteResult, ForgeThreadId, +} from '@deepseek-ai/dsh-experimental-forge' import { SessionId } from '@deepseek-ai/dsh-session' import ForgePanelController from '../src/index.ts' import type { ForgePanelState } from '../src/index.ts' @@ -29,10 +31,11 @@ async function opened(config: Parameters[1] = {}): Promise<{ opene function review(headSha: string, path = 'src/a.ts'): ForgeReviewData { return { - headSha, viewer: 'octo', truncated: false, + headSha, viewer: 'octo', truncated: false, pendingReview: null, viewerCanReview: true, threads: [{ id: 'thread-1' as ForgeThreadId, path, side: 'R', subject: 'line', resolved: false, diffHunk: '@@ -1 +1 @@\n-old\n+new', current: { commit: headSha, startLine: 1, endLine: 1 }, original: { commit: headSha, startLine: 1, endLine: 1 }, comments: [], + viewerCanReply: true, viewerCanResolve: true, }], } } @@ -124,6 +127,106 @@ describe('forgePanel change request reviews', () => { expect(readReview).toHaveBeenCalledTimes(codes.length) }) + it('writes through the provider, then drops the kept threads so the next read goes to the host', async () => { + const { opened: panel, follower } = await opened() + const readReview = vi.fn(async (_ref: ChangeRequestRef, headSha: string): Promise => review(headSha)) + const writeReview = vi.fn(async (): Promise => ({ ok: true })) + Object.assign(panel.provider, { readReview, writeReview }) + shellTurn(panel.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }]) + await follower.until(state => polledAt(state, pullUrl(7))) + const write: ForgeReviewWrite = { kind: 'resolve', headSha: HEAD, thread: 'thread-1' as ForgeThreadId, resolved: true } + + await panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, signal) + await expect(panel.ctx.forgePanel.changeRequestReviewWrite(panel.session, pullUrl(7), write, signal)).resolves.toEqual({ ok: true }) + expect(writeReview).toHaveBeenCalledWith(expect.objectContaining({ number: 7 }), write, expect.any(AbortSignal)) + await panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, signal) + expect(readReview).toHaveBeenCalledTimes(2) + + writeReview.mockRejectedValueOnce(new Error('gh crashed')) + await expect(panel.ctx.forgePanel.changeRequestReviewWrite(panel.session, pullUrl(7), write, signal)).rejects.toThrow('gh crashed') + await panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, signal) + expect(readReview).toHaveBeenCalledTimes(3) + }) + + it('keeps no threads read before a write that settled during the read', async () => { + const { opened: panel, follower } = await opened() + const reading = Promise.withResolvers() + const readReview = vi.fn(async (_ref: ChangeRequestRef, headSha: string): Promise => review(headSha)) + readReview.mockReturnValueOnce(reading.promise) + Object.assign(panel.provider, { readReview, writeReview: async (): Promise => ({ ok: true }) }) + shellTurn(panel.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }]) + await follower.until(state => polledAt(state, pullUrl(7))) + + const first = panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, signal) + await vi.waitFor(() => { expect(readReview).toHaveBeenCalledTimes(1) }) + await panel.ctx.forgePanel.changeRequestReviewWrite(panel.session, pullUrl(7), + { kind: 'delete-comment', headSha: HEAD, comment: 'comment-1' as ForgeCommentId }, signal) + reading.resolve(review(HEAD, 'src/before.ts')) + await expect(first).resolves.toMatchObject({ threads: [{ path: 'src/before.ts' }] }) + await expect(panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, signal)) + .resolves.toMatchObject({ threads: [{ path: 'src/a.ts' }] }) + expect(readReview).toHaveBeenCalledTimes(2) + }) + + it('reports a provider without review writes as unsupported and refuses an unbound change request and invalid writes', async () => { + const { opened: panel, follower } = await opened() + shellTurn(panel.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }]) + await follower.until(state => polledAt(state, pullUrl(7))) + const write = (url: string, value: ForgeReviewWrite): Promise => + panel.ctx.forgePanel.changeRequestReviewWrite(panel.session, url, value, signal) + const thread = 'thread-1' as ForgeThreadId + const comment = 'comment-1' as ForgeCommentId + const reviewId = 'review-1' as ForgeReviewId + const line = { path: 'src/a.ts', side: 'R' as const, startLine: 2, endLine: 3, body: 'Check' } + + await expect(write(pullUrl(7), { kind: 'resolve', headSha: HEAD, thread, resolved: false })) + .resolves.toEqual({ ok: false, code: 'unsupported', message: 'This provider does not support review writes' }) + await expect(write(pullUrl(9), { kind: 'resolve', headSha: HEAD, thread, resolved: false })).rejects.toMatchObject({ code: 'forgePanel/not-bound' }) + await expect(write(pullUrl(7), { kind: 'resolve', headSha: 'main', thread, resolved: false })).rejects.toThrow('Invalid review commit') + const invalid: ForgeReviewWrite[] = [ + { kind: 'reply', headSha: HEAD, thread, body: ' ', pending: false }, + { kind: 'reply', headSha: HEAD, thread: '' as ForgeThreadId, body: 'Done', pending: false }, + { kind: 'resolve', headSha: HEAD, thread: '' as ForgeThreadId, resolved: true }, + { kind: 'edit-comment', headSha: HEAD, comment, body: '' }, + { kind: 'edit-comment', headSha: HEAD, comment: '' as ForgeCommentId, body: 'Text' }, + { kind: 'delete-comment', headSha: HEAD, comment: '' as ForgeCommentId }, + { kind: 'add-pending', headSha: HEAD, comment: { ...line, path: '' } }, + { kind: 'add-pending', headSha: HEAD, comment: { ...line, body: '\n' } }, + { kind: 'add-pending', headSha: HEAD, comment: { ...line, startLine: 0 } }, + { kind: 'add-pending', headSha: HEAD, comment: { ...line, startLine: 1.5 } }, + { kind: 'add-pending', headSha: HEAD, comment: { ...line, endLine: 1 } }, + { kind: 'add-pending', headSha: HEAD, comment: { ...line, endLine: Number.POSITIVE_INFINITY } }, + { kind: 'submit-pending', headSha: HEAD, review: '' as ForgeReviewId, event: 'comment', body: '' }, + { kind: 'submit-pending', headSha: HEAD, review: reviewId, event: 'request-changes', body: ' ' }, + { kind: 'discard-pending', headSha: HEAD, review: '' as ForgeReviewId }, + ] + for (const value of invalid) await expect(write(pullUrl(7), value)).rejects.toThrow('Invalid review write') + const valid: ForgeReviewWrite[] = [ + { kind: 'reply', headSha: HEAD, thread, body: 'Done', pending: true }, + { kind: 'edit-comment', headSha: HEAD, comment, body: 'Text' }, + { kind: 'delete-comment', headSha: HEAD, comment }, + { kind: 'add-pending', headSha: HEAD, comment: line }, + { kind: 'submit-pending', headSha: HEAD, review: reviewId, event: 'approve', body: '' }, + { kind: 'submit-pending', headSha: HEAD, review: reviewId, event: 'request-changes', body: 'Fix it' }, + { kind: 'discard-pending', headSha: HEAD, review: reviewId }, + ] + for (const value of valid) await expect(write(pullUrl(7), value)).resolves.toMatchObject({ ok: false, code: 'unsupported' }) + }) + + it('drops the kept threads after publishing a comment so the next read shows it', async () => { + const { opened: panel, follower } = await opened() + const readReview = vi.fn(async (_ref: ChangeRequestRef, headSha: string): Promise => review(headSha)) + Object.assign(panel.provider, { readReview, submitReview: async () => ({ ok: true as const, url: `${pullUrl(7)}#discussion_r1` }) }) + shellTurn(panel.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }]) + await follower.until(state => polledAt(state, pullUrl(7))) + + await panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, signal) + await panel.ctx.forgePanel.submitReview(panel.session, pullUrl(7), + { kind: 'comment', headSha: HEAD, comment: { path: 'src/a.ts', side: 'R', startLine: 1, endLine: 1, body: 'Nit' } }, signal) + await panel.ctx.forgePanel.changeRequestReview(panel.session, pullUrl(7), HEAD, signal) + expect(readReview).toHaveBeenCalledTimes(2) + }) + it.each([ [{ reviewRefreshMs: 0 }, 'forge-panel: reviewRefreshMs must be a positive integer no greater than 2147483647'], [{ reviewRefreshMs: 2_147_483_648 }, 'forge-panel: reviewRefreshMs must be a positive integer no greater than 2147483647'], diff --git a/packages/experimental/forge-github/package.json b/packages/experimental/forge-github/package.json index d0270615b4..9d9fcc6391 100644 --- a/packages/experimental/forge-github/package.json +++ b/packages/experimental/forge-github/package.json @@ -34,6 +34,7 @@ "dependencies": { "@deepseek-ai/schemastery": "workspace:~", "@deepseek-ai/dsh-timeout": "workspace:*", + "@deepseek-ai/dsh-util-values": "workspace:*", "execa": "^10.0.1", "zod": "4.6.6" }, diff --git a/packages/experimental/forge-github/src/provider.ts b/packages/experimental/forge-github/src/provider.ts index cf6905149e..806ef46d7b 100644 --- a/packages/experimental/forge-github/src/provider.ts +++ b/packages/experimental/forge-github/src/provider.ts @@ -3,7 +3,8 @@ import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge' import type { ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure, ForgeCommitList, ForgeFailure, ForgeProvider, - ForgeReadiness, ForgeRepository, ForgeReviewData, ForgeReviewRequest, ForgeReviewResult, MergeRequest, + ForgeReadiness, ForgeRepository, ForgeReviewData, ForgeReviewRequest, ForgeReviewResult, ForgeReviewWrite, ForgeReviewWriteResult, + MergeRequest, } from '@deepseek-ai/dsh-experimental-forge' import { listCommits } from './commits.ts' import type { GraphqlReader } from './commits.ts' @@ -17,6 +18,7 @@ import { import type { PageResult, SnapshotPages } from './graphql.ts' import { checkedRepository, isCommit, parsePullRequestUrl, parseRemoteUrl } from './urls.ts' import { submitGitHubReview } from './review.ts' +import { writeGitHubReview } from './review-writes.ts' import { readReviewThreads } from './threads.ts' const AUTHENTICATION = /gh auth login|authentication|bad credentials|HTTP 401/i @@ -65,6 +67,17 @@ export class GitHubProvider implements ForgeProvider { return await readReviewThreads(this.graphql, ref, headSha, this.limits, signal) } + /** + * Write to the review threads or the pending review of a pull request through GraphQL mutations after a check of its head. + * @see writeGitHubReview + */ + async writeReview(ref: ChangeRequestRef, write: ForgeReviewWrite, signal: AbortSignal): Promise { + const failure = this.hostFailure(ref.repository.host) + if (failure !== undefined) return { ok: false, code: 'failed', message: failure.message } + if (!isCommit(write.headSha)) throw new Error(`forge-github: invalid head commit ${JSON.stringify(write.headSha)}`) + return await writeGitHubReview(this.graphql, this.gh, ref, write, signal) + } + /** * @param gh - runner that executes `gh` on the host. * @param hosts - host names this provider serves, such as `github.com` and Enterprise hosts. diff --git a/packages/experimental/forge-github/src/review-writes.ts b/packages/experimental/forge-github/src/review-writes.ts new file mode 100644 index 0000000000..d2c6835512 --- /dev/null +++ b/packages/experimental/forge-github/src/review-writes.ts @@ -0,0 +1,209 @@ +/** GitHub writes to review threads and the pending review through GraphQL mutations, each after a check of the head. */ + +import type { + ChangeRequestRef, ForgeLineComment, ForgeReviewId, ForgeReviewWrite, ForgeReviewWriteResult, +} from '@deepseek-ai/dsh-experimental-forge' +import { assertNever } from '@deepseek-ai/dsh-util-values' +import { z } from 'zod' +import type { GraphqlReader } from './commits.ts' +import { GhUnavailableError, type GhOutput, type GhRunner } from './gh.ts' +import { checkedRepository } from './urls.ts' + +/** The pull request, its head, and the signed-in user's pending review; variables `owner` and `name` are strings, `number` an integer. */ +export const WRITE_CHECK_QUERY = `query($owner: String!, $name: String!, $number: Int!) { + repository(owner: $owner, name: $name) { + pullRequest(number: $number) { id headRefOid reviews(states: PENDING, first: 1) { nodes { id viewerDidAuthor } } } + } +}` + +/** Start a pending review at a commit, with the line threads of `threads`. */ +export const ADD_REVIEW_MUTATION = `mutation($pull: ID!, $commit: GitObjectID!, $threads: [DraftPullRequestReviewThread]) { + addPullRequestReview(input: { pullRequestId: $pull, commitOID: $commit, threads: $threads }) { pullRequestReview { id } } +}` + +/** Add one line thread to a pending review. */ +export const ADD_THREAD_MUTATION = `mutation($review: ID!, $path: String!, $body: String!, $line: Int!, $side: DiffSide!, $startLine: Int, $startSide: DiffSide) { + addPullRequestReviewThread(input: { + pullRequestReviewId: $review, path: $path, body: $body, line: $line, side: $side, startLine: $startLine, startSide: $startSide + }) { thread { id } } +}` + +/** Reply to a thread, inside the pending review `review` when it is set. */ +export const REPLY_MUTATION = `mutation($thread: ID!, $body: String!, $review: ID) { + addPullRequestReviewThreadReply(input: { pullRequestReviewThreadId: $thread, body: $body, pullRequestReviewId: $review }) { comment { id } } +}` + +/** Mark a thread resolved. */ +export const RESOLVE_MUTATION = 'mutation($thread: ID!) { resolveReviewThread(input: { threadId: $thread }) { thread { id } } }' + +/** Mark a thread unresolved. */ +export const UNRESOLVE_MUTATION = 'mutation($thread: ID!) { unresolveReviewThread(input: { threadId: $thread }) { thread { id } } }' + +/** Replace the text of a review comment. */ +export const EDIT_COMMENT_MUTATION = `mutation($comment: ID!, $body: String!) { + updatePullRequestReviewComment(input: { pullRequestReviewCommentId: $comment, body: $body }) { pullRequestReviewComment { id } } +}` + +/** Delete a review comment. */ +export const DELETE_COMMENT_MUTATION = 'mutation($comment: ID!) { deletePullRequestReviewComment(input: { id: $comment }) { clientMutationId } }' + +/** Submit a pending review with a decision and summary. */ +export const SUBMIT_REVIEW_MUTATION = `mutation($review: ID!, $event: PullRequestReviewEvent!, $body: String) { + submitPullRequestReview(input: { pullRequestReviewId: $review, event: $event, body: $body }) { pullRequestReview { id } } +}` + +/** Delete a pending review with its comments. */ +export const DELETE_REVIEW_MUTATION = 'mutation($review: ID!) { deletePullRequestReview(input: { pullRequestReviewId: $review }) { pullRequestReview { id } } }' + +const EVENTS = { comment: 'COMMENT', approve: 'APPROVE', 'request-changes': 'REQUEST_CHANGES' } as const + +/** HTTP statuses that mean GitHub refused the request, so it changed nothing. */ +const REFUSED = /\(HTTP (?:400|401|403|404|409|422)\)/ + +const checkSchema = z.object({ data: z.object({ repository: z.object({ pullRequest: z.object({ + id: z.string(), + headRefOid: z.string(), + reviews: z.object({ nodes: z.array(z.object({ id: z.string(), viewerDidAuthor: z.boolean() })) }), +}) }) }) }) + +const graphqlErrors = z.object({ errors: z.array(z.object({ message: z.string() })).min(1) }) + +/** One mutation and the payload field that holds its result. */ +interface Mutation { + readonly query: string + readonly field: string + readonly variables: Readonly> +} + +/** A mutation's result: the payload on success, else the write's outcome. */ +type Sent = { readonly ok: true; readonly payload: unknown } | Extract + +const stringId = z.object({ id: z.string() }) + +/** + * Write to the review threads or the pending review of a pull request. One read first checks that the head is still + * `write.headSha` and finds the signed-in user's pending review; a moved head returns `stale` without writing. A pending + * reply or comment without a pending review starts one at `write.headSha`, so it takes two mutations. A reply at once is + * refused with `failed` while the user has a pending review, since GitHub would add it to that review. Mutations send + * their variables as JSON on stdin, and none is retried: a refusal GitHub reports returns `failed`, and an answer that + * does not show whether GitHub applied a mutation returns `unknown`. + * @param read - runs the check as one GraphQL request. + * @param gh - bounded, cancellable GitHub CLI runner for the mutations. + * @param ref - pull request, with an owner and name already checked for inlining. + * @param write - the write and the head commit the user saw. + * @param signal - cancellation of the check and the mutations. + * @returns whether GitHub took the write. + * @throws with `signal.reason` when the signal aborts before a mutation is sent. + */ +export async function writeGitHubReview( + read: GraphqlReader, gh: GhRunner, ref: ChangeRequestRef, write: ForgeReviewWrite, signal: AbortSignal, +): Promise { + const { host, owner, name } = checkedRepository(ref) + const checked = await read(['api', 'graphql', '--hostname', host, + '-f', `query=${WRITE_CHECK_QUERY}`, '-f', `owner=${owner}`, '-f', `name=${name}`, '-F', `number=${ref.number}`], signal) + if (!checked.ok) return { ok: false, code: 'failed', message: checked.failure.message } + const parsed = checkSchema.safeParse(checked.body) + if (!parsed.success) return { ok: false, code: 'failed', message: 'unexpected GitHub response to the pull request check' } + const pull = parsed.data.data.repository.pullRequest + if (pull.headRefOid.toLowerCase() !== write.headSha.toLowerCase()) { + return { ok: false, code: 'stale', message: `the pull request head moved from ${write.headSha} to ${pull.headRefOid}` } + } + const pending = pull.reviews.nodes.find(review => review.viewerDidAuthor)?.id ?? null + signal.throwIfAborted() + const send = async (mutation: Mutation): Promise => await sendMutation(gh, host, mutation, signal) + const done = (sent: Sent): ForgeReviewWriteResult => sent.ok ? { ok: true } : sent + /** Find the pending review, starting one at the head without threads when the user has none. */ + const pendingReview = async (): Promise<{ readonly ok: true; readonly id: string } | Extract> => { + if (pending !== null) return { ok: true, id: pending } + const started = await send({ query: ADD_REVIEW_MUTATION, field: 'addPullRequestReview', + variables: { pull: pull.id, commit: write.headSha, threads: null } }) + if (!started.ok) return started + const review = z.object({ pullRequestReview: stringId }).safeParse(started.payload) + return review.success ? { ok: true, id: review.data.pullRequestReview.id } + : { ok: false, code: 'unknown', message: 'unexpected GitHub response to starting a pending review' } + } + switch (write.kind) { + case 'reply': { + // GitHub adds every reply of a user with a pending review to that review, even one sent without its id. + if (!write.pending && pending !== null) { + return { ok: false, code: 'failed', message: 'GitHub adds a reply to the pending review while one exists; submit or discard it first' } + } + const review = write.pending ? await pendingReview() : { ok: true as const, id: null } + if (!review.ok) return review + return done(await send({ query: REPLY_MUTATION, field: 'addPullRequestReviewThreadReply', + variables: { thread: write.thread, body: write.body, review: review.id } })) + } + case 'resolve': + return done(await send(write.resolved + ? { query: RESOLVE_MUTATION, field: 'resolveReviewThread', variables: { thread: write.thread } } + : { query: UNRESOLVE_MUTATION, field: 'unresolveReviewThread', variables: { thread: write.thread } })) + case 'edit-comment': + return done(await send({ query: EDIT_COMMENT_MUTATION, field: 'updatePullRequestReviewComment', + variables: { comment: write.comment, body: write.body } })) + case 'delete-comment': + return done(await send({ query: DELETE_COMMENT_MUTATION, field: 'deletePullRequestReviewComment', variables: { comment: write.comment } })) + case 'add-pending': + return done(await send(pending === null + ? { query: ADD_REVIEW_MUTATION, field: 'addPullRequestReview', + variables: { pull: pull.id, commit: write.headSha, threads: [draftThread(write.comment)] } } + : { query: ADD_THREAD_MUTATION, field: 'addPullRequestReviewThread', variables: { review: pending, ...draftThread(write.comment) } })) + case 'submit-pending': + if (pending !== write.review) return missingReview(write.review) + return done(await send({ query: SUBMIT_REVIEW_MUTATION, field: 'submitPullRequestReview', + variables: { review: write.review, event: EVENTS[write.event], body: write.body } })) + case 'discard-pending': + if (pending !== write.review) return missingReview(write.review) + return done(await send({ query: DELETE_REVIEW_MUTATION, field: 'deletePullRequestReview', variables: { review: write.review } })) + /* v8 ignore next -- closed ForgeReviewWrite kind union exhaustiveness guard */ + default: return assertNever(write, 'ForgeReviewWrite.kind') + } +} + +/** The fields of a line thread in a pending review, for one side of the diff. */ +function draftThread(comment: ForgeLineComment): Readonly> { + const side = comment.side === 'L' ? 'LEFT' : 'RIGHT' + return { path: comment.path, body: comment.body, line: comment.endLine, side, + ...comment.startLine === comment.endLine ? { startLine: null, startSide: null } : { startLine: comment.startLine, startSide: side } } +} + +function missingReview(review: ForgeReviewId): ForgeReviewWriteResult { + return { ok: false, code: 'failed', message: `the pending review ${review} is no longer the signed-in user's pending review` } +} + +/** + * Send one mutation with its query and variables as JSON on stdin. + * @returns the payload of `mutation.field`; `failed` when GitHub reports a refusal or `gh` cannot start, else `unknown`. + */ +async function sendMutation(gh: GhRunner, host: string, mutation: Mutation, signal: AbortSignal): Promise { + let output: GhOutput + try { + output = await gh(['api', 'graphql', '--hostname', host, '--input', '-'], signal, + JSON.stringify({ query: mutation.query, variables: mutation.variables })) + } catch (error) { + const message = error instanceof Error ? error.message : String(error) + return { ok: false, code: error instanceof GhUnavailableError ? 'failed' : 'unknown', message } + } + const body = parse(output.stdout) + // A payload means GitHub applied the mutation, even beside errors about the fields it selects. + const payload = z.object({ data: z.record(z.string(), z.unknown()) }).safeParse(body) + const value = payload.success ? payload.data.data[mutation.field] : undefined + if (value !== undefined && value !== null) return { ok: true, payload: value } + const errors = graphqlErrors.safeParse(body) + if (errors.success) return { ok: false, code: 'failed', message: errors.data.errors.map(error => error.message).join('; ') } + if (output.exitCode !== 0) { + const message = output.stderr.trim() || output.stdout.trim() || `gh exited with ${output.exitCode}` + return { ok: false, code: REFUSED.test(output.stderr) ? 'failed' : 'unknown', message } + } + return { ok: false, code: 'unknown', message: `unexpected GitHub response to ${mutation.field}` } +} + +function parse(text: string): unknown { + let value: unknown + try { + value = JSON.parse(text) + } catch (error) { + void error // gh prints diagnostics instead of JSON when a request fails before GitHub answers. + return undefined + } + return value +} diff --git a/packages/experimental/forge-github/src/threads.ts b/packages/experimental/forge-github/src/threads.ts index 5717f47a0c..6b1e6096b3 100644 --- a/packages/experimental/forge-github/src/threads.ts +++ b/packages/experimental/forge-github/src/threads.ts @@ -2,7 +2,8 @@ import { Buffer } from 'node:buffer' import type { - ChangeRequestRef, ForgeAnchor, ForgeCommentId, ForgeFailure, ForgeReviewComment, ForgeReviewData, ForgeReviewThread, ForgeThreadId, + ChangeRequestRef, ForgeAnchor, ForgeCommentId, ForgeFailure, ForgeReviewComment, ForgeReviewData, ForgeReviewId, ForgeReviewThread, + ForgeThreadId, } from '@deepseek-ai/dsh-experimental-forge' import { z } from 'zod' import type { GraphqlReader } from './commits.ts' @@ -11,7 +12,10 @@ import { checkedRepository, isCommit } from './urls.ts' /** Most nodes GitHub returns in one connection page. */ const PAGE_SIZE = 100 -const COMMENT_FIELDS = 'id state createdAt url body author { __typename login avatarUrl(size: 48) }' +/** Repository permissions that may comment on a locked conversation. */ +const WRITERS: ReadonlySet = new Set(['ADMIN', 'MAINTAIN', 'WRITE']) + +const COMMENT_FIELDS = 'id state createdAt url body viewerCanUpdate viewerCanDelete author { __typename login avatarUrl(size: 48) }' const COMMENT_PAGE = `comments(first: ${PAGE_SIZE}, after: $cursor) { pageInfo { hasNextPage endCursor } nodes { ${COMMENT_FIELDS} } }` @@ -20,15 +24,26 @@ const COMMENT_PAGE = `comments(first: ${PAGE_SIZE}, after: $cursor) { pageInfo { * first page of comments starts without a cursor. */ const THREAD_FIELDS = `id isOutdated isResolved path diffSide startDiffSide line startLine originalLine originalStartLine subjectType + viewerCanReply viewerCanResolve viewerCanUnresolve root: comments(first: 1) { nodes { diffHunk commit { oid } originalCommit { oid } } } ${COMMENT_PAGE.replace(', after: $cursor', '')}` const THREAD_PAGE = `pageInfo { hasNextPage endCursor } nodes { ${THREAD_FIELDS} }` -/** First thread page with the head and the viewer; variables `owner` and `name` are strings, `number` and `first` integers. */ +/** + * First thread page with the head, the viewer, whether the viewer may comment, and the viewer's pending review; variables + * `owner` and `name` are strings, `number` and `first` integers. + */ export const REVIEW_QUERY = `query($owner: String!, $name: String!, $number: Int!, $first: Int!) { viewer { login } - repository(owner: $owner, name: $name) { pullRequest(number: $number) { id headRefOid reviewThreads(first: $first) { ${THREAD_PAGE} } } } + repository(owner: $owner, name: $name) { + isArchived viewerPermission + pullRequest(number: $number) { + id headRefOid locked + reviews(states: PENDING, first: 1) { nodes { id viewerDidAuthor commit { oid } comments { totalCount } } } + reviewThreads(first: $first) { ${THREAD_PAGE} } + } + } }` /** Following thread page with the head it was read at; variables `id` and `cursor` are strings, `first` an integer. */ @@ -62,6 +77,8 @@ const commentSchema = z.object({ createdAt: z.string(), url: z.string().nullable(), body: z.string(), + viewerCanUpdate: z.boolean(), + viewerCanDelete: z.boolean(), author: z.object({ __typename: z.string(), login: z.string(), avatarUrl: z.string().nullable() }).nullable(), }) @@ -79,15 +96,35 @@ const threadSchema = z.object({ originalLine: z.number().int().nullable(), originalStartLine: z.number().int().nullable(), subjectType: z.string(), + viewerCanReply: z.boolean(), + viewerCanResolve: z.boolean(), + viewerCanUnresolve: z.boolean(), root: z.object({ nodes: z.array(z.object({ diffHunk: z.string(), commit: commitSchema, originalCommit: commitSchema })) }), comments: commentPageSchema, }) const threadPageSchema = z.object({ pageInfo: pageInfoSchema, nodes: z.array(threadSchema) }) +const pendingSchema = z.object({ + id: z.string(), + viewerDidAuthor: z.boolean(), + commit: commitSchema, + comments: z.object({ totalCount: z.number().int().nonnegative() }), +}) + const firstPageSchema = z.object({ data: z.object({ viewer: z.object({ login: z.string() }).nullable(), - repository: z.object({ pullRequest: z.object({ id: z.string(), headRefOid: z.string(), reviewThreads: threadPageSchema }) }), + repository: z.object({ + isArchived: z.boolean(), + viewerPermission: z.string().nullable(), + pullRequest: z.object({ + id: z.string(), + headRefOid: z.string(), + locked: z.boolean(), + reviews: z.object({ nodes: z.array(pendingSchema) }), + reviewThreads: threadPageSchema, + }), + }), }) }) const nextPageSchema = z.object({ data: z.object({ node: z.object({ headRefOid: z.string(), reviewThreads: threadPageSchema }) }) }) @@ -127,14 +164,20 @@ export async function readReviewThreads( if ('code' in first) return first const parsed = firstPageSchema.safeParse(first.body) if (!parsed.success) return unexpected - const pull = parsed.data.data.repository.pullRequest + const repository = parsed.data.data.repository + const pull = repository.pullRequest const moved = stale(pull.headRefOid) if (moved !== undefined) return moved let bytes = first.bytes let page = pull.reviewThreads const threads: ForgeReviewThread[] = [] const viewer = parsed.data.data.viewer?.login ?? null - const result = (truncated: boolean): ForgeReviewData => ({ headSha, viewer, threads, truncated }) + const pending = pull.reviews.nodes.find(review => review.viewerDidAuthor) + const pendingReview = pending?.commit == null ? null + : { id: pending.id as ForgeReviewId, commit: pending.commit.oid, comments: pending.comments.totalCount } + // GitHub refuses every write to an archived repository, and comments on a locked conversation from anyone without write access. + const viewerCanReview = !repository.isArchived && (!pull.locked || WRITERS.has(repository.viewerPermission ?? '')) + const result = (truncated: boolean): ForgeReviewData => ({ headSha, viewer, threads, truncated, pendingReview, viewerCanReview }) const cursors = new Set() for (;;) { for (const node of page.nodes.slice(0, limits.maxReviewThreads - threads.length)) { @@ -193,6 +236,8 @@ function toThread(node: ThreadNode, comments: readonly CommentNode[], head: stri ? anchor(root.originalCommit.oid, sameSide ? node.originalStartLine : null, node.originalLine) : null, diffHunk: root === undefined || root.diffHunk === '' ? null : root.diffHunk, resolved: node.isResolved, + viewerCanReply: node.viewerCanReply, + viewerCanResolve: node.isResolved ? node.viewerCanUnresolve : node.viewerCanResolve, comments: comments.map(toComment), } } @@ -209,5 +254,7 @@ function toComment(node: CommentNode): ForgeReviewComment { createdAt: node.createdAt, pending: node.state === 'PENDING', url: node.url, + viewerCanEdit: node.viewerCanUpdate, + viewerCanDelete: node.viewerCanDelete, } } diff --git a/packages/experimental/forge-github/tests/review-writes.spec.ts b/packages/experimental/forge-github/tests/review-writes.spec.ts new file mode 100644 index 0000000000..d620401e36 --- /dev/null +++ b/packages/experimental/forge-github/tests/review-writes.spec.ts @@ -0,0 +1,253 @@ +/** GitHub review thread and pending review writes check the head first, send JSON on stdin, and never retry. */ +import { describe, expect, it } from 'vitest' +import type { ForgeCommentId, ForgeReviewId, ForgeReviewWrite, ForgeThreadId } from '@deepseek-ai/dsh-experimental-forge' +import { GhTimeoutError, GhUnavailableError, type GhOutput, type GhRunner } from '../src/gh.ts' +import { GitHubProvider } from '../src/provider.ts' +import { + ADD_REVIEW_MUTATION, ADD_THREAD_MUTATION, DELETE_COMMENT_MUTATION, DELETE_REVIEW_MUTATION, EDIT_COMMENT_MUTATION, REPLY_MUTATION, + RESOLVE_MUTATION, SUBMIT_REVIEW_MUTATION, UNRESOLVE_MUTATION, WRITE_CHECK_QUERY, +} from '../src/review-writes.ts' +import { demo, pull } from './fixtures.ts' + +const head = 'c'.repeat(40) +const pushed = 'd'.repeat(40) +const signal = new AbortController().signal +const thread = 'thread-1' as ForgeThreadId +const comment = 'comment-1' as ForgeCommentId +const review = 'review-1' as ForgeReviewId + +function output(stdout: unknown, exitCode = 0, stderr = ''): GhOutput { + return { exitCode, stdout: typeof stdout === 'string' ? stdout : JSON.stringify(stdout), stderr } +} + +function checked(pending: string | null = null, headRefOid = head, viewerDidAuthor = true): GhOutput { + return output({ data: { repository: { pullRequest: { + id: 'pull-7', headRefOid, reviews: { nodes: pending === null ? [] : [{ id: pending, viewerDidAuthor }] }, + } } } }) +} + +/** One recorded `gh` call: its arguments and, for a mutation, the JSON it sent on stdin. */ +interface Call { + readonly args: readonly string[] + readonly input: { readonly query: string; readonly variables: Record } | undefined +} + +/** A mutation answer that throws `throws` instead of printing output. */ +interface Thrown { readonly throws: unknown } + +/** Answer the check with `check`, then each mutation in turn from `mutations`. */ +function fakeGh(check: GhOutput, ...mutations: Array): { run: GhRunner; calls: Call[] } { + const calls: Call[] = [] + const queue = [...mutations] + return { calls, run: async (args, _signal, input) => { + calls.push({ args: [...args], input: input === undefined ? undefined : JSON.parse(input) as Call['input'] }) + if (input === undefined) return check + const next = queue.shift() + if (next === undefined) throw new Error(`unexpected gh ${args.join(' ')}`) + if ('throws' in next) throw next.throws + return next + } } +} + +function provider(run: GhRunner): GitHubProvider { + return new GitHubProvider(run, ['github.com'], { maxOutputBytes: 8_388_608, maxReviewThreads: 1_000, maxCommits: 250 }) +} + +function payload(field: string, value: unknown = { id: 'x' }): GhOutput { + return output({ data: { [field]: value } }) +} + +const MUTATION_ARGS = ['api', 'graphql', '--hostname', 'github.com', '--input', '-'] + +describe('GitHub review writes', () => { + it('checks the head with the pull request as variables and replies at once without a pending review', async () => { + const gh = fakeGh(checked(), payload('addPullRequestReviewThreadReply', { comment: { id: 'reply-1' } })) + + await expect(provider(gh.run).writeReview(pull(7), { kind: 'reply', headSha: head, thread, body: 'Fixed in `$(x)`', pending: false }, signal)) + .resolves.toEqual({ ok: true }) + expect(gh.calls).toEqual([ + { args: ['api', 'graphql', '--hostname', 'github.com', '-f', `query=${WRITE_CHECK_QUERY}`, '-f', `owner=${demo.owner}`, + '-f', `name=${demo.name}`, '-F', 'number=7'], input: undefined }, + { args: MUTATION_ARGS, input: { query: REPLY_MUTATION, variables: { thread, body: 'Fixed in `$(x)`', review: null } } }, + ]) + }) + + it('refuses a reply at once without a mutation while the viewer has a pending review, which GitHub would add it to', async () => { + const gh = fakeGh(checked('review-9')) + + await expect(provider(gh.run).writeReview(pull(7), { kind: 'reply', headSha: head, thread, body: 'Now', pending: false }, signal)) + .resolves.toEqual({ ok: false, code: 'failed', + message: 'GitHub adds a reply to the pending review while one exists; submit or discard it first' }) + expect(gh.calls).toHaveLength(1) + }) + + it('replies inside the existing pending review', async () => { + const gh = fakeGh(checked('review-9'), payload('addPullRequestReviewThreadReply')) + + await provider(gh.run).writeReview(pull(7), { kind: 'reply', headSha: head, thread, body: 'Later', pending: true }, signal) + + expect(gh.calls[1]?.input).toEqual({ query: REPLY_MUTATION, variables: { thread, body: 'Later', review: 'review-9' } }) + }) + + it('starts a pending review at the head before a pending reply when the viewer has none', async () => { + const gh = fakeGh(checked('review-of-other', head, false), + payload('addPullRequestReview', { pullRequestReview: { id: 'review-new' } }), payload('addPullRequestReviewThreadReply')) + + await expect(provider(gh.run).writeReview(pull(7), { kind: 'reply', headSha: head, thread, body: 'Later', pending: true }, signal)) + .resolves.toEqual({ ok: true }) + expect(gh.calls.slice(1).map(call => call.input)).toEqual([ + { query: ADD_REVIEW_MUTATION, variables: { pull: 'pull-7', commit: head, threads: null } }, + { query: REPLY_MUTATION, variables: { thread, body: 'Later', review: 'review-new' } }, + ]) + }) + + it('returns the failure of starting a pending review and an unexpected start without replying', async () => { + const write: ForgeReviewWrite = { kind: 'reply', headSha: head, thread, body: 'Later', pending: true } + const refused = fakeGh(checked(), output({ data: { addPullRequestReview: null }, errors: [{ message: 'Pull request is locked' }] }, 1)) + await expect(provider(refused.run).writeReview(pull(7), write, signal)) + .resolves.toEqual({ ok: false, code: 'failed', message: 'Pull request is locked' }) + expect(refused.calls).toHaveLength(2) + + const odd = fakeGh(checked(), payload('addPullRequestReview', { pullRequestReview: null })) + await expect(provider(odd.run).writeReview(pull(7), write, signal)) + .resolves.toEqual({ ok: false, code: 'unknown', message: 'unexpected GitHub response to starting a pending review' }) + expect(odd.calls).toHaveLength(2) + }) + + it.each([ + [true, RESOLVE_MUTATION, 'resolveReviewThread'], + [false, UNRESOLVE_MUTATION, 'unresolveReviewThread'], + ] as const)('marks a thread resolved %s through its mutation', async (resolved, query, field) => { + const gh = fakeGh(checked(), payload(field, { thread: { id: thread } })) + + await expect(provider(gh.run).writeReview(pull(7), { kind: 'resolve', headSha: head, thread, resolved }, signal)).resolves.toEqual({ ok: true }) + expect(gh.calls[1]?.input).toEqual({ query, variables: { thread } }) + }) + + it('edits and deletes a comment', async () => { + const edit = fakeGh(checked(), payload('updatePullRequestReviewComment')) + await provider(edit.run).writeReview(pull(7), { kind: 'edit-comment', headSha: head, comment, body: 'Reworded' }, signal) + expect(edit.calls[1]?.input).toEqual({ query: EDIT_COMMENT_MUTATION, variables: { comment, body: 'Reworded' } }) + + const remove = fakeGh(checked(), payload('deletePullRequestReviewComment', { clientMutationId: null })) + await expect(provider(remove.run).writeReview(pull(7), { kind: 'delete-comment', headSha: head, comment }, signal)).resolves.toEqual({ ok: true }) + expect(remove.calls[1]?.input).toEqual({ query: DELETE_COMMENT_MUTATION, variables: { comment } }) + }) + + it('starts a pending review at the head holding a new comment when the viewer has none', async () => { + const gh = fakeGh(checked(), payload('addPullRequestReview', { pullRequestReview: { id: 'review-new' } })) + + await provider(gh.run).writeReview(pull(7), { kind: 'add-pending', headSha: head, + comment: { path: 'src/a.ts', side: 'L', startLine: 3, endLine: 5, body: 'Range' } }, signal) + + expect(gh.calls[1]?.input).toEqual({ query: ADD_REVIEW_MUTATION, variables: { pull: 'pull-7', commit: head, threads: [ + { path: 'src/a.ts', body: 'Range', line: 5, side: 'LEFT', startLine: 3, startSide: 'LEFT' }, + ] } }) + }) + + it('adds a new single-line comment to the existing pending review', async () => { + const gh = fakeGh(checked('review-9'), payload('addPullRequestReviewThread', { thread: { id: 'thread-new' } })) + + await provider(gh.run).writeReview(pull(7), { kind: 'add-pending', headSha: head, + comment: { path: 'src/a.ts', side: 'R', startLine: 8, endLine: 8, body: 'Line' } }, signal) + + expect(gh.calls[1]?.input).toEqual({ query: ADD_THREAD_MUTATION, variables: { + review: 'review-9', path: 'src/a.ts', body: 'Line', line: 8, side: 'RIGHT', startLine: null, startSide: null, + } }) + }) + + it.each([ + ['comment', 'COMMENT'], ['approve', 'APPROVE'], ['request-changes', 'REQUEST_CHANGES'], + ] as const)('submits the pending review as a %s review', async (event, graphqlEvent) => { + const gh = fakeGh(checked(review), payload('submitPullRequestReview', { pullRequestReview: { id: review } })) + + await expect(provider(gh.run).writeReview(pull(7), { kind: 'submit-pending', headSha: head, review, event, body: 'Summary' }, signal)) + .resolves.toEqual({ ok: true }) + expect(gh.calls[1]?.input).toEqual({ query: SUBMIT_REVIEW_MUTATION, variables: { review, event: graphqlEvent, body: 'Summary' } }) + }) + + it('discards the pending review', async () => { + const gh = fakeGh(checked(review), payload('deletePullRequestReview', { pullRequestReview: { id: review } })) + + await expect(provider(gh.run).writeReview(pull(7), { kind: 'discard-pending', headSha: head, review }, signal)).resolves.toEqual({ ok: true }) + expect(gh.calls[1]?.input).toEqual({ query: DELETE_REVIEW_MUTATION, variables: { review } }) + }) + + it.each([ + ['submit', { kind: 'submit-pending', headSha: head, review, event: 'comment', body: '' }], + ['discard', { kind: 'discard-pending', headSha: head, review }], + ] as const)('refuses to %s a pending review that is no longer the viewer\'s without a mutation', async (_label, write) => { + for (const pending of [null, 'review-other']) { + const gh = fakeGh(checked(pending)) + await expect(provider(gh.run).writeReview(pull(7), write, signal)) + .resolves.toEqual({ ok: false, code: 'failed', message: 'the pending review review-1 is no longer the signed-in user\'s pending review' }) + expect(gh.calls).toHaveLength(1) + } + }) + + it('refuses a moved head without a mutation and accepts a head in another case', async () => { + const write: ForgeReviewWrite = { kind: 'resolve', headSha: head, thread, resolved: true } + const moved = fakeGh(checked(null, pushed)) + await expect(provider(moved.run).writeReview(pull(7), write, signal)) + .resolves.toEqual({ ok: false, code: 'stale', message: `the pull request head moved from ${head} to ${pushed}` }) + expect(moved.calls).toHaveLength(1) + + const upper = fakeGh(checked(null, head.toUpperCase()), payload('resolveReviewThread')) + await expect(provider(upper.run).writeReview(pull(7), write, signal)).resolves.toEqual({ ok: true }) + }) + + it('reports a failed or unexpected check as failed without a mutation', async () => { + const write: ForgeReviewWrite = { kind: 'resolve', headSha: head, thread, resolved: true } + const down = fakeGh(output('', 1, 'gh: Server Error (HTTP 502)')) + await expect(provider(down.run).writeReview(pull(7), write, signal)) + .resolves.toEqual({ ok: false, code: 'failed', message: 'gh: Server Error (HTTP 502)' }) + + const odd = fakeGh(output({ data: { repository: { pullRequest: null } } })) + await expect(provider(odd.run).writeReview(pull(7), write, signal)) + .resolves.toEqual({ ok: false, code: 'failed', message: 'unexpected GitHub response to the pull request check' }) + expect([down.calls, odd.calls].map(calls => calls.length)).toEqual([1, 1]) + }) + + it.each([ + ['a gh that cannot start', { throws: new GhUnavailableError('gh could not start: ENOENT') }, 'failed', 'gh could not start: ENOENT'], + ['a gh that times out', { throws: new GhTimeoutError('gh api timed out after 30000ms') }, 'unknown', 'gh api timed out after 30000ms'], + ['a thrown value that is not an error', { throws: 'lost' }, 'unknown', 'lost'], + ['GraphQL errors', output({ data: { resolveReviewThread: null }, errors: [{ message: 'one' }, { message: 'two' }] }, 1), 'failed', 'one; two'], + ['an HTTP refusal', output('', 1, 'gh: Validation Failed (HTTP 422)'), 'failed', 'gh: Validation Failed (HTTP 422)'], + ['a server error', output('', 1, 'gh: Server Error (HTTP 502)'), 'unknown', 'gh: Server Error (HTTP 502)'], + ['a failure printed on stdout', output('connection reset', 1), 'unknown', 'connection reset'], + ['a failure without output', output('', 1), 'unknown', 'gh exited with 1'], + ['an answer that is not JSON', output(''), 'unknown', 'unexpected GitHub response to resolveReviewThread'], + ['an empty payload', payload('resolveReviewThread', null), 'unknown', 'unexpected GitHub response to resolveReviewThread'], + ] as const)('reports a mutation ending in %s as %s', async (_label, answer, code, message) => { + const gh = fakeGh(checked(), answer) + + await expect(provider(gh.run).writeReview(pull(7), { kind: 'resolve', headSha: head, thread, resolved: true }, signal)) + .resolves.toEqual({ ok: false, code, message }) + }) + + it('treats a payload beside errors about its fields as applied', async () => { + const gh = fakeGh(checked(), output({ data: { resolveReviewThread: { thread: null } }, errors: [{ message: 'thread is not visible' }] })) + + await expect(provider(gh.run).writeReview(pull(7), { kind: 'resolve', headSha: head, thread, resolved: true }, signal)) + .resolves.toEqual({ ok: true }) + }) + + it('throws the abort reason when the signal aborts before a mutation is sent', async () => { + const controller = new AbortController() + const reason = new Error('closed') + const run: GhRunner = async () => { controller.abort(reason); return checked() } + + await expect(provider(run).writeReview(pull(7), { kind: 'resolve', headSha: head, thread, resolved: true }, controller.signal)).rejects.toBe(reason) + }) + + it('refuses an unconfigured host without starting gh and a head that is not a commit object name', async () => { + const gh = fakeGh(checked()) + const write: ForgeReviewWrite = { kind: 'resolve', headSha: head, thread, resolved: true } + + await expect(provider(gh.run).writeReview(pull(7, { ...demo, host: 'ghe.other.example' }), write, signal)) + .resolves.toEqual({ ok: false, code: 'failed', message: 'forge-github: host "ghe.other.example" is not configured' }) + await expect(provider(gh.run).writeReview(pull(7), { ...write, headSha: 'main' }, signal)).rejects.toThrow('forge-github: invalid head commit "main"') + expect(gh.calls).toEqual([]) + }) +}) diff --git a/packages/experimental/forge-github/tests/threads.spec.ts b/packages/experimental/forge-github/tests/threads.spec.ts index 42c49f389a..1e4fc80037 100644 --- a/packages/experimental/forge-github/tests/threads.spec.ts +++ b/packages/experimental/forge-github/tests/threads.spec.ts @@ -32,6 +32,7 @@ function page(nodes: readonly unknown[], next: string | null = null): Record = {}): Record { return { id, state: 'SUBMITTED', createdAt: '2026-11-05T08:00:00Z', url: `https://github.com/octo/demo/pull/7#discussion_${id}`, body: `Body of ${id}`, + viewerCanUpdate: false, viewerCanDelete: false, author: { __typename: 'User', login: 'reviewer', avatarUrl: 'https://avatars.githubusercontent.com/u/1?s=48&v=4' }, ...overrides, } @@ -42,14 +43,20 @@ function threadNode(id: string, overrides: Record = {}, root: R return { id, isOutdated: false, isResolved: false, path: 'src/a.ts', diffSide: 'RIGHT', startDiffSide: null, line: 12, startLine: null, originalLine: 12, originalStartLine: null, subjectType: 'LINE', + viewerCanReply: true, viewerCanResolve: true, viewerCanUnresolve: false, root: { nodes: [{ diffHunk: '@@ -10,2 +10,3 @@\n a\n+b\n c', commit: { oid: head }, originalCommit: { oid: head }, ...root }] }, comments: page([commentNode(`${id}-1`)]), ...overrides, } } -function firstPage(threads: Record, headRefOid = head, viewer: unknown = { login: 'octo' }): Record { - return { data: { viewer, repository: { pullRequest: { id: 'pull-7', headRefOid, reviewThreads: threads } } } } +function firstPage( + threads: Record, headRefOid = head, viewer: unknown = { login: 'octo' }, pull: Record = {}, + repository: Record = {}, +): Record { + return { data: { viewer, repository: { isArchived: false, viewerPermission: 'READ', ...repository, pullRequest: { + id: 'pull-7', headRefOid, locked: false, reviews: { nodes: [] }, reviewThreads: threads, ...pull, + } } } } } function nextPage(threads: Record, headRefOid = head): Record { @@ -84,16 +91,21 @@ describe('GitHub provider review threads', () => { headSha: head, viewer: 'octo', truncated: false, + pendingReview: null, + viewerCanReview: true, threads: [{ id: 't1', path: 'src/a.ts', side: 'R', subject: 'line', current: { commit: head, startLine: 12, endLine: 12 }, original: { commit: head, startLine: 12, endLine: 12 }, diffHunk: '@@ -10,2 +10,3 @@\n a\n+b\n c', resolved: true, + viewerCanReply: true, + viewerCanResolve: false, comments: [{ id: 't1-1', body: 'Body of t1-1', createdAt: '2026-11-05T08:00:00Z', pending: false, url: 'https://github.com/octo/demo/pull/7#discussion_t1-1', author: { login: 'reviewer', avatarUrl: 'https://avatars.githubusercontent.com/u/1?s=48&v=4', bot: false }, + viewerCanEdit: false, viewerCanDelete: false, }], }], }) @@ -161,6 +173,51 @@ describe('GitHub provider review threads', () => { expect(result).toMatchObject({ threads: { length: 1 } }) }) + it('maps the permissions of the viewer on threads and comments, resolving an unresolved thread and unresolving a resolved one', async () => { + const gh = review(firstPage(page([ + threadNode('open', { viewerCanReply: false, viewerCanResolve: true, viewerCanUnresolve: false, comments: page([ + commentNode('mine', { viewerCanUpdate: true, viewerCanDelete: true }), + ]) }), + threadNode('settled', { isResolved: true, viewerCanResolve: false, viewerCanUnresolve: true }), + ]))) + + const result = await provider(gh.run).readReview(pull(7), head, signal) + + expect(result).toMatchObject({ threads: [ + { id: 'open', viewerCanReply: false, viewerCanResolve: true, comments: [{ id: 'mine', viewerCanEdit: true, viewerCanDelete: true }] }, + { id: 'settled', viewerCanReply: true, viewerCanResolve: true }, + ] }) + }) + + it('reports the pending review the viewer authored with its commit and comment count', async () => { + const reviews = { nodes: [{ id: 'review-1', viewerDidAuthor: true, commit: { oid: older }, comments: { totalCount: 2 } }] } + const gh = review(firstPage(page([]), head, { login: 'octo' }, { reviews })) + + await expect(provider(gh.run).readReview(pull(7), head, signal)) + .resolves.toMatchObject({ pendingReview: { id: 'review-1', commit: older, comments: 2 } }) + }) + + it.each([ + ['another user authored', { id: 'review-2', viewerDidAuthor: false, commit: { oid: head }, comments: { totalCount: 1 } }], + ['names no commit', { id: 'review-3', viewerDidAuthor: true, commit: null, comments: { totalCount: 1 } }], + ] as const)('reports no pending review for one %s', async (_label, node) => { + const gh = review(firstPage(page([]), head, { login: 'octo' }, { reviews: { nodes: [node] } })) + + await expect(provider(gh.run).readReview(pull(7), head, signal)).resolves.toMatchObject({ pendingReview: null }) + }) + + it.each([ + ['an archived repository', {}, { isArchived: true, viewerPermission: 'ADMIN' }, false], + ['a locked conversation without write access', { locked: true }, { viewerPermission: 'TRIAGE' }, false], + ['a locked conversation without a known permission', { locked: true }, { viewerPermission: null }, false], + ['a locked conversation with write access', { locked: true }, { viewerPermission: 'WRITE' }, true], + ['an open conversation with read access', {}, { viewerPermission: 'READ' }, true], + ] as const)('reports whether the viewer can review in %s', async (_label, pullFields, repository, expected) => { + const gh = review(firstPage(page([]), head, { login: 'octo' }, pullFields, repository)) + + await expect(provider(gh.run).readReview(pull(7), head, signal)).resolves.toMatchObject({ viewerCanReview: expected }) + }) + it('reads the following thread and comment pages, asking only for the threads left under maxReviewThreads', async () => { const gh = review( firstPage(page([threadNode('t1', { comments: page([commentNode('c1')], 'comments-1') })], 'threads-1')), @@ -198,7 +255,7 @@ describe('GitHub provider review threads', () => { const byComments = review(first, threads, comments) await expect(provider(byComments.run, { maxOutputBytes: size + 10 }).readReview(pull(7), head, signal)) - .resolves.toEqual({ headSha: head, viewer: 'octo', threads: [], truncated: true }) + .resolves.toEqual({ headSha: head, viewer: 'octo', threads: [], truncated: true, pendingReview: null, viewerCanReview: true }) const commentBytes = JSON.stringify(comments['comments-1']).length const byThreads = review(first, threads, comments) diff --git a/packages/experimental/forge-github/tsconfig.json b/packages/experimental/forge-github/tsconfig.json index fea1cc6ec1..ff2c3474bc 100644 --- a/packages/experimental/forge-github/tsconfig.json +++ b/packages/experimental/forge-github/tsconfig.json @@ -28,6 +28,9 @@ }, { "path": "../../util/brand" + }, + { + "path": "../../util/values" } ] } diff --git a/packages/experimental/forge/src/index.ts b/packages/experimental/forge/src/index.ts index 88068c3aee..1373810e80 100644 --- a/packages/experimental/forge/src/index.ts +++ b/packages/experimental/forge/src/index.ts @@ -8,7 +8,7 @@ import { nextPollDelay } from './schedule.ts' import type { ChangeRequestKey, ChangeRequestListener, ChangeRequestRef, ChangeRequestSnapshot, ChangeRequestUpdate, Config, ForgeCommitList, ForgeActionFailure, ForgeFailure, ForgeProvider, ForgeReadiness, ForgeRepository, ForgeReviewData, ForgeReviewRequest, ForgeReviewResult, - MergeRequest, + ForgeReviewWrite, ForgeReviewWriteResult, MergeRequest, } from './types.ts' export { changeRequestKey } from './keys.ts' @@ -253,7 +253,7 @@ export class ForgeService extends Service { async diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise { const result = await this.invoke(this.registration(ref.repository.forge), signal, (provider, operation) => provider.diff(ref, headSha, operation)) - if (typeof result !== 'string') this.staleRead(ref, headSha, result) + if (typeof result !== 'string') this.staleRead(ref, headSha, result.code) return result } @@ -270,7 +270,26 @@ export class ForgeService extends Service { const result = await this.invoke(this.registration(ref.repository.forge), signal, (provider, operation) => provider.readReview?.(ref, headSha, operation) ?? Promise.resolve({ code: 'unsupported', message: 'This provider does not support review reads' } as const)) - if ('code' in result) this.staleRead(ref, headSha, result) + if ('code' in result) this.staleRead(ref, headSha, result.code) + return result + } + + /** + * Write to the review threads or the pending review of a change request while its head is still `write.headSha`, then + * poll the change request at once when it is watched. A `stale` result polls it as a stale read does. + * @param ref - change request served by a registered provider. + * @param write - the write and the head commit the user saw. + * @param signal - cancellation of the write. + * @returns whether the host took the write; `unsupported` when the provider cannot write reviews, and `unknown` when the + * outcome must be checked on the host before the write is tried again. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ + async writeReview(ref: ChangeRequestRef, write: ForgeReviewWrite, signal: AbortSignal): Promise { + const result = await this.invoke(this.registration(ref.repository.forge), signal, + (provider, operation) => provider.writeReview?.(ref, write, operation) + ?? Promise.resolve({ ok: false, code: 'unsupported', message: 'This provider does not support review writes' } as const)) + if (!result.ok && result.code === 'stale') this.staleRead(ref, write.headSha, result.code) + else this.refresh(ref) return result } @@ -398,10 +417,10 @@ export class ForgeService extends Service { return this.watches.get(changeRequestKey(ref))?.latest } - /** Poll a watched change request at once after the first `stale` read at `headSha`; later ones wait for the regular poll. */ - private staleRead(ref: ChangeRequestRef, headSha: string, failure: ForgeFailure): void { + /** Poll a watched change request at once after the first `stale` read or write at `headSha`; later ones wait for the regular poll. */ + private staleRead(ref: ChangeRequestRef, headSha: string, code: ForgeFailure['code']): void { const watch = this.watches.get(changeRequestKey(ref)) - if (failure.code !== 'stale' || watch === undefined || watch.staleHead === headSha) return + if (code !== 'stale' || watch === undefined || watch.staleHead === headSha) return watch.staleHead = headSha this.refresh(ref) } diff --git a/packages/experimental/forge/src/types.ts b/packages/experimental/forge/src/types.ts index 71bd7270e0..6ef6526059 100644 --- a/packages/experimental/forge/src/types.ts +++ b/packages/experimental/forge/src/types.ts @@ -160,7 +160,7 @@ export type ForgeReviewRequest = { readonly headSha: string } & ( | { readonly kind: 'comment'; readonly comment: ForgeLineComment } - | { readonly kind: 'review'; readonly event: 'comment' | 'approve' | 'request-changes'; readonly body: string; readonly comments: readonly ForgeLineComment[] } + | { readonly kind: 'review'; readonly event: ForgeReviewEvent; readonly body: string; readonly comments: readonly ForgeLineComment[] } ) /** Opaque host identity of one review thread. */ @@ -169,6 +169,9 @@ export type ForgeThreadId = Branded<'ForgeThreadId'> /** Opaque host identity of one review comment. */ export type ForgeCommentId = Branded<'ForgeCommentId'> +/** Opaque host identity of one review. */ +export type ForgeReviewId = Branded<'ForgeReviewId'> + /** Consecutive lines of one file at one commit. */ export interface ForgeAnchor { /** Full object name of the commit whose file the lines number. */ @@ -203,6 +206,10 @@ export interface ForgeReviewComment { readonly pending: boolean /** Web page of the comment, or null when the host reports none. */ readonly url: string | null + /** Whether the signed-in user can replace the comment's text through `writeReview`; false for a provider without it. */ + readonly viewerCanEdit: boolean + /** Whether the signed-in user can delete the comment through `writeReview`; false for a provider without it. */ + readonly viewerCanDelete: boolean } /** @@ -227,10 +234,27 @@ export interface ForgeReviewThread { readonly diffHunk: string | null /** Whether the thread is marked resolved. */ readonly resolved: boolean + /** Whether the signed-in user can reply to the thread through `writeReview`; false for a provider without it. */ + readonly viewerCanReply: boolean + /** + * Whether the signed-in user can mark the thread resolved, or unresolved when `resolved`, through `writeReview`; false + * for a provider without it. + */ + readonly viewerCanResolve: boolean /** Comments oldest first; the first starts the thread. */ readonly comments: readonly ForgeReviewComment[] } +/** The signed-in user's review of a change request that is not submitted yet, which only that user sees. */ +export interface ForgePendingReview { + /** Host identity of the review. */ + readonly id: ForgeReviewId + /** Full object name of the commit the review addresses. */ + readonly commit: string + /** Comments the review holds. */ + readonly comments: number +} + /** Review threads of a change request read at one head commit. */ export interface ForgeReviewData { /** Head commit the threads were read at; `current` positions number its files. */ @@ -241,8 +265,44 @@ export interface ForgeReviewData { readonly threads: readonly ForgeReviewThread[] /** Whether the change request has more threads than `threads` holds. */ readonly truncated: boolean + /** The signed-in user's pending review, or null without one. */ + readonly pendingReview: ForgePendingReview | null + /** + * Whether the signed-in user can add comments to a pending review and submit or discard it through `writeReview`; + * false for a provider without it. + */ + readonly viewerCanReview: boolean } +/** Decision a submitted review records. */ +export type ForgeReviewEvent = 'comment' | 'approve' | 'request-changes' + +/** + * One write to the review threads and the pending review of a change request. `pending` replies and `add-pending` + * comments join the signed-in user's pending review, which is started when the user has none. A host that adds every + * reply to an existing pending review, as GitHub does, refuses a reply with `pending: false` while one exists. + */ +export type ForgeReviewWrite = { + /** Head commit the user saw; providers check it before writing and refuse with `stale` once the head is another commit. */ + readonly headSha: string +} & ( + | { readonly kind: 'reply'; readonly thread: ForgeThreadId; readonly body: string; readonly pending: boolean } + | { readonly kind: 'resolve'; readonly thread: ForgeThreadId; readonly resolved: boolean } + | { readonly kind: 'edit-comment'; readonly comment: ForgeCommentId; readonly body: string } + /** Deleting the only comment of a thread deletes the thread. */ + | { readonly kind: 'delete-comment'; readonly comment: ForgeCommentId } + /** A comment on lines of `headSha`. */ + | { readonly kind: 'add-pending'; readonly comment: ForgeLineComment } + | { readonly kind: 'submit-pending'; readonly review: ForgeReviewId; readonly event: ForgeReviewEvent; readonly body: string } + /** Delete the pending review with every comment it holds. */ + | { readonly kind: 'discard-pending'; readonly review: ForgeReviewId } +) + +/** Result of a review write; an `unknown` outcome must be checked on the host before the write is tried again. */ +export type ForgeReviewWriteResult = + | { readonly ok: true } + | { readonly ok: false; readonly code: 'unsupported' | 'stale' | 'failed' | 'unknown'; readonly message: string } + /** Result of a review write; unknown outcomes must be checked on the host before another submission. */ export type ForgeReviewResult = | { readonly ok: true; readonly url: string } @@ -306,6 +366,12 @@ export interface ForgeProvider { * Omission declares that this provider cannot read reviews. */ readReview?(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise + /** + * Write to the review threads or the pending review of a change request while its head is `write.headSha`; once the + * head is another commit, the write resolves to `stale` without writing. A write is never retried. Omission declares + * that this provider cannot write reviews, and its `readReview` then reports no viewer permission. + */ + writeReview?(ref: ChangeRequestRef, write: ForgeReviewWrite, signal: AbortSignal): Promise /** Map a Git remote URL to its repository, or undefined when this provider does not serve it. */ repositoryFromRemote(url: string): ForgeRepository | undefined /** Map a change request web URL to its reference, or undefined when this provider does not serve it. */ diff --git a/packages/experimental/forge/tests/registry.spec.ts b/packages/experimental/forge/tests/registry.spec.ts index a87103be4e..b9d24f6338 100644 --- a/packages/experimental/forge/tests/registry.spec.ts +++ b/packages/experimental/forge/tests/registry.spec.ts @@ -1,7 +1,7 @@ import { Context } from '@deepseek-ai/cordis' import { afterEach, describe, expect, it, vi } from 'vitest' import ForgeService, { changeRequestKey } from '../src/index.ts' -import type { ForgeReviewData } from '../src/types.ts' +import type { ForgeReviewData, ForgeReviewWrite, ForgeThreadId } from '../src/types.ts' import { demo, FakeProvider, forgeContext, provide, ref, snapshot } from './fake-provider.ts' let ctx: Context | undefined @@ -134,13 +134,30 @@ describe('forge registry', () => { await expect(ctx.forge.readReview(ref(3), 'a'.repeat(40), signal)) .resolves.toEqual({ code: 'unsupported', message: 'This provider does not support review reads' }) - const review: ForgeReviewData = { headSha: 'a'.repeat(40), viewer: 'octo', threads: [], truncated: false } + const review: ForgeReviewData = { + headSha: 'a'.repeat(40), viewer: 'octo', threads: [], truncated: false, pendingReview: null, viewerCanReview: false, + } const readReview = vi.fn(async () => review) Object.assign(provider, { readReview }) await expect(ctx.forge.readReview(ref(3), 'a'.repeat(40), signal)).resolves.toBe(review) expect(readReview).toHaveBeenCalledWith(ref(3), 'a'.repeat(40), expect.any(AbortSignal)) }) + it('delegates review writes to the provider of their forge and reports a provider without them as unsupported', async () => { + ctx = await forgeContext() + const provider = new FakeProvider() + await provide(ctx, provider) + const signal = new AbortController().signal + const write: ForgeReviewWrite = { kind: 'resolve', headSha: 'a'.repeat(40), thread: 'thread-1' as ForgeThreadId, resolved: true } + + await expect(ctx.forge.writeReview(ref(3), write, signal)) + .resolves.toEqual({ ok: false, code: 'unsupported', message: 'This provider does not support review writes' }) + const writeReview = vi.fn(async () => ({ ok: true as const })) + Object.assign(provider, { writeReview }) + await expect(ctx.forge.writeReview(ref(3), write, signal)).resolves.toEqual({ ok: true }) + expect(writeReview).toHaveBeenCalledWith(ref(3), write, expect.any(AbortSignal)) + }) + it('delegates change request actions to the provider of their forge and returns its outcome', async () => { ctx = await forgeContext() const provider = new FakeProvider() diff --git a/packages/experimental/forge/tests/watch.spec.ts b/packages/experimental/forge/tests/watch.spec.ts index 5903fb42fa..43dc792c07 100644 --- a/packages/experimental/forge/tests/watch.spec.ts +++ b/packages/experimental/forge/tests/watch.spec.ts @@ -1,7 +1,10 @@ import { Context } from '@deepseek-ai/cordis' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import ForgeService, { changeRequestKey } from '../src/index.ts' -import type { ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot, ChangeRequestUpdate, ForgeFailure, ForgeRepository, ForgeReviewData } from '../src/types.ts' +import type { + ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot, ChangeRequestUpdate, ForgeFailure, ForgeRepository, ForgeReviewData, + ForgeReviewWrite, ForgeReviewWriteResult, ForgeThreadId, +} from '../src/types.ts' import { FakeProvider, forgeContext, provide, ref, snapshot } from './fake-provider.ts' const config = { activeIntervalMs: 1_000, idleIntervalMs: 5_000, maxBackoffMs: 6_000, fetchTimeoutMs: 500 } @@ -289,6 +292,33 @@ describe('forge watch', () => { expect(provider.fetches).toHaveLength(2) }) + it('polls at once after every review write, and after a stale one only once per head', async () => { + const provider = new FakeProvider() + provider.results.set(key, snapshot(ref(1))) + const writeReview = vi.fn(async (): Promise => ({ ok: true })) + Object.assign(provider, { writeReview }) + const context = await setup(provider) + collect(context) + await vi.advanceTimersByTimeAsync(0) + const signal = new AbortController().signal + const write: ForgeReviewWrite = { kind: 'reply', headSha: 'a'.repeat(40), thread: 'thread-1' as ForgeThreadId, body: 'Done', pending: false } + + await expect(context.forge.writeReview(ref(1), write, signal)).resolves.toEqual({ ok: true }) + await vi.advanceTimersByTimeAsync(0) + expect(provider.fetches).toHaveLength(2) + writeReview.mockResolvedValue({ ok: false, code: 'unknown', message: 'connection reset' }) + await context.forge.writeReview(ref(1), write, signal) + await vi.advanceTimersByTimeAsync(0) + expect(provider.fetches).toHaveLength(3) + writeReview.mockResolvedValue({ ok: false, code: 'stale', message: 'the head moved' }) + await expect(context.forge.writeReview(ref(1), write, signal)).resolves.toEqual({ ok: false, code: 'stale', message: 'the head moved' }) + await vi.advanceTimersByTimeAsync(0) + expect(provider.fetches).toHaveLength(4) + await context.forge.writeReview(ref(1), write, signal) + await vi.advanceTimersByTimeAsync(0) + expect(provider.fetches).toHaveLength(4) + }) + it('coalesces refreshes during a fetch into one immediate subsequent fetch', async () => { const provider = new FakeProvider() const release = held(provider, target => snapshot(target)) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9a2b3cbd92..f6b6836d6f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -10172,6 +10172,9 @@ importers: '@deepseek-ai/dsh-timeout': specifier: workspace:* version: link:../../util/timeout + '@deepseek-ai/dsh-util-values': + specifier: workspace:* + version: link:../../util/values '@deepseek-ai/schemastery': specifier: link:../../../vendor/schemastery version: link:../../../vendor/schemastery From b1aa940b0fa92b870ff91539cea9ba23480b53f5 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Mon, 9 Nov 2026 11:21:15 +0800 Subject: [PATCH 029/184] feat(forge-panel): reply to, resolve, and edit review threads and submit the pending review Thread cards gain a reply field, Resolve and Unresolve, and edit and delete for the viewer's own comments. Start review and Add to review add pull request comments to the GitHub pending review, which Submit review submits or discards; while one exists, replies join it and no single comment is offered, as GitHub refuses one. On the viewer's own pull request the dialog offers only Comment. Comment drafts an earlier panel kept in the browser stay editable, can move into the pending review, and block submission while one exists. --- .../client-ui-forge/src/client/ChangesTab.tsx | 113 +++++++- .../src/client/ReviewComposer.tsx | 53 ++-- .../src/client/ReviewThread.tsx | 31 ++- .../src/client/ReviewThreads.module.css | 78 ++++++ .../src/client/ReviewThreads.tsx | 177 +++++++++++- .../src/client/SubmitReview.module.css | 3 + .../src/client/SubmitReview.tsx | 51 +++- .../client-ui-forge/src/client/locales.ts | 184 +++++++++++++ .../client-ui-forge/src/client/mount.ts | 3 +- .../src/client/review-queue.ts | 15 +- .../src/client/thread-state.ts | 6 +- .../tests/changes-tab.client.spec.tsx | 259 ++++++++++++++++-- .../tests/mount.client.spec.ts | 15 +- .../tests/review-thread-cards.client.spec.tsx | 174 +++++++++++- .../tests/review.client.spec.tsx | 190 ++++++++++--- .../tests/thread-fixtures.client.ts | 9 +- 16 files changed, 1214 insertions(+), 147 deletions(-) diff --git a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx index 0747a901bc..91ef3242e7 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx @@ -22,13 +22,14 @@ import { import type { HostObservable, InjectFace, PropsLocale, PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots' import type { SidebarRightTabInfo } from '@deepseek-ai/dsh-client-ui-sidebar-right/client' import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import { assertNever } from '@deepseek-ai/dsh-util-values' import { fileAddressFor, pathPartsOf } from '@deepseek-ai/dsh-util-workspace-path' import type { ForgeBaseBranch, ForgeBaseBranches, ForgeChangeRequestDiff, ForgeCommitRange, ForgeDiffFile, ForgeLocalCommits, ForgeLocalDiff, ForgeLocalScope, ForgePanelChangeRequest, ForgePanelState, } from '../types.ts' import type { - ForgeCommitList, ForgeReviewData, ForgeReviewRequest, ForgeReviewResult, ForgeReviewThread, + ForgeCommitList, ForgeReviewData, ForgeReviewRequest, ForgeReviewResult, ForgeReviewThread, ForgeReviewWrite, ForgeReviewWriteResult, } from '@deepseek-ai/dsh-experimental-forge/types' import { sameReviewSource, type ReviewQueue } from './review-queue.ts' import { ReviewThread, useFileReview } from './ReviewThread.tsx' @@ -49,7 +50,7 @@ import { drawnLines, matchesHunks, textLines } from './diff-rows.ts' import { ChangeRequestGlyph } from './glyphs.tsx' import type { ForgePanelKey, NS } from './locales.ts' import { RefreshGlyph } from './RefreshGlyph.tsx' -import type { FileThreads, ThreadActions, ThreadFocus } from './ReviewThreads.tsx' +import type { FileThreads, ThreadActions, ThreadFocus, ThreadWrite } from './ReviewThreads.tsx' import { inFileOrder, type ThreadFilter } from './review-threads.ts' import { usePlacedThreads, useThreadRead, type PlacedThread } from './thread-state.ts' import { ThreadList } from './ThreadList.tsx' @@ -94,6 +95,8 @@ export interface ChangesTabInjected { readonly changeRequestText: (url: string, commit: string, path: string) => Promise> /** Read the review threads of a change request at the head of its latest status; `signal` aborts the read. */ readonly changeRequestReview: (url: string, headSha: string, signal: AbortSignal) => Promise> + /** Write to the review threads or the pending review of a change request; never retries a write. */ + readonly changeRequestReviewWrite: (url: string, write: ForgeReviewWrite) => Promise> /** Quote a whole review thread of the change request at `url` in the main input without submitting it. */ readonly addThreadToInput: (thread: ForgeReviewThread, url: string, range: string | null) => boolean /** Open a URL outside the app. */ @@ -433,7 +436,7 @@ function OrphanReviews({ path, actions, t }: PropsLocale & { */ export function ChangesTab({ useTabInfo, sessionId, useStore, actions, usePanel, reconnect, localDiff, diffBases, localText, localCommits, changeRequestDiff, - changeRequestText, changeRequestCommits, changeRequestReview, viewedFiles, + changeRequestText, changeRequestCommits, changeRequestReview, changeRequestReviewWrite, viewedFiles, openLink, copyPath, createChangeRequest, addReviewToInput, addThreadToInput, reviewQueue, submitReview, report, t, }: ChangesTabProps): ReactNode { const { tab } = useTabInfo() @@ -482,6 +485,40 @@ export function ChangesTab({ setReviewBusy(false) } } + // Every write that may have changed the threads reads them again; writes run one at a time, so a write that starts a + // pending review settles before the next write looks for one. + const [reviewRevision, setReviewRevision] = useState(0) + const writing = useRef>(Promise.resolve()) + const writeReview = (url: string, write: ForgeReviewWrite): Promise => { + const run = async (): Promise => { + const response = await changeRequestReviewWrite(url, write) + if (!response.ok) { + if (response.error.code === 'forgePanel/not-bound') return t('thread.writeFailed', { message: response.error.message }) + setReviewRevision(value => value + 1) + return t('thread.writeUnknown') + } + const result = response.value + if (result.ok) { + setReviewRevision(value => value + 1) + return undefined + } + switch (result.code) { + case 'unsupported': return t('thread.writeUnsupported') + case 'failed': + setReviewRevision(value => value + 1) + return t('thread.writeFailed', { message: result.message }) + case 'stale': return t('thread.writeStale') + case 'unknown': + setReviewRevision(value => value + 1) + return t('thread.writeUnknown') + /* v8 ignore next -- closed ForgeReviewWriteResult code union exhaustiveness guard */ + default: return assertNever(result.code, 'ForgeReviewWriteResult.code') + } + } + const next = writing.current.then(run, run) + writing.current = next + return next + } const choices = useStore(store => store.byTab[tab.id]) const [wanted, setWanted] = useState(null) const [treeState, setTreeState] = useState({ query: '', collapsed: {}, selected: null }) @@ -575,7 +612,7 @@ export function ChangesTab({ const prHead = entry?.snapshot?.headSha ?? null const prAuthor = entry?.snapshot?.author ?? null const threadRead = useThreadRead({ visible: tab.visible, url: source.kind === 'change' ? source.url : null, head: prHead, - updatedAt: entry?.snapshot?.updatedAt ?? null, statusAt, attempt, read: changeRequestReview }) + updatedAt: entry?.snapshot?.updatedAt ?? null, statusAt, attempt, revision: reviewRevision, read: changeRequestReview }) const review = data?.kind === 'change' && threadRead.review !== null && threadRead.review.headSha === prHead && (data.commits !== null || data.headSha === prHead) ? threadRead.review : null const placed = usePlacedThreads(review, data?.kind === 'change' ? { head: prHead ?? '', end: data.headSha, commits: data.commits } : null) @@ -689,16 +726,61 @@ export function ChangesTab({ return list } - // A review addresses the head commit, so it is submitted from the view of the whole change request. + // A review addresses the head commit, so it is submitted from the view of the whole change request. A pending review on + // the code host is submitted or discarded there; without one, the summary and any comment drafts kept in the browser + // are published as one review. + const pendingReview = review?.pendingReview ?? null + // Logins compare without case, as GitHub's do. + const ownChangeRequest = review?.viewer != null && prAuthor !== null && review.viewer.toLowerCase() === prAuthor.toLowerCase() + const finishWrite = async (send: () => Promise, done: ForgePanelKey): Promise => { + if (reviewRunning.current) return + reviewRunning.current = true + setReviewBusy(true) + setReviewError(null) + try { + const failure = await send() + if (failure !== undefined) { + setReviewError(failure) + return + } + report(done) + setReviewOpen(false) + } finally { + reviewRunning.current = false + setReviewBusy(false) + } + } const reviewForm = tab.visible && data !== null && reviewOpen && data.kind === 'change' && data.commits === null && { setReviewOpen(false) }} + url={data.url} headSha={data.headSha} pending={pendingReview} own={ownChangeRequest} busy={reviewBusy} error={reviewError} + close={() => { setReviewOpen(false) }} check={() => { openLink(data.url) }} reconcile={() => { queue.finish(false); setReviewError(null) }} submit={() => { const latest = queue.getSnapshot() - void publishReview(data.url, { kind: 'review', headSha: data.headSha, event: latest.event, - body: latest.body, comments: latest.comments.map(item => item.comment) }, url => queue.finish(true, url)) + if (pendingReview === null) { + void publishReview(data.url, { kind: 'review', headSha: data.headSha, event: latest.event, + body: latest.body, comments: latest.comments.map(item => item.comment) }, url => queue.finish(true, url)) + return + } + void finishWrite(async () => { + const failure = await writeReview(data.url, { kind: 'submit-pending', headSha: data.headSha, review: pendingReview.id, + event: latest.event, body: latest.body }) + if (failure === undefined && !queue.finish(true)) report('review.saveFailed') + return failure + }, 'review.submitted') + }} + discard={pendingReview === null ? undefined : () => { + void finishWrite(() => writeReview(data.url, { kind: 'discard-pending', headSha: data.headSha, review: pendingReview.id }), 'review.discarded') }} t={t} /> + /** Add a comment to the pending review on the code host at the head the comment was selected on. */ + const addPending = (selection: ReviewSelection): Promise => { + if (selection.source.kind !== 'change') return Promise.resolve(t('review.stale')) + const { path, side, startLine, endLine, body } = selection.comment + return writeReview(selection.source.url, { kind: 'add-pending', headSha: selection.source.headSha, comment: { path, side, startLine, endLine, body } }) + } + // Only the whole change request takes new comments for its pending review, once the threads say the user may review. + const pendingComments = data?.kind === 'change' && data.commits === null && review?.viewerCanReview === true ? { queue: addPending } : {} + const recordActions: ReviewActions = { source: shownSource ?? (source.kind === 'local' ? { kind: 'local', scope, base: null, baseRef: baseRefOf(localScope), commits: commitsOf(localScope) } @@ -718,6 +800,11 @@ export function ChangesTab({ readText: (commit, path) => changeRequestText(data.url, commit, path), inputFailed: () => { report('thread.inputFailed') }, focused: focus, + writes: { + write: (write: ThreadWrite) => writeReview(data.url, { ...write, headSha: review.headSha }), + reviewStarted: review.pendingReview !== null, + canReview: review.viewerCanReview, + }, } const threadsOf = (path: string): FileThreads | undefined => { const group = placed.files.get(path) @@ -869,11 +956,12 @@ export function ChangesTab({ file={file} review={{ source: reviewSourceOf(data), addToInput: addReviewToInput, - records: queue, openLink, reviewStarted: reviewState.comments.length > 0, + records: queue, openLink, reviewStarted: pendingReview !== null, onQuoted: (selection) => { if (!queue.recordAgent(selection)) report('review.saveFailed') }, publishingBlocked: reviewState.uncertain !== null, - ...data.kind === 'local' || data.commits !== null ? {} : { - queue: selection => queue.add(selection), + ...pendingComments, + // GitHub refuses a comment published on its own while the user has a pending review. + ...data.kind === 'local' || data.commits !== null || pendingReview !== null ? {} : { publish: selection => selection.source.kind === 'change' ? publishReview(selection.source.url, { kind: 'comment', headSha: selection.source.headSha, comment: selection.comment }, url => queue.published(selection, url)) @@ -939,7 +1027,8 @@ export function ChangesTab({ ? { actions.based(tab.id, next) }} commitMenu={commitMenu} createChangeRequest={createChangeRequest} t={t} /> - : { setReviewOpen(true) }} t={t} />} {!reviewOpen && reviewState.error !== null && {t(reviewState.error === 'load' ? 'review.loadFailed' : 'review.saveFailed')}} {!reviewOpen && reviewState.uncertain !== null && !reviewBusy && source.kind === 'change' &&
diff --git a/packages/experimental/client-ui-forge/src/client/ReviewComposer.tsx b/packages/experimental/client-ui-forge/src/client/ReviewComposer.tsx index 94407dfee8..82e482c35f 100644 --- a/packages/experimental/client-ui-forge/src/client/ReviewComposer.tsx +++ b/packages/experimental/client-ui-forge/src/client/ReviewComposer.tsx @@ -15,7 +15,7 @@ export interface ReviewActions { readonly source: ReviewSource /** Browser records shared by the changes tab. */ readonly records?: ReviewQueue - /** Whether another comment already started a pending review. */ + /** Whether the signed-in user has a pending review on the code host that the next comment joins. */ readonly reviewStarted?: boolean /** Open the confirmed publication URL. */ readonly openLink?: (url: string) => void @@ -27,26 +27,32 @@ export interface ReviewActions { readonly onQuoted?: (selection: ReviewSelection) => void /** Publish one comment; an error string preserves the editor. */ readonly publish?: (selection: ReviewSelection) => Promise - /** Keep one comment for the final review; false preserves the editor. */ - readonly queue?: (selection: ReviewSelection) => boolean + /** Add one comment to the pending review on the code host, starting one when needed; an error string preserves the editor. */ + readonly queue?: (selection: ReviewSelection) => Promise } -function GitHubAction({ disabled, busy, started, queue, publish, t }: PropsLocale & { +/** + * Render a primary action with an optional second action in its menu. + * @param props - the main action, the optional menu action, the menu's name, and availability. + * @returns the split button. + */ +export function SplitAction({ disabled, label, run, menuLabel, menu, other }: { readonly disabled: boolean - readonly busy: boolean - readonly started: boolean - readonly queue: () => void - readonly publish: (() => void) | undefined + readonly label: string + readonly run: () => void + /** Accessible name of the menu button. */ + readonly menuLabel: string + /** Label of the action in the menu, or undefined without one. */ + readonly other: string | undefined + readonly menu: () => void }): ReactNode { const [open, setOpen] = useState(false) return
- - {publish !== undefined && { setOpen(false) }} + + {other !== undefined && { setOpen(false) }} anchor={}> - { setOpen(false); publish() }}>{t('review.publish')} + aria-label={menuLabel} onClick={() => { setOpen(value => !value) }}>}> + { setOpen(false); menu() }}>{other} }
} @@ -73,13 +79,14 @@ export function ReviewComposer({ selection, actions, close, visible = true, spli useEffect(() => { input.current?.focus() }, []) const comment = (): ReviewSelection => ({ ...selection, comment: { ...selection.comment, body: body.current } }) const range = reviewRange(selection.comment) - const publish = async (): Promise => { - if (running.current || actions.publish === undefined) return + /** Send the comment to the code host, closing the form once it is taken and keeping its text otherwise. */ + const send = async (destination: ((selection: ReviewSelection) => Promise) | undefined): Promise => { + if (running.current || destination === undefined) return running.current = true setBusy(true) setError(null) try { - const failure = await actions.publish(comment()) + const failure = await destination(comment()) if (failure === undefined) close() else setError(failure) } catch (_error) { @@ -108,14 +115,12 @@ export function ReviewComposer({ selection, actions, close, visible = true, spli if (actions.addToInput(selected)) { actions.onQuoted?.(selected); close() } else setError(t('review.inputFailed')) }}>{t('review.addToInput')} - {visible && actions.queue !== undefined && { - if (actions.queue?.(comment()) === true) close() - else setError(t('review.saveFailed')) - }} publish={actions.publish === undefined ? undefined : () => { void publish() }} t={t} />} + {visible && actions.queue !== undefined && { void send(actions.queue) }} menuLabel={t('review.githubActions')} + other={actions.publish === undefined ? undefined : t('review.publish')} menu={() => { void send(actions.publish) }} />} {actions.queue === undefined && actions.publish !== undefined && } + disabled={busy || actions.publishingBlocked === true || empty} onClick={() => { void send(actions.publish) }}>{t('review.publish')}}
diff --git a/packages/experimental/client-ui-forge/src/client/ReviewThread.tsx b/packages/experimental/client-ui-forge/src/client/ReviewThread.tsx index f626c2dc47..7abb3a7f67 100644 --- a/packages/experimental/client-ui-forge/src/client/ReviewThread.tsx +++ b/packages/experimental/client-ui-forge/src/client/ReviewThread.tsx @@ -1,4 +1,4 @@ -/** Inline comment records and editing of a pending review at its captured code location. */ +/** Inline comment records and the editing of comment drafts kept in the browser at their captured code location. */ import { useCallback, useState, useSyncExternalStore, type ReactNode } from 'react' import { Button, Tag } from '@deepseek-ai/dsh-client-ui-primitives' @@ -24,7 +24,8 @@ export function useFileReview(actions: ReviewActions | undefined, path: string): } /** - * Render a saved comment at its line, with pending edits kept in the browser queue. + * Render a saved comment at its line. A comment draft kept in the browser can be edited, deleted, or moved into the + * pending review on the code host. * @param props - record, edit availability, source actions, and localized copy. * @returns one compact inline comment card. */ @@ -38,11 +39,27 @@ export function ReviewThread({ thread, actions, locked, outdated, split, t }: Pr const [editing, setEditing] = useState(false) const [body, setBody] = useState(thread.selection.comment.body) const [error, setError] = useState(null) + const [moving, setMoving] = useState(false) const comment = thread.selection.comment const quoted = editing && thread.kind === 'pending' ? { ...thread.selection, comment: { ...comment, body } } : thread.selection const range = reviewRange(comment) - const status = thread.kind === 'pending' ? 'review.pending' : thread.kind === 'published' ? 'review.published' : 'review.quoted' + const status = thread.kind === 'pending' ? 'review.browserDraft' : thread.kind === 'published' ? 'review.published' : 'review.quoted' const save = (): boolean => actions.records?.editThread(thread.key, body) === true + const queue = actions.queue + /** Add the draft to the pending review on the code host, then delete it from the browser. */ + const move = async (add: NonNullable): Promise => { + setMoving(true) + setError(null) + try { + const failure = await add(thread.selection) + if (failure !== undefined) setError(failure) + else if (actions.records?.editThread(thread.key, null) !== true) setError(t('review.saveFailed')) + } catch (_error) { + setError(t('review.unknown')) + } finally { + setMoving(false) + } + } return
@@ -65,13 +82,15 @@ export function ReviewThread({ thread, actions, locked, outdated, split, t }: Pr }}>{t('review.addToInput')} {thread.kind === 'pending' && <> {editing - ? - : } - } + + {queue !== undefined && !editing && !outdated && } } {thread.kind === 'published' && actions.openLink !== undefined && }
diff --git a/packages/experimental/client-ui-forge/src/client/ReviewThreads.module.css b/packages/experimental/client-ui-forge/src/client/ReviewThreads.module.css index b84b5a8428..046ba7baad 100644 --- a/packages/experimental/client-ui-forge/src/client/ReviewThreads.module.css +++ b/packages/experimental/client-ui-forge/src/client/ReviewThreads.module.css @@ -151,6 +151,84 @@ margin: 10px -8px -4px; } +/* A reply or a comment edit uses the inline review form's field; its actions sit under it like the form's. */ +.form { margin-top: 10px; } + +.formActions { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: flex-end; + gap: 8px; + margin-top: 8px; +} + +/* The collapsed reply field, a field-shaped button that opens the reply form. */ +.replyPrompt { + display: block; + box-sizing: border-box; + width: 100%; + min-height: 32px; + margin-top: 10px; + padding: 6px 12px; + border: 0.5px solid var(--dsw-alias-border-l4); + border-radius: var(--dsw-radius-md); + background: var(--dsw-alias-bg-layer-3); + color: var(--dsw-alias-label-dimmed); + font: inherit; + text-align: start; + cursor: text; +} + +.replyPrompt:focus-visible { + outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); + outline-offset: 2px; +} + +.menuAnchor { display: inline-flex; flex: none; } + +/* The comment menu's icon button keeps the 20px row height of the header it ends. */ +.icon { + display: inline-flex; + align-items: center; + justify-content: center; + width: 20px; + height: 20px; + padding: 0; + border: 0; + border-radius: var(--dsw-radius-xs); + background: transparent; + color: var(--dsw-alias-label-secondary); + cursor: pointer; +} + +.icon[aria-expanded="true"] { background: var(--dsw-alias-interactive-bg-hover); color: var(--dsw-alias-label-primary); } + +.icon:focus-visible { + outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); + outline-offset: 1px; +} + +@media (hover: hover) { + .icon:hover { background: var(--dsw-alias-interactive-bg-hover); color: var(--dsw-alias-label-primary); } +} + +/* Confirming a deletion replaces nothing: the comment stays readable above the question. */ +.confirm { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + margin-top: 8px; +} + +.confirmText { flex: 1 1 auto; min-width: 0; color: var(--dsw-alias-label-secondary); overflow-wrap: anywhere; } + +.confirmError, +.actionError { flex-basis: 100%; margin-top: 0; } + +.actionError { padding-inline: 8px; } + /* The end of the recorded hunk, drawn like the diff rows it came from. */ .excerpt, .original { diff --git a/packages/experimental/client-ui-forge/src/client/ReviewThreads.tsx b/packages/experimental/client-ui-forge/src/client/ReviewThreads.tsx index 02cf0c8fae..feedfe071b 100644 --- a/packages/experimental/client-ui-forge/src/client/ReviewThreads.tsx +++ b/packages/experimental/client-ui-forge/src/client/ReviewThreads.tsx @@ -1,23 +1,44 @@ /** - * Read-only review threads of a change request inside the changes view: a thread card at its lines or at the top of - * its file, a resolved thread folded into one row, and the outdated threads of a file in a section after its lines. + * Review threads of a change request inside the changes view: a thread card at its lines or at the top of its file, a + * resolved thread folded into one row, and the outdated threads of a file in a section after its lines. A card offers + * the writes the signed-in user may make: a reply, published at once or added to the pending review, resolving or + * unresolving the thread, and editing or deleting the user's own comments. */ import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react' import clsx from 'clsx' import { - Button, IconCheckOutlineRegular, IconChevronDownOutlineRegular, IconRightUpOutlineRegular, MarkdownText, Tag, type MarkdownLabels, + Button, IconCheckOutlineRegular, IconChevronDownOutlineRegular, IconEllipsisOutlineRegular, IconRightUpOutlineRegular, MarkdownText, + Menu, Tag, Tooltip, type MarkdownLabels, } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' -import type { ForgeReviewComment, ForgeReviewThread, ForgeThreadId } from '@deepseek-ai/dsh-experimental-forge/types' +import type { ForgeReviewComment, ForgeReviewThread, ForgeReviewWrite, ForgeThreadId } from '@deepseek-ai/dsh-experimental-forge/types' import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' import { formatAgo } from './format.ts' import { anchorRange, hunkExcerpt, type ThreadPlace } from './review-threads.ts' +import { SplitAction } from './ReviewComposer.tsx' import type { NS } from './locales.ts' import css from './ReviewThreads.module.css' +import composerCss from './ReviewComposer.module.css' type Translate = PropsLocale['t'] +/** Each member of a union without its `headSha`. */ +type WithoutHead = T extends unknown ? Omit : never + +/** A write to one thread or its comments, without the head commit the changes view adds. */ +export type ThreadWrite = WithoutHead> + +/** Writes the signed-in user can make to the threads of one changes view. */ +export interface ThreadWrites { + /** Send a write; resolves to the message to show, or undefined once the code host took it. */ + readonly write: (write: ThreadWrite) => Promise + /** Whether the user has a pending review, which every reply then joins. */ + readonly reviewStarted: boolean + /** Whether the user can add a reply to a pending review, starting one when needed. */ + readonly canReview: boolean +} + /** Reads, actions, and identities every thread card of one changes view shares. */ export interface ThreadActions { /** Login of the signed-in user, or null when the host names none. */ @@ -34,6 +55,8 @@ export interface ThreadActions { readonly inputFailed: () => void /** The latest jump to a thread, which unfolds that thread and its section until the reader folds them again; null before any. */ readonly focused: ThreadFocus | null + /** Writes the user can make, or null when the code host takes none from this view. */ + readonly writes: ThreadWrites | null } /** One jump to a thread; each jump has its own revision, so a jump to the same thread unfolds it again. */ @@ -97,14 +120,77 @@ export function Avatar({ author, size = 20 }: { readonly author: ForgeReviewComm } -function Comment({ comment, actions, labels, now, t }: { +/** Run one write at a time for a card section, keeping its error until the next attempt. */ +function useWriting(t: Translate): { + readonly busy: boolean + readonly error: string | null + readonly run: (send: () => Promise) => Promise +} { + const [busy, setBusy] = useState(false) + const [error, setError] = useState(null) + const running = useRef(false) + const run = async (send: () => Promise): Promise => { + if (running.current) return false + running.current = true + setBusy(true) + setError(null) + try { + const failure = await send() + setError(failure ?? null) + return failure === undefined + } catch (_error) { + setError(t('thread.writeUnknown')) + return false + } finally { + running.current = false + setBusy(false) + } + } + return { busy, error, run } +} + +/** A plain-text field with Cancel and the actions that send it, for a reply or a comment edit. */ +function TextForm({ label, initial, busy, error, cancel, children }: { + readonly label: string + readonly initial: string + readonly busy: boolean + readonly error: string | null + readonly cancel: { readonly label: string; readonly run: () => void } + /** The sending actions, given the current text and whether it is blank. */ + readonly children: (text: string, blank: boolean) => ReactNode +}): ReactNode { + const [text, setText] = useState(initial) + return
+