test(cua-macos): exercise recovered input targets and undispatched failures

This commit is contained in:
creatixchu committed 2026-11-12 17:06:35 +08:00
1 parent f4fe0d82d2
commit bfef6e3942
11 files changed
+268 -8

No files matched your search

@@ -15,8 +15,8 @@
en: 1777e7bf6785f986
zh: e3daac1074ebb74d
/deepseek-ai-dsh-cua-macos/use-this-package:
en: 845b7d3ae975db5d
zh: 06d823bbe64eea1a
en: 89d20cf0e1ef4225
zh: a1080670b7731cac
/deepseek-ai-dsh-cua-macos/use-this-package/connect-an-external-execution-environment:
en: 7058be5d1b778643
zh: 821de6b0ad7aba27
+1 -1
View File
@@ -91,7 +91,7 @@ Application consent is enforced before AX reads, window-title reads, screenshots
Raw `getState` exposes validated state fields and the complete text for the requested disclosure options. The native helper also returns structured element diagnostics with opaque string `elementId` values for native checks; the tool projection omits that duplicate array from model text and structured tool values.
AX observations show menu-bar entries by default. Use `app.getAccessibilityTree({ includeMenus: true })` to expand menu contents and `app.getAccessibilityTree({ details: true })` for identifiers, global-point bounds and complete action names. These options also apply to raw `getState`. Every read replaces the application's current snapshot; use element IDs from that read. Pass `maxElements` or `maxDepth` to override either configured limit for one read. Truncation identifies the reached limit. Unreadable children have separate markers in the tree and set the optional raw `hasUnreadableElements` flag.
AX observations show menu-bar entries by default. Use `app.getAccessibilityTree({ includeMenus: true })` to expand menu contents and `app.getAccessibilityTree({ details: true })` for identifiers, global-point bounds and complete action names. These options also apply to raw `getState`. Every read replaces the application's current snapshot; use element IDs from that read. Pass `maxElements` or `maxDepth` to override either configured limit for one read. Truncation identifies the reached limit. Unreadable children have separate markers in the tree and set the optional raw `hasUnreadableElements` flag. A marker beside an observed control does not prevent acting on that control by its element ID. When an action must search again, macOS recovers readable children using the same range reads as observation.
Values and placeholders are separate. Named, stateful or actionable groups and scroll areas retain their own rows. Repeated names, descriptions and help text on one node are shown once. Values, placeholders and URLs keep their distinct meanings even when their text matches; body text shared by distinct nodes remains intact. Writability is explicit on relevant controls, including `AXIncrementor`; `unknown` means the system did not report it. Missing optional state fields do not imply false. During tree observation, an AXValue or AXSelectedTextRange writability probe returning -25200 leaves that field unknown and preserves the remaining nodes. Actual writes remain strict; permission, communication and invalid-element errors still propagate. UTF-16 ranges outside the observed value are marked unavailable. Compact tree labels can omit AppKit target and selector details. Pass the exact name returned by `listActions(elementId)` to `performAction`.
+1 -1
View File
@@ -91,7 +91,7 @@ CUA 工具在读取 AX、窗口标题、截图、激活和输入前检查应用
原始 `getState` 操作返回经过校验的状态字段,以及按本次披露选项生成的完整文本。原生 helper 还返回供原生检查使用的结构化元素诊断数组,其中 `elementId` 是不透明字符串;工具投影会从模型文本和结构化工具值中移除这份重复数组。
AX 观察默认只展示菜单栏入口。使用 `app.getAccessibilityTree({ includeMenus: true })` 展开菜单内容,使用 `app.getAccessibilityTree({ details: true })` 读取标识符、全局 point 坐标和完整动作名。原始 `getState` 也接受这两个选项。每次读取都会替换应用当前的快照;应使用该次读取返回的元素 ID。传入 `maxElements` 或 `maxDepth` 可调整本次读取的上限。树被截断时会提示触发的上限。子项无法读取时,树中会标出缺失部分,原始结果会返回 `hasUnreadableElements: true`。
AX 观察默认只展示菜单栏入口。使用 `app.getAccessibilityTree({ includeMenus: true })` 展开菜单内容,使用 `app.getAccessibilityTree({ details: true })` 读取标识符、全局 point 坐标和完整动作名。原始 `getState` 也接受这两个选项。每次读取都会替换应用当前的快照;应使用该次读取返回的元素 ID。传入 `maxElements` 或 `maxDepth` 可调整本次读取的上限。树被截断时会提示触发的上限。子项无法读取时,树中会标出缺失部分,原始结果会返回 `hasUnreadableElements: true`。控件旁边有缺失提示时,仍可按该控件的元素 ID 操作。执行时需要重新查找目标的,macOS 会沿用读树时的分段读取方式找回可读子项。
实际值与占位文字分别展示。有名称、状态或可用动作的分组和滚动区域保留独立行。同一节点中重复的名称、描述和帮助只显示一次。实际值、占位文字和 URL 即使文字相同也保留各自含义,不删除不同节点共有的正文。相关控件明确展示可写性,包括 `AXIncrementor`;`unknown` 表示系统未报告。缺少可选状态字段不代表 false。读树时,AXValue 或 AXSelectedTextRange 的可写性探测返回 -25200,会将该字段保留为未知并继续读取其他节点。实际写入仍严格校验;权限、通信和失效元素错误仍向上传播。超出当前值长度的 UTF-16 选区标为不可用。树中的动作简称可能省略 AppKit 的 target 和 selector 信息。调用 `performAction` 时使用 `listActions(elementId)` 返回的完整名称。
@@ -21,8 +21,8 @@
en: a993e9eacf63cceb
zh: 12292c9ba53df2ad
/dsh-cua-native-helper/observation-and-input:
en: a41e41d4e83e0e7b
zh: d2bdfe14578fa548
en: 6847f691ef08cefc
zh: ded73323a20e8708
/dsh-cua-native-helper/verification:
en: 908b13b2732c1bec
zh: ac3bbd77ed9a69b8
@@ -97,6 +97,8 @@ Protocol declarations are generated from [the shared protocol](../../cua/src/pro
`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 window discovery completes and 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. If reading `AXChildren` returns -25200, the helper reads failed ranges of up to five children individually and halves larger failed ranges. Successful ranges retain their original order. An observation makes at most `maxElements` extra count and range reads. It stops starting recovery reads once recovery has spent `axTimeoutMs`. The overall request deadline is `timeoutMs`. An unreadable child has a marker in sibling order and no element ID. If positions are unknown, the tree marks the parent instead. Both cases set `hasUnreadableElements: true`. This field is omitted when all visited child lists were readable. Only a node or depth limit sets `truncated: true`. 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. Raw element targets require `appHandle`, `snapshotId` and an opaque string `elementId`. For `click` and `mouseMove`, the optional `windowId` must match both the snapshot scope (unless app-wide) and the element’s enclosing window or sheet. A mismatch returns `STALE_SNAPSHOT` before dispatch. Coordinate targets use `windowId`, `x` and `y` and may include a snapshot from that window or the app. Mixing an element ID with coordinates returns `INVALID_ARGUMENT`. The Host converts relative coordinates before dispatch, so the native JSONL protocol rejects the `relative` field. Native references never cross JSON. 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.
Input target discovery uses the same range recovery as observation. All recovery reads in a request share a count and time budget. Paste uses its configured node limit for the count. Window and panel routing use the native element ceiling. Window lookup checks top-level IDs before reading attached sheets. A matching owned window ID is sufficient even if another child is unreadable. Paste requires a complete search for a unique command. A system file panel can receive clicks or new keyboard input once its service process and window are confirmed. Incomplete searches return UNSUPPORTED for Paste, WINDOW_UNAVAILABLE for a window or sheet, or PANEL_NOT_READY for a panel recipient. These errors report that no input was dispatched and request a fresh observation.
Hiding a window does not itself expire its AX snapshot. An inventory refresh can retain the previous screenshot mapping only while the same window ID remains present at the same observed size. An observed size change requires a new screenshot for pixel input; a closed window cannot be targeted. Omission from discovery does not block input to a known ID: ownership, geometry and input checks still apply, and dispatch does not confirm receipt.
Clicks send mouse-down and mouse-up events at the element center or the supplied coordinates. Use `invoke` for the default AX action or `performAction` for a named action. Click, scroll and 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. 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.
@@ -97,6 +97,8 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后
`getState` 可将 AX 遍历限定到应用所属窗口或嵌套 sheet 的 `windowId`。新的刷新或失败的刷新使同一应用/窗口范围的旧快照失效,其他窗口范围仍可使用。窗口发现完成后,如果应用所属 CG 窗口没有匹配的 AX 界面,getState 返回空 tree/elements、truncated 为 false 的新快照,仍可截图和坐标输入。遍历后重新检查进程生命期、窗口归属、会话未锁定及辅助功能权限。窗口发现中的 APIDisabled 和通信错误仍会失败;不支持或缺失的可选 AX 属性可以产生空观察。不存在或属于其他应用的窗口不会返回空成功结果。读取 `AXChildren` 返回 -25200 时,helper 将读取失败且超过 5 项的范围对半拆分,5 项及以下的失败范围按下标逐项读取,成功的范围按原顺序保留。一次观察中的额外计数和范围读取合计不超过 `maxElements` 次。恢复累计耗时达到 `axTimeoutMs` 后停止发起新的恢复读取,整个请求受 `timeoutMs` 限制。树在不可读子项的原位置插入提示,不为提示分配元素 ID。无法确定位置时,在父节点处标记。两种情况都返回 `hasUnreadableElements: true`。已访问的子项列表全部可读时省略该字段。只有触及节点数或深度上限时才返回 `truncated: true`。遍历中 AX 元素失效会以 `STALE_SNAPSHOT` 拒绝整次读取,不发布部分树。应用变化后可以重新观察,但不重复输入。原生元素目标需要 `appHandle`、`snapshotId` 和字符串 `elementId`。`click` 和 `mouseMove` 可附带 `windowId`。它必须与元素所属窗口或 sheet 一致,对窗口级快照还必须与快照的窗口一致,否则在发送输入前返回 `STALE_SNAPSHOT`。坐标目标使用 `windowId`、`x`、`y`,可以附带来自该窗口或应用的快照。混用元素 ID 和坐标会返回 `INVALID_ARGUMENT`。Host 在发送请求前换算相对坐标,原生 JSONL 协议会拒绝 `relative` 字段。原生引用不跨 JSON 传递。刷新窗口列表会释放已关闭窗口的快照。进程身份、快照代次和窗口归属检查不会锁住桌面,用户或应用仍可同时改变状态。
执行时查找目标会沿用读树的范围恢复逻辑。同一请求中的恢复读取共用次数和时间预算。Paste 使用配置的节点数上限,窗口和面板使用原生协议的节点数上限。查窗口时先匹配顶层窗口 ID,再查附属 sheet。只要能确认窗口 ID 和归属,其他子项不可读也能选中目标。Paste 需要搜完整个菜单,确认命令唯一。系统文件面板需要确认接收进程和窗口才能派发点击或新的键盘输入。查找不完整时,Paste 返回 UNSUPPORTED,窗口或 sheet 返回 WINDOW_UNAVAILABLE,面板接收方返回 PANEL_NOT_READY。这些错误说明本次未派发输入,并提示重新观察。
窗口隐藏本身不会使 AX 快照失效。刷新清单时,只有同一窗口 ID 仍存在且观察到的尺寸未变,才能继续使用此前截图的像素坐标。观察到尺寸变化后需要重新截图;窗口销毁后不能继续操作。清单中省略窗口不会阻止按已知 ID 发起输入。窗口归属、尺寸和输入检查仍然生效,成功分派不代表应用已接收。
点击在元素中心或给定坐标发送鼠标按下和抬起事件。执行默认 AX 动作用 `invoke`,执行指定动作用 `performAction`。点击、滚动和拖动核实窗口归属和边界后,使用后台 PID/窗口定向输入。事件优先使用 SkyLight,不可用时使用公开的 PID 定向 API;已发送的事件不通过另一 API 重发。坐标是整个窗口左上角起算的 macOS point,包含标题栏。`deltaLinesY` 为正时显示上方内容,为负时显示下方内容;`deltaLinesX` 为正时显示左侧内容,为负时显示右侧内容。每个轴接受 -10 到 10 的整数,至少一个轴非零。helper 直接发送按行计量的滚轮事件。点击和拖动支持左、右、中键及 command/control/option/shift/fn 修饰键,只有左键支持双击。拖动在一个窗口中完成一次按下、移动、抬起,调用方显式提供 durationMs(1..5000)和 steps(1..240)。移动延迟按小数精度分配到各段,按下和抬起的固定等待及调度延迟另计。不存在隐式改用全局桌面输入的后备路径。
@@ -5,9 +5,14 @@ import ApplicationServices
@MainActor private final class ChildFixtureWindow: NSWindow {
var childList: [Any]?
var pressed: [String] = []
var inputLog: URL?
override func accessibilityChildren() -> [Any]? { childList ?? super.accessibilityChildren() }
@objc func press(_ sender: NSButton) { pressed.append(sender.title) }
@objc func press(_ sender: NSButton) {
pressed.append(sender.title)
if sender.title == "Identify as open panel" { setAccessibilityIdentifier("open-panel") }
if let inputLog { try! JSONEncoder().encode(pressed).write(to: inputLog, options: .atomic) }
}
func button(_ title: String) -> NSButton {
let button = NSButton(title: title, target: self, action: #selector(press(_:)))
@@ -26,6 +31,8 @@ import ApplicationServices
return window
}
let good = makeWindow(), bad = makeWindow()
good.title = "Healthy target"
bad.title = "Partial target"
defer { bad.close(); good.close() }
good.childList = [good.button("Healthy window")]
let before = bad.button("Before gap"), after = bad.button("After gap")
@@ -39,6 +46,27 @@ import ApplicationServices
bad.orderBack(nil)
app.finishLaunching()
if let path = CommandLine.arguments.dropFirst().first {
bad.inputLog = URL(fileURLWithPath: path)
before.frame = NSRect(x: 10, y: 15, width: 100, height: 28)
after.frame = NSRect(x: 120, y: 55, width: 100, height: 28)
bad.childList?.append(bad.button("Identify as open panel"))
app.setActivationPolicy(.regular)
bad.makeKeyAndOrderFront(nil)
app.activate(ignoringOtherApps: true)
let monitor = NSEvent.addLocalMonitorForEvents(matching: [.keyDown, .keyUp, .leftMouseDown]) { event in
if bad.pressed.contains("Identify as open panel") {
bad.pressed.append("Unexpected input")
try! JSONEncoder().encode(bad.pressed).write(to: URL(fileURLWithPath: path), options: .atomic)
}
return event
}
defer { if let monitor { NSEvent.removeMonitor(monitor) } }
print("READY"); fflush(stdout)
app.run()
return
}
let access = AXAccess(timeout: 3, cancellation: CancellationLatch())
let identity = try NativePlatform.identity(getpid())
func project(_ window: NSWindow, depth: Int = 12) throws -> AXProjection {
@@ -87,7 +115,33 @@ import ApplicationServices
let uncertain = try project(bad)
try check(uncertain.hasUnreadableElements && !uncertain.truncated && uncertain.indexed.isEmpty,
"Partial window discovery must not expose controls from another window")
print("Passed real AX range recovery, sibling actions, window scoping and independent observation flags.")
let goodID = UInt32(good.windowNumber), badID = UInt32(bad.windowNumber)
app.setAccessibilityWindows([good, bad])
var exhausted = AXChildRecoveryBudget(maxElements: 0, timeout: 0)
let exact = try access.windowElement(badID, owner: identity, budget: &exhausted)
try check(exact == badRoot, "An earlier window's unreadable children blocked an exact ID")
app.setAccessibilityWindows([good])
bad.setAccessibilityRole(.sheet)
for children: [Any] in [[bad, NSNull()], [NSNull(), bad]] {
good.childList = children
var budget = AXChildRecoveryBudget(maxElements: 16, timeout: 3)
let sheet = try access.windowElement(badID, owner: identity, budget: &budget)
try check(sheet == badRoot && budget.requests < 16, "A recovered sheet was lost at the gap")
let left = budget.requests
_ = try access.windowElement(goodID, owner: identity, budget: &budget)
try check(budget.requests == left, "An exact window consumed additional recovery requests")
for (requests, time): (Int, Float) in [(1, 3), (16, 0)] {
var insufficient = AXChildRecoveryBudget(maxElements: requests, timeout: time)
do {
_ = try access.windowElement(badID, owner: identity, budget: &insufficient)
throw NativeFailure(code: "FIXTURE", message: "Unseen sheet accepted after recovery exhausted")
} catch let failure as NativeFailure where failure.code == "WINDOW_UNAVAILABLE" {
try check(failure.message.contains("No input was dispatched. Read fresh state"), failure.message)
}
}
}
print("Passed AX range recovery, sibling actions, exact window and recovered sheet selection, and recovery budgets.")
}
private static func check(_ condition: Bool, _ message: String) throws {
@@ -1,5 +1,6 @@
// Each clipboard case owns a named pasteboard rather than touching the user's clipboard.
import AppKit
import ApplicationServices
import Foundation
import Testing
@testable import CuaNative
@@ -134,3 +135,42 @@ import Testing
} catch let error as NativeFailure { #expect(error.code == "UNSUPPORTED") }
#expect(board.string(forType: .string) == "original")
}
/// Search and clipboard transaction run together. The synthetic menu owns no desktop input.
@Test @MainActor func pasteRequiresOneCommandAcrossAllRecoveredBranches() async throws {
let root = AXUIElementCreateApplication(10)
let first = AXUIElementCreateApplication(11)
let other = AXUIElementCreateApplication(12)
let cases: [(AXObservedChildren, Set<AXUIElement>, String?)] = [
(.init(entries: [first, other]), [first], nil),
(.init(entries: [other, first, first]), [first], nil),
(.init(entries: [first, nil]), [first], "incomplete"),
(.init(entries: [nil, first]), [first], "incomplete"),
(.init(entries: [first, nil, other]), [first, other], "ambiguous"),
(.init(entries: [first], parentIncomplete: true), [first], "incomplete"),
(.init(entries: [first], elementLimitReached: true), [first], "incomplete"),
]
for (list, commands, reason) in cases {
let board = NSPasteboard.withUniqueName()
defer { board.releaseGlobally() }
#expect(board.setString("original", forType: .string))
var received: [AXUIElement] = []
do {
try await ClipboardPaste(pasteboard: board).perform(text: "payload", format: "text", maxBytes: 1024,
readTimeout: .seconds(1)) { ownership in
let command = try AXAccess.pasteCommand(in: root, maxElements: 10, maxDepth: 2,
matches: commands.contains, children: { $0 == root ? list : .init() })
try ownership()
received.append(command)
#expect(board.string(forType: .string) == "payload")
}
#expect(reason == nil)
} catch let error as NativeFailure {
#expect(error.code == "UNSUPPORTED")
#expect(error.message.contains(try #require(reason)))
#expect(error.message.contains("No input was dispatched. Read fresh state"))
}
#expect(received == (reason == nil ? [first] : []))
#expect(board.string(forType: .string) == "original")
}
}
@@ -1,10 +1,67 @@
"""Run the production AX projection on an isolated AppKit process's own windows."""
import argparse
import json
import subprocess
import tempfile
import time
from pathlib import Path
from native_test_support import NativeHelper, line, run_cleanup, stop
def check_input(executable, helper_path, root):
log = root / "presses.json"
target = subprocess.Popen([str(executable), str(log)], stdout=subprocess.PIPE, text=True)
helper = None
try:
assert line(target).strip() == "READY"
helper = NativeHelper([], helper_path)
owner = {"appHandle": helper.call("getApp", {"selector": str(target.pid)})["appHandle"]}
helper.call("activate", owner)
windows = helper.call("listWindows", owner)
partial = next(window for window in windows if window["title"] == "Partial target")
scoped = {**owner, "windowId": partial["windowId"]}
def observe():
return helper.call("getState", {**scoped, "maxElements": 1000, "maxDepth": 12})
def button(state, title):
match = next(item for item in state["elements"] if item["title"] == title and item["role"] == "AXButton")
return {**scoped, "snapshotId": state["snapshotId"], "elementId": match["elementId"]}
def wait_presses(expected):
deadline = time.monotonic() + 5
while not log.exists() or json.loads(log.read_text()) != expected:
assert time.monotonic() < deadline, (expected, log.read_text() if log.exists() else [])
time.sleep(0.025)
state = observe()
assert state["hasUnreadableElements"]
expected = []
for title in ["Before gap", "After gap"]:
assert helper.call("click", button(state, title)) == {"dispatched": True}
expected.append(title)
wait_presses(expected)
panel = "Identify as open panel"
assert helper.call("invoke", button(state, panel)) == {"dispatched": True}
expected.append(panel)
wait_presses(expected)
state = observe()
assert state["focusedWindowId"] == partial["windowId"]
assert any(item["identifier"] == "open-panel" for item in state["elements"])
for method, params in [("click", button(state, "Before gap")),
("click", {**scoped, "x": 20, "y": 40}),
("typeText", {**owner, "text": "a"}),
("pressKey", {**owner, "key": "a"}),
("sendKeyEvent", {**owner, "key": "a", "direction": "down", "runId": "fixture"})]:
failure = helper.call(method, params, "PANEL_NOT_READY")
assert failure["message"] == "File panel recipient discovery is incomplete. No input was dispatched. Read fresh state before retrying.", failure
assert json.loads(log.read_text()) == expected
print("Passed two observed sibling clicks and pre-dispatch rejection of pointer and keyboard input to an incomplete panel.")
finally:
run_cleanup(*([helper.stop] if helper else []), lambda: stop(target))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--helper", type=Path, help="Exercise click and keyboard dispatch through this signed helper")
args = parser.parse_args()
tests = Path(__file__).resolve().parent
sources = sorted((tests.parent / "Sources" / "CuaNative").glob("*.swift"))
with tempfile.TemporaryDirectory(prefix="ax-child-projection-") as temporary:
@@ -13,6 +70,8 @@ def main():
*[str(source) for source in sources if source.name != "Main.swift"],
str(tests / "ChildProjectionFixture.swift"), "-o", str(executable)], check=True)
subprocess.run([str(executable)], check=True, timeout=30)
if args.helper:
check_input(executable, args.helper, Path(temporary))
if __name__ == "__main__":
@@ -2111,6 +2111,105 @@
}
]
},
{
"kind": "chunks",
"chunks": [
{
"type": "block-start",
"index": 0,
"blockType": "tool-call"
},
{
"type": "block-end",
"index": 0,
"block": {
"type": "tool-call",
"id": "cua-incomplete-targets",
"name": "cua",
"arguments": "{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F6\"}}"
}
},
{
"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-incomplete-menu",
"name": "cua",
"arguments": "{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture\"}}"
}
},
{
"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-incomplete-panel",
"name": "cua",
"arguments": "{\"method\":\"typeText\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture\"}}"
}
},
{
"type": "usage",
"usage": {
"inputTokens": 3,
"outputTokens": 3
}
},
{
"type": "finish",
"reason": {
"kind": "tool-calls"
}
}
]
},
{
"kind": "chunks",
"chunks": [
@@ -125,6 +125,7 @@ function createApplicationState(socket, record, application, captureBroker, conn
let generation = 0
let observationChanged = false
let malformedScreenshot = false
let incompleteInputTargets = false
function refuse(code, message) { throw Object.assign(new Error(message), { code }) }
function call(requestId, method, params) {
record('call', { requestId, method, params })
@@ -243,6 +244,8 @@ function createApplicationState(socket, record, application, captureBroker, conn
}
if (method === 'pressKey' && params.key === 'Return') observationChanged = true
// Fixture-only keys simulate a pending system callback and its eventual completion.
if (method === 'pressKey' && params.key === 'F6') incompleteInputTargets = true
if (incompleteInputTargets && method === 'typeText') refuse('PANEL_NOT_READY', 'File panel recipient discovery is incomplete. No input was dispatched. Read fresh state before retrying.')
if (method === 'pressKey' && params.key === 'F8') application.panelVisibility = 'visible'
if (method === 'pressKey' && params.key === 'F7' && application.panelVisibility !== 'closed') application.panelVisibility = 'hidden'
if (method === 'pressKey' && params.key === 'F11') captureBroker.pendingCapture = true
@@ -250,6 +253,7 @@ function createApplicationState(socket, record, application, captureBroker, conn
if (method === 'pressKey' && params.key === 'F12') malformedScreenshot = true
if (method === 'pressKey' && params.key === 'F9') { application.frontPid = 42; application.frontWindowId = '99' }
if (method === 'paste') {
if (incompleteInputTargets) refuse('UNSUPPORTED', 'Paste menu discovery is incomplete. No input was dispatched. Read fresh state before retrying.')
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
return { dispatched: true }