From ec892f6b937884e85eb2c7b138af9bbd955f71df Mon Sep 17 00:00:00 2001 From: creatixchu Date: Mon, 9 Nov 2026 14:16:10 +0800 Subject: [PATCH] fix(cua): retain hidden panel coordinate frames without exposing them --- .../cua-macos/native/README.i18n.yaml | 4 ++-- .../experimental/cua-macos/native/README.md | 2 +- .../cua-macos/native/README.zh.md | 2 +- .../native/Sources/CuaNative/AXWorker.swift | 4 ++-- .../native/Sources/CuaNative/Protocol.swift | 6 ++++-- .../native/tests/floating_windows_e2e.py | 3 ++- .../native/tests/swift/ProtocolTests.swift | 2 +- .../tests/provider-lifecycle.spec.ts | 20 +++++++++++++++++-- packages/experimental/cua/src/index.ts | 17 +++++++++++++--- 9 files changed, 45 insertions(+), 15 deletions(-) diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index e6875a1e0b..79aac1ba9a 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -18,8 +18,8 @@ en: 1435672513328c05 zh: 11e7a1e672410c10 /dsh-cua-native-helper/request-protocol: - en: 26b60edc15bcbd69 - zh: c9954251858de5d6 + en: fef3cf6f0aa086b2 + zh: 237569eb426d886e /dsh-cua-native-helper/observation-and-input: en: 7e63469ddd8c4e72 zh: dbc87b8d8953c7e7 diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index 7894cc0101..db7ea14d92 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -74,7 +74,7 @@ Successful `activate` returns `dispatched` and `foregroundChanged`. A known chan | `findApps` | Installed matches `{id, displayName, path, isRunning, pid?}` from standard application directories or an absolute application path; discovery never launches them. | | `getApp` | Running selection returns `{appHandle, pid, name, bundleId?, running: true, authorization}`. A stopped selection returns `{appHandle, name, bundleId?, running: false, authorization}` with no `pid`, 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 (including hidden ones) and positive-size, onscreen auxiliary windows not known to be on another Space, with `{windowId, appName, title, bounds, isOnScreen, onCurrentSpace}`. Space membership can be null. | +| `listWindows` | Owned windows across all layers. The Host uses private `cacheOnly: true` records for geometry only, except for an explicitly selected target. Discovery includes all normal windows and positive-size, onscreen auxiliary windows not known to be on another Space, with `{windowId, appName, title, bounds, isOnScreen, onCurrentSpace}`. Space membership can be null. | | `getState` | `{appHandle, windowId, focusedWindowId, snapshotId, tree, elements, windows, truncated}`. `windowId` is null for an app-wide observation. Elements include the opaque string `elementId`, 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. | | `listActions` | Provider-defined action names for one element as a string array; an element may advertise none. | | `show` | `{dispatched: boolean, windowId, foregroundChanged}` records restoration dispatch. `windowId` is null when no window was selected; `foregroundChanged` is null when the sampled observation was unavailable. | diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index 204ad2ce4a..1c2ea27c9e 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` | 运行中的选择返回 `{appHandle, pid, name, bundleId?, running: true, authorization}`。未运行的选择返回 `{appHandle, name, bundleId?, running: false, authorization}`,其中没有 `pid`,并等待 Host 授权。名称歧义会失败。 | | `launchApp` | 授权后的 Host 专用续接操作;不请求激活,等待应用启动完成后将句柄绑定到已核实的进程身份。 | -| `listWindows` | 应用的普通窗口(包括隐藏窗口),以及在屏、尺寸大于零且未确定位于其他 Space 的辅助窗口,包含 `{windowId, appName, title, bounds, isOnScreen, onCurrentSpace}`。Space 归属可为 null。 | +| `listWindows` | 返回应用在各层级的窗口。Host 使用私有的 `cacheOnly: true` 记录维护坐标,只在显式选中该目标时展示。清单包含全部普通窗口,以及在屏、尺寸大于零且未确定位于其他 Space 的辅助窗口,包含 `{windowId, appName, title, bounds, isOnScreen, onCurrentSpace}`。Space 归属可为 null。 | | `getState` | `{appHandle, windowId, focusedWindowId, snapshotId, tree, elements, windows, truncated}`。应用级观察的 `windowId` 为 null。元素包含不透明字符串 `elementId`、role、title、value、description、identifier、bounds、actions 和 enabled 状态。元素边界为 null 或屏幕 point 单位的 [x, y, width, height],窗口输入使用局部 point。这些结构化元素诊断供原生检查保留,模型工具投影会移除它们。不可用的可选描述属性为 null,无法取得的动作列表为空;权限、通信和窗口发现失败仍会拒绝观察。 | | `listActions` | 一个元素由 provider 定义的动作名数组;元素可以不声明任何动作。 | | `show` | `{dispatched: boolean, windowId, foregroundChanged}` 记录恢复分派。未选中窗口时 `windowId` 为 null;无法取得采样观察时 `foregroundChanged` 为 null。 | diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift index 98c838ec66..f7c321d358 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift @@ -272,7 +272,7 @@ actor AXWorker { let ids = Set(windows.map(\.windowID)) snapshots = snapshots.filter { key, _ in key.appHandle != handle || (key.windowID.map { ids.contains($0) } ?? true) } observedWindowBounds[handle] = observedWindowBounds[handle]?.filter { ids.contains($0.key) } - return .result(.array(windows.filter(\.isDiscoverable).map(\.json))) + return .result(.array(windows.map(\.json))) } if method == "getState" { let windowID = try params.optionalWindowID() @@ -325,7 +325,7 @@ actor AXWorker { "windowId": window.map { .number(Double($0)) } ?? .null, "focusedWindowId": projection.focusedWindowID.map { .number(Double($0)) } ?? .null, "snapshotId": .string(id), "tree": .string(projection.tree), "elements": .array(projection.elements), - "windows": .array(observedWindows.filter { $0.isDiscoverable || $0.windowID == window }.map(\.json)), "truncated": .bool(projection.truncated)])) + "windows": .array(observedWindows.map(\.json)), "truncated": .bool(projection.truncated)])) case "screenshot": trace?.mark("screen-permission.begin") try NativePlatform.requireScreenRecording() diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/Protocol.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/Protocol.swift index 8e010b03fb..21022db0c5 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/Protocol.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/Protocol.swift @@ -146,10 +146,12 @@ struct WindowInfo: Sendable { } var json: JSONValue { - .object([ + var record: [String: JSONValue] = [ "windowId": .number(Double(windowID)), "appName": .string(appName), "title": .string(title), "bounds": bounds.json, "isOnScreen": .bool(isOnScreen), "onCurrentSpace": onCurrentSpace.map(JSONValue.bool) ?? .null, - ]) + ] + if !isDiscoverable { record["cacheOnly"] = .bool(true) } + return .object(record) } } 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 614915f97d..ef84156a5d 100644 --- a/packages/experimental/cua-macos/native/tests/floating_windows_e2e.py +++ b/packages/experimental/cua-macos/native/tests/floating_windows_e2e.py @@ -83,7 +83,8 @@ def main(): wait_state(lambda value: value['count'] == 2) os.kill(fixture.pid, signal.SIGUSR1) wait_state(lambda value: not value['panelOnScreen'] and value['panelLayer'] > 0) - assert panel_id not in [w['windowId'] for w in helper.call('listWindows', owner)] + hidden = next(w for w in helper.call('listWindows', owner) if w['windowId'] == panel_id) + assert hidden.get('cacheOnly') is True, hidden os.kill(fixture.pid, signal.SIGUSR1) wait_state(lambda value: value['panelOnScreen'] and value['panelWindowId'] == panel_id) assert panel_id in [w['windowId'] for w in helper.call('listWindows', owner)] diff --git a/packages/experimental/cua-macos/native/tests/swift/ProtocolTests.swift b/packages/experimental/cua-macos/native/tests/swift/ProtocolTests.swift index e330bffe32..b9e03b7b8e 100644 --- a/packages/experimental/cua-macos/native/tests/swift/ProtocolTests.swift +++ b/packages/experimental/cua-macos/native/tests/swift/ProtocolTests.swift @@ -63,7 +63,7 @@ func discoversNormalWindowsAndVisibleAuxiliaryWindows(layer: Int, onScreen: Bool let window = WindowInfo(windowID: 7, pid: 42, appName: "Fixture", title: "", bounds: WindowBounds(x: 0, y: 0, width: width, height: 100), isOnScreen: onScreen, onCurrentSpace: currentSpace, layer: layer) - #expect(window.isDiscoverable == expected) + #expect(window.json.object?["cacheOnly"] == (expected ? nil : .bool(true))) #expect(window.json.object?.keys.contains("layer") == false) } diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index 5e7b5893f6..4981c1d76f 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -545,8 +545,24 @@ 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', - bounds: { ...metadata.bounds, width: 2 }, isOnScreen: true, onCurrentSpace: true }] + const window = { windowId: 7, appName: 'Fixture', title: 'Window', bounds: metadata.bounds, isOnScreen: false, onCurrentSpace: true } + const hiddenPanel = { ...window, cacheOnly: true } + const minimizedDocument = { ...window, windowId: 8, title: 'Document' } + native.request.mockResolvedValueOnce([hiddenPanel, minimizedDocument]) + const discovery = await f.execute('listWindows', { appHandle: 'app-one' }) + expect(discovery.value).toEqual([minimizedDocument]) + expect(discovery.content).toEqual([{ type: 'text', text: JSON.stringify([minimizedDocument]) }]) + for (const windowId of [null, 7]) { + native.request.mockResolvedValueOnce({ appHandle: 'app-one', windowId, snapshotId: 'snapshot', tree: '', + windows: [hiddenPanel, minimizedDocument], truncated: false }) + const state = await f.execute('getState', { appHandle: 'app-one', ...windowId === null ? {} : { windowId } }) + expect(state.value).toMatchObject({ windows: windowId === null ? [minimizedDocument] : [window, minimizedDocument] }) + } + native.request.mockResolvedValueOnce([{ ...window, isOnScreen: true }, minimizedDocument ]) + await f.execute('listWindows', { appHandle: 'app-one' }) + native.request.mockResolvedValueOnce({ dispatched: true }) + expect((await f.execute('click', { appHandle: 'app-one', windowId: 7, x: 0, y: 0 })).isError).toBe(false) + const windows = [{ ...window, bounds: { ...metadata.bounds, width: 2 }, isOnScreen: true }] native.request.mockResolvedValueOnce(windows) const listed = await f.execute('listWindows', { appHandle: 'app-one' }) expect(listed.isError).toBe(false) diff --git a/packages/experimental/cua/src/index.ts b/packages/experimental/cua/src/index.ts index 43ca13308e..aea8ea56d6 100644 --- a/packages/experimental/cua/src/index.ts +++ b/packages/experimental/cua/src/index.ts @@ -99,6 +99,13 @@ interface CuaExecution extends ToolExecution { } +// Providers can retain geometry for a live window without listing it as a discovery candidate. +const NativeWindows = WindowsResult.element.extend({ cacheOnly: z.literal(true).optional() }).array() +const NativeState = StateResult.extend({ windows: NativeWindows }) +function discoveredWindows(windows: z.output, selected?: number | null) { + return windows.flatMap(({ cacheOnly, ...window }) => !cacheOnly || window.windowId === selected ? [window] : []) +} + type ScreenshotValue = z.infer & { attachment: { [K in keyof ImageAttachmentRef]: ImageAttachmentRef[K] } } /** Native values stay available to programs; only metadata and the stored image enter model content. */ @@ -295,14 +302,18 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) } } if (method === 'getState') { - const state = StateResult.parse(result) + const state = NativeState.parse(result) if (state.appHandle !== parsedParams.appHandle || state.windowId !== (parsedParams.windowId ?? null)) { throw new NativeError('NATIVE_PROTOCOL', 'Native observation belongs to another application or window') } execution.coordinates.observe(state.appHandle, state.windows, state.windowId ?? undefined) - return state + return { ...state, windows: discoveredWindows(state.windows, state.windowId) } + } + if (method === 'listWindows') { + const windows = NativeWindows.parse(result) + execution.coordinates.observe(parsedParams.appHandle as CuaAppHandle, windows) + return discoveredWindows(windows) } - if (method === 'listWindows') execution.coordinates.observe(parsedParams.appHandle as CuaAppHandle, WindowsResult.parse(result)) return result } const tool: ToolDefinition = {