fix(cua-macos): recover readable AX children by range

This commit is contained in:
creatixchu committed 2026-11-12 13:16:51 +08:00
1 parent 8d9c78459c
commit 037410b5d7
9 files changed
+165 -19

No files matched your search

@@ -21,8 +21,8 @@
en: 21d92283c084d8bb
zh: 7a29731b9f58c709
/dsh-cua-native-helper/observation-and-input:
en: a1de529f35c130d4
zh: ec19b62804df2264
en: 70f4d9992b3f052c
zh: 3fec0fbfb8274ca0
/dsh-cua-native-helper/verification:
en: 908b13b2732c1bec
zh: ac3bbd77ed9a69b8
@@ -95,7 +95,7 @@ Protocol declarations are generated from [the shared protocol](../../cua/src/pro
<a id="observation-and-input"></a>
## 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. 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.
`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 child ranges and splits failing ranges to retain readable siblings in order. Recovery shares a budget of `maxElements` extra AX requests across the observation. Missing children are marked in the tree and set `truncated` to 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.
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.
@@ -95,7 +95,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后
<a id="observation-and-input"></a>
## 观察与输入
`getState` 可将 AX 遍历限定到应用所属窗口或嵌套 sheet 的 `windowId`。新的刷新或失败的刷新使同一应用/窗口范围的旧快照失效,其他窗口范围仍可使用。应用所属 CG 窗口没有匹配 AX 界面时,getState 返回空 tree/elements、truncated 为 false 的新快照,仍可截图和坐标输入。遍历后重新检查进程生命期、窗口归属、会话未锁定及辅助功能权限。窗口发现中的 APIDisabled 和通信错误仍会失败;不支持或缺失的可选 AX 属性可以产生空观察。不存在或属于其他应用的窗口不会返回空成功结果。遍历中 AX 元素失效会以 `STALE_SNAPSHOT` 拒绝整次读取,不发布部分树。应用变化后可以重新观察,但不重复输入。原生元素目标需要 `appHandle`、`snapshotId` 和字符串 `elementId`。`click` 和 `mouseMove` 可附带 `windowId`。它必须与元素所属窗口或 sheet 一致,对窗口级快照还必须与快照的窗口一致,否则在发送输入前返回 `STALE_SNAPSHOT`。坐标目标使用 `windowId`、`x`、`y`,可以附带来自该窗口或应用的快照。混用元素 ID 和坐标会返回 `INVALID_ARGUMENT`。Host 在发送请求前换算相对坐标,原生 JSONL 协议会拒绝 `relative` 字段。原生引用不跨 JSON 传递。刷新窗口列表会释放已关闭窗口的快照。进程身份、快照代次和窗口归属检查不会锁住桌面,用户或应用仍可同时改变状态。
`getState` 可将 AX 遍历限定到应用所属窗口或嵌套 sheet 的 `windowId`。新的刷新或失败的刷新使同一应用/窗口范围的旧快照失效,其他窗口范围仍可使用。窗口发现完成后,如果应用所属 CG 窗口没有匹配的 AX 界面,getState 返回空 tree/elements、truncated 为 false 的新快照,仍可截图和坐标输入。遍历后重新检查进程生命期、窗口归属、会话未锁定及辅助功能权限。窗口发现中的 APIDisabled 和通信错误仍会失败;不支持或缺失的可选 AX 属性可以产生空观察。不存在或属于其他应用的窗口不会返回空成功结果。读取 `AXChildren` 返回 -25200 时,helper 按范围读取子项并拆分失败的范围,按原顺序保留可读的子项。一次观察中的恢复操作最多额外调用 `maxElements` 次 AX 接口。树会标出未读到的子项,并将 `truncated` 设为 true。遍历中 AX 元素失效会以 `STALE_SNAPSHOT` 拒绝整次读取,不发布部分树。应用变化后可以重新观察,但不重复输入。原生元素目标需要 `appHandle`、`snapshotId` 和字符串 `elementId`。`click` 和 `mouseMove` 可附带 `windowId`。它必须与元素所属窗口或 sheet 一致,对窗口级快照还必须与快照的窗口一致,否则在发送输入前返回 `STALE_SNAPSHOT`。坐标目标使用 `windowId`、`x`、`y`,可以附带来自该窗口或应用的快照。混用元素 ID 和坐标会返回 `INVALID_ARGUMENT`。Host 在发送请求前换算相对坐标,原生 JSONL 协议会拒绝 `relative` 字段。原生引用不跨 JSON 传递。刷新窗口列表会释放已关闭窗口的快照。进程身份、快照代次和窗口归属检查不会锁住桌面,用户或应用仍可同时改变状态。
窗口隐藏本身不会使 AX 快照失效。刷新清单时,只有同一窗口 ID 仍存在且观察到的尺寸未变,才能继续使用此前截图的像素坐标。观察到尺寸变化后需要重新截图;窗口销毁后不能继续操作。清单中省略窗口不会阻止按已知 ID 发起输入。窗口归属、尺寸和输入检查仍然生效,成功分派不代表应用已接收。
@@ -53,9 +53,9 @@ final class AXAccess {
let error = AXUIElementSetMessagingTimeout(element, timeout)
guard error == .success else { throw failure(error, "set AX messaging timeout") }
}
func failure(_ error: AXError, _ operation: String) -> NativeFailure {
func failure(_ error: AXError, _ operation: String, attribute: String? = nil) -> NativeFailure {
NativeFailure(code: error == .apiDisabled ? "PERMISSION_DENIED" : "NATIVE_ERROR",
message: "Accessibility \(operation) failed with error \(error.rawValue)", accessibilityError: error.rawValue)
message: "Accessibility \(operation) failed with error \(error.rawValue)", accessibilityError: error.rawValue, attribute: attribute)
}
private func absent(_ error: AXError) -> Bool { error == .attributeUnsupported || error == .noValue || error == .notImplemented }
static func optionalAttributeUnavailable(_ error: AXError, attribute: String) -> Bool {
@@ -71,7 +71,7 @@ final class AXAccess {
var value: CFTypeRef?
let error = AXUIElementCopyAttributeValue(element, name as CFString, &value)
if absent(error) || Self.optionalAttributeUnavailable(error, attribute: name) { return nil }
guard error == .success else { throw failure(error, "read \(name)") }
guard error == .success else { throw failure(error, "read \(name)", attribute: name) }
guard let value else { throw NativeFailure(code: "NATIVE_ERROR", message: "Accessibility \(name) returned no value after success") }
return value
}
@@ -118,6 +118,26 @@ final class AXAccess {
}
return try array.map { try elementValue($0, name) }
}
private func recoverChildren(_ element: AXUIElement, limit: Int, requests: inout Int) throws -> AXObservedChildren {
guard requests > 0 else { return .unavailable }
requests -= 1
try prepare(element)
var count = 0
let error = AXUIElementGetAttributeValueCount(element, kAXChildrenAttribute as CFString, &count)
if absent(error) || error == .failure { return .unavailable }
guard error == .success else { throw failure(error, "count AXChildren") }
return try AXObservedChildren.readRanges(count: count, limit: limit, requests: &requests) { range in
try prepare(element)
var values: CFArray?
let error = AXUIElementCopyAttributeValues(element, kAXChildrenAttribute as CFString,
range.lowerBound, range.count, &values)
if error == .failure { return .unreadable }
if absent(error) || error == .illegalArgument { return .unavailable }
guard error == .success else { throw failure(error, "read AXChildren range") }
guard let values, CFArrayGetCount(values) == range.count else { return .unavailable }
return .values(try childValues(values, attribute: "AXChildren"))
}
}
func windowID(_ element: AXUIElement) throws -> UInt32? {
try prepare(element)
guard let windowFunction else { return nil }
@@ -515,7 +535,7 @@ final class AXAccess {
if error == .attributeUnsupported || error == .noValue || error == .notImplemented
|| optionalAttributeUnavailable(error, attribute: name) { return nil }
throw NativeFailure(code: error == .apiDisabled ? "PERMISSION_DENIED" : "NATIVE_ERROR",
message: "Accessibility read \(name) failed with error \(error.rawValue)", accessibilityError: error.rawValue)
message: "Accessibility read \(name) failed with error \(error.rawValue)", accessibilityError: error.rawValue, attribute: name)
}
}
return value
@@ -545,7 +565,20 @@ final class AXAccess {
func project(identity: ProcessIdentity, windowID requested: UInt32?, maxElements: Int, maxDepth: Int, includeMenus: Bool = false, details: Bool = false) throws -> AXProjection {
let app = AXUIElementCreateApplication(identity.pid)
try enableAX(app, identity: identity)
var roots = try children(app)
var recoveryRequests = maxElements
// Window discovery and traversal can both enumerate the same parent.
var discovery: [AXUIElement: AXObservedChildren] = [:]
func observedChildren(_ parent: AXUIElement, _ value: @autoclosure () throws -> CFTypeRef?, duringDiscovery: Bool = false) throws -> AXObservedChildren {
if let cached = discovery[parent] { return cached }
do {
return try AXObservedChildren(elements: childValues(value(), attribute: "AXChildren"), incomplete: false)
} catch let error as NativeFailure where error.attribute == "AXChildren" && error.accessibilityError == AXError.failure.rawValue {
let children = try recoverChildren(parent, limit: maxElements, requests: &recoveryRequests)
if duringDiscovery { discovery[parent] = children }
return children
}
}
var roots = try observedChildren(app, attribute(app, "AXChildren"), duringDiscovery: true).elements
func appendUnique(_ element: AXUIElement) {
if !roots.contains(where: { CFEqual($0, element) }) { roots.append(element) }
}
@@ -558,7 +591,7 @@ final class AXAccess {
cursor += 1
let role = try string(root, "AXRole")
guard role == "AXWindow" || role == "AXSheet" else { continue }
for child in try children(root) where roots.count < maxElements {
for child in try observedChildren(root, attribute(root, "AXChildren"), duringDiscovery: true).elements where roots.count < maxElements {
if try string(child, "AXRole") == "AXSheet" { appendUnique(child) }
}
}
@@ -577,6 +610,7 @@ final class AXAccess {
}
if matches.isEmpty {
_ = try NativePlatform.ownedWindow(identity.pid, requested)
if discovery.values.contains(where: \.incomplete) { throw failure(.failure, "locate window in incomplete AXChildren") }
return AXProjection(tree: "", elements: [], indexed: [:], focusedWindowID: focusedID, truncated: false)
}
let dialog = try matches.contains { root in
@@ -592,17 +626,26 @@ final class AXAccess {
}
if !dialog { roots.append(contentsOf: anonymousSheets) }
}
if roots.isEmpty && discovery[app]?.incomplete == true { throw failure(.failure, "read application AXChildren") }
var visited: [CFHashCode: [AXUIElement]] = [:]
var count = 0
var elementLimitReached = false
var depthLimitReached = false
var unreportedParents = Set(discovery.compactMap { $0.value.incomplete ? $0.key : nil })
var childrenMissing = !unreportedParents.isEmpty
var menusCollapsed = false
var lines = ["AX scope=\(requested == nil ? "application" : "window") offsets=UTF-16\(details ? " bounds=global-points" : "")"]
var elements: [JSONValue] = []
var indexed: [Int: AXUIElement] = [:]
var pending = roots.reversed().map { (element: $0, level: 0, depth: 0) }
func enqueueChildren(_ children: [AXUIElement], level: Int, depth: Int) {
for child in children.reversed() { pending.append((child, level, depth)) }
func enqueueChildren(_ parent: AXUIElement, observation: AXNodeObservation, level: Int, depth: Int) throws {
let children = try observedChildren(parent, observation.attribute("AXChildren"))
if children.incomplete {
childrenMissing = true
unreportedParents.remove(parent)
lines.append(String(repeating: " ", count: level) + "[Some children of " + observation.role + " could not be read.]")
}
for child in children.elements.reversed() { pending.append((child, level, depth)) }
}
while let (element, level, depth) = pending.popLast() {
try cancellation.check()
@@ -644,7 +687,7 @@ final class AXAccess {
identifier: identifier, url: url, focused: focused, expanded: expanded)
node.validateSelection()
if node.transparent || (!addressable && !node.hasMeaning && role != "AXWindow" && role != "AXSheet") {
enqueueChildren(try childValues(observed("AXChildren"), attribute: "AXChildren"), level: level, depth: depth + 1)
try enqueueChildren(element, observation: observation, level: level, depth: depth + 1)
continue
}
let index: Int? = addressable ? indexed.count : nil
@@ -669,12 +712,13 @@ final class AXAccess {
]))
}
if role == "AXMenuBarItem" && !includeMenus { menusCollapsed = true; continue }
enqueueChildren(try childValues(observed("AXChildren"), attribute: "AXChildren"), level: level + 1, depth: depth + 1)
try enqueueChildren(element, observation: observation, level: level + 1, depth: depth + 1)
}
if menusCollapsed { lines.append("Menu contents omitted; request includeMenus=true to expand.") }
let truncated = elementLimitReached || depthLimitReached
if truncated { lines.append(AXTextFormatter.truncation(maxElements: elementLimitReached ? maxElements : nil, maxDepth: depthLimitReached ? maxDepth : nil)) }
return AXProjection(tree: lines.joined(separator: "\n"), elements: elements, indexed: indexed, focusedWindowID: focusedID, truncated: truncated)
if !unreportedParents.isEmpty { lines.append("[Some children could not be read during window discovery.]") }
return AXProjection(tree: lines.joined(separator: "\n"), elements: elements, indexed: indexed, focusedWindowID: focusedID, truncated: truncated || childrenMissing)
}
func enclosingWindow(_ element: AXUIElement) throws -> (element: AXUIElement, id: UInt32) {
@@ -0,0 +1,44 @@
// Range reads recover siblings when one child prevents macOS from returning the entire AXChildren array.
import ApplicationServices
struct AXObservedChildren {
let elements: [AXUIElement]
let incomplete: Bool
static var unavailable: Self { Self(elements: [], incomplete: true) }
enum RangeRead {
case values([AXUIElement])
case unreadable
case unavailable
}
/// Requests are shared across the observation. A changed range invalidates this parent's accumulated indices.
static func readRanges(count: Int, limit: Int, requests: inout Int,
read: (Range<Int>) throws -> RangeRead) rethrows -> Self {
guard count > 0 else { return .unavailable }
let end = min(count, limit)
var pending = [0..<end]
var children: [AXUIElement] = []
var incomplete = end < count
while let range = pending.popLast() {
guard requests > 0 else { incomplete = true; break }
requests -= 1
switch try read(range) {
case .values(let values):
children.append(contentsOf: values)
case .unavailable:
return .unavailable
case .unreadable:
if range.count == 1 {
incomplete = true
} else {
let middle = range.lowerBound + range.count / 2
pending.append(middle..<range.upperBound)
pending.append(range.lowerBound..<middle)
}
}
}
return Self(elements: children, incomplete: incomplete)
}
}
@@ -50,11 +50,13 @@ struct NativeFailure: Error, Sendable {
let code: String
let message: String
let accessibilityError: Int32?
let attribute: String?
init(code: String, message: String, accessibilityError: Int32? = nil) {
init(code: String, message: String, accessibilityError: Int32? = nil, attribute: String? = nil) {
self.code = code
self.message = message
self.accessibilityError = accessibilityError
self.attribute = attribute
}
}
@@ -0,0 +1,56 @@
// Synthetic AX references distinguish siblings without access to a desktop process.
import ApplicationServices
import Testing
@testable import CuaNative
@Test func aFailingChildPreservesReadableSiblingsInOrder() {
let nodes = (1...32).map { AXUIElementCreateApplication(Int32($0)) }
var requests = 32
let children = AXObservedChildren.readRanges(count: nodes.count, limit: nodes.count, requests: &requests) { range in
range.contains(17) ? .unreadable : .values(Array(nodes[range]))
}
#expect(children.incomplete)
#expect(children.elements == Array(nodes[..<17]) + Array(nodes[18...]))
#expect(requests > 0)
}
@Test func recoveryHonorsBothTheRequestAndElementLimits() {
let node = AXUIElementCreateApplication(1)
var requests = 3
let limited = AXObservedChildren.readRanges(count: Int.max, limit: 4, requests: &requests) { range in
#expect(range.upperBound <= 4)
return range.upperBound > 2 ? .unreadable : .values(Array(repeating: node, count: range.count))
}
#expect(limited.elements == [node, node])
#expect(limited.incomplete)
#expect(requests == 0)
let exhausted = AXObservedChildren.readRanges(count: 2, limit: 2, requests: &requests) { _ in
Issue.record("Recovery called AX after exhausting the observation budget")
return .unreadable
}
#expect(exhausted.elements.isEmpty)
#expect(exhausted.incomplete)
}
@Test func aChangedRangeDiscardsEarlierChildrenAndOtherErrorsPropagate() {
let node = AXUIElementCreateApplication(1)
var requests = 10
let changed = AXObservedChildren.readRanges(count: 2, limit: 2, requests: &requests) { range in
if range.count == 2 { return .unreadable }
return range.lowerBound == 0 ? .values([node]) : .unavailable
}
#expect(changed.incomplete)
#expect(changed.elements.isEmpty)
#expect(throws: CancellationError.self) {
try AXObservedChildren.readRanges(count: 2, limit: 2, requests: &requests) { _ in throw CancellationError() }
}
}
@Test func completeRangeRecoveryPublishesACompleteObservation() {
let node = AXUIElementCreateApplication(1)
var requests = 1
let recovered = AXObservedChildren.readRanges(count: 1, limit: 1, requests: &requests) { _ in .values([node]) }
#expect(recovered.elements == [node])
#expect(!recovered.incomplete)
}
@@ -39,7 +39,7 @@
{"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":1794214350389,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794214350389,"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":1794214350389,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794214350389,"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\",\"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\",\"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},{\"windowId\":\"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":"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\",\"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 [Some children of AXMenuBarItem could not be read.]\\n - [3] AXMenuItem \\\"Fixture command\\\"\",\"windows\":[{\"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},{\"windowId\":\"9\",\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":true}"}],"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\",\"elementId\":\"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":1794214350417,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794214350417,"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\",\"elementId\":\"0\",\"holdMs\":800}}"}}},{"type":"chunk","time":1794214350417,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1794214350417,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"}
@@ -190,10 +190,10 @@ function createApplicationState(socket, record, application, captureBroker, conn
tree: `AX scope=${params.windowId === undefined ? 'application' : 'window'} offsets=UTF-16\n- [0] AXButton "Increment"\nAccessibility tree truncated (maxElements=1).`,
elements: [], windows: windows(), truncated: true }
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=${writableFailure === 'AXValue' ? 'unknown' : 'true'} selectionWritable=${writableFailure === 'AXSelectedTextRange' ? 'unknown' : '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.'}`,
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=${writableFailure === 'AXValue' ? 'unknown' : 'true'} selectionWritable=${writableFailure === 'AXSelectedTextRange' ? 'unknown' : '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 [Some children of AXMenuBarItem could not be read.]\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 }],
focusedWindowId: window.windowId, windows: windows(), truncated: false }
focusedWindowId: window.windowId, windows: windows(), truncated: params.includeMenus === true }
}
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')