From 531004f06e677a22f394ef40637c9b7b614d4960 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 14:42:37 +0800 Subject: [PATCH 01/73] Unify macOS CUA held input around turn finalization --- docs/agent-lifecycle.md | 1 + docs/agent-lifecycle.zh.md | 1 + docs/architecture.i18n.yaml | 4 +- docs/architecture.md | 3 +- docs/architecture.zh.md | 3 +- docs/subsystems/core.md | 24 ++ docs/subsystems/core.zh.md | 24 ++ .../cua-turn-inputs/guide.i18n.yaml | 16 ++ .../v0.2.2-rc.4/cua-turn-inputs/guide.md | 17 ++ .../v0.2.2-rc.4/cua-turn-inputs/guide.zh.md | 17 ++ packages/core/agent-loop/README.i18n.yaml | 4 +- packages/core/agent-loop/README.md | 2 + packages/core/agent-loop/README.zh.md | 2 + packages/core/agent-loop/src/agent.ts | 13 +- .../tests/contract-regressions.spec.ts | 38 ++++ packages/core/agent/README.i18n.yaml | 4 +- packages/core/agent/README.md | 2 +- packages/core/agent/README.zh.md | 2 +- packages/core/agent/src/dispatch.ts | 14 ++ packages/core/agent/src/runtime-types.ts | 11 + .../experimental/cua-macos/README.i18n.yaml | 16 +- packages/experimental/cua-macos/README.md | 12 +- packages/experimental/cua-macos/README.zh.md | 12 +- .../native/Sources/CuaNative/AXWorker.swift | 38 ++-- .../native/Sources/CuaNative/HeldInputs.swift | 211 ++++++++++++++++++ .../native/Sources/CuaNative/HeldKeys.swift | 114 ---------- .../Sources/CuaNative/KeyboardInput.swift | 25 +-- .../CuaNative/NativeProtocol.generated.swift | 9 +- .../Sources/CuaNative/RequestAdmission.swift | 6 + .../CuaNative/RequestCoordinator.swift | 22 +- .../Sources/CuaNative/RequestScheduler.swift | 4 +- .../CuaNative/SystemPointerInput.swift | 56 +---- .../CuaNative/WindowPointerInput.swift | 25 ++- .../cua-macos/native/generate-protocol.ts | 11 +- .../cua-macos/native/protocol.schema.json | 76 ++++--- .../native/tests/capabilities_e2e.py | 8 +- .../native/tests/native_test_support.py | 5 + .../native/tests/shared_helper_e2e.py | 5 + .../native/tests/swift/HeldInputTests.swift | 105 +++++++++ .../tests/swift/KeyboardChordTests.swift | 72 ------ .../native/tests/test_ax_projection.py | 2 +- .../experimental/cua-macos/src/guidance.ts | 4 +- .../experimental/cua-macos/src/held-keys.ts | 60 ----- packages/experimental/cua-macos/src/index.ts | 3 +- .../cua-macos/tests/guidance.spec.ts | 8 +- .../cua-macos/tests/held-keys.spec.ts | 156 ------------- .../tests/protocol-generation.spec.ts | 2 +- .../tests/provider-lifecycle.spec.ts | 205 +++-------------- packages/experimental/cua/README.i18n.yaml | 4 +- packages/experimental/cua/README.md | 2 + packages/experimental/cua/README.zh.md | 2 + packages/experimental/cua/src/guidance.ts | 2 +- packages/experimental/cua/src/index.ts | 22 +- .../experimental/cua/src/mouse-control.ts | 26 +-- packages/experimental/cua/src/turn-inputs.ts | 82 +++++++ packages/experimental/cua/src/types.ts | 7 +- .../cua/tests/run-code-composition.spec.ts | 135 ++++++++++- .../extensions/tool-cordis/src/api-catalog.ts | 8 + scripts/fixtures/python-snapshot-tool.mjs | 7 + snapshots/sdk/ptc-cancel/cancel.mjs | 6 + .../session/cua-run-code/native-channel.d.mts | 8 + .../session/cua-run-code/native-channel.mjs | 60 ++++- snapshots/session/cua-run-code/provider.mjs | 3 +- .../session/cua-run-code/session.v4.jsonl | 4 +- 64 files changed, 1031 insertions(+), 821 deletions(-) create mode 100644 docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.i18n.yaml create mode 100644 docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.md create mode 100644 docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.zh.md create mode 100644 packages/experimental/cua-macos/native/Sources/CuaNative/HeldInputs.swift delete mode 100644 packages/experimental/cua-macos/native/Sources/CuaNative/HeldKeys.swift create mode 100644 packages/experimental/cua-macos/native/tests/swift/HeldInputTests.swift delete mode 100644 packages/experimental/cua-macos/src/held-keys.ts delete mode 100644 packages/experimental/cua-macos/tests/held-keys.spec.ts create mode 100644 packages/experimental/cua/src/turn-inputs.ts diff --git a/docs/agent-lifecycle.md b/docs/agent-lifecycle.md index 8dea01c100..858718ef0c 100644 --- a/docs/agent-lifecycle.md +++ b/docs/agent-lifecycle.md @@ -78,6 +78,7 @@ sequenceDiagram end end end + Driver->>Hooks: agent/turn-finalizing await all resource finalizers Driver->>Session: turn/end Driver-->>SDK: agent/status idle ``` diff --git a/docs/agent-lifecycle.zh.md b/docs/agent-lifecycle.zh.md index 66c5dd90bf..30347102fb 100644 --- a/docs/agent-lifecycle.zh.md +++ b/docs/agent-lifecycle.zh.md @@ -80,6 +80,7 @@ sequenceDiagram end end end + Driver->>Hooks: agent/turn-finalizing await all resource finalizers Driver->>Session: turn/end Driver-->>SDK: agent/status idle ``` diff --git a/docs/architecture.i18n.yaml b/docs/architecture.i18n.yaml index c4549ec197..8f6550670f 100644 --- a/docs/architecture.i18n.yaml +++ b/docs/architecture.i18n.yaml @@ -24,8 +24,8 @@ en: 0d4481070a0ba352 zh: 026be77a9f3db68e /deepseek-harness-architecture/turn-flow: - en: 96ad2d8611fd5b88 - zh: 0a6bb22b3b0e1335 + en: 676f1cec024509b4 + zh: d47bcaeb1e856aa9 /deepseek-harness-architecture/session-log: en: b3b63d8fe7cab9fe zh: 3703fcf30b1639d0 diff --git a/docs/architecture.md b/docs/architecture.md index 9661ac7ad6..5a26c381b4 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -102,10 +102,11 @@ turn/start step/end tools owe another request, or next-step input arrived -> claim -> next step -> agent/turn-stopping + -> agent/turn-finalizing (all outcomes; awaited) turn/end ``` -`turn/*`, `step/*`, `system/message`, `user/message`, `assistant/message`, `assistant/attempt`, and `tool/*` are durable session events; the rest are live extension points across three domains. `agent/assistant-stream` publishes process-local start, transient chunk, and end frames. The loop commits the complete compact stream as one message or log-only attempt before a committed end frame, and the Web Session-follow adapter is the live event's only remote consumer. `agent/pre-step`, `agent/request`, `llm/stream`, and the three `tools/*` events are waterfalls, whose listeners must call `next()` to delegate; `agent/turn-stopping` is serial and has no `next()`. +`turn/*`, `step/*`, `system/message`, `user/message`, `assistant/message`, `assistant/attempt`, and `tool/*` are durable session events; the rest are live extension points across three domains. `agent/assistant-stream` publishes process-local start, transient chunk, and end frames. The loop commits the complete compact stream as one message or log-only attempt before a committed end frame, and the Web Session-follow adapter is the live event's only remote consumer. `agent/pre-step`, `agent/request`, `llm/stream`, and the three `tools/*` events are waterfalls, whose listeners must call `next()` to delegate; `agent/turn-stopping` is serial and has no `next()`. `agent/turn-finalizing` awaits every resource finalizer on completion, error and cancellation before `turn/end` and the next turn; failures are reported after all listeners settle. Fork creation stores the caller-supplied history; a sharing backend persists the parent prefix first ([lifecycle](../packages/core/agent-loop/README.md#understand-the-implementation)). Factory setup follows SessionStore entry and `session/created`, preceding `agent/created`; closing events commit before removal. diff --git a/docs/architecture.zh.md b/docs/architecture.zh.md index 41595f1bbb..d9a99cc44b 100644 --- a/docs/architecture.zh.md +++ b/docs/architecture.zh.md @@ -106,10 +106,11 @@ turn/start step/end tools owe another request, or next-step input arrived -> claim -> next step -> agent/turn-stopping + -> agent/turn-finalizing (all outcomes; awaited) turn/end ``` -`turn/*`、`step/*`、`system/message`、`user/message`、`assistant/message`、`assistant/attempt` 和 `tool/*` 是持久会话事件;其余是分属三个事件域的实时扩展点。`agent/assistant-stream` 发布进程本地 start、瞬态 chunk 与 end frame。loop 会在 committed end frame 前把完整紧凑 stream 提交为一个 message 或仅日志 attempt;Web Session-follow adapter 是该 live event 唯一的远程消费方。`agent/pre-step`、`agent/request`、`llm/stream` 和三个 `tools/*` 事件是 waterfall(瀑布式事件),其监听器必须调用 `next()` 才能委托下去;`agent/turn-stopping` 是 serial 事件,没有 `next()`。 +`turn/*`、`step/*`、`system/message`、`user/message`、`assistant/message`、`assistant/attempt` 和 `tool/*` 是持久会话事件;其余是分属三个事件域的实时扩展点。`agent/assistant-stream` 发布进程本地 start、瞬态 chunk 与 end frame。loop 会在 committed end frame 前把完整紧凑 stream 提交为一个 message 或仅日志 attempt;Web Session-follow adapter 是该 live event 唯一的远程消费方。`agent/pre-step`、`agent/request`、`llm/stream` 和三个 `tools/*` 事件是 waterfall(瀑布式事件),其监听器必须调用 `next()` 才能委托下去;`agent/turn-stopping` 是 serial 事件,没有 `next()`。`agent/turn-finalizing` 在正常完成、错误和取消时等待所有资源清理,再提交 `turn/end` 和开始下一回合;所有监听器结束后统一报告失败。 fork 创建存储调用方提供的历史;共享前缀的后端先持久化父前缀([生命周期](../packages/core/agent-loop/README.zh.md#understand-the-implementation))。工厂 setup 在 Session 进入 SessionStore 并完成 `session/created` 之后、`agent/created` 之前运行;收尾事件在移除之前提交。 diff --git a/docs/subsystems/core.md b/docs/subsystems/core.md index a316daaba9..f399b5f850 100644 --- a/docs/subsystems/core.md +++ b/docs/subsystems/core.md @@ -1087,6 +1087,30 @@ Types: [Scoped](scope.md) Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/src/runtime-types.ts) + + +#### `agent/turn-finalizing` — parallel + +The turn has irrevocably stopped admitting steps. Await all resource finalizers before committing turn/end, becoming idle, or starting another turn, including on cancellation. Listeners own bounded cleanup independent of the cancelled operation signal. Failures are reported through agent/error and the durable turn ending after every listener settles. + +```ts cordis-catalog +/** + * The turn has irrevocably stopped admitting steps. Await all resource finalizers before + * committing turn/end, becoming idle, or starting another turn, including on cancellation. + * Listeners own bounded cleanup independent of the cancelled operation signal. Failures + * are reported through agent/error and the durable turn ending after every listener settles. + * @param payload.agent - the agent whose work has settled. + * @param payload.turn - the turn being finalized. + * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. + * @mode parallel + */ +'agent/turn-finalizing'(this: Scoped, payload: { agent: Agent; turn: number }): Promise | void +``` + +Types: [Scoped](scope.md) + +Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/src/runtime-types.ts) + #### `agent/turn-stopping` — serial diff --git a/docs/subsystems/core.zh.md b/docs/subsystems/core.zh.md index 9d8d401f85..3740079bd3 100644 --- a/docs/subsystems/core.zh.md +++ b/docs/subsystems/core.zh.md @@ -1099,6 +1099,30 @@ Types: [Scoped](scope.zh.md) Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/src/runtime-types.ts) + + +#### `agent/turn-finalizing` — parallel + +The turn has irrevocably stopped admitting steps. Await all resource finalizers before committing turn/end, becoming idle, or starting another turn, including on cancellation. Listeners own bounded cleanup independent of the cancelled operation signal. Failures are reported through agent/error and the durable turn ending after every listener settles. + +```ts cordis-catalog +/** + * The turn has irrevocably stopped admitting steps. Await all resource finalizers before + * committing turn/end, becoming idle, or starting another turn, including on cancellation. + * Listeners own bounded cleanup independent of the cancelled operation signal. Failures + * are reported through agent/error and the durable turn ending after every listener settles. + * @param payload.agent - the agent whose work has settled. + * @param payload.turn - the turn being finalized. + * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. + * @mode parallel + */ +'agent/turn-finalizing'(this: Scoped, payload: { agent: Agent; turn: number }): Promise | void +``` + +Types: [Scoped](scope.zh.md) + +Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/src/runtime-types.ts) + #### `agent/turn-stopping` — serial diff --git a/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.i18n.yaml new file mode 100644 index 0000000000..eacc286081 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/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.4/cua-turn-inputs/guide.md +/: + en: 41907c88d906eadf + zh: 738dc3d3b4cc33e4 +/macos-cua-input-holds-last-for-one-turn: + en: 34b24b7c3428274b + zh: 7e73cf9ba46ff2dd +/macos-cua-input-holds-last-for-one-turn/change: + en: fdf88fdc0141c9d8 + zh: a4af8cab104d38d1 +/macos-cua-input-holds-last-for-one-turn/migration: + en: 5e45c629483d2fd5 + zh: 3e8be5a85f2c54ef diff --git a/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.md b/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.md new file mode 100644 index 0000000000..4a61ebeab8 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.md @@ -0,0 +1,17 @@ +--- +kind: upgrade-guide +description: macOS CUA explicit key and mouse downs now remain held across program executions within a turn. +--- +# macOS CUA input holds last for one turn + +English | [中文](guide.zh.md) + +## Change + +macOS `sendKeyEvent('down')` holds a key across `run_code` and `cua_run_code` calls in the same turn. Returning or throwing from a program no longer releases it while the turn continues. Explicit `up` releases it immediately at the original recipient. Window-directed and system `toggleMouse('down')` join the same lifecycle. At turn completion, failure or user cancellation, cleanup releases all remaining keys and mouse buttons in reverse dispatch order and waits for native acknowledgement. Complete `pressKey`, `typeText`, `click` and `drag` operations keep their operation-local cleanup. Windows retains its current behavior. + +## Migration + +1. If a program requires release before it returns, send an explicit `up` in its `finally` block. Otherwise a later program in the same turn can release the held input. +2. Upgrade the macOS package and helper together. A custom `helperPath` must point to a rebuilt helper implementing the new private turn input protocol. +3. Verify a down in one program remains held until an up in a later program, or until the turn ends. If cleanup cannot be confirmed, CUA disables input for that task. Check the desktop before starting a new task. diff --git a/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.zh.md new file mode 100644 index 0000000000..9221e10c49 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.zh.md @@ -0,0 +1,17 @@ +--- +kind: upgrade-guide +description: macOS CUA 的显式键盘和鼠标按下现在可在同一回合内跨程序执行保持。 +--- +# macOS CUA 输入以回合为持有范围 + +[English](guide.md) | 中文 + +## 变更 + +macOS 的 `sendKeyEvent('down')` 可在同一回合内跨 `run_code` 和 `cua_run_code` 调用持有按键。程序返回或抛错后,回合仍继续时不再自动释放。显式 `up` 立即向原接收方释放。窗口定向和系统 `toggleMouse('down')` 使用相同生命周期。回合正常完成、异常结束或用户取消时,清理按实际派发顺序的反序释放剩余键盘键和鼠标按钮,并等待原生确认。完整的 `pressKey`、`typeText`、`click` 和 `drag` 操作继续在本次操作内清理。Windows 保持现有行为。 + +## 迁移 + +1. 如果程序需要在返回前释放输入,在 `finally` 中显式发送 `up`。否则可由同一回合中的后续程序释放。 +2. 同步升级 macOS 包和 helper。自定义 `helperPath` 必须指向已重建、支持新回合输入私有协议的 helper。 +3. 验证前一次程序的 `down` 能保持到后一次程序发送 `up`,或回合结束。清理无法确认时,CUA 会禁用该任务的输入。检查桌面状态后再创建新任务。 diff --git a/packages/core/agent-loop/README.i18n.yaml b/packages/core/agent-loop/README.i18n.yaml index 53441930a2..ffbdf8b61d 100644 --- a/packages/core/agent-loop/README.i18n.yaml +++ b/packages/core/agent-loop/README.i18n.yaml @@ -48,8 +48,8 @@ en: 4bd3c8b4a9ee8cf8 zh: 2f4965a3197bed0e /deepseek-ai-dsh-agent-loop/understand-the-implementation/failure-and-cancellation: - en: eea56903c4ff82f5 - zh: c0d5abb5767780ed + en: 3355aa6bfce07a2f + zh: 8d4e51ea7b1d2ca0 /deepseek-ai-dsh-agent-loop/further-exploration: en: 7ac519f8e635acbc zh: 975e514915dc6c9f diff --git a/packages/core/agent-loop/README.md b/packages/core/agent-loop/README.md index 28a4fe8e9c..5e80f14bc2 100644 --- a/packages/core/agent-loop/README.md +++ b/packages/core/agent-loop/README.md @@ -127,6 +127,8 @@ The runtime-context projection compares the ordered names and text in committed ### Failure and cancellation +`agent/turn-finalizing` runs after the turn stops admitting steps, on completion, error and cancellation. All listeners settle before `turn/end`, idle status, subsequent turns and Agent disposal. A listener failure does not skip other finalizers; it produces `agent/error` and an error ending. Finalizers own their cleanup deadlines and must not reuse an aborted operation signal or await this Agent becoming idle. + `turn/end` declares `TurnEndCancelCause`; cancellation records a fresh `AgentCancelCause` there, retaining the caller's `kind` and the hook's `reason` text. The live `AbortSignal.reason` remains the caller's object, which a transport may extend — Node's fetch assigns a `stack` onto it — so the copy keeps that trace out of the log and keeps the ending appendable. Final adapter selection, dispatch, and iteration failures arrive as terminal finishes and enter `agent/request-error`; a handling listener returns `{ kind: 'retry' }` without calling `next()`, while an unhandled failure is terminal. Middleware, result-processing, tool, and other extension failures remain thrown and close the turn directly — plugin failure ends the turn, not the loop. Undispatched model tool calls after cancellation receive synthetic `tool/call` plus `ABORTED_BEFORE_DISPATCH` result pairs. diff --git a/packages/core/agent-loop/README.zh.md b/packages/core/agent-loop/README.zh.md index 20f958752b..d4933a09fe 100644 --- a/packages/core/agent-loop/README.zh.md +++ b/packages/core/agent-loop/README.zh.md @@ -127,6 +127,8 @@ loop 在发布工厂前等待必需的注册完成。它对模型选择和 inbox ### 失败与取消 +`agent/turn-finalizing` 在回合停止接纳步骤后执行,覆盖正常完成、错误和取消。所有监听器结束后才提交 `turn/end`、发布空闲状态、开始后续回合或完成 Agent 销毁。一个监听器失败不会跳过其他清理监听器;失败会产生 `agent/error` 和错误结束记录。清理监听器自行设置超时,不得复用已取消的操作 signal,也不得等待本 Agent 变为空闲。 + `turn/end` 声明的类型是 `TurnEndCancelCause`;取消时,循环在其中记录一份新的 `AgentCancelCause`,保留调用方的 `kind` 和 hook 的 `reason` 文本。实时 `AbortSignal.reason` 仍是调用方的那个对象,传输层可能向其添加属性——Node 的 fetch 会给它赋一个 `stack`——因此这份拷贝既让该调用栈不进入日志,也让结束事件保持可追加。 最终适配器选择、分发与迭代失败以终止结束的形式到达并进入 `agent/request-error`;处理该失败的监听器返回 `{ kind: 'retry' }` 且不调用 `next()`,未被处理的失败则是终态。Middleware、结果处理、工具及其他扩展失败仍会抛出并直接关闭轮次——插件失败结束的是轮次,不是循环。取消后未分发的模型工具调用会收到合成的 `tool/call` 加 `ABORTED_BEFORE_DISPATCH` 结果对。 diff --git a/packages/core/agent-loop/src/agent.ts b/packages/core/agent-loop/src/agent.ts index 7ec43dd132..c3a3d6122f 100644 --- a/packages/core/agent-loop/src/agent.ts +++ b/packages/core/agent-loop/src/agent.ts @@ -424,8 +424,17 @@ export class ReactLoopAgent implements Agent { this.throwError(error) } finally { try { - // oxlint-disable-next-line typescript/no-non-null-assertion -- every exit assigns a turn ending - this.session.append('turn/end', { turn, reason: turnEnds! }) + try { + await this.dispatch.settled('agent/turn-finalizing', { turn }) + const cause = abortedCancelCause(signal) + if (cause !== undefined) turnEnds = { kind: 'aborted', reason: cause } + } catch (error: unknown) { + turnEnds = { kind: 'error', error: { code: 'UNKNOWN', message: errorChain(error) } } + throw error + } finally { + // oxlint-disable-next-line typescript/no-non-null-assertion -- every exit assigns a turn ending + this.session.append('turn/end', { turn, reason: turnEnds! }) + } } catch (error: unknown) { this.throwError(error) } diff --git a/packages/core/agent-loop/tests/contract-regressions.spec.ts b/packages/core/agent-loop/tests/contract-regressions.spec.ts index d467ed3e2a..3be9ed1171 100644 --- a/packages/core/agent-loop/tests/contract-regressions.spec.ts +++ b/packages/core/agent-loop/tests/contract-regressions.spec.ts @@ -1528,3 +1528,41 @@ describe('disposal and cancellation during pre-step assembly', () => { expect(adapter.requests).toHaveLength(0) }) }) + +describe('turn finalization', () => { + it('waits for every finalizer after a rejection and commits failure before idle', async () => { + const ctx = await harness(new MockAdapter([textResponse('done')])) + const agent = await ctx.agentLoop.create(brandString('finalization'), { provider: 'mock', model: 'mock' }) + const entered: PromiseWithResolvers = Promise.withResolvers() + const release: PromiseWithResolvers = Promise.withResolvers() + const reported: unknown[] = [] + ctx.on('agent/error', ({ error }) => { reported.push(error) }) + ctx.on('agent/turn-finalizing', () => { throw new Error('first finalizer failed') }) + agent.ctx.on('agent/turn-finalizing', async () => { entered.resolve(); await release.promise }) + try { + send(agent, 'go') + await entered.promise + expect(agent.status).toBe('running') + expect(agent.session.snapshotEvents().some(event => event.type === 'turn/end')).toBe(false) + release.resolve() + await agent.whenIdle() + expect(reported).toHaveLength(1) + expect(agent.session.snapshotEvents().at(-1)).toMatchObject({ type: 'turn/end', data: { reason: { kind: 'error' } } }) + } finally { release.resolve(); await ctx.fiber.dispose() } + }) + + it('does not finalize when turn-stopping steering continues the current turn', async () => { + const ctx = await harness(new MockAdapter([textResponse('first'), textResponse('second')])) + const agent = await ctx.agentLoop.create(brandString('finalization-steering'), { provider: 'mock', model: 'mock' }) + const finalized: number[] = [] + let stops = 0 + ctx.on('agent/turn-stopping', () => { if (++stops === 1) agent.steer(createUserMessage({ content: [{ type: 'text', text: 'continue' }], source: { kind: 'user' } })) }) + ctx.on('agent/turn-finalizing', ({ turn }) => { finalized.push(turn) }) + try { + send(agent, 'go') + await agent.whenIdle() + expect(finalized).toEqual([1]) + expect(agent.session.snapshotEvents().filter(event => event.type === 'step/start')).toHaveLength(2) + } finally { await ctx.fiber.dispose() } + }) +}) diff --git a/packages/core/agent/README.i18n.yaml b/packages/core/agent/README.i18n.yaml index 5dbbf2ac8a..adbc40371d 100644 --- a/packages/core/agent/README.i18n.yaml +++ b/packages/core/agent/README.i18n.yaml @@ -30,8 +30,8 @@ en: 2594a1e02adea801 zh: cae8860369728efb /deepseek-ai-dsh-agent/use-this-package/intercept-or-observe-work-in-flight: - en: 371511fb13093dd2 - zh: 4be81d246cf299b2 + en: a75d2d050ea46674 + zh: 909587726147b9ce /deepseek-ai-dsh-agent/understand-the-implementation: en: ce7e776e9d516bdb zh: 59d2751743db7795 diff --git a/packages/core/agent/README.md b/packages/core/agent/README.md index 6983725201..5dc7d9709e 100644 --- a/packages/core/agent/README.md +++ b/packages/core/agent/README.md @@ -79,7 +79,7 @@ await handle.agent.whenIdle() `agent/request` is deprecated and retained for existing listeners. Do not add new listeners. Provider, model, and optional explicit reasoning effort are fixed at step preparation; listeners must preserve all three, including an absent effort. `AgentOptions.maxTokens` sets the output cap. Other per-request control overrides have no replacement API. See the [migration guide](../../../docs/upgrade-guide/v0.2.1-alpha.4/session-model-selection/guide.md) for affected callers. -The `agent/*` events let plugins act on live work without depending on the loop package. `agent/pre-step` can reject a proposed step or replace the messages entering it; `agent/request-error` lets a listener retry a failed model request; `agent/turn-stopping` runs before an otherwise completed turn closes and can steer to keep it open. `agent/assistant-stream` carries one process-local Assistant attempt's ordered start, transient chunk, and end frames. Start names the attempt's turn and step, chunk indexes are dense from zero, and `end.index` is the next chunk position. The loop commits the complete compact stream as one `assistant/message` or `assistant/attempt` before a committed end frame, so the live event remains presentation data rather than the replay source. `agent/status`, `agent/created`, and `agent/disposed` drive UI and coordination state, and the per-message `agent/inbox/*` notifications keep inbox projections in sync. Exact signatures, dispatch modes, and payload contracts live in the generated region of the [core subsystem page](../../../docs/subsystems/core.md#cordis-surface). +The `agent/*` events let plugins act on live work without depending on the loop package. `agent/pre-step` can reject a proposed step or replace the messages entering it; `agent/request-error` lets a listener retry a failed model request; `agent/turn-stopping` runs before an otherwise completed turn closes and can steer to keep it open. `agent/turn-finalizing` awaits resource cleanup on every ending, including cancellation, before `turn/end` and idle. `agent/assistant-stream` carries one process-local Assistant attempt's ordered start, transient chunk, and end frames. Start names the attempt's turn and step, chunk indexes are dense from zero, and `end.index` is the next chunk position. The loop commits the complete compact stream as one `assistant/message` or `assistant/attempt` before a committed end frame, so the live event remains presentation data rather than the replay source. `agent/status`, `agent/created`, and `agent/disposed` drive UI and coordination state, and the per-message `agent/inbox/*` notifications keep inbox projections in sync. Exact signatures, dispatch modes, and payload contracts live in the generated region of the [core subsystem page](../../../docs/subsystems/core.md#cordis-surface). ----- diff --git a/packages/core/agent/README.zh.md b/packages/core/agent/README.zh.md index e74ddaefa1..d6ba191c4b 100644 --- a/packages/core/agent/README.zh.md +++ b/packages/core/agent/README.zh.md @@ -79,7 +79,7 @@ await handle.agent.whenIdle() `agent/request` 已弃用,仅为现有监听器保留。不要添加新监听器。提供方、模型和可选的显式推理强度在步骤准备时固定;监听器必须保留三者,包括未指定强度的状态。`AgentOptions.maxTokens` 设置输出上限。其他逐请求控制参数覆盖没有替代 API。受影响的调用方参见[迁移指南](../../../docs/upgrade-guide/v0.2.1-alpha.4/session-model-selection/guide.zh.md)。 -`agent/*` 事件让插件无需依赖循环包即可作用于实时工作。`agent/pre-step` 可以拒绝拟进入的步骤或替换进入它的消息;`agent/request-error` 让监听器重试失败的模型请求;`agent/turn-stopping` 在本可完成的轮次关闭前运行,并可通过 steer 使其保持打开。`agent/assistant-stream` 携带一个进程本地 Assistant attempt 的有序 start、瞬态分片与 end frame。start 给出该 attempt 的轮次与步骤,分片索引从零开始密集递增,`end.index` 则是下一个分片位置。loop 会在 committed end frame 前把完整紧凑流提交为一个 `assistant/message` 或 `assistant/attempt`,因此实时事件仍是呈现数据而非回放来源。`agent/status`、`agent/created` 与 `agent/disposed` 驱动 UI 与协调状态,逐消息的 `agent/inbox/*` 通知则让收件箱投影保持同步。确切签名、分发 mode 与 payload 约定见 [core 子系统页](../../../docs/subsystems/core.zh.md#cordis-surface) 的生成区块。 +`agent/*` 事件让插件无需依赖循环包即可作用于实时工作。`agent/pre-step` 可以拒绝拟进入的步骤或替换进入它的消息;`agent/request-error` 让监听器重试失败的模型请求;`agent/turn-stopping` 在本可完成的轮次关闭前运行,并可通过 steer 使其保持打开。`agent/turn-finalizing` 在所有结束路径中等待资源清理,包括取消;清理结束后才提交 `turn/end` 和发布空闲状态。`agent/assistant-stream` 携带一个进程本地 Assistant attempt 的有序 start、瞬态分片与 end frame。start 给出该 attempt 的轮次与步骤,分片索引从零开始密集递增,`end.index` 则是下一个分片位置。loop 会在 committed end frame 前把完整紧凑流提交为一个 `assistant/message` 或 `assistant/attempt`,因此实时事件仍是呈现数据而非回放来源。`agent/status`、`agent/created` 与 `agent/disposed` 驱动 UI 与协调状态,逐消息的 `agent/inbox/*` 通知则让收件箱投影保持同步。确切签名、分发 mode 与 payload 约定见 [core 子系统页](../../../docs/subsystems/core.zh.md#cordis-surface) 的生成区块。 ----- diff --git a/packages/core/agent/src/dispatch.ts b/packages/core/agent/src/dispatch.ts index 03fd952ac5..1064cd74d1 100644 --- a/packages/core/agent/src/dispatch.ts +++ b/packages/core/agent/src/dispatch.ts @@ -68,6 +68,13 @@ export interface AgentEventDispatch { * @returns the serial chain's result (the first bail value, if any). */ serial(name: K, payload: PayloadRest): Promise>> + /** + * Await every listener, including after another listener fails; reject with all failures. + * @param name - the agent-subject event to dispatch. + * @param payload - the event's payload fields; `agent` is injected. + * @returns completion after all listeners settle. + */ + settled(name: K, payload: PayloadRest): Promise /** * Around-middleware dispatch (Cordis `waterfall`) in the agent's scope. The * declared event parameters already end with the `next` callback, so `rest` @@ -135,6 +142,13 @@ export function agentEvents(ctx: Context, agent: Agent, carrier: Scoped = } } }, + async settled(name, payload) { + const args: unknown[] = [carrier, name, fused(payload)] + const callbacks = ctx.events.dispatch('parallel', args) + const results = await Promise.allSettled(callbacks.map(callback => Promise.resolve().then(() => callback(...args)))) + const errors = results.flatMap(result => result.status === 'rejected' ? [result.reason] : []) + if (errors.length > 0) throw new AggregateError(errors, `Agent event "${name}" failed`) + }, async serial(name, payload) { // oxlint-disable-next-line typescript/unbound-method -- the events mixin accessor returns a pre-bound function const serial = ctx.serial as (thisArg: Scoped, name: string, ...args: unknown[]) => Promise diff --git a/packages/core/agent/src/runtime-types.ts b/packages/core/agent/src/runtime-types.ts index 7012dfdf50..ec2ec9706f 100644 --- a/packages/core/agent/src/runtime-types.ts +++ b/packages/core/agent/src/runtime-types.ts @@ -416,6 +416,17 @@ declare module '@deepseek-ai/cordis' { * @mode serial */ 'agent/turn-stopping'(this: Scoped, payload: { agent: Agent; turn: number; signal: AbortSignal }): Promise | void + /** + * The turn has irrevocably stopped admitting steps. Await all resource finalizers before + * committing turn/end, becoming idle, or starting another turn, including on cancellation. + * Listeners own bounded cleanup independent of the cancelled operation signal. Failures + * are reported through agent/error and the durable turn ending after every listener settles. + * @param payload.agent - the agent whose work has settled. + * @param payload.turn - the turn being finalized. + * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. + * @mode parallel + */ + 'agent/turn-finalizing'(this: Scoped, payload: { agent: Agent; turn: number }): Promise | void // ---- error notifications (emit) ---- /** * A step or turn errored. The machine reports a failure here even when diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index 607de4a959..e146a1a819 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -15,14 +15,14 @@ en: 1777e7bf6785f986 zh: e3daac1074ebb74d /deepseek-ai-dsh-cua-macos/use-this-package: - en: f94dc9734a47325d - zh: 4085438218993e49 + en: 24149124235e72ee + zh: d02e5e844a5e0a83 /deepseek-ai-dsh-cua-macos/use-this-package/connect-an-external-execution-environment: - en: 847dafcf9ca05915 - zh: 6452dcb41b43d014 + en: 3bf05d9ce5eb7224 + zh: d8d0cd6429374860 /deepseek-ai-dsh-cua-macos/understand-the-implementation: - en: d441fbe64f97ddd9 - zh: 821af0f6ac8bb225 + en: ad6bfda9592f4722 + zh: 0a179c77b9ffd894 /deepseek-ai-dsh-cua-macos/further-exploration: en: ff9fac614001a98f zh: 329678941154aaea @@ -45,8 +45,8 @@ en: a2c9acb5a4320dda zh: e8d1586af60215c4 /deepseek-ai-dsh-cua-macos/known-limitations-and-deferred-work: - en: b93e0a9ed7732fc4 - zh: a29e95a99132269e + en: a3639148d575b42e + zh: f51a709fd77a1cfa /deepseek-ai-dsh-cua-macos/known-limitations-and-deferred-work/dev-note: en: b836f01bd0bceb4a zh: 8122fa08b2aa95fa diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index d076664d1d..75f4e9c234 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -83,7 +83,7 @@ The [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-cua-m `pressKey(key, modifiers?)` presses and releases one key. For shortcuts, pass held modifiers separately, as in `pressKey('a', ['command'])`. Pressing a modifier itself, as in `pressKey('shift')`, sets its flag on press and clears it on release. A single `+` or `plus` sends Shift+=. For `pressKey`, `click`, and `drag`, use `command`, `shift`, `option`/`alt`, `control`/`ctrl`, or `fn`. Only `pressKey` accepts `cmd` as a modifier alias for `command`. Key names are platform-defined; keypad names (`KP_0` through `KP_9`, `KP_Enter`, and keypad operators) retain their physical key codes. `typeText` sends literal text, including its line breaks and tabs. Use the App object's `pressKey` for a short press. -For a long press, call `app.sendKeyEvent('w', 'down')` inside `run_code` or `cua_run_code`. The first down holds the key across subsequent tool calls. For an ordinary key already held by this execution, each additional down sends one key-down marked as a repeat to the original process. Choose the interval between calls. A control can filter synthetic repeats, so check its response. One up releases the key. Choose when to send each up: after W down, D down and D up, W stays down. When the program returns, exits with an error, or the user pauses it, the helper releases the remaining keys at the processes that received their downs. A later execution cannot release an earlier execution's keys. +For a long press, call `app.sendKeyEvent('w', 'down')` in an active turn. The key stays down across `run_code` and `cua_run_code` executions, including a program failure when the turn continues. An explicit up releases the key immediately at its original recipient. Repeated down events for an ordinary key retain one hold. Turn completion, failure, and user cancellation release every remaining key and mouse button together in reverse dispatch order. Complete `pressKey`, `typeText`, `click`, and `drag` operations retain their own immediate cleanup. Agent disposal and plugin unload cancel and await the complete tool call, including image admission and attachment storage. An image write already in progress must settle before disposal returns; a canceled call cannot return a successful screenshot. @@ -123,7 +123,7 @@ Use the `cua` API to discover and select the application (`listApps`, `getState` Ordinary `mouseMove(target)` defaults to AX hover. Without both `AXShowAlternateUI` and `AXShowDefaultUI` on an enabled target or ancestor, it returns `HOVER_UNAVAILABLE` without prompting. Only when the task requires physical movement should the main task call `win.mouseMove(target, { useSystemPointer: true })`. On approval the Host rechecks the window and point and dispatches this move. Pass `useSystemPointer: true` on every physical move. Later explicit moves reuse the decision until the session closes or DSH restarts. Omitting the option or passing `false` uses AX. Refusal sends no input. -`win.toggleMouse(button, direction)` sends a window event at the current cursor by default. A press must hit the selected foreground window or it returns `FOREGROUND_REQUIRED`. A release can reach that window after the cursor leaves or focus changes. For a control that reads system button state, pass `{ useSystemPointer: true }` on both press and release. This shares the drag approval. Moving the mouse while the button is held can drag items. The end of the turn or connection releases an outstanding system button. +`win.toggleMouse(button, direction)` sends a window event at the current cursor by default. Down must hit the selected foreground window. For system button state, pass `{ useSystemPointer: true }` on down; this shares the drag approval. Up always uses the saved route, even after focus changes or window closure. System-button cleanup still releases at the current pointer if the original process exits. PID-directed release verifies the saved process identity and skips an exited or reused PID. By default, drag posts mouse events to the target window. For controls that need system button state, use `win.drag(from, to, { useSystemPointer: true })`. This shares the session permission for system-pointer moves. The start and path must hit the foreground window. Cancellation or loss of the target releases the button at the last posted point. @@ -148,6 +148,8 @@ Element clicks use opaque element IDs from the current snapshot. Left clicks sup ## Understand the implementation +The shared helper's `HeldInputs` records task, turn, connection, process generation, application/window and actual input route before each explicit down is posted. One lock orders keyboard and pointer posts and releases. `agent/turn-finalizing` closes host admission, cancels in-flight native work and awaits `releaseHeldInputs` with an independent bounded request. `whenIdle()` and Agent disposal include this wait. Connection shutdown cancels and joins native work before fallback release; a killed host relies on that disconnect path. Repeated cleanup cannot release a later turn's inputs. +
Dispatch and resource ownership @@ -228,7 +230,7 @@ Leave useSystemPointer unset for ordinary mouseMove, drag, and toggleMouse calls Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemPointer?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemPointer omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemPointer?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemPointer: true on both down and up. Physical moves can then drag, including your own mouse movements. The turn ending or the connection closing releases a remaining system hold. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemPointer?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; platform guidance defines their cleanup scope. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemPointer: true on down. Up uses the input route and window saved by down. Physical moves can then drag, including your own mouse movements. Both routes hold across programs in the same turn and release with held keys when the turn ends. click and drag release their own buttons within the operation. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], 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. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying. - 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. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemPointer?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control. An explicit system drag shares the session decision with mouseMove and holds the chosen button along the path in the unobscured foreground window. @@ -240,7 +242,7 @@ Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - 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?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across run_code and cua_run_code calls in the same turn, for example W down, D down, D up, W up. Send 'up' to release it immediately at its original recipient. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. A program returning or throwing keeps its holds while the turn continues. When the turn completes, fails, or is stopped, macOS releases remaining keys and mouse buttons together in reverse press order. pressKey and typeText still release their own presses within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. @@ -265,7 +267,7 @@ The queue orders individual native requests. Holding an app object does not rese -- Window-directed button presses require an explicit release even if the program ends. Send up to the same window in a `finally` block. +- The native acknowledgement confirms event dispatch, not application processing. If turn cleanup is refused, times out, or loses its connection, CUA reports the uncertainty and blocks further input in that task. Check the desktop before starting a new task. - macOS 14 is the minimum supported version; settings navigation, drag acceptance, and permission refresh require qualification on each supported release. If macOS requires quitting and reopening the helper after a Screen Recording change, its preflight check can remain denied until that restart. The guide can be dismissed without terminating other connections. - The guide closes when its selected settings window leaves the visible-window list, including when a Space switch or minimization removes it. Request permission again after returning to reopen the guide. - This provider supports macOS. For Windows, see the [Windows provider](../cua-windows/README.md#setup). Browser tabs, AX diffs, unassociated system panels and accessory-only apps are unsupported. diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index a38566d646..792d5bc251 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -83,7 +83,7 @@ pnpm dsh headless --patch packages/experimental/cua-macos/examples/macos.cordis. `pressKey(key, modifiers?)` 按下并松开一个键。使用快捷键时单独传入修饰键,例如 `pressKey('a', ['command'])`。单独调用 `pressKey('shift')` 时,按下事件带有 Shift 标志,释放事件清除该标志。`+` 和 `plus` 都会发送 Shift 和等号。`pressKey`、`click` 和 `drag` 都接受修饰键 `command`、`shift`、`option`/`alt`、`control`/`ctrl` 和 `fn`。只有 `pressKey` 的修饰键参数还接受 `command` 的别名 `cmd`。按键名由平台定义;数字键盘名称(`KP_0` 到 `KP_9`、`KP_Enter` 和数字键盘运算键)保留独立的物理键码。`typeText` 发送字面文本,包括其中的换行和制表符。短按使用 App 对象上的 `pressKey`。 -长按时,在 `run_code` 或 `cua_run_code` 中调用 `app.sendKeyEvent('w', 'down')`。首次按下后,该键在同一次执行的后续工具调用中保持按下。对自己已按住的普通键再发一次 `down`,原接收进程会收到一次带重复标志的按下事件。调用方决定是否重复和间隔多久。控件可能过滤模拟的重复事件,可通过控件的实际变化确认效果。松键只需一次 `up`。每个键可分别松开。例如先按 W,再按 D,松开 D 后 W 仍按着。程序正常返回、出错退出或用户暂停时,helper 为本次执行仍按着的键逐一发送松开事件,每个事件都发回原接收进程。后续执行不能释放前一次执行的键。 +长按时,在活动回合中调用 `app.sendKeyEvent('w', 'down')`。按键可跨 `run_code` 和 `cua_run_code` 执行保持;程序出错后回合仍继续时,也保留持有状态。显式 `up` 立即向原接收方释放按键。普通键的重复 `down` 只保留一条持有记录。回合正常完成、异常结束和用户停止时,所有仍按住的键盘键与鼠标按钮按实际派发顺序的反序统一释放。完整的 `pressKey`、`typeText`、`click` 和 `drag` 操作仍自行及时清理。 Agent 销毁和插件卸载会取消并等待完整工具调用,包括图像接入检查和附件存储。已经开始的图像写入必须结束后,销毁才会返回;已取消的调用不会返回成功截图。 @@ -123,7 +123,7 @@ inspect(await window.getScreenshot()) 普通 `mouseMove(target)` 默认通过辅助功能悬停。如果目标或其祖先没有同时声明 `AXShowAlternateUI` 和 `AXShowDefaultUI`,则返回 `HOVER_UNAVAILABLE`,不会弹窗。只有任务确实需要移动用户的鼠标时,主任务才调用 `win.mouseMove(target, { useSystemPointer: true })`。用户允许后,Host 重新检查窗口和目标位置,再执行本次移动。每次移动系统指针都要显式传 `useSystemPointer: true`。省略参数或传 `false` 时使用辅助功能悬停。拒绝时不派发输入。会话记住此次选择,直到关闭会话或重启 DSH。 -默认情况下,`win.toggleMouse(button, direction)` 在当前指针位置向所选窗口发送事件。按下要求指针命中前台应用的所选窗口,否则返回 `FOREGROUND_REQUIRED`。松开允许指针移出窗口或应用失去焦点。只有控件需要读取系统鼠标键状态时,才在按下和松开时都传 `{ useSystemPointer: true }`。系统模式与拖动共用会话审批,按住期间用户移动鼠标也可能触发拖动。任务回合结束或连接关闭时会松开剩余的系统按键。 +`win.toggleMouse(button, direction)` 默认向窗口发送当前鼠标位置的事件。按下时必须命中选定的前台窗口。需要系统按钮状态时,在 `down` 上传入 `{ useSystemPointer: true }`,沿用拖动审批。`up` 始终使用保存的输入方式和窗口,即使焦点改变或窗口关闭也如此。原进程退出后,系统按钮清理仍在当前鼠标位置释放;定向释放会检查保存的进程身份,跳过已退出或复用的 PID。 默认拖动向目标窗口发送鼠标事件。需要系统鼠标按键状态的控件可使用 `win.drag(from, to, { useSystemPointer: true })`。该操作与系统指针移动共用会话授权,起点和拖动路径必须位于可接收输入的前台窗口内。取消或失去目标窗口时,helper 在最后投递的位置释放鼠标键。 @@ -148,6 +148,8 @@ AppKit 的 sheet 可以出现在文档窗口的树里,并有独立的窗口 ID ## 理解实现 +共享 helper 的 `HeldInputs` 在每次显式按下派发前记录任务、回合、连接、进程代次、应用或窗口和实际输入方式。同一把锁维护键盘与鼠标的派发和释放顺序。`agent/turn-finalizing` 关闭宿主输入准入、取消在途原生操作,并通过独立且有超时限制的请求等待 `releaseHeldInputs` 确认。`whenIdle()` 和 Agent 销毁都包含这段等待。连接关闭会先取消并等待原生操作停止,再做兜底释放;宿主被强杀时依靠这条断连路径。重复清理不会释放后续回合的输入。 +
操作分派与资源归属 @@ -228,7 +230,7 @@ Leave useSystemPointer unset for ordinary mouseMove, drag, and toggleMouse calls Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemPointer?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemPointer omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemPointer?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemPointer: true on both down and up. Physical moves can then drag, including your own mouse movements. The turn ending or the connection closing releases a remaining system hold. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemPointer?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; platform guidance defines their cleanup scope. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemPointer: true on down. Up uses the input route and window saved by down. Physical moves can then drag, including your own mouse movements. Both routes hold across programs in the same turn and release with held keys when the turn ends. click and drag release their own buttons within the operation. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], 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. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying. - 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. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemPointer?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control. An explicit system drag shares the session decision with mouseMove and holds the chosen button along the path in the unobscured foreground window. @@ -240,7 +242,7 @@ Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - 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?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across run_code and cua_run_code calls in the same turn, for example W down, D down, D up, W up. Send 'up' to release it immediately at its original recipient. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. A program returning or throwing keeps its holds while the turn continues. When the turn completes, fails, or is stopped, macOS releases remaining keys and mouse buttons together in reverse press order. pressKey and typeText still release their own presses within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. @@ -265,7 +267,7 @@ Only if the task cannot be completed without moving the user’s pointer, call a -- 默认窗口模式下,程序结束时不会自动补发松开事件。调用方应在 `finally` 中向原窗口发送 `up`。 +- 原生确认表示事件已派发,不表示应用已处理。回合清理被拒绝、超时或断连时,CUA 会报告不确定结果,并禁止该任务继续发送输入。检查桌面状态后再创建新任务。 - 最低支持 macOS 14;设置导航、拖放接收和权限刷新需要在各支持版本验收。若 macOS 要求在修改屏幕录制权限后退出并重新打开 helper,权限检查在重启前可能仍返回未授权。可以关闭引导框,不必终止其他连接。 - 所选设置窗口离开可见窗口列表时,引导框会关闭,包括切换桌面空间或最小化导致窗口不再可见的情况。返回后再次申请权限可重新打开引导。 - 本提供方适用于 macOS。Windows 的配置见 [Windows 提供方](../cua-windows/README.zh.md#setup)。不支持浏览器标签、AX 差分、无法确认应用归属的系统面板和仅后台辅助类型的应用。 diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift index 7bc12e9c2d..5eeba2157f 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift @@ -81,15 +81,17 @@ actor AXWorker { private let maxClickHoldMs: Int private let sessionState: @Sendable () -> Bool? private var access: AXAccess? - private let heldKeys: HeldKeys + private let connectionID: UUID + private let heldInputs: HeldInputs private var keyboard: KeyboardInput? private var pointer: WindowPointerInput? private var hovers: [String: AXHover] = [:] private var closed = false - init(cancellation: CancellationLatch, axTimeout: Float, textEventInterval: Double, maxClickHoldMs: Int, heldKeys: HeldKeys = HeldKeys(), + init(cancellation: CancellationLatch, axTimeout: Float, textEventInterval: Double, maxClickHoldMs: Int, heldInputs: HeldInputs = HeldInputs(), connectionID: UUID = UUID(), sessionState: @escaping @Sendable () -> Bool? = NativePlatform.sessionLocked) { - self.heldKeys = heldKeys + self.heldInputs = heldInputs + self.connectionID = connectionID self.cancellation = cancellation self.axTimeout = axTimeout self.textEventInterval = textEventInterval @@ -119,8 +121,8 @@ actor AXWorker { if let keyboard, let pointer { return (keyboard, pointer) } let poster = PIDEventPoster() let latch = cancellation - let key = KeyboardInput(post: poster.post, textEventInterval: textEventInterval, held: heldKeys, checkCancellation: { try latch.check() }) - let mouse = WindowPointerInput(poster: poster, checkCancellation: { try latch.check() }) + let key = KeyboardInput(post: poster.post, textEventInterval: textEventInterval, held: heldInputs, connection: connectionID, checkCancellation: { try latch.check() }) + let mouse = WindowPointerInput(poster: poster, held: heldInputs, checkCancellation: { try latch.check() }) keyboard = key; pointer = mouse return (key, mouse) } @@ -199,14 +201,10 @@ actor AXWorker { trace: ScreenshotTrace? = nil) async throws -> DriverOutcome { try cancellation.check() guard !closed else { throw NativeFailure(code: "NATIVE_CLOSED", message: "Helper is closing") } - if method == "releaseHeldKeys" { - try keyboard?.releaseHeldKeys(run: params.string("runId")) - return .result(Self.actionResult) - } var recovery = AXChildRecoveryBudget(maxElements: NativeProtocol.elementRange.upperBound, timeout: axTimeout) if method == "sendKeyEvent", try params.string("direction") == "up" { let handle = try params.string("appHandle") - let dispatched = try inputs().0.keyUp(params.string("key"), app: handle, run: params.string("runId")) { + let dispatched = try inputs().0.keyUp(params.string("key"), app: handle, scope: params.inputScope()) { try NativePlatform.requireUnlocked(observeSession()) try NativePlatform.requireAccessibility() return try ax().keyboardRecipient(validateIdentity(handle), catalog: catalog, budget: &recovery) @@ -348,7 +346,7 @@ actor AXWorker { readTimeout: .milliseconds(try params.integer("pasteReadTimeoutMs", in: 1...2147483647)), maxElements: try params.integer("maxElements", in: NativeProtocol.elementRange), maxDepth: try params.integer("maxDepth", in: NativeProtocol.depthRange))) case "sendKeyEvent": - try inputs().0.keyDown(params.string("key"), app: handle, run: params.string("runId")) { + try inputs().0.keyDown(params.string("key"), app: handle, scope: params.inputScope()) { try ax().keyboardRecipient(identity, catalog: catalog, budget: &recovery) } case "typeText", "pressKey": @@ -372,22 +370,16 @@ actor AXWorker { suffix: params.optionalString("suffix"), mode: params.optionalString("selectionType") ?? "text") case "toggleMouse": let id = try params.windowID() - let isDown = try params.string("direction") == "down" - let window: WindowInfo - if isDown { - guard NativePlatform.frontPID() == identity.pid else { - throw NativeFailure(code: "FOREGROUND_REQUIRED", message: "Activate the selected application before pressing a mouse button") - } - window = try ax().coordinateWindow(identity, id, budget: &recovery).window - } else { - window = try NativePlatform.ownedWindow(identity.pid, id) + guard NativePlatform.frontPID() == identity.pid else { + throw NativeFailure(code: "FOREGROUND_REQUIRED", message: "Activate the selected application before pressing a mouse button") } + let window = try ax().coordinateWindow(identity, id, budget: &recovery).window let route = WindowRoute(owner: identity, windowID: id, bounds: window.bounds) if try params.optionalBoolean("useSystemPointer") == true { return .systemButtonDown(route, try WindowPointerInput.button(params.string("mouseButton"))) } - try await inputs().1.toggleMouse(in: route, - button: params.string("mouseButton"), isDown: isDown) + try await inputs().1.mouseDown(owner: .init(connection: connectionID, scope: params.inputScope(), app: handle), + in: route, button: params.string("mouseButton")) case "click", "mouseMove": let useSystemPointer = try params.optionalBoolean("useSystemPointer") ?? false let holdMs = params.contains("holdMs") ? try params.integer("holdMs", in: 0...maxClickHoldMs) : nil @@ -541,8 +533,6 @@ actor AXWorker { .object(["dispatched": .bool(true), "hoverRoute": .string(route), "systemPointerMoved": .bool(pointerMoved)]) } func shutdown() { - do { try keyboard?.releaseHeldKeys() } - catch { fputs("Could not release held keys on disconnect: \(error)\n", stderr) } closed = true; snapshots.removeAll(); observedWindowBounds.removeAll(); targets.removeAll(); hovers.removeAll() access = nil; keyboard = nil; pointer = nil } diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/HeldInputs.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/HeldInputs.swift new file mode 100644 index 0000000000..4c7e0a5585 --- /dev/null +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/HeldInputs.swift @@ -0,0 +1,211 @@ +// One ledger orders key and pointer posts across the shared helper's workers and connections. +import CoreGraphics +import Foundation + +/// The lock covers registration, dispatch, explicit release, and reverse-order cleanup. +final class HeldInputs: @unchecked Sendable { + struct Scope: Equatable { + let task: String + let turn: Int + } + struct Owner: Equatable { + let connection: UUID + let scope: Scope + let app: String + } + enum Mode: Equatable { + case keyboard(CGKeyCode, CGEventFlags) + case windowPointer(CGMouseButton, UInt32) + case systemPointer(CGMouseButton, UInt32) + } + private struct Press { + let owner: Owner + let recipient: ProcessIdentity + let mode: Mode + let up: CGEvent + let post: (CGEvent) -> Void + } + private let lock = NSLock() + private var pressed: [Press] = [] + private var ended: [UUID: [String: Int]] = [:] + + func snapshot(pid: Int32) -> [CGKeyCode: CGEventFlags] { + lock.withLock { + Dictionary(uniqueKeysWithValues: pressed.compactMap { + guard $0.recipient.pid == pid, case .keyboard(let code, let flag) = $0.mode else { return nil } + return (code, flag) + }) + } + } + + private func admit(_ owner: Owner) throws { + if let last = ended[owner.connection]?[owner.scope.task], owner.scope.turn <= last { + throw NativeFailure(code: "INPUT_TURN_CLOSED", message: "Input for this turn has already been released") + } + } + + private func conflict(_ name: String, holder: Owner, caller: Owner) -> NativeFailure { + let source: String + if holder.connection != caller.connection { source = "another session" } + else if holder.scope != caller.scope { source = "another turn" } + else { source = "a different application handle in this turn" } + return RequestParameters.invalid("Key '\(name)' is held for this target by \(source). No event was sent. Wait for the holder to release it or for its turn to end.") + } + + /// Repeats retain the original recipient and do not change the cleanup order. + func repeatIfHeld(owner: Owner, name: String, code: CGKeyCode, down: CGEvent, post: (CGEvent, Int32) -> Void) throws -> Bool { + try lock.withLock { + try admit(owner) + guard let key = pressed.first(where: { $0.owner == owner && $0.mode.keyCode == code }) else { return false } + guard case .keyboard(_, let flag) = key.mode, flag.isEmpty, down.type == .keyDown else { + throw RequestParameters.invalid("Modifier '\(name)' is already held. Send 'up' to release it.") + } + try NativePlatform.verify(key.recipient) + down.flags = flags(for: key.recipient) + down.setIntegerValueField(.keyboardEventAutorepeat, value: 1) + post(down, key.recipient.pid) + return true + } + } + + func keyDown(owner: Owner, recipient: ProcessIdentity, name: String, code: CGKeyCode, flag: CGEventFlags, + down: CGEvent, up: CGEvent, post: @escaping (CGEvent, Int32) -> Void) throws { + try lock.withLock { + try admit(owner) + if let key = pressed.first(where: { $0.mode.keyCode == code && $0.recipient.pid == recipient.pid }) { + throw conflict(name, holder: key.owner, caller: owner) + } + pressed.append(Press(owner: owner, recipient: recipient, mode: .keyboard(code, flag), up: up, + post: { post($0, recipient.pid) })) + down.flags = flags(for: recipient) + post(down, recipient.pid) + } + } + + private func flags(for recipient: ProcessIdentity) -> CGEventFlags { + pressed.reduce(into: CGEventFlags()) { + if $1.recipient == recipient, case .keyboard(_, let flag) = $1.mode { $0.formUnion(flag) } + } + } + + /// System releases must reach the desktop even after the original process or window disappears. + private func release(at index: Int) throws -> Bool { + let press = pressed[index] + if case .systemPointer = press.mode { + if let point = CGEvent(source: nil)?.location { press.up.location = point } + } else { + do { try NativePlatform.verify(press.recipient) } + catch let error as NativeFailure where error.code == "STALE_APP" || error.code == "APP_UNAVAILABLE" { + pressed.remove(at: index) + return false + } + } + pressed.remove(at: index) + if case .keyboard = press.mode { press.up.flags = flags(for: press.recipient) } + press.post(press.up) + return true + } + + func keyUp(owner: Owner, name: String, code: CGKeyCode, recipientIfUnheld: () throws -> ProcessIdentity) throws -> Bool { + let dispatched = try lock.withLock { () throws -> Bool? in + guard let index = pressed.firstIndex(where: { $0.owner == owner && $0.mode.keyCode == code }) else { return nil } + return try release(at: index) + } + if let dispatched { return dispatched } + let recipient = try recipientIfUnheld() + throw lock.withLock { + if let key = pressed.first(where: { $0.mode.keyCode == code && $0.recipient == recipient }) { + return conflict(name, holder: key.owner, caller: owner) + } + return RequestParameters.invalid("Key '\(name)' is not held for this target. Send 'down' in this turn before 'up'.") + } + } + + func pointerDown(owner: Owner, route: WindowRoute, button: CGMouseButton, system: Bool, + down: CGEvent, up: CGEvent, post: @escaping (CGEvent) -> Void) throws { + try lock.withLock { + try admit(owner) + try checkPointerAvailable(route: route, button: button, system: system) + pressed.append(Press(owner: owner, recipient: route.owner, + mode: system ? .systemPointer(button, route.windowID) : .windowPointer(button, route.windowID), up: up, post: post)) + post(down) + } + } + + /// A balanced action cannot release another operation's held mouse button. + func requirePointerAvailable(route: WindowRoute, button: CGMouseButton, system: Bool) throws { + try lock.withLock { try checkPointerAvailable(route: route, button: button, system: system) } + } + + private func checkPointerAvailable(route: WindowRoute, button: CGMouseButton, system: Bool) throws { + if pressed.contains(where: { press in + switch press.mode { + case .keyboard: return false + case .systemPointer: return true + case .windowPointer(let held, _): return system || (held == button && press.recipient == route.owner) + } + }) { throw Self.pointerBusy } + } + + /// The requested routing option is irrelevant to an up: use the route saved by its down. + func pointerUp(owner: Owner, window: UInt32, button: CGMouseButton) throws -> Bool { + try lock.withLock { + guard let index = pressed.firstIndex(where: { $0.owner == owner && $0.mode.pointer == button && $0.mode.window == window }) else { + throw RequestParameters.invalid("Release the mouse button through the same task, turn, application and window that pressed it") + } + return try release(at: index) + } + } + + /// Create and post movement under the same lock as ownership and the saved release point. + func moveSystem(owner: Owner, route: WindowRoute, screen: CGPoint, checkCancellation: () throws -> Void) throws { + try lock.withLock { + try admit(owner) + let press = pressed.first { if case .systemPointer = $0.mode { return true }; return false } + let event: CGEvent + if let press { + guard press.owner == owner, press.recipient == route.owner, press.mode.window == route.windowID, + let button = press.mode.pointer else { throw Self.pointerBusy } + event = try SystemPointerInput.event(WindowPointerInput.dragged(button), source: nil, at: screen, + button: button, group: press.up.getIntegerValueField(.mouseEventNumber)) + let previous = CGEvent(source: nil)?.location ?? press.up.location + event.setIntegerValueField(.mouseEventDeltaX, value: Int64(screen.x.rounded() - previous.x.rounded())) + event.setIntegerValueField(.mouseEventDeltaY, value: Int64(screen.y.rounded() - previous.y.rounded())) + } else { + event = try SystemPointerInput.event(.mouseMoved, source: nil, at: screen, button: .left, group: 0) + } + try checkCancellation() + SystemPointerInput.post(event) + press?.up.location = screen + } + } + + func release(connection: UUID, scope: Scope? = nil) throws { + try lock.withLock { + if let scope { ended[connection, default: [:]][scope.task] = max(ended[connection]?[scope.task] ?? 0, scope.turn) } + defer { if scope == nil { ended.removeValue(forKey: connection) } } + var failures: [String] = [] + for index in pressed.indices.reversed() { + let owner = pressed[index].owner + guard owner.connection == connection, scope == nil || owner.scope == scope else { continue } + do { _ = try release(at: index) } + catch { failures.append(String(describing: error)) } + } + if !failures.isEmpty { throw NativeFailure(code: "INPUT_CLEANUP_FAILED", message: failures.joined(separator: "; ")) } + } + } + + private static var pointerBusy: NativeFailure { + NativeFailure(code: "INPUT_BUSY", message: "A mouse button is held; release it before dispatching a conflicting gesture") + } +} + +private extension HeldInputs.Mode { + var keyCode: CGKeyCode? { if case .keyboard(let code, _) = self { return code }; return nil } + var pointer: CGMouseButton? { + switch self { case .keyboard: return nil; case .windowPointer(let button, _), .systemPointer(let button, _): return button } + } + var window: UInt32? { + switch self { case .keyboard: return nil; case .windowPointer(_, let window), .systemPointer(_, let window): return window } + } +} diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/HeldKeys.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/HeldKeys.swift deleted file mode 100644 index 3d29795127..0000000000 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/HeldKeys.swift +++ /dev/null @@ -1,114 +0,0 @@ -// All connections to the shared helper deliver to the same desktop processes. -import CoreGraphics -import Foundation - -/// The lock covers both the held-key records and their corresponding PID-targeted event posts. -/// Shutdown may release a connection's keys outside the ordinary request scheduler. -final class HeldKeys: @unchecked Sendable { - struct Owner: Equatable { - let connection: UUID - let run: String - let app: String - } - - private struct Press { - let owner: Owner - let recipient: ProcessIdentity - let code: CGKeyCode - let flag: CGEventFlags - let up: CGEvent - } - - private let lock = NSLock() - private var pressed: [Press] = [] - - func snapshot(pid: Int32) -> [CGKeyCode: CGEventFlags] { - lock.withLock { Dictionary(uniqueKeysWithValues: pressed.filter { $0.recipient.pid == pid }.map { ($0.code, $0.flag) }) } - } - - private func conflict(_ name: String, holder: Owner, caller: Owner) -> NativeFailure { - let source: String - if holder.connection != caller.connection { source = "another session" } - else if holder.run != caller.run { source = "another run_code execution" } - else { source = "a different application handle in this run_code" } - return RequestParameters.invalid("Key '\(name)' is held for this target by \(source). No event was sent. Wait for the holder to release it or for its run_code to end.") - } - - /// Repeats use the saved recipient even when the selected application's focused panel has changed. - func repeatIfHeld(owner: Owner, name: String, code: CGKeyCode, down: CGEvent, post: (CGEvent, Int32) -> Void) throws -> Bool { - try lock.withLock { - guard let key = pressed.first(where: { $0.owner == owner && $0.code == code }) else { return false } - guard key.flag.isEmpty, down.type == .keyDown else { - throw RequestParameters.invalid("Modifier '\(name)' is already held. Send 'up' to release it.") - } - try NativePlatform.verify(key.recipient) - down.flags = flags(for: key.recipient) - down.setIntegerValueField(.keyboardEventAutorepeat, value: 1) - post(down, key.recipient.pid) - return true - } - } - - func down(owner: Owner, recipient: ProcessIdentity, name: String, code: CGKeyCode, flag: CGEventFlags, - down: CGEvent, up: CGEvent, post: (CGEvent, Int32) -> Void) throws { - try lock.withLock { - if let key = pressed.first(where: { $0.code == code && $0.recipient.pid == recipient.pid }) { - throw conflict(name, holder: key.owner, caller: owner) - } - pressed.append(Press(owner: owner, recipient: recipient, code: code, flag: flag, up: up)) - down.flags = flags(for: recipient) - post(down, recipient.pid) - } - } - - private func flags(for recipient: ProcessIdentity) -> CGEventFlags { - pressed.reduce(into: CGEventFlags()) { if $1.recipient == recipient { $0.formUnion($1.flag) } } - } - - /// An up always targets the process selected at down. Never post to a recycled PID. - private func release(at index: Int, post: (CGEvent, Int32) -> Void) throws -> Bool { - let key = pressed[index] - do { try NativePlatform.verify(key.recipient) } - catch let error as NativeFailure where error.code == "STALE_APP" || error.code == "APP_UNAVAILABLE" { - pressed.remove(at: index) - return false - } - pressed.remove(at: index) - key.up.flags = flags(for: key.recipient) - post(key.up, key.recipient.pid) - return true - } - - func up(owner: Owner, name: String, code: CGKeyCode, recipientIfUnheld: () throws -> ProcessIdentity, - post: (CGEvent, Int32) -> Void) throws -> Bool { - let dispatched = try lock.withLock { () throws -> Bool? in - guard let index = pressed.firstIndex(where: { $0.owner == owner && $0.code == code }) else { return nil } - return try release(at: index, post: post) - } - if let dispatched { return dispatched } - let recipient = try recipientIfUnheld() - throw lock.withLock { - if let key = pressed.first(where: { $0.code == code && $0.recipient == recipient }) { - return conflict(name, holder: key.owner, caller: owner) - } - return RequestParameters.invalid("Key '\(name)' is not held for this target. Send 'down' in this run_code before 'up'.") - } - } - - func release(connection: UUID, run: String?, post: (CGEvent, Int32) -> Void) throws { - try lock.withLock { - defer { - // A closed connection cannot retry an unverifiable recipient. - if run == nil { pressed.removeAll { $0.owner.connection == connection } } - } - var firstError: Error? - for index in pressed.indices.reversed() { - let owner = pressed[index].owner - guard owner.connection == connection, run == nil || owner.run == run else { continue } - do { _ = try release(at: index, post: post) } - catch { firstError = firstError ?? error } - } - if let firstError { throw firstError } - } - } -} diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift index b435d4e46b..cbceb54806 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift @@ -9,21 +9,22 @@ final class KeyboardInput { let flag: CGEventFlags } - private let connection = UUID() - private let held: HeldKeys + private let connection: UUID + private let held: HeldInputs private let post: (CGEvent, Int32) -> Void private let textEventInterval: Double private let checkCancellation: @Sendable () throws -> Void - init(post: @escaping (CGEvent, Int32) -> Void, textEventInterval: Double, held: HeldKeys = HeldKeys(), checkCancellation: @escaping @Sendable () throws -> Void = {}) { + init(post: @escaping (CGEvent, Int32) -> Void, textEventInterval: Double, held: HeldInputs = HeldInputs(), connection: UUID = UUID(), checkCancellation: @escaping @Sendable () throws -> Void = {}) { self.held = held + self.connection = connection self.post = post self.textEventInterval = textEventInterval self.checkCancellation = checkCancellation } - func keyDown(_ name: String, app: String, run: String, recipient: () throws -> ProcessIdentity) throws { - let owner = HeldKeys.Owner(connection: connection, run: run, app: app) + func keyDown(_ name: String, app: String, scope: HeldInputs.Scope, recipient: () throws -> ProcessIdentity) throws { + let owner = HeldInputs.Owner(connection: connection, scope: scope, app: app) let code = try Self.keyCode(name) let source = try Self.source() let down = try Self.keyEvent(source: source, code: code, down: true, flags: []) @@ -33,17 +34,13 @@ final class KeyboardInput { let up = try Self.keyEvent(source: source, code: code, down: false, flags: []) try checkCancellation() try NativePlatform.verify(target) - try held.down(owner: owner, recipient: target, name: name, code: code, flag: Self.namedModifier(name)?.flag ?? [], + try held.keyDown(owner: owner, recipient: target, name: name, code: code, flag: Self.namedModifier(name)?.flag ?? [], down: down, up: up, post: post) } - func keyUp(_ name: String, app: String, run: String, recipientIfUnheld: () throws -> ProcessIdentity) throws -> Bool { - try held.up(owner: .init(connection: connection, run: run, app: app), name: name, code: Self.keyCode(name), - recipientIfUnheld: recipientIfUnheld, post: post) - } - - func releaseHeldKeys(run: String? = nil) throws { - try held.release(connection: connection, run: run, post: post) + func keyUp(_ name: String, app: String, scope: HeldInputs.Scope, recipientIfUnheld: () throws -> ProcessIdentity) throws -> Bool { + try held.keyUp(owner: .init(connection: connection, scope: scope, app: app), name: name, code: Self.keyCode(name), + recipientIfUnheld: recipientIfUnheld) } /// Prepare every event before dispatch. On cancellation, release only the keys this call pressed. @@ -56,7 +53,7 @@ final class KeyboardInput { chord.append(Key(keyCode: code, flag: Self.namedModifier(name)?.flag ?? [])) let alreadyHeld = held.snapshot(pid: pid) guard alreadyHeld[code] == nil else { - throw RequestParameters.invalid("Key '\(name)' is already held for this target. Use pressKey after the run_code that holds it releases it.") + throw RequestParameters.invalid("Key '\(name)' is already held for this target. Release it before using pressKey.") } var selected = Set(alreadyHeld.keys) var flags = alreadyHeld.values.reduce(CGEventFlags()) { $0.union($1) } diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift index 62d3ae2155..bb2ef0c7c0 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift @@ -16,22 +16,21 @@ enum NativeProtocol { "listActions": ["appHandle", "elementId", "snapshotId", "windowId"], "listApps": [], "listWindows": ["appHandle"], - "mouseMove": ["appHandle", "elementId", "snapshotId", "useSystemPointer", "windowId", "x", "y"], + "mouseMove": ["appHandle", "elementId", "snapshotId", "taskId", "turn", "useSystemPointer", "windowId", "x", "y"], "openPermissionSettings": ["permission", "settingsMessage"], "paste": ["appHandle", "format", "maxClipboardBytes", "maxDepth", "maxElements", "pasteReadTimeoutMs", "text", "windowId"], "performAction": ["action", "appHandle", "argument", "elementId", "snapshotId", "windowId"], "permissionStatus": [], "pressKey": ["appHandle", "key", "modifiers", "windowId"], - "releaseHeldKeys": ["runId"], - "releaseSystemButton": [], + "releaseHeldInputs": ["taskId", "turn"], "requestPermission": ["backLabel", "finderLabel", "instruction", "permission", "pollIntervalMs", "settingsMessage", "unavailableMessage"], "screenshot": ["appHandle", "windowId"], "scroll": ["appHandle", "deltaLinesX", "deltaLinesY", "snapshotId", "windowId", "x", "y"], "selectText": ["appHandle", "elementId", "prefix", "selectionType", "snapshotId", "suffix", "text", "windowId"], - "sendKeyEvent": ["appHandle", "direction", "key", "runId", "windowId"], + "sendKeyEvent": ["appHandle", "direction", "key", "taskId", "turn", "windowId"], "setValue": ["appHandle", "elementId", "snapshotId", "value", "windowId"], "show": ["appHandle", "windowId"], - "toggleMouse": ["appHandle", "direction", "mouseButton", "useSystemPointer", "windowId"], + "toggleMouse": ["appHandle", "direction", "mouseButton", "taskId", "turn", "useSystemPointer", "windowId"], "typeText": ["appHandle", "text", "windowId"], ] static let stringEnums: [String: [String: Set]] = [ diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestAdmission.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestAdmission.swift index 9ebb8c4877..0c1450889c 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestAdmission.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestAdmission.swift @@ -81,3 +81,9 @@ struct RequestParameters: Sendable { } func point(_ x: String = "x", _ y: String = "y") throws -> WindowPoint { WindowPoint(x: try number(x), y: try number(y)) } } + +extension RequestParameters { + func inputScope() throws -> HeldInputs.Scope { + try HeldInputs.Scope(task: string("taskId"), turn: integer("turn", in: 1...Int.max)) + } +} diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift index 73d80be2bd..f606fb9740 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift @@ -43,7 +43,7 @@ import Darwin self.onFatal = onFatal worker = AXWorker(cancellation: cancellation, axTimeout: configuration.axTimeoutSeconds, textEventInterval: configuration.textEventIntervalSeconds, maxClickHoldMs: configuration.maxClickHoldMs, - heldKeys: scheduler.heldKeys) + heldInputs: scheduler.heldInputs, connectionID: connectionID) input = JSONLInput(limit: configuration.maxRequestBytes, cancellation: cancellation, channel: channel) self.writer = writer } @@ -165,15 +165,14 @@ import Darwin private func execute(_ request: NativeRequest, trace: ScreenshotTrace?) async throws -> JSONValue { let params = try RequestParameters(request) try cancellation.check() - if request.method == "releaseSystemButton" { - scheduler.systemPointer.release(connection: connectionID) + if request.method == "releaseHeldInputs" { + try scheduler.heldInputs.release(connection: connectionID, scope: params.inputScope()) return AXWorker.actionResult } - if request.method == "toggleMouse", try params.optionalBoolean("useSystemPointer") == true, - try params.string("direction") == "up" { - try scheduler.systemPointer.up(connection: connectionID, app: params.string("appHandle"), window: params.windowID(), - button: WindowPointerInput.button(params.string("mouseButton"))) - return AXWorker.actionResult + if request.method == "toggleMouse", try params.string("direction") == "up" { + let dispatched = try scheduler.heldInputs.pointerUp(owner: .init(connection: connectionID, scope: params.inputScope(), + app: params.string("appHandle")), window: params.windowID(), button: WindowPointerInput.button(params.string("mouseButton"))) + return .object(["dispatched": .bool(dispatched)]) } if request.method == "screenshot" { try capture.requireAvailable() } let requiresCatalog = ["getApp", "launchApp", "listApps", "findApps", "typeText", "pressKey", "sendKeyEvent", "click"].contains(request.method) @@ -224,10 +223,10 @@ import Darwin case .foreground(let plan): result = try await performForeground(plan, requestID: request.id) case .mouseMove(let route, let point): let latch = cancellation - try scheduler.systemPointer.move(connection: connectionID, in: route, at: point, checkCancellation: { try latch.check() }) + try scheduler.systemPointer.move(owner: .init(connection: connectionID, scope: params.inputScope(), app: params.string("appHandle")), in: route, at: point, checkCancellation: { try latch.check() }) result = AXWorker.mouseMoveResult(route: "system-pointer", pointerMoved: true) case .systemButtonDown(let route, let button): - try scheduler.systemPointer.down(connection: connectionID, app: params.string("appHandle"), in: route, button: button, + try scheduler.systemPointer.down(owner: .init(connection: connectionID, scope: params.inputScope(), app: params.string("appHandle")), in: route, button: button, checkCancellation: { try cancellation.check() }) result = AXWorker.actionResult case .paste(let plan): @@ -270,7 +269,6 @@ import Darwin stopping = true permissions.closeGuide(owner: connectionID) cancellation.cancel() - scheduler.systemPointer.release(connection: connectionID) deadline?.cancel() deadline = nil cancelRequest(NativeFailure(code: "NATIVE_CANCELLED", message: "Native client disconnected")) @@ -285,6 +283,8 @@ import Darwin await pending?.value deadline?.cancel() deadline = nil + do { try scheduler.heldInputs.release(connection: connectionID) } + catch { fputs("Could not confirm input release on disconnect: \(error)\n", stderr) } await worker.shutdown() onClose() } diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestScheduler.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestScheduler.swift index d2e0c051d5..856ae4dcc0 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestScheduler.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestScheduler.swift @@ -7,8 +7,8 @@ import Dispatch let id: UUID let continuation: CheckedContinuation } - let heldKeys = HeldKeys() - let systemPointer = SystemPointerInput() + let heldInputs = HeldInputs() + lazy var systemPointer = SystemPointerInput(held: heldInputs) private var owner: UUID? private var waiting: [Waiting] = [] diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/SystemPointerInput.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/SystemPointerInput.swift index 06ad68fe9e..fac58df0b4 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/SystemPointerInput.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/SystemPointerInput.swift @@ -1,18 +1,12 @@ -// The shared desktop has one system pointer. Its held button belongs to the connection and window that pressed it. +// System pointer validation; HeldInputs owns every persistent button press. import CoreGraphics import Dispatch import Foundation @MainActor final class SystemPointerInput { - private struct Press { - let connection: UUID - let app: String - let route: WindowRoute - let button: CGMouseButton - let group: Int64 - let release: CGEvent - } - private var press: Press? + private let held: HeldInputs + + init(held: HeldInputs) { self.held = held } nonisolated static func event(_ type: CGEventType, source: CGEventSource?, at screen: CGPoint, button: CGMouseButton, group: Int64, flags: CGEventFlags = []) throws -> CGEvent { @@ -30,8 +24,7 @@ import Foundation event.post(tap: .cghidEventTap) } - func down(connection: UUID, app: String, in route: WindowRoute, button: CGMouseButton, checkCancellation: () throws -> Void) throws { - guard press == nil else { throw Self.busy } + func down(owner: HeldInputs.Owner, in route: WindowRoute, button: CGMouseButton, checkCancellation: () throws -> Void) throws { try WindowPointerInput.validateWindow(route) guard let point = CGEvent(source: nil)?.location else { throw NativeFailure(code: "NATIVE_ERROR", message: "Could not read the current pointer position") @@ -42,48 +35,15 @@ import Foundation let down = try Self.event(WindowPointerInput.down(button), source: nil, at: point, button: button, group: group) let up = try Self.event(WindowPointerInput.up(button), source: nil, at: point, button: button, group: group) try checkCancellation() - press = Press(connection: connection, app: app, route: route, button: button, group: group, release: up) - Self.post(down) + try held.pointerDown(owner: owner, route: route, button: button, system: true, down: down, up: up, post: Self.post) } - func move(connection: UUID, in route: WindowRoute, at point: WindowPoint, checkCancellation: () throws -> Void) throws { + func move(owner: HeldInputs.Owner, in route: WindowRoute, at point: WindowPoint, checkCancellation: () throws -> Void) throws { try WindowPointerInput.validate(point, in: route) try WindowPointerInput.validateWindow(route) let screen = WindowPointerInput.screenPoint(point, in: route) try WindowPointerInput.checkSystemHit(route, at: screen) - let event: CGEvent - if let press { - guard press.connection == connection, press.route.owner == route.owner, press.route.windowID == route.windowID else { throw Self.busy } - let button = press.button - event = try Self.event(WindowPointerInput.dragged(button), source: nil, at: screen, button: button, group: press.group) - let previous = CGEvent(source: nil)?.location ?? press.release.location - event.setIntegerValueField(.mouseEventDeltaX, value: Int64(screen.x.rounded() - previous.x.rounded())) - event.setIntegerValueField(.mouseEventDeltaY, value: Int64(screen.y.rounded() - previous.y.rounded())) - } else { - event = try Self.event(.mouseMoved, source: nil, at: screen, button: .left, group: 0) - } + try held.moveSystem(owner: owner, route: route, screen: screen, checkCancellation: checkCancellation) try checkCancellation() - Self.post(event) - press?.release.location = screen - try checkCancellation() - } - - func up(connection: UUID, app: String, window: UInt32, button: CGMouseButton) throws { - guard let press, press.connection == connection, press.app == app, press.route.windowID == window, press.button == button else { - throw RequestParameters.invalid("Release the system button through the same window and connection that pressed it") - } - release(connection: connection) - } - - /// Releasing at the current pointer also works after focus changes or the original window closes. - func release(connection: UUID) { - guard let press, press.connection == connection else { return } - if let point = CGEvent(source: nil)?.location { press.release.location = point } - Self.post(press.release) - self.press = nil - } - - private static var busy: NativeFailure { - NativeFailure(code: "INPUT_BUSY", message: "A system mouse button is held; release it before controlling another window or button") } } diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/WindowPointerInput.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/WindowPointerInput.swift index bca1bc6cc1..43dcc1d55e 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/WindowPointerInput.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/WindowPointerInput.swift @@ -15,11 +15,13 @@ final class WindowPointerInput { let release: CGEvent } + private let held: HeldInputs private let poster: PIDEventPoster private let checkCancellation: @Sendable () throws -> Void - init(poster: PIDEventPoster, checkCancellation: @escaping @Sendable () throws -> Void = {}) { + init(poster: PIDEventPoster, held: HeldInputs = HeldInputs(), checkCancellation: @escaping @Sendable () throws -> Void = {}) { self.poster = poster + self.held = held self.checkCancellation = checkCancellation } @@ -48,23 +50,22 @@ final class WindowPointerInput { } } - /// Send one window-directed transition at the current cursor. A release can be outside the window. - func toggleMouse(in route: WindowRoute, button: String, isDown: Bool, - isolation: isolated (any Actor)? = #isolation) async throws { + /// Save the exact window release before posting the down event. + func mouseDown(owner: HeldInputs.Owner, in route: WindowRoute, button: String, + isolation: isolated (any Actor)? = #isolation) async throws { let selected = try Self.button(button) try Self.validateWindow(route) guard let screen = CGEvent(source: nil)?.location else { throw NativeFailure(code: "NATIVE_ERROR", message: "Could not read the current pointer position") } + try await Self.checkSystemHit(route, at: screen) let point = WindowPoint(x: screen.x - route.bounds.x, y: screen.y - route.bounds.y) - if isDown { - try await Self.checkSystemHit(route, at: screen) - } - let event = try mouseEvent(source: Self.source(), route: route, screen: screen, local: point, - type: isDown ? Self.down(selected) : Self.up(selected), - button: selected, clickState: 1, subtype: 3, group: nil) + let pair = try mousePair(source: Self.source(), route: route, screen: screen, local: point, + button: selected, clickState: 1, group: Self.clickGroup()) try checkCancellation() - poster.post(event, to: route.owner.pid) + let poster = self.poster + try held.pointerDown(owner: owner, route: route, button: selected, system: false, down: pair.down, up: pair.up, + post: { poster.post($0, to: route.owner.pid) }) } /// Post balanced mouse presses; holdMs replaces each press-to-release interval and remains cancellable. @@ -77,6 +78,7 @@ final class WindowPointerInput { } let source = try Self.source() let selectedButton = try Self.button(button) + try held.requirePointerAvailable(route: route, button: selectedButton, system: false) let flags = try KeyboardInput.modifierFlags(modifiers) let group = Self.clickGroup() let screen = Self.screenPoint(point, in: route) @@ -163,6 +165,7 @@ final class WindowPointerInput { } let source = try Self.source() let selected = try Self.button(button) + try held.requirePointerAvailable(route: route, button: selected, system: useSystemPointer) let flags = try KeyboardInput.modifierFlags(modifiers) let group = Self.clickGroup() func event(_ type: CGEventType, at point: WindowPoint) throws -> CGEvent { diff --git a/packages/experimental/cua-macos/native/generate-protocol.ts b/packages/experimental/cua-macos/native/generate-protocol.ts index 081a7d9e72..4fc739d685 100644 --- a/packages/experimental/cua-macos/native/generate-protocol.ts +++ b/packages/experimental/cua-macos/native/generate-protocol.ts @@ -15,18 +15,19 @@ export function renderNativeProtocol(): { json: string; swift: string } { maxElements: z.number().int().min(1).max(AX_TRAVERSAL_MAX.maxElements), maxDepth: z.number().int().min(1).max(AX_TRAVERSAL_MAX.maxDepth), } + const owner = { taskId: z.string().min(1), turn: z.number().int().positive() } const systemPointer = { useSystemPointer: z.boolean().optional() } const { fields, enums, json } = nativeProtocol({ getState: NativeResourceParameters.getState.extend(traversal), paste: NativeResourceParameters.paste.extend(traversal), - sendKeyEvent: z.object({ runId: z.string().min(1) }), - mouseMove: z.object(systemPointer), - toggleMouse: z.object(systemPointer), + sendKeyEvent: z.object(owner), + mouseMove: z.object({ ...systemPointer, taskId: owner.taskId.optional(), turn: owner.turn.optional() }), + toggleMouse: z.object({ ...systemPointer, ...owner }), drag: NativeResourceParameters.drag.extend(systemPointer), requestPermission: PermissionGuideParameters, openPermissionSettings: PermissionSettingsParameters, }, [z.object({ - method: z.literal('releaseHeldKeys'), params: z.object({ runId: z.string().min(1) }).strict(), - }).strict(), z.object({ method: z.literal('releaseSystemButton'), params: z.object({}).strict() }).strict()]) + method: z.literal('releaseHeldInputs'), params: z.object(owner).strict(), + }).strict()]) const quoted = (values: Iterable) => [...values].sort().map(value => JSON.stringify(value)).join(', ') const swift = [ '// Generated by native/generate-protocol.ts from @deepseek-ai/dsh-cua/native-schema. Do not edit.', diff --git a/packages/experimental/cua-macos/native/protocol.schema.json b/packages/experimental/cua-macos/native/protocol.schema.json index 10e5695f8e..f79948b7cb 100644 --- a/packages/experimental/cua-macos/native/protocol.schema.json +++ b/packages/experimental/cua-macos/native/protocol.schema.json @@ -489,13 +489,24 @@ }, "useSystemPointer": { "type": "boolean" + }, + "taskId": { + "type": "string", + "minLength": 1 + }, + "turn": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 } }, "required": [ "appHandle", "windowId", "mouseButton", - "direction" + "direction", + "taskId", + "turn" ], "additionalProperties": false } @@ -541,6 +552,15 @@ }, "useSystemPointer": { "type": "boolean" + }, + "taskId": { + "type": "string", + "minLength": 1 + }, + "turn": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 } }, "required": [ @@ -575,6 +595,15 @@ }, "useSystemPointer": { "type": "boolean" + }, + "taskId": { + "type": "string", + "minLength": 1 + }, + "turn": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 } }, "required": [ @@ -1097,16 +1126,22 @@ "up" ] }, - "runId": { + "taskId": { "type": "string", "minLength": 1 + }, + "turn": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 } }, "required": [ "appHandle", "key", "direction", - "runId" + "taskId", + "turn" ], "additionalProperties": false } @@ -1515,18 +1550,24 @@ }, "method": { "type": "string", - "const": "releaseHeldKeys" + "const": "releaseHeldInputs" }, "params": { "type": "object", "properties": { - "runId": { + "taskId": { "type": "string", "minLength": 1 + }, + "turn": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 } }, "required": [ - "runId" + "taskId", + "turn" ], "additionalProperties": false } @@ -1537,29 +1578,6 @@ "params" ], "additionalProperties": false - }, - { - "type": "object", - "properties": { - "id": { - "type": "string" - }, - "method": { - "type": "string", - "const": "releaseSystemButton" - }, - "params": { - "type": "object", - "properties": {}, - "additionalProperties": false - } - }, - "required": [ - "id", - "method", - "params" - ], - "additionalProperties": false } ] } diff --git a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py index 8ef081b5e9..563f3a3a11 100644 --- a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py +++ b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py @@ -122,7 +122,7 @@ def check_toggle_mouse(helper, owner, state_file, executable): events = wait_for_state(state_file, lambda s: len(s["events"]) >= count + 3)["events"][count:] assert [e["type"] for e in events] == [down, moved, up], events assert len({e["eventNumber"] for e in events}) == 1 and not events[-1]["pressedButtons"] & (1 << index), events - for ending in ("releaseSystemButton", "disconnect"): + for ending in ("releaseHeldInputs", "disconnect"): connection = Connection(socket, key) try: app = connection.call("getApp", {"selector": str(state["pid"])}) @@ -268,7 +268,7 @@ def check_keyboard(call, owner, state_file, state): count = len(state["events"]) def key(name, direction): - call("sendKeyEvent", {**owner, "runId": "held-input", "key": name, "direction": direction}) + call("sendKeyEvent", {**owner, "key": name, "direction": direction}) key("w", "down") key("d", "down") @@ -280,7 +280,7 @@ def check_keyboard(call, owner, state_file, state): held = state["events"][count:] assert [(event["type"], event["keyCode"]) for event in held] == [(10, 13), (10, 2), (11, 2)], held assert held[2]["timestamp"] - held[1]["timestamp"] >= 2, held - call("releaseHeldKeys", {"runId": "held-input"}) + call("releaseHeldInputs", {}) state = wait_for_state(state_file, lambda value: len(value["events"]) >= count + 4) assert [(e["type"], e["keyCode"]) for e in state["events"][count:]] == [(10, 13), (10, 2), (11, 2), (11, 13)] @@ -290,7 +290,7 @@ def check_keyboard(call, owner, state_file, state): key("w", "down") if explicit_up: key("w", "up") - call("releaseHeldKeys", {"runId": "held-input"}) + call("releaseHeldInputs", {}) state = wait_for_state(state_file, lambda value: any( e["type"] == 11 and e.get("keyCode") == 13 for e in value["events"][count:])) view_events = [(e["type"], e["keyCode"], e["repeat"]) for e in state["events"][count:]] diff --git a/packages/experimental/cua-macos/native/tests/native_test_support.py b/packages/experimental/cua-macos/native/tests/native_test_support.py index 0e2f35846d..22bf87aeb6 100644 --- a/packages/experimental/cua-macos/native/tests/native_test_support.py +++ b/packages/experimental/cua-macos/native/tests/native_test_support.py @@ -106,9 +106,14 @@ class NativeHelper: self.process = subprocess.Popen([str(binary)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, start_new_session=True) self.sequence = 0 + self.input_turn = 1 self.transcript = transcript def call(self, method, params, error_code=None): + if method in ("sendKeyEvent", "toggleMouse", "releaseHeldInputs") or (method == "mouseMove" and params.get("useSystemPointer")): + params = {**params, "taskId": "native-fixture", "turn": self.input_turn} + if method == "releaseHeldInputs": + self.input_turn += 1 self.sequence += 1 request = {"id": str(self.sequence), "method": method, "params": params} self.process.stdin.write(json.dumps(request) + "\n") diff --git a/packages/experimental/cua-macos/native/tests/shared_helper_e2e.py b/packages/experimental/cua-macos/native/tests/shared_helper_e2e.py index 72a7ac71ff..ab0e0f4e99 100644 --- a/packages/experimental/cua-macos/native/tests/shared_helper_e2e.py +++ b/packages/experimental/cua-macos/native/tests/shared_helper_e2e.py @@ -34,6 +34,7 @@ class Connection: self.socket.connect(str(path)) self.reader = self.socket.makefile("rb") self.sequence = 0 + self.input_turn = 1 self.diagnostics = [] self.cleanup_timeout = overrides.get("graceMs", CONFIG["graceMs"]) / 1000 self.send({"type": "hello", "protocol": 1, "runtimeKey": key, "config": {**CONFIG, **overrides}}) @@ -55,6 +56,10 @@ class Connection: return value def call(self, method, params, error=None): + if method in ("sendKeyEvent", "toggleMouse", "releaseHeldInputs") or (method == "mouseMove" and params.get("useSystemPointer")): + params = {**params, "taskId": "native-fixture", "turn": self.input_turn} + if method == "releaseHeldInputs": + self.input_turn += 1 self.sequence += 1 identifier = str(self.sequence) self.send({"id": identifier, "method": method, "params": params}) diff --git a/packages/experimental/cua-macos/native/tests/swift/HeldInputTests.swift b/packages/experimental/cua-macos/native/tests/swift/HeldInputTests.swift new file mode 100644 index 0000000000..d237d1efb4 --- /dev/null +++ b/packages/experimental/cua-macos/native/tests/swift/HeldInputTests.swift @@ -0,0 +1,105 @@ +// Observe native CGEvents at dispatch without injecting input into the developer's desktop. +import CoreGraphics +import Darwin +import Foundation +import Testing +@testable import CuaNative + +private let scope = HeldInputs.Scope(task: "task", turn: 1) + +private func pointer(_ type: CGEventType) throws -> CGEvent { + let event = try #require(CGEvent(mouseEventSource: nil, mouseType: type, mouseCursorPosition: .zero, mouseButton: .left)) + event.flags = .maskAlternate + return event +} + +@Test(arguments: [false, true]) +func mixedInputsReleaseInDispatchOrder(_ system: Bool) throws { + let held = HeldInputs() + let connection = UUID() + let target = try NativePlatform.identity(getpid()) + let owner = HeldInputs.Owner(connection: connection, scope: scope, app: "editor") + let route = WindowRoute(owner: target, windowID: 7, bounds: .init(x: 0, y: 0, width: 100, height: 100)) + var events: [String] = [] + let input = KeyboardInput(post: { event, pid in + #expect(pid == target.pid) + events.append("key:\(event.getIntegerValueField(.keyboardEventKeycode)):\(event.type.rawValue)") + }, textEventInterval: 0, held: held, connection: connection) + try input.keyDown("shift", app: "editor", scope: scope, recipient: { target }) + try held.pointerDown(owner: owner, route: route, button: .left, system: system, + down: pointer(.leftMouseDown), up: pointer(.leftMouseUp), post: { events.append("mouse:\($0.type.rawValue)") }) + try input.keyDown("w", app: "editor", scope: scope, recipient: { target }) + try held.release(connection: connection, scope: scope) + try held.release(connection: connection, scope: scope) + #expect(events == ["key:56:12", "mouse:1", "key:13:10", "key:13:11", "mouse:2", "key:56:12"]) +} + +@Test func explicitReleaseRepeatAndRepressKeepOnlyTheLatestPress() throws { + let held = HeldInputs() + let connection = UUID() + let target = try NativePlatform.identity(getpid()) + var events: [CGEvent] = [] + let input = KeyboardInput(post: { event, _ in events.append(event) }, textEventInterval: 0, held: held, connection: connection) + func changedFocus() throws -> ProcessIdentity { throw RequestParameters.invalid("Unexpected focus lookup") } + try input.keyDown("w", app: "editor", scope: scope, recipient: { target }) + try input.keyDown("w", app: "editor", scope: scope, recipient: changedFocus) + #expect(try input.keyUp("w", app: "editor", scope: scope, recipientIfUnheld: changedFocus)) + try input.keyDown("d", app: "editor", scope: scope, recipient: { target }) + try input.keyDown("w", app: "editor", scope: scope, recipient: { target }) + try held.release(connection: connection, scope: scope) + #expect(events.map { $0.getIntegerValueField(.keyboardEventKeycode) } == [13, 13, 13, 2, 13, 13, 2]) + #expect(events.map(\.type) == [.keyDown, .keyDown, .keyUp, .keyDown, .keyDown, .keyUp, .keyUp]) + #expect(events.map { $0.getIntegerValueField(.keyboardEventAutorepeat) } == [0, 1, 0, 0, 0, 0, 0]) +} + +@Test func connectionsAndTurnsCannotReleaseEachOthersInput() throws { + let held = HeldInputs() + let a = UUID(), b = UUID() + let target = try NativePlatform.identity(getpid()) + var events: [CGEventType] = [] + let input = KeyboardInput(post: { event, _ in events.append(event.type) }, textEventInterval: 0, held: held, connection: a) + let peer = KeyboardInput(post: { _, _ in Issue.record("Foreign connection posted input") }, textEventInterval: 0, held: held, connection: b) + try input.keyDown("w", app: "editor", scope: scope, recipient: { target }) + #expect(throws: NativeFailure.self) { try peer.keyDown("w", app: "editor", scope: scope, recipient: { target }) } + #expect(throws: NativeFailure.self) { try peer.keyUp("w", app: "editor", scope: scope, recipientIfUnheld: { target }) } + try held.release(connection: b) + #expect(events == [.keyDown]) + try held.release(connection: a, scope: scope) + #expect(throws: NativeFailure.self) { try input.keyDown("w", app: "editor", scope: scope, recipient: { target }) } + let next = HeldInputs.Scope(task: scope.task, turn: 2) + try input.keyDown("w", app: "editor", scope: next, recipient: { target }) + try held.release(connection: a, scope: scope) + #expect(events == [.keyDown, .keyUp, .keyDown]) + try held.release(connection: a) + #expect(events == [.keyDown, .keyUp, .keyDown, .keyUp]) +} + +@Test(arguments: [false, true]) +func pointerReleaseUsesSavedRouteAfterWindowAndProcessChanges(_ system: Bool) throws { + let held = HeldInputs() + let target = try NativePlatform.identity(getpid()) + // The current PID with a different start identity models a reused process identifier. + let stale = ProcessIdentity(pid: target.pid, startedSeconds: target.startedSeconds + 1, startedMicroseconds: target.startedMicroseconds) + let owner = HeldInputs.Owner(connection: UUID(), scope: scope, app: "old-window") + let route = WindowRoute(owner: stale, windowID: 987654, bounds: .init(x: 0, y: 0, width: 100, height: 100)) + var events: [CGEventType] = [] + try held.pointerDown(owner: owner, route: route, button: .left, system: system, + down: pointer(.leftMouseDown), up: pointer(.leftMouseUp), post: { events.append($0.type) }) + #expect(try held.pointerUp(owner: owner, window: route.windowID, button: .left) == system) + try held.release(connection: owner.connection) + #expect(events == (system ? [.leftMouseDown, .leftMouseUp] : [.leftMouseDown])) +} + +@Test func balancedGestureCannotReleaseAWindowHold() throws { + let held = HeldInputs() + let target = try NativePlatform.identity(getpid()) + let route = WindowRoute(owner: target, windowID: 7, bounds: .init(x: 0, y: 0, width: 100, height: 100)) + let owner = HeldInputs.Owner(connection: UUID(), scope: scope, app: "editor") + try held.pointerDown(owner: owner, route: route, button: .left, system: false, + down: pointer(.leftMouseDown), up: pointer(.leftMouseUp), post: { _ in }) + #expect(throws: NativeFailure.self) { try held.requirePointerAvailable(route: route, button: .left, system: false) } + #expect(throws: NativeFailure.self) { try held.requirePointerAvailable(route: route, button: .right, system: true) } + try held.requirePointerAvailable(route: route, button: .right, system: false) + try held.release(connection: owner.connection) + try held.requirePointerAvailable(route: route, button: .left, system: false) +} diff --git a/packages/experimental/cua-macos/native/tests/swift/KeyboardChordTests.swift b/packages/experimental/cua-macos/native/tests/swift/KeyboardChordTests.swift index a971328ce3..22e904d386 100644 --- a/packages/experimental/cua-macos/native/tests/swift/KeyboardChordTests.swift +++ b/packages/experimental/cua-macos/native/tests/swift/KeyboardChordTests.swift @@ -63,75 +63,3 @@ func plusAlonePressesShiftEquals(_ alias: String) throws { #expect(events.map(\.type) == [.flagsChanged, .flagsChanged]) #expect(events.map { $0.flags.contains(.maskShift) } == [true, false]) } - -@Test func directionalReleaseUsesOriginalRecipientAndPreservesOtherRuns() throws { - let target = try NativePlatform.identity(getpid()) - let held = HeldKeys() - var events: [CGEvent] = [] - let input = KeyboardInput(post: { event, pid in - #expect(pid == target.pid) - events.append(event) - }, textEventInterval: 0, held: held) - try input.keyDown("shift", app: "editor", run: "one", recipient: { target }) - #expect(throws: NativeFailure.self) { try input.keyDown("shift", app: "editor", run: "one", recipient: { target }) } - try input.keyDown("w", app: "editor", run: "two", recipient: { target }) - #expect(throws: NativeFailure.self) { try input.keyDown("W", app: "editor", run: "one", recipient: { target }) } - #expect(throws: NativeFailure.self) { try input.keyUp("w", app: "other", run: "two", recipientIfUnheld: { target }) } - #expect(throws: NativeFailure.self) { try input.pressKey("w", modifiers: [], to: target.pid) } - try input.pressKey("d", modifiers: ["shift"], to: target.pid) - try input.releaseHeldKeys(run: "one") - #expect(try input.keyUp("w", app: "editor", run: "two", recipientIfUnheld: { target })) - try input.releaseHeldKeys(run: "two") - #expect(events.map { $0.getIntegerValueField(.keyboardEventKeycode) } == [56, 13, 2, 2, 56, 13]) - #expect(events.map { $0.flags.contains(.maskShift) } == [true, true, true, true, false, false]) -} - -@Test(arguments: [true, false]) -func repeatedDownUsesOriginalRecipientAndOneRelease(_ explicitUp: Bool) throws { - let target = try NativePlatform.identity(getpid()) - var events: [CGEvent] = [] - let input = KeyboardInput(post: { event, pid in - #expect(pid == target.pid) - events.append(event) - }, textEventInterval: 0) - func changedFocus() throws -> ProcessIdentity { - throw RequestParameters.invalid("The repeat or release looked up a new recipient") - } - try input.keyDown("w", app: "editor", run: "one", recipient: { target }) - try input.keyDown("W", app: "editor", run: "one", recipient: changedFocus) - if explicitUp { #expect(try input.keyUp("w", app: "editor", run: "one", recipientIfUnheld: changedFocus)) } - try input.releaseHeldKeys(run: "one") - #expect(events.map(\.type) == [.keyDown, .keyDown, .keyUp]) - #expect(events.map { $0.getIntegerValueField(.keyboardEventAutorepeat) } == [0, 1, 0]) -} - -@Test func foreignSessionCannotRepeatOrReleaseTheOwnersKey() throws { - let target = try NativePlatform.identity(getpid()) - let held = HeldKeys() - var events: [CGEvent] = [] - let a = KeyboardInput(post: { event, _ in events.append(event) }, textEventInterval: 0, held: held) - let b = KeyboardInput(post: { _, _ in Issue.record("Non-owner dispatched an event") }, textEventInterval: 0, held: held) - try a.keyDown("w", app: "a", run: "same-run-id", recipient: { target }) - for direction in ["down", "up"] { - do { - if direction == "down" { try b.keyDown("W", app: "b", run: "same-run-id", recipient: { target }) } - else { _ = try b.keyUp("W", app: "b", run: "same-run-id", recipientIfUnheld: { target }) } - Issue.record("Non-owner was allowed to send an event") - } catch let failure as NativeFailure { - #expect(failure.code == "INVALID_ARGUMENT") - #expect(failure.message.contains("Key 'W' is held for this target by another session")) - #expect(failure.message.contains("Wait for the holder to release it")) - } - } - try b.releaseHeldKeys() - try a.keyDown("W", app: "a", run: "same-run-id", recipient: { target }) - try a.releaseHeldKeys() - #expect(events.map(\.type) == [.keyDown, .keyDown, .keyUp]) - do { - _ = try b.keyUp("W", app: "b", run: "same-run-id", recipientIfUnheld: { target }) - Issue.record("Unheld key was released") - } catch let failure as NativeFailure { - #expect(failure.code == "INVALID_ARGUMENT") - #expect(failure.message.contains("Key 'W' is not held for this target")) - } -} diff --git a/packages/experimental/cua-macos/native/tests/test_ax_projection.py b/packages/experimental/cua-macos/native/tests/test_ax_projection.py index e795c9916d..ad66437d6e 100644 --- a/packages/experimental/cua-macos/native/tests/test_ax_projection.py +++ b/packages/experimental/cua-macos/native/tests/test_ax_projection.py @@ -49,7 +49,7 @@ def check_input(executable, helper_path, root): ("click", {**scoped, "x": 20, "y": 40}), ("typeText", {**owner, "text": "a"}), ("pressKey", {**owner, "key": "a"}), - ("sendKeyEvent", {**owner, "key": "a", "direction": "down", "runId": "fixture"})]: + ("sendKeyEvent", {**owner, "key": "a", "direction": "down", "taskId": "fixture", "turn": 1})]: 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 diff --git a/packages/experimental/cua-macos/src/guidance.ts b/packages/experimental/cua-macos/src/guidance.ts index 7ef1486163..a3b1cda5a1 100644 --- a/packages/experimental/cua-macos/src/guidance.ts +++ b/packages/experimental/cua-macos/src/guidance.ts @@ -10,10 +10,10 @@ function operationGuidance(treeAdvice: string): string { const methodDetails = new Map([ ['cua.listApps', 'Each row represents one running process. To select one of several instances with the same name or bundle ID, pass String(row.pid) to cua.getApp.'], ['cua.findApps', 'Running installation matches include their process ID. Stopped matches have no pid.'], - ['sendKeyEvent', "Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients."], + ['sendKeyEvent', "Send 'down' to hold a key across run_code and cua_run_code calls in the same turn, for example W down, D down, D up, W up. Send 'up' to release it immediately at its original recipient. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. A program returning or throwing keeps its holds while the turn continues. When the turn completes, fails, or is stopped, macOS releases remaining keys and mouse buttons together in reverse press order. pressKey and typeText still release their own presses within the operation."], ['getAccessibilityTree', `macOS accepts maxElements up to 100000 and maxDepth up to 512. If the tree is truncated, select a narrower window or raise the reported limit on the next read. ${treeAdvice} Use element ids from the file only while that observation is current.`], ['mouseMove', 'With useSystemPointer omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again.'], - ['toggleMouse', 'Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemPointer: true on both down and up. Physical moves can then drag, including your own mouse movements. The turn ending or the connection closing releases a remaining system hold.'], + ['toggleMouse', 'Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemPointer: true on down. Up uses the input route and window saved by down. Physical moves can then drag, including your own mouse movements. Both routes hold across programs in the same turn and release with held keys when the turn ends. click and drag release their own buttons within the operation.'], ['drag', 'Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control. An explicit system drag shares the session decision with mouseMove and holds the chosen button along the path in the unobscured foreground window.'], ['click', 'click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying.'], ]) diff --git a/packages/experimental/cua-macos/src/held-keys.ts b/packages/experimental/cua-macos/src/held-keys.ts deleted file mode 100644 index ee57cffb5a..0000000000 --- a/packages/experimental/cua-macos/src/held-keys.ts +++ /dev/null @@ -1,60 +0,0 @@ -/** Directional input belongs to the enclosing program, including while its worker calls other tools. */ -import { randomUUID } from 'node:crypto' -import type { Context } from '@deepseek-ai/cordis' -import type { CuaBackend } from '@deepseek-ai/dsh-cua' -import { NativeError, type NativeClient } from '@deepseek-ai/dsh-cua/native-client' -import { RUN_CODE_NAME, type ToolExecutionToken } from '@deepseek-ai/dsh-tools' - -interface HeldKeyRun { - id: string - client?: NativeClient - removeCleanup?: () => void - released: boolean - release(canRequest?: boolean): Promise -} - -/** - * Keep native key ownership until program settlement or its Agent's native connection closes. - * @param ctx - Provider scope owning the tool execution listener. - * @returns Directional input handler; each native connection owns cleanup of the runs that use it. - */ -export function installHeldKeys(ctx: Context): NonNullable { - const runs = new Map() - ctx.on('tools/execute', async (execution, next) => { - if (execution.name !== RUN_CODE_NAME && execution.name !== 'cua_run_code') return next() - let cleanup: Promise | undefined - const run: HeldKeyRun = { - id: randomUUID(), released: false, - release(canRequest = true) { - run.released = true - return cleanup ??= Promise.resolve().then(async () => { - try { if (canRequest) await run.client?.requestCleanup('releaseHeldKeys', { runId: run.id }) } - finally { run.removeCleanup?.(); runs.delete(execution.token) } - }) - }, - } - runs.set(execution.token, run) - // Pause may arrive while an unrelated subtool is still settling. - const onAbort = () => { void run.release().catch(() => undefined) } - const signal = execution.signal - signal.addEventListener('abort', onAbort, { once: true }) - try { - return await next() - } finally { - signal.removeEventListener('abort', onAbort) - await run.release() - } - }) - return (client, params, execution) => { - const run = execution.parent && runs.get(execution.parent) - if (!run || run.released) throw new NativeError('INVALID_ARGUMENT', 'Use sendKeyEvent inside an active run_code or cua_run_code execution') - if (run.client !== undefined && run.client !== client) { - throw new NativeError('INVALID_ARGUMENT', 'The native connection changed; start a new program before holding keys') - } - if (run.client === undefined) { - run.removeCleanup = client.registerCleanup(canRequest => run.release(canRequest)) - run.client = client - } - return client.request('sendKeyEvent', { ...params, runId: run.id }, execution.signal, execution.callId) - } -} diff --git a/packages/experimental/cua-macos/src/index.ts b/packages/experimental/cua-macos/src/index.ts index 87baa83eea..3a80984f98 100644 --- a/packages/experimental/cua-macos/src/index.ts +++ b/packages/experimental/cua-macos/src/index.ts @@ -8,7 +8,6 @@ import { CuaConfigFields } from '@deepseek-ai/dsh-cua/config' import { createPermissionParameters } from './permission-guide.ts' import { nativeHostArchitecture, prepareNativeExecutable, type SourceSigning } from './native-build.ts' import { createSharedNativeChannel } from './shared-native.ts' -import { installHeldKeys } from './held-keys.ts' import { AX_TRAVERSAL_MAX } from './ax-limits.ts' import { GUIDANCE, PROGRAM_GUIDANCE } from './guidance.ts' export { GUIDANCE } from './guidance.ts' @@ -64,7 +63,7 @@ export const Config = Schema.object({ * @returns Completion after native preparation and tool registration. */ export async function apply(ctx: Context, config: Config): Promise { - const backend = { createChannel: createSharedNativeChannel, sendKeyEvent: installHeldKeys(ctx), + const backend = { createChannel: createSharedNativeChannel, turnInputLifecycle: true, getGuidance: (kind: 'raw' | 'standalone') => kind === 'raw' ? GUIDANCE : PROGRAM_GUIDANCE, capabilities: CAPABILITIES, acceptsPidSelector: true, permissionParameters: createPermissionParameters(config.permissionPollIntervalMs) } if (config.helperPath !== undefined) { diff --git a/packages/experimental/cua-macos/tests/guidance.spec.ts b/packages/experimental/cua-macos/tests/guidance.spec.ts index 6e774fae0c..a32bb159ba 100644 --- a/packages/experimental/cua-macos/tests/guidance.spec.ts +++ b/packages/experimental/cua-macos/tests/guidance.spec.ts @@ -41,7 +41,7 @@ it.each([GUIDANCE, PROGRAM_GUIDANCE])('explains when macOS mouse input needs a s expect(instructions).toContain('The question interrupts the user.') expect(instructions).toContain('Omitting the option or passing false uses the default hover route without prompting.') expect(instructions).toContain("direction: 'down' | 'up', options?: { useSystemPointer?: boolean }") - expect(instructions).toContain('pass useSystemPointer: true on both down and up') + expect(instructions).toContain('pass useSystemPointer: true on down') const drag = catalog.split('\n').find(line => line.startsWith('- drag(')) expect(drag).toContain('useSystemPointer?: boolean') expect(drag).toContain('Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control.') @@ -54,7 +54,7 @@ it('states the macOS accessibility, keyboard, and mouse levels', () => { expect(PLATFORM_GUIDANCE).toContain('Simulated mouse input is available at window level') const pressKey = GUIDANCE.split('\n').find(line => line.startsWith('- pressKey(')) expect(GUIDANCE).toContain("sendKeyEvent(key: string, direction: 'down' | 'up')") - expect(GUIDANCE).toContain('returns, throws, or the user pauses') + expect(GUIDANCE).toContain('When the turn completes, fails, or is stopped') const sharedKeyEvent = COMMON_GUIDANCE.split('\n').find(line => line.startsWith('- sendKeyEvent(')) expect(sharedKeyEvent).toBeDefined() expect(GUIDANCE.split('\n').find(line => line.startsWith('- sendKeyEvent('))).toContain(sharedKeyEvent) @@ -75,7 +75,7 @@ it('documents explicit mouse-button events immediately after mouseMove', () => { const lines = COMMON_GUIDANCE.split('\n') const index = lines.findIndex(line => line.startsWith('- toggleMouse(')) expect(lines[index - 1]).toMatch(/^- mouseMove\(/) - expect(lines[index]).toBe("- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically.") + expect(lines[index]).toBe("- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; platform guidance defines their cleanup scope.") expect(index).toBeGreaterThan(lines.indexOf('## Simulated mouse')) expect(index).toBeLessThan(lines.indexOf('## Simulated keyboard')) }) @@ -83,7 +83,7 @@ it('documents explicit mouse-button events immediately after mouseMove', () => { it.each([GUIDANCE, PROGRAM_GUIDANCE])('documents the default window release and the optional system hold', (catalog) => { const entry = catalog.split('\n').find(line => line.startsWith('- toggleMouse(')) expect(entry).toContain('By default the window receives the events, even a release outside it, and the system button stays up.') - expect(entry).toContain('pass useSystemPointer: true on both down and up') + expect(entry).toContain('pass useSystemPointer: true on down') }) it('enumerates every public method once in its catalog entry', () => { diff --git a/packages/experimental/cua-macos/tests/held-keys.spec.ts b/packages/experimental/cua-macos/tests/held-keys.spec.ts deleted file mode 100644 index 24e07d51c8..0000000000 --- a/packages/experimental/cua-macos/tests/held-keys.spec.ts +++ /dev/null @@ -1,156 +0,0 @@ -/** Held-key cleanup through real native byte streams and the tool execution wrapper. */ -import { PassThrough, Writable } from 'node:stream' -import { finished } from 'node:stream/promises' -import { Context } from '@deepseek-ai/cordis' -import { NativeClient } from '@deepseek-ai/dsh-cua/native-client' -import type { ToolCallId } from '@deepseek-ai/dsh-llm' -import SystemPrompt from '@deepseek-ai/dsh-system-prompt' -import Tools, { defineTool } from '@deepseek-ai/dsh-tools' -import { executeToolFixture } from '@deepseek-ai/dsh-tool-testkit' -import { expect, it, onTestFinished, vi } from 'vitest' -import { z } from 'zod' -import { installHeldKeys } from '../src/held-keys.ts' -import { brandString } from '@deepseek-ai/dsh-brand' - -const Request = z.object({ id: z.string(), method: z.string(), params: z.record(z.string(), z.json()) }) - -function nativeConnection(holdRelease = false) { - const requests: z.infer[] = [] - const events: string[] = [] - const held = new Set() - const releasing: PromiseWithResolvers = Promise.withResolvers() - const stdout = new PassThrough() - let releaseId: string | undefined - const acknowledge = (): void => { - if (releaseId === undefined) return - held.clear() - events.push('released') - stdout.write(JSON.stringify({ id: releaseId, result: { dispatched: true } }) + '\n') - releaseId = undefined - } - const stdin = new Writable({ write(chunk, _encoding, callback) { - const request = Request.parse(JSON.parse(String(chunk))) - requests.push(request) - if (request.method === 'releaseHeldKeys') { - events.push('release requested') - releaseId = request.id - releasing.resolve() - if (!holdRelease) acknowledge() - } else { - held.add(z.string().parse(request.params.key)) - events.push('key held') - stdout.write(JSON.stringify({ id: request.id, result: { dispatched: true } }) + '\n') - } - callback() - } }) - const done = Promise.all([finished(stdin, { cleanup: true }), finished(stdout, { cleanup: true })]).then(() => undefined) - const close = vi.fn(() => { - events.push('connection closed') - held.clear() - stdin.end() - stdout.end() - }) - const client = new NativeClient({ subprocess: { spawn() { throw new Error('The byte-stream fixture does not spawn a helper') } } }, { - helperPath: '/fixture/helper', cwd: '/fixture', timeoutMs: 60_000, connectTimeoutMs: 5000, - screenshotTimeoutMs: 5000, axTimeoutMs: 3000, maxRequestBytes: 4096, maxResponseBytes: 4096, - graceMs: 1000, textEventIntervalMs: 1, maxClickHoldMs: 5000, - }, () => ({ stdin, stdout, done, close, waitForClose: () => done })) - onTestFinished(async () => { client.invalidate(); await client.dispose().catch(() => undefined) }) - return { client, requests, events, held, releasing: releasing.promise, acknowledge, close } -} - -async function program(body: (send: (client: NativeClient) => Promise) => Promise) { - const ctx = new Context() - onTestFinished(() => ctx.fiber.dispose()) - await ctx.plugin(SystemPrompt) - await ctx.plugin(Tools) - const sendKeyEvent = installHeldKeys(ctx) - ctx.tools.register(defineTool({ name: 'cua_run_code', description: 'Exercise native key ownership.', parameters: {}, - output: { schema: { type: 'json' }, render: () => [] }, - async execute(_args, execution) { - await body(async (client) => { - await sendKeyEvent(client, { key: 'w', direction: 'down' }, { - ...execution, name: 'cua', callId: brandString('held-key'), parent: execution.token, - }) - }) - return null - }, - })) - return { run: () => executeToolFixture(ctx, { name: 'cua_run_code', callId: brandString('held-program'), arguments: {}, signal: new AbortController().signal }) } -} - -it('releases native keys before connection closure without waiting for unrelated program work', async () => { - const native = nativeConnection(true) - const entered: PromiseWithResolvers = Promise.withResolvers() - const finishProgram: PromiseWithResolvers = Promise.withResolvers() - const fixture = await program(async (send) => { - await send(native.client) - entered.resolve() - await finishProgram.promise - }) - let programEnded = false - const running = fixture.run().then((result) => { programEnded = true; return result }) - let closing: Promise | undefined - try { - await entered.promise - closing = native.client.dispose() - await native.releasing - expect(native.held).toEqual(new Set(['w'])) - expect(native.close).not.toHaveBeenCalled() - native.acknowledge() - await closing - expect(programEnded).toBe(false) - expect(native.events).toEqual(['key held', 'release requested', 'released', 'connection closed']) - expect(native.held.size).toBe(0) - finishProgram.resolve() - expect((await running).isError).toBe(false) - expect(native.requests.map(request => request.method)).toEqual(['sendKeyEvent', 'releaseHeldKeys']) - expect(native.close).toHaveBeenCalledTimes(1) - } finally { - finishProgram.resolve() - native.acknowledge() - await running - await closing - } -}) - -it('cleans up local held-key ownership after forced connection closure without sending another request', async () => { - const native = nativeConnection() - const entered: PromiseWithResolvers = Promise.withResolvers() - const finishProgram: PromiseWithResolvers = Promise.withResolvers() - const fixture = await program(async (send) => { - await send(native.client) - entered.resolve() - await finishProgram.promise - await expect(send(native.client)).rejects.toMatchObject({ code: 'INVALID_ARGUMENT' }) - }) - const running = fixture.run() - try { - await entered.promise - native.client.invalidate() - await native.client.dispose() - expect(native.held.size).toBe(0) - finishProgram.resolve() - expect((await running).isError).toBe(false) - expect(native.requests.map(request => request.method)).toEqual(['sendKeyEvent']) - expect(native.close).toHaveBeenCalledTimes(1) - } finally { finishProgram.resolve(); await running } -}) - -it('keeps a held-key run on its first connection and unregisters after normal release', async () => { - const first = nativeConnection() - const second = nativeConnection() - const register = vi.spyOn(second.client, 'registerCleanup') - onTestFinished(() => { register.mockRestore() }) - const fixture = await program(async (send) => { - await send(first.client) - await expect(send(second.client)).rejects.toMatchObject({ code: 'INVALID_ARGUMENT' }) - }) - expect((await fixture.run()).isError).toBe(false) - expect(register).not.toHaveBeenCalled() - expect(second.requests).toEqual([]) - expect(first.requests.map(request => request.method)).toEqual(['sendKeyEvent', 'releaseHeldKeys']) - await first.client.dispose() - expect(first.requests).toHaveLength(2) - expect(first.close).toHaveBeenCalledTimes(1) -}) diff --git a/packages/experimental/cua-macos/tests/protocol-generation.spec.ts b/packages/experimental/cua-macos/tests/protocol-generation.spec.ts index ab0cfd2ad5..4b2893ce2f 100644 --- a/packages/experimental/cua-macos/tests/protocol-generation.spec.ts +++ b/packages/experimental/cua-macos/tests/protocol-generation.spec.ts @@ -61,7 +61,7 @@ describe('native protocol generation', () => { { method: 'paste', params: { appHandle: 'app', text: 'text', pasteReadTimeoutMs: 1000 } }, { method: 'mouseMove', params: { appHandle: 'app', windowId: '1', x: 0, y: 0, allowSystemPointer: true } }, { method: 'findApps', params: { query: 'Editor', maxAppMatches: 1 } }, - { method: 'releaseHeldKeys', params: { runId: 'execution' } }, + { method: 'releaseHeldInputs', params: { taskId: 'task', turn: 1 } }, { method: 'launchApp', params: { appHandle: 'pending' } }, { method: 'applicationIcons', params: { paths: ['/Applications/Fixture.app'] } }, { method: 'permissionStatus', params: {} }, diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index ab57b77108..66304e8cd4 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -27,7 +27,7 @@ import NodeRuntime from '@deepseek-ai/dsh-ptc-runtime-node' import { createRunCodeTool } from '@deepseek-ai/dsh-tool-executor-ptc/run-code' import Sandbox from '@deepseek-ai/dsh-sandbox-local' import SandboxPolicy from '@deepseek-ai/dsh-sandbox-policy' -import { LlmAdapter, LlmError, type ToolCallId, type LlmResolvedModelInfo, type StreamChunk } from '@deepseek-ai/dsh-llm' +import { LlmAdapter, LlmError, type ToolCallId, type LlmResolvedModelInfo, type StreamChunk, createUserMessage } from '@deepseek-ai/dsh-llm' import type { SessionId } from '@deepseek-ai/dsh-session' import Subprocess from '@deepseek-ai/dsh-subprocess' import SubprocessLocal from '@deepseek-ai/dsh-subprocess-local' @@ -172,6 +172,25 @@ async function setup( return { ctx, provider, handle, execute } } +async function thinkingTurn(f: Awaited>) { + const entered: PromiseWithResolvers = Promise.withResolvers() + class WaitingModel extends LlmAdapter { + async * stream(options: import('@deepseek-ai/dsh-llm').GenerateOptions): AsyncIterable { + entered.resolve() + await new Promise((resolve) => { + if (options.signal?.aborted) resolve() + else options.signal?.addEventListener('abort', () => { resolve() }, { once: true }) + }) + yield { type: 'finish', reason: { kind: 'aborted' } } + } + } + f.ctx.llm.registerAdapter(['thinking'], new WaitingModel()) + Object.assign(f.handle.agent.options, { provider: 'thinking', model: 'fixture' }) + f.handle.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Wait for input' }], source: { kind: 'user' } })) + onTestFinished(async () => { f.handle.agent.cancel({ kind: 'user' }); await f.handle.agent.whenIdle() }) + await entered.promise +} + async function executeProgram( f: Awaited>, name: 'run_code' | 'cua_run_code', code: string, description: string, signal = new AbortController().signal, @@ -195,13 +214,13 @@ async function selectApplication(f: Awaited>) { expect((await f.execute('getApp', { selector: 'Fixture' })).isError).toBe(false) } -it('requires an enclosing run_code before sending a directional key', async () => { +it('requires an active turn before sending a directional key', async () => { const f = await setup() await selectApplication(f) native.request.mockClear() const result = await f.execute('sendKeyEvent', { appHandle: 'app-one', key: 'w', direction: 'down' }) expect(result.isError).toBe(true) - expect(JSON.stringify(result.content)).toContain('active run_code') + expect(JSON.stringify(result.content)).toContain('active agent turn') expect(native.request).not.toHaveBeenCalled() }) @@ -217,151 +236,6 @@ it.each(['run_code', 'cua_run_code'] as const)('finishes a shortcut-only %s with expect(native.cleanup).not.toHaveBeenCalled() }) -it.each((['run_code', 'cua_run_code'] as const).flatMap(name => - ['return', 'throw', 'pause', 'pause with cleanup error'].map(ending => ({ name, ending })), -))('cleans up only the held W when $name ends by $ending', async ({ name, ending }) => { - const f = await setup(undefined, true) - await selectApplication(f) - const held = new Set() - const events: string[] = [] - const controller = new AbortController() - const runIds = new Set() - native.request.mockImplementation(async (method, params) => { - expect(method).toBe('sendKeyEvent') - runIds.add(params.runId) - const { key, direction } = params - if (typeof key !== 'string' || (direction !== 'down' && direction !== 'up')) throw new Error('Invalid directional event') - if (direction === 'down') held.add(key) - else held.delete(key) - events.push(`${key}:${direction}`) - return { dispatched: true } - }) - native.cleanup.mockImplementation(async (method, params) => { - expect(method).toBe('releaseHeldKeys') - expect(runIds).toEqual(new Set([params.runId])) - if (ending === 'pause with cleanup error') throw new Error('release acknowledgement failed') - for (const key of held) events.push(`${key}:up`) - held.clear() - return { dispatched: true } - }) - f.ctx.tools.register({ - name: 'check_held_keys', description: 'Observe the keys held by the test receiver.', - parameters: { type: 'object', properties: {} }, - output: { schema: {}, render: () => [] }, - async execute() { - const keys = [...held] - if (ending.startsWith('pause') && keys.length === 1) { - controller.abort() - await setImmediate() - expect(held.size).toBe(ending === 'pause' ? 0 : 1) - } - return keys - }, - }) - const code = [ - "const key = (key, direction) => tools.cua({ method: 'sendKeyEvent', params: { appHandle: 'app-one', key, direction } });", - "await key('w', 'down'); await key('d', 'down');", - "if ((await tools.check_held_keys({})).join(',') !== 'w,d') throw Error('lost held keys');", - "await key('d', 'up');", - "if ((await tools.check_held_keys({})).join(',') !== 'w') throw Error('lost W');", - ending === 'throw' ? "throw Error('program failed');" : "return 'done';", - ].join('\n') - const result = await executeProgram(f, name, code, 'Exercise held keys', controller.signal) - expect(events, JSON.stringify(result.content)).toEqual(['w:down', 'd:down', 'd:up', ...ending === 'pause with cleanup error' ? [] : ['w:up']]) - expect(native.cleanup).toHaveBeenCalledTimes(1) - expect(result.isError).toBe(ending !== 'return') - if (ending === 'throw') expect(JSON.stringify(result.content)).toContain('program failed') -}) - -it.each(['running', 'settling'] as const)('awaits held-key cleanup before unloading native resources while the raw program is %s', async (phase) => { - const f = await setup(undefined, true) - await selectApplication(f) - const entered: PromiseWithResolvers = Promise.withResolvers() - const programRelease: PromiseWithResolvers = Promise.withResolvers() - const cleanupEntered: PromiseWithResolvers = Promise.withResolvers() - const cleanupRelease: PromiseWithResolvers = Promise.withResolvers() - const events: string[] = [] - native.request.mockClear().mockImplementation(async () => { events.push('key down'); return { dispatched: true } }) - native.cleanup.mockImplementation(async () => { - events.push('release entered') - cleanupEntered.resolve() - await cleanupRelease.promise - expect(native.dispose).not.toHaveBeenCalled() - events.push('release finished') - return { dispatched: true } - }) - native.dispose.mockImplementation(async () => { events.push('native closed') }) - f.ctx.tools.register({ name: 'hold_program', description: 'Wait for the test program release.', - parameters: { type: 'object', properties: {} }, output: { schema: {}, render: () => [] }, - async execute() { entered.resolve(); await programRelease.promise; return null }, - }) - const controller = new AbortController() - let settled = false - const running = executeProgram(f, 'run_code', - "await tools.cua({ method: 'sendKeyEvent', params: { appHandle: 'app-one', key: 'w', direction: 'down' } }); await tools.hold_program({}); return 'finished';", - 'Hold a key during provider unload', controller.signal).then((result) => { settled = true; return result }) - let closing: Promise | undefined - try { - await entered.promise - if (phase === 'settling') { - programRelease.resolve() - await cleanupEntered.promise - } - closing = f.provider.dispose() - expect(await Promise.race([cleanupEntered.promise.then(() => 'cleanup'), closing.then(() => 'closed')])).toBe('cleanup') - expect(native.dispose).not.toHaveBeenCalled() - expect(events).toEqual(['key down', 'release entered']) - cleanupRelease.resolve() - await closing - expect(events).toEqual(['key down', 'release entered', 'release finished', 'native closed']) - if (phase === 'running') expect(settled).toBe(false) - programRelease.resolve() - expect((await running).isError).toBe(false) - expect(native.cleanup).toHaveBeenCalledTimes(1) - expect(native.dispose).toHaveBeenCalledTimes(1) - } finally { - controller.abort() - programRelease.resolve() - cleanupRelease.resolve() - await running - await closing - } -}) - -it('closes the native connection after a held-key cleanup failure and reuses that failure at program settlement', async () => { - const f = await setup(undefined, true) - await selectApplication(f) - const entered: PromiseWithResolvers = Promise.withResolvers() - const programRelease: PromiseWithResolvers = Promise.withResolvers() - native.request.mockClear().mockResolvedValue({ dispatched: true }) - const failure = new Error('Held-key release was not acknowledged') - native.cleanup.mockRejectedValue(failure) - const reported: unknown[] = [] - const log = vi.spyOn(f.provider.ctx.logger, 'error').mockImplementation((error) => { reported.push(error) }) - onTestFinished(() => { log.mockRestore() }) - f.ctx.tools.register({ name: 'hold_program', description: 'Wait for the test program release.', - parameters: { type: 'object', properties: {} }, output: { schema: {}, render: () => [] }, - async execute() { entered.resolve(); await programRelease.promise; return null }, - }) - const controller = new AbortController() - const running = executeProgram(f, 'run_code', - "await tools.cua({ method: 'sendKeyEvent', params: { appHandle: 'app-one', key: 'w', direction: 'down' } }); await tools.hold_program({});", - 'Hold a key before cleanup fails', controller.signal) - try { - await entered.promise - await f.provider.dispose() - expect(native.dispose).toHaveBeenCalledTimes(1) - expect(native.cleanup).toHaveBeenCalledTimes(1) - const aggregate = reported.find(error => error instanceof AggregateError) - expect(aggregate?.errors).toContain(failure) - programRelease.resolve() - const result = await running - expect(result.isError).toBe(true) - expect(JSON.stringify(result.content)).toContain(failure.message) - expect(native.cleanup).toHaveBeenCalledTimes(1) - } finally { controller.abort(); programRelease.resolve(); await running } -}) - it('rejects a relative helper path before publishing computer-use operations', async () => { const ctx = new Context() onTestFinished(() => ctx.fiber.dispose()) @@ -1208,6 +1082,7 @@ const physicalHover = { ...hoverTarget, useSystemPointer: true } async function hoverFixture(requireApproval = true) { const f = await setup() + await thinkingTurn(f) if (!requireApproval) { await f.provider.dispose() await f.ctx.plugin(NativeProvider, { ...config, requireSystemPointerApproval: false }) @@ -1280,9 +1155,10 @@ it.each([true, false])('shares the mouse control decision for a system button wi if (allow) { expect(results.every(result => !result.isError)).toBe(true) expect(native.request.mock.calls.map(([method, params]) => [method, params.useSystemPointer])) - .toEqual([['toggleMouse', true], ['mouseMove', true], ['toggleMouse', true]]) - f.handle.agent.session.append('turn/end', { turn: 1, reason: { kind: 'aborted', reason: { kind: 'user' } } }) - expect(native.cleanup).toHaveBeenCalledWith('releaseSystemButton', {}) + .toEqual([['toggleMouse', true], ['mouseMove', true], ['toggleMouse', undefined]]) + f.handle.agent.cancel({ kind: 'user' }) + await f.handle.agent.whenIdle() + expect(native.cleanup).toHaveBeenCalledWith('releaseHeldInputs', { taskId: f.handle.agent.id, turn: 1 }) } else { for (const result of results) expect(JSON.stringify(result.content)).toContain('MOUSE_CONTROL_DENIED') expect(native.request).not.toHaveBeenCalled() @@ -1290,33 +1166,6 @@ it.each([true, false])('shares the mouse control decision for a system button wi expect(f.ask).toHaveBeenCalledOnce() }) -it('reports a failed turn-end button release once and forgets the hold', async () => { - const f = await hoverFixture() - const failure = new Error('The release was not acknowledged') - native.cleanup.mockRejectedValueOnce(failure) - const warn = vi.spyOn(f.provider.ctx.logger, 'warn').mockImplementation(() => {}) - onTestFinished(() => { warn.mockRestore() }) - expect((await f.execute('toggleMouse', { appHandle: 'app-one', windowId: '7', mouseButton: 'left', - direction: 'down', useSystemPointer: true })).isError).toBe(false) - const session = f.handle.agent.session - session.append('turn/end', { turn: 1, reason: { kind: 'aborted', reason: { kind: 'user' } } }) - await vi.waitFor(() => { - expect(warn).toHaveBeenCalledWith('Could not release system mouse input at turn end: %s', failure) - }) - session.append('turn/end', { turn: 2, reason: { kind: 'completed' } }) - expect(native.cleanup).toHaveBeenCalledExactlyOnceWith('releaseSystemButton', {}) -}) - -it('leaves button release to disconnect when application access was revoked before turn end', async () => { - const f = await hoverFixture() - expect((await f.execute('toggleMouse', { appHandle: 'app-one', windowId: '7', mouseButton: 'left', - direction: 'down', useSystemPointer: true })).isError).toBe(false) - await f.ctx.cuaAccess.revoke('a'.repeat(64) as Parameters[0]) - expect(native.dispose).toHaveBeenCalled() - f.handle.agent.session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) - expect(native.cleanup).not.toHaveBeenCalled() -}) - it.each([true, false])('asks before a system drag and shares the session decision with hover (allow=%s)', async (allow) => { const f = await hoverFixture() const target = { appHandle: 'app-one', windowId: '7', relative: true, fromX: 100, fromY: 200, toX: 300, toY: 400 } diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index 3a4ec748f2..29cd20a2c8 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -21,8 +21,8 @@ en: 3f638a4a76023fc5 zh: 515aeb5de6ae5b33 /deepseek-ai-dsh-cua/understand-the-implementation: - en: c9fc9c1fb5a72154 - zh: a234881ef8e03761 + en: a106735c075a5d21 + zh: aad70f757745e311 /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 a4a08df9e7..00101235a5 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -89,6 +89,8 @@ Permission responses identify their platform and report only the state that plat
Shared execution and platform ownership +A provider enables `CuaBackend.turnInputLifecycle` only after its helper accepts `taskId` and `turn` on `sendKeyEvent`, `toggleMouse`, and system `mouseMove`, and acknowledges `releaseHeldInputs({ taskId, turn })`. The shared owner blocks admission on cancellation or finalization, awaits native cancellation before independent bounded cleanup, and disables the task after an unconfirmed release. Providers must record actual dispatch order, targets and routes before posting, implement explicit up and mixed reverse-order cleanup, reject stale turns, and clean only their connection on disconnect. Windows leaves this option unset until these native behaviors are implemented; it receives neither new parameters nor cleanup commands. + The [permission store](src/permission-store.ts) uses `storageDomain` with the configured backend. The default JSON backend writes `$DSH_HOME/storages/cua_permissions_.json`, where the digest identifies the canonical profile directory. Each authorization check opens fresh state under the profile's file lock and closes its domain afterward; native dispatch uses a separate application lock. Revocation waits for operations already admitted by another process; after it completes, every process rejects old handles. Files on different machines or PID namespaces must not share this lock. Legacy `allowedApps` are imported on first store access and never reapplied after migration. The old configuration can be removed after checking the permission page. Grants, denials and the option to ask again are durable; the page still omits conversation-only grants. Standalone compositions without a profile retain only process-local decisions; a profile without domain storage refuses authorization operations. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index fb6e21f8ef..5670fef393 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -89,6 +89,8 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边
共享执行与平台职责 +提供方仅在 helper 已接受 `sendKeyEvent`、`toggleMouse` 和系统 `mouseMove` 的 `taskId`、`turn` 参数,并能确认 `releaseHeldInputs({ taskId, turn })` 后,才启用 `CuaBackend.turnInputLifecycle`。共通持有方在取消或收尾时禁止新输入,等待原生取消后用独立且有超时限制的请求清理;释放未经确认时禁用该任务的输入。提供方必须在派发前记录实际顺序、目标与输入方式,实现显式释放和键鼠混合反序清理,拒绝旧回合输入,并在断连时只清理本连接。Windows 在实现这些原生行为前保持此选项未设置,不接收新增参数或清理命令。 + [授权存储](src/permission-store.ts)复用 `storageDomain` 和配置的后端。默认 JSON 后端写入 `$DSH_HOME/storages/cua_permissions_.json`,摘要对应 profile 的真实目录。每次授权检查在 profile 文件锁内打开并读取最新状态,随后关闭存储域;原生操作使用单独的应用锁。撤销会等待其他进程已获准执行的操作结束;撤销完成后,各进程都拒绝旧句柄。不同电脑或 PID 命名空间不能共享这把锁。 旧 `allowedApps` 只在首次访问存储时导入,迁移后不再应用。确认权限页显示正确后,可以删除旧配置。授权、拒绝和允许再次询问均持久化,页面仍不显示仅对某个会话生效的许可。没有 profile 的独立组合只保留进程内决定;有 profile 但缺少域存储的组合会拒绝授权操作。 diff --git a/packages/experimental/cua/src/guidance.ts b/packages/experimental/cua/src/guidance.ts index 5f5fb160c5..37128c264c 100644 --- a/packages/experimental/cua/src/guidance.ts +++ b/packages/experimental/cua/src/guidance.ts @@ -43,7 +43,7 @@ Use an explicit window for screenshots. ## Simulated mouse Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - ${hoverSignature} -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; platform guidance defines their cleanup scope. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], 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. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. diff --git a/packages/experimental/cua/src/index.ts b/packages/experimental/cua/src/index.ts index 9226e32ad7..7b4e809319 100644 --- a/packages/experimental/cua/src/index.ts +++ b/packages/experimental/cua/src/index.ts @@ -14,6 +14,7 @@ import type { JsonValue } from '@deepseek-ai/dsh-util-values' import { z } from 'zod' import { NativeClient, NativeError, type NativeClientConfig, type NativeChannelFactory } from './native-client.ts' import { MouseControl } from './mouse-control.ts' +import { CuaInputTurns } from './turn-inputs.ts' import { withSystemPointerGuidance } from './guidance.ts' import { CuaPermissionStore } from './permission-store.ts' import { ApplicationAuthorizationResult, installCuaAccess } from './access.ts' @@ -186,9 +187,8 @@ export interface CuaBackend { capabilities: CuaStartupCapabilities /** Preserve discovery PIDs when getApp accepts a decimal PID as an exact process selector. */ acceptsPidSelector?: boolean - /** Dispatch a directional key through the provider's execution-scoped input owner, after application authorization. */ - sendKeyEvent?: (client: NativeClient, params: Record, - execution: Readonly) => Promise + /** Opt in to task/turn parameters and acknowledged releaseHeldInputs; omission preserves the provider's existing protocol. */ + turnInputLifecycle?: boolean /** * Build native permission parameters for the selected action and Client language. * @param method Native permission action. @@ -207,6 +207,7 @@ export interface CuaBackend { */ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend): void { const { helperPath } = backend + const inputTurns = backend.turnInputLifecycle ? new CuaInputTurns(ctx) : undefined const systemPointer = backend.capabilities.systemPointer === true const mouseControl = systemPointer ? new MouseControl(ctx, config.requireSystemPointerApproval) : undefined const requestSchema = systemPointer ? SystemPointerRequest : Request @@ -285,8 +286,13 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) // Earlier helpers accept an explicit false only for mouseMove. if (method !== 'mouseMove' && !useSystemPointer) delete params.useSystemPointer else if (useSystemPointer !== undefined) params.useSystemPointer = useSystemPointer - if (method === 'sendKeyEvent' && backend.sendKeyEvent) return backend.sendKeyEvent(client, params, execution) - if (method === 'toggleMouse' && useSystemPointer && params.direction === 'down') mouseControl?.trackPress(agent, client) + if (inputTurns && (method === 'sendKeyEvent' || method === 'toggleMouse' || (method === 'mouseMove' && useSystemPointer))) { + const turn = inputTurns.scope(agent) + if (!turn) throw new ToolContextUnavailableError('Directional CUA input requires an active agent turn') + turn.track(client) + params.taskId = agent.id + params.turn = turn.turn + } const nativeParams = method === 'findApps' ? { ...params, maxAppMatches: config.maxAppMatches } : method === 'paste' @@ -380,7 +386,8 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) execution.signal.throwIfAborted() lifetime.signal.throwIfAborted() const owner = ownerFor(agent) - const signal = AbortSignal.any([execution.signal, lifetime.signal, owner.signal]) + const turn = inputTurns?.scope(agent) + const signal = AbortSignal.any([execution.signal, lifetime.signal, owner.signal, ...turn ? [turn.signal] : []]) signal.throwIfAborted() const operation = (async () => { const previous = clients.get(agent) @@ -408,7 +415,8 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) owner.coordinates = new CuaCoordinates() } const nativeClient = client - const route = request.method === 'mouseMove' || request.method === 'drag' || request.method === 'toggleMouse' + const route = request.method === 'mouseMove' || request.method === 'drag' + || (request.method === 'toggleMouse' && !(inputTurns && request.params.direction === 'up')) ? mouseControl?.resolve(agent, 'useSystemPointer' in request.params && request.params.useSystemPointer === true) : undefined if (route?.prepare) owner.coordinates.parameters(request) diff --git a/packages/experimental/cua/src/mouse-control.ts b/packages/experimental/cua/src/mouse-control.ts index 255f23705d..ef247bd7b9 100644 --- a/packages/experimental/cua/src/mouse-control.ts +++ b/packages/experimental/cua/src/mouse-control.ts @@ -2,7 +2,7 @@ import type { Context } from '@deepseek-ai/cordis' import type { Agent } from '@deepseek-ai/dsh-agent' import { UserQuestionError } from '@deepseek-ai/dsh-user-questions' -import { NativeError, type NativeClient } from './native-client.ts' +import { NativeError } from './native-client.ts' import { applicationAccessDisplay } from './locales.ts' import { mouseControlPrompt } from './mouse-control-locales.ts' @@ -10,29 +10,7 @@ import { mouseControlPrompt } from './mouse-control-locales.ts' export class MouseControl { private readonly decisions = new WeakMap() - private readonly pressed = new WeakMap() - - constructor(private readonly ctx: Context, private readonly requireApproval: boolean) { - ctx.on('session/event', (session, event) => { - if (event.type !== 'turn/end') return - const client = this.pressed.get(session) - this.pressed.delete(session) - if (client && !client.disposed) { - void client.requestCleanup('releaseSystemButton', {}).catch((error: unknown) => { - ctx.logger.warn('Could not release system mouse input at turn end: %s', error) - }) - } - }) - } - - /** - * Arm turn-end cleanup before posting; cancellation can hide an already dispatched press. - * @param agent Owner of the current turn. - * @param client Connection that owns and can release the native button. - */ - trackPress(agent: Agent, client: NativeClient): void { - this.pressed.set(agent.session, client) - } + constructor(private readonly ctx: Context, private readonly requireApproval: boolean) {} /** * Select the per-call route and any approval required before dispatch. diff --git a/packages/experimental/cua/src/turn-inputs.ts b/packages/experimental/cua/src/turn-inputs.ts new file mode 100644 index 0000000000..3cfe2eb29e --- /dev/null +++ b/packages/experimental/cua/src/turn-inputs.ts @@ -0,0 +1,82 @@ +/** Turn-owned admission and acknowledged cleanup for providers implementing held input. */ +import type { Context } from '@deepseek-ai/cordis' +import type { Agent } from '@deepseek-ai/dsh-agent' +import { NativeError, type NativeClient } from './native-client.ts' + +class InputTurn { + readonly controller = new AbortController() + readonly signal: AbortSignal + private client?: NativeClient + private removeCleanup?: () => void + private closing?: Promise + + constructor(readonly agent: Agent, readonly turn: number, signal: AbortSignal, + private readonly failed: (error: unknown) => void) { + this.signal = AbortSignal.any([signal, this.controller.signal]) + } + + track(client: NativeClient): void { + this.signal.throwIfAborted() + if (this.client && this.client !== client) { + throw new NativeError('INPUT_CONNECTION_CHANGED', 'Held input belongs to the original connection; finish this turn before selecting another connection') + } + if (!this.client) { + this.removeCleanup = client.registerCleanup(canRequest => this.close(canRequest)) + this.client = client + } + } + + close(canRequest = true): Promise { + this.controller.abort() + return this.closing ??= Promise.resolve().then(async () => { + try { + if (!this.client) return + if (!canRequest) throw new NativeError('INPUT_CLEANUP_UNCONFIRMED', 'Native connection closed before turn input cleanup was confirmed. Input is disabled for this task; start a new task after checking the desktop') + await this.client.requestCleanup('releaseHeldInputs', { taskId: this.agent.id, turn: this.turn }) + } catch (error) { + this.failed(error) + throw error + } finally { + this.removeCleanup?.() + } + }) + } +} + +/** A provider opts in only when its helper implements the turn-owned input protocol. */ +export class CuaInputTurns { + private readonly turns = new WeakMap() + private readonly failures = new WeakMap() + + /** @param ctx - Provider scope owning the lifecycle listeners. */ + constructor(private readonly ctx: Context) { + ctx.on('agent/pre-step', (event, next) => { + if (this.turns.get(event.agent)?.turn !== event.turn) { + this.turns.set(event.agent, new InputTurn(event.agent, event.turn, event.signal, (error) => { + this.failures.set(event.agent, error) + ctx.logger.error('CUA input cleanup was not confirmed; input is disabled for task %s: %s', event.agent.id, error) + })) + } + return next() + }) + ctx.on('agent/turn-finalizing', ({ agent, turn }) => { + const owner = this.turns.get(agent) + if (owner?.turn === turn) return owner.close() + }) + } + + /** + * Resolve admission for the current turn; a failed cleanup blocks further CUA dispatch. + * @param agent - Task issuing the operation. + * @returns Turn signal and native ownership, or undefined before a turn starts. + */ + scope(agent: Agent): InputTurn | undefined { + if (this.failures.has(agent)) { + throw new NativeError('INPUT_CLEANUP_UNCONFIRMED', 'CUA input cleanup was not confirmed. Input is disabled for this task; start a new task after checking the desktop', { cause: this.failures.get(agent) }) + } + const boundary = this.ctx.agents.turnBoundaryOf(agent.session) + if (boundary.openTurnStartSeq === null) return undefined + const owner = this.turns.get(agent) + return owner?.turn === boundary.lastTurn ? owner : undefined + } +} diff --git a/packages/experimental/cua/src/types.ts b/packages/experimental/cua/src/types.ts index a057e1167a..9501b9e77e 100644 --- a/packages/experimental/cua/src/types.ts +++ b/packages/experimental/cua/src/types.ts @@ -157,10 +157,10 @@ export interface CuaSurface { pressKey(key: string, modifiers?: string[]): Promise /** * Send one key-down or key-up event at the current input focus. - * Does not send the opposite event. + * macOS retains explicit downs across programs within one turn and releases remaining input at turn end. * Rejects when the provider does not support keyboard input at this scope. * @param key - Platform-defined key name; modifier keys may themselves be targets. - * @param direction - Explicit event direction; the opposite event is never sent implicitly. + * @param direction - Down establishes a hold; up immediately releases owned input at its saved recipient. * @returns Whether the provider successfully executed the requested operation. */ sendKeyEvent(key: string, direction: 'down' | 'up'): Promise @@ -192,7 +192,8 @@ export interface CuaWindow extends CuaSurface { options?: CuaCoordinateOptions & { useSystemPointer?: boolean }): Promise /** * Send one mouse-button down or up event without moving the pointer. - * Does not send the opposite event; callers explicitly release a pressed button. + * macOS retains explicit downs within one turn; up uses the saved window and input route. + * Turn completion, failure, or cancellation releases remaining keys and buttons in reverse press order. * @param mouseButton - Mouse button to press or release. * @param direction - Explicit event direction. * @param options - Request a system button on a provider reporting systemPointer. diff --git a/packages/experimental/cua/tests/run-code-composition.spec.ts b/packages/experimental/cua/tests/run-code-composition.spec.ts index 1601bffee5..f689f705d6 100644 --- a/packages/experimental/cua/tests/run-code-composition.spec.ts +++ b/packages/experimental/cua/tests/run-code-composition.spec.ts @@ -40,6 +40,7 @@ const programs = [ class ProgramModel extends LlmAdapter { readonly requests: GenerateOptions[] = [] + beforeStream?: (index: number, options: GenerateOptions) => Promise /** Requests a test holds back until it has finished acting between two model steps. */ readonly gates = new Map>() constructor(private readonly programs: readonly string[]) { super() } @@ -47,6 +48,7 @@ class ProgramModel extends LlmAdapter { return Promise.resolve({ provider, id: model, name: model, inputModalities: ['text', 'image'] }) } async * stream(options: GenerateOptions): AsyncIterable { + await this.beforeStream?.(this.requests.length, options) await this.gates.get(this.requests.length) const code = this.programs[this.requests.length] this.requests.push(options) @@ -63,7 +65,7 @@ class ProgramModel extends LlmAdapter { } } -async function setup(programs: readonly string[], platform = 'macos', selectorPid?: number, presetFree = false) { +async function setup(programs: readonly string[], platform = 'macos', selectorPid?: number, presetFree = false, turnInputLifecycle = false) { const directory = await mkdtemp(join(tmpdir(), 'dsh-cua-run-code-')) const ctx = new Context() onTestFinished(async () => { @@ -103,8 +105,8 @@ async function setup(programs: readonly string[], platform = 'macos', selectorPi apply(owner: Context, config: CuaConfig) { installCua(owner, config, { helperPath: process.execPath, createChannel: native.createChannel, getGuidance: () => 'Use the CUA object API to inspect and control the selected application.', - acceptsPidSelector: selectorPid !== undefined, - capabilities: { platform, methods: ['getCapabilities', 'listApps', 'getApp', 'getState', 'click', 'screenshot'], + acceptsPidSelector: selectorPid !== undefined, turnInputLifecycle, + capabilities: { platform, methods: ['getCapabilities', 'listApps', 'getApp', 'getState', 'click', 'screenshot', 'sendKeyEvent', 'toggleMouse'], appLevelAccessibility: true, keyboard: ['app'], browser: false, coordinateSpace: 'screenshot-pixels' }, permissionParameters: (_method, permission, locale) => ({ permission, locale }), }) @@ -140,7 +142,7 @@ async function setup(programs: readonly string[], platform = 'macos', selectorPi ctx.on('agent/status', ({ agent: subject, status }) => { if (subject === agent && status === 'idle') idle.resolve() }) const provider = [...ctx.loader.entries()].find(entry => entry.options.id === 'cua') if (provider?.fiber === undefined) throw new Error('Loader did not activate the CUA fixture provider') - return { ctx, native, guarded, model, agent, provider: provider.fiber, + return { ctx, native, guarded, model, agent, handle, provider: provider.fiber, run: () => { agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Inspect and increment the fixture counter.' }], source: { kind: 'user' } })) return idle.promise @@ -354,3 +356,128 @@ it('forwards per-read accessibility limits to the Windows backend', async () => expect(native.calls.find(call => call.method === 'getState')?.params) .toMatchObject({ maxElements: 30, maxDepth: 3 }) }) + +const holdProgram = 'var app = await cua.getApp("test.fixture"); await app.sendKeyEvent("w", "down")' + +it('keeps held keys across programs and a failed program until explicit up or turn completion', async () => { + const f = await setup([holdProgram, 'throw Error("program failed")', + 'await app.sendKeyEvent("w", "up"); await app.sendKeyEvent("shift", "down"); var win = await app.getWindow("7"); await win.toggleMouse("left", "down"); await app.sendKeyEvent("d", "down")'], + 'macos', undefined, true, true) + await f.run() + const results = f.agent.session.deriveMessages().filter(message => message.role === 'tool') + expect(results.map(result => result.isError)).toEqual([false, true, false]) + expect(f.native.events).toEqual(['w:down', 'w:up', 'shift:down', 'left:down', 'd:down', 'd:up', 'left:up', 'shift:up']) + const requests = f.native.calls.filter(call => call.method === 'sendKeyEvent') + expect(requests.map(call => [call.params.taskId, call.params.turn])).toEqual(Array(4).fill([f.agent.id, 1])) + expect(f.native.calls.filter(call => call.method === 'releaseHeldInputs')).toHaveLength(1) + expect(f.native.held).toEqual([]) +}) + +it.each(['normal', 'model failure', 'thinking stop'] as const)('awaits native release before idle on %s', async (ending) => { + const f = await setup([holdProgram], 'macos', undefined, true, true) + const thinking: PromiseWithResolvers = Promise.withResolvers() + f.model.beforeStream = async (index, options) => { + if (index !== 1) return + if (ending === 'model failure') throw new Error('Model request failed') + if (ending === 'thinking stop') { + thinking.resolve() + await new Promise((resolve) => { options.signal?.addEventListener('abort', () => { resolve() }, { once: true }) }) + } + } + const release = f.native.controlNext('releaseHeldInputs') + const running = f.run() + if (ending === 'thinking stop') { await thinking.promise; f.agent.cancel({ kind: 'user' }) } + await release.entered + try { + expect(f.agent.status).toBe('running') + expect(f.agent.session.snapshotEvents().some(event => event.type === 'turn/end')).toBe(false) + expect(f.native.held.map(press => press.key)).toEqual(['w']) + } finally { release.reply(); await running } + expect(f.native.held).toEqual([]) + expect(f.agent.session.snapshotEvents().at(-1)).toMatchObject({ type: 'turn/end', data: { reason: { + kind: ending === 'normal' ? 'completed' : ending === 'model failure' ? 'error' : 'aborted', + } } }) +}) + +it('stops an in-flight down before cleanup and does not release input from the next turn', async () => { + const f = await setup([holdProgram], 'macos', undefined, true, true) + const down = f.native.controlNext('sendKeyEvent', { afterDispatch: true, waitForCancellation: true }) + const running = f.run() + await down.entered + f.agent.cancel({ kind: 'user' }) + await down.cancelled + expect(f.native.held.map(press => press.key)).toEqual(['w']) + expect(f.native.calls.some(call => call.method === 'releaseHeldInputs')).toBe(false) + down.reply({ code: 'NATIVE_CANCELLED', message: 'Input stopped after dispatch' }) + await running + expect(f.native.held).toEqual([]) + f.model.requests.length = 0 + const release = f.native.controlNext('releaseHeldInputs') + f.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Next turn' }], source: { kind: 'user' } })) + await release.entered + expect(f.native.held.map(press => press.turn)).toEqual([2]) + release.reply() + await f.agent.whenIdle() + expect(f.native.calls.filter(call => call.method === 'releaseHeldInputs').map(call => call.params.turn)).toEqual([1, 2]) + expect(f.native.events.filter(event => event === 'w:up')).toHaveLength(2) +}) + +it.each(['refusal', 'disconnect'] as const)('reports cleanup %s and prevents this task from dispatching more input', async (failure) => { + const f = await setup([holdProgram], 'macos', undefined, true, true) + const errors: unknown[] = [] + f.ctx.on('agent/error', (event) => { errors.push(event.error) }) + const release = f.native.controlNext('releaseHeldInputs') + const running = f.run() + await release.entered + if (failure === 'refusal') release.reply({ code: 'INPUT_CLEANUP_FAILED', message: 'Fixture release rejected' }) + else release.disconnect() + await running + expect(errors).toHaveLength(1) + expect(f.agent.session.snapshotEvents().at(-1)).toMatchObject({ type: 'turn/end', data: { reason: { kind: 'error' } } }) + const count = f.native.calls.length + f.model.requests.length = 0 + f.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Try again' }], source: { kind: 'user' } })) + await f.agent.whenIdle() + expect(f.native.calls).toHaveLength(count) + expect(JSON.stringify(f.agent.session.deriveMessages())).toContain('INPUT_CLEANUP_UNCONFIRMED') +}) + +it.each(['agent', 'provider'] as const)('awaits held input cleanup when the %s is disposed', async (owner) => { + const f = await setup([holdProgram], 'macos', undefined, true, true) + const thinking: PromiseWithResolvers = Promise.withResolvers() + f.model.beforeStream = async (index, options) => { + if (index !== 1) return + thinking.resolve() + await new Promise((resolve) => { options.signal?.addEventListener('abort', () => { resolve() }, { once: true }) }) + } + const running = f.run() + await thinking.promise + const release = f.native.controlNext('releaseHeldInputs') + let disposed = false + const closing = (owner === 'agent' ? f.handle.dispose() : f.provider.dispose()).then(() => { disposed = true }) + await release.entered + try { + expect(disposed).toBe(false) + expect(f.native.state.closedChannels).toBe(0) + } finally { + release.reply() + f.agent.cancel({ kind: 'user' }) + await closing + await running + } + expect(f.native.held).toEqual([]) + expect(f.native.calls.filter(call => call.method === 'releaseHeldInputs')).toHaveLength(1) + expect(f.native.state.closedChannels).toBe(1) +}) + +it('does not send turn input parameters or cleanup to a provider that has not opted in', async () => { + const f = await setup([holdProgram, 'await app.sendKeyEvent("w", "up")'], 'windows', undefined, true) + await f.run() + const input = f.native.calls.filter(call => call.method === 'sendKeyEvent') + expect(input).toHaveLength(2) + for (const call of input) { + expect(call.params).not.toHaveProperty('turn') + expect(call.params).not.toHaveProperty('taskId') + } + expect(f.native.calls.some(call => call.method === 'releaseHeldInputs')).toBe(false) +}) diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index f7a5c48fe8..283d905c7b 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -5375,6 +5375,14 @@ export const EVENT_API: readonly EventApiEntry[] = [ description: 'Agent status changed (`idle` ⇄ `running`). A waking delivery enters `running` synchronously after reserving cancellation; `idle` means no driver remains scheduled or active.', parameters: [{ name: 'payload', description: '.status - the status just entered (the transition\'s destination). Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.' }], }, + { + name: 'agent/turn-finalizing', + mode: 'parallel', + signature: '\'agent/turn-finalizing\'(this: Scoped, payload: { agent: Agent; turn: number }): Promise | void', + summary: 'The turn has irrevocably stopped admitting steps.', + description: 'The turn has irrevocably stopped admitting steps. Await all resource finalizers before committing turn/end, becoming idle, or starting another turn, including on cancellation. Listeners own bounded cleanup independent of the cancelled operation signal. Failures are reported through agent/error and the durable turn ending after every listener settles.', + parameters: [{ name: 'payload', description: '.turn - the turn being finalized. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.' }], + }, { name: 'agent/turn-stopping', mode: 'serial', diff --git a/scripts/fixtures/python-snapshot-tool.mjs b/scripts/fixtures/python-snapshot-tool.mjs index dcf8afdf17..5a02fac27a 100644 --- a/scripts/fixtures/python-snapshot-tool.mjs +++ b/scripts/fixtures/python-snapshot-tool.mjs @@ -1,9 +1,16 @@ /** Deterministic job-backed tool and denial fixture for the packaged SDK snapshot. */ +import { createUserMessage } from '@deepseek-ai/dsh-llm' + export const name = 'python-snapshot-tool' export const inject = ['tools', 'jobs'] /** @param {import('@deepseek-ai/cordis').Context} ctx - Scenario-owned tool registration. */ export function apply(ctx) { + ctx.on('agent/turn-finalizing', async ({ agent }) => { + if (agent.id !== 'advanced-executable') return + await Promise.resolve() + agent.inject(createUserMessage({ content: [{ type: 'text', text: 'Turn resources released.' }], source: { kind: 'user' } })) + }) ctx.on('tools/pre-execute', (exec, next) => { if (exec.name !== 'snapshot_double' || exec.arguments.value !== -1) return next() return { diff --git a/snapshots/sdk/ptc-cancel/cancel.mjs b/snapshots/sdk/ptc-cancel/cancel.mjs index 42bdabdddc..d8ee51b63f 100644 --- a/snapshots/sdk/ptc-cancel/cancel.mjs +++ b/snapshots/sdk/ptc-cancel/cancel.mjs @@ -1,7 +1,13 @@ /** Cancel after the PTC process completes a nested job_list call. */ +import { createUserMessage } from '@deepseek-ai/dsh-llm' + export const name = 'ptc-cancel-fixture' export const inject = ['tools'] export function apply(ctx) { + ctx.on('agent/turn-finalizing', async ({ agent }) => { + await Promise.resolve() + agent.inject(createUserMessage({ content: [{ type: 'text', text: 'Turn resources released.' }], source: { kind: 'user' } })) + }) ctx.on('tools/result', (exec) => { if (exec.name === 'job_list' && exec.parent !== undefined && exec.agent !== undefined) { exec.agent.cancel({ kind: 'user' }) diff --git a/snapshots/session/cua-run-code/native-channel.d.mts b/snapshots/session/cua-run-code/native-channel.d.mts index c50d91e559..aa3ac63e27 100644 --- a/snapshots/session/cua-run-code/native-channel.d.mts +++ b/snapshots/session/cua-run-code/native-channel.d.mts @@ -12,6 +12,14 @@ export function createNativeFixture(selectorPid?: number): { createChannel: NativeChannelFactory calls: Array<{ id: string; method: string; params: Record }> events: string[] + held: Array<{ connection: number; taskId: string; turn: number; key: string }> + /** Control one native reply or cancellation acknowledgement at a deterministic barrier. */ + controlNext(method: string, options?: { afterDispatch?: boolean; waitForCancellation?: boolean }): { + entered: Promise + cancelled: Promise + reply(error?: { code: string; message: string }): void + disconnect(): void + } state: { count: number; openedChannels: number; closedChannels: number } /** @returns A barrier reached when the next click waits for native cancellation. */ holdNextClick(): Promise diff --git a/snapshots/session/cua-run-code/native-channel.mjs b/snapshots/session/cua-run-code/native-channel.mjs index 2e276b16bf..aeb02c824f 100644 --- a/snapshots/session/cua-run-code/native-channel.mjs +++ b/snapshots/session/cua-run-code/native-channel.mjs @@ -12,18 +12,31 @@ export function createNativeFixture(selectorPid) { const calls = [] const events = [] const state = { count: 0, openedChannels: 0, closedChannels: 0 } + const held = [] + let controlled let nextHeldClick const bounds = { x: 40, y: 60, width: 320, height: 200 } const window = { windowId: '7', appName: 'Fixture', title: 'CUA fixture', bounds, isOnScreen: true, onCurrentSpace: true } function createChannel() { - state.openedChannels++ + const connection = ++state.openedChannels const stdout = new PassThrough() let acquired = false let generation = 0 let observed + let blocked let heldCallId function dispatch(method, params) { + if (method === 'releaseHeldInputs') { + for (let index = held.length - 1; index >= 0; index--) { + const press = held[index] + if (press.connection === connection && press.taskId === params.taskId && press.turn === params.turn) { + events.push(`${press.key}:up`) + held.splice(index, 1) + } + } + return { dispatched: true } + } if (method === 'getCapabilities') return { sessionLocked: false, permissions: { accessibility: true, screenRecording: true } } if (method === 'listApps') return [{ id: 'test.fixture', name: 'Fixture', isRunning: true, pid: selectorPid ?? 4 }] if (method === 'getApp') { @@ -35,6 +48,17 @@ export function createNativeFixture(selectorPid) { authorization: { id: 'a'.repeat(64), name: 'Fixture', executablePath: '/fixture/app', persistable: true } } } if (!acquired || params.appHandle !== 'fixture-app') throw new Error('Acquire the application before using its handle') + if (method === 'sendKeyEvent' || method === 'toggleMouse') { + const key = params.key ?? params.mouseButton + const index = held.findIndex(press => press.connection === connection && press.taskId === params.taskId && press.turn === params.turn && press.key === key) + if (params.direction === 'down' && index < 0) held.push({ connection, taskId: params.taskId, turn: params.turn, key }) + if (params.direction === 'up') { + if (index < 0) throw new Error('Input was not held by this turn') + held.splice(index, 1) + } + events.push(`${key}:${params.direction}`) + return { dispatched: true } + } if (method === 'listWindows') return [window] if (method === 'getState') { observed = `fixture-snapshot-${++generation}` @@ -53,13 +77,31 @@ export function createNativeFixture(selectorPid) { const stdin = new Writable({ write(chunk, _encoding, callback) { try { const { type, id, method, params } = JSON.parse(chunk.toString()) - if (type === 'cancel' && id === heldCallId) { + if (type === 'cancel' && blocked?.id === id) { + events.push('native-cancelled') + blocked.control.cancelled.resolve() + if (!blocked.control.waitForCancellation) blocked.finish({ code: 'NATIVE_CANCELLED', message: 'Fixture input cancelled.' }) + } else if (type === 'cancel' && id === heldCallId) { heldCallId = undefined events.push('native-cancelled') stdout.write(JSON.stringify({ id, error: { code: 'NATIVE_CANCELLED', message: 'Fixture click cancelled.' } }) + '\n') } else { calls.push({ id, method, params }) - if (method === 'click' && nextHeldClick !== undefined) { + if (controlled?.method === method) { + const control = controlled + controlled = undefined + const result = control.afterDispatch ? dispatch(method, params) : undefined + const finish = error => { + if (!blocked) return + blocked = undefined + const response = error ? { id, error } : { id, result: result ?? dispatch(method, params) } + stdout.write(JSON.stringify(response) + '\n') + } + blocked = { id, control, finish } + control.reply = finish + control.disconnect = () => { stdout.end() } + control.entered.resolve() + } else if (method === 'click' && nextHeldClick !== undefined) { heldCallId = id const started = nextHeldClick nextHeldClick = undefined @@ -80,13 +122,23 @@ export function createNativeFixture(selectorPid) { if (closed) return closed = true events.push('native-close') + for (let index = held.length - 1; index >= 0; index--) if (held[index].connection === connection) held.splice(index, 1) stdin.end() stdout.end() }, waitForClose: () => done, } } - return { createChannel, calls, events, state, + return { createChannel, calls, events, state, held, + controlNext(method, { afterDispatch = false, waitForCancellation = false } = {}) { + if (controlled) throw new Error('Another request is already controlled') + const entered = Promise.withResolvers(), cancelled = Promise.withResolvers() + const control = { method, afterDispatch, waitForCancellation, entered, cancelled, + reply: () => { throw new Error('Request has not arrived') }, disconnect: () => { throw new Error('Request has not arrived') } } + controlled = control + return { entered: entered.promise, cancelled: cancelled.promise, + reply: error => control.reply(error), disconnect: () => control.disconnect() } + }, holdNextClick() { if (nextHeldClick !== undefined) throw new Error('A fixture click is already held') nextHeldClick = Promise.withResolvers() diff --git a/snapshots/session/cua-run-code/provider.mjs b/snapshots/session/cua-run-code/provider.mjs index 10f864cabb..f7ef100d80 100644 --- a/snapshots/session/cua-run-code/provider.mjs +++ b/snapshots/session/cua-run-code/provider.mjs @@ -12,9 +12,10 @@ export function apply(ctx, config) { const fixture = createNativeFixture() installCua(ctx, config, { helperPath: process.execPath, + turnInputLifecycle: true, createChannel: fixture.createChannel, getGuidance: () => COMMON_GUIDANCE, - capabilities: { platform: 'macos', methods: ['getCapabilities', 'getApp', 'getState', 'click', 'screenshot'], + capabilities: { platform: 'macos', methods: ['getCapabilities', 'getApp', 'getState', 'click', 'screenshot', 'sendKeyEvent', 'toggleMouse'], appLevelAccessibility: true, keyboard: ['app'], browser: false, coordinateSpace: 'screenshot-pixels' }, permissionParameters: (_method, permission, locale) => ({ permission, locale }), }) diff --git a/snapshots/session/cua-run-code/session.v4.jsonl b/snapshots/session/cua-run-code/session.v4.jsonl index 7ab86a1e77..e264635e40 100644 --- a/snapshots/session/cua-run-code/session.v4.jsonl +++ b/snapshots/session/cua-run-code/session.v4.jsonl @@ -13,7 +13,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 cua_run_code to select test.fixture,","messageSeqs":[9],"source":{"kind":"fallback"}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"stream":[{"type":"chunk","time":1794291763110,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794291763110,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}}},{"type":"chunk","time":1794291763110,"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_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); await app.sendKeyEvent(\\\"w\\\", \\\"down\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"stream":[{"type":"chunk","time":1794291763110,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794291763110,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); await app.sendKeyEvent(\\\"w\\\", \\\"down\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}}},{"type":"chunk","time":1794291763110,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemPointer\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} @@ -28,7 +28,7 @@ {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"cua_first"},"toolCallId":"cua_first","content":[{"type":"text","text":"{\"visits\":1,\"bindings\":[\"cua\"],\"app\":\"fixture-app\",\"window\":\"7\"}\n"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[15],"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_reuse","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\",\"description\":\"Reuse the retained application and window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:6}}"},"stream":[{"type":"chunk","time":1794291763317,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794291763317,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_reuse","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\",\"description\":\"Reuse the retained application and window\"}"}}},{"type":"chunk","time":1794291763317,"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_reuse","name":"cua_run_code","arguments":"{\"code\":\"await app.sendKeyEvent(\\\"w\\\", \\\"up\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) })); await win.toggleMouse(\\\"left\\\", \\\"down\\\"); await app.sendKeyEvent(\\\"d\\\", \\\"down\\\")\",\"description\":\"Reuse the retained application and window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:6}}"},"stream":[{"type":"chunk","time":1794291763317,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794291763317,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_reuse","name":"cua_run_code","arguments":"{\"code\":\"await app.sendKeyEvent(\\\"w\\\", \\\"up\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) })); await win.toggleMouse(\\\"left\\\", \\\"down\\\"); await app.sendKeyEvent(\\\"d\\\", \\\"down\\\")\",\"description\":\"Reuse the retained application and window\"}"}}},{"type":"chunk","time":1794291763317,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"cua_reuse","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\",\"description\":\"Reuse the retained application and window\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:1","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:1","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"snapshotId\":\"fixture-snapshot-2\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 1\\\"\",\"windows\":[{\"windowId\":\"7\",\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} From 50b18e554f8f85eea0670374f416a84b24314f61 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 14:47:44 +0800 Subject: [PATCH 02/73] Update input approval fixtures for active turn ownership --- .../tests/provider-lifecycle.spec.ts | 26 +++++++++++-------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index 66304e8cd4..f4563c0146 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -1,4 +1,5 @@ /** Native helper replacement is synchronized with Agent and provider disposal. */ +import { randomUUID } from 'node:crypto' import { executeModelToolFixture, executeToolFixture } from '@deepseek-ai/dsh-tool-testkit' import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' @@ -184,8 +185,9 @@ async function thinkingTurn(f: Awaited>) { yield { type: 'finish', reason: { kind: 'aborted' } } } } - f.ctx.llm.registerAdapter(['thinking'], new WaitingModel()) - Object.assign(f.handle.agent.options, { provider: 'thinking', model: 'fixture' }) + const provider = `thinking-${randomUUID()}` + f.ctx.llm.registerAdapter([provider], new WaitingModel()) + Object.assign(f.handle.agent.options, { provider, model: 'fixture' }) f.handle.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Wait for input' }], source: { kind: 'user' } })) onTestFinished(async () => { f.handle.agent.cancel({ kind: 'user' }); await f.handle.agent.whenIdle() }) await entered.promise @@ -1082,11 +1084,11 @@ const physicalHover = { ...hoverTarget, useSystemPointer: true } async function hoverFixture(requireApproval = true) { const f = await setup() - await thinkingTurn(f) if (!requireApproval) { await f.provider.dispose() await f.ctx.plugin(NativeProvider, { ...config, requireSystemPointerApproval: false }) } + await thinkingTurn(f) const questions = await f.ctx.plugin(UserQuestions) const questionId = 'cua-mouse-control' const approved = { answers: [{ id: questionId, selected: ['Allow for this session'] }] } @@ -1126,9 +1128,9 @@ it('requires an explicit system-pointer request on every move and asks only once [hoverTarget, false], [{ ...hoverTarget, useSystemPointer: false }, false], [physicalHover, true], ] as const) { expect((await f.execute('mouseMove', params)).isError).toBe(false) - expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...hoverTarget, useSystemPointer: physical }, expect.any(AbortSignal), expect.any(String)) + expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...hoverTarget, useSystemPointer: physical, ...physical ? { taskId: f.handle.agent.id, turn: 1 } : {} }, expect.any(AbortSignal), expect.any(String)) } - expect(native.request.mock.calls[1]?.[1]).toEqual(physicalHover) + expect(native.request.mock.calls[1]?.[1]).toEqual({ ...physicalHover, taskId: f.handle.agent.id, turn: 1 }) expect(f.ask).toHaveBeenCalledTimes(1) }) @@ -1137,7 +1139,7 @@ it.each([true, false])('shares the mouse control decision for a system button wi const target = { appHandle: 'app-one', windowId: '7', mouseButton: 'left', direction: 'down' } for (const params of [target, { ...target, useSystemPointer: false }]) { expect((await f.execute('toggleMouse', params)).isError).toBe(false) - expect(native.request.mock.lastCall?.[1]).toEqual(target) + expect(native.request.mock.lastCall?.[1]).toEqual({ ...target, taskId: f.handle.agent.id, turn: 1 }) } expect(f.ask).not.toHaveBeenCalled() const answer = Promise.withResolvers() @@ -1160,8 +1162,9 @@ it.each([true, false])('shares the mouse control decision for a system button wi await f.handle.agent.whenIdle() expect(native.cleanup).toHaveBeenCalledWith('releaseHeldInputs', { taskId: f.handle.agent.id, turn: 1 }) } else { - for (const result of results) expect(JSON.stringify(result.content)).toContain('MOUSE_CONTROL_DENIED') - expect(native.request).not.toHaveBeenCalled() + for (const result of results.slice(0, 2)) expect(JSON.stringify(result.content)).toContain('MOUSE_CONTROL_DENIED') + expect(results[2]?.isError).toBe(false) + expect(native.request.mock.calls.map(([method]) => method)).toEqual(['toggleMouse']) } expect(f.ask).toHaveBeenCalledOnce() }) @@ -1205,10 +1208,11 @@ it('keeps refusals and grants separate and forgets a closed session on reopen', expect((await f.call(agent, 'mouseMove', hoverTarget)).isError).toBe(false) expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...hoverTarget, useSystemPointer: false }, expect.any(AbortSignal), expect.any(String)) expect((await f.execute('mouseMove', physicalHover)).isError).toBe(false) - expect(native.request).toHaveBeenLastCalledWith('mouseMove', physicalHover, expect.any(AbortSignal), expect.any(String)) + expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...physicalHover, taskId: f.handle.agent.id, turn: 1 }, expect.any(AbortSignal), expect.any(String)) const sessionId = f.handle.agent.id await f.handle.dispose() const reopened = await f.ctx.agents.create({ sessionId }) + await thinkingTurn({ ...f, handle: reopened }) await f.select(reopened.agent) expect((await f.call(reopened.agent, 'mouseMove', hoverTarget)).isError).toBe(false) expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...hoverTarget, useSystemPointer: false }, expect.any(AbortSignal), expect.any(String)) @@ -1264,7 +1268,7 @@ it('allows only the explicitly requested physical move when approval is disabled const f = await hoverFixture(false) for (const [target, expected] of [[hoverTarget, false], [physicalHover, true], [hoverTarget, false]] as const) { expect((await f.execute('mouseMove', target)).isError).toBe(false) - expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...hoverTarget, useSystemPointer: expected }, expect.any(AbortSignal), expect.any(String)) + expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...hoverTarget, useSystemPointer: expected, ...expected ? { taskId: f.handle.agent.id, turn: 1 } : {} }, expect.any(AbortSignal), expect.any(String)) } expect(f.ask).not.toHaveBeenCalled() }) @@ -1319,7 +1323,7 @@ it.each([true, false])('uses the declared systemPointer capability for a non-mac const physical = await f.execute('mouseMove', physicalHover) expect(physical.isError).toBe(!systemPointer) expect(answer).toHaveBeenCalledTimes(systemPointer ? 1 : 0) - if (systemPointer) expect(native.request).toHaveBeenLastCalledWith('mouseMove', physicalHover, expect.any(AbortSignal), expect.any(String)) + if (systemPointer) expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...physicalHover, taskId: f.handle.agent.id, turn: 1 }, expect.any(AbortSignal), expect.any(String)) else expect(native.request).not.toHaveBeenCalled() expect((await f.execute('mouseMove', hoverTarget)).isError).toBe(false) expect(native.request).toHaveBeenLastCalledWith('mouseMove', systemPointer ? { ...hoverTarget, useSystemPointer: false } : hoverTarget, From ddbc1809ab5d7e299f54b437e034079af677a67f Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 14:50:41 +0800 Subject: [PATCH 03/73] Cover cleanup timeout and concurrent CUA turn ownership --- .../cua/tests/run-code-composition.spec.ts | 48 +++++++++++++++++-- 1 file changed, 44 insertions(+), 4 deletions(-) diff --git a/packages/experimental/cua/tests/run-code-composition.spec.ts b/packages/experimental/cua/tests/run-code-composition.spec.ts index f689f705d6..6dd86ed0b2 100644 --- a/packages/experimental/cua/tests/run-code-composition.spec.ts +++ b/packages/experimental/cua/tests/run-code-composition.spec.ts @@ -65,7 +65,7 @@ class ProgramModel extends LlmAdapter { } } -async function setup(programs: readonly string[], platform = 'macos', selectorPid?: number, presetFree = false, turnInputLifecycle = false) { +async function setup(programs: readonly string[], platform = 'macos', selectorPid?: number, presetFree = false, turnInputLifecycle = false, timeoutMs = 30_000) { const directory = await mkdtemp(join(tmpdir(), 'dsh-cua-run-code-')) const ctx = new Context() onTestFinished(async () => { @@ -121,7 +121,7 @@ async function setup(programs: readonly string[], platform = 'macos', selectorPi ...name === 'sandboxPolicy' ? { config: { mode: 'danger-full-access', workspaceRoot: directory } } : {}, ...name === 'sharedRuntime' ? { config: { executionMode: 'per-call' } } : {}, ...name === 'attachments' ? { config: { dshHome: directory } } : {}, - ...name === 'cua' ? { config: { allowedApps: [{ id: 'a'.repeat(64), name: 'Fixture', executablePath: '/fixture/app' }] } } : {}, + ...name === 'cua' ? { config: { timeoutMs, allowedApps: [{ id: 'a'.repeat(64), name: 'Fixture', executablePath: '/fixture/app' }] } } : {}, })) const configPath = join(directory, 'cordis.yml') await writeFile(configPath, JSON.stringify(entries, null, 2) + '\n') @@ -422,7 +422,7 @@ it('stops an in-flight down before cleanup and does not release input from the n expect(f.native.events.filter(event => event === 'w:up')).toHaveLength(2) }) -it.each(['refusal', 'disconnect'] as const)('reports cleanup %s and prevents this task from dispatching more input', async (failure) => { +it.each(['refusal', 'disconnect', 'timeout'] as const)('reports cleanup %s and prevents this task from dispatching more input', async (failure) => { const f = await setup([holdProgram], 'macos', undefined, true, true) const errors: unknown[] = [] f.ctx.on('agent/error', (event) => { errors.push(event.error) }) @@ -430,7 +430,7 @@ it.each(['refusal', 'disconnect'] as const)('reports cleanup %s and prevents thi const running = f.run() await release.entered if (failure === 'refusal') release.reply({ code: 'INPUT_CLEANUP_FAILED', message: 'Fixture release rejected' }) - else release.disconnect() + else if (failure === 'disconnect') release.disconnect() await running expect(errors).toHaveLength(1) expect(f.agent.session.snapshotEvents().at(-1)).toMatchObject({ type: 'turn/end', data: { reason: { kind: 'error' } } }) @@ -481,3 +481,43 @@ it('does not send turn input parameters or cleanup to a provider that has not op } expect(f.native.calls.some(call => call.method === 'releaseHeldInputs')).toBe(false) }) + +it('cleans one task without releasing another connection and prevents a queued turn from overtaking cleanup', async () => { + const f = await setup([holdProgram], 'macos', undefined, true, true) + const peerModel = new ProgramModel([holdProgram.replace('"w"', '"d"')]) + f.ctx.llm.registerAdapter(['peer-fixture'], peerModel) + const peer = await f.ctx.agents.create({ sessionId: brandString('peer-input-owner'), meta: { cwd: process.cwd() }, + agentOptions: { provider: 'peer-fixture', model: 'vision' } }) + const ready: Array> = [Promise.withResolvers(), Promise.withResolvers()] + for (const [index, model] of [f.model, peerModel].entries()) { + model.beforeStream = async (step, options) => { + if (step !== 1) return + ready[index]!.resolve() + await new Promise((resolve) => { options.signal?.addEventListener('abort', () => { resolve() }, { once: true }) }) + } + } + const running = f.run() + peer.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Hold D' }], source: { kind: 'user' } })) + await Promise.all(ready.map(value => value.promise)) + expect(f.native.held.map(press => press.key).sort()).toEqual(['d', 'w']) + const cleanup = f.native.controlNext('releaseHeldInputs') + f.agent.cancel({ kind: 'user' }) + await cleanup.entered + const count = f.native.calls.length + f.model.requests.length = 0 + f.model.beforeStream = undefined + f.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Hold W again' }], source: { kind: 'user' } })) + expect(f.native.calls).toHaveLength(count) + const nextCleanup = f.native.controlNext('releaseHeldInputs') + cleanup.reply() + await nextCleanup.entered + try { + expect(f.native.held.map(press => [press.taskId, press.turn, press.key]).sort()) + .toEqual([[f.agent.id, 2, 'w'], [peer.agent.id, 1, 'd']].sort()) + } finally { + nextCleanup.reply() + peer.agent.cancel({ kind: 'user' }) + await Promise.all([running, f.agent.whenIdle(), peer.agent.whenIdle()]) + } + expect(f.native.held).toEqual([]) +}) From e7a0f330fbe141a6f25d7e357234eefb340e1211 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 14:52:40 +0800 Subject: [PATCH 04/73] Align lifecycle test protocols and SDK cancellation recording --- .../experimental/cua-macos/tests/provider-lifecycle.spec.ts | 4 ++-- .../experimental/cua-windows/tests/provider-lifecycle.spec.ts | 2 +- packages/experimental/cua/tests/run-code-composition.spec.ts | 4 ++-- snapshots/sdk/ptc-cancel/session.v4.jsonl | 4 +++- snapshots/session/cua-native/workspace/native-helper.mjs | 1 + snapshots/session/cua-ptc/system-prompt.expected.md | 4 ++-- snapshots/session/cua-run-code-ptc/session.v4.jsonl | 2 +- snapshots/session/cua-run-code-ptc/system-prompt.expected.md | 2 +- snapshots/session/cua-run-code-scoped/session.v4.jsonl | 2 +- snapshots/session/cua-run-code/session.v4.jsonl | 4 ++-- 10 files changed, 16 insertions(+), 13 deletions(-) diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index f4563c0146..34ed3cd629 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -182,7 +182,7 @@ async function thinkingTurn(f: Awaited>) { if (options.signal?.aborted) resolve() else options.signal?.addEventListener('abort', () => { resolve() }, { once: true }) }) - yield { type: 'finish', reason: { kind: 'aborted' } } + yield { type: 'finish', reason: { kind: 'aborted', failure: { code: 'ABORTED', message: 'Fixture cancelled' } } } } } const provider = `thinking-${randomUUID()}` @@ -1323,7 +1323,7 @@ it.each([true, false])('uses the declared systemPointer capability for a non-mac const physical = await f.execute('mouseMove', physicalHover) expect(physical.isError).toBe(!systemPointer) expect(answer).toHaveBeenCalledTimes(systemPointer ? 1 : 0) - if (systemPointer) expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...physicalHover, taskId: f.handle.agent.id, turn: 1 }, expect.any(AbortSignal), expect.any(String)) + if (systemPointer) expect(native.request).toHaveBeenLastCalledWith('mouseMove', physicalHover, expect.any(AbortSignal), expect.any(String)) else expect(native.request).not.toHaveBeenCalled() expect((await f.execute('mouseMove', hoverTarget)).isError).toBe(false) expect(native.request).toHaveBeenLastCalledWith('mouseMove', systemPointer ? { ...hoverTarget, useSystemPointer: false } : hoverTarget, diff --git a/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts index 4109de1af6..4b7a68b633 100644 --- a/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts @@ -50,7 +50,7 @@ it('uses an absolute fixture without compiling and disposes the Host runtime', a expect(backend.capabilities).toMatchObject({ platform: 'windows', appLevelAccessibility: false, keyboard: ['window'] }) expect(backend.capabilities.methods).toContain('sendKeyEvent') expect(backend.capabilities.methods).toContain('toggleMouse') - expect(backend.sendKeyEvent).toBeUndefined() + expect(backend.turnInputLifecycle).toBeUndefined() const channel = { marker: 'native stream' } native.connect.mockReturnValue(channel) const options = { ...config, helperPath: backend.helperPath, cwd: process.cwd() } diff --git a/packages/experimental/cua/tests/run-code-composition.spec.ts b/packages/experimental/cua/tests/run-code-composition.spec.ts index 6dd86ed0b2..19409aa22c 100644 --- a/packages/experimental/cua/tests/run-code-composition.spec.ts +++ b/packages/experimental/cua/tests/run-code-composition.spec.ts @@ -423,7 +423,7 @@ it('stops an in-flight down before cleanup and does not release input from the n }) it.each(['refusal', 'disconnect', 'timeout'] as const)('reports cleanup %s and prevents this task from dispatching more input', async (failure) => { - const f = await setup([holdProgram], 'macos', undefined, true, true) + const f = await setup([holdProgram], 'macos', undefined, true, true, failure === 'timeout' ? 200 : 30_000) const errors: unknown[] = [] f.ctx.on('agent/error', (event) => { errors.push(event.error) }) const release = f.native.controlNext('releaseHeldInputs') @@ -505,7 +505,7 @@ it('cleans one task without releasing another connection and prevents a queued t await cleanup.entered const count = f.native.calls.length f.model.requests.length = 0 - f.model.beforeStream = undefined + delete f.model.beforeStream f.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Hold W again' }], source: { kind: 'user' } })) expect(f.native.calls).toHaveLength(count) const nextCleanup = f.native.controlNext('releaseHeldInputs') diff --git a/snapshots/sdk/ptc-cancel/session.v4.jsonl b/snapshots/sdk/ptc-cancel/session.v4.jsonl index 08c8bd59a1..2f28e82281 100644 --- a/snapshots/sdk/ptc-cancel/session.v4.jsonl +++ b/snapshots/sdk/ptc-cancel/session.v4.jsonl @@ -13,10 +13,12 @@ {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Start a run_code program, call","messageSeqs":[8],"source":{"kind":"fallback"}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"ptc-cancel","name":"run_code","arguments":"{\"code\":\"await tools.job_list({}); for (;;) {}\",\"description\":\"Run until stopped\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:5}}"},"stream":[{"type":"chunk","time":1793796116464,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1793796116464,"index":0,"dt":[],"id":"ptc-cancel","name":"run_code","args":["{\"code\":\"await tools.job_list({}); for (;;) {}\",\"description\":\"Run until stopped\"}"]},{"type":"chunk","time":1793796116464,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"ptc-cancel","name":"run_code","arguments":"{\"code\":\"await tools.job_list({}); for (;;) {}\",\"description\":\"Run until stopped\"}"}}},{"type":"chunk","time":1793796116464,"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":"ptc-cancel","name":"run_code","arguments":"{\"code\":\"await tools.job_list({}); for (;;) {}\",\"description\":\"Run until stopped\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:5}}"},"stream":[{"type":"chunk","time":1794984671734,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1794984671734,"index":0,"dt":[],"id":"ptc-cancel","name":"run_code","args":["{\"code\":\"await tools.job_list({}); for (;;) {}\",\"description\":\"Run until stopped\"}"]},{"type":"chunk","time":1794984671734,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"ptc-cancel","name":"run_code","arguments":"{\"code\":\"await tools.job_list({}); for (;;) {}\",\"description\":\"Run until stopped\"}"}}},{"type":"chunk","time":1794984671734,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"ptc-cancel","name":"run_code","arguments":"{\"code\":\"await tools.job_list({}); for (;;) {}\",\"description\":\"Run until stopped\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"ptc-cancel","parentCallId":"ptc-cancel","subCallId":"ptc-cancel:ptc:1","name":"job_list","arguments":{}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"ptc-cancel","parentCallId":"ptc-cancel","subCallId":"ptc-cancel:ptc:1","name":"job_list","arguments":{},"isError":false,"content":[{"type":"text","text":"(no background jobs)"}]}} {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"ptc-cancel"},"toolCallId":"ptc-cancel","content":[{"type":"text","text":"Error: tool call aborted"}],"isError":true,"id":"{{message:6}}"},"error":{"name":"AbortError","code":"ABORTED"}},"sourceEventSeqs":[15],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"Turn resources released."}],"source":{"kind":"user"},"role":"user","id":"{{message:7}}"}]}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"aborted","reason":{"kind":"user"}}}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[],"outcome":"canceled"}} diff --git a/snapshots/session/cua-native/workspace/native-helper.mjs b/snapshots/session/cua-native/workspace/native-helper.mjs index a6e7f24d94..9190c515ff 100755 --- a/snapshots/session/cua-native/workspace/native-helper.mjs +++ b/snapshots/session/cua-native/workspace/native-helper.mjs @@ -137,6 +137,7 @@ function createApplicationState(socket, record, application, captureBroker, conn const state = JSON.parse(readFileSync(new URL('./permissions.json', import.meta.url), 'utf8')) return { platform: 'darwin', ...state, helper: { pid: process.pid }, parent: { pid: process.ppid } } } + if (method === 'releaseHeldInputs') return { dispatched: true } if (method === 'getCapabilities') return { sessionLocked: false, permissions: { accessibility: true, screenRecording: true } } if (method === 'listApps') return [{ pid: app.pid, name: app.name, bundleId: app.bundleId, isRunning: true }] if (method === 'getApp') { diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index 04bb35f747..688b1de8ac 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -77,7 +77,7 @@ Leave useSystemPointer unset for ordinary mouseMove, drag, and toggleMouse calls Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemPointer?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemPointer omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemPointer?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemPointer: true on both down and up. Physical moves can then drag, including your own mouse movements. The turn ending or the connection closing releases a remaining system hold. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemPointer?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; platform guidance defines their cleanup scope. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemPointer: true on down. Up uses the input route and window saved by down. Physical moves can then drag, including your own mouse movements. Both routes hold across programs in the same turn and release with held keys when the turn ends. click and drag release their own buttons within the operation. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], 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. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying. - 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. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemPointer?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control. An explicit system drag shares the session decision with mouseMove and holds the chosen button along the path in the unobscured foreground window. @@ -89,7 +89,7 @@ Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - 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?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across run_code and cua_run_code calls in the same turn, for example W down, D down, D up, W up. Send 'up' to release it immediately at its original recipient. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. A program returning or throwing keeps its holds while the turn continues. When the turn completes, fails, or is stopped, macOS releases remaining keys and mouse buttons together in reverse press order. pressKey and typeText still release their own presses within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/snapshots/session/cua-run-code-ptc/session.v4.jsonl b/snapshots/session/cua-run-code-ptc/session.v4.jsonl index f83b4bc647..fa1e688499 100644 --- a/snapshots/session/cua-run-code-ptc/session.v4.jsonl +++ b/snapshots/session/cua-run-code-ptc/session.v4.jsonl @@ -16,7 +16,7 @@ {"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua_first","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"globalThis.visits = 1; var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))\\\", description: \\\"Select the fixture window and click Increment\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Select the fixture window and click Increment\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua_run_code","arguments":{"code":"globalThis.visits = 1; var app = await cua.getApp(\"test.fixture\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\"0\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))","description":"Select the fixture window and click Increment"}}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemPointer\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemPointer\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\",\"sendKeyEvent\",\"toggleMouse\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1: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_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:3","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} diff --git a/snapshots/session/cua-run-code-ptc/system-prompt.expected.md b/snapshots/session/cua-run-code-ptc/system-prompt.expected.md index 1bffa2dc7b..6b0a3f5ef0 100644 --- a/snapshots/session/cua-run-code-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-run-code-ptc/system-prompt.expected.md @@ -73,7 +73,7 @@ Use an explicit window for screenshots. ## Simulated mouse Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; platform guidance defines their cleanup scope. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], 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. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. diff --git a/snapshots/session/cua-run-code-scoped/session.v4.jsonl b/snapshots/session/cua-run-code-scoped/session.v4.jsonl index 7ab86a1e77..1052c75c7e 100644 --- a/snapshots/session/cua-run-code-scoped/session.v4.jsonl +++ b/snapshots/session/cua-run-code-scoped/session.v4.jsonl @@ -16,7 +16,7 @@ {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"stream":[{"type":"chunk","time":1794291763110,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794291763110,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}}},{"type":"chunk","time":1794291763110,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemPointer\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemPointer\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\",\"sendKeyEvent\",\"toggleMouse\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first: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_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:3","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} diff --git a/snapshots/session/cua-run-code/session.v4.jsonl b/snapshots/session/cua-run-code/session.v4.jsonl index e264635e40..1a850c3a7e 100644 --- a/snapshots/session/cua-run-code/session.v4.jsonl +++ b/snapshots/session/cua-run-code/session.v4.jsonl @@ -14,7 +14,7 @@ {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"}} {"type":"session/title","data":{"title":"Use cua_run_code to select test.fixture,","messageSeqs":[9],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); await app.sendKeyEvent(\\\"w\\\", \\\"down\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"stream":[{"type":"chunk","time":1794291763110,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794291763110,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); await app.sendKeyEvent(\\\"w\\\", \\\"down\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}}},{"type":"chunk","time":1794291763110,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}} +{"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); await app.sendKeyEvent(\\\"w\\\", \\\"down\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemPointer\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}}}} @@ -29,7 +29,7 @@ {"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_reuse","name":"cua_run_code","arguments":"{\"code\":\"await app.sendKeyEvent(\\\"w\\\", \\\"up\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) })); await win.toggleMouse(\\\"left\\\", \\\"down\\\"); await app.sendKeyEvent(\\\"d\\\", \\\"down\\\")\",\"description\":\"Reuse the retained application and window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:6}}"},"stream":[{"type":"chunk","time":1794291763317,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794291763317,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_reuse","name":"cua_run_code","arguments":"{\"code\":\"await app.sendKeyEvent(\\\"w\\\", \\\"up\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) })); await win.toggleMouse(\\\"left\\\", \\\"down\\\"); await app.sendKeyEvent(\\\"d\\\", \\\"down\\\")\",\"description\":\"Reuse the retained application and window\"}"}}},{"type":"chunk","time":1794291763317,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":2,"callId":"cua_reuse","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\",\"description\":\"Reuse the retained application and window\"}"}} +{"type":"tool/call","data":{"turn":1,"step":2,"callId":"cua_reuse","name":"cua_run_code","arguments":"{\"code\":\"await app.sendKeyEvent(\\\"w\\\", \\\"up\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) })); await win.toggleMouse(\\\"left\\\", \\\"down\\\"); await app.sendKeyEvent(\\\"d\\\", \\\"down\\\")\",\"description\":\"Reuse the retained application and window\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:1","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:1","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"snapshotId\":\"fixture-snapshot-2\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 1\\\"\",\"windows\":[{\"windowId\":\"7\",\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:2","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-2","elementId":"0"}}}} From 8d67f8732e68b56e1671b824d54a916f8fd0c044 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 14:54:18 +0800 Subject: [PATCH 05/73] Preserve pointer release coordinates and exercise native mixed input --- .../native/Sources/CuaNative/HeldInputs.swift | 9 ++++-- .../CuaNative/WindowPointerInput.swift | 7 +++- .../native/tests/capabilities_e2e.py | 32 +++++++++++++++++-- 3 files changed, 42 insertions(+), 6 deletions(-) diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/HeldInputs.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/HeldInputs.swift index 4c7e0a5585..6d8373bf5c 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/HeldInputs.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/HeldInputs.swift @@ -24,6 +24,7 @@ final class HeldInputs: @unchecked Sendable { let mode: Mode let up: CGEvent let post: (CGEvent) -> Void + let prepareRelease: ((CGEvent) throws -> Void)? } private let lock = NSLock() private var pressed: [Press] = [] @@ -76,7 +77,7 @@ final class HeldInputs: @unchecked Sendable { throw conflict(name, holder: key.owner, caller: owner) } pressed.append(Press(owner: owner, recipient: recipient, mode: .keyboard(code, flag), up: up, - post: { post($0, recipient.pid) })) + post: { post($0, recipient.pid) }, prepareRelease: nil)) down.flags = flags(for: recipient) post(down, recipient.pid) } @@ -100,6 +101,7 @@ final class HeldInputs: @unchecked Sendable { return false } } + try press.prepareRelease?(press.up) pressed.remove(at: index) if case .keyboard = press.mode { press.up.flags = flags(for: press.recipient) } press.post(press.up) @@ -122,12 +124,13 @@ final class HeldInputs: @unchecked Sendable { } func pointerDown(owner: Owner, route: WindowRoute, button: CGMouseButton, system: Bool, - down: CGEvent, up: CGEvent, post: @escaping (CGEvent) -> Void) throws { + down: CGEvent, up: CGEvent, post: @escaping (CGEvent) -> Void, + prepareRelease: ((CGEvent) throws -> Void)? = nil) throws { try lock.withLock { try admit(owner) try checkPointerAvailable(route: route, button: button, system: system) pressed.append(Press(owner: owner, recipient: route.owner, - mode: system ? .systemPointer(button, route.windowID) : .windowPointer(button, route.windowID), up: up, post: post)) + mode: system ? .systemPointer(button, route.windowID) : .windowPointer(button, route.windowID), up: up, post: post, prepareRelease: prepareRelease)) post(down) } } diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/WindowPointerInput.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/WindowPointerInput.swift index 43dcc1d55e..995b18a43f 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/WindowPointerInput.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/WindowPointerInput.swift @@ -65,7 +65,12 @@ final class WindowPointerInput { try checkCancellation() let poster = self.poster try held.pointerDown(owner: owner, route: route, button: selected, system: false, down: pair.down, up: pair.up, - post: { poster.post($0, to: route.owner.pid) }) + post: { poster.post($0, to: route.owner.pid) }, prepareRelease: { event in + guard let screen = CGEvent(source: nil)?.location else { return } + event.location = screen + try poster.stampWindow(event, pid: route.owner.pid, windowID: route.windowID, + point: WindowPoint(x: screen.x - route.bounds.x, y: screen.y - route.bounds.y)) + }) } /// Post balanced mouse presses; holdMs replaces each press-to-release interval and remains cancellable. diff --git a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py index 563f3a3a11..9775a497ed 100644 --- a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py +++ b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py @@ -257,6 +257,29 @@ def check_clicks(helper, window, point, state_file): return state +def check_mixed_input(call, owner, state_file, executable): + def cursor(*position): + return json.loads(subprocess.check_output([executable, "--cursor", *map(str, position)], text=True)) + call("activate", owner) + state = wait_for_state(state_file, lambda s: s["active"] and s["keyWindow"]) + window = {**owner, "windowId": state["windowId"]} + bounds = next(w["bounds"] for w in call("listWindows", owner) if w["windowId"] == window["windowId"]) + original = cursor() + try: + cursor(bounds["x"] + state["pad"][0] + 80, bounds["y"] + state["pad"][1] + 70) + for system in (False, True): + count = len(json.loads(state_file.read_text())["events"]) + call("sendKeyEvent", {**owner, "key": "a", "direction": "down"}) + call("toggleMouse", {**window, "mouseButton": "left", "direction": "down", "useSystemPointer": system}) + call("sendKeyEvent", {**owner, "key": "w", "direction": "down"}) + call("releaseHeldInputs", {}) + state = wait_for_state(state_file, lambda s: len(s["events"]) >= count + 6) + events = [(e["type"], e.get("keyCode")) for e in state["events"][count:]] + assert events == [(10, 0), (1, None), (10, 13), (11, 13), (2, None), (11, 0)], events + finally: + run_cleanup(lambda: call("releaseHeldInputs", {}), lambda: cursor(*original)) + + def check_keyboard(call, owner, state_file, state): count = len(state["events"]) call("pressKey", {**owner, "key": ["w", "d"]}, "INVALID_ARGUMENT") @@ -308,6 +331,7 @@ def main(): only.add_argument("--keyboard-only", action="store_true") only.add_argument("--drag-only", action="store_true") only.add_argument("--toggle-only", action="store_true") + only.add_argument("--mixed-only", action="store_true") args = parser.parse_args() transcript = [] helper = None @@ -321,8 +345,8 @@ def main(): info = {"CFBundleName": "Capabilities Fixture", "CFBundleDisplayName": "Capabilities Fixture", "CFBundleIdentifier": "test.dsh.cua." + uuid.uuid4().hex, "CFBundleExecutable": "CapabilitiesFixture", "CFBundlePackageType": "APPL", - "DSHFixtureStatePath": str(state_file), "DSHFixtureBackground": args.click_only or args.keyboard_only or args.drag_only or args.toggle_only, - "DSHFixtureKeyboard": args.keyboard_only} + "DSHFixtureStatePath": str(state_file), "DSHFixtureBackground": args.click_only or args.keyboard_only or args.drag_only or args.toggle_only or args.mixed_only, + "DSHFixtureKeyboard": args.keyboard_only or args.mixed_only} (application / "Contents/Info.plist").write_bytes(plistlib.dumps(info)) subprocess.run(["swiftc", str(ROOT / "tests/CapabilitiesFixture.swift"), "-o", str(executable)], check=True) try: @@ -339,6 +363,10 @@ def main(): app = call("launchApp", owner) assert app["running"] is True, app pid = wait_for_state(state_file, lambda value: bool(value["windowId"]))["pid"] + if args.mixed_only: + check_mixed_input(call, owner, state_file, executable) + print("PASS: receiver observes mixed keyboard/window and keyboard/system input in reverse release order") + return if args.toggle_only: check_toggle_mouse(helper, owner, state_file, executable) print("PASS: window-directed and HID events for three buttons, held moves, explicit release, cleanup and disconnect") From e8259b96e1317e0d845e4ddcffe8905589a508ab Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 15:00:10 +0800 Subject: [PATCH 06/73] Restrict persistent ownership to explicit downs and add desktop turn checks --- .../tests/turn-inputs.desktop.e2e.ts | 129 ++++++++++++++++++ packages/experimental/cua/src/index.ts | 2 +- scripts/fixtures/python-snapshot-tool.mjs | 7 - snapshots/sdk/text-turn/feedback-producer.mjs | 5 +- .../session/cua-run-code/session.v4.jsonl | 42 +++--- .../cua-run-code/system-prompt.expected.md | 2 +- 6 files changed, 159 insertions(+), 28 deletions(-) create mode 100644 packages/experimental/cua-macos/tests/turn-inputs.desktop.e2e.ts diff --git a/packages/experimental/cua-macos/tests/turn-inputs.desktop.e2e.ts b/packages/experimental/cua-macos/tests/turn-inputs.desktop.e2e.ts new file mode 100644 index 0000000000..b88d454ed0 --- /dev/null +++ b/packages/experimental/cua-macos/tests/turn-inputs.desktop.e2e.ts @@ -0,0 +1,129 @@ +/** Opt-in desktop receiver checks through the real program tools, AgentLoop, and signed helper. */ +import { execFile, spawn } from 'node:child_process' +import { once } from 'node:events' +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { promisify } from 'node:util' +import { Context } from '@deepseek-ai/cordis' +import { mountAgentLoopTestDependencies, mountAgentLoopTestHarness } from '@deepseek-ai/dsh-agent-loop-testkit' +import { brandString } from '@deepseek-ai/dsh-brand' +import ComputerUse from '@deepseek-ai/dsh-computer-use' +import { createUserMessage, LlmAdapter, type GenerateOptions, type StreamChunk, type ToolCallId } from '@deepseek-ai/dsh-llm' +import NodeRuntime from '@deepseek-ai/dsh-ptc-runtime-node' +import Sandbox from '@deepseek-ai/dsh-sandbox-local' +import SandboxPolicy from '@deepseek-ai/dsh-sandbox-policy' +import type { SessionId } from '@deepseek-ai/dsh-session' +import Subprocess from '@deepseek-ai/dsh-subprocess-local' +import UserQuestions from '@deepseek-ai/dsh-user-questions' +import { expect, it } from 'vitest' +import { z } from 'zod' +import * as Provider from '../src/index.ts' + +const run = promisify(execFile) +const helperPath = process.env.DSH_CUA_TEST_HELPER +const State = z.object({ + pid: z.number(), windowId: z.string().nullable(), active: z.boolean(), keyWindow: z.boolean(), + pad: z.tuple([z.number(), z.number(), z.number(), z.number()]), + events: z.array(z.object({ type: z.number(), keyCode: z.number().optional() })), +}) + +// These cases share the real desktop and deliberately run in order. Run this opt-in file alone. +it.skipIf(process.platform !== 'darwin' || helperPath === undefined).each(['completed', 'error', 'thinking-stop', 'tool-stop'] as const)( + 'receives mixed releases after %s through cua_run_code', async (ending) => { + const directory = await mkdtemp(join(tmpdir(), 'dsh-turn-input-desktop-')) + const appDirectory = join(directory, 'Input Receiver.app') + const executable = join(appDirectory, 'Contents/MacOS/InputReceiver') + const stateFile = join(directory, 'state.json') + const ctx = new Context() + let fixture: ReturnType | undefined + let exited: Promise | undefined + let cursor: number[] | undefined + try { + await mkdir(join(appDirectory, 'Contents/MacOS'), { recursive: true }) + await writeFile(join(appDirectory, 'Contents/Info.plist'), ` + + +CFBundleIdentifiertest.dsh.turn-input +CFBundleNameInput Receiver +CFBundleExecutableInputReceiver +CFBundlePackageTypeAPPL +DSHFixtureBackground +DSHFixtureKeyboard +`) + await run('swiftc', [fileURLToPath(new URL('../native/tests/CapabilitiesFixture.swift', import.meta.url)), '-o', executable]) + cursor = z.array(z.number()).parse(JSON.parse((await run(executable, ['--cursor'])).stdout)) + fixture = spawn(executable, [stateFile], { stdio: 'ignore' }) + exited = once(fixture, 'exit') + const observe = async () => State.parse(JSON.parse(await readFile(stateFile, 'utf8'))) + await expect.poll(async () => { + try { return (await observe()).windowId } + catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; throw error } + }).toBeTruthy() + const initial = await observe() + const pad = initial.pad + const programs = [ + `var app = await cua.getApp(${JSON.stringify(String(initial.pid))}); await app.activate(); var win = await app.getWindow(${JSON.stringify(initial.windowId)}); await win.getAccessibilityTree(); var bounds = (await app.getWindows()).find(w => w.windowId === win.windowId).bounds; await win.mouseMove([Math.round(${pad[0] + 80} / bounds.width * 999), Math.round(${pad[1] + 70} / bounds.height * 999)], { relative: true, useSystemPointer: true }); await app.sendKeyEvent('a', 'down')`, + `await win.toggleMouse('left', 'down'); await app.sendKeyEvent('w', 'down'); ${ending === 'tool-stop' ? 'await new Promise(() => {})' : ''}`, + ] + const thinking: PromiseWithResolvers = Promise.withResolvers() + class Model extends LlmAdapter { + private index = 0 + async * stream(options: GenerateOptions): AsyncIterable { + const code = programs[this.index++] + if (code !== undefined) { + yield { type: 'block-start', index: 0, blockType: 'tool-call' } + yield { type: 'block-end', index: 0, block: { type: 'tool-call', id: brandString(`input-${this.index}`), + name: 'cua_run_code', arguments: JSON.stringify({ code, description: 'Exercise the owned desktop input receiver' }) } } + yield { type: 'finish', reason: { kind: 'tool-calls' } } + return + } + if (ending === 'error') throw new Error('Controlled model failure after input') + if (ending === 'thinking-stop') { + thinking.resolve() + await new Promise((resolve) => { options.signal?.addEventListener('abort', () => { resolve() }, { once: true }) }) + } + yield { type: 'finish', reason: { kind: 'stop' } } + } + } + await mountAgentLoopTestDependencies(ctx, { workingDirectory: true }) + await ctx.plugin(Subprocess) + await ctx.plugin(Sandbox) + await ctx.plugin(SandboxPolicy, { mode: 'danger-full-access' }) + await ctx.plugin(NodeRuntime) + await ctx.plugin(ComputerUse) + 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, requireSystemPointerApproval: false }) + await mountAgentLoopTestHarness(ctx) + ctx.llm.registerAdapter(['desktop-fixture'], new Model()) + const handle = await ctx.agents.create({ sessionId: brandString(`desktop-${ending}`), meta: { cwd: directory }, + agentOptions: { provider: 'desktop-fixture', model: 'fixture' } }) + handle.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Exercise owned input' }], source: { kind: 'user' } })) + if (ending === 'thinking-stop') { await thinking.promise; handle.agent.cancel({ kind: 'user' }) } + if (ending === 'tool-stop') { + await expect.poll(async () => (await observe()).events.length).toBe(3) + handle.agent.cancel({ kind: 'user' }) + } + await handle.agent.whenIdle() + await expect.poll(async () => (await observe()).events.map(event => [event.type, event.keyCode ?? null])).toEqual([ + [10, 0], [1, null], [10, 13], [11, 13], [2, null], [11, 0], + ]) + const outcomes = handle.agent.session.snapshotEvents().filter(event => event.type === 'turn/end') + expect(outcomes).toHaveLength(1) + expect(outcomes[0]?.data.reason.kind).toBe(ending === 'completed' ? 'completed' : ending === 'error' ? 'error' : 'aborted') + await handle.dispose() + } finally { + try { await ctx.fiber.dispose() } finally { + if (cursor) await run(executable, ['--cursor', ...cursor.map(String)]) + if (fixture && exited && fixture.exitCode === null && fixture.signalCode === null) { + fixture.kill('SIGTERM') + const deadline = setTimeout(() => { fixture?.kill('SIGKILL') }, 5000) + try { await exited } finally { clearTimeout(deadline) } + } + await rm(directory, { recursive: true, force: true }) + } + } + }, +) diff --git a/packages/experimental/cua/src/index.ts b/packages/experimental/cua/src/index.ts index 7b4e809319..9f00d7a725 100644 --- a/packages/experimental/cua/src/index.ts +++ b/packages/experimental/cua/src/index.ts @@ -289,7 +289,7 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) if (inputTurns && (method === 'sendKeyEvent' || method === 'toggleMouse' || (method === 'mouseMove' && useSystemPointer))) { const turn = inputTurns.scope(agent) if (!turn) throw new ToolContextUnavailableError('Directional CUA input requires an active agent turn') - turn.track(client) + if (method !== 'mouseMove' && params.direction === 'down') turn.track(client) params.taskId = agent.id params.turn = turn.turn } diff --git a/scripts/fixtures/python-snapshot-tool.mjs b/scripts/fixtures/python-snapshot-tool.mjs index 5a02fac27a..dcf8afdf17 100644 --- a/scripts/fixtures/python-snapshot-tool.mjs +++ b/scripts/fixtures/python-snapshot-tool.mjs @@ -1,16 +1,9 @@ /** Deterministic job-backed tool and denial fixture for the packaged SDK snapshot. */ -import { createUserMessage } from '@deepseek-ai/dsh-llm' - export const name = 'python-snapshot-tool' export const inject = ['tools', 'jobs'] /** @param {import('@deepseek-ai/cordis').Context} ctx - Scenario-owned tool registration. */ export function apply(ctx) { - ctx.on('agent/turn-finalizing', async ({ agent }) => { - if (agent.id !== 'advanced-executable') return - await Promise.resolve() - agent.inject(createUserMessage({ content: [{ type: 'text', text: 'Turn resources released.' }], source: { kind: 'user' } })) - }) ctx.on('tools/pre-execute', (exec, next) => { if (exec.name !== 'snapshot_double' || exec.arguments.value !== -1) return next() return { diff --git a/snapshots/sdk/text-turn/feedback-producer.mjs b/snapshots/sdk/text-turn/feedback-producer.mjs index b2e36a8761..34acf76a77 100644 --- a/snapshots/sdk/text-turn/feedback-producer.mjs +++ b/snapshots/sdk/text-turn/feedback-producer.mjs @@ -6,7 +6,8 @@ export const inject = ['commands', 'messageFeedback', 'sessionFeedback'] * @param {import('@deepseek-ai/cordis').Context} ctx - Composed runtime services. */ export function apply(ctx) { - ctx.on('agent/turn-stopping', async ({ agent, signal }) => { + ctx.on('agent/turn-finalizing', async ({ agent }) => { + const signal = AbortSignal.timeout(30_000) if (agent.session.header.parentSession !== undefined) return const messages = agent.session.deriveMessages() const message = messages.findLast(message => message.role === 'assistant') @@ -18,7 +19,7 @@ export function apply(ctx) { const target = { sessionId: agent.id, messageId: message.id } const created = await ctx.messageFeedback.put({ ...target, rating: 'negative', note: 'Explain the result.', category: 'task-result', ifVersion: null }) if (!created.ok) throw new Error(created.error.code) - const edited = await ctx.messageFeedback.put({ ...target, rating: 'positive', note: 'The explanation is clear now.', ifVersion: created.value.version }) + const edited = await ctx.messageFeedback.put({ ...target, rating: 'positive', note: 'Turn resources released.', ifVersion: created.value.version }) if (!edited.ok) throw new Error(edited.error.code) const deleted = await ctx.messageFeedback.delete({ ...target, ifVersion: edited.value.version }) if (!deleted.ok) throw new Error(deleted.error.code) diff --git a/snapshots/session/cua-run-code/session.v4.jsonl b/snapshots/session/cua-run-code/session.v4.jsonl index 1a850c3a7e..93709c6714 100644 --- a/snapshots/session/cua-run-code/session.v4.jsonl +++ b/snapshots/session/cua-run-code/session.v4.jsonl @@ -13,32 +13,40 @@ {"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 cua_run_code to select test.fixture,","messageSeqs":[9],"source":{"kind":"fallback"}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); await app.sendKeyEvent(\\\"w\\\", \\\"down\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"stream":[{"type":"chunk","time":1794291763110,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794291763110,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); await app.sendKeyEvent(\\\"w\\\", \\\"down\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}}},{"type":"chunk","time":1794291763110,"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_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); await app.sendKeyEvent(\\\"w\\\", \\\"down\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"stream":[{"type":"chunk","time":1794984911025,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794984911026,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); await app.sendKeyEvent(\\\"w\\\", \\\"down\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}}},{"type":"chunk","time":1794984911026,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); await app.sendKeyEvent(\\\"w\\\", \\\"down\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemPointer\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemPointer\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\",\"sendKeyEvent\",\"toggleMouse\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first: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_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:3","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:3","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"snapshotId\":\"fixture-snapshot-1\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 0\\\"\",\"windows\":[{\"windowId\":\"7\",\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} -{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:4","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-1","elementId":"0"}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:4","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-1","elementId":"0"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} -{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:5","name":"cua","arguments":{"method":"screenshot","params":{"appHandle":"fixture-app","windowId":"7"}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:5","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_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:3","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"w","direction":"down"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:3","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"w","direction":"down"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:4","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:4","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"snapshotId\":\"fixture-snapshot-1\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 0\\\"\",\"windows\":[{\"windowId\":\"7\",\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:5","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-1","elementId":"0"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:5","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-1","elementId":"0"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:6","name":"cua","arguments":{"method":"screenshot","params":{"appHandle":"fixture-app","windowId":"7"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first: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":1,"message":{"role":"tool","source":{"kind":"tool","callId":"cua_first"},"toolCallId":"cua_first","content":[{"type":"text","text":"{\"visits\":1,\"bindings\":[\"cua\"],\"app\":\"fixture-app\",\"window\":\"7\"}\n"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[15],"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_reuse","name":"cua_run_code","arguments":"{\"code\":\"await app.sendKeyEvent(\\\"w\\\", \\\"up\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) })); await win.toggleMouse(\\\"left\\\", \\\"down\\\"); await app.sendKeyEvent(\\\"d\\\", \\\"down\\\")\",\"description\":\"Reuse the retained application and window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:6}}"},"stream":[{"type":"chunk","time":1794291763317,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794291763317,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_reuse","name":"cua_run_code","arguments":"{\"code\":\"await app.sendKeyEvent(\\\"w\\\", \\\"up\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) })); await win.toggleMouse(\\\"left\\\", \\\"down\\\"); await app.sendKeyEvent(\\\"d\\\", \\\"down\\\")\",\"description\":\"Reuse the retained application and window\"}"}}},{"type":"chunk","time":1794291763317,"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_reuse","name":"cua_run_code","arguments":"{\"code\":\"await app.sendKeyEvent(\\\"w\\\", \\\"up\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) })); await win.toggleMouse(\\\"left\\\", \\\"down\\\"); await app.sendKeyEvent(\\\"d\\\", \\\"down\\\")\",\"description\":\"Reuse the retained application and window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:6}}"},"stream":[{"type":"chunk","time":1794984911395,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794984911395,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_reuse","name":"cua_run_code","arguments":"{\"code\":\"await app.sendKeyEvent(\\\"w\\\", \\\"up\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) })); await win.toggleMouse(\\\"left\\\", \\\"down\\\"); await app.sendKeyEvent(\\\"d\\\", \\\"down\\\")\",\"description\":\"Reuse the retained application and window\"}"}}},{"type":"chunk","time":1794984911395,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"cua_reuse","name":"cua_run_code","arguments":"{\"code\":\"await app.sendKeyEvent(\\\"w\\\", \\\"up\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) })); await win.toggleMouse(\\\"left\\\", \\\"down\\\"); await app.sendKeyEvent(\\\"d\\\", \\\"down\\\")\",\"description\":\"Reuse the retained application and window\"}"}} -{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:1","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:1","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"snapshotId\":\"fixture-snapshot-2\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 1\\\"\",\"windows\":[{\"windowId\":\"7\",\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} -{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:2","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-2","elementId":"0"}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:2","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-2","elementId":"0"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} -{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:3","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:3","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"snapshotId\":\"fixture-snapshot-3\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 2\\\"\",\"windows\":[{\"windowId\":\"7\",\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} -{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"cua_reuse"},"toolCallId":"cua_reuse","content":[{"type":"text","text":"{\"visits\":2,\"app\":\"fixture-app\",\"window\":\"7\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 2\\\"\",\"bindings\":[\"cua\"]}\n"}],"isError":false,"id":"{{message:7}}"}},"sourceEventSeqs":[30],"surfaceOp":"append"} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:1","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"w","direction":"up"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:1","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"w","direction":"up"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:2","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:2","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"snapshotId\":\"fixture-snapshot-2\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 1\\\"\",\"windows\":[{\"windowId\":\"7\",\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:3","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-2","elementId":"0"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:3","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-2","elementId":"0"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:4","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:4","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"snapshotId\":\"fixture-snapshot-3\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 2\\\"\",\"windows\":[{\"windowId\":\"7\",\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:5","name":"cua","arguments":{"method":"toggleMouse","params":{"appHandle":"fixture-app","windowId":"7","mouseButton":"left","direction":"down"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:5","name":"cua","arguments":{"method":"toggleMouse","params":{"appHandle":"fixture-app","windowId":"7","mouseButton":"left","direction":"down"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:6","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"d","direction":"down"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:6","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"d","direction":"down"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} +{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"cua_reuse"},"toolCallId":"cua_reuse","content":[{"type":"text","text":"{\"visits\":2,\"app\":\"fixture-app\",\"window\":\"7\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 2\\\"\",\"bindings\":[\"cua\"]}\n"}],"isError":false,"id":"{{message:7}}"}},"sourceEventSeqs":[32],"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":"text","text":"The retained application and window report Count: 2. The counter persisted across calls, and the program exposes only tools.cua. The screenshot was attached after the first call."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:8}}"},"stream":[{"type":"chunk","time":1794291763343,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1794291763343,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"The retained application and window report Count: 2. The counter persisted across calls, and the program exposes only tools.cua. The screenshot was attached after the first call."}}},{"type":"chunk","time":1794291763343,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"text","text":"The retained application and window report Count: 2. The counter persisted across calls, and the program exposes only tools.cua. The screenshot was attached after the first call."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:8}}"},"stream":[{"type":"chunk","time":1794984911492,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1794984911492,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"The retained application and window report Count: 2. The counter persisted across calls, and the program exposes only tools.cua. The screenshot was attached after the first call."}}},{"type":"chunk","time":1794984911492,"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-run-code/system-prompt.expected.md b/snapshots/session/cua-run-code/system-prompt.expected.md index a194b2db34..8eebb36749 100644 --- a/snapshots/session/cua-run-code/system-prompt.expected.md +++ b/snapshots/session/cua-run-code/system-prompt.expected.md @@ -71,7 +71,7 @@ Use an explicit window for screenshots. ## Simulated mouse Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; platform guidance defines their cleanup scope. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], 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. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. From 2d637490171fe40bbcf879a51b65af8d49288052 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 15:05:28 +0800 Subject: [PATCH 07/73] Identify native test events by their source and update lifecycle reference --- docs/architecture.i18n.yaml | 4 ++-- docs/architecture.md | 2 +- docs/architecture.zh.md | 2 +- .../experimental/cua-macos/native/README.i18n.yaml | 4 ++-- packages/experimental/cua-macos/native/README.md | 2 +- packages/experimental/cua-macos/native/README.zh.md | 2 +- .../cua-macos/native/tests/CapabilitiesFixture.swift | 1 + .../cua-macos/native/tests/capabilities_e2e.py | 5 +++-- .../cua-macos/tests/turn-inputs.desktop.e2e.ts | 12 ++++++++---- 9 files changed, 20 insertions(+), 14 deletions(-) diff --git a/docs/architecture.i18n.yaml b/docs/architecture.i18n.yaml index 8f6550670f..da396a0816 100644 --- a/docs/architecture.i18n.yaml +++ b/docs/architecture.i18n.yaml @@ -24,8 +24,8 @@ en: 0d4481070a0ba352 zh: 026be77a9f3db68e /deepseek-harness-architecture/turn-flow: - en: 676f1cec024509b4 - zh: d47bcaeb1e856aa9 + en: 8a5952fde4a9a805 + zh: e69d970b98a089d0 /deepseek-harness-architecture/session-log: en: b3b63d8fe7cab9fe zh: 3703fcf30b1639d0 diff --git a/docs/architecture.md b/docs/architecture.md index 5a26c381b4..95b09e8a95 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -106,7 +106,7 @@ turn/start turn/end ``` -`turn/*`, `step/*`, `system/message`, `user/message`, `assistant/message`, `assistant/attempt`, and `tool/*` are durable session events; the rest are live extension points across three domains. `agent/assistant-stream` publishes process-local start, transient chunk, and end frames. The loop commits the complete compact stream as one message or log-only attempt before a committed end frame, and the Web Session-follow adapter is the live event's only remote consumer. `agent/pre-step`, `agent/request`, `llm/stream`, and the three `tools/*` events are waterfalls, whose listeners must call `next()` to delegate; `agent/turn-stopping` is serial and has no `next()`. `agent/turn-finalizing` awaits every resource finalizer on completion, error and cancellation before `turn/end` and the next turn; failures are reported after all listeners settle. +`turn/*`, `step/*`, `system/message`, `user/message`, `assistant/message`, `assistant/attempt`, and `tool/*` are durable Session events. Other events are live extension points. `agent/assistant-stream` publishes process-local start, transient chunks, and end; the loop commits the stream before a committed end, and Web Session-follow is its only remote consumer. Waterfall listeners for `agent/pre-step`, `agent/request`, `llm/stream`, and `tools/*` must call `next()`; `agent/turn-stopping` is serial. `agent/turn-finalizing` awaits all resource cleanup before `turn/end`, including error and cancellation; every listener settles before failure is reported. Fork creation stores the caller-supplied history; a sharing backend persists the parent prefix first ([lifecycle](../packages/core/agent-loop/README.md#understand-the-implementation)). Factory setup follows SessionStore entry and `session/created`, preceding `agent/created`; closing events commit before removal. diff --git a/docs/architecture.zh.md b/docs/architecture.zh.md index d9a99cc44b..1c94b4c2ed 100644 --- a/docs/architecture.zh.md +++ b/docs/architecture.zh.md @@ -110,7 +110,7 @@ turn/start turn/end ``` -`turn/*`、`step/*`、`system/message`、`user/message`、`assistant/message`、`assistant/attempt` 和 `tool/*` 是持久会话事件;其余是分属三个事件域的实时扩展点。`agent/assistant-stream` 发布进程本地 start、瞬态 chunk 与 end frame。loop 会在 committed end frame 前把完整紧凑 stream 提交为一个 message 或仅日志 attempt;Web Session-follow adapter 是该 live event 唯一的远程消费方。`agent/pre-step`、`agent/request`、`llm/stream` 和三个 `tools/*` 事件是 waterfall(瀑布式事件),其监听器必须调用 `next()` 才能委托下去;`agent/turn-stopping` 是 serial 事件,没有 `next()`。`agent/turn-finalizing` 在正常完成、错误和取消时等待所有资源清理,再提交 `turn/end` 和开始下一回合;所有监听器结束后统一报告失败。 +`turn/*`、`step/*`、`system/message`、`user/message`、`assistant/message`、`assistant/attempt` 和 `tool/*` 是持久 Session 事件。其他事件是实时扩展点。`agent/assistant-stream` 发布进程本地 start、瞬态分片和 end;loop 在 committed end 之前提交完整 stream,Web Session-follow 是唯一的远程消费方。`agent/pre-step`、`agent/request`、`llm/stream` 和 `tools/*` 的 waterfall 监听器必须调用 `next()`;`agent/turn-stopping` 是 serial 事件。`agent/turn-finalizing` 在 `turn/end` 前等待所有资源清理,覆盖错误和取消路径;所有监听器结束后统一报告失败。 fork 创建存储调用方提供的历史;共享前缀的后端先持久化父前缀([生命周期](../packages/core/agent-loop/README.zh.md#understand-the-implementation))。工厂 setup 在 Session 进入 SessionStore 并完成 `session/created` 之后、`agent/created` 之前运行;收尾事件在移除之前提交。 diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index 0524aac4ce..02b2e58893 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -21,8 +21,8 @@ en: bde8f9131c179da3 zh: bd5886c046505c4c /dsh-cua-native-helper/observation-and-input: - en: 1617d112aab897fe - zh: bb16c199e9559c75 + en: 168a837cd4af479a + zh: e046cda9ebc57d9c /dsh-cua-native-helper/verification: en: 11172b21e8ebf972 zh: dac6787e1e75a88e diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index b50b4bac80..a13e4e334b 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -111,7 +111,7 @@ Capture and pointer delivery read CG bounds before and after an exact-window AX `typeText` and `pressKey` target the selected process's current focused control, not an exact window. `pressKey` presses the listed modifiers followed by one key, then releases all pressed keys in reverse order, including on cancellation. Keyboard events go directly to the target PID and bypass the global HID queue. Key names are platform-defined; keypad names such as `KP_0` and `KP_Enter` preserve their physical key codes. Background pointer actions may change that keyboard focus. Text injection sends Unicode characters individually and does not use the clipboard. LF, CR and CRLF send one Return; tabs send Tab. Applications apply their normal editing behavior, including indentation and focus navigation. Each `typeText` down/up event is followed by the configured text interval; `pressKey` keeps its own press and release timing, and dispatch completion does not confirm that the receiving application consumed every event. Cancellation can interrupt text or a gesture after partial input; it cannot undo received events. Very long text can exceed the host's operation deadline. Validate observed application state before deciding how to continue. -The Host associates directional key events with one `run_code` or `cua_run_code` execution. On down, the helper retains the selected application, recipient PID and process start time, physical key code, and matching up event. A repeated down from the owner posts one key-down with `keyboardEventAutorepeat` set and reuses the existing record. The event is posted to the recipient PID. An AppKit view can receive the initial down and final up while filtering the marked repeat. Repeats, explicit up and cleanup verify the original process identity. A conflicting down or up reports the key and whether another session or another run holds it. On return, error, or user pause, the Host waits for any in-flight native request and asks the helper to release only that execution’s remaining keys. Disconnect cleanup also releases keys owned by the closed connection. +The Host attaches `taskId` and `turn` to directional input. `HeldInputs` records each explicit down with its connection, task, turn, application, original process identity, key or button, release event, and actual input route before dispatch. A repeated ordinary key-down sets `keyboardEventAutorepeat` and retains one record; AppKit may filter that repeat. Explicit up uses the saved recipient and route. PID-directed releases verify process identity; system-button releases still run after window closure or process exit. `releaseHeldInputs` releases a turn's keys and buttons together in reverse dispatch order and rejects later downs for that turn. The Host stops admission and waits for in-flight cancellation before requesting cleanup independently of the cancelled signal. Disconnect cleanup joins native work before releasing that connection's records. Complete key chords, text, clicks and drags keep their operation-local cleanup. The selected helper application needs macOS Accessibility permission for AX state and input, and Screen Recording permission for screenshots. Capability preflight and permission errors do not grant permissions. Capture refuses a window that moves or resizes while the image is being read. Unassociated system panels and accessory-only applications are not selectable. diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index 4ba6760c92..e189f60282 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -111,7 +111,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 `typeText` 和 `pressKey` 面向所选进程当前获得焦点的控件,不指定窗口。`pressKey` 向目标 PID 依次发送修饰键和一个主键的按下事件,再逆序释放。操作中途取消也会逆序释放已按下的键。键盘事件直接发给目标进程,绕过全局 HID 队列。按键名由平台定义;KP_0 和 KP_Enter 等数字键盘名称保留物理键码。后台鼠标操作可能改变键盘焦点。文本逐个 Unicode 字符输入,不使用剪贴板。LF、CR 和 CRLF 发送一次 Return,制表符发送 Tab。应用保留缩进和焦点导航等正常编辑行为。`typeText` 的每次按下和抬起后等待配置的文本事件间隔;`pressKey` 使用自己的按下与释放节奏,分派完成不证明应用已消费全部事件。取消可能中断部分文本或手势,无法撤销已接收事件。很长的文本可能超过 Host 操作期限。继续输入前应核实应用状态。 -宿主为每次 `run_code` 或 `cua_run_code` 的 `sendKeyEvent` 附上执行标识。按下时,helper 保存已选应用、接收进程的 PID 与启动时间、物理键码及对应的松开事件。持有方再次按下普通键时,helper 复用原记录,向接收进程发送一次带 `keyboardEventAutorepeat` 标志的按下事件。AppKit 视图可能只收到首次按下和最终松开,过滤中间的重复事件。重复、显式松键和执行结束时都会核对原进程身份。其他执行尝试按下或松开同一个键时,错误会指出键名,并区分其他会话和同一连接内的其他执行。正常返回、异常退出或用户暂停时,宿主等待在途原生请求结束,再通知 helper 释放该执行持有的其余按键。连接断开时,helper 也会清理该连接持有的按键。 +宿主为定向输入附上 `taskId` 和 `turn`。`HeldInputs` 在显式按下派发前记录连接、任务、回合、应用、原进程身份、键码或按钮、释放事件和实际输入方式。普通键的重复按下设置 `keyboardEventAutorepeat`,仍只保留一条记录;AppKit 可能过滤该重复事件。显式松开使用保存的接收方和输入方式。定向释放检查进程身份;系统按钮在窗口关闭或进程退出后仍会释放。`releaseHeldInputs` 按实际派发顺序的反序统一释放本回合的键盘键与鼠标按钮,并拒绝该回合后续的按下。宿主先禁止新输入并等待在途取消,再独立于已取消的 signal 请求清理。断连清理先等待原生操作结束,再释放本连接的记录。完整快捷键、文本输入、点击和拖动仍在本次操作内自行清理。 所选 helper 应用需要 macOS 辅助功能权限以读取 AX 和输入,需要屏幕录制权限以截图。能力预检和权限错误不授予权限。截图会拒绝在读取图片期间移动或缩放的窗口。无法确认归属的系统面板及仅后台辅助类型的应用不可选择。 diff --git a/packages/experimental/cua-macos/native/tests/CapabilitiesFixture.swift b/packages/experimental/cua-macos/native/tests/CapabilitiesFixture.swift index bd100c33b8..317552cb74 100644 --- a/packages/experimental/cua-macos/native/tests/CapabilitiesFixture.swift +++ b/packages/experimental/cua-macos/native/tests/CapabilitiesFixture.swift @@ -84,6 +84,7 @@ final class CapabilitiesFixture: NSObject, NSApplicationDelegate, NSWindowDelega pad.received = { [weak self] event in guard let self else { return } var value: [String: Any] = ["type": event.type.rawValue, "timestamp": event.timestamp, "flags": event.modifierFlags.rawValue, + "sourcePid": event.cgEvent?.getIntegerValueField(.eventSourceUnixProcessID) ?? 0, "shift": event.modifierFlags.contains(.shift), "command": event.modifierFlags.contains(.command)] if [.keyDown, .keyUp].contains(event.type) { value["keyCode"] = event.keyCode diff --git a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py index 9775a497ed..5ea6ac011b 100644 --- a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py +++ b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py @@ -260,6 +260,7 @@ def check_clicks(helper, window, point, state_file): def check_mixed_input(call, owner, state_file, executable): def cursor(*position): return json.loads(subprocess.check_output([executable, "--cursor", *map(str, position)], text=True)) + source_pid = call("permissionStatus", {})["helper"]["pid"] call("activate", owner) state = wait_for_state(state_file, lambda s: s["active"] and s["keyWindow"]) window = {**owner, "windowId": state["windowId"]} @@ -273,8 +274,8 @@ def check_mixed_input(call, owner, state_file, executable): call("toggleMouse", {**window, "mouseButton": "left", "direction": "down", "useSystemPointer": system}) call("sendKeyEvent", {**owner, "key": "w", "direction": "down"}) call("releaseHeldInputs", {}) - state = wait_for_state(state_file, lambda s: len(s["events"]) >= count + 6) - events = [(e["type"], e.get("keyCode")) for e in state["events"][count:]] + state = wait_for_state(state_file, lambda s: sum(e.get("sourcePid") == source_pid for e in s["events"][count:]) >= 6) + events = [(e["type"], e.get("keyCode")) for e in state["events"][count:] if e.get("sourcePid") == source_pid] assert events == [(10, 0), (1, None), (10, 13), (11, 13), (2, None), (11, 0)], events finally: run_cleanup(lambda: call("releaseHeldInputs", {}), lambda: cursor(*original)) diff --git a/packages/experimental/cua-macos/tests/turn-inputs.desktop.e2e.ts b/packages/experimental/cua-macos/tests/turn-inputs.desktop.e2e.ts index b88d454ed0..e460d543ac 100644 --- a/packages/experimental/cua-macos/tests/turn-inputs.desktop.e2e.ts +++ b/packages/experimental/cua-macos/tests/turn-inputs.desktop.e2e.ts @@ -26,7 +26,7 @@ const helperPath = process.env.DSH_CUA_TEST_HELPER const State = z.object({ pid: z.number(), windowId: z.string().nullable(), active: z.boolean(), keyWindow: z.boolean(), pad: z.tuple([z.number(), z.number(), z.number(), z.number()]), - events: z.array(z.object({ type: z.number(), keyCode: z.number().optional() })), + events: z.array(z.object({ type: z.number(), keyCode: z.number().optional(), sourcePid: z.number() })), }) // These cases share the real desktop and deliberately run in order. Run this opt-in file alone. @@ -60,7 +60,7 @@ it.skipIf(process.platform !== 'darwin' || helperPath === undefined).each(['comp await expect.poll(async () => { try { return (await observe()).windowId } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; throw error } - }).toBeTruthy() + }, { timeout: 30_000 }).toBeTruthy() const initial = await observe() const pad = initial.pad const programs = [ @@ -96,6 +96,10 @@ it.skipIf(process.platform !== 'darwin' || helperPath === undefined).each(['comp 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, requireSystemPointerApproval: false }) + const permissions = await ctx.cuaAccess.systemStatus() + if (permissions.platform !== 'darwin') throw new Error('Expected macOS permission metadata') + const sourcePid = permissions.helper.pid + const received = async () => (await observe()).events.filter(event => event.sourcePid === sourcePid) await mountAgentLoopTestHarness(ctx) ctx.llm.registerAdapter(['desktop-fixture'], new Model()) const handle = await ctx.agents.create({ sessionId: brandString(`desktop-${ending}`), meta: { cwd: directory }, @@ -103,11 +107,11 @@ it.skipIf(process.platform !== 'darwin' || helperPath === undefined).each(['comp handle.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Exercise owned input' }], source: { kind: 'user' } })) if (ending === 'thinking-stop') { await thinking.promise; handle.agent.cancel({ kind: 'user' }) } if (ending === 'tool-stop') { - await expect.poll(async () => (await observe()).events.length).toBe(3) + await expect.poll(async () => (await received()).length, { timeout: 30_000 }).toBe(3) handle.agent.cancel({ kind: 'user' }) } await handle.agent.whenIdle() - await expect.poll(async () => (await observe()).events.map(event => [event.type, event.keyCode ?? null])).toEqual([ + await expect.poll(async () => (await received()).map(event => [event.type, event.keyCode ?? null]), { timeout: 30_000 }).toEqual([ [10, 0], [1, null], [10, 13], [11, 13], [2, null], [11, 0], ]) const outcomes = handle.agent.session.snapshotEvents().filter(event => event.type === 'turn/end') From 4aaa4f1ec198f4d58da2d5e3277af341ca9c2ab9 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 15:10:56 +0800 Subject: [PATCH 08/73] Keep complete MCP input available while requiring turns for holds --- .../cua-turn-inputs/guide.i18n.yaml | 4 ++-- .../v0.2.2-rc.4/cua-turn-inputs/guide.md | 2 ++ .../v0.2.2-rc.4/cua-turn-inputs/guide.zh.md | 2 ++ .../native/Sources/CuaNative/HeldInputs.swift | 4 ++-- .../CuaNative/RequestCoordinator.swift | 4 +++- .../CuaNative/SystemPointerInput.swift | 2 +- .../tests/provider-lifecycle.spec.ts | 10 ++++++++++ .../experimental/cua-mcp/README.i18n.yaml | 4 ++-- packages/experimental/cua-mcp/README.md | 1 + packages/experimental/cua-mcp/README.zh.md | 1 + packages/experimental/cua-mcp/src/server.ts | 3 ++- .../cua-mcp/tests/composition.spec.ts | 19 +++++++++++++++++-- packages/experimental/cua/src/index.ts | 10 ++++++---- 13 files changed, 51 insertions(+), 15 deletions(-) diff --git a/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.i18n.yaml index eacc286081..290b73d6bb 100644 --- a/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.i18n.yaml @@ -12,5 +12,5 @@ en: fdf88fdc0141c9d8 zh: a4af8cab104d38d1 /macos-cua-input-holds-last-for-one-turn/migration: - en: 5e45c629483d2fd5 - zh: 3e8be5a85f2c54ef + en: 30b6c3ffc7326ca0 + zh: a66655caa4c5e509 diff --git a/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.md b/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.md index 4a61ebeab8..097b6a2d04 100644 --- a/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.md @@ -12,6 +12,8 @@ macOS `sendKeyEvent('down')` holds a key across `run_code` and `cua_run_code` ca ## Migration +MCP does not supply DSH turn boundaries. Explicit macOS holds through `sendKeyEvent` or `toggleMouse` are unavailable there; replace them with complete `pressKey`, `click`, or `drag` actions. System pointer movement remains available. + 1. If a program requires release before it returns, send an explicit `up` in its `finally` block. Otherwise a later program in the same turn can release the held input. 2. Upgrade the macOS package and helper together. A custom `helperPath` must point to a rebuilt helper implementing the new private turn input protocol. 3. Verify a down in one program remains held until an up in a later program, or until the turn ends. If cleanup cannot be confirmed, CUA disables input for that task. Check the desktop before starting a new task. diff --git a/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.zh.md index 9221e10c49..3753a2d02c 100644 --- a/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.zh.md @@ -12,6 +12,8 @@ macOS 的 `sendKeyEvent('down')` 可在同一回合内跨 `run_code` 和 `cua_ru ## 迁移 +MCP 不提供 DSH 回合边界。macOS 的 `sendKeyEvent` 和 `toggleMouse` 显式持有在该入口不可用,请改用完整的 `pressKey`、`click` 或 `drag` 动作。系统鼠标移动仍可使用。 + 1. 如果程序需要在返回前释放输入,在 `finally` 中显式发送 `up`。否则可由同一回合中的后续程序释放。 2. 同步升级 macOS 包和 helper。自定义 `helperPath` 必须指向已重建、支持新回合输入私有协议的 helper。 3. 验证前一次程序的 `down` 能保持到后一次程序发送 `up`,或回合结束。清理无法确认时,CUA 会禁用该任务的输入。检查桌面状态后再创建新任务。 diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/HeldInputs.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/HeldInputs.swift index 6d8373bf5c..ab4fefc77b 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/HeldInputs.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/HeldInputs.swift @@ -161,9 +161,9 @@ final class HeldInputs: @unchecked Sendable { } /// Create and post movement under the same lock as ownership and the saved release point. - func moveSystem(owner: Owner, route: WindowRoute, screen: CGPoint, checkCancellation: () throws -> Void) throws { + func moveSystem(owner: Owner?, route: WindowRoute, screen: CGPoint, checkCancellation: () throws -> Void) throws { try lock.withLock { - try admit(owner) + if let owner { try admit(owner) } let press = pressed.first { if case .systemPointer = $0.mode { return true }; return false } let event: CGEvent if let press { diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift index f606fb9740..2effd119e7 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift @@ -223,7 +223,9 @@ import Darwin case .foreground(let plan): result = try await performForeground(plan, requestID: request.id) case .mouseMove(let route, let point): let latch = cancellation - try scheduler.systemPointer.move(owner: .init(connection: connectionID, scope: params.inputScope(), app: params.string("appHandle")), in: route, at: point, checkCancellation: { try latch.check() }) + let owner: HeldInputs.Owner? = try params.contains("taskId") || params.contains("turn") + ? .init(connection: connectionID, scope: params.inputScope(), app: params.string("appHandle")) : nil + try scheduler.systemPointer.move(owner: owner, in: route, at: point, checkCancellation: { try latch.check() }) result = AXWorker.mouseMoveResult(route: "system-pointer", pointerMoved: true) case .systemButtonDown(let route, let button): try scheduler.systemPointer.down(owner: .init(connection: connectionID, scope: params.inputScope(), app: params.string("appHandle")), in: route, button: button, diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/SystemPointerInput.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/SystemPointerInput.swift index fac58df0b4..2f9be350ed 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/SystemPointerInput.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/SystemPointerInput.swift @@ -38,7 +38,7 @@ import Foundation try held.pointerDown(owner: owner, route: route, button: button, system: true, down: down, up: up, post: Self.post) } - func move(owner: HeldInputs.Owner, in route: WindowRoute, at point: WindowPoint, checkCancellation: () throws -> Void) throws { + func move(owner: HeldInputs.Owner?, in route: WindowRoute, at point: WindowPoint, checkCancellation: () throws -> Void) throws { try WindowPointerInput.validate(point, in: route) try WindowPointerInput.validateWindow(route) let screen = WindowPointerInput.screenPoint(point, in: route) diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index 34ed3cd629..1957f30f35 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -1329,3 +1329,13 @@ it.each([true, false])('uses the declared systemPointer capability for a non-mac expect(native.request).toHaveBeenLastCalledWith('mouseMove', systemPointer ? { ...hoverTarget, useSystemPointer: false } : hoverTarget, expect.any(AbortSignal), expect.any(String)) }) + +it('keeps complete system moves available outside a turn without registering a persistent hold', async () => { + const f = await setup(undefined, false, { requireSystemPointerApproval: false }) + await selectApplication(f) + native.request.mockClear() + expect((await f.execute('mouseMove', physicalHover)).isError).toBe(false) + expect(native.request).toHaveBeenCalledExactlyOnceWith('mouseMove', physicalHover, expect.any(AbortSignal), expect.any(String)) + await f.handle.dispose() + expect(native.cleanup).not.toHaveBeenCalled() +}) diff --git a/packages/experimental/cua-mcp/README.i18n.yaml b/packages/experimental/cua-mcp/README.i18n.yaml index d6b4890821..59b87e135d 100644 --- a/packages/experimental/cua-mcp/README.i18n.yaml +++ b/packages/experimental/cua-mcp/README.i18n.yaml @@ -51,8 +51,8 @@ en: 0b0c63281111993b zh: 45716a56b5a5ad12 /deepseek-ai-dsh-cua-mcp/known-limitations-and-deferred-work: - en: 7d592e6b49063ae8 - zh: 6f58f0e3a00dd2a8 + en: 743cd8c6a8c89453 + zh: 0d85356f5a9537a0 /deepseek-ai-dsh-cua-mcp/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 8ec3e73528ddb1a6 diff --git a/packages/experimental/cua-mcp/README.md b/packages/experimental/cua-mcp/README.md index a4c7b4e6cb..d6ea48810f 100644 --- a/packages/experimental/cua-mcp/README.md +++ b/packages/experimental/cua-mcp/README.md @@ -167,6 +167,7 @@ The tool catalog and instructions are stable for one installation. The reference +- macOS explicit `sendKeyEvent` and `toggleMouse` holds require an active DSH turn. MCP programs run as maintenance activities, so these operations are unavailable through MCP. Use complete `pressKey`, `typeText`, `click`, or `drag` actions; system pointer movement remains available. The server cannot infer the client's turn boundaries. - macOS and native Windows Hosts have a provider. Other Hosts, WSL included, list `cua_get_api_reference` and `cua_reset`, which both name the missing provider; a `cua_run_code` call fails as `unknown tool`. - On Windows the [provider's limits](../cua-windows/README.md#known-limitations-and-deferred-work) apply through MCP: it does not launch applications, grants no `Always allow`, and an npm installation needs `helperPath`. - Elicitation uses the 2025 MCP request model; a client that negotiates the 2026-07-28 revision receives an error for consent requests and should use `DSH_CUA_CONSENT=allow`. diff --git a/packages/experimental/cua-mcp/README.zh.md b/packages/experimental/cua-mcp/README.zh.md index 808785398f..98e7bb5a2d 100644 --- a/packages/experimental/cua-mcp/README.zh.md +++ b/packages/experimental/cua-mcp/README.zh.md @@ -167,6 +167,7 @@ patch 还以 `screenshotTarget: { longEdge: 2048, maxBytes: 2097152 }` 挂载该 +- macOS 的 `sendKeyEvent` 和 `toggleMouse` 显式持有要求活动的 DSH 回合。MCP 程序以维护活动执行,因此这些操作在 MCP 中不可用。请使用完整的 `pressKey`、`typeText`、`click` 或 `drag` 动作;系统鼠标移动仍可使用。服务器无法推断客户端的回合边界。 - macOS 与原生 Windows Host 有提供方。其他 Host(包括 WSL)列出 `cua_get_api_reference` 与 `cua_reset`,二者都指出缺少提供方;调用 `cua_run_code` 以 `unknown tool` 失败。 - 在 Windows 上,[提供方的限制](../cua-windows/README.zh.md#known-limitations-and-deferred-work)经 MCP 同样适用:它不启动应用,不提供 `Always allow` 授权,npm 安装需要配置 `helperPath`。 - Elicitation 使用 2025 版 MCP 请求模型;协商到 2026-07-28 修订版的客户端在授权请求时收到错误,应改用 `DSH_CUA_CONSENT=allow`。 diff --git a/packages/experimental/cua-mcp/src/server.ts b/packages/experimental/cua-mcp/src/server.ts index 6d173e7478..3c7f09b4c9 100644 --- a/packages/experimental/cua-mcp/src/server.ts +++ b/packages/experimental/cua-mcp/src/server.ts @@ -95,7 +95,8 @@ const INSTRUCTIONS = 'DeepSeek Harness Computer Use: observe and operate desktop + 'Start every conversation by calling cua_get_api_reference: it returns the complete cua API reference, and programs ' + 'written without it guess the API wrong. Then call cua_run_code with a TypeScript program that uses the global cua ' + 'object; program state persists across calls on this connection. A call may ask the user for application or pointer ' - + 'consent before it proceeds. Call cua_reset to discard program state.' + + 'consent before it proceeds. Call cua_reset to discard program state. ' + + 'On macOS, MCP programs cannot hold keys or mouse buttons with explicit down events. Use pressKey, click, or drag.' const NO_PROVIDER = 'Computer Use is not available on this Host: the cua-mcp profile has no active CUA provider. ' + 'Providers exist for macOS and native Windows; on those Hosts the server\'s stderr names why the provider did not start.' diff --git a/packages/experimental/cua-mcp/tests/composition.spec.ts b/packages/experimental/cua-mcp/tests/composition.spec.ts index 5599fe4017..9aebf1dc0d 100644 --- a/packages/experimental/cua-mcp/tests/composition.spec.ts +++ b/packages/experimental/cua-mcp/tests/composition.spec.ts @@ -108,12 +108,12 @@ async function setup(options: SetupOptions = {}) { cua: { inject: ['computerUse', 'subprocess', 'tools', 'systemPrompt', 'agents'], Config: CuaConfig, apply(owner: Context, config: CuaConfig) { - installCua(owner, config, { helperPath: process.execPath, + installCua(owner, config, { helperPath: process.execPath, turnInputLifecycle: true, createChannel: options.cancellationAcknowledgementMs === undefined ? native.createChannel : delayCancellation(native.createChannel, options.cancellationAcknowledgementMs, () => { native.events.push('cancellation-acknowledged') }), getGuidance: () => 'Fixture CUA guidance: select test.fixture and operate window 7.', - capabilities: { platform: 'macos', methods: ['getCapabilities', 'getApp', 'getState', 'click', 'screenshot'], + capabilities: { platform: 'macos', methods: ['getCapabilities', 'getApp', 'getState', 'click', 'screenshot', 'sendKeyEvent', 'toggleMouse'], appLevelAccessibility: true, keyboard: ['app'], browser: false, coordinateSpace: 'screenshot-pixels' }, permissionParameters: (_method, permission, locale) => ({ permission, locale }), }) @@ -182,6 +182,21 @@ async function setup(options: SetupOptions = {}) { } describe('Computer Use MCP composition', () => { + it('refuses persistent downs outside a turn and still completes clicks through MCP', async () => { + const { client, native, run } = await setup() + expect(client.getInstructions()).toContain('MCP programs cannot hold keys or mouse buttons') + const selected = await run('var app = await cua.getApp("test.fixture"); var win = await app.getWindow("7"); await win.getAccessibilityTree()') + expect(selected.isError).not.toBe(true) + for (const code of ['await app.sendKeyEvent("w", "down")', 'await win.toggleMouse("left", "down")']) { + const result = await run(code) + expect(result.isError).toBe(true) + expect(texts(result).join('\n')).toContain('active agent turn') + } + expect(native.calls.some(call => call.method === 'sendKeyEvent' || call.method === 'toggleMouse')).toBe(false) + expect((await run('await win.click("0")')).isError).not.toBe(true) + expect(native.state.count).toBe(1) + }) + it('serves three tools, returns the API reference on request, and retains program state in the workspace', async () => { const { ctx, native, client, run, adapter, directory } = await setup() expect(client.getInstructions()).toContain('Start every conversation by calling cua_get_api_reference') diff --git a/packages/experimental/cua/src/index.ts b/packages/experimental/cua/src/index.ts index 9f00d7a725..b8ac5bc851 100644 --- a/packages/experimental/cua/src/index.ts +++ b/packages/experimental/cua/src/index.ts @@ -288,10 +288,12 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) else if (useSystemPointer !== undefined) params.useSystemPointer = useSystemPointer if (inputTurns && (method === 'sendKeyEvent' || method === 'toggleMouse' || (method === 'mouseMove' && useSystemPointer))) { const turn = inputTurns.scope(agent) - if (!turn) throw new ToolContextUnavailableError('Directional CUA input requires an active agent turn') - if (method !== 'mouseMove' && params.direction === 'down') turn.track(client) - params.taskId = agent.id - params.turn = turn.turn + if (!turn && method !== 'mouseMove') throw new ToolContextUnavailableError('Directional CUA input requires an active agent turn; external MCP programs can use pressKey, click, and drag') + if (turn) { + if (method !== 'mouseMove' && params.direction === 'down') turn.track(client) + params.taskId = agent.id + params.turn = turn.turn + } } const nativeParams = method === 'findApps' ? { ...params, maxAppMatches: config.maxAppMatches } From 14baaa29025731249328cd100d82204f94c85d44 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 15:15:40 +0800 Subject: [PATCH 09/73] Preserve turn failures and discover awaited finalization in generated docs --- docs/config-catalog.md | 2 +- docs/config-catalog.zh.md | 2 +- docs/event-producer-consumer.md | 9 +++++---- docs/event-producer-consumer.zh.md | 9 +++++---- packages/core/agent-loop/src/agent.ts | 9 +++++++-- .../agent-loop/tests/contract-regressions.spec.ts | 15 +++++++++++++++ scripts/gen-doc-graphs.spec.ts | 11 ++++++++++- scripts/gen-doc-graphs.ts | 6 ++++-- 8 files changed, 48 insertions(+), 15 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 1ffca1c6ab..d55b138847 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -940,7 +940,7 @@ export interface Config { - `inject`: `computerUse` · `tools` · `systemPrompt` · `subprocess` · `agents` - `refs`: [`CuaConfig`](../packages/experimental/cua/src/index.ts) -- `source`: [`packages/experimental/cua-macos/src/index.ts:34`](../packages/experimental/cua-macos/src/index.ts) +- `source`: [`packages/experimental/cua-macos/src/index.ts:33`](../packages/experimental/cua-macos/src/index.ts) ```ts config-catalog /** Native preparation, source-build signing, operation bounds, and profile-local application grants. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index f898bb3cd3..9f1b6eb8c4 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -942,7 +942,7 @@ export interface Config { - `inject`: `computerUse` · `tools` · `systemPrompt` · `subprocess` · `agents` - `refs`: [`CuaConfig`](../packages/experimental/cua/src/index.ts) -- `source`: [`packages/experimental/cua-macos/src/index.ts:34`](../packages/experimental/cua-macos/src/index.ts) +- `source`: [`packages/experimental/cua-macos/src/index.ts:33`](../packages/experimental/cua-macos/src/index.ts) ```ts config-catalog /** Native preparation, source-build signing, operation bounds, and profile-local application grants. */ diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index cdbd5b0e82..636a30ff6b 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -15,13 +15,14 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:400`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | | `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:291`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`timeline`](../packages/experimental/timeline) | | `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:300`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), [`mcp-client`](../packages/mcp/mcp-client), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`timeline`](../packages/experimental/timeline), [`tool-office`](../packages/document/tool-office), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | -| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:430`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | +| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:441`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | | `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:329`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | | `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:337`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | | `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:318`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | -| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:351`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | +| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:351`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`cua`](../packages/experimental/cua), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | | `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:390`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | | `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:310`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`timeline`](../packages/experimental/timeline) | +| `agent/turn-finalizing` | `parallel` | [`packages/core/agent/src/runtime-types.ts:429`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`settled`) | [`cua`](../packages/experimental/cua) | | `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:418`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:697`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:677`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | @@ -74,7 +75,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `session-telemetry/record` | `waterfall` | [`packages/session/session-telemetry/src/index.ts:44`](../packages/session/session-telemetry/src/index.ts) | [`session-telemetry`](../packages/session/session-telemetry) (`waterfall`) | - | | `session/created` | `emit` | [`packages/core/session/src/index.ts:56`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | `server`, `session-controller`, [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry) | | `session/disposed` | `emit` | [`packages/core/session/src/index.ts:65`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `file-upload`, `forge-session`, [`office-kit`](../packages/document/office-kit), `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-title`](../packages/session/session-title), `ui-trajectory`, [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `session/event` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`timeline`](../packages/experimental/timeline), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-session-status`, `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `session/event` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`timeline`](../packages/experimental/timeline), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-session-status`, `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `session/flush` | `parallel` | [`packages/core/session/src/index.ts:87`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`session-telemetry`](../packages/session/session-telemetry) | | `settings/document-updated` | `emit` | [`packages/settings/settings/src/types.ts:75`](../packages/settings/settings/src/types.ts) | [`settings`](../packages/settings/settings) (`emit`) | `remotes` | | `skills/change` | `emit` | [`packages/skill/skill/src/index.ts:299`](../packages/skill/skill/src/index.ts) | [`skill`](../packages/skill/skill) (`events.dispatch`) | - | @@ -86,7 +87,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `system-prompt/change` | `emit` | [`packages/core/system-prompt/src/index.ts:37`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`emit`) | - | | `timeline/priority` | `emit` | [`packages/experimental/timeline/src/storage.ts:56`](../packages/experimental/timeline/src/storage.ts) | [`timeline`](../packages/experimental/timeline) (`emit`) | [`timeline`](../packages/experimental/timeline) | | `tools/change` | `emit` | [`packages/core/tools/src/events.ts:56`](../packages/core/tools/src/events.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`), [`tools`](../packages/core/tools) (`emit`) | `browser-use-runtime`, [`timeline`](../packages/experimental/timeline) | -| `tools/execute` | `waterfall` | [`packages/core/tools/src/events.ts:29`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `browser-use-runtime`, `browser-use-stagehand-native`, `claude-code-mods`, `computer-use-cua-driver-native`, [`cua-macos`](../packages/experimental/cua-macos), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `timeout-policy` | +| `tools/execute` | `waterfall` | [`packages/core/tools/src/events.ts:29`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `browser-use-runtime`, `browser-use-stagehand-native`, `claude-code-mods`, `computer-use-cua-driver-native`, [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `timeout-policy` | | `tools/post-execute` | `waterfall` | [`packages/core/tools/src/events.ts:41`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `claude-code-mods`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`spill-policy`](../packages/spill/spill-policy), [`tool-fs-search`](../packages/fs/tool-fs-search) | | `tools/pre-execute` | `waterfall` | [`packages/core/tools/src/events.ts:18`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `auto-review`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`tool-jobs`](../packages/jobs/tool-jobs), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `tools/ptc-dispatch-log` | `waterfall` | [`packages/core/tool-executor-ptc/src/runtime-types.ts:46`](../packages/core/tool-executor-ptc/src/runtime-types.ts) | [`tool-executor-ptc`](../packages/core/tool-executor-ptc) (`waterfall`) | [`spill-policy`](../packages/spill/spill-policy) | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index d11a029e90..b9fa0b789d 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -17,13 +17,14 @@ | `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:400`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | | `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:291`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`timeline`](../packages/experimental/timeline) | | `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:300`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), [`mcp-client`](../packages/mcp/mcp-client), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`timeline`](../packages/experimental/timeline), [`tool-office`](../packages/document/tool-office), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | -| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:430`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | +| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:441`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | | `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:329`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | | `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:337`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | | `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:318`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | -| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:351`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | +| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:351`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`cua`](../packages/experimental/cua), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | | `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:390`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | | `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:310`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`timeline`](../packages/experimental/timeline) | +| `agent/turn-finalizing` | `parallel` | [`packages/core/agent/src/runtime-types.ts:429`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`settled`) | [`cua`](../packages/experimental/cua) | | `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:418`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:697`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:677`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | @@ -76,7 +77,7 @@ | `session-telemetry/record` | `waterfall` | [`packages/session/session-telemetry/src/index.ts:44`](../packages/session/session-telemetry/src/index.ts) | [`session-telemetry`](../packages/session/session-telemetry) (`waterfall`) | - | | `session/created` | `emit` | [`packages/core/session/src/index.ts:56`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | `server`, `session-controller`, [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry) | | `session/disposed` | `emit` | [`packages/core/session/src/index.ts:65`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `file-upload`, `forge-session`, [`office-kit`](../packages/document/office-kit), `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-title`](../packages/session/session-title), `ui-trajectory`, [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `session/event` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`timeline`](../packages/experimental/timeline), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-session-status`, `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `session/event` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`timeline`](../packages/experimental/timeline), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-session-status`, `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `session/flush` | `parallel` | [`packages/core/session/src/index.ts:87`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`session-telemetry`](../packages/session/session-telemetry) | | `settings/document-updated` | `emit` | [`packages/settings/settings/src/types.ts:75`](../packages/settings/settings/src/types.ts) | [`settings`](../packages/settings/settings) (`emit`) | `remotes` | | `skills/change` | `emit` | [`packages/skill/skill/src/index.ts:299`](../packages/skill/skill/src/index.ts) | [`skill`](../packages/skill/skill) (`events.dispatch`) | - | @@ -88,7 +89,7 @@ | `system-prompt/change` | `emit` | [`packages/core/system-prompt/src/index.ts:37`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`emit`) | - | | `timeline/priority` | `emit` | [`packages/experimental/timeline/src/storage.ts:56`](../packages/experimental/timeline/src/storage.ts) | [`timeline`](../packages/experimental/timeline) (`emit`) | [`timeline`](../packages/experimental/timeline) | | `tools/change` | `emit` | [`packages/core/tools/src/events.ts:56`](../packages/core/tools/src/events.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`), [`tools`](../packages/core/tools) (`emit`) | `browser-use-runtime`, [`timeline`](../packages/experimental/timeline) | -| `tools/execute` | `waterfall` | [`packages/core/tools/src/events.ts:29`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `browser-use-runtime`, `browser-use-stagehand-native`, `claude-code-mods`, `computer-use-cua-driver-native`, [`cua-macos`](../packages/experimental/cua-macos), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `timeout-policy` | +| `tools/execute` | `waterfall` | [`packages/core/tools/src/events.ts:29`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `browser-use-runtime`, `browser-use-stagehand-native`, `claude-code-mods`, `computer-use-cua-driver-native`, [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `timeout-policy` | | `tools/post-execute` | `waterfall` | [`packages/core/tools/src/events.ts:41`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `claude-code-mods`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`spill-policy`](../packages/spill/spill-policy), [`tool-fs-search`](../packages/fs/tool-fs-search) | | `tools/pre-execute` | `waterfall` | [`packages/core/tools/src/events.ts:18`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `auto-review`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`tool-jobs`](../packages/jobs/tool-jobs), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `tools/ptc-dispatch-log` | `waterfall` | [`packages/core/tool-executor-ptc/src/runtime-types.ts:46`](../packages/core/tool-executor-ptc/src/runtime-types.ts) | [`tool-executor-ptc`](../packages/core/tool-executor-ptc) (`waterfall`) | [`spill-policy`](../packages/spill/spill-policy) | diff --git a/packages/core/agent-loop/src/agent.ts b/packages/core/agent-loop/src/agent.ts index c3a3d6122f..1636ebb567 100644 --- a/packages/core/agent-loop/src/agent.ts +++ b/packages/core/agent-loop/src/agent.ts @@ -345,6 +345,7 @@ export class ReactLoopAgent implements Agent { } phase.turn = turn let turnEnds: TurnEndReason | null = null + let turnFailure: { error: unknown } | undefined let target: InboxTarget = 'next-turn' try { while (true) { @@ -406,6 +407,7 @@ export class ReactLoopAgent implements Agent { target = 'next-step' } } catch (error: unknown) { + turnFailure = { error } // A cause is present exactly while the signal is aborted. const cause = abortedCancelCause(signal) if (cause !== undefined) { @@ -427,8 +429,11 @@ export class ReactLoopAgent implements Agent { try { await this.dispatch.settled('agent/turn-finalizing', { turn }) const cause = abortedCancelCause(signal) - if (cause !== undefined) turnEnds = { kind: 'aborted', reason: cause } - } catch (error: unknown) { + if (cause !== undefined && turnEnds?.kind !== 'error') turnEnds = { kind: 'aborted', reason: cause } + } catch (cleanupError: unknown) { + const error = turnFailure === undefined ? cleanupError : new AggregateError( + [turnFailure.error, cleanupError], 'Turn execution and finalization failed', { cause: turnFailure.error }, + ) turnEnds = { kind: 'error', error: { code: 'UNKNOWN', message: errorChain(error) } } throw error } finally { diff --git a/packages/core/agent-loop/tests/contract-regressions.spec.ts b/packages/core/agent-loop/tests/contract-regressions.spec.ts index 3be9ed1171..5cc9810ef3 100644 --- a/packages/core/agent-loop/tests/contract-regressions.spec.ts +++ b/packages/core/agent-loop/tests/contract-regressions.spec.ts @@ -1566,3 +1566,18 @@ describe('turn finalization', () => { } finally { await ctx.fiber.dispose() } }) }) + +it('retains the turn failure alongside a failed resource finalizer', async () => { + const ctx = await harness(new MockAdapter([])) + const agent = await ctx.agentLoop.create(brandString('failed-finalization'), { provider: 'mock', model: 'mock' }) + ctx.on('agent/pre-step', () => { throw new Error('turn preparation failed') }) + ctx.on('agent/turn-finalizing', () => { throw new Error('resource release failed') }) + try { + send(agent, 'go') + await agent.whenIdle() + const ending = agent.session.snapshotEvents().find(event => event.type === 'turn/end') + expect(ending?.data.reason.kind).toBe('error') + expect(JSON.stringify(ending)).toContain('turn preparation failed') + expect(JSON.stringify(ending)).toContain('resource release failed') + } finally { await ctx.fiber.dispose() } +}) diff --git a/scripts/gen-doc-graphs.spec.ts b/scripts/gen-doc-graphs.spec.ts index 9315e03b92..79b4bce919 100644 --- a/scripts/gen-doc-graphs.spec.ts +++ b/scripts/gen-doc-graphs.spec.ts @@ -43,7 +43,7 @@ const FIXTURE: Record = { '', ].join('\n'), 'packages/core/agent/src/dispatch.ts': - 'export interface AgentEventDispatch { emit(...args: unknown[]): void }\n', + 'export interface AgentEventDispatch { emit(...args: unknown[]): void; settled(...args: unknown[]): Promise }\n', // fireLocal: every same-file reference is a direct callee, so the locality // proof holds and only this file is indexed. fireAliased: the exported // const is a value-position reference, so the proof fails and the global @@ -55,6 +55,10 @@ const FIXTURE: Record = { "fireLocal(['pkga/local-event'])", "function fireAliased(args: [string]): void { void events.dispatch('emit', args) }", 'export const aliased = fireAliased', + "declare const agent: import('../../../core/agent/src/dispatch.ts').AgentEventDispatch", + "void agent.settled('agent/turn-finalizing')", + 'const unrelated = { settled(_event: string): void {} }', + "unrelated.settled('agent/unrelated')", '', ].join('\n'), 'packages/fix/pkgb/src/index.ts': [ @@ -221,3 +225,8 @@ describe('memoized filesystem probes', () => { .toEqual(project.sourceFiles().map(sourceFile => sourceFile.fileName)) }) }) + +it('discovers awaited agent finalizers without treating unrelated settled methods as events', () => { + expect(dispatchersOf(['pkga'], 'agent/turn-finalizing')).toEqual(['pkga']) + expect(dispatchersOf(['pkga'], 'agent/unrelated')).toEqual([]) +}) diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts index ab031dc062..9ee177e2ed 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -1248,7 +1248,7 @@ type CallSiteIndex = Map>Hooks: ${mermaidCode('agent/turn-finalizing')} await all resource finalizers`, ` Driver->>Session: ${mermaidCode('turn/end')}`, ` Driver-->>SDK: ${mermaidCode('agent/status')} idle`, '```', From 15e36acd446108e7790b0b88ba25e7eece26687f Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 15:22:23 +0800 Subject: [PATCH 10/73] Record finalized SDK output without queuing another turn --- .../experimental/cua-macos/tests/turn-inputs.desktop.e2e.ts | 1 + .../snapshots/python-sdk-single-exe/advanced-ptc/result.json | 4 ++-- .../python-sdk-single-exe/advanced-ptc/session.v4.jsonl | 2 +- scripts/snapshots/python-sdk-single-exe/advanced/result.json | 4 ++-- .../snapshots/python-sdk-single-exe/advanced/session.v4.jsonl | 2 +- snapshots/sdk/ptc-cancel/cancel.mjs | 4 +--- snapshots/sdk/ptc-cancel/session.v4.jsonl | 1 - snapshots/session/cua-native/system-prompt.expected.md | 4 ++-- 8 files changed, 10 insertions(+), 12 deletions(-) diff --git a/packages/experimental/cua-macos/tests/turn-inputs.desktop.e2e.ts b/packages/experimental/cua-macos/tests/turn-inputs.desktop.e2e.ts index e460d543ac..fa90af8e1e 100644 --- a/packages/experimental/cua-macos/tests/turn-inputs.desktop.e2e.ts +++ b/packages/experimental/cua-macos/tests/turn-inputs.desktop.e2e.ts @@ -32,6 +32,7 @@ const State = z.object({ // These cases share the real desktop and deliberately run in order. Run this opt-in file alone. it.skipIf(process.platform !== 'darwin' || helperPath === undefined).each(['completed', 'error', 'thinking-stop', 'tool-stop'] as const)( 'receives mixed releases after %s through cua_run_code', async (ending) => { + if (helperPath === undefined) throw new Error('Set DSH_CUA_TEST_HELPER to a signed helper application executable') const directory = await mkdtemp(join(tmpdir(), 'dsh-turn-input-desktop-')) const appDirectory = join(directory, 'Input Receiver.app') const executable = join(appDirectory, 'Contents/MacOS/InputReceiver') diff --git a/scripts/snapshots/python-sdk-single-exe/advanced-ptc/result.json b/scripts/snapshots/python-sdk-single-exe/advanced-ptc/result.json index 590a5001e8..670bf27fe6 100644 --- a/scripts/snapshots/python-sdk-single-exe/advanced-ptc/result.json +++ b/scripts/snapshots/python-sdk-single-exe/advanced-ptc/result.json @@ -984,7 +984,7 @@ "item": { "messageId": "{{message:1}}", "rating": "positive", - "note": "The explanation is clear now.", + "note": "Turn resources released.", "version": "{{feedback-version:2}}", "createdAt": 0, "updatedAt": 0 @@ -2258,7 +2258,7 @@ "item": { "messageId": "{{message:1}}", "rating": "positive", - "note": "The explanation is clear now.", + "note": "Turn resources released.", "version": "{{feedback-version:2}}", "createdAt": 0, "updatedAt": 0 diff --git a/scripts/snapshots/python-sdk-single-exe/advanced-ptc/session.v4.jsonl b/scripts/snapshots/python-sdk-single-exe/advanced-ptc/session.v4.jsonl index 799360745b..1259ffbba5 100644 --- a/scripts/snapshots/python-sdk-single-exe/advanced-ptc/session.v4.jsonl +++ b/scripts/snapshots/python-sdk-single-exe/advanced-ptc/session.v4.jsonl @@ -45,6 +45,6 @@ {"type":"command/done","data":{"commandId":"{{command:1}}","kind":"success","text":"Feedback recorded for session {{parent}}\nAnonymous user: {{anonymous-user}}."}} {"type":"feedback/record","data":{"category":"other"}} {"type":"feedback/message-put","data":{"sessionId":"{{parent}}","item":{"messageId":"{{message:1}}","rating":"negative","note":"Explain the result.","category":"task-result","version":"{{feedback-version:1}}","createdAt":0,"updatedAt":0}}} -{"type":"feedback/message-put","data":{"sessionId":"{{parent}}","item":{"messageId":"{{message:1}}","rating":"positive","note":"The explanation is clear now.","version":"{{feedback-version:2}}","createdAt":0,"updatedAt":0}}} +{"type":"feedback/message-put","data":{"sessionId":"{{parent}}","item":{"messageId":"{{message:1}}","rating":"positive","note":"Turn resources released.","version":"{{feedback-version:2}}","createdAt":0,"updatedAt":0}}} {"type":"feedback/message-delete","data":{"sessionId":"{{parent}}","messageId":"{{message:1}}"}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/scripts/snapshots/python-sdk-single-exe/advanced/result.json b/scripts/snapshots/python-sdk-single-exe/advanced/result.json index 78a94e27da..3a704fd34e 100644 --- a/scripts/snapshots/python-sdk-single-exe/advanced/result.json +++ b/scripts/snapshots/python-sdk-single-exe/advanced/result.json @@ -1460,7 +1460,7 @@ "item": { "messageId": "{{message:1}}", "rating": "positive", - "note": "The explanation is clear now.", + "note": "Turn resources released.", "version": "{{feedback-version:2}}", "createdAt": 0, "updatedAt": 0 @@ -4868,7 +4868,7 @@ "item": { "messageId": "{{message:1}}", "rating": "positive", - "note": "The explanation is clear now.", + "note": "Turn resources released.", "version": "{{feedback-version:2}}", "createdAt": 0, "updatedAt": 0 diff --git a/scripts/snapshots/python-sdk-single-exe/advanced/session.v4.jsonl b/scripts/snapshots/python-sdk-single-exe/advanced/session.v4.jsonl index 6681e94bc0..776cc9dcc1 100644 --- a/scripts/snapshots/python-sdk-single-exe/advanced/session.v4.jsonl +++ b/scripts/snapshots/python-sdk-single-exe/advanced/session.v4.jsonl @@ -62,6 +62,6 @@ {"type":"command/done","data":{"commandId":"{{command:1}}","kind":"success","text":"Feedback recorded for session {{parent}}\nAnonymous user: {{anonymous-user}}."}} {"type":"feedback/record","data":{"category":"other"}} {"type":"feedback/message-put","data":{"sessionId":"{{parent}}","item":{"messageId":"{{message:1}}","rating":"negative","note":"Explain the result.","category":"task-result","version":"{{feedback-version:1}}","createdAt":0,"updatedAt":0}}} -{"type":"feedback/message-put","data":{"sessionId":"{{parent}}","item":{"messageId":"{{message:1}}","rating":"positive","note":"The explanation is clear now.","version":"{{feedback-version:2}}","createdAt":0,"updatedAt":0}}} +{"type":"feedback/message-put","data":{"sessionId":"{{parent}}","item":{"messageId":"{{message:1}}","rating":"positive","note":"Turn resources released.","version":"{{feedback-version:2}}","createdAt":0,"updatedAt":0}}} {"type":"feedback/message-delete","data":{"sessionId":"{{parent}}","messageId":"{{message:1}}"}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/snapshots/sdk/ptc-cancel/cancel.mjs b/snapshots/sdk/ptc-cancel/cancel.mjs index d8ee51b63f..c1729045e2 100644 --- a/snapshots/sdk/ptc-cancel/cancel.mjs +++ b/snapshots/sdk/ptc-cancel/cancel.mjs @@ -1,12 +1,10 @@ /** Cancel after the PTC process completes a nested job_list call. */ -import { createUserMessage } from '@deepseek-ai/dsh-llm' - export const name = 'ptc-cancel-fixture' export const inject = ['tools'] export function apply(ctx) { ctx.on('agent/turn-finalizing', async ({ agent }) => { await Promise.resolve() - agent.inject(createUserMessage({ content: [{ type: 'text', text: 'Turn resources released.' }], source: { kind: 'user' } })) + agent.session.append('feedback/record', { category: 'other' }) }) ctx.on('tools/result', (exec) => { if (exec.name === 'job_list' && exec.parent !== undefined && exec.agent !== undefined) { diff --git a/snapshots/sdk/ptc-cancel/session.v4.jsonl b/snapshots/sdk/ptc-cancel/session.v4.jsonl index 2f28e82281..c31c586b7a 100644 --- a/snapshots/sdk/ptc-cancel/session.v4.jsonl +++ b/snapshots/sdk/ptc-cancel/session.v4.jsonl @@ -19,6 +19,5 @@ {"type":"tool/ptc-dispatch","data":{"rootCallId":"ptc-cancel","parentCallId":"ptc-cancel","subCallId":"ptc-cancel:ptc:1","name":"job_list","arguments":{},"isError":false,"content":[{"type":"text","text":"(no background jobs)"}]}} {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"ptc-cancel"},"toolCallId":"ptc-cancel","content":[{"type":"text","text":"Error: tool call aborted"}],"isError":true,"id":"{{message:6}}"},"error":{"name":"AbortError","code":"ABORTED"}},"sourceEventSeqs":[15],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} -{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"Turn resources released."}],"source":{"kind":"user"},"role":"user","id":"{{message:7}}"}]}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"aborted","reason":{"kind":"user"}}}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[],"outcome":"canceled"}} diff --git a/snapshots/session/cua-native/system-prompt.expected.md b/snapshots/session/cua-native/system-prompt.expected.md index 4782131f9f..b2c566a0b6 100644 --- a/snapshots/session/cua-native/system-prompt.expected.md +++ b/snapshots/session/cua-native/system-prompt.expected.md @@ -75,7 +75,7 @@ Leave useSystemPointer unset for ordinary mouseMove, drag, and toggleMouse calls Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemPointer?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemPointer omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemPointer?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemPointer: true on both down and up. Physical moves can then drag, including your own mouse movements. The turn ending or the connection closing releases a remaining system hold. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemPointer?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; platform guidance defines their cleanup scope. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemPointer: true on down. Up uses the input route and window saved by down. Physical moves can then drag, including your own mouse movements. Both routes hold across programs in the same turn and release with held keys when the turn ends. click and drag release their own buttons within the operation. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], 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. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying. - 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. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemPointer?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control. An explicit system drag shares the session decision with mouseMove and holds the chosen button along the path in the unobscured foreground window. @@ -87,7 +87,7 @@ Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - 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?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across run_code and cua_run_code calls in the same turn, for example W down, D down, D up, W up. Send 'up' to release it immediately at its original recipient. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. A program returning or throwing keeps its holds while the turn continues. When the turn completes, fails, or is stopped, macOS releases remaining keys and mouse buttons together in reverse press order. pressKey and typeText still release their own presses within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. From 794cd66634a2a629bc5e733852ee759eb406962e Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 15:40:37 +0800 Subject: [PATCH 11/73] Keep cleanup listeners alive through unload and honor stop during finalization --- apps/web/tests/cua-run-code.e2e.ts | 4 +- docs/event-producer-consumer.md | 2 +- docs/event-producer-consumer.zh.md | 2 +- .../cua-turn-inputs/guide.i18n.yaml | 4 +- .../v0.2.2-rc.4/cua-turn-inputs/guide.md | 2 +- .../v0.2.2-rc.4/cua-turn-inputs/guide.zh.md | 2 +- packages/core/agent-loop/src/agent.ts | 3 +- .../tests/contract-regressions.spec.ts | 39 +++++++++++++++++++ packages/core/agent/src/dispatch.ts | 12 +++--- .../experimental/cua-macos/README.i18n.yaml | 4 +- packages/experimental/cua-macos/README.md | 2 +- packages/experimental/cua-macos/README.zh.md | 2 +- .../tests/provider-lifecycle.spec.ts | 1 + packages/experimental/cua/README.i18n.yaml | 4 +- packages/experimental/cua/README.md | 2 +- packages/experimental/cua/README.zh.md | 2 +- packages/experimental/cua/src/index.ts | 3 +- packages/experimental/cua/src/turn-inputs.ts | 19 ++++----- .../cua/tests/run-code-composition.spec.ts | 6 +++ scripts/gen-doc-graphs.spec.ts | 11 +----- scripts/gen-doc-graphs.ts | 5 +-- snapshots/sdk/ptc-cancel/session.v4.jsonl | 1 - .../text-turn/notifications.expected.jsonl | 2 +- snapshots/sdk/text-turn/session.v4.jsonl | 2 +- 24 files changed, 86 insertions(+), 50 deletions(-) diff --git a/apps/web/tests/cua-run-code.e2e.ts b/apps/web/tests/cua-run-code.e2e.ts index 272f418272..2a49c519e9 100644 --- a/apps/web/tests/cua-run-code.e2e.ts +++ b/apps/web/tests/cua-run-code.e2e.ts @@ -60,7 +60,7 @@ it.skipIf(mode === 'record')('shows standard CUA programs and their recorded sou const results = events.filter(event => event.type === 'tool/result') expect(results).toHaveLength(2) expect(results.every(event => !event.data.message.isError)).toBe(true) - expect(events.filter(event => event.type === 'tool/ptc-dispatch')).toHaveLength(8) + expect(events.filter(event => event.type === 'tool/ptc-dispatch')).toHaveLength(12) const calls = page.locator('[data-tool="cua_run_code"]') const description = 'Select and capture the fixture window' const turnControl = page.locator('[data-turn-process="1"]') @@ -78,7 +78,7 @@ it.skipIf(mode === 'record')('shows standard CUA programs and their recorded sou const source = calls.first().locator('pre.shiki') await source.waitFor() expect(await source.textContent()).toContain('var app = await cua.getApp("test.fixture")') - expect(await page.locator('[data-subcalls] [data-tool="cua"]').count()).toBe(8) + expect(await page.locator('[data-subcalls] [data-tool="cua"]').count()).toBe(12) expect(events.filter(event => event.type === 'tool/ptc-dispatch' && event.data.content.some(block => block.type === 'image'))).toHaveLength(1) expect(events.filter(event => event.type === 'tool/result' && event.data.message.content.some(block => block.type === 'image'))).toHaveLength(1) diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 636a30ff6b..4b9308fc28 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -22,7 +22,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:351`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`cua`](../packages/experimental/cua), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | | `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:390`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | | `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:310`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`timeline`](../packages/experimental/timeline) | -| `agent/turn-finalizing` | `parallel` | [`packages/core/agent/src/runtime-types.ts:429`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`settled`) | [`cua`](../packages/experimental/cua) | +| `agent/turn-finalizing` | `parallel` | [`packages/core/agent/src/runtime-types.ts:429`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`parallel`) | [`cua`](../packages/experimental/cua) | | `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:418`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:697`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:677`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index b9fa0b789d..eb17f3c6a1 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -24,7 +24,7 @@ | `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:351`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`cua`](../packages/experimental/cua), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | | `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:390`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | | `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:310`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`timeline`](../packages/experimental/timeline) | -| `agent/turn-finalizing` | `parallel` | [`packages/core/agent/src/runtime-types.ts:429`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`settled`) | [`cua`](../packages/experimental/cua) | +| `agent/turn-finalizing` | `parallel` | [`packages/core/agent/src/runtime-types.ts:429`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`parallel`) | [`cua`](../packages/experimental/cua) | | `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:418`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:697`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:677`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | diff --git a/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.i18n.yaml index 290b73d6bb..dc5e4fb96f 100644 --- a/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.i18n.yaml @@ -12,5 +12,5 @@ en: fdf88fdc0141c9d8 zh: a4af8cab104d38d1 /macos-cua-input-holds-last-for-one-turn/migration: - en: 30b6c3ffc7326ca0 - zh: a66655caa4c5e509 + en: 2003c761142c4449 + zh: 47376f07776cd74d diff --git a/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.md b/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.md index 097b6a2d04..bd86392dba 100644 --- a/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.md @@ -16,4 +16,4 @@ MCP does not supply DSH turn boundaries. Explicit macOS holds through `sendKeyEv 1. If a program requires release before it returns, send an explicit `up` in its `finally` block. Otherwise a later program in the same turn can release the held input. 2. Upgrade the macOS package and helper together. A custom `helperPath` must point to a rebuilt helper implementing the new private turn input protocol. -3. Verify a down in one program remains held until an up in a later program, or until the turn ends. If cleanup cannot be confirmed, CUA disables input for that task. Check the desktop before starting a new task. +3. Verify a down in one program remains held until an up in a later program, or until the turn ends. If cleanup cannot be confirmed, CUA disables all its operations for that task. Inspect the desktop manually before starting a new task. diff --git a/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.zh.md index 3753a2d02c..0bc720e5ce 100644 --- a/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.zh.md @@ -16,4 +16,4 @@ MCP 不提供 DSH 回合边界。macOS 的 `sendKeyEvent` 和 `toggleMouse` 显 1. 如果程序需要在返回前释放输入,在 `finally` 中显式发送 `up`。否则可由同一回合中的后续程序释放。 2. 同步升级 macOS 包和 helper。自定义 `helperPath` 必须指向已重建、支持新回合输入私有协议的 helper。 -3. 验证前一次程序的 `down` 能保持到后一次程序发送 `up`,或回合结束。清理无法确认时,CUA 会禁用该任务的输入。检查桌面状态后再创建新任务。 +3. 验证前一次程序的 `down` 能保持到后一次程序发送 `up`,或回合结束。清理无法确认时,CUA 会禁用该任务的全部操作。请手动检查桌面状态后再创建新任务。 diff --git a/packages/core/agent-loop/src/agent.ts b/packages/core/agent-loop/src/agent.ts index 1636ebb567..049692b0ea 100644 --- a/packages/core/agent-loop/src/agent.ts +++ b/packages/core/agent-loop/src/agent.ts @@ -427,7 +427,7 @@ export class ReactLoopAgent implements Agent { } finally { try { try { - await this.dispatch.settled('agent/turn-finalizing', { turn }) + await this.dispatch.parallel('agent/turn-finalizing', { turn }) const cause = abortedCancelCause(signal) if (cause !== undefined && turnEnds?.kind !== 'error') turnEnds = { kind: 'aborted', reason: cause } } catch (cleanupError: unknown) { @@ -444,6 +444,7 @@ export class ReactLoopAgent implements Agent { this.throwError(error) } } + signal.throwIfAborted() if (!this.inbox.hasPending) return false phase.abort = new AbortController() // A fresh controller makes a latch set on the old one stale: the live driver claims the queue itself. diff --git a/packages/core/agent-loop/tests/contract-regressions.spec.ts b/packages/core/agent-loop/tests/contract-regressions.spec.ts index 5cc9810ef3..6337c27050 100644 --- a/packages/core/agent-loop/tests/contract-regressions.spec.ts +++ b/packages/core/agent-loop/tests/contract-regressions.spec.ts @@ -1581,3 +1581,42 @@ it('retains the turn failure alongside a failed resource finalizer', async () => expect(JSON.stringify(ending)).toContain('resource release failed') } finally { await ctx.fiber.dispose() } }) + +it('parks queued input when cancellation arrives during resource finalization', async () => { + const adapter = new MockAdapter([textResponse('done'), textResponse('must stay queued')]) + const ctx = await harness(adapter) + const agent = await ctx.agentLoop.create(brandString('cancel-finalization'), { provider: 'mock', model: 'mock' }) + const entered: PromiseWithResolvers = Promise.withResolvers() + const release: PromiseWithResolvers = Promise.withResolvers() + ctx.on('agent/turn-finalizing', async () => { entered.resolve(); await release.promise }) + try { + send(agent, 'first') + await entered.promise + send(agent, 'queued') + agent.cancel({ kind: 'user' }, { keepInbox: true }) + release.resolve() + await agent.whenIdle() + expect(agent.session.snapshotEvents().filter(event => event.type === 'turn/start')).toHaveLength(1) + expect(agent.inbox.nextTurn).toHaveLength(1) + expect(agent.session.snapshotEvents().find(event => event.type === 'turn/end')?.data.reason) + .toEqual({ kind: 'aborted', reason: { kind: 'user' } }) + } finally { release.resolve(); await ctx.fiber.dispose() } +}) + +it('keeps an execution error when disposal cancels its finalizer wait', async () => { + const ctx = await harness(new MockAdapter([])) + const agent = await ctx.agentLoop.create(brandString('error-finalization'), { provider: 'mock', model: 'mock' }) + const entered: PromiseWithResolvers = Promise.withResolvers() + const release: PromiseWithResolvers = Promise.withResolvers() + ctx.on('agent/pre-step', () => { throw new Error('preparation failed') }) + ctx.on('agent/turn-finalizing', async () => { entered.resolve(); await release.promise }) + try { + send(agent, 'first') + await entered.promise + agent.cancel({ kind: 'disposed' }, { keepInbox: true }) + release.resolve() + await agent.whenIdle() + expect(agent.session.snapshotEvents().find(event => event.type === 'turn/end')?.data.reason) + .toMatchObject({ kind: 'error', error: { message: 'preparation failed' } }) + } finally { release.resolve(); await ctx.fiber.dispose() } +}) diff --git a/packages/core/agent/src/dispatch.ts b/packages/core/agent/src/dispatch.ts index 1064cd74d1..0f0f80a73e 100644 --- a/packages/core/agent/src/dispatch.ts +++ b/packages/core/agent/src/dispatch.ts @@ -74,7 +74,7 @@ export interface AgentEventDispatch { * @param payload - the event's payload fields; `agent` is injected. * @returns completion after all listeners settle. */ - settled(name: K, payload: PayloadRest): Promise + parallel(name: K, payload: PayloadRest): Promise /** * Around-middleware dispatch (Cordis `waterfall`) in the agent's scope. The * declared event parameters already end with the `next` callback, so `rest` @@ -142,12 +142,10 @@ export function agentEvents(ctx: Context, agent: Agent, carrier: Scoped = } } }, - async settled(name, payload) { - const args: unknown[] = [carrier, name, fused(payload)] - const callbacks = ctx.events.dispatch('parallel', args) - const results = await Promise.allSettled(callbacks.map(callback => Promise.resolve().then(() => callback(...args)))) - const errors = results.flatMap(result => result.status === 'rejected' ? [result.reason] : []) - if (errors.length > 0) throw new AggregateError(errors, `Agent event "${name}" failed`) + async parallel(name, payload) { + // oxlint-disable-next-line typescript/unbound-method -- the events mixin accessor returns a pre-bound function + const parallel = ctx.parallel as (thisArg: Scoped, name: string, ...args: unknown[]) => Promise + await parallel(carrier, name, fused(payload)) }, async serial(name, payload) { // oxlint-disable-next-line typescript/unbound-method -- the events mixin accessor returns a pre-bound function diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index e146a1a819..58534708cc 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -45,8 +45,8 @@ en: a2c9acb5a4320dda zh: e8d1586af60215c4 /deepseek-ai-dsh-cua-macos/known-limitations-and-deferred-work: - en: a3639148d575b42e - zh: f51a709fd77a1cfa + en: dd03900c0fafe3be + zh: 56e011ce9a21e12c /deepseek-ai-dsh-cua-macos/known-limitations-and-deferred-work/dev-note: en: b836f01bd0bceb4a zh: 8122fa08b2aa95fa diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index 75f4e9c234..142c04a162 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -267,7 +267,7 @@ The queue orders individual native requests. Holding an app object does not rese -- The native acknowledgement confirms event dispatch, not application processing. If turn cleanup is refused, times out, or loses its connection, CUA reports the uncertainty and blocks further input in that task. Check the desktop before starting a new task. +- The native acknowledgement confirms event dispatch, not application processing. If turn cleanup is refused, times out, or loses its connection, CUA reports the uncertainty and blocks all CUA operations in that task. Inspect the desktop manually before starting a new task. - macOS 14 is the minimum supported version; settings navigation, drag acceptance, and permission refresh require qualification on each supported release. If macOS requires quitting and reopening the helper after a Screen Recording change, its preflight check can remain denied until that restart. The guide can be dismissed without terminating other connections. - The guide closes when its selected settings window leaves the visible-window list, including when a Space switch or minimization removes it. Request permission again after returning to reopen the guide. - This provider supports macOS. For Windows, see the [Windows provider](../cua-windows/README.md#setup). Browser tabs, AX diffs, unassociated system panels and accessory-only apps are unsupported. diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 792d5bc251..8a6e23fb2a 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -267,7 +267,7 @@ Only if the task cannot be completed without moving the user’s pointer, call a -- 原生确认表示事件已派发,不表示应用已处理。回合清理被拒绝、超时或断连时,CUA 会报告不确定结果,并禁止该任务继续发送输入。检查桌面状态后再创建新任务。 +- 原生确认表示事件已派发,不表示应用已处理。回合清理被拒绝、超时或断连时,CUA 会报告不确定结果,并禁止该任务的全部 CUA 操作。请手动检查桌面状态后再创建新任务。 - 最低支持 macOS 14;设置导航、拖放接收和权限刷新需要在各支持版本验收。若 macOS 要求在修改屏幕录制权限后退出并重新打开 helper,权限检查在重启前可能仍返回未授权。可以关闭引导框,不必终止其他连接。 - 所选设置窗口离开可见窗口列表时,引导框会关闭,包括切换桌面空间或最小化导致窗口不再可见的情况。返回后再次申请权限可重新打开引导。 - 本提供方适用于 macOS。Windows 的配置见 [Windows 提供方](../cua-windows/README.zh.md#setup)。不支持浏览器标签、AX 差分、无法确认应用归属的系统面板和仅后台辅助类型的应用。 diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index 1957f30f35..d33cacc1dc 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -487,6 +487,7 @@ it('reports failed cleanup after waiting for other owners and releasing their Ag expect(native.dispose).toHaveBeenCalledTimes(2) const aggregate = reported.find(error => error instanceof AggregateError) expect(aggregate?.errors).toContain(failure) + expect(f.ctx.computerUse.providerName).toBeUndefined() const errorsBeforeAgentDisposal = errors.mock.calls.length await Promise.all([f.handle.dispose(), other.dispose()]) expect(native.dispose).toHaveBeenCalledTimes(2) diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index 29cd20a2c8..79d2f27618 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -21,8 +21,8 @@ en: 3f638a4a76023fc5 zh: 515aeb5de6ae5b33 /deepseek-ai-dsh-cua/understand-the-implementation: - en: a106735c075a5d21 - zh: aad70f757745e311 + en: 7876bc7034fa9f83 + zh: 312ff855f94b7ef1 /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 00101235a5..2933c4c0ee 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -89,7 +89,7 @@ Permission responses identify their platform and report only the state that plat
Shared execution and platform ownership -A provider enables `CuaBackend.turnInputLifecycle` only after its helper accepts `taskId` and `turn` on `sendKeyEvent`, `toggleMouse`, and system `mouseMove`, and acknowledges `releaseHeldInputs({ taskId, turn })`. The shared owner blocks admission on cancellation or finalization, awaits native cancellation before independent bounded cleanup, and disables the task after an unconfirmed release. Providers must record actual dispatch order, targets and routes before posting, implement explicit up and mixed reverse-order cleanup, reject stale turns, and clean only their connection on disconnect. Windows leaves this option unset until these native behaviors are implemented; it receives neither new parameters nor cleanup commands. +A provider enables `CuaBackend.turnInputLifecycle` only after its helper accepts `taskId` and `turn` on `sendKeyEvent`, `toggleMouse`, and system `mouseMove`, and acknowledges `releaseHeldInputs({ taskId, turn })`. The shared owner blocks admission on cancellation or finalization, awaits native cancellation before independent bounded cleanup, and disables all CUA operations for the task after an unconfirmed release. Providers must record actual dispatch order, targets and routes before posting, implement explicit up and mixed reverse-order cleanup, reject stale turns, and clean only their connection on disconnect. Windows leaves this option unset until these native behaviors are implemented; it receives neither new parameters nor cleanup commands. The [permission store](src/permission-store.ts) uses `storageDomain` with the configured backend. The default JSON backend writes `$DSH_HOME/storages/cua_permissions_.json`, where the digest identifies the canonical profile directory. Each authorization check opens fresh state under the profile's file lock and closes its domain afterward; native dispatch uses a separate application lock. Revocation waits for operations already admitted by another process; after it completes, every process rejects old handles. Files on different machines or PID namespaces must not share this lock. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index 5670fef393..55410d2087 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -89,7 +89,7 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边
共享执行与平台职责 -提供方仅在 helper 已接受 `sendKeyEvent`、`toggleMouse` 和系统 `mouseMove` 的 `taskId`、`turn` 参数,并能确认 `releaseHeldInputs({ taskId, turn })` 后,才启用 `CuaBackend.turnInputLifecycle`。共通持有方在取消或收尾时禁止新输入,等待原生取消后用独立且有超时限制的请求清理;释放未经确认时禁用该任务的输入。提供方必须在派发前记录实际顺序、目标与输入方式,实现显式释放和键鼠混合反序清理,拒绝旧回合输入,并在断连时只清理本连接。Windows 在实现这些原生行为前保持此选项未设置,不接收新增参数或清理命令。 +提供方仅在 helper 已接受 `sendKeyEvent`、`toggleMouse` 和系统 `mouseMove` 的 `taskId`、`turn` 参数,并能确认 `releaseHeldInputs({ taskId, turn })` 后,才启用 `CuaBackend.turnInputLifecycle`。共通持有方在取消或收尾时禁止新输入,等待原生取消后用独立且有超时限制的请求清理;释放未经确认时禁用该任务的全部 CUA 操作。提供方必须在派发前记录实际顺序、目标与输入方式,实现显式释放和键鼠混合反序清理,拒绝旧回合输入,并在断连时只清理本连接。Windows 在实现这些原生行为前保持此选项未设置,不接收新增参数或清理命令。 [授权存储](src/permission-store.ts)复用 `storageDomain` 和配置的后端。默认 JSON 后端写入 `$DSH_HOME/storages/cua_permissions_.json`,摘要对应 profile 的真实目录。每次授权检查在 profile 文件锁内打开并读取最新状态,随后关闭存储域;原生操作使用单独的应用锁。撤销会等待其他进程已获准执行的操作结束;撤销完成后,各进程都拒绝旧句柄。不同电脑或 PID 命名空间不能共享这把锁。 diff --git a/packages/experimental/cua/src/index.ts b/packages/experimental/cua/src/index.ts index b8ac5bc851..58647c2968 100644 --- a/packages/experimental/cua/src/index.ts +++ b/packages/experimental/cua/src/index.ts @@ -264,6 +264,7 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) return owner } ctx.effect(function* () { + if (inputTurns) yield* inputTurns.install() yield ctx.computerUse.register(brandString('dsh-cua')) yield async () => { lifetime.abort() @@ -274,7 +275,7 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) const releases = await Promise.allSettled(owners.map(owner => owner.release())) const errors: unknown[] = [] for (const result of [...await permissions, ...results, ...releases]) if (result.status === 'rejected') errors.push(result.reason) - if (errors.length > 0) throw new AggregateError(errors, 'dsh-cua helper cleanup failed') + if (errors.length > 0) ctx.logger.error(new AggregateError(errors, 'dsh-cua helper cleanup failed')) } const callNative = async (request: CuaOperation, execution: Readonly, useSystemPointer?: boolean) => { const { method, params: parsedParams } = request diff --git a/packages/experimental/cua/src/turn-inputs.ts b/packages/experimental/cua/src/turn-inputs.ts index 3cfe2eb29e..10d4f255c5 100644 --- a/packages/experimental/cua/src/turn-inputs.ts +++ b/packages/experimental/cua/src/turn-inputs.ts @@ -17,9 +17,6 @@ class InputTurn { track(client: NativeClient): void { this.signal.throwIfAborted() - if (this.client && this.client !== client) { - throw new NativeError('INPUT_CONNECTION_CHANGED', 'Held input belongs to the original connection; finish this turn before selecting another connection') - } if (!this.client) { this.removeCleanup = client.registerCleanup(canRequest => this.close(canRequest)) this.client = client @@ -31,7 +28,7 @@ class InputTurn { return this.closing ??= Promise.resolve().then(async () => { try { if (!this.client) return - if (!canRequest) throw new NativeError('INPUT_CLEANUP_UNCONFIRMED', 'Native connection closed before turn input cleanup was confirmed. Input is disabled for this task; start a new task after checking the desktop') + if (!canRequest) throw new NativeError('INPUT_CLEANUP_UNCONFIRMED', 'Native connection closed before turn cleanup was confirmed. All CUA operations are disabled for this task; inspect the desktop manually before starting a new task') await this.client.requestCleanup('releaseHeldInputs', { taskId: this.agent.id, turn: this.turn }) } catch (error) { this.failed(error) @@ -49,17 +46,21 @@ export class CuaInputTurns { private readonly failures = new WeakMap() /** @param ctx - Provider scope owning the lifecycle listeners. */ - constructor(private readonly ctx: Context) { - ctx.on('agent/pre-step', (event, next) => { + constructor(private readonly ctx: Context) {} + + /** @returns Exact listener disposers for the runtime effect to retain through native cleanup. */ + *install(): Generator<() => void> { + const ctx = this.ctx + yield ctx.on('agent/pre-step', (event, next) => { if (this.turns.get(event.agent)?.turn !== event.turn) { this.turns.set(event.agent, new InputTurn(event.agent, event.turn, event.signal, (error) => { this.failures.set(event.agent, error) - ctx.logger.error('CUA input cleanup was not confirmed; input is disabled for task %s: %s', event.agent.id, error) + ctx.logger.error('CUA cleanup was not confirmed; all CUA operations are disabled for task %s: %s', event.agent.id, error) })) } return next() }) - ctx.on('agent/turn-finalizing', ({ agent, turn }) => { + yield ctx.on('agent/turn-finalizing', ({ agent, turn }) => { const owner = this.turns.get(agent) if (owner?.turn === turn) return owner.close() }) @@ -72,7 +73,7 @@ export class CuaInputTurns { */ scope(agent: Agent): InputTurn | undefined { if (this.failures.has(agent)) { - throw new NativeError('INPUT_CLEANUP_UNCONFIRMED', 'CUA input cleanup was not confirmed. Input is disabled for this task; start a new task after checking the desktop', { cause: this.failures.get(agent) }) + throw new NativeError('INPUT_CLEANUP_UNCONFIRMED', 'CUA cleanup was not confirmed. All CUA operations are disabled for this task; inspect the desktop manually before starting a new task', { cause: this.failures.get(agent) }) } const boundary = this.ctx.agents.turnBoundaryOf(agent.session) if (boundary.openTurnStartSeq === null) return undefined diff --git a/packages/experimental/cua/tests/run-code-composition.spec.ts b/packages/experimental/cua/tests/run-code-composition.spec.ts index 19409aa22c..99a315a897 100644 --- a/packages/experimental/cua/tests/run-code-composition.spec.ts +++ b/packages/experimental/cua/tests/run-code-composition.spec.ts @@ -1,4 +1,5 @@ /** Standard-mode CUA through Loader, the native executor, and real persistent Node programs. */ +import { setImmediate } from 'node:timers/promises' import { mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -459,6 +460,11 @@ it.each(['agent', 'provider'] as const)('awaits held input cleanup when the %s i try { expect(disposed).toBe(false) expect(f.native.state.closedChannels).toBe(0) + f.agent.cancel({ kind: 'user' }) + // The model's abort and loop finalization are in-process; the native reply remains behind its explicit barrier. + await setImmediate() + expect(f.agent.status).toBe('running') + expect(f.agent.session.snapshotEvents().some(event => event.type === 'turn/end')).toBe(false) } finally { release.reply() f.agent.cancel({ kind: 'user' }) diff --git a/scripts/gen-doc-graphs.spec.ts b/scripts/gen-doc-graphs.spec.ts index 79b4bce919..9315e03b92 100644 --- a/scripts/gen-doc-graphs.spec.ts +++ b/scripts/gen-doc-graphs.spec.ts @@ -43,7 +43,7 @@ const FIXTURE: Record = { '', ].join('\n'), 'packages/core/agent/src/dispatch.ts': - 'export interface AgentEventDispatch { emit(...args: unknown[]): void; settled(...args: unknown[]): Promise }\n', + 'export interface AgentEventDispatch { emit(...args: unknown[]): void }\n', // fireLocal: every same-file reference is a direct callee, so the locality // proof holds and only this file is indexed. fireAliased: the exported // const is a value-position reference, so the proof fails and the global @@ -55,10 +55,6 @@ const FIXTURE: Record = { "fireLocal(['pkga/local-event'])", "function fireAliased(args: [string]): void { void events.dispatch('emit', args) }", 'export const aliased = fireAliased', - "declare const agent: import('../../../core/agent/src/dispatch.ts').AgentEventDispatch", - "void agent.settled('agent/turn-finalizing')", - 'const unrelated = { settled(_event: string): void {} }', - "unrelated.settled('agent/unrelated')", '', ].join('\n'), 'packages/fix/pkgb/src/index.ts': [ @@ -225,8 +221,3 @@ describe('memoized filesystem probes', () => { .toEqual(project.sourceFiles().map(sourceFile => sourceFile.fileName)) }) }) - -it('discovers awaited agent finalizers without treating unrelated settled methods as events', () => { - expect(dispatchersOf(['pkga'], 'agent/turn-finalizing')).toEqual(['pkga']) - expect(dispatchersOf(['pkga'], 'agent/unrelated')).toEqual([]) -}) diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts index 9ee177e2ed..0409c43f6e 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -1248,7 +1248,7 @@ type CallSiteIndex = Map Date: Wed, 18 Nov 2026 15:45:21 +0800 Subject: [PATCH 12/73] Report hold availability by execution context and cover forced disconnect --- .../tests/provider-lifecycle.spec.ts | 2 +- .../cua-mcp/tests/composition.spec.ts | 2 ++ packages/experimental/cua/src/index.ts | 3 ++- .../cua/tests/run-code-composition.spec.ts | 23 +++++++++++++++++++ 4 files changed, 28 insertions(+), 2 deletions(-) diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index d33cacc1dc..e287cb0ff0 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -319,7 +319,7 @@ it('merges startup capabilities into runtime native fields', async () => { coordinateSpace: 'screenshot-pixels', methods: [ 'activate', 'click', 'drag', 'findApps', 'getApp', 'getCapabilities', 'getState', 'invoke', 'listActions', 'listApps', 'listWindows', 'mouseMove', 'paste', 'performAction', 'pressKey', 'screenshot', 'scroll', - 'selectText', 'sendKeyEvent', 'setValue', 'show', 'toggleMouse', 'typeText', + 'selectText', 'setValue', 'show', 'typeText', ] }) expect(native.request).toHaveBeenCalledExactlyOnceWith('getCapabilities', {}, expect.any(AbortSignal), brandString('lifecycle-1')) }) diff --git a/packages/experimental/cua-mcp/tests/composition.spec.ts b/packages/experimental/cua-mcp/tests/composition.spec.ts index 9aebf1dc0d..b574ff5882 100644 --- a/packages/experimental/cua-mcp/tests/composition.spec.ts +++ b/packages/experimental/cua-mcp/tests/composition.spec.ts @@ -185,6 +185,8 @@ describe('Computer Use MCP composition', () => { it('refuses persistent downs outside a turn and still completes clicks through MCP', async () => { const { client, native, run } = await setup() expect(client.getInstructions()).toContain('MCP programs cannot hold keys or mouse buttons') + const capabilities = await run('inspect(JSON.stringify((await cua.getCapabilities()).methods))') + expect(texts(capabilities).join('')).not.toMatch(/sendKeyEvent|toggleMouse/) const selected = await run('var app = await cua.getApp("test.fixture"); var win = await app.getWindow("7"); await win.getAccessibilityTree()') expect(selected.isError).not.toBe(true) for (const code of ['await app.sendKeyEvent("w", "down")', 'await win.toggleMouse("left", "down")']) { diff --git a/packages/experimental/cua/src/index.ts b/packages/experimental/cua/src/index.ts index 58647c2968..31bcd317a1 100644 --- a/packages/experimental/cua/src/index.ts +++ b/packages/experimental/cua/src/index.ts @@ -363,10 +363,11 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) if (method === 'getCapabilities') { const runtime = z.record(z.string(), z.json()).parse(result) const capabilities = backend.capabilities + const canHoldInput = !inputTurns || inputTurns.scope(agent) !== undefined return { ...runtime, platform: capabilities.platform, systemPointer, - methods: [...capabilities.methods], + methods: capabilities.methods.filter(method => canHoldInput || (method !== 'sendKeyEvent' && method !== 'toggleMouse')), appLevelAccessibility: capabilities.appLevelAccessibility, keyboard: [...capabilities.keyboard], browser: capabilities.browser, diff --git a/packages/experimental/cua/tests/run-code-composition.spec.ts b/packages/experimental/cua/tests/run-code-composition.spec.ts index 99a315a897..5edc198b7b 100644 --- a/packages/experimental/cua/tests/run-code-composition.spec.ts +++ b/packages/experimental/cua/tests/run-code-composition.spec.ts @@ -527,3 +527,26 @@ it('cleans one task without releasing another connection and prevents a queued t } expect(f.native.held).toEqual([]) }) + +it('reports disconnect after a dispatched down and blocks a later program in the same turn', async () => { + const f = await setup([holdProgram, 'await cua.getApp("test.fixture")'], 'macos', undefined, true, true) + const down = f.native.controlNext('sendKeyEvent', { afterDispatch: true }) + const running = f.run() + await down.entered + down.disconnect() + await running + const results = f.agent.session.deriveMessages().filter(message => message.role === 'tool') + expect(results.map(result => result.isError)).toEqual([true, true]) + expect(JSON.stringify(results[1])).toContain('INPUT_CLEANUP_UNCONFIRMED') + expect(f.native.calls.filter(call => call.method === 'getApp')).toHaveLength(1) + expect(f.native.calls.some(call => call.method === 'releaseHeldInputs')).toBe(false) + expect(f.agent.session.snapshotEvents().find(event => event.type === 'turn/end')?.data.reason.kind).toBe('error') +}) + +it('finalizes without native cleanup when prompt assembly fails before input admission', async () => { + const f = await setup([holdProgram], 'macos', undefined, true, true) + f.ctx.on('system-prompt/assemble', async () => { throw new Error('Fixture assembly failed') }) + await f.run() + expect(f.native.calls).toEqual([]) + expect(f.agent.session.snapshotEvents().find(event => event.type === 'turn/end')?.data.reason.kind).toBe('error') +}) From 85c460cd3b2086461a6b58a6967e804352ec8e83 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 15:54:05 +0800 Subject: [PATCH 13/73] Refresh SDK and Web recordings and document contextual hold availability --- packages/experimental/cua-mcp/README.i18n.yaml | 4 ++-- packages/experimental/cua-mcp/README.md | 2 +- packages/experimental/cua-mcp/README.zh.md | 2 +- packages/experimental/cua/README.i18n.yaml | 4 ++-- packages/experimental/cua/README.md | 2 +- packages/experimental/cua/README.zh.md | 2 +- packages/experimental/cua/src/turn-inputs.ts | 1 + packages/experimental/cua/src/types.ts | 4 ++-- snapshots/sdk/ptc-cancel/session.v4.jsonl | 3 ++- snapshots/web/cua-run-code/code.expected.md | 2 +- snapshots/web/cua-run-code/ui.expected.md | 6 +++++- 11 files changed, 19 insertions(+), 13 deletions(-) diff --git a/packages/experimental/cua-mcp/README.i18n.yaml b/packages/experimental/cua-mcp/README.i18n.yaml index 59b87e135d..81f5e950ba 100644 --- a/packages/experimental/cua-mcp/README.i18n.yaml +++ b/packages/experimental/cua-mcp/README.i18n.yaml @@ -45,8 +45,8 @@ en: b4b85192e7287a64 zh: 82457adbaa7c2454 /deepseek-ai-dsh-cua-mcp/model-experience/external-harness-model/token-effect: - en: eea25b57964fd62e - zh: fbd23924f1562960 + en: a1e565f3662c01d9 + zh: 26467072decb772b /deepseek-ai-dsh-cua-mcp/model-experience/external-harness-model/kv-cache-effect: en: 0b0c63281111993b zh: 45716a56b5a5ad12 diff --git a/packages/experimental/cua-mcp/README.md b/packages/experimental/cua-mcp/README.md index d6ea48810f..efba38a3e1 100644 --- a/packages/experimental/cua-mcp/README.md +++ b/packages/experimental/cua-mcp/README.md @@ -157,7 +157,7 @@ The connected harness's model sees `cua_get_api_reference`, the Agent's `cua_run #### Token effect -The tool description carries the registration's execution rules, about 3,200 characters; a `cua_get_api_reference` result is the API reference, about 13,000 characters with the current macOS provider, about 3,300 tokens by the repository's four-character estimate, spent once per call. Screenshots are inline images at the provider's `screenshotTarget` size. Clients cap tool output; the documented Codex configuration raises the `cua_run_code` budget to 25,000 tokens. Clients also cap tool descriptions and server instructions: Claude Code 2.1.309 forwards the first 4,096 characters of either and appends `… [truncated]`; DSH's `dsh-mcp-client` forwards a 20,000-character description intact. The registration's description and the instructions, about 500 characters, fit that budget; the reference does not and travels as a tool result. +The tool description carries the registration's execution rules, about 3,200 characters; a `cua_get_api_reference` result is the API reference, about 13,000 characters with the current macOS provider, about 3,300 tokens by the repository's four-character estimate, spent once per call. Screenshots are inline images at the provider's `screenshotTarget` size. Clients cap tool output; the documented Codex configuration raises the `cua_run_code` budget to 25,000 tokens. Clients also cap tool descriptions and server instructions: Claude Code 2.1.309 forwards the first 4,096 characters of either and appends `… [truncated]`; DSH's `dsh-mcp-client` forwards a 20,000-character description intact. The registration's description and the instructions, about 600 characters, fit that budget; the reference does not and travels as a tool result. #### KV Cache effect diff --git a/packages/experimental/cua-mcp/README.zh.md b/packages/experimental/cua-mcp/README.zh.md index 98e7bb5a2d..a7342e3c43 100644 --- a/packages/experimental/cua-mcp/README.zh.md +++ b/packages/experimental/cua-mcp/README.zh.md @@ -157,7 +157,7 @@ patch 还以 `screenshotTarget: { longEdge: 2048, maxBytes: 2097152 }` 挂载该 #### Token 影响 -工具描述携带注册项的执行规则,约 3,200 个字符;一次 `cua_get_api_reference` 的结果就是 API 参考,使用当前 macOS 提供方时约 13,000 个字符,按仓库四字符/token 估算约 3,300 token,每次调用支付一次。截图是提供方 `screenshotTarget` 尺寸的内联图片。客户端会限制工具输出;文档给出的 Codex 配置把 `cua_run_code` 的预算提高到 25,000 token。客户端同样限制工具描述和服务器说明:Claude Code 2.1.309 对二者都只转发前 4,096 个字符并追加 `… [truncated]`;DSH 的 `dsh-mcp-client` 原样转发 20,000 个字符的描述。注册项的描述和约 500 个字符的服务器说明都在该预算之内;参考超出预算,因此作为工具结果传递。 +工具描述携带注册项的执行规则,约 3,200 个字符;一次 `cua_get_api_reference` 的结果就是 API 参考,使用当前 macOS 提供方时约 13,000 个字符,按仓库四字符/token 估算约 3,300 token,每次调用支付一次。截图是提供方 `screenshotTarget` 尺寸的内联图片。客户端会限制工具输出;文档给出的 Codex 配置把 `cua_run_code` 的预算提高到 25,000 token。客户端同样限制工具描述和服务器说明:Claude Code 2.1.309 对二者都只转发前 4,096 个字符并追加 `… [truncated]`;DSH 的 `dsh-mcp-client` 原样转发 20,000 个字符的描述。注册项的描述和约 600 个字符的服务器说明都在该预算之内;参考超出预算,因此作为工具结果传递。 #### KV Cache 影响 diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index 79d2f27618..7aa9e0534d 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -21,8 +21,8 @@ en: 3f638a4a76023fc5 zh: 515aeb5de6ae5b33 /deepseek-ai-dsh-cua/understand-the-implementation: - en: 7876bc7034fa9f83 - zh: 312ff855f94b7ef1 + en: 2956c20207126d3d + zh: 09cf710e2cd37f9b /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 2933c4c0ee..7aaf3d86f7 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -89,7 +89,7 @@ Permission responses identify their platform and report only the state that plat
Shared execution and platform ownership -A provider enables `CuaBackend.turnInputLifecycle` only after its helper accepts `taskId` and `turn` on `sendKeyEvent`, `toggleMouse`, and system `mouseMove`, and acknowledges `releaseHeldInputs({ taskId, turn })`. The shared owner blocks admission on cancellation or finalization, awaits native cancellation before independent bounded cleanup, and disables all CUA operations for the task after an unconfirmed release. Providers must record actual dispatch order, targets and routes before posting, implement explicit up and mixed reverse-order cleanup, reject stale turns, and clean only their connection on disconnect. Windows leaves this option unset until these native behaviors are implemented; it receives neither new parameters nor cleanup commands. +A provider enables `CuaBackend.turnInputLifecycle` only after its helper accepts `taskId` and `turn` on `sendKeyEvent`, `toggleMouse`, and system `mouseMove`, and acknowledges `releaseHeldInputs({ taskId, turn })`. The shared owner blocks admission on cancellation or finalization, awaits native cancellation before independent bounded cleanup, and disables all CUA operations for the task after an unconfirmed release. Providers must record actual dispatch order, targets and routes before posting, implement explicit up and mixed reverse-order cleanup, reject stale turns, and clean only their connection on disconnect. For these providers, `getCapabilities().methods` omits `sendKeyEvent` and `toggleMouse` outside an active turn. Windows leaves this option unset until these native behaviors are implemented; it receives neither new parameters nor cleanup commands. The [permission store](src/permission-store.ts) uses `storageDomain` with the configured backend. The default JSON backend writes `$DSH_HOME/storages/cua_permissions_.json`, where the digest identifies the canonical profile directory. Each authorization check opens fresh state under the profile's file lock and closes its domain afterward; native dispatch uses a separate application lock. Revocation waits for operations already admitted by another process; after it completes, every process rejects old handles. Files on different machines or PID namespaces must not share this lock. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index 55410d2087..3ffa84341b 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -89,7 +89,7 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边
共享执行与平台职责 -提供方仅在 helper 已接受 `sendKeyEvent`、`toggleMouse` 和系统 `mouseMove` 的 `taskId`、`turn` 参数,并能确认 `releaseHeldInputs({ taskId, turn })` 后,才启用 `CuaBackend.turnInputLifecycle`。共通持有方在取消或收尾时禁止新输入,等待原生取消后用独立且有超时限制的请求清理;释放未经确认时禁用该任务的全部 CUA 操作。提供方必须在派发前记录实际顺序、目标与输入方式,实现显式释放和键鼠混合反序清理,拒绝旧回合输入,并在断连时只清理本连接。Windows 在实现这些原生行为前保持此选项未设置,不接收新增参数或清理命令。 +提供方仅在 helper 已接受 `sendKeyEvent`、`toggleMouse` 和系统 `mouseMove` 的 `taskId`、`turn` 参数,并能确认 `releaseHeldInputs({ taskId, turn })` 后,才启用 `CuaBackend.turnInputLifecycle`。共通持有方在取消或收尾时禁止新输入,等待原生取消后用独立且有超时限制的请求清理;释放未经确认时禁用该任务的全部 CUA 操作。提供方必须在派发前记录实际顺序、目标与输入方式,实现显式释放和键鼠混合反序清理,拒绝旧回合输入,并在断连时只清理本连接。这些提供方在没有活动回合时,从 `getCapabilities().methods` 中省略 `sendKeyEvent` 和 `toggleMouse`。Windows 在实现这些原生行为前保持此选项未设置,不接收新增参数或清理命令。 [授权存储](src/permission-store.ts)复用 `storageDomain` 和配置的后端。默认 JSON 后端写入 `$DSH_HOME/storages/cua_permissions_.json`,摘要对应 profile 的真实目录。每次授权检查在 profile 文件锁内打开并读取最新状态,随后关闭存储域;原生操作使用单独的应用锁。撤销会等待其他进程已获准执行的操作结束;撤销完成后,各进程都拒绝旧句柄。不同电脑或 PID 命名空间不能共享这把锁。 diff --git a/packages/experimental/cua/src/turn-inputs.ts b/packages/experimental/cua/src/turn-inputs.ts index 10d4f255c5..aaee013e2c 100644 --- a/packages/experimental/cua/src/turn-inputs.ts +++ b/packages/experimental/cua/src/turn-inputs.ts @@ -15,6 +15,7 @@ class InputTurn { this.signal = AbortSignal.any([signal, this.controller.signal]) } + /** installCua retains one Agent connection until its registered cleanup closes admission here. */ track(client: NativeClient): void { this.signal.throwIfAborted() if (!this.client) { diff --git a/packages/experimental/cua/src/types.ts b/packages/experimental/cua/src/types.ts index 9501b9e77e..54af154c3b 100644 --- a/packages/experimental/cua/src/types.ts +++ b/packages/experimental/cua/src/types.ts @@ -247,8 +247,8 @@ export interface CuaApp extends CuaSurface { /** Native app API; its caller owns global bindings and variable persistence. */ export interface CuaApi { /** - * Inspect permissions without requesting them. - * @returns reported native capabilities. + * Inspect permissions without requesting them. Turn-managed providers omit explicit hold methods outside an active turn. + * @returns Reported native capabilities for this execution context. */ getCapabilities(): Promise /** diff --git a/snapshots/sdk/ptc-cancel/session.v4.jsonl b/snapshots/sdk/ptc-cancel/session.v4.jsonl index 15046419b3..037d641f20 100644 --- a/snapshots/sdk/ptc-cancel/session.v4.jsonl +++ b/snapshots/sdk/ptc-cancel/session.v4.jsonl @@ -13,10 +13,11 @@ {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Start a run_code program, call","messageSeqs":[8],"source":{"kind":"fallback"}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"ptc-cancel","name":"run_code","arguments":"{\"code\":\"await tools.job_list({}); for (;;) {}\",\"description\":\"Run until stopped\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:5}}"},"stream":[{"type":"chunk","time":1794984671734,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1794984671734,"index":0,"dt":[],"id":"ptc-cancel","name":"run_code","args":["{\"code\":\"await tools.job_list({}); for (;;) {}\",\"description\":\"Run until stopped\"}"]},{"type":"chunk","time":1794984671734,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"ptc-cancel","name":"run_code","arguments":"{\"code\":\"await tools.job_list({}); for (;;) {}\",\"description\":\"Run until stopped\"}"}}},{"type":"chunk","time":1794984671734,"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":"ptc-cancel","name":"run_code","arguments":"{\"code\":\"await tools.job_list({}); for (;;) {}\",\"description\":\"Run until stopped\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:5}}"},"stream":[{"type":"chunk","time":1794988150476,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1794988150476,"index":0,"dt":[],"id":"ptc-cancel","name":"run_code","args":["{\"code\":\"await tools.job_list({}); for (;;) {}\",\"description\":\"Run until stopped\"}"]},{"type":"chunk","time":1794988150476,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"ptc-cancel","name":"run_code","arguments":"{\"code\":\"await tools.job_list({}); for (;;) {}\",\"description\":\"Run until stopped\"}"}}},{"type":"chunk","time":1794988150476,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"ptc-cancel","name":"run_code","arguments":"{\"code\":\"await tools.job_list({}); for (;;) {}\",\"description\":\"Run until stopped\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"ptc-cancel","parentCallId":"ptc-cancel","subCallId":"ptc-cancel:ptc:1","name":"job_list","arguments":{}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"ptc-cancel","parentCallId":"ptc-cancel","subCallId":"ptc-cancel:ptc:1","name":"job_list","arguments":{},"isError":false,"content":[{"type":"text","text":"(no background jobs)"}]}} {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"ptc-cancel"},"toolCallId":"ptc-cancel","content":[{"type":"text","text":"Error: tool call aborted"}],"isError":true,"id":"{{message:6}}"},"error":{"name":"AbortError","code":"ABORTED"}},"sourceEventSeqs":[15],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} +{"type":"feedback/record","data":{"category":"other"}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"aborted","reason":{"kind":"user"}}}} diff --git a/snapshots/web/cua-run-code/code.expected.md b/snapshots/web/cua-run-code/code.expected.md index 24f68a7612..442b8ef667 100644 --- a/snapshots/web/cua-run-code/code.expected.md +++ b/snapshots/web/cua-run-code/code.expected.md @@ -3,4 +3,4 @@ - button "Wrap lines" [pressed] - button "Original JSON" - button "Copy code" - - code: "globalThis.visits = 1; var app = await cua.getApp(\"test.fixture\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\"0\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)" + - code: "globalThis.visits = 1; var app = await cua.getApp(\"test.fixture\"); await app.sendKeyEvent(\"w\", \"down\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\"0\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)" diff --git a/snapshots/web/cua-run-code/ui.expected.md b/snapshots/web/cua-run-code/ui.expected.md index 70299ccafd..d1edad4a0e 100644 --- a/snapshots/web/cua-run-code/ui.expected.md +++ b/snapshots/web/cua-run-code/ui.expected.md @@ -20,18 +20,22 @@ - text: typescript - button "Wrap lines" [pressed] - button "Copy" -- code: "globalThis.visits = 1; var app = await cua.getApp(\"test.fixture\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\"0\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)" +- code: "globalThis.visits = 1; var app = await cua.getApp(\"test.fixture\"); await app.sendKeyEvent(\"w\", \"down\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\"0\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)" - text: "OUT {\"visits\":1,\"bindings\":[\"cua\"],\"app\":\"fixture-app\",\"window\":\"7\"} sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee (1x1px, 90 bytes)" - button "Inspect" - button "Tool call cua · getCapabilities" - button "Tool call cua · getApp" +- button "Tool call cua · sendKeyEvent" - button "Tool call cua · getState" - button "Tool call cua · click" - button "Tool call cua · screenshot" - button "Code Reuse the retained application and window" +- button "Tool call cua · sendKeyEvent" - button "Tool call cua · getState" - button "Tool call cua · click" - button "Tool call cua · getState" +- button "Tool call cua · toggleMouse" +- button "Tool call cua · sendKeyEvent" - paragraph: "The retained application and window report Count: 2. The counter persisted across calls, and the program exposes only tools.cua. The screenshot was attached after the first call." - button "Copy" - button "Good response" From d86cec3093da9a4ce357f7faeef5402ddaf7af4e Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 16:05:16 +0800 Subject: [PATCH 14/73] Complete lifecycle API documentation and pin native release preconditions --- .../experimental/cua-macos/native/tests/capabilities_e2e.py | 1 + packages/experimental/cua/src/turn-inputs.ts | 5 ++++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py index 5ea6ac011b..540e89315e 100644 --- a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py +++ b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py @@ -91,6 +91,7 @@ def check_toggle_mouse(helper, owner, state_file, executable): call("activate", {"appHandle": other_app["appHandle"]}) wait_for_state(state_file, lambda s: not s["active"]) finally: + assert cursor(*outside) == outside toggle(button, "up") state = wait_for_state(state_file, lambda s: len(s["events"]) >= count + 2) events = state["events"][count:] diff --git a/packages/experimental/cua/src/turn-inputs.ts b/packages/experimental/cua/src/turn-inputs.ts index aaee013e2c..877bbf467a 100644 --- a/packages/experimental/cua/src/turn-inputs.ts +++ b/packages/experimental/cua/src/turn-inputs.ts @@ -49,7 +49,10 @@ export class CuaInputTurns { /** @param ctx - Provider scope owning the lifecycle listeners. */ constructor(private readonly ctx: Context) {} - /** @returns Exact listener disposers for the runtime effect to retain through native cleanup. */ + /** + * Install turn admission and finalization listeners. + * @returns Exact disposers for the runtime effect to retain through native cleanup. + */ *install(): Generator<() => void> { const ctx = this.ctx yield ctx.on('agent/pre-step', (event, next) => { From cddddfff8209a5e0503a735d3ff47ee09186a3c6 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 16:07:00 +0800 Subject: [PATCH 15/73] Cover enclosing context shutdown with pending native input cleanup --- packages/experimental/cua/tests/run-code-composition.spec.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/experimental/cua/tests/run-code-composition.spec.ts b/packages/experimental/cua/tests/run-code-composition.spec.ts index 5edc198b7b..0e22b54dad 100644 --- a/packages/experimental/cua/tests/run-code-composition.spec.ts +++ b/packages/experimental/cua/tests/run-code-composition.spec.ts @@ -443,7 +443,7 @@ it.each(['refusal', 'disconnect', 'timeout'] as const)('reports cleanup %s and p expect(JSON.stringify(f.agent.session.deriveMessages())).toContain('INPUT_CLEANUP_UNCONFIRMED') }) -it.each(['agent', 'provider'] as const)('awaits held input cleanup when the %s is disposed', async (owner) => { +it.each(['agent', 'provider', 'context'] as const)('awaits held input cleanup when the %s is disposed', async (owner) => { const f = await setup([holdProgram], 'macos', undefined, true, true) const thinking: PromiseWithResolvers = Promise.withResolvers() f.model.beforeStream = async (index, options) => { @@ -455,7 +455,7 @@ it.each(['agent', 'provider'] as const)('awaits held input cleanup when the %s i await thinking.promise const release = f.native.controlNext('releaseHeldInputs') let disposed = false - const closing = (owner === 'agent' ? f.handle.dispose() : f.provider.dispose()).then(() => { disposed = true }) + const closing = (owner === 'agent' ? f.handle.dispose() : owner === 'provider' ? f.provider.dispose() : f.ctx.fiber.dispose()).then(() => { disposed = true }) await release.entered try { expect(disposed).toBe(false) From efa1b999a693f0c892fa76ef7d4e30ee23327d47 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 16:20:24 +0800 Subject: [PATCH 16/73] Verify system release independently of window delivery and refresh SDK CUA --- .../native/tests/CapabilitiesFixture.swift | 5 ++++ .../native/tests/capabilities_e2e.py | 23 +++++++++++++++---- .../cua/tests/run-code-composition.spec.ts | 3 ++- snapshots/sdk/cua-run-code/session.v4.jsonl | 2 +- .../cua-run-code/system-prompt.expected.md | 2 +- 5 files changed, 28 insertions(+), 7 deletions(-) diff --git a/packages/experimental/cua-macos/native/tests/CapabilitiesFixture.swift b/packages/experimental/cua-macos/native/tests/CapabilitiesFixture.swift index 317552cb74..862608c734 100644 --- a/packages/experimental/cua-macos/native/tests/CapabilitiesFixture.swift +++ b/packages/experimental/cua-macos/native/tests/CapabilitiesFixture.swift @@ -152,6 +152,11 @@ if CommandLine.arguments.dropFirst().first == "--cursor" { print("[\(position.x),\(position.y)]") exit(0) } +if CommandLine.arguments.dropFirst().first == "--buttons" { + let values = [CGMouseButton.left, .right, .center].map { CGEventSource.buttonState(.combinedSessionState, button: $0) } + print(String(data: try! JSONSerialization.data(withJSONObject: values), encoding: .utf8)!) + exit(0) +} let statePath = CommandLine.arguments.dropFirst().first ?? Bundle.main.object(forInfoDictionaryKey: "DSHFixtureStatePath") as? String if let statePath { let application = NSApplication.shared diff --git a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py index 540e89315e..f247f6c2ed 100644 --- a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py +++ b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py @@ -123,20 +123,35 @@ def check_toggle_mouse(helper, owner, state_file, executable): events = wait_for_state(state_file, lambda s: len(s["events"]) >= count + 3)["events"][count:] assert [e["type"] for e in events] == [down, moved, up], events assert len({e["eventNumber"] for e in events}) == 1 and not events[-1]["pressedButtons"] & (1 << index), events + def wait_button(pressed): + deadline = time.monotonic() + 10 + while time.monotonic() < deadline: + buttons = json.loads(subprocess.check_output([executable, "--buttons"], text=True)) + if buttons[0] == pressed: + return + time.sleep(0.025) + raise AssertionError(f"System left button did not become {pressed}") + for ending in ("releaseHeldInputs", "disconnect"): + call("activate", owner) + wait_for_state(state_file, lambda s: s["active"] and s["keyWindow"]) + assert cursor(*inside) == inside connection = Connection(socket, key) try: app = connection.call("getApp", {"selector": str(state["pid"])}) - count = len(json.loads(state_file.read_text())["events"]) + params = {**window, "mouseButton": "left", "useSystemPointer": True} connection.call("toggleMouse", {**params, "appHandle": app["appHandle"], "direction": "down"}) - wait_for_state(state_file, lambda s: len(s["events"]) > count) + wait_button(True) call("toggleMouse", {**params, "direction": "up"}, "INVALID_ARGUMENT") + wait_button(True) + call("activate", {"appHandle": other_app["appHandle"]}) + wait_for_state(state_file, lambda s: not s["active"]) if ending != "disconnect": connection.call(ending, {}) finally: connection.close() - events = wait_for_state(state_file, lambda s: len(s["events"]) >= count + 2)["events"][count:] - assert [e["type"] for e in events] == [25, 26] and events[-1]["pressedButtons"] == 0, events + wait_button(False) + finally: run_cleanup(lambda: cursor(*original), *([lambda: stop(other)] if other else [])) diff --git a/packages/experimental/cua/tests/run-code-composition.spec.ts b/packages/experimental/cua/tests/run-code-composition.spec.ts index 0e22b54dad..36f5fbea9b 100644 --- a/packages/experimental/cua/tests/run-code-composition.spec.ts +++ b/packages/experimental/cua/tests/run-code-composition.spec.ts @@ -456,7 +456,8 @@ it.each(['agent', 'provider', 'context'] as const)('awaits held input cleanup wh const release = f.native.controlNext('releaseHeldInputs') let disposed = false const closing = (owner === 'agent' ? f.handle.dispose() : owner === 'provider' ? f.provider.dispose() : f.ctx.fiber.dispose()).then(() => { disposed = true }) - await release.entered + const first = await Promise.race([release.entered.then(() => 'cleanup'), closing.then(() => 'closed')]) + expect(first, JSON.stringify({ calls: f.native.calls, events: f.native.events, held: f.native.held })).toBe('cleanup') try { expect(disposed).toBe(false) expect(f.native.state.closedChannels).toBe(0) diff --git a/snapshots/sdk/cua-run-code/session.v4.jsonl b/snapshots/sdk/cua-run-code/session.v4.jsonl index d347b92f52..5a9d77ded0 100644 --- a/snapshots/sdk/cua-run-code/session.v4.jsonl +++ b/snapshots/sdk/cua-run-code/session.v4.jsonl @@ -18,7 +18,7 @@ {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:6}}"},"stream":[{"type":"chunk","time":1792108800000,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792108800000,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}}},{"type":"chunk","time":1792108800000,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemPointer\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemPointer\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\",\"sendKeyEvent\",\"toggleMouse\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first: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_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:3","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} diff --git a/snapshots/sdk/cua-run-code/system-prompt.expected.md b/snapshots/sdk/cua-run-code/system-prompt.expected.md index db7bd43972..b4e44f643e 100644 --- a/snapshots/sdk/cua-run-code/system-prompt.expected.md +++ b/snapshots/sdk/cua-run-code/system-prompt.expected.md @@ -72,7 +72,7 @@ Use an explicit window for screenshots. ## Simulated mouse Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; platform guidance defines their cleanup scope. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], 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. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. From 693c29bdfe9dd98b51f22a94f1f28d809e22ccf5 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 16:25:48 +0800 Subject: [PATCH 17/73] Drain native input before withdrawing program runtime dependencies --- packages/experimental/cua/README.i18n.yaml | 4 ++-- packages/experimental/cua/README.md | 2 +- packages/experimental/cua/README.zh.md | 2 +- packages/experimental/cua/src/index.ts | 5 +++-- 4 files changed, 7 insertions(+), 6 deletions(-) diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index 7aa9e0534d..b64faa7930 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -21,8 +21,8 @@ en: 3f638a4a76023fc5 zh: 515aeb5de6ae5b33 /deepseek-ai-dsh-cua/understand-the-implementation: - en: 2956c20207126d3d - zh: 09cf710e2cd37f9b + en: 42936c8d175250bd + zh: 0c20588d6e7b811d /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 7aaf3d86f7..9df1f361b8 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -89,7 +89,7 @@ Permission responses identify their platform and report only the state that plat
Shared execution and platform ownership -A provider enables `CuaBackend.turnInputLifecycle` only after its helper accepts `taskId` and `turn` on `sendKeyEvent`, `toggleMouse`, and system `mouseMove`, and acknowledges `releaseHeldInputs({ taskId, turn })`. The shared owner blocks admission on cancellation or finalization, awaits native cancellation before independent bounded cleanup, and disables all CUA operations for the task after an unconfirmed release. Providers must record actual dispatch order, targets and routes before posting, implement explicit up and mixed reverse-order cleanup, reject stale turns, and clean only their connection on disconnect. For these providers, `getCapabilities().methods` omits `sendKeyEvent` and `toggleMouse` outside an active turn. Windows leaves this option unset until these native behaviors are implemented; it receives neither new parameters nor cleanup commands. +A provider enables `CuaBackend.turnInputLifecycle` only after its helper accepts `taskId` and `turn` on `sendKeyEvent`, `toggleMouse`, and system `mouseMove`, and acknowledges `releaseHeldInputs({ taskId, turn })`. Provider unload closes input admission and awaits native cleanup before withdrawing program tools and lifecycle listeners. The shared owner blocks admission on cancellation or finalization, awaits native cancellation before independent bounded cleanup, and disables all CUA operations for the task after an unconfirmed release. Providers must record actual dispatch order, targets and routes before posting, implement explicit up and mixed reverse-order cleanup, reject stale turns, and clean only their connection on disconnect. For these providers, `getCapabilities().methods` omits `sendKeyEvent` and `toggleMouse` outside an active turn. Windows leaves this option unset until these native behaviors are implemented; it receives neither new parameters nor cleanup commands. The [permission store](src/permission-store.ts) uses `storageDomain` with the configured backend. The default JSON backend writes `$DSH_HOME/storages/cua_permissions_.json`, where the digest identifies the canonical profile directory. Each authorization check opens fresh state under the profile's file lock and closes its domain afterward; native dispatch uses a separate application lock. Revocation waits for operations already admitted by another process; after it completes, every process rejects old handles. Files on different machines or PID namespaces must not share this lock. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index 3ffa84341b..9201149552 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -89,7 +89,7 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边
共享执行与平台职责 -提供方仅在 helper 已接受 `sendKeyEvent`、`toggleMouse` 和系统 `mouseMove` 的 `taskId`、`turn` 参数,并能确认 `releaseHeldInputs({ taskId, turn })` 后,才启用 `CuaBackend.turnInputLifecycle`。共通持有方在取消或收尾时禁止新输入,等待原生取消后用独立且有超时限制的请求清理;释放未经确认时禁用该任务的全部 CUA 操作。提供方必须在派发前记录实际顺序、目标与输入方式,实现显式释放和键鼠混合反序清理,拒绝旧回合输入,并在断连时只清理本连接。这些提供方在没有活动回合时,从 `getCapabilities().methods` 中省略 `sendKeyEvent` 和 `toggleMouse`。Windows 在实现这些原生行为前保持此选项未设置,不接收新增参数或清理命令。 +提供方仅在 helper 已接受 `sendKeyEvent`、`toggleMouse` 和系统 `mouseMove` 的 `taskId`、`turn` 参数,并能确认 `releaseHeldInputs({ taskId, turn })` 后,才启用 `CuaBackend.turnInputLifecycle`。提供方卸载时先禁止新输入并等待原生清理,再移除程序工具和生命周期监听器。共通持有方在取消或收尾时禁止新输入,等待原生取消后用独立且有超时限制的请求清理;释放未经确认时禁用该任务的全部 CUA 操作。提供方必须在派发前记录实际顺序、目标与输入方式,实现显式释放和键鼠混合反序清理,拒绝旧回合输入,并在断连时只清理本连接。这些提供方在没有活动回合时,从 `getCapabilities().methods` 中省略 `sendKeyEvent` 和 `toggleMouse`。Windows 在实现这些原生行为前保持此选项未设置,不接收新增参数或清理命令。 [授权存储](src/permission-store.ts)复用 `storageDomain` 和配置的后端。默认 JSON 后端写入 `$DSH_HOME/storages/cua_permissions_.json`,摘要对应 profile 的真实目录。每次授权检查在 profile 文件锁内打开并读取最新状态,随后关闭存储域;原生操作使用单独的应用锁。撤销会等待其他进程已获准执行的操作结束;撤销完成后,各进程都拒绝旧句柄。不同电脑或 PID 命名空间不能共享这把锁。 diff --git a/packages/experimental/cua/src/index.ts b/packages/experimental/cua/src/index.ts index 31bcd317a1..ba588ab056 100644 --- a/packages/experimental/cua/src/index.ts +++ b/packages/experimental/cua/src/index.ts @@ -266,7 +266,7 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) ctx.effect(function* () { if (inputTurns) yield* inputTurns.install() yield ctx.computerUse.register(brandString('dsh-cua')) - yield async () => { + const closeNative = ctx.effect(() => async () => { lifetime.abort() const permissions = Promise.allSettled([access.dispose()]) await Promise.allSettled(pending.keys()) @@ -276,7 +276,7 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) const errors: unknown[] = [] for (const result of [...await permissions, ...results, ...releases]) if (result.status === 'rejected') errors.push(result.reason) if (errors.length > 0) ctx.logger.error(new AggregateError(errors, 'dsh-cua helper cleanup failed')) - } + }, 'dsh-cua.native-cleanup') const callNative = async (request: CuaOperation, execution: Readonly, useSystemPointer?: boolean) => { const { method, params: parsedParams } = request const params = execution.coordinates.parameters(request) @@ -446,6 +446,7 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) }, } yield installCuaTools(ctx, config, tool, guidance, programGuidance) + yield closeNative }, 'dsh-cua.runtime') } From 3e9e861ede21998b5f61526e923e49afe1fc4ac5 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 16:32:41 +0800 Subject: [PATCH 18/73] Await owned activity during root teardown and cover cross-program key holds --- .../tests/provider-lifecycle.spec.ts | 27 ++++++++++++++++++- .../cua/tests/run-code-composition.spec.ts | 4 +-- .../session/cua-run-code-ptc/session.v4.jsonl | 8 +++--- 3 files changed, 31 insertions(+), 8 deletions(-) diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index e287cb0ff0..59222e5321 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -204,7 +204,7 @@ async function executeProgram( })) } const execute = name === 'run_code' ? executeModelToolFixture : executeToolFixture - return execute(f.ctx, { agent: f.handle.agent, callId: brandString('keyboard-run'), name, + return execute(f.ctx, { agent: f.handle.agent, callId: brandString(`keyboard-${name}`), name, arguments: { code, description }, signal }) } @@ -238,6 +238,31 @@ it.each(['run_code', 'cua_run_code'] as const)('finishes a shortcut-only %s with expect(native.cleanup).not.toHaveBeenCalled() }) +it('holds a key from run_code until a later cua_run_code explicitly releases it in the same turn', async () => { + const f = await setup(undefined, true) + await thinkingTurn(f) + await selectApplication(f) + const held = new Set() + native.request.mockClear().mockImplementation(async (method, params) => { + expect(method).toBe('sendKeyEvent') + expect(params).toMatchObject({ taskId: f.handle.agent.id, turn: 1 }) + if (params.direction === 'down') held.add(String(params.key)) + else { expect(held.has(String(params.key))).toBe(true); held.delete(String(params.key)) } + return { dispatched: true } + }) + expect((await executeProgram(f, 'run_code', + "await tools.cua({ method: 'sendKeyEvent', params: { appHandle: 'app-one', key: 'w', direction: 'down' } });", 'Hold W')).isError).toBe(false) + expect(held).toEqual(new Set(['w'])) + expect(native.cleanup).not.toHaveBeenCalled() + expect((await executeProgram(f, 'cua_run_code', + "await tools.cua({ method: 'sendKeyEvent', params: { appHandle: 'app-one', key: 'w', direction: 'up' } });", 'Release W')).isError).toBe(false) + expect(held.size).toBe(0) + expect(native.cleanup).not.toHaveBeenCalled() + f.handle.agent.cancel({ kind: 'user' }) + await f.handle.agent.whenIdle() + expect(native.cleanup).toHaveBeenCalledExactlyOnceWith('releaseHeldInputs', { taskId: f.handle.agent.id, turn: 1 }) +}) + it('rejects a relative helper path before publishing computer-use operations', async () => { const ctx = new Context() onTestFinished(() => ctx.fiber.dispose()) diff --git a/packages/experimental/cua/tests/run-code-composition.spec.ts b/packages/experimental/cua/tests/run-code-composition.spec.ts index 36f5fbea9b..f16ab2770a 100644 --- a/packages/experimental/cua/tests/run-code-composition.spec.ts +++ b/packages/experimental/cua/tests/run-code-composition.spec.ts @@ -139,14 +139,12 @@ async function setup(programs: readonly string[], platform = 'macos', selectorPi ...presetFree ? {} : { setup: async (owner: Context) => { await ctx.agentPresets.mount(owner, 'standard') } }, }) const agent = handle.agent - const idle: PromiseWithResolvers = Promise.withResolvers() - ctx.on('agent/status', ({ agent: subject, status }) => { if (subject === agent && status === 'idle') idle.resolve() }) const provider = [...ctx.loader.entries()].find(entry => entry.options.id === 'cua') if (provider?.fiber === undefined) throw new Error('Loader did not activate the CUA fixture provider') return { ctx, native, guarded, model, agent, handle, provider: provider.fiber, run: () => { agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Inspect and increment the fixture counter.' }], source: { kind: 'user' } })) - return idle.promise + return agent.whenIdle() }, } } diff --git a/snapshots/session/cua-run-code-ptc/session.v4.jsonl b/snapshots/session/cua-run-code-ptc/session.v4.jsonl index fa1e688499..b8a3a6172c 100644 --- a/snapshots/session/cua-run-code-ptc/session.v4.jsonl +++ b/snapshots/session/cua-run-code-ptc/session.v4.jsonl @@ -12,8 +12,8 @@ {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"From run_code, call tools.cua_run_code t","messageSeqs":[8],"source":{"kind":"fallback"}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua_first","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"globalThis.visits = 1; var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))\\\", description: \\\"Select the fixture window and click Increment\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Select the fixture window and click Increment\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"stream":[{"type":"chunk","time":1794479327867,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794479327867,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_first","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"globalThis.visits = 1; var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))\\\", description: \\\"Select the fixture window and click Increment\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Select the fixture window and click Increment\"}"}}},{"type":"chunk","time":1794479327867,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua_first","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"globalThis.visits = 1; var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))\\\", description: \\\"Select the fixture window and click Increment\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Select the fixture window and click Increment\"}"}} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua_first","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"globalThis.visits = 1; var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"down\\\\\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))\\\", description: \\\"Select the fixture window and click Increment\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Select the fixture window and click Increment\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"stream":[{"type":"chunk","time":1794479327867,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794479327867,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_first","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"globalThis.visits = 1; var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"down\\\\\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))\\\", description: \\\"Select the fixture window and click Increment\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Select the fixture window and click Increment\"}"}}},{"type":"chunk","time":1794479327867,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua_first","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"globalThis.visits = 1; var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"down\\\\\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))\\\", description: \\\"Select the fixture window and click Increment\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Select the fixture window and click Increment\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua_run_code","arguments":{"code":"globalThis.visits = 1; var app = await cua.getApp(\"test.fixture\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\"0\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))","description":"Select the fixture window and click Increment"}}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemPointer\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\",\"sendKeyEvent\",\"toggleMouse\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} @@ -27,8 +27,8 @@ {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"cua_first"},"toolCallId":"cua_first","content":[{"type":"text","text":"{\"cuaTools\":[\"cua_run_code\"],\"logs\":[\"{\\\"visits\\\":1,\\\"bindings\\\":[\\\"cua\\\"],\\\"app\\\":\\\"fixture-app\\\",\\\"window\\\":\\\"7\\\"}\\n\"]}\n"}],"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_reuse","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\\\", description: \\\"Reuse the retained application and window\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Reuse the retained application and window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"stream":[{"type":"chunk","time":1794479328103,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794479328103,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_reuse","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\\\", description: \\\"Reuse the retained application and window\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Reuse the retained application and window\"}"}}},{"type":"chunk","time":1794479328103,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":2,"callId":"cua_reuse","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\\\", description: \\\"Reuse the retained application and window\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Reuse the retained application and window\"}"}} +{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua_reuse","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"up\\\\\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\\\", description: \\\"Reuse the retained application and window\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Reuse the retained application and window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"stream":[{"type":"chunk","time":1794479328103,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794479328103,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_reuse","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"up\\\\\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\\\", description: \\\"Reuse the retained application and window\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Reuse the retained application and window\"}"}}},{"type":"chunk","time":1794479328103,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":2,"callId":"cua_reuse","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"up\\\\\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\\\", description: \\\"Reuse the retained application and window\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Reuse the retained application and window\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:1","name":"cua_run_code","arguments":{"code":"globalThis.visits++; await win.getAccessibilityTree(); await win.click(\"0\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))","description":"Reuse the retained application and window"}}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse:ptc:1","subCallId":"cua_reuse:ptc:1:ptc:1","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse:ptc:1","subCallId":"cua_reuse:ptc:1:ptc:1","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"snapshotId\":\"fixture-snapshot-2\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 1\\\"\",\"windows\":[{\"windowId\":\"7\",\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} From 72ac4b5d57b36083f1947eddc17a8a2a665952f1 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 16:40:20 +0800 Subject: [PATCH 19/73] Preserve subcall settlement before connection close and record PTC held keys --- packages/experimental/cua/README.i18n.yaml | 4 +- packages/experimental/cua/README.md | 2 +- packages/experimental/cua/README.zh.md | 2 +- packages/experimental/cua/src/index.ts | 5 +-- .../session/cua-run-code-ptc/session.v4.jsonl | 40 ++++++++++--------- 5 files changed, 28 insertions(+), 25 deletions(-) diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index b64faa7930..74ff8be173 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -21,8 +21,8 @@ en: 3f638a4a76023fc5 zh: 515aeb5de6ae5b33 /deepseek-ai-dsh-cua/understand-the-implementation: - en: 42936c8d175250bd - zh: 0c20588d6e7b811d + en: dc47468ea4cd1bca + zh: 9739728015c70810 /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 9df1f361b8..fa8177cecf 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -89,7 +89,7 @@ Permission responses identify their platform and report only the state that plat
Shared execution and platform ownership -A provider enables `CuaBackend.turnInputLifecycle` only after its helper accepts `taskId` and `turn` on `sendKeyEvent`, `toggleMouse`, and system `mouseMove`, and acknowledges `releaseHeldInputs({ taskId, turn })`. Provider unload closes input admission and awaits native cleanup before withdrawing program tools and lifecycle listeners. The shared owner blocks admission on cancellation or finalization, awaits native cancellation before independent bounded cleanup, and disables all CUA operations for the task after an unconfirmed release. Providers must record actual dispatch order, targets and routes before posting, implement explicit up and mixed reverse-order cleanup, reject stale turns, and clean only their connection on disconnect. For these providers, `getCapabilities().methods` omits `sendKeyEvent` and `toggleMouse` outside an active turn. Windows leaves this option unset until these native behaviors are implemented; it receives neither new parameters nor cleanup commands. +A provider enables `CuaBackend.turnInputLifecycle` only after its helper accepts `taskId` and `turn` on `sendKeyEvent`, `toggleMouse`, and system `mouseMove`, and acknowledges `releaseHeldInputs({ taskId, turn })`. Provider unload retains lifecycle listeners until program calls and native cleanup have settled. The shared owner blocks admission on cancellation or finalization, awaits native cancellation before independent bounded cleanup, and disables all CUA operations for the task after an unconfirmed release. Providers must record actual dispatch order, targets and routes before posting, implement explicit up and mixed reverse-order cleanup, reject stale turns, and clean only their connection on disconnect. For these providers, `getCapabilities().methods` omits `sendKeyEvent` and `toggleMouse` outside an active turn. Windows leaves this option unset until these native behaviors are implemented; it receives neither new parameters nor cleanup commands. The [permission store](src/permission-store.ts) uses `storageDomain` with the configured backend. The default JSON backend writes `$DSH_HOME/storages/cua_permissions_.json`, where the digest identifies the canonical profile directory. Each authorization check opens fresh state under the profile's file lock and closes its domain afterward; native dispatch uses a separate application lock. Revocation waits for operations already admitted by another process; after it completes, every process rejects old handles. Files on different machines or PID namespaces must not share this lock. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index 9201149552..9f4d6fc7f0 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -89,7 +89,7 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边
共享执行与平台职责 -提供方仅在 helper 已接受 `sendKeyEvent`、`toggleMouse` 和系统 `mouseMove` 的 `taskId`、`turn` 参数,并能确认 `releaseHeldInputs({ taskId, turn })` 后,才启用 `CuaBackend.turnInputLifecycle`。提供方卸载时先禁止新输入并等待原生清理,再移除程序工具和生命周期监听器。共通持有方在取消或收尾时禁止新输入,等待原生取消后用独立且有超时限制的请求清理;释放未经确认时禁用该任务的全部 CUA 操作。提供方必须在派发前记录实际顺序、目标与输入方式,实现显式释放和键鼠混合反序清理,拒绝旧回合输入,并在断连时只清理本连接。这些提供方在没有活动回合时,从 `getCapabilities().methods` 中省略 `sendKeyEvent` 和 `toggleMouse`。Windows 在实现这些原生行为前保持此选项未设置,不接收新增参数或清理命令。 +提供方仅在 helper 已接受 `sendKeyEvent`、`toggleMouse` 和系统 `mouseMove` 的 `taskId`、`turn` 参数,并能确认 `releaseHeldInputs({ taskId, turn })` 后,才启用 `CuaBackend.turnInputLifecycle`。提供方卸载时保留生命周期监听器,直到程序调用和原生清理都已结束。共通持有方在取消或收尾时禁止新输入,等待原生取消后用独立且有超时限制的请求清理;释放未经确认时禁用该任务的全部 CUA 操作。提供方必须在派发前记录实际顺序、目标与输入方式,实现显式释放和键鼠混合反序清理,拒绝旧回合输入,并在断连时只清理本连接。这些提供方在没有活动回合时,从 `getCapabilities().methods` 中省略 `sendKeyEvent` 和 `toggleMouse`。Windows 在实现这些原生行为前保持此选项未设置,不接收新增参数或清理命令。 [授权存储](src/permission-store.ts)复用 `storageDomain` 和配置的后端。默认 JSON 后端写入 `$DSH_HOME/storages/cua_permissions_.json`,摘要对应 profile 的真实目录。每次授权检查在 profile 文件锁内打开并读取最新状态,随后关闭存储域;原生操作使用单独的应用锁。撤销会等待其他进程已获准执行的操作结束;撤销完成后,各进程都拒绝旧句柄。不同电脑或 PID 命名空间不能共享这把锁。 diff --git a/packages/experimental/cua/src/index.ts b/packages/experimental/cua/src/index.ts index ba588ab056..31bcd317a1 100644 --- a/packages/experimental/cua/src/index.ts +++ b/packages/experimental/cua/src/index.ts @@ -266,7 +266,7 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) ctx.effect(function* () { if (inputTurns) yield* inputTurns.install() yield ctx.computerUse.register(brandString('dsh-cua')) - const closeNative = ctx.effect(() => async () => { + yield async () => { lifetime.abort() const permissions = Promise.allSettled([access.dispose()]) await Promise.allSettled(pending.keys()) @@ -276,7 +276,7 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) const errors: unknown[] = [] for (const result of [...await permissions, ...results, ...releases]) if (result.status === 'rejected') errors.push(result.reason) if (errors.length > 0) ctx.logger.error(new AggregateError(errors, 'dsh-cua helper cleanup failed')) - }, 'dsh-cua.native-cleanup') + } const callNative = async (request: CuaOperation, execution: Readonly, useSystemPointer?: boolean) => { const { method, params: parsedParams } = request const params = execution.coordinates.parameters(request) @@ -446,7 +446,6 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) }, } yield installCuaTools(ctx, config, tool, guidance, programGuidance) - yield closeNative }, 'dsh-cua.runtime') } diff --git a/snapshots/session/cua-run-code-ptc/session.v4.jsonl b/snapshots/session/cua-run-code-ptc/session.v4.jsonl index b8a3a6172c..c56c1f134b 100644 --- a/snapshots/session/cua-run-code-ptc/session.v4.jsonl +++ b/snapshots/session/cua-run-code-ptc/session.v4.jsonl @@ -12,34 +12,38 @@ {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"From run_code, call tools.cua_run_code t","messageSeqs":[8],"source":{"kind":"fallback"}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua_first","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"globalThis.visits = 1; var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"down\\\\\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))\\\", description: \\\"Select the fixture window and click Increment\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Select the fixture window and click Increment\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"stream":[{"type":"chunk","time":1794479327867,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794479327867,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_first","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"globalThis.visits = 1; var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"down\\\\\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))\\\", description: \\\"Select the fixture window and click Increment\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Select the fixture window and click Increment\"}"}}},{"type":"chunk","time":1794479327867,"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_first","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"globalThis.visits = 1; var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"down\\\\\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))\\\", description: \\\"Select the fixture window and click Increment\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Select the fixture window and click Increment\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"stream":[{"type":"chunk","time":1794990891271,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794990891272,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_first","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"globalThis.visits = 1; var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"down\\\\\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))\\\", description: \\\"Select the fixture window and click Increment\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Select the fixture window and click Increment\"}"}}},{"type":"chunk","time":1794990891272,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua_first","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"globalThis.visits = 1; var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"down\\\\\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))\\\", description: \\\"Select the fixture window and click Increment\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Select the fixture window and click Increment\"}"}} -{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua_run_code","arguments":{"code":"globalThis.visits = 1; var app = await cua.getApp(\"test.fixture\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\"0\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))","description":"Select the fixture window and click Increment"}}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua_run_code","arguments":{"code":"globalThis.visits = 1; var app = await cua.getApp(\"test.fixture\"); await app.sendKeyEvent(\"w\", \"down\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\"0\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))","description":"Select the fixture window and click Increment"}}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemPointer\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\",\"sendKeyEvent\",\"toggleMouse\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1: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_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:3","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:3","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"snapshotId\":\"fixture-snapshot-1\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 0\\\"\",\"windows\":[{\"windowId\":\"7\",\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} -{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:4","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-1","elementId":"0"}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:4","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-1","elementId":"0"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua_run_code","arguments":{"code":"globalThis.visits = 1; var app = await cua.getApp(\"test.fixture\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\"0\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))","description":"Select the fixture window and click Increment"},"isError":false,"content":[{"type":"text","text":"{\"visits\":1,\"bindings\":[\"cua\"],\"app\":\"fixture-app\",\"window\":\"7\"}\n"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:3","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"w","direction":"down"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:3","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"w","direction":"down"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:4","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:4","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"snapshotId\":\"fixture-snapshot-1\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 0\\\"\",\"windows\":[{\"windowId\":\"7\",\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:5","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-1","elementId":"0"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:5","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-1","elementId":"0"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua_run_code","arguments":{"code":"globalThis.visits = 1; var app = await cua.getApp(\"test.fixture\"); await app.sendKeyEvent(\"w\", \"down\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\"0\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))","description":"Select the fixture window and click Increment"},"isError":false,"content":[{"type":"text","text":"{\"visits\":1,\"bindings\":[\"cua\"],\"app\":\"fixture-app\",\"window\":\"7\"}\n"}]}} {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"cua_first"},"toolCallId":"cua_first","content":[{"type":"text","text":"{\"cuaTools\":[\"cua_run_code\"],\"logs\":[\"{\\\"visits\\\":1,\\\"bindings\\\":[\\\"cua\\\"],\\\"app\\\":\\\"fixture-app\\\",\\\"window\\\":\\\"7\\\"}\\n\"]}\n"}],"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_reuse","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"up\\\\\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\\\", description: \\\"Reuse the retained application and window\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Reuse the retained application and window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"stream":[{"type":"chunk","time":1794479328103,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794479328103,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_reuse","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"up\\\\\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\\\", description: \\\"Reuse the retained application and window\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Reuse the retained application and window\"}"}}},{"type":"chunk","time":1794479328103,"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_reuse","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"up\\\\\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\\\", description: \\\"Reuse the retained application and window\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Reuse the retained application and window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"stream":[{"type":"chunk","time":1794990891775,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794990891775,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_reuse","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"up\\\\\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\\\", description: \\\"Reuse the retained application and window\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Reuse the retained application and window\"}"}}},{"type":"chunk","time":1794990891775,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"cua_reuse","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"up\\\\\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\\\", description: \\\"Reuse the retained application and window\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Reuse the retained application and window\"}"}} -{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:1","name":"cua_run_code","arguments":{"code":"globalThis.visits++; await win.getAccessibilityTree(); await win.click(\"0\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))","description":"Reuse the retained application and window"}}} -{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse:ptc:1","subCallId":"cua_reuse:ptc:1:ptc:1","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse:ptc:1","subCallId":"cua_reuse:ptc:1:ptc:1","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"snapshotId\":\"fixture-snapshot-2\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 1\\\"\",\"windows\":[{\"windowId\":\"7\",\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} -{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse:ptc:1","subCallId":"cua_reuse:ptc:1:ptc:2","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-2","elementId":"0"}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse:ptc:1","subCallId":"cua_reuse:ptc:1:ptc:2","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-2","elementId":"0"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} -{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse:ptc:1","subCallId":"cua_reuse:ptc:1:ptc:3","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse:ptc:1","subCallId":"cua_reuse:ptc:1:ptc:3","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"snapshotId\":\"fixture-snapshot-3\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 2\\\"\",\"windows\":[{\"windowId\":\"7\",\"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_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:1","name":"cua_run_code","arguments":{"code":"globalThis.visits++; await win.getAccessibilityTree(); await win.click(\"0\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))","description":"Reuse the retained application and window"},"isError":false,"content":[{"type":"text","text":"{\"visits\":2,\"app\":\"fixture-app\",\"window\":\"7\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 2\\\"\",\"bindings\":[\"cua\"]}\n"}]}} -{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"cua_reuse"},"toolCallId":"cua_reuse","content":[{"type":"text","text":"{\"cuaTools\":[\"cua_run_code\"],\"logs\":[\"{\\\"visits\\\":2,\\\"app\\\":\\\"fixture-app\\\",\\\"window\\\":\\\"7\\\",\\\"tree\\\":\\\"- [0] AXButton \\\\\\\"Increment\\\\\\\"\\\\n- AXStaticText \\\\\\\"Count: 2\\\\\\\"\\\",\\\"bindings\\\":[\\\"cua\\\"]}\\n\"]}\n"}],"isError":false,"id":"{{message:7}}"}},"sourceEventSeqs":[29],"surfaceOp":"append"} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:1","name":"cua_run_code","arguments":{"code":"await app.sendKeyEvent(\"w\", \"up\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\"0\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))","description":"Reuse the retained application and window"}}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse:ptc:1","subCallId":"cua_reuse:ptc:1:ptc:1","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"w","direction":"up"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse:ptc:1","subCallId":"cua_reuse:ptc:1:ptc:1","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"w","direction":"up"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse:ptc:1","subCallId":"cua_reuse:ptc:1:ptc:2","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse:ptc:1","subCallId":"cua_reuse:ptc:1:ptc:2","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"snapshotId\":\"fixture-snapshot-2\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 1\\\"\",\"windows\":[{\"windowId\":\"7\",\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse:ptc:1","subCallId":"cua_reuse:ptc:1:ptc:3","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-2","elementId":"0"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse:ptc:1","subCallId":"cua_reuse:ptc:1:ptc:3","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-2","elementId":"0"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse:ptc:1","subCallId":"cua_reuse:ptc:1:ptc:4","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse:ptc:1","subCallId":"cua_reuse:ptc:1:ptc:4","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"snapshotId\":\"fixture-snapshot-3\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 2\\\"\",\"windows\":[{\"windowId\":\"7\",\"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_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:1","name":"cua_run_code","arguments":{"code":"await app.sendKeyEvent(\"w\", \"up\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\"0\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))","description":"Reuse the retained application and window"},"isError":false,"content":[{"type":"text","text":"{\"visits\":2,\"app\":\"fixture-app\",\"window\":\"7\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 2\\\"\",\"bindings\":[\"cua\"]}\n"}]}} +{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"cua_reuse"},"toolCallId":"cua_reuse","content":[{"type":"text","text":"{\"cuaTools\":[\"cua_run_code\"],\"logs\":[\"{\\\"visits\\\":2,\\\"app\\\":\\\"fixture-app\\\",\\\"window\\\":\\\"7\\\",\\\"tree\\\":\\\"- [0] AXButton \\\\\\\"Increment\\\\\\\"\\\\n- AXStaticText \\\\\\\"Count: 2\\\\\\\"\\\",\\\"bindings\\\":[\\\"cua\\\"]}\\n\"]}\n"}],"isError":false,"id":"{{message:7}}"}},"sourceEventSeqs":[31],"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":"text","text":"Both programs ran through tools.cua_run_code inside run_code. The retained window reports Count: 2, the counter persisted across calls, run_code exposes cua_run_code as its only CUA tool, and each nested program can call only tools.cua."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:8}}"},"stream":[{"type":"chunk","time":1794479328211,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1794479328211,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Both programs ran through tools.cua_run_code inside run_code. The retained window reports Count: 2, the counter persisted across calls, run_code exposes cua_run_code as its only CUA tool, and each nested program can call only tools.cua."}}},{"type":"chunk","time":1794479328211,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"text","text":"Both programs ran through tools.cua_run_code inside run_code. The retained window reports Count: 2, the counter persisted across calls, run_code exposes cua_run_code as its only CUA tool, and each nested program can call only tools.cua."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:8}}"},"stream":[{"type":"chunk","time":1794990892006,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1794990892006,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Both programs ran through tools.cua_run_code inside run_code. The retained window reports Count: 2, the counter persisted across calls, run_code exposes cua_run_code as its only CUA tool, and each nested program can call only tools.cua."}}},{"type":"chunk","time":1794990892006,"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"}}} From 5f9bbdd6362c0c803fc19046a2c187e46628ff17 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 17:02:00 +0800 Subject: [PATCH 20/73] Narrow native fixture key names before tracking held input --- .../experimental/cua-macos/tests/provider-lifecycle.spec.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index 59222e5321..8da8ef0b51 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -246,8 +246,10 @@ it('holds a key from run_code until a later cua_run_code explicitly releases it native.request.mockClear().mockImplementation(async (method, params) => { expect(method).toBe('sendKeyEvent') expect(params).toMatchObject({ taskId: f.handle.agent.id, turn: 1 }) - if (params.direction === 'down') held.add(String(params.key)) - else { expect(held.has(String(params.key))).toBe(true); held.delete(String(params.key)) } + const key = params.key + if (typeof key !== 'string') throw new Error('The native fixture requires a key name') + if (params.direction === 'down') held.add(key) + else { expect(held.has(key)).toBe(true); held.delete(key) } return { dispatched: true } }) expect((await executeProgram(f, 'run_code', From fb64f7d0bf1a809c9a8f7778a42b75800e8628bb Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 17:16:20 +0800 Subject: [PATCH 21/73] Refresh shipped MCP profile instructions and API reference expectations --- apps/cli/tests/profiles/cua-mcp/expected/instructions.txt | 2 +- apps/cli/tests/profiles/cua-mcp/expected/reference.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/cli/tests/profiles/cua-mcp/expected/instructions.txt b/apps/cli/tests/profiles/cua-mcp/expected/instructions.txt index 4ae508c48b..3414fe6ee5 100644 --- a/apps/cli/tests/profiles/cua-mcp/expected/instructions.txt +++ b/apps/cli/tests/profiles/cua-mcp/expected/instructions.txt @@ -1 +1 @@ -DeepSeek Harness Computer Use: observe and operate desktop applications on this machine. Start every conversation by calling cua_get_api_reference: it returns the complete cua API reference, and programs written without it guess the API wrong. Then call cua_run_code with a TypeScript program that uses the global cua object; program state persists across calls on this connection. A call may ask the user for application or pointer consent before it proceeds. Call cua_reset to discard program state. +DeepSeek Harness Computer Use: observe and operate desktop applications on this machine. Start every conversation by calling cua_get_api_reference: it returns the complete cua API reference, and programs written without it guess the API wrong. Then call cua_run_code with a TypeScript program that uses the global cua object; program state persists across calls on this connection. A call may ask the user for application or pointer consent before it proceeds. Call cua_reset to discard program state. On macOS, MCP programs cannot hold keys or mouse buttons with explicit down events. Use pressKey, click, or drag. diff --git a/apps/cli/tests/profiles/cua-mcp/expected/reference.md b/apps/cli/tests/profiles/cua-mcp/expected/reference.md index ea7301ee1b..ada8d5930e 100644 --- a/apps/cli/tests/profiles/cua-mcp/expected/reference.md +++ b/apps/cli/tests/profiles/cua-mcp/expected/reference.md @@ -38,7 +38,7 @@ Use an explicit window for screenshots. ## Simulated mouse Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; platform guidance defines their cleanup scope. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], 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. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. From b13a25d49cb3b859dadd53b6df00dd2f08ee6da2 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 17:40:46 +0800 Subject: [PATCH 22/73] Refresh retained-script guidance and keep the scoped-input decision current --- .../2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml | 8 ++++---- .../2026-11-05-cua-scoped-surfaces-and-input.md | 4 ++-- .../2026-11-05-cua-scoped-surfaces-and-input.zh.md | 4 ++-- packages/experimental/cua-macos/README.i18n.yaml | 4 ++-- packages/experimental/cua-macos/README.md | 2 +- packages/experimental/cua-macos/README.zh.md | 2 +- .../session/ptc-script-retained/system-prompt.expected.md | 4 ++-- 7 files changed, 14 insertions(+), 14 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 81912accfe..c2abf0a1c3 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,11 +9,11 @@ en: f72db0b79aa02fb5 zh: b91c1f177dc93ab4 /agent-note-cua-scoped-surfaces-and-separated-input-capabilities/decision: - en: 41fd533d5be7642b - zh: c6fcbabec22bdbb7 + en: b4814d1d835a27d0 + zh: d398a39c2d75756f /agent-note-cua-scoped-surfaces-and-separated-input-capabilities/alternatives-considered: en: 32c970ae153e0f6c zh: 8431be0a10ffed15 /agent-note-cua-scoped-surfaces-and-separated-input-capabilities/consequences: - en: c4b12ca80865e670 - zh: 396426fad0105eaa + en: 3a12a64b45e17f51 + zh: 28627d190a21b5b9 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 6d9aea0408..2e021166cb 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 @@ -12,7 +12,7 @@ Application and window objects share accessibility operations, but only an expli `CuaSurface` declares operations shared by application and window objects; `CuaApp` and `CuaWindow` extend it with their own operations. One base factory builds the surface, and the derived factories inject scope parameters plus `requireAccessibility` and `requireKeyboard` checks. The shared base never branches on a capability that exists only for applications. -Provider startup capabilities are static. Platform, supported methods, application-level accessibility, keyboard scopes, browser support, and coordinate space are fixed when the provider is installed. The native `getCapabilities` RPC reports runtime permissions and session lock only; `installCua` merges the two layers for the model-visible result. The neutral RPC is a common operation representation, not a capability inventory; provider guidance names the actions its platform supports. +Provider startup capabilities are static. Platform, supported methods, application-level accessibility, keyboard scopes, browser support, and coordinate space are fixed when the provider is installed. The native `getCapabilities` RPC reports runtime permissions and session lock only; `installCua` merges the two layers for the model-visible result and omits turn-managed hold methods when the caller has no active turn. The neutral RPC is a common operation representation, not a capability inventory; provider guidance names the actions its platform supports. 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. @@ -34,6 +34,6 @@ Within one API instance, the object facade keeps one current accessibility snaps Element IDs belong to the application's current accessibility snapshot. Reading one window replaces the facade’s current snapshot for that application, so callers observe again and confirm the IDs they use. The new read does not guarantee that an old string is rejected or that an ID changes; callers must not assume an older ID still identifies the same control. Pointer input and screenshots require an explicit window object; callers enumerate windows first. -Keyboard behavior follows the provider's supported scopes. A caller that uses `sendKeyEvent` owns the down/up pairing, during execution. macOS releases that run’s remaining keys when the program ends or the user pauses it. Keyboard modifier names are provider-defined, so the same string may have different support across providers. +Keyboard behavior follows the provider's supported scopes. A caller that uses `sendKeyEvent` controls its down/up pairing. macOS holds explicit downs across programs within an active turn and releases remaining keys and mouse buttons together when the turn completes, fails, or is stopped. Keyboard modifier names are provider-defined, so the same string may have different support across providers. Provider guidance owns the list of supported actions. Adding a method to the shared schema does not claim that every provider implements it, and the merged `getCapabilities` result remains the runtime source for permissions and session lock. 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 ceed375ff3..7f62dbb167 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 @@ -12,7 +12,7 @@ Status: implemented `CuaSurface` 声明应用对象与窗口对象共享的操作;`CuaApp` 与 `CuaWindow` 通过扩展它增加各自的操作。一个基类工厂负责构建表面,派生工厂注入作用域参数以及 `requireAccessibility`、`requireKeyboard` 检查。共享基类从不为只属于应用的能力分支。 -Provider 的启动能力是静态的。平台、支持的方法、应用级辅助功能、键盘作用域、浏览器支持和坐标空间在安装 provider 时固定。原生 `getCapabilities` RPC 只报告运行时权限和会话锁定状态;`installCua` 为模型可见结果合并两层。中立的 RPC 是通用操作表示,不是能力清单;provider 指导文本说明其平台支持的动作。 +Provider 的启动能力是静态的。平台、支持的方法、应用级辅助功能、键盘作用域、浏览器支持和坐标空间在安装 provider 时固定。原生 `getCapabilities` RPC 只报告运行时权限和会话锁定状态;`installCua` 为模型可见结果合并两层,并在调用方没有活动回合时省略按回合管理的持有方法。中立的 RPC 是通用操作表示,不是能力清单;provider 指导文本说明其平台支持的动作。 键盘输入把按键与修饰键分开:`pressKey(key, modifiers?)` 在按住所列修饰键时按下并释放一个键,其键盘修饰键列表是 provider 定义的普通字符串数组。`sendKeyEvent(key, direction)` 只发送一次按下或抬起,不隐式发送相反事件。因此调用方可以保持修饰键或拆分手势;两个方法都不接受组合键字符串,共享 schema 也不枚举平台按键名。 @@ -34,6 +34,6 @@ Provider 的启动能力是静态的。平台、支持的方法、应用级辅 元素 ID 属于应用当前的辅助功能快照。读取一个窗口会替换门面对该应用的当前快照,因此调用方需要重新观察并确认要使用的 ID。新的读取不保证拒绝旧字符串,也不保证 ID 会改变;调用方不得假定旧 ID 仍指向同一控件。指针输入和截图都要求显式的窗口对象;调用方先枚举窗口。 -键盘行为遵循 provider 支持的作用域。使用 `sendKeyEvent` 的调用方负责按下与抬起的配对,在 macOS 上,程序结束或用户暂停时会释放本次执行仍按着的键。键盘修饰键名称由 provider 定义,同一字符串在不同 provider 上可能支持不同。 +键盘行为遵循 provider 支持的作用域。使用 `sendKeyEvent` 的调用方控制按下与抬起的配对。在 macOS 上,显式按下可在活动回合内跨程序保持;回合完成、失败或停止时统一释放剩余键盘键和鼠标按钮。键盘修饰键名称由 provider 定义,同一字符串在不同 provider 上可能支持不同。 Provider 指导文本负责支持动作的清单。把方法加入共享 schema 并不表示每个 provider 都已实现它;合并后的 `getCapabilities` 结果仍是权限和会话锁定状态的运行时来源。 diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index 58534708cc..e5887824c9 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -45,8 +45,8 @@ en: a2c9acb5a4320dda zh: e8d1586af60215c4 /deepseek-ai-dsh-cua-macos/known-limitations-and-deferred-work: - en: dd03900c0fafe3be - zh: 56e011ce9a21e12c + en: fa3bbb2690fb592c + zh: 45177218316e2954 /deepseek-ai-dsh-cua-macos/known-limitations-and-deferred-work/dev-note: en: b836f01bd0bceb4a zh: 8122fa08b2aa95fa diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index 142c04a162..340b17510b 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -263,7 +263,7 @@ Tool results append to Session history. Changing plugin configuration or tool pr The native operation deadline (`timeoutMs`), per-AX-call timeout (`axTimeoutMs`), and response size limit (`maxResponseBytes`) still apply to larger tree reads. -The queue orders individual native requests. Holding an app object does not reserve its application across a Session; [continuous interaction](../../../.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.md) grants no cross-call ownership. Capture RPCs that never return occupy the single capture slot; creating new app objects does not reset that system connection. +The queue orders individual native requests. Holding an app object does not reserve its application across a Session; [continuous interaction](../../../.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.md) does not reserve an application across calls. Capture RPCs that never return occupy the single capture slot; creating new app objects does not reset that system connection. diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 8a6e23fb2a..a122836cdf 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -263,7 +263,7 @@ Only if the task cannot be completed without moving the user’s pointer, call a 读取较大的树仍受原生操作超时(`timeoutMs`)、单次 AX 调用超时(`axTimeoutMs`)和响应大小限制(`maxResponseBytes`)约束。 -队列只排序单次原生请求。持有 app 对象不会为 Session 保留应用,[连续交互](../../../.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.zh.md)不分配跨调用所有权。一直不返回的系统截图 RPC 会占用唯一捕获槽位,重新创建 app 对象不会重置该系统连接。 +队列只排序单次原生请求。持有 app 对象不会为 Session 保留应用,[连续交互](../../../.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.zh.md)不在调用之间独占应用。一直不返回的系统截图 RPC 会占用唯一捕获槽位,重新创建 app 对象不会重置该系统连接。 diff --git a/snapshots/session/ptc-script-retained/system-prompt.expected.md b/snapshots/session/ptc-script-retained/system-prompt.expected.md index 9db6c644a2..64e5e36174 100644 --- a/snapshots/session/ptc-script-retained/system-prompt.expected.md +++ b/snapshots/session/ptc-script-retained/system-prompt.expected.md @@ -77,7 +77,7 @@ Leave useSystemPointer unset for ordinary mouseMove, drag, and toggleMouse calls Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemPointer?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemPointer omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemPointer?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemPointer: true on both down and up. Physical moves can then drag, including your own mouse movements. The turn ending or the connection closing releases a remaining system hold. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemPointer?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; platform guidance defines their cleanup scope. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemPointer: true on down. Up uses the input route and window saved by down. Physical moves can then drag, including your own mouse movements. Both routes hold across programs in the same turn and release with held keys when the turn ends. click and drag release their own buttons within the operation. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], 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. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying. - 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. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemPointer?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control. An explicit system drag shares the session decision with mouseMove and holds the chosen button along the path in the unobscured foreground window. @@ -89,7 +89,7 @@ Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - 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?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across run_code and cua_run_code calls in the same turn, for example W down, D down, D up, W up. Send 'up' to release it immediately at its original recipient. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. A program returning or throwing keeps its holds while the turn continues. When the turn completes, fails, or is stopped, macOS releases remaining keys and mouse buttons together in reverse press order. pressKey and typeText still release their own presses within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. From 6d0411b5ec98f2f9f6e27967a7cb4d1b8659eb76 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 18:16:59 +0800 Subject: [PATCH 23/73] Keep turn input cleanup inside CUA after turn/end --- docs/agent-lifecycle.md | 1 - docs/agent-lifecycle.zh.md | 1 - docs/architecture.i18n.yaml | 4 +- docs/architecture.md | 3 +- docs/architecture.zh.md | 3 +- docs/event-producer-consumer.md | 7 +- docs/event-producer-consumer.zh.md | 7 +- docs/subsystems/core.md | 24 ----- docs/subsystems/core.zh.md | 24 ----- .../cua-turn-inputs/guide.i18n.yaml | 8 +- .../v0.2.2-rc.4/cua-turn-inputs/guide.md | 4 +- .../v0.2.2-rc.4/cua-turn-inputs/guide.zh.md | 4 +- packages/core/agent-loop/README.i18n.yaml | 4 +- packages/core/agent-loop/README.md | 2 - packages/core/agent-loop/README.zh.md | 2 - packages/core/agent-loop/src/agent.ts | 19 +--- .../tests/contract-regressions.spec.ts | 92 ------------------- packages/core/agent/README.i18n.yaml | 4 +- packages/core/agent/README.md | 2 +- packages/core/agent/README.zh.md | 2 +- packages/core/agent/src/dispatch.ts | 12 --- packages/core/agent/src/runtime-types.ts | 11 --- .../experimental/cua-macos/README.i18n.yaml | 4 +- packages/experimental/cua-macos/README.md | 2 +- packages/experimental/cua-macos/README.zh.md | 2 +- packages/experimental/cua/README.i18n.yaml | 4 +- packages/experimental/cua/README.md | 2 +- packages/experimental/cua/README.zh.md | 2 +- packages/experimental/cua/src/index.ts | 1 + packages/experimental/cua/src/turn-inputs.ts | 46 ++++++++-- .../cua/tests/run-code-composition.spec.ts | 79 +++++++++++++--- .../extensions/tool-cordis/src/api-catalog.ts | 8 -- scripts/gen-doc-graphs.ts | 1 - snapshots/sdk/ptc-cancel/cancel.mjs | 4 - snapshots/sdk/ptc-cancel/session.v4.jsonl | 3 +- snapshots/sdk/text-turn/feedback-producer.mjs | 5 +- .../text-turn/notifications.expected.jsonl | 2 +- snapshots/sdk/text-turn/session.v4.jsonl | 2 +- 38 files changed, 148 insertions(+), 259 deletions(-) diff --git a/docs/agent-lifecycle.md b/docs/agent-lifecycle.md index 858718ef0c..8dea01c100 100644 --- a/docs/agent-lifecycle.md +++ b/docs/agent-lifecycle.md @@ -78,7 +78,6 @@ sequenceDiagram end end end - Driver->>Hooks: agent/turn-finalizing await all resource finalizers Driver->>Session: turn/end Driver-->>SDK: agent/status idle ``` diff --git a/docs/agent-lifecycle.zh.md b/docs/agent-lifecycle.zh.md index 30347102fb..66c5dd90bf 100644 --- a/docs/agent-lifecycle.zh.md +++ b/docs/agent-lifecycle.zh.md @@ -80,7 +80,6 @@ sequenceDiagram end end end - Driver->>Hooks: agent/turn-finalizing await all resource finalizers Driver->>Session: turn/end Driver-->>SDK: agent/status idle ``` diff --git a/docs/architecture.i18n.yaml b/docs/architecture.i18n.yaml index da396a0816..c4549ec197 100644 --- a/docs/architecture.i18n.yaml +++ b/docs/architecture.i18n.yaml @@ -24,8 +24,8 @@ en: 0d4481070a0ba352 zh: 026be77a9f3db68e /deepseek-harness-architecture/turn-flow: - en: 8a5952fde4a9a805 - zh: e69d970b98a089d0 + en: 96ad2d8611fd5b88 + zh: 0a6bb22b3b0e1335 /deepseek-harness-architecture/session-log: en: b3b63d8fe7cab9fe zh: 3703fcf30b1639d0 diff --git a/docs/architecture.md b/docs/architecture.md index 95b09e8a95..9661ac7ad6 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -102,11 +102,10 @@ turn/start step/end tools owe another request, or next-step input arrived -> claim -> next step -> agent/turn-stopping - -> agent/turn-finalizing (all outcomes; awaited) turn/end ``` -`turn/*`, `step/*`, `system/message`, `user/message`, `assistant/message`, `assistant/attempt`, and `tool/*` are durable Session events. Other events are live extension points. `agent/assistant-stream` publishes process-local start, transient chunks, and end; the loop commits the stream before a committed end, and Web Session-follow is its only remote consumer. Waterfall listeners for `agent/pre-step`, `agent/request`, `llm/stream`, and `tools/*` must call `next()`; `agent/turn-stopping` is serial. `agent/turn-finalizing` awaits all resource cleanup before `turn/end`, including error and cancellation; every listener settles before failure is reported. +`turn/*`, `step/*`, `system/message`, `user/message`, `assistant/message`, `assistant/attempt`, and `tool/*` are durable session events; the rest are live extension points across three domains. `agent/assistant-stream` publishes process-local start, transient chunk, and end frames. The loop commits the complete compact stream as one message or log-only attempt before a committed end frame, and the Web Session-follow adapter is the live event's only remote consumer. `agent/pre-step`, `agent/request`, `llm/stream`, and the three `tools/*` events are waterfalls, whose listeners must call `next()` to delegate; `agent/turn-stopping` is serial and has no `next()`. Fork creation stores the caller-supplied history; a sharing backend persists the parent prefix first ([lifecycle](../packages/core/agent-loop/README.md#understand-the-implementation)). Factory setup follows SessionStore entry and `session/created`, preceding `agent/created`; closing events commit before removal. diff --git a/docs/architecture.zh.md b/docs/architecture.zh.md index 1c94b4c2ed..41595f1bbb 100644 --- a/docs/architecture.zh.md +++ b/docs/architecture.zh.md @@ -106,11 +106,10 @@ turn/start step/end tools owe another request, or next-step input arrived -> claim -> next step -> agent/turn-stopping - -> agent/turn-finalizing (all outcomes; awaited) turn/end ``` -`turn/*`、`step/*`、`system/message`、`user/message`、`assistant/message`、`assistant/attempt` 和 `tool/*` 是持久 Session 事件。其他事件是实时扩展点。`agent/assistant-stream` 发布进程本地 start、瞬态分片和 end;loop 在 committed end 之前提交完整 stream,Web Session-follow 是唯一的远程消费方。`agent/pre-step`、`agent/request`、`llm/stream` 和 `tools/*` 的 waterfall 监听器必须调用 `next()`;`agent/turn-stopping` 是 serial 事件。`agent/turn-finalizing` 在 `turn/end` 前等待所有资源清理,覆盖错误和取消路径;所有监听器结束后统一报告失败。 +`turn/*`、`step/*`、`system/message`、`user/message`、`assistant/message`、`assistant/attempt` 和 `tool/*` 是持久会话事件;其余是分属三个事件域的实时扩展点。`agent/assistant-stream` 发布进程本地 start、瞬态 chunk 与 end frame。loop 会在 committed end frame 前把完整紧凑 stream 提交为一个 message 或仅日志 attempt;Web Session-follow adapter 是该 live event 唯一的远程消费方。`agent/pre-step`、`agent/request`、`llm/stream` 和三个 `tools/*` 事件是 waterfall(瀑布式事件),其监听器必须调用 `next()` 才能委托下去;`agent/turn-stopping` 是 serial 事件,没有 `next()`。 fork 创建存储调用方提供的历史;共享前缀的后端先持久化父前缀([生命周期](../packages/core/agent-loop/README.zh.md#understand-the-implementation))。工厂 setup 在 Session 进入 SessionStore 并完成 `session/created` 之后、`agent/created` 之前运行;收尾事件在移除之前提交。 diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 4b9308fc28..3e35c75b1b 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -15,14 +15,13 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:400`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | | `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:291`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`timeline`](../packages/experimental/timeline) | | `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:300`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), [`mcp-client`](../packages/mcp/mcp-client), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`timeline`](../packages/experimental/timeline), [`tool-office`](../packages/document/tool-office), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | -| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:441`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | +| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:430`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`), [`cua`](../packages/experimental/cua) (`emitAgentEvent`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | | `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:329`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | | `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:337`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | | `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:318`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | | `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:351`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`cua`](../packages/experimental/cua), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | | `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:390`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | -| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:310`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`timeline`](../packages/experimental/timeline) | -| `agent/turn-finalizing` | `parallel` | [`packages/core/agent/src/runtime-types.ts:429`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`parallel`) | [`cua`](../packages/experimental/cua) | +| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:310`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`cua`](../packages/experimental/cua), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`timeline`](../packages/experimental/timeline) | | `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:418`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:697`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:677`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | @@ -75,7 +74,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `session-telemetry/record` | `waterfall` | [`packages/session/session-telemetry/src/index.ts:44`](../packages/session/session-telemetry/src/index.ts) | [`session-telemetry`](../packages/session/session-telemetry) (`waterfall`) | - | | `session/created` | `emit` | [`packages/core/session/src/index.ts:56`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | `server`, `session-controller`, [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry) | | `session/disposed` | `emit` | [`packages/core/session/src/index.ts:65`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `file-upload`, `forge-session`, [`office-kit`](../packages/document/office-kit), `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-title`](../packages/session/session-title), `ui-trajectory`, [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `session/event` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`timeline`](../packages/experimental/timeline), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-session-status`, `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `session/event` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`timeline`](../packages/experimental/timeline), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-session-status`, `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `session/flush` | `parallel` | [`packages/core/session/src/index.ts:87`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`session-telemetry`](../packages/session/session-telemetry) | | `settings/document-updated` | `emit` | [`packages/settings/settings/src/types.ts:75`](../packages/settings/settings/src/types.ts) | [`settings`](../packages/settings/settings) (`emit`) | `remotes` | | `skills/change` | `emit` | [`packages/skill/skill/src/index.ts:299`](../packages/skill/skill/src/index.ts) | [`skill`](../packages/skill/skill) (`events.dispatch`) | - | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index eb17f3c6a1..b564549f87 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -17,14 +17,13 @@ | `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:400`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | | `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:291`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`timeline`](../packages/experimental/timeline) | | `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:300`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), [`mcp-client`](../packages/mcp/mcp-client), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`timeline`](../packages/experimental/timeline), [`tool-office`](../packages/document/tool-office), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | -| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:441`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | +| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:430`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`), [`cua`](../packages/experimental/cua) (`emitAgentEvent`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | | `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:329`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | | `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:337`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | | `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:318`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | | `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:351`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`cua`](../packages/experimental/cua), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | | `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:390`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | -| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:310`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`timeline`](../packages/experimental/timeline) | -| `agent/turn-finalizing` | `parallel` | [`packages/core/agent/src/runtime-types.ts:429`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`parallel`) | [`cua`](../packages/experimental/cua) | +| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:310`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`cua`](../packages/experimental/cua), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`timeline`](../packages/experimental/timeline) | | `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:418`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:697`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:677`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | @@ -77,7 +76,7 @@ | `session-telemetry/record` | `waterfall` | [`packages/session/session-telemetry/src/index.ts:44`](../packages/session/session-telemetry/src/index.ts) | [`session-telemetry`](../packages/session/session-telemetry) (`waterfall`) | - | | `session/created` | `emit` | [`packages/core/session/src/index.ts:56`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | `server`, `session-controller`, [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry) | | `session/disposed` | `emit` | [`packages/core/session/src/index.ts:65`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `file-upload`, `forge-session`, [`office-kit`](../packages/document/office-kit), `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-title`](../packages/session/session-title), `ui-trajectory`, [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `session/event` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`timeline`](../packages/experimental/timeline), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-session-status`, `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `session/event` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`timeline`](../packages/experimental/timeline), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-session-status`, `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `session/flush` | `parallel` | [`packages/core/session/src/index.ts:87`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`session-telemetry`](../packages/session/session-telemetry) | | `settings/document-updated` | `emit` | [`packages/settings/settings/src/types.ts:75`](../packages/settings/settings/src/types.ts) | [`settings`](../packages/settings/settings) (`emit`) | `remotes` | | `skills/change` | `emit` | [`packages/skill/skill/src/index.ts:299`](../packages/skill/skill/src/index.ts) | [`skill`](../packages/skill/skill) (`events.dispatch`) | - | diff --git a/docs/subsystems/core.md b/docs/subsystems/core.md index f399b5f850..a316daaba9 100644 --- a/docs/subsystems/core.md +++ b/docs/subsystems/core.md @@ -1087,30 +1087,6 @@ Types: [Scoped](scope.md) Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/src/runtime-types.ts) - - -#### `agent/turn-finalizing` — parallel - -The turn has irrevocably stopped admitting steps. Await all resource finalizers before committing turn/end, becoming idle, or starting another turn, including on cancellation. Listeners own bounded cleanup independent of the cancelled operation signal. Failures are reported through agent/error and the durable turn ending after every listener settles. - -```ts cordis-catalog -/** - * The turn has irrevocably stopped admitting steps. Await all resource finalizers before - * committing turn/end, becoming idle, or starting another turn, including on cancellation. - * Listeners own bounded cleanup independent of the cancelled operation signal. Failures - * are reported through agent/error and the durable turn ending after every listener settles. - * @param payload.agent - the agent whose work has settled. - * @param payload.turn - the turn being finalized. - * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. - * @mode parallel - */ -'agent/turn-finalizing'(this: Scoped, payload: { agent: Agent; turn: number }): Promise | void -``` - -Types: [Scoped](scope.md) - -Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/src/runtime-types.ts) - #### `agent/turn-stopping` — serial diff --git a/docs/subsystems/core.zh.md b/docs/subsystems/core.zh.md index 3740079bd3..9d8d401f85 100644 --- a/docs/subsystems/core.zh.md +++ b/docs/subsystems/core.zh.md @@ -1099,30 +1099,6 @@ Types: [Scoped](scope.zh.md) Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/src/runtime-types.ts) - - -#### `agent/turn-finalizing` — parallel - -The turn has irrevocably stopped admitting steps. Await all resource finalizers before committing turn/end, becoming idle, or starting another turn, including on cancellation. Listeners own bounded cleanup independent of the cancelled operation signal. Failures are reported through agent/error and the durable turn ending after every listener settles. - -```ts cordis-catalog -/** - * The turn has irrevocably stopped admitting steps. Await all resource finalizers before - * committing turn/end, becoming idle, or starting another turn, including on cancellation. - * Listeners own bounded cleanup independent of the cancelled operation signal. Failures - * are reported through agent/error and the durable turn ending after every listener settles. - * @param payload.agent - the agent whose work has settled. - * @param payload.turn - the turn being finalized. - * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. - * @mode parallel - */ -'agent/turn-finalizing'(this: Scoped, payload: { agent: Agent; turn: number }): Promise | void -``` - -Types: [Scoped](scope.zh.md) - -Source: [`packages/core/agent/src/runtime-types.ts`](../../packages/core/agent/src/runtime-types.ts) - #### `agent/turn-stopping` — serial diff --git a/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.i18n.yaml index dc5e4fb96f..22088cda77 100644 --- a/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.i18n.yaml @@ -9,8 +9,8 @@ en: 34b24b7c3428274b zh: 7e73cf9ba46ff2dd /macos-cua-input-holds-last-for-one-turn/change: - en: fdf88fdc0141c9d8 - zh: a4af8cab104d38d1 + en: 8bf80b8969d46419 + zh: 820fc1b7036ab251 /macos-cua-input-holds-last-for-one-turn/migration: - en: 2003c761142c4449 - zh: 47376f07776cd74d + en: 87e09c9f8803105a + zh: 2408e5b6a29ef924 diff --git a/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.md b/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.md index bd86392dba..478655452e 100644 --- a/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.md @@ -8,7 +8,7 @@ English | [中文](guide.zh.md) ## Change -macOS `sendKeyEvent('down')` holds a key across `run_code` and `cua_run_code` calls in the same turn. Returning or throwing from a program no longer releases it while the turn continues. Explicit `up` releases it immediately at the original recipient. Window-directed and system `toggleMouse('down')` join the same lifecycle. At turn completion, failure or user cancellation, cleanup releases all remaining keys and mouse buttons in reverse dispatch order and waits for native acknowledgement. Complete `pressKey`, `typeText`, `click` and `drag` operations keep their operation-local cleanup. Windows retains its current behavior. +macOS `sendKeyEvent('down')` holds a key across `run_code` and `cua_run_code` calls in the same turn. Returning or throwing from a program no longer releases it while the turn continues. Explicit `up` releases it immediately at the original recipient. Window-directed and system `toggleMouse('down')` join the same lifecycle. After `turn/end`, including failure or user cancellation, CUA releases all remaining keys and mouse buttons in reverse dispatch order and waits for native acknowledgement. The end record can precede release; `whenIdle()` and subsequent CUA input wait for cleanup. Complete `pressKey`, `typeText`, `click` and `drag` operations keep their operation-local cleanup. Windows retains its current behavior. ## Migration @@ -16,4 +16,4 @@ MCP does not supply DSH turn boundaries. Explicit macOS holds through `sendKeyEv 1. If a program requires release before it returns, send an explicit `up` in its `finally` block. Otherwise a later program in the same turn can release the held input. 2. Upgrade the macOS package and helper together. A custom `helperPath` must point to a rebuilt helper implementing the new private turn input protocol. -3. Verify a down in one program remains held until an up in a later program, or until the turn ends. If cleanup cannot be confirmed, CUA disables all its operations for that task. Inspect the desktop manually before starting a new task. +3. Verify a down in one program remains held until an up in a later program, or until cleanup after the turn ends. If cleanup cannot be confirmed, CUA disables all its operations for that task. Inspect the desktop manually before starting a new task. diff --git a/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.zh.md index 0bc720e5ce..45c05af79b 100644 --- a/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.zh.md @@ -8,7 +8,7 @@ description: macOS CUA 的显式键盘和鼠标按下现在可在同一回合内 ## 变更 -macOS 的 `sendKeyEvent('down')` 可在同一回合内跨 `run_code` 和 `cua_run_code` 调用持有按键。程序返回或抛错后,回合仍继续时不再自动释放。显式 `up` 立即向原接收方释放。窗口定向和系统 `toggleMouse('down')` 使用相同生命周期。回合正常完成、异常结束或用户取消时,清理按实际派发顺序的反序释放剩余键盘键和鼠标按钮,并等待原生确认。完整的 `pressKey`、`typeText`、`click` 和 `drag` 操作继续在本次操作内清理。Windows 保持现有行为。 +macOS 的 `sendKeyEvent('down')` 可在同一回合内跨 `run_code` 和 `cua_run_code` 调用持有按键。程序返回或抛错后,回合仍继续时不再自动释放。显式 `up` 立即向原接收方释放。窗口定向和系统 `toggleMouse('down')` 使用相同生命周期。`turn/end` 之后,包括异常结束和用户取消,CUA 按实际派发顺序的反序释放剩余键盘键和鼠标按钮,并等待原生确认。结束记录可以早于释放;`whenIdle()` 和后续 CUA 输入会等待清理完成。完整的 `pressKey`、`typeText`、`click` 和 `drag` 操作继续在本次操作内清理。Windows 保持现有行为。 ## 迁移 @@ -16,4 +16,4 @@ MCP 不提供 DSH 回合边界。macOS 的 `sendKeyEvent` 和 `toggleMouse` 显 1. 如果程序需要在返回前释放输入,在 `finally` 中显式发送 `up`。否则可由同一回合中的后续程序释放。 2. 同步升级 macOS 包和 helper。自定义 `helperPath` 必须指向已重建、支持新回合输入私有协议的 helper。 -3. 验证前一次程序的 `down` 能保持到后一次程序发送 `up`,或回合结束。清理无法确认时,CUA 会禁用该任务的全部操作。请手动检查桌面状态后再创建新任务。 +3. 验证前一次程序的 `down` 能保持到后一次程序发送 `up`,或回合结束后的清理。清理无法确认时,CUA 会禁用该任务的全部操作。请手动检查桌面状态后再创建新任务。 diff --git a/packages/core/agent-loop/README.i18n.yaml b/packages/core/agent-loop/README.i18n.yaml index ffbdf8b61d..53441930a2 100644 --- a/packages/core/agent-loop/README.i18n.yaml +++ b/packages/core/agent-loop/README.i18n.yaml @@ -48,8 +48,8 @@ en: 4bd3c8b4a9ee8cf8 zh: 2f4965a3197bed0e /deepseek-ai-dsh-agent-loop/understand-the-implementation/failure-and-cancellation: - en: 3355aa6bfce07a2f - zh: 8d4e51ea7b1d2ca0 + en: eea56903c4ff82f5 + zh: c0d5abb5767780ed /deepseek-ai-dsh-agent-loop/further-exploration: en: 7ac519f8e635acbc zh: 975e514915dc6c9f diff --git a/packages/core/agent-loop/README.md b/packages/core/agent-loop/README.md index 5e80f14bc2..28a4fe8e9c 100644 --- a/packages/core/agent-loop/README.md +++ b/packages/core/agent-loop/README.md @@ -127,8 +127,6 @@ The runtime-context projection compares the ordered names and text in committed ### Failure and cancellation -`agent/turn-finalizing` runs after the turn stops admitting steps, on completion, error and cancellation. All listeners settle before `turn/end`, idle status, subsequent turns and Agent disposal. A listener failure does not skip other finalizers; it produces `agent/error` and an error ending. Finalizers own their cleanup deadlines and must not reuse an aborted operation signal or await this Agent becoming idle. - `turn/end` declares `TurnEndCancelCause`; cancellation records a fresh `AgentCancelCause` there, retaining the caller's `kind` and the hook's `reason` text. The live `AbortSignal.reason` remains the caller's object, which a transport may extend — Node's fetch assigns a `stack` onto it — so the copy keeps that trace out of the log and keeps the ending appendable. Final adapter selection, dispatch, and iteration failures arrive as terminal finishes and enter `agent/request-error`; a handling listener returns `{ kind: 'retry' }` without calling `next()`, while an unhandled failure is terminal. Middleware, result-processing, tool, and other extension failures remain thrown and close the turn directly — plugin failure ends the turn, not the loop. Undispatched model tool calls after cancellation receive synthetic `tool/call` plus `ABORTED_BEFORE_DISPATCH` result pairs. diff --git a/packages/core/agent-loop/README.zh.md b/packages/core/agent-loop/README.zh.md index d4933a09fe..20f958752b 100644 --- a/packages/core/agent-loop/README.zh.md +++ b/packages/core/agent-loop/README.zh.md @@ -127,8 +127,6 @@ loop 在发布工厂前等待必需的注册完成。它对模型选择和 inbox ### 失败与取消 -`agent/turn-finalizing` 在回合停止接纳步骤后执行,覆盖正常完成、错误和取消。所有监听器结束后才提交 `turn/end`、发布空闲状态、开始后续回合或完成 Agent 销毁。一个监听器失败不会跳过其他清理监听器;失败会产生 `agent/error` 和错误结束记录。清理监听器自行设置超时,不得复用已取消的操作 signal,也不得等待本 Agent 变为空闲。 - `turn/end` 声明的类型是 `TurnEndCancelCause`;取消时,循环在其中记录一份新的 `AgentCancelCause`,保留调用方的 `kind` 和 hook 的 `reason` 文本。实时 `AbortSignal.reason` 仍是调用方的那个对象,传输层可能向其添加属性——Node 的 fetch 会给它赋一个 `stack`——因此这份拷贝既让该调用栈不进入日志,也让结束事件保持可追加。 最终适配器选择、分发与迭代失败以终止结束的形式到达并进入 `agent/request-error`;处理该失败的监听器返回 `{ kind: 'retry' }` 且不调用 `next()`,未被处理的失败则是终态。Middleware、结果处理、工具及其他扩展失败仍会抛出并直接关闭轮次——插件失败结束的是轮次,不是循环。取消后未分发的模型工具调用会收到合成的 `tool/call` 加 `ABORTED_BEFORE_DISPATCH` 结果对。 diff --git a/packages/core/agent-loop/src/agent.ts b/packages/core/agent-loop/src/agent.ts index 049692b0ea..7ec43dd132 100644 --- a/packages/core/agent-loop/src/agent.ts +++ b/packages/core/agent-loop/src/agent.ts @@ -345,7 +345,6 @@ export class ReactLoopAgent implements Agent { } phase.turn = turn let turnEnds: TurnEndReason | null = null - let turnFailure: { error: unknown } | undefined let target: InboxTarget = 'next-turn' try { while (true) { @@ -407,7 +406,6 @@ export class ReactLoopAgent implements Agent { target = 'next-step' } } catch (error: unknown) { - turnFailure = { error } // A cause is present exactly while the signal is aborted. const cause = abortedCancelCause(signal) if (cause !== undefined) { @@ -426,25 +424,12 @@ export class ReactLoopAgent implements Agent { this.throwError(error) } finally { try { - try { - await this.dispatch.parallel('agent/turn-finalizing', { turn }) - const cause = abortedCancelCause(signal) - if (cause !== undefined && turnEnds?.kind !== 'error') turnEnds = { kind: 'aborted', reason: cause } - } catch (cleanupError: unknown) { - const error = turnFailure === undefined ? cleanupError : new AggregateError( - [turnFailure.error, cleanupError], 'Turn execution and finalization failed', { cause: turnFailure.error }, - ) - turnEnds = { kind: 'error', error: { code: 'UNKNOWN', message: errorChain(error) } } - throw error - } finally { - // oxlint-disable-next-line typescript/no-non-null-assertion -- every exit assigns a turn ending - this.session.append('turn/end', { turn, reason: turnEnds! }) - } + // oxlint-disable-next-line typescript/no-non-null-assertion -- every exit assigns a turn ending + this.session.append('turn/end', { turn, reason: turnEnds! }) } catch (error: unknown) { this.throwError(error) } } - signal.throwIfAborted() if (!this.inbox.hasPending) return false phase.abort = new AbortController() // A fresh controller makes a latch set on the old one stale: the live driver claims the queue itself. diff --git a/packages/core/agent-loop/tests/contract-regressions.spec.ts b/packages/core/agent-loop/tests/contract-regressions.spec.ts index 6337c27050..d467ed3e2a 100644 --- a/packages/core/agent-loop/tests/contract-regressions.spec.ts +++ b/packages/core/agent-loop/tests/contract-regressions.spec.ts @@ -1528,95 +1528,3 @@ describe('disposal and cancellation during pre-step assembly', () => { expect(adapter.requests).toHaveLength(0) }) }) - -describe('turn finalization', () => { - it('waits for every finalizer after a rejection and commits failure before idle', async () => { - const ctx = await harness(new MockAdapter([textResponse('done')])) - const agent = await ctx.agentLoop.create(brandString('finalization'), { provider: 'mock', model: 'mock' }) - const entered: PromiseWithResolvers = Promise.withResolvers() - const release: PromiseWithResolvers = Promise.withResolvers() - const reported: unknown[] = [] - ctx.on('agent/error', ({ error }) => { reported.push(error) }) - ctx.on('agent/turn-finalizing', () => { throw new Error('first finalizer failed') }) - agent.ctx.on('agent/turn-finalizing', async () => { entered.resolve(); await release.promise }) - try { - send(agent, 'go') - await entered.promise - expect(agent.status).toBe('running') - expect(agent.session.snapshotEvents().some(event => event.type === 'turn/end')).toBe(false) - release.resolve() - await agent.whenIdle() - expect(reported).toHaveLength(1) - expect(agent.session.snapshotEvents().at(-1)).toMatchObject({ type: 'turn/end', data: { reason: { kind: 'error' } } }) - } finally { release.resolve(); await ctx.fiber.dispose() } - }) - - it('does not finalize when turn-stopping steering continues the current turn', async () => { - const ctx = await harness(new MockAdapter([textResponse('first'), textResponse('second')])) - const agent = await ctx.agentLoop.create(brandString('finalization-steering'), { provider: 'mock', model: 'mock' }) - const finalized: number[] = [] - let stops = 0 - ctx.on('agent/turn-stopping', () => { if (++stops === 1) agent.steer(createUserMessage({ content: [{ type: 'text', text: 'continue' }], source: { kind: 'user' } })) }) - ctx.on('agent/turn-finalizing', ({ turn }) => { finalized.push(turn) }) - try { - send(agent, 'go') - await agent.whenIdle() - expect(finalized).toEqual([1]) - expect(agent.session.snapshotEvents().filter(event => event.type === 'step/start')).toHaveLength(2) - } finally { await ctx.fiber.dispose() } - }) -}) - -it('retains the turn failure alongside a failed resource finalizer', async () => { - const ctx = await harness(new MockAdapter([])) - const agent = await ctx.agentLoop.create(brandString('failed-finalization'), { provider: 'mock', model: 'mock' }) - ctx.on('agent/pre-step', () => { throw new Error('turn preparation failed') }) - ctx.on('agent/turn-finalizing', () => { throw new Error('resource release failed') }) - try { - send(agent, 'go') - await agent.whenIdle() - const ending = agent.session.snapshotEvents().find(event => event.type === 'turn/end') - expect(ending?.data.reason.kind).toBe('error') - expect(JSON.stringify(ending)).toContain('turn preparation failed') - expect(JSON.stringify(ending)).toContain('resource release failed') - } finally { await ctx.fiber.dispose() } -}) - -it('parks queued input when cancellation arrives during resource finalization', async () => { - const adapter = new MockAdapter([textResponse('done'), textResponse('must stay queued')]) - const ctx = await harness(adapter) - const agent = await ctx.agentLoop.create(brandString('cancel-finalization'), { provider: 'mock', model: 'mock' }) - const entered: PromiseWithResolvers = Promise.withResolvers() - const release: PromiseWithResolvers = Promise.withResolvers() - ctx.on('agent/turn-finalizing', async () => { entered.resolve(); await release.promise }) - try { - send(agent, 'first') - await entered.promise - send(agent, 'queued') - agent.cancel({ kind: 'user' }, { keepInbox: true }) - release.resolve() - await agent.whenIdle() - expect(agent.session.snapshotEvents().filter(event => event.type === 'turn/start')).toHaveLength(1) - expect(agent.inbox.nextTurn).toHaveLength(1) - expect(agent.session.snapshotEvents().find(event => event.type === 'turn/end')?.data.reason) - .toEqual({ kind: 'aborted', reason: { kind: 'user' } }) - } finally { release.resolve(); await ctx.fiber.dispose() } -}) - -it('keeps an execution error when disposal cancels its finalizer wait', async () => { - const ctx = await harness(new MockAdapter([])) - const agent = await ctx.agentLoop.create(brandString('error-finalization'), { provider: 'mock', model: 'mock' }) - const entered: PromiseWithResolvers = Promise.withResolvers() - const release: PromiseWithResolvers = Promise.withResolvers() - ctx.on('agent/pre-step', () => { throw new Error('preparation failed') }) - ctx.on('agent/turn-finalizing', async () => { entered.resolve(); await release.promise }) - try { - send(agent, 'first') - await entered.promise - agent.cancel({ kind: 'disposed' }, { keepInbox: true }) - release.resolve() - await agent.whenIdle() - expect(agent.session.snapshotEvents().find(event => event.type === 'turn/end')?.data.reason) - .toMatchObject({ kind: 'error', error: { message: 'preparation failed' } }) - } finally { release.resolve(); await ctx.fiber.dispose() } -}) diff --git a/packages/core/agent/README.i18n.yaml b/packages/core/agent/README.i18n.yaml index adbc40371d..5dbbf2ac8a 100644 --- a/packages/core/agent/README.i18n.yaml +++ b/packages/core/agent/README.i18n.yaml @@ -30,8 +30,8 @@ en: 2594a1e02adea801 zh: cae8860369728efb /deepseek-ai-dsh-agent/use-this-package/intercept-or-observe-work-in-flight: - en: a75d2d050ea46674 - zh: 909587726147b9ce + en: 371511fb13093dd2 + zh: 4be81d246cf299b2 /deepseek-ai-dsh-agent/understand-the-implementation: en: ce7e776e9d516bdb zh: 59d2751743db7795 diff --git a/packages/core/agent/README.md b/packages/core/agent/README.md index 5dc7d9709e..6983725201 100644 --- a/packages/core/agent/README.md +++ b/packages/core/agent/README.md @@ -79,7 +79,7 @@ await handle.agent.whenIdle() `agent/request` is deprecated and retained for existing listeners. Do not add new listeners. Provider, model, and optional explicit reasoning effort are fixed at step preparation; listeners must preserve all three, including an absent effort. `AgentOptions.maxTokens` sets the output cap. Other per-request control overrides have no replacement API. See the [migration guide](../../../docs/upgrade-guide/v0.2.1-alpha.4/session-model-selection/guide.md) for affected callers. -The `agent/*` events let plugins act on live work without depending on the loop package. `agent/pre-step` can reject a proposed step or replace the messages entering it; `agent/request-error` lets a listener retry a failed model request; `agent/turn-stopping` runs before an otherwise completed turn closes and can steer to keep it open. `agent/turn-finalizing` awaits resource cleanup on every ending, including cancellation, before `turn/end` and idle. `agent/assistant-stream` carries one process-local Assistant attempt's ordered start, transient chunk, and end frames. Start names the attempt's turn and step, chunk indexes are dense from zero, and `end.index` is the next chunk position. The loop commits the complete compact stream as one `assistant/message` or `assistant/attempt` before a committed end frame, so the live event remains presentation data rather than the replay source. `agent/status`, `agent/created`, and `agent/disposed` drive UI and coordination state, and the per-message `agent/inbox/*` notifications keep inbox projections in sync. Exact signatures, dispatch modes, and payload contracts live in the generated region of the [core subsystem page](../../../docs/subsystems/core.md#cordis-surface). +The `agent/*` events let plugins act on live work without depending on the loop package. `agent/pre-step` can reject a proposed step or replace the messages entering it; `agent/request-error` lets a listener retry a failed model request; `agent/turn-stopping` runs before an otherwise completed turn closes and can steer to keep it open. `agent/assistant-stream` carries one process-local Assistant attempt's ordered start, transient chunk, and end frames. Start names the attempt's turn and step, chunk indexes are dense from zero, and `end.index` is the next chunk position. The loop commits the complete compact stream as one `assistant/message` or `assistant/attempt` before a committed end frame, so the live event remains presentation data rather than the replay source. `agent/status`, `agent/created`, and `agent/disposed` drive UI and coordination state, and the per-message `agent/inbox/*` notifications keep inbox projections in sync. Exact signatures, dispatch modes, and payload contracts live in the generated region of the [core subsystem page](../../../docs/subsystems/core.md#cordis-surface). ----- diff --git a/packages/core/agent/README.zh.md b/packages/core/agent/README.zh.md index d6ba191c4b..e74ddaefa1 100644 --- a/packages/core/agent/README.zh.md +++ b/packages/core/agent/README.zh.md @@ -79,7 +79,7 @@ await handle.agent.whenIdle() `agent/request` 已弃用,仅为现有监听器保留。不要添加新监听器。提供方、模型和可选的显式推理强度在步骤准备时固定;监听器必须保留三者,包括未指定强度的状态。`AgentOptions.maxTokens` 设置输出上限。其他逐请求控制参数覆盖没有替代 API。受影响的调用方参见[迁移指南](../../../docs/upgrade-guide/v0.2.1-alpha.4/session-model-selection/guide.zh.md)。 -`agent/*` 事件让插件无需依赖循环包即可作用于实时工作。`agent/pre-step` 可以拒绝拟进入的步骤或替换进入它的消息;`agent/request-error` 让监听器重试失败的模型请求;`agent/turn-stopping` 在本可完成的轮次关闭前运行,并可通过 steer 使其保持打开。`agent/turn-finalizing` 在所有结束路径中等待资源清理,包括取消;清理结束后才提交 `turn/end` 和发布空闲状态。`agent/assistant-stream` 携带一个进程本地 Assistant attempt 的有序 start、瞬态分片与 end frame。start 给出该 attempt 的轮次与步骤,分片索引从零开始密集递增,`end.index` 则是下一个分片位置。loop 会在 committed end frame 前把完整紧凑流提交为一个 `assistant/message` 或 `assistant/attempt`,因此实时事件仍是呈现数据而非回放来源。`agent/status`、`agent/created` 与 `agent/disposed` 驱动 UI 与协调状态,逐消息的 `agent/inbox/*` 通知则让收件箱投影保持同步。确切签名、分发 mode 与 payload 约定见 [core 子系统页](../../../docs/subsystems/core.zh.md#cordis-surface) 的生成区块。 +`agent/*` 事件让插件无需依赖循环包即可作用于实时工作。`agent/pre-step` 可以拒绝拟进入的步骤或替换进入它的消息;`agent/request-error` 让监听器重试失败的模型请求;`agent/turn-stopping` 在本可完成的轮次关闭前运行,并可通过 steer 使其保持打开。`agent/assistant-stream` 携带一个进程本地 Assistant attempt 的有序 start、瞬态分片与 end frame。start 给出该 attempt 的轮次与步骤,分片索引从零开始密集递增,`end.index` 则是下一个分片位置。loop 会在 committed end frame 前把完整紧凑流提交为一个 `assistant/message` 或 `assistant/attempt`,因此实时事件仍是呈现数据而非回放来源。`agent/status`、`agent/created` 与 `agent/disposed` 驱动 UI 与协调状态,逐消息的 `agent/inbox/*` 通知则让收件箱投影保持同步。确切签名、分发 mode 与 payload 约定见 [core 子系统页](../../../docs/subsystems/core.zh.md#cordis-surface) 的生成区块。 ----- diff --git a/packages/core/agent/src/dispatch.ts b/packages/core/agent/src/dispatch.ts index 0f0f80a73e..03fd952ac5 100644 --- a/packages/core/agent/src/dispatch.ts +++ b/packages/core/agent/src/dispatch.ts @@ -68,13 +68,6 @@ export interface AgentEventDispatch { * @returns the serial chain's result (the first bail value, if any). */ serial(name: K, payload: PayloadRest): Promise>> - /** - * Await every listener, including after another listener fails; reject with all failures. - * @param name - the agent-subject event to dispatch. - * @param payload - the event's payload fields; `agent` is injected. - * @returns completion after all listeners settle. - */ - parallel(name: K, payload: PayloadRest): Promise /** * Around-middleware dispatch (Cordis `waterfall`) in the agent's scope. The * declared event parameters already end with the `next` callback, so `rest` @@ -142,11 +135,6 @@ export function agentEvents(ctx: Context, agent: Agent, carrier: Scoped = } } }, - async parallel(name, payload) { - // oxlint-disable-next-line typescript/unbound-method -- the events mixin accessor returns a pre-bound function - const parallel = ctx.parallel as (thisArg: Scoped, name: string, ...args: unknown[]) => Promise - await parallel(carrier, name, fused(payload)) - }, async serial(name, payload) { // oxlint-disable-next-line typescript/unbound-method -- the events mixin accessor returns a pre-bound function const serial = ctx.serial as (thisArg: Scoped, name: string, ...args: unknown[]) => Promise diff --git a/packages/core/agent/src/runtime-types.ts b/packages/core/agent/src/runtime-types.ts index ec2ec9706f..7012dfdf50 100644 --- a/packages/core/agent/src/runtime-types.ts +++ b/packages/core/agent/src/runtime-types.ts @@ -416,17 +416,6 @@ declare module '@deepseek-ai/cordis' { * @mode serial */ 'agent/turn-stopping'(this: Scoped, payload: { agent: Agent; turn: number; signal: AbortSignal }): Promise | void - /** - * The turn has irrevocably stopped admitting steps. Await all resource finalizers before - * committing turn/end, becoming idle, or starting another turn, including on cancellation. - * Listeners own bounded cleanup independent of the cancelled operation signal. Failures - * are reported through agent/error and the durable turn ending after every listener settles. - * @param payload.agent - the agent whose work has settled. - * @param payload.turn - the turn being finalized. - * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent. - * @mode parallel - */ - 'agent/turn-finalizing'(this: Scoped, payload: { agent: Agent; turn: number }): Promise | void // ---- error notifications (emit) ---- /** * A step or turn errored. The machine reports a failure here even when diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index e5887824c9..6aed2783ff 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -21,8 +21,8 @@ en: 3bf05d9ce5eb7224 zh: d8d0cd6429374860 /deepseek-ai-dsh-cua-macos/understand-the-implementation: - en: ad6bfda9592f4722 - zh: 0a179c77b9ffd894 + en: 3d88c0f7fa4ddf57 + zh: 7f9830bd8c3175bb /deepseek-ai-dsh-cua-macos/further-exploration: en: ff9fac614001a98f zh: 329678941154aaea diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index 340b17510b..a74f937141 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -148,7 +148,7 @@ Element clicks use opaque element IDs from the current snapshot. Left clicks sup ## Understand the implementation -The shared helper's `HeldInputs` records task, turn, connection, process generation, application/window and actual input route before each explicit down is posted. One lock orders keyboard and pointer posts and releases. `agent/turn-finalizing` closes host admission, cancels in-flight native work and awaits `releaseHeldInputs` with an independent bounded request. `whenIdle()` and Agent disposal include this wait. Connection shutdown cancels and joins native work before fallback release; a killed host relies on that disconnect path. Repeated cleanup cannot release a later turn's inputs. +The shared helper's `HeldInputs` records task, turn, connection, process generation, application/window and actual input route before each explicit down is posted. One lock orders keyboard and pointer posts and releases. `turn/end` starts CUA cleanup: it closes host admission, cancels in-flight native work and awaits `releaseHeldInputs` with an independent bounded request. CUA uses the existing `runMaintenance()` and pre-step hooks to make `whenIdle()`, subsequent input and Agent disposal wait for cleanup. The turn record and idle notification can precede release acknowledgement; cleanup failure is reported separately through `agent/error` and disables CUA for the task. Connection shutdown cancels and joins native work before fallback release; a killed host relies on that disconnect path. Repeated cleanup cannot release a later turn's inputs.
Dispatch and resource ownership diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index a122836cdf..a1ea56e675 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -148,7 +148,7 @@ AppKit 的 sheet 可以出现在文档窗口的树里,并有独立的窗口 ID ## 理解实现 -共享 helper 的 `HeldInputs` 在每次显式按下派发前记录任务、回合、连接、进程代次、应用或窗口和实际输入方式。同一把锁维护键盘与鼠标的派发和释放顺序。`agent/turn-finalizing` 关闭宿主输入准入、取消在途原生操作,并通过独立且有超时限制的请求等待 `releaseHeldInputs` 确认。`whenIdle()` 和 Agent 销毁都包含这段等待。连接关闭会先取消并等待原生操作停止,再做兜底释放;宿主被强杀时依靠这条断连路径。重复清理不会释放后续回合的输入。 +共享 helper 的 `HeldInputs` 在每次显式按下派发前记录任务、回合、连接、进程代次、应用或窗口和实际输入方式。同一把锁维护键盘与鼠标的派发和释放顺序。`turn/end` 触发 CUA 清理:关闭宿主输入准入、取消在途原生操作,并通过独立且有超时限制的请求等待 `releaseHeldInputs` 确认。CUA 利用现有 `runMaintenance()` 和 pre-step 入口,使 `whenIdle()`、后续输入和 Agent 销毁等待清理完成。回合结束记录和空闲通知可以早于释放确认;清理失败单独通过 `agent/error` 报告,并禁用该任务的 CUA。连接关闭会先取消并等待原生操作停止,再做兜底释放;宿主被强杀时依靠这条断连路径。重复清理不会释放后续回合的输入。
操作分派与资源归属 diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index 74ff8be173..dc89dcf285 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -21,8 +21,8 @@ en: 3f638a4a76023fc5 zh: 515aeb5de6ae5b33 /deepseek-ai-dsh-cua/understand-the-implementation: - en: dc47468ea4cd1bca - zh: 9739728015c70810 + en: 9c6e811e8844d5f2 + zh: 41e744e238a992c2 /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 fa8177cecf..56edc0eec9 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -89,7 +89,7 @@ Permission responses identify their platform and report only the state that plat
Shared execution and platform ownership -A provider enables `CuaBackend.turnInputLifecycle` only after its helper accepts `taskId` and `turn` on `sendKeyEvent`, `toggleMouse`, and system `mouseMove`, and acknowledges `releaseHeldInputs({ taskId, turn })`. Provider unload retains lifecycle listeners until program calls and native cleanup have settled. The shared owner blocks admission on cancellation or finalization, awaits native cancellation before independent bounded cleanup, and disables all CUA operations for the task after an unconfirmed release. Providers must record actual dispatch order, targets and routes before posting, implement explicit up and mixed reverse-order cleanup, reject stale turns, and clean only their connection on disconnect. For these providers, `getCapabilities().methods` omits `sendKeyEvent` and `toggleMouse` outside an active turn. Windows leaves this option unset until these native behaviors are implemented; it receives neither new parameters nor cleanup commands. +A provider enables `CuaBackend.turnInputLifecycle` only after its helper accepts `taskId` and `turn` on `sendKeyEvent`, `toggleMouse`, and system `mouseMove`, and acknowledges `releaseHeldInputs({ taskId, turn })`. Provider unload retains lifecycle listeners until program calls and native cleanup have settled. The shared owner starts cleanup from `turn/end`, closes input admission, and awaits native cancellation before independent bounded cleanup. It retains the completion promise through existing Agent maintenance and pre-step waits; `turn/end` and idle notifications alone do not confirm release. An unconfirmed release reports `agent/error` and disables all CUA operations for the task. Providers must record actual dispatch order, targets and routes before posting, implement explicit up and mixed reverse-order cleanup, reject stale turns, and clean only their connection on disconnect. For these providers, `getCapabilities().methods` omits `sendKeyEvent` and `toggleMouse` outside an active turn. Windows leaves this option unset until these native behaviors are implemented; it receives neither new parameters nor cleanup commands. The [permission store](src/permission-store.ts) uses `storageDomain` with the configured backend. The default JSON backend writes `$DSH_HOME/storages/cua_permissions_.json`, where the digest identifies the canonical profile directory. Each authorization check opens fresh state under the profile's file lock and closes its domain afterward; native dispatch uses a separate application lock. Revocation waits for operations already admitted by another process; after it completes, every process rejects old handles. Files on different machines or PID namespaces must not share this lock. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index 9f4d6fc7f0..e3509fc6ea 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -89,7 +89,7 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边
共享执行与平台职责 -提供方仅在 helper 已接受 `sendKeyEvent`、`toggleMouse` 和系统 `mouseMove` 的 `taskId`、`turn` 参数,并能确认 `releaseHeldInputs({ taskId, turn })` 后,才启用 `CuaBackend.turnInputLifecycle`。提供方卸载时保留生命周期监听器,直到程序调用和原生清理都已结束。共通持有方在取消或收尾时禁止新输入,等待原生取消后用独立且有超时限制的请求清理;释放未经确认时禁用该任务的全部 CUA 操作。提供方必须在派发前记录实际顺序、目标与输入方式,实现显式释放和键鼠混合反序清理,拒绝旧回合输入,并在断连时只清理本连接。这些提供方在没有活动回合时,从 `getCapabilities().methods` 中省略 `sendKeyEvent` 和 `toggleMouse`。Windows 在实现这些原生行为前保持此选项未设置,不接收新增参数或清理命令。 +提供方仅在 helper 已接受 `sendKeyEvent`、`toggleMouse` 和系统 `mouseMove` 的 `taskId`、`turn` 参数,并能确认 `releaseHeldInputs({ taskId, turn })` 后,才启用 `CuaBackend.turnInputLifecycle`。提供方卸载时保留生命周期监听器,直到程序调用和原生清理都已结束。共通持有方从 `turn/end` 开始清理,禁止新输入,等待原生取消后用独立且有超时限制的请求释放。它通过现有的 Agent maintenance 和 pre-step 等待保留清理完成结果;单独的 `turn/end` 或空闲通知不表示释放已经确认。释放未经确认时报告 `agent/error`,并禁用该任务的全部 CUA 操作。提供方必须在派发前记录实际顺序、目标与输入方式,实现显式释放和键鼠混合反序清理,拒绝旧回合输入,并在断连时只清理本连接。这些提供方在没有活动回合时,从 `getCapabilities().methods` 中省略 `sendKeyEvent` 和 `toggleMouse`。Windows 在实现这些原生行为前保持此选项未设置,不接收新增参数或清理命令。 [授权存储](src/permission-store.ts)复用 `storageDomain` 和配置的后端。默认 JSON 后端写入 `$DSH_HOME/storages/cua_permissions_.json`,摘要对应 profile 的真实目录。每次授权检查在 profile 文件锁内打开并读取最新状态,随后关闭存储域;原生操作使用单独的应用锁。撤销会等待其他进程已获准执行的操作结束;撤销完成后,各进程都拒绝旧句柄。不同电脑或 PID 命名空间不能共享这把锁。 diff --git a/packages/experimental/cua/src/index.ts b/packages/experimental/cua/src/index.ts index 31bcd317a1..eaecbaac43 100644 --- a/packages/experimental/cua/src/index.ts +++ b/packages/experimental/cua/src/index.ts @@ -390,6 +390,7 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) execution.signal.throwIfAborted() lifetime.signal.throwIfAborted() const owner = ownerFor(agent) + if (inputTurns) await inputTurns.ready(agent) const turn = inputTurns?.scope(agent) const signal = AbortSignal.any([execution.signal, lifetime.signal, owner.signal, ...turn ? [turn.signal] : []]) signal.throwIfAborted() diff --git a/packages/experimental/cua/src/turn-inputs.ts b/packages/experimental/cua/src/turn-inputs.ts index 877bbf467a..e77c85a949 100644 --- a/packages/experimental/cua/src/turn-inputs.ts +++ b/packages/experimental/cua/src/turn-inputs.ts @@ -1,6 +1,6 @@ /** Turn-owned admission and acknowledged cleanup for providers implementing held input. */ import type { Context } from '@deepseek-ai/cordis' -import type { Agent } from '@deepseek-ai/dsh-agent' +import { emitAgentEvent, type Agent } from '@deepseek-ai/dsh-agent' import { NativeError, type NativeClient } from './native-client.ts' class InputTurn { @@ -24,6 +24,14 @@ class InputTurn { } } + get pending(): boolean { return this.removeCleanup !== undefined } + + /** Close reports and disables the failed owner; background and maintenance waits must still settle. */ + async settle(): Promise { + try { await this.close() } + catch (_error) { /* close has reported the failure and disabled this task's CUA operations. */ } + } + close(canRequest = true): Promise { this.controller.abort() return this.closing ??= Promise.resolve().then(async () => { @@ -36,6 +44,7 @@ class InputTurn { throw error } finally { this.removeCleanup?.() + this.removeCleanup = undefined } }) } @@ -50,24 +59,49 @@ export class CuaInputTurns { constructor(private readonly ctx: Context) {} /** - * Install turn admission and finalization listeners. + * Install turn admission, post-turn cleanup and whole-agent maintenance waits. * @returns Exact disposers for the runtime effect to retain through native cleanup. */ *install(): Generator<() => void> { const ctx = this.ctx - yield ctx.on('agent/pre-step', (event, next) => { - if (this.turns.get(event.agent)?.turn !== event.turn) { + yield ctx.on('agent/pre-step', async (event, next) => { + const previous = this.turns.get(event.agent) + if (previous?.turn !== event.turn) { + await previous?.settle() this.turns.set(event.agent, new InputTurn(event.agent, event.turn, event.signal, (error) => { this.failures.set(event.agent, error) ctx.logger.error('CUA cleanup was not confirmed; all CUA operations are disabled for task %s: %s', event.agent.id, error) + emitAgentEvent(ctx, event.agent, 'agent/error', { turn: event.turn, step: 0, error }) })) } return next() }) - yield ctx.on('agent/turn-finalizing', ({ agent, turn }) => { + yield ctx.on('session/event', (session, event) => { + if (event.type !== 'turn/end') return + const agent = ctx.agents.get(session.id) + if (agent?.session !== session) return const owner = this.turns.get(agent) - if (owner?.turn === turn) return owner.close() + if (owner?.turn === event.data.turn) void owner.settle() }) + yield ctx.on('agent/status', ({ agent, status }) => { + if (status !== 'idle') return + const owner = this.turns.get(agent) + if (!owner?.pending) return + // Claim the idle phase before notification consumers submit more work. whenIdle follows maintenance. + void agent.runMaintenance(() => owner.settle()) + }, { prepend: true }) + } + + /** + * Wait for an ended turn before a direct CUA operation can acquire the connection. + * @param agent - Task issuing the operation. + * @returns Completion after cleanup has settled and any failure has been reported. + */ + async ready(agent: Agent): Promise { + const owner = this.turns.get(agent) + if (owner?.controller.signal.aborted) { + await owner.settle() + } } /** diff --git a/packages/experimental/cua/tests/run-code-composition.spec.ts b/packages/experimental/cua/tests/run-code-composition.spec.ts index f16ab2770a..aead14dca0 100644 --- a/packages/experimental/cua/tests/run-code-composition.spec.ts +++ b/packages/experimental/cua/tests/run-code-composition.spec.ts @@ -372,9 +372,11 @@ it('keeps held keys across programs and a failed program until explicit up or tu expect(f.native.held).toEqual([]) }) -it.each(['normal', 'model failure', 'thinking stop'] as const)('awaits native release before idle on %s', async (ending) => { +it.each(['normal', 'model failure', 'thinking stop'] as const)('records turn/end before cleanup and makes whenIdle await native release on %s', async (ending) => { const f = await setup([holdProgram], 'macos', undefined, true, true) const thinking: PromiseWithResolvers = Promise.withResolvers() + const idle: PromiseWithResolvers = Promise.withResolvers() + f.ctx.on('agent/status', ({ agent, status }) => { if (agent === f.agent && status === 'idle') idle.resolve() }) f.model.beforeStream = async (index, options) => { if (index !== 1) return if (ending === 'model failure') throw new Error('Model request failed') @@ -384,12 +386,14 @@ it.each(['normal', 'model failure', 'thinking stop'] as const)('awaits native re } } const release = f.native.controlNext('releaseHeldInputs') - const running = f.run() + let settled = false + const running = f.run().then(() => { settled = true }) if (ending === 'thinking stop') { await thinking.promise; f.agent.cancel({ kind: 'user' }) } - await release.entered + await Promise.all([release.entered, idle.promise]) try { - expect(f.agent.status).toBe('running') - expect(f.agent.session.snapshotEvents().some(event => event.type === 'turn/end')).toBe(false) + expect(f.agent.status).toBe('idle') + expect(settled).toBe(false) + expect(f.agent.session.snapshotEvents().some(event => event.type === 'turn/end')).toBe(true) expect(f.native.held.map(press => press.key)).toEqual(['w']) } finally { release.reply(); await running } expect(f.native.held).toEqual([]) @@ -432,7 +436,7 @@ it.each(['refusal', 'disconnect', 'timeout'] as const)('reports cleanup %s and p else if (failure === 'disconnect') release.disconnect() await running expect(errors).toHaveLength(1) - expect(f.agent.session.snapshotEvents().at(-1)).toMatchObject({ type: 'turn/end', data: { reason: { kind: 'error' } } }) + expect(f.agent.session.snapshotEvents().at(-1)).toMatchObject({ type: 'turn/end', data: { reason: { kind: 'completed' } } }) const count = f.native.calls.length f.model.requests.length = 0 f.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Try again' }], source: { kind: 'user' } })) @@ -460,10 +464,9 @@ it.each(['agent', 'provider', 'context'] as const)('awaits held input cleanup wh expect(disposed).toBe(false) expect(f.native.state.closedChannels).toBe(0) f.agent.cancel({ kind: 'user' }) - // The model's abort and loop finalization are in-process; the native reply remains behind its explicit barrier. + // Turn completion is observable while native acknowledgement remains behind its explicit barrier. await setImmediate() - expect(f.agent.status).toBe('running') - expect(f.agent.session.snapshotEvents().some(event => event.type === 'turn/end')).toBe(false) + expect(f.agent.session.snapshotEvents().some(event => event.type === 'turn/end')).toBe(true) } finally { release.reply() f.agent.cancel({ kind: 'user' }) @@ -539,13 +542,67 @@ it('reports disconnect after a dispatched down and blocks a later program in the expect(JSON.stringify(results[1])).toContain('INPUT_CLEANUP_UNCONFIRMED') expect(f.native.calls.filter(call => call.method === 'getApp')).toHaveLength(1) expect(f.native.calls.some(call => call.method === 'releaseHeldInputs')).toBe(false) - expect(f.agent.session.snapshotEvents().find(event => event.type === 'turn/end')?.data.reason.kind).toBe('error') + expect(f.agent.session.snapshotEvents().find(event => event.type === 'turn/end')?.data.reason.kind).toBe('completed') }) -it('finalizes without native cleanup when prompt assembly fails before input admission', async () => { +it('ends without native cleanup when prompt assembly fails before input admission', async () => { const f = await setup([holdProgram], 'macos', undefined, true, true) f.ctx.on('system-prompt/assemble', async () => { throw new Error('Fixture assembly failed') }) await f.run() expect(f.native.calls).toEqual([]) expect(f.agent.session.snapshotEvents().find(event => event.type === 'turn/end')?.data.reason.kind).toBe('error') }) + +it('keeps held input while turn-stopping steering continues the same turn', async () => { + const f = await setup([holdProgram], 'macos', undefined, true, true) + let stops = 0 + f.ctx.on('agent/turn-stopping', ({ agent }) => { + if (agent !== f.agent || ++stops !== 1) return + agent.steer(createUserMessage({ content: [{ type: 'text', text: 'Continue this turn' }], source: { kind: 'user' } })) + }) + f.model.beforeStream = async (index) => { + if (index === 2) expect(f.native.held.map(press => press.key)).toEqual(['w']) + } + await f.run() + expect(stops).toBe(2) + expect(f.native.events).toEqual(['w:down', 'w:up']) + expect(f.native.calls.filter(call => call.method === 'releaseHeldInputs').map(call => call.params.turn)).toEqual([1]) +}) + +it('blocks a queued turn at pre-step until the previous native cleanup settles', async () => { + const f = await setup([holdProgram], 'macos', undefined, true, true) + const nextStep: PromiseWithResolvers = Promise.withResolvers() + f.ctx.on('agent/pre-step', (event, next) => { + if (event.agent === f.agent && event.turn === 2) nextStep.resolve() + return next() + }, { prepend: true }) + f.model.beforeStream = async (index) => { + if (index === 1) f.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Queued turn' }], source: { kind: 'user' } })) + } + const release = f.native.controlNext('releaseHeldInputs') + const running = f.run() + await Promise.all([release.entered, nextStep.promise]) + try { + expect(f.model.requests).toHaveLength(2) + expect(f.native.held.map(press => press.turn)).toEqual([1]) + expect(f.agent.session.snapshotEvents().filter(event => event.type === 'turn/end')).toHaveLength(1) + } finally { release.reply(); await running } + expect(f.model.requests).toHaveLength(3) + expect(f.native.held).toEqual([]) +}) + +it('does not resume retained inbox work when stopped during post-turn cleanup', async () => { + const f = await setup([holdProgram], 'macos', undefined, true, true) + const idle: PromiseWithResolvers = Promise.withResolvers() + f.ctx.on('agent/status', ({ status }) => { if (status === 'idle') idle.resolve() }) + const release = f.native.controlNext('releaseHeldInputs') + const running = f.run() + await Promise.all([release.entered, idle.promise]) + f.agent.inject(createUserMessage({ content: [{ type: 'text', text: 'Retained input' }], source: { kind: 'user' } })) + f.agent.cancel({ kind: 'user' }, { keepInbox: true }) + release.reply() + await running + expect(f.native.held).toEqual([]) + expect(f.agent.session.snapshotEvents().filter(event => event.type === 'turn/start')).toHaveLength(1) + expect(f.agent.inbox.hasPending).toBe(true) +}) diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 283d905c7b..f7a5c48fe8 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -5375,14 +5375,6 @@ export const EVENT_API: readonly EventApiEntry[] = [ description: 'Agent status changed (`idle` ⇄ `running`). A waking delivery enters `running` synchronously after reserving cancellation; `idle` means no driver remains scheduled or active.', parameters: [{ name: 'payload', description: '.status - the status just entered (the transition\'s destination). Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.' }], }, - { - name: 'agent/turn-finalizing', - mode: 'parallel', - signature: '\'agent/turn-finalizing\'(this: Scoped, payload: { agent: Agent; turn: number }): Promise | void', - summary: 'The turn has irrevocably stopped admitting steps.', - description: 'The turn has irrevocably stopped admitting steps. Await all resource finalizers before committing turn/end, becoming idle, or starting another turn, including on cancellation. Listeners own bounded cleanup independent of the cancelled operation signal. Failures are reported through agent/error and the durable turn ending after every listener settles.', - parameters: [{ name: 'payload', description: '.turn - the turn being finalized. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only that agent.' }], - }, { name: 'agent/turn-stopping', mode: 'serial', diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts index 0409c43f6e..ab031dc062 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -1777,7 +1777,6 @@ function renderLifecycle(): string { ' end', ' end', ' end', - ` Driver->>Hooks: ${mermaidCode('agent/turn-finalizing')} await all resource finalizers`, ` Driver->>Session: ${mermaidCode('turn/end')}`, ` Driver-->>SDK: ${mermaidCode('agent/status')} idle`, '```', diff --git a/snapshots/sdk/ptc-cancel/cancel.mjs b/snapshots/sdk/ptc-cancel/cancel.mjs index c1729045e2..42bdabdddc 100644 --- a/snapshots/sdk/ptc-cancel/cancel.mjs +++ b/snapshots/sdk/ptc-cancel/cancel.mjs @@ -2,10 +2,6 @@ export const name = 'ptc-cancel-fixture' export const inject = ['tools'] export function apply(ctx) { - ctx.on('agent/turn-finalizing', async ({ agent }) => { - await Promise.resolve() - agent.session.append('feedback/record', { category: 'other' }) - }) ctx.on('tools/result', (exec) => { if (exec.name === 'job_list' && exec.parent !== undefined && exec.agent !== undefined) { exec.agent.cancel({ kind: 'user' }) diff --git a/snapshots/sdk/ptc-cancel/session.v4.jsonl b/snapshots/sdk/ptc-cancel/session.v4.jsonl index 037d641f20..08c8bd59a1 100644 --- a/snapshots/sdk/ptc-cancel/session.v4.jsonl +++ b/snapshots/sdk/ptc-cancel/session.v4.jsonl @@ -13,11 +13,10 @@ {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Start a run_code program, call","messageSeqs":[8],"source":{"kind":"fallback"}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"ptc-cancel","name":"run_code","arguments":"{\"code\":\"await tools.job_list({}); for (;;) {}\",\"description\":\"Run until stopped\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:5}}"},"stream":[{"type":"chunk","time":1794988150476,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1794988150476,"index":0,"dt":[],"id":"ptc-cancel","name":"run_code","args":["{\"code\":\"await tools.job_list({}); for (;;) {}\",\"description\":\"Run until stopped\"}"]},{"type":"chunk","time":1794988150476,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"ptc-cancel","name":"run_code","arguments":"{\"code\":\"await tools.job_list({}); for (;;) {}\",\"description\":\"Run until stopped\"}"}}},{"type":"chunk","time":1794988150476,"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":"ptc-cancel","name":"run_code","arguments":"{\"code\":\"await tools.job_list({}); for (;;) {}\",\"description\":\"Run until stopped\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:5}}"},"stream":[{"type":"chunk","time":1793796116464,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1793796116464,"index":0,"dt":[],"id":"ptc-cancel","name":"run_code","args":["{\"code\":\"await tools.job_list({}); for (;;) {}\",\"description\":\"Run until stopped\"}"]},{"type":"chunk","time":1793796116464,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"ptc-cancel","name":"run_code","arguments":"{\"code\":\"await tools.job_list({}); for (;;) {}\",\"description\":\"Run until stopped\"}"}}},{"type":"chunk","time":1793796116464,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"ptc-cancel","name":"run_code","arguments":"{\"code\":\"await tools.job_list({}); for (;;) {}\",\"description\":\"Run until stopped\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"ptc-cancel","parentCallId":"ptc-cancel","subCallId":"ptc-cancel:ptc:1","name":"job_list","arguments":{}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"ptc-cancel","parentCallId":"ptc-cancel","subCallId":"ptc-cancel:ptc:1","name":"job_list","arguments":{},"isError":false,"content":[{"type":"text","text":"(no background jobs)"}]}} {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"ptc-cancel"},"toolCallId":"ptc-cancel","content":[{"type":"text","text":"Error: tool call aborted"}],"isError":true,"id":"{{message:6}}"},"error":{"name":"AbortError","code":"ABORTED"}},"sourceEventSeqs":[15],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} -{"type":"feedback/record","data":{"category":"other"}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"aborted","reason":{"kind":"user"}}}} diff --git a/snapshots/sdk/text-turn/feedback-producer.mjs b/snapshots/sdk/text-turn/feedback-producer.mjs index 34acf76a77..b2e36a8761 100644 --- a/snapshots/sdk/text-turn/feedback-producer.mjs +++ b/snapshots/sdk/text-turn/feedback-producer.mjs @@ -6,8 +6,7 @@ export const inject = ['commands', 'messageFeedback', 'sessionFeedback'] * @param {import('@deepseek-ai/cordis').Context} ctx - Composed runtime services. */ export function apply(ctx) { - ctx.on('agent/turn-finalizing', async ({ agent }) => { - const signal = AbortSignal.timeout(30_000) + ctx.on('agent/turn-stopping', async ({ agent, signal }) => { if (agent.session.header.parentSession !== undefined) return const messages = agent.session.deriveMessages() const message = messages.findLast(message => message.role === 'assistant') @@ -19,7 +18,7 @@ export function apply(ctx) { const target = { sessionId: agent.id, messageId: message.id } const created = await ctx.messageFeedback.put({ ...target, rating: 'negative', note: 'Explain the result.', category: 'task-result', ifVersion: null }) if (!created.ok) throw new Error(created.error.code) - const edited = await ctx.messageFeedback.put({ ...target, rating: 'positive', note: 'Turn resources released.', ifVersion: created.value.version }) + const edited = await ctx.messageFeedback.put({ ...target, rating: 'positive', note: 'The explanation is clear now.', ifVersion: created.value.version }) if (!edited.ok) throw new Error(edited.error.code) const deleted = await ctx.messageFeedback.delete({ ...target, ifVersion: edited.value.version }) if (!deleted.ok) throw new Error(deleted.error.code) diff --git a/snapshots/sdk/text-turn/notifications.expected.jsonl b/snapshots/sdk/text-turn/notifications.expected.jsonl index bc755c9d6e..917506815d 100644 --- a/snapshots/sdk/text-turn/notifications.expected.jsonl +++ b/snapshots/sdk/text-turn/notifications.expected.jsonl @@ -18,7 +18,7 @@ {"method":"session.event","params":{"sessionId":"{{session:1}}","event":{"type":"command/done","seq":19,"time":0,"data":{"commandId":"{{command:1}}","kind":"success","text":"Feedback recorded for session {{session:1}}\nAnonymous user: {{id:1}}."}}}} {"method":"session.event","params":{"sessionId":"{{session:1}}","event":{"type":"feedback/record","seq":20,"time":0,"data":{"category":"other"}}}} {"method":"session.event","params":{"sessionId":"{{session:1}}","event":{"type":"feedback/message-put","seq":21,"time":0,"data":{"sessionId":"{{session:1}}","item":{"messageId":"{{message:5}}","rating":"negative","note":"Explain the result.","category":"task-result","version":"{{id:2}}","createdAt":0,"updatedAt":0}}}}} -{"method":"session.event","params":{"sessionId":"{{session:1}}","event":{"type":"feedback/message-put","seq":22,"time":0,"data":{"sessionId":"{{session:1}}","item":{"messageId":"{{message:5}}","rating":"positive","note":"Turn resources released.","version":"{{id:3}}","createdAt":0,"updatedAt":0}}}}} +{"method":"session.event","params":{"sessionId":"{{session:1}}","event":{"type":"feedback/message-put","seq":22,"time":0,"data":{"sessionId":"{{session:1}}","item":{"messageId":"{{message:5}}","rating":"positive","note":"The explanation is clear now.","version":"{{id:3}}","createdAt":0,"updatedAt":0}}}}} {"method":"session.event","params":{"sessionId":"{{session:1}}","event":{"type":"feedback/message-delete","seq":23,"time":0,"data":{"sessionId":"{{session:1}}","messageId":"{{message:5}}"}}}} {"method":"session.event","params":{"sessionId":"{{session:1}}","event":{"type":"turn/end","seq":24,"time":0,"data":{"turn":1,"reason":{"kind":"completed"}}}}} {"method":"session.status","params":{"sessionId":"{{session:1}}","status":"idle"}} diff --git a/snapshots/sdk/text-turn/session.v4.jsonl b/snapshots/sdk/text-turn/session.v4.jsonl index 12c2ea9851..1d2b1e1bab 100644 --- a/snapshots/sdk/text-turn/session.v4.jsonl +++ b/snapshots/sdk/text-turn/session.v4.jsonl @@ -21,6 +21,6 @@ {"type":"command/done","data":{"commandId":"{{command:1}}","kind":"success","text":"Feedback recorded for session {{session:1}}\nAnonymous user: {{id:1}}."}} {"type":"feedback/record","data":{"category":"other"}} {"type":"feedback/message-put","data":{"sessionId":"{{session:1}}","item":{"messageId":"{{message:5}}","rating":"negative","note":"Explain the result.","category":"task-result","version":"{{id:2}}","createdAt":0,"updatedAt":0}}} -{"type":"feedback/message-put","data":{"sessionId":"{{session:1}}","item":{"messageId":"{{message:5}}","rating":"positive","note":"Turn resources released.","version":"{{id:3}}","createdAt":0,"updatedAt":0}}} +{"type":"feedback/message-put","data":{"sessionId":"{{session:1}}","item":{"messageId":"{{message:5}}","rating":"positive","note":"The explanation is clear now.","version":"{{id:3}}","createdAt":0,"updatedAt":0}}} {"type":"feedback/message-delete","data":{"sessionId":"{{session:1}}","messageId":"{{message:5}}"}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} From 9e34a5e8e8cfbce7b798db65623606f3fa9967d6 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 18:18:29 +0800 Subject: [PATCH 24/73] Cover unrelated session endings and type cleanup deregistration explicitly --- packages/experimental/cua/src/turn-inputs.ts | 2 +- .../cua/tests/run-code-composition.spec.ts | 21 +++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/packages/experimental/cua/src/turn-inputs.ts b/packages/experimental/cua/src/turn-inputs.ts index e77c85a949..82029dd8b8 100644 --- a/packages/experimental/cua/src/turn-inputs.ts +++ b/packages/experimental/cua/src/turn-inputs.ts @@ -7,7 +7,7 @@ class InputTurn { readonly controller = new AbortController() readonly signal: AbortSignal private client?: NativeClient - private removeCleanup?: () => void + private removeCleanup: (() => void) | undefined private closing?: Promise constructor(readonly agent: Agent, readonly turn: number, signal: AbortSignal, diff --git a/packages/experimental/cua/tests/run-code-composition.spec.ts b/packages/experimental/cua/tests/run-code-composition.spec.ts index aead14dca0..70b6edd9f1 100644 --- a/packages/experimental/cua/tests/run-code-composition.spec.ts +++ b/packages/experimental/cua/tests/run-code-composition.spec.ts @@ -606,3 +606,24 @@ it('does not resume retained inbox work when stopped during post-turn cleanup', expect(f.agent.session.snapshotEvents().filter(event => event.type === 'turn/start')).toHaveLength(1) expect(f.agent.inbox.hasPending).toBe(true) }) + +it('ignores an unattached Session ending while another task holds input', async () => { + const f = await setup([holdProgram], 'macos', undefined, true, true) + const thinking: PromiseWithResolvers = Promise.withResolvers() + const finish: PromiseWithResolvers = Promise.withResolvers() + f.model.beforeStream = async (index) => { + if (index !== 1) return + thinking.resolve() + await finish.promise + } + const running = f.run() + await thinking.promise + try { + const session = f.ctx.sessions.create(brandString('without-agent')) + session.append('turn/start', { turn: 1 }) + session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) + expect(f.native.held.map(press => press.key)).toEqual(['w']) + expect(f.native.calls.some(call => call.method === 'releaseHeldInputs')).toBe(false) + } finally { finish.resolve(); await running } + expect(f.native.held).toEqual([]) +}) From c0242b0efe9cd7541cc9d03f751c8675c2bbb3f6 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 18:21:51 +0800 Subject: [PATCH 25/73] Restore SDK expectations and use the public inbox view in cleanup tests --- packages/experimental/cua/tests/run-code-composition.spec.ts | 2 +- .../snapshots/python-sdk-single-exe/advanced-ptc/result.json | 4 ++-- .../python-sdk-single-exe/advanced-ptc/session.v4.jsonl | 2 +- scripts/snapshots/python-sdk-single-exe/advanced/result.json | 4 ++-- .../snapshots/python-sdk-single-exe/advanced/session.v4.jsonl | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/packages/experimental/cua/tests/run-code-composition.spec.ts b/packages/experimental/cua/tests/run-code-composition.spec.ts index 70b6edd9f1..d0fe9bfdda 100644 --- a/packages/experimental/cua/tests/run-code-composition.spec.ts +++ b/packages/experimental/cua/tests/run-code-composition.spec.ts @@ -604,7 +604,7 @@ it('does not resume retained inbox work when stopped during post-turn cleanup', await running expect(f.native.held).toEqual([]) expect(f.agent.session.snapshotEvents().filter(event => event.type === 'turn/start')).toHaveLength(1) - expect(f.agent.inbox.hasPending).toBe(true) + expect(f.agent.inbox.nextStep).toHaveLength(1) }) it('ignores an unattached Session ending while another task holds input', async () => { diff --git a/scripts/snapshots/python-sdk-single-exe/advanced-ptc/result.json b/scripts/snapshots/python-sdk-single-exe/advanced-ptc/result.json index 670bf27fe6..590a5001e8 100644 --- a/scripts/snapshots/python-sdk-single-exe/advanced-ptc/result.json +++ b/scripts/snapshots/python-sdk-single-exe/advanced-ptc/result.json @@ -984,7 +984,7 @@ "item": { "messageId": "{{message:1}}", "rating": "positive", - "note": "Turn resources released.", + "note": "The explanation is clear now.", "version": "{{feedback-version:2}}", "createdAt": 0, "updatedAt": 0 @@ -2258,7 +2258,7 @@ "item": { "messageId": "{{message:1}}", "rating": "positive", - "note": "Turn resources released.", + "note": "The explanation is clear now.", "version": "{{feedback-version:2}}", "createdAt": 0, "updatedAt": 0 diff --git a/scripts/snapshots/python-sdk-single-exe/advanced-ptc/session.v4.jsonl b/scripts/snapshots/python-sdk-single-exe/advanced-ptc/session.v4.jsonl index 1259ffbba5..799360745b 100644 --- a/scripts/snapshots/python-sdk-single-exe/advanced-ptc/session.v4.jsonl +++ b/scripts/snapshots/python-sdk-single-exe/advanced-ptc/session.v4.jsonl @@ -45,6 +45,6 @@ {"type":"command/done","data":{"commandId":"{{command:1}}","kind":"success","text":"Feedback recorded for session {{parent}}\nAnonymous user: {{anonymous-user}}."}} {"type":"feedback/record","data":{"category":"other"}} {"type":"feedback/message-put","data":{"sessionId":"{{parent}}","item":{"messageId":"{{message:1}}","rating":"negative","note":"Explain the result.","category":"task-result","version":"{{feedback-version:1}}","createdAt":0,"updatedAt":0}}} -{"type":"feedback/message-put","data":{"sessionId":"{{parent}}","item":{"messageId":"{{message:1}}","rating":"positive","note":"Turn resources released.","version":"{{feedback-version:2}}","createdAt":0,"updatedAt":0}}} +{"type":"feedback/message-put","data":{"sessionId":"{{parent}}","item":{"messageId":"{{message:1}}","rating":"positive","note":"The explanation is clear now.","version":"{{feedback-version:2}}","createdAt":0,"updatedAt":0}}} {"type":"feedback/message-delete","data":{"sessionId":"{{parent}}","messageId":"{{message:1}}"}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/scripts/snapshots/python-sdk-single-exe/advanced/result.json b/scripts/snapshots/python-sdk-single-exe/advanced/result.json index 3a704fd34e..78a94e27da 100644 --- a/scripts/snapshots/python-sdk-single-exe/advanced/result.json +++ b/scripts/snapshots/python-sdk-single-exe/advanced/result.json @@ -1460,7 +1460,7 @@ "item": { "messageId": "{{message:1}}", "rating": "positive", - "note": "Turn resources released.", + "note": "The explanation is clear now.", "version": "{{feedback-version:2}}", "createdAt": 0, "updatedAt": 0 @@ -4868,7 +4868,7 @@ "item": { "messageId": "{{message:1}}", "rating": "positive", - "note": "Turn resources released.", + "note": "The explanation is clear now.", "version": "{{feedback-version:2}}", "createdAt": 0, "updatedAt": 0 diff --git a/scripts/snapshots/python-sdk-single-exe/advanced/session.v4.jsonl b/scripts/snapshots/python-sdk-single-exe/advanced/session.v4.jsonl index 776cc9dcc1..6681e94bc0 100644 --- a/scripts/snapshots/python-sdk-single-exe/advanced/session.v4.jsonl +++ b/scripts/snapshots/python-sdk-single-exe/advanced/session.v4.jsonl @@ -62,6 +62,6 @@ {"type":"command/done","data":{"commandId":"{{command:1}}","kind":"success","text":"Feedback recorded for session {{parent}}\nAnonymous user: {{anonymous-user}}."}} {"type":"feedback/record","data":{"category":"other"}} {"type":"feedback/message-put","data":{"sessionId":"{{parent}}","item":{"messageId":"{{message:1}}","rating":"negative","note":"Explain the result.","category":"task-result","version":"{{feedback-version:1}}","createdAt":0,"updatedAt":0}}} -{"type":"feedback/message-put","data":{"sessionId":"{{parent}}","item":{"messageId":"{{message:1}}","rating":"positive","note":"Turn resources released.","version":"{{feedback-version:2}}","createdAt":0,"updatedAt":0}}} +{"type":"feedback/message-put","data":{"sessionId":"{{parent}}","item":{"messageId":"{{message:1}}","rating":"positive","note":"The explanation is clear now.","version":"{{feedback-version:2}}","createdAt":0,"updatedAt":0}}} {"type":"feedback/message-delete","data":{"sessionId":"{{parent}}","messageId":"{{message:1}}"}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} From 3802a948031dfdd257a9cd4275b0c62eecc79b39 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 18:33:12 +0800 Subject: [PATCH 26/73] Define turn input scope in shared CUA guidance and document Windows support gap --- .../v0.2.2-rc.4/cua-turn-inputs/guide.i18n.yaml | 4 ++-- docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.md | 2 +- docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.zh.md | 2 +- packages/experimental/cua-macos/src/guidance.ts | 4 ++-- packages/experimental/cua-macos/tests/guidance.spec.ts | 5 +++-- packages/experimental/cua-windows/README.i18n.yaml | 4 ++-- packages/experimental/cua-windows/README.md | 1 + packages/experimental/cua-windows/README.zh.md | 1 + packages/experimental/cua-windows/src/guidance.ts | 2 +- .../cua-windows/tests/provider-lifecycle.spec.ts | 2 ++ packages/experimental/cua/README.i18n.yaml | 4 ++-- packages/experimental/cua/README.md | 2 +- packages/experimental/cua/README.zh.md | 2 +- packages/experimental/cua/src/guidance.ts | 4 +++- packages/experimental/cua/src/types.ts | 7 ++++--- 15 files changed, 27 insertions(+), 19 deletions(-) diff --git a/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.i18n.yaml index 22088cda77..ed6291975f 100644 --- a/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.i18n.yaml @@ -9,8 +9,8 @@ en: 34b24b7c3428274b zh: 7e73cf9ba46ff2dd /macos-cua-input-holds-last-for-one-turn/change: - en: 8bf80b8969d46419 - zh: 820fc1b7036ab251 + en: f090c924a02c6a40 + zh: 9690a60ffa37587b /macos-cua-input-holds-last-for-one-turn/migration: en: 87e09c9f8803105a zh: 2408e5b6a29ef924 diff --git a/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.md b/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.md index 478655452e..e5bc626aff 100644 --- a/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.md @@ -8,7 +8,7 @@ English | [中文](guide.zh.md) ## Change -macOS `sendKeyEvent('down')` holds a key across `run_code` and `cua_run_code` calls in the same turn. Returning or throwing from a program no longer releases it while the turn continues. Explicit `up` releases it immediately at the original recipient. Window-directed and system `toggleMouse('down')` join the same lifecycle. After `turn/end`, including failure or user cancellation, CUA releases all remaining keys and mouse buttons in reverse dispatch order and waits for native acknowledgement. The end record can precede release; `whenIdle()` and subsequent CUA input wait for cleanup. Complete `pressKey`, `typeText`, `click` and `drag` operations keep their operation-local cleanup. Windows retains its current behavior. +macOS `sendKeyEvent('down')` holds a key across `run_code` and `cua_run_code` calls in the same turn. Returning or throwing from a program no longer releases it while the turn continues. Explicit `up` releases it immediately at the original recipient. Window-directed and system `toggleMouse('down')` join the same lifecycle. After `turn/end`, including failure or user cancellation, CUA releases all remaining keys and mouse buttons in reverse dispatch order and waits for native acknowledgement. The end record can precede release; `whenIdle()` and subsequent CUA input wait for cleanup. Complete `pressKey`, `typeText`, `click` and `drag` operations keep their operation-local cleanup. The turn scope belongs to shared CUA behavior. Windows has not yet implemented this lifecycle and retains its current behavior. ## Migration diff --git a/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.zh.md index 45c05af79b..1690777d4d 100644 --- a/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.zh.md @@ -8,7 +8,7 @@ description: macOS CUA 的显式键盘和鼠标按下现在可在同一回合内 ## 变更 -macOS 的 `sendKeyEvent('down')` 可在同一回合内跨 `run_code` 和 `cua_run_code` 调用持有按键。程序返回或抛错后,回合仍继续时不再自动释放。显式 `up` 立即向原接收方释放。窗口定向和系统 `toggleMouse('down')` 使用相同生命周期。`turn/end` 之后,包括异常结束和用户取消,CUA 按实际派发顺序的反序释放剩余键盘键和鼠标按钮,并等待原生确认。结束记录可以早于释放;`whenIdle()` 和后续 CUA 输入会等待清理完成。完整的 `pressKey`、`typeText`、`click` 和 `drag` 操作继续在本次操作内清理。Windows 保持现有行为。 +macOS 的 `sendKeyEvent('down')` 可在同一回合内跨 `run_code` 和 `cua_run_code` 调用持有按键。程序返回或抛错后,回合仍继续时不再自动释放。显式 `up` 立即向原接收方释放。窗口定向和系统 `toggleMouse('down')` 使用相同生命周期。`turn/end` 之后,包括异常结束和用户取消,CUA 按实际派发顺序的反序释放剩余键盘键和鼠标按钮,并等待原生确认。结束记录可以早于释放;`whenIdle()` 和后续 CUA 输入会等待清理完成。完整的 `pressKey`、`typeText`、`click` 和 `drag` 操作继续在本次操作内清理。回合持有范围属于共通 CUA 规则。Windows 尚未实现这套生命周期,保持现有行为。 ## 迁移 diff --git a/packages/experimental/cua-macos/src/guidance.ts b/packages/experimental/cua-macos/src/guidance.ts index a3b1cda5a1..edb87c6f29 100644 --- a/packages/experimental/cua-macos/src/guidance.ts +++ b/packages/experimental/cua-macos/src/guidance.ts @@ -10,10 +10,10 @@ function operationGuidance(treeAdvice: string): string { const methodDetails = new Map([ ['cua.listApps', 'Each row represents one running process. To select one of several instances with the same name or bundle ID, pass String(row.pid) to cua.getApp.'], ['cua.findApps', 'Running installation matches include their process ID. Stopped matches have no pid.'], - ['sendKeyEvent', "Send 'down' to hold a key across run_code and cua_run_code calls in the same turn, for example W down, D down, D up, W up. Send 'up' to release it immediately at its original recipient. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. A program returning or throwing keeps its holds while the turn continues. When the turn completes, fails, or is stopped, macOS releases remaining keys and mouse buttons together in reverse press order. pressKey and typeText still release their own presses within the operation."], + ['sendKeyEvent', "For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold."], ['getAccessibilityTree', `macOS accepts maxElements up to 100000 and maxDepth up to 512. If the tree is truncated, select a narrower window or raise the reported limit on the next read. ${treeAdvice} Use element ids from the file only while that observation is current.`], ['mouseMove', 'With useSystemPointer omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again.'], - ['toggleMouse', 'Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemPointer: true on down. Up uses the input route and window saved by down. Physical moves can then drag, including your own mouse movements. Both routes hold across programs in the same turn and release with held keys when the turn ends. click and drag release their own buttons within the operation.'], + ['toggleMouse', 'Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemPointer: true on down. Up uses the input route and window saved by down. Physical moves can then drag, including your own mouse movements.'], ['drag', 'Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control. An explicit system drag shares the session decision with mouseMove and holds the chosen button along the path in the unobscured foreground window.'], ['click', 'click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying.'], ]) diff --git a/packages/experimental/cua-macos/tests/guidance.spec.ts b/packages/experimental/cua-macos/tests/guidance.spec.ts index a32bb159ba..08a21589b6 100644 --- a/packages/experimental/cua-macos/tests/guidance.spec.ts +++ b/packages/experimental/cua-macos/tests/guidance.spec.ts @@ -54,7 +54,8 @@ it('states the macOS accessibility, keyboard, and mouse levels', () => { expect(PLATFORM_GUIDANCE).toContain('Simulated mouse input is available at window level') const pressKey = GUIDANCE.split('\n').find(line => line.startsWith('- pressKey(')) expect(GUIDANCE).toContain("sendKeyEvent(key: string, direction: 'down' | 'up')") - expect(GUIDANCE).toContain('When the turn completes, fails, or is stopped') + expect(COMMON_GUIDANCE).toContain('sendKeyEvent and toggleMouse share one turn-wide hold scope') + expect(COMMON_GUIDANCE).toContain('After turn/end, cleanup releases remaining keys and buttons together in reverse dispatch order') const sharedKeyEvent = COMMON_GUIDANCE.split('\n').find(line => line.startsWith('- sendKeyEvent(')) expect(sharedKeyEvent).toBeDefined() expect(GUIDANCE.split('\n').find(line => line.startsWith('- sendKeyEvent('))).toContain(sharedKeyEvent) @@ -75,7 +76,7 @@ it('documents explicit mouse-button events immediately after mouseMove', () => { const lines = COMMON_GUIDANCE.split('\n') const index = lines.findIndex(line => line.startsWith('- toggleMouse(')) expect(lines[index - 1]).toMatch(/^- mouseMove\(/) - expect(lines[index]).toBe("- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; platform guidance defines their cleanup scope.") + expect(lines[index]).toBe("- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Send 'up' to release a held button immediately.") expect(index).toBeGreaterThan(lines.indexOf('## Simulated mouse')) expect(index).toBeLessThan(lines.indexOf('## Simulated keyboard')) }) diff --git a/packages/experimental/cua-windows/README.i18n.yaml b/packages/experimental/cua-windows/README.i18n.yaml index 1479fbb051..244a61100c 100644 --- a/packages/experimental/cua-windows/README.i18n.yaml +++ b/packages/experimental/cua-windows/README.i18n.yaml @@ -45,8 +45,8 @@ en: db3e2957041fafbb zh: 34f953887dff37f7 /deepseek-ai-dsh-cua-windows/known-limitations-and-deferred-work: - en: 93e47def8054cd3f - zh: 20c19872c775ea98 + en: 7c590d6de4705041 + zh: 3dfa7cd99010308d /deepseek-ai-dsh-cua-windows/known-limitations-and-deferred-work/dev-note: en: 0a1253c6f7b5e8b9 zh: 9f56528562c7c914 diff --git a/packages/experimental/cua-windows/README.md b/packages/experimental/cua-windows/README.md index 1c1fb6959b..f93dd523ee 100644 --- a/packages/experimental/cua-windows/README.md +++ b/packages/experimental/cua-windows/README.md @@ -81,6 +81,7 @@ Inspected results append to model history. Retaining an App, Window, or returned - The npm package omits the Windows helper. Use the [standalone ZIP on x64 or a matching build on ARM64](#setup). - Hover, click, scroll and drag use the system pointer. `requireSystemPointerApproval` does not prompt separately for Windows pointer operations. - Drag checks the topmost window only at its starting point. An overlay from another application along the path or at the destination can receive the drop even while the selected window stays in the foreground. +- The shared CUA hold scope is one turn. Windows has not yet implemented that lifecycle or unified reverse-order cleanup. Explicitly pair every key and mouse down with up; do not rely on automatic turn cleanup. - The helper does not check each key or button release during cleanup. If an input remains held after a failure, release it manually before continuing. - Helper identity hashes only the exe. Different DLLs with the same apphost can reuse the old service. Stop Hosts using the same output directory before rebuilding to avoid locked files. - The Windows handshake requires a positive `maxClickHoldMs`. With zero, it fails with `INVALID_CONFIG` before ordinary clicks or status queries can run. diff --git a/packages/experimental/cua-windows/README.zh.md b/packages/experimental/cua-windows/README.zh.md index b57a4bd438..d2441860f5 100644 --- a/packages/experimental/cua-windows/README.zh.md +++ b/packages/experimental/cua-windows/README.zh.md @@ -81,6 +81,7 @@ kind: "package-reference" - 通过 npm 安装的包不含 Windows helper。x64 可使用独立 ZIP,ARM64 需要对应架构的构建产物,见[配置说明](#setup)。 - 悬停、点击、滚动和拖拽使用系统指针。`requireSystemPointerApproval` 不会为 Windows 操作弹出单独的指针授权提示。 - 拖拽只检查起点处最上层的窗口。若其他应用遮住路径或终点,即使目标仍在前台,也可能把内容拖到其他应用。 +- 共通 CUA 的持有范围是一个回合。Windows 尚未实现这套生命周期和统一反序清理。每次键盘或鼠标 down 都须显式配对 up,不能依赖回合自动清理。 - 清理输入时,helper 不检查每个按键或鼠标按钮的释放结果。操作失败后如有按键或按钮仍处于按下状态,请先手动释放。 - helper 的身份摘要只覆盖 exe。同一 apphost 搭配不同 DLL 时可能复用旧服务。重新构建前请先关闭使用同一输出目录的 Host,避免文件被占用。 - Windows 握手要求 `maxClickHoldMs` 为正整数。设为 0 会使连接以 `INVALID_CONFIG` 失败,连普通点击和状态查询也不可用。 diff --git a/packages/experimental/cua-windows/src/guidance.ts b/packages/experimental/cua-windows/src/guidance.ts index 166581fae9..f8f14225a5 100644 --- a/packages/experimental/cua-windows/src/guidance.ts +++ b/packages/experimental/cua-windows/src/guidance.ts @@ -2,7 +2,7 @@ import { COMMON_GUIDANCE } from '@deepseek-ai/dsh-cua/guidance' /** Windows operation levels, application selectors, and input availability. */ -export const PLATFORM_GUIDANCE = 'Windows: accessibility tree operations are available only at window level. Simulated mouse and keyboard input are available at window level. Supported modifiers: ctrl, alt, shift, win. control is an alias for ctrl.' +export const PLATFORM_GUIDANCE = 'Windows: accessibility tree operations are available only at window level. Simulated mouse and keyboard input are available at window level. Supported modifiers: ctrl, alt, shift, win. control is an alias for ctrl. Turn-wide held-input cleanup is not yet implemented on Windows. Explicitly release every held key and mouse button with up; do not rely on automatic release after turn/end.' const methodDetails = new Map([ ['cua.getApp', 'Windows accepts an exact AUMID returned by listApps or an existing absolute .exe path, including an executable absent from listApps. Display names and PIDs are not alternative selectors. Selection uses the existing application consent flow and starts the application only when it is not running.'], diff --git a/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts index 4b7a68b633..fa50c4eb64 100644 --- a/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts @@ -51,6 +51,8 @@ it('uses an absolute fixture without compiling and disposes the Host runtime', a expect(backend.capabilities.methods).toContain('sendKeyEvent') expect(backend.capabilities.methods).toContain('toggleMouse') expect(backend.turnInputLifecycle).toBeUndefined() + expect(GUIDANCE).toContain('sendKeyEvent and toggleMouse share one turn-wide hold scope') + expect(GUIDANCE).toContain('Turn-wide held-input cleanup is not yet implemented on Windows') const channel = { marker: 'native stream' } native.connect.mockReturnValue(channel) const options = { ...config, helperPath: backend.helperPath, cwd: process.cwd() } diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index dc89dcf285..e16de6bfa6 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -21,8 +21,8 @@ en: 3f638a4a76023fc5 zh: 515aeb5de6ae5b33 /deepseek-ai-dsh-cua/understand-the-implementation: - en: 9c6e811e8844d5f2 - zh: 41e744e238a992c2 + en: a18beb69352e7635 + zh: 6bfe96f036840427 /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 56edc0eec9..72b88efcf2 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -89,7 +89,7 @@ Permission responses identify their platform and report only the state that plat
Shared execution and platform ownership -A provider enables `CuaBackend.turnInputLifecycle` only after its helper accepts `taskId` and `turn` on `sendKeyEvent`, `toggleMouse`, and system `mouseMove`, and acknowledges `releaseHeldInputs({ taskId, turn })`. Provider unload retains lifecycle listeners until program calls and native cleanup have settled. The shared owner starts cleanup from `turn/end`, closes input admission, and awaits native cancellation before independent bounded cleanup. It retains the completion promise through existing Agent maintenance and pre-step waits; `turn/end` and idle notifications alone do not confirm release. An unconfirmed release reports `agent/error` and disables all CUA operations for the task. Providers must record actual dispatch order, targets and routes before posting, implement explicit up and mixed reverse-order cleanup, reject stale turns, and clean only their connection on disconnect. For these providers, `getCapabilities().methods` omits `sendKeyEvent` and `toggleMouse` outside an active turn. Windows leaves this option unset until these native behaviors are implemented; it receives neither new parameters nor cleanup commands. +The shared CUA lifecycle uses one turn as the hold scope for explicit keyboard and mouse downs. Platform guidance describes implementation support, not a different hold scope. A provider enables `CuaBackend.turnInputLifecycle` only after its helper accepts `taskId` and `turn` on `sendKeyEvent`, `toggleMouse`, and system `mouseMove`, and acknowledges `releaseHeldInputs({ taskId, turn })`. Provider unload retains lifecycle listeners until program calls and native cleanup have settled. The shared owner starts cleanup from `turn/end`, closes input admission, and awaits native cancellation before independent bounded cleanup. It retains the completion promise through existing Agent maintenance and pre-step waits; `turn/end` and idle notifications alone do not confirm release. An unconfirmed release reports `agent/error` and disables all CUA operations for the task. Providers must record actual dispatch order, targets and routes before posting, implement explicit up and mixed reverse-order cleanup, reject stale turns, and clean only their connection on disconnect. For these providers, `getCapabilities().methods` omits `sendKeyEvent` and `toggleMouse` outside an active turn. Windows leaves this option unset until these native behaviors are implemented; it receives neither new parameters nor cleanup commands. The [permission store](src/permission-store.ts) uses `storageDomain` with the configured backend. The default JSON backend writes `$DSH_HOME/storages/cua_permissions_.json`, where the digest identifies the canonical profile directory. Each authorization check opens fresh state under the profile's file lock and closes its domain afterward; native dispatch uses a separate application lock. Revocation waits for operations already admitted by another process; after it completes, every process rejects old handles. Files on different machines or PID namespaces must not share this lock. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index e3509fc6ea..0389e2b4a1 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -89,7 +89,7 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边
共享执行与平台职责 -提供方仅在 helper 已接受 `sendKeyEvent`、`toggleMouse` 和系统 `mouseMove` 的 `taskId`、`turn` 参数,并能确认 `releaseHeldInputs({ taskId, turn })` 后,才启用 `CuaBackend.turnInputLifecycle`。提供方卸载时保留生命周期监听器,直到程序调用和原生清理都已结束。共通持有方从 `turn/end` 开始清理,禁止新输入,等待原生取消后用独立且有超时限制的请求释放。它通过现有的 Agent maintenance 和 pre-step 等待保留清理完成结果;单独的 `turn/end` 或空闲通知不表示释放已经确认。释放未经确认时报告 `agent/error`,并禁用该任务的全部 CUA 操作。提供方必须在派发前记录实际顺序、目标与输入方式,实现显式释放和键鼠混合反序清理,拒绝旧回合输入,并在断连时只清理本连接。这些提供方在没有活动回合时,从 `getCapabilities().methods` 中省略 `sendKeyEvent` 和 `toggleMouse`。Windows 在实现这些原生行为前保持此选项未设置,不接收新增参数或清理命令。 +共通 CUA 生命周期以一个回合作为显式键盘和鼠标按下的持有范围。平台指导说明实现支持情况,不定义另一套持有范围。提供方仅在 helper 已接受 `sendKeyEvent`、`toggleMouse` 和系统 `mouseMove` 的 `taskId`、`turn` 参数,并能确认 `releaseHeldInputs({ taskId, turn })` 后,才启用 `CuaBackend.turnInputLifecycle`。提供方卸载时保留生命周期监听器,直到程序调用和原生清理都已结束。共通持有方从 `turn/end` 开始清理,禁止新输入,等待原生取消后用独立且有超时限制的请求释放。它通过现有的 Agent maintenance 和 pre-step 等待保留清理完成结果;单独的 `turn/end` 或空闲通知不表示释放已经确认。释放未经确认时报告 `agent/error`,并禁用该任务的全部 CUA 操作。提供方必须在派发前记录实际顺序、目标与输入方式,实现显式释放和键鼠混合反序清理,拒绝旧回合输入,并在断连时只清理本连接。这些提供方在没有活动回合时,从 `getCapabilities().methods` 中省略 `sendKeyEvent` 和 `toggleMouse`。Windows 在实现这些原生行为前保持此选项未设置,不接收新增参数或清理命令。 [授权存储](src/permission-store.ts)复用 `storageDomain` 和配置的后端。默认 JSON 后端写入 `$DSH_HOME/storages/cua_permissions_.json`,摘要对应 profile 的真实目录。每次授权检查在 profile 文件锁内打开并读取最新状态,随后关闭存储域;原生操作使用单独的应用锁。撤销会等待其他进程已获准执行的操作结束;撤销完成后,各进程都拒绝旧句柄。不同电脑或 PID 命名空间不能共享这把锁。 diff --git a/packages/experimental/cua/src/guidance.ts b/packages/experimental/cua/src/guidance.ts index 37128c264c..0aa590fe1d 100644 --- a/packages/experimental/cua/src/guidance.ts +++ b/packages/experimental/cua/src/guidance.ts @@ -43,7 +43,7 @@ Use an explicit window for screenshots. ## Simulated mouse Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - ${hoverSignature} -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; platform guidance defines their cleanup scope. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Send 'up' to release a held button immediately. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], 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. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. @@ -57,6 +57,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. +Explicit downs from sendKeyEvent and toggleMouse share one turn-wide hold scope across run_code and cua_run_code calls. An explicit up releases input immediately at its original recipient. Program return or failure does not end a continuing turn. After turn/end, cleanup releases remaining keys and buttons together in reverse dispatch order, including on failure or user stop. pressKey, typeText, click, and complete drag release their own inputs within the operation. + click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. 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 54af154c3b..943e071c26 100644 --- a/packages/experimental/cua/src/types.ts +++ b/packages/experimental/cua/src/types.ts @@ -157,7 +157,8 @@ export interface CuaSurface { pressKey(key: string, modifiers?: string[]): Promise /** * Send one key-down or key-up event at the current input focus. - * macOS retains explicit downs across programs within one turn and releases remaining input at turn end. + * Explicit downs share the current turn across programs; cleanup after turn/end releases remaining input. + * macOS implements turn cleanup; Windows support is pending and requires explicit up. * Rejects when the provider does not support keyboard input at this scope. * @param key - Platform-defined key name; modifier keys may themselves be targets. * @param direction - Down establishes a hold; up immediately releases owned input at its saved recipient. @@ -192,8 +193,8 @@ export interface CuaWindow extends CuaSurface { options?: CuaCoordinateOptions & { useSystemPointer?: boolean }): Promise /** * Send one mouse-button down or up event without moving the pointer. - * macOS retains explicit downs within one turn; up uses the saved window and input route. - * Turn completion, failure, or cancellation releases remaining keys and buttons in reverse press order. + * Uses the same turn lifecycle as {@link CuaSurface.sendKeyEvent}; up uses the saved window and input route. + * Implemented turn cleanup releases keys and buttons together in reverse press order after turn/end. * @param mouseButton - Mouse button to press or release. * @param direction - Explicit event direction. * @param options - Request a system button on a provider reporting systemPointer. From 52e966b3d8b7385127a7c645579fadbd04de4692 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 18:35:10 +0800 Subject: [PATCH 27/73] Refresh CUA guidance references and keyless prompt snapshots --- apps/cli/tests/profiles/cua-mcp/expected/reference.md | 4 +++- packages/experimental/cua-macos/README.md | 6 ++++-- packages/experimental/cua-macos/README.zh.md | 6 ++++-- snapshots/sdk/cua-run-code/system-prompt.expected.md | 4 +++- snapshots/session/cua-native/system-prompt.expected.md | 6 ++++-- snapshots/session/cua-ptc/system-prompt.expected.md | 6 ++++-- .../session/cua-run-code-ptc/system-prompt.expected.md | 4 +++- snapshots/session/cua-run-code/system-prompt.expected.md | 4 +++- .../session/ptc-script-retained/system-prompt.expected.md | 6 ++++-- 9 files changed, 32 insertions(+), 14 deletions(-) diff --git a/apps/cli/tests/profiles/cua-mcp/expected/reference.md b/apps/cli/tests/profiles/cua-mcp/expected/reference.md index ada8d5930e..7c9eccb31c 100644 --- a/apps/cli/tests/profiles/cua-mcp/expected/reference.md +++ b/apps/cli/tests/profiles/cua-mcp/expected/reference.md @@ -38,7 +38,7 @@ Use an explicit window for screenshots. ## Simulated mouse Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; platform guidance defines their cleanup scope. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Send 'up' to release a held button immediately. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], 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. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. @@ -52,6 +52,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. +Explicit downs from sendKeyEvent and toggleMouse share one turn-wide hold scope across run_code and cua_run_code calls. An explicit up releases input immediately at its original recipient. Program return or failure does not end a continuing turn. After turn/end, cleanup releases remaining keys and buttons together in reverse dispatch order, including on failure or user stop. pressKey, typeText, click, and complete drag release their own inputs within the operation. + click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. 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-macos/README.md b/packages/experimental/cua-macos/README.md index a74f937141..24caeed865 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -230,7 +230,7 @@ Leave useSystemPointer unset for ordinary mouseMove, drag, and toggleMouse calls Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemPointer?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemPointer omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemPointer?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; platform guidance defines their cleanup scope. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemPointer: true on down. Up uses the input route and window saved by down. Physical moves can then drag, including your own mouse movements. Both routes hold across programs in the same turn and release with held keys when the turn ends. click and drag release their own buttons within the operation. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemPointer?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Send 'up' to release a held button immediately. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemPointer: true on down. Up uses the input route and window saved by down. Physical moves can then drag, including your own mouse movements. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], 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. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying. - 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. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemPointer?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control. An explicit system drag shares the session decision with mouseMove and holds the chosen button along the path in the unobscured foreground window. @@ -242,7 +242,9 @@ Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - 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?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across run_code and cua_run_code calls in the same turn, for example W down, D down, D up, W up. Send 'up' to release it immediately at its original recipient. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. A program returning or throwing keeps its holds while the turn continues. When the turn completes, fails, or is stopped, macOS releases remaining keys and mouse buttons together in reverse press order. pressKey and typeText still release their own presses within the operation. +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. + +Explicit downs from sendKeyEvent and toggleMouse share one turn-wide hold scope across run_code and cua_run_code calls. An explicit up releases input immediately at its original recipient. Program return or failure does not end a continuing turn. After turn/end, cleanup releases remaining keys and buttons together in reverse dispatch order, including on failure or user stop. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index a1ea56e675..fba5586cf1 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -230,7 +230,7 @@ Leave useSystemPointer unset for ordinary mouseMove, drag, and toggleMouse calls Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemPointer?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemPointer omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemPointer?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; platform guidance defines their cleanup scope. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemPointer: true on down. Up uses the input route and window saved by down. Physical moves can then drag, including your own mouse movements. Both routes hold across programs in the same turn and release with held keys when the turn ends. click and drag release their own buttons within the operation. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemPointer?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Send 'up' to release a held button immediately. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemPointer: true on down. Up uses the input route and window saved by down. Physical moves can then drag, including your own mouse movements. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], 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. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying. - 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. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemPointer?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control. An explicit system drag shares the session decision with mouseMove and holds the chosen button along the path in the unobscured foreground window. @@ -242,7 +242,9 @@ Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - 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?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across run_code and cua_run_code calls in the same turn, for example W down, D down, D up, W up. Send 'up' to release it immediately at its original recipient. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. A program returning or throwing keeps its holds while the turn continues. When the turn completes, fails, or is stopped, macOS releases remaining keys and mouse buttons together in reverse press order. pressKey and typeText still release their own presses within the operation. +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. + +Explicit downs from sendKeyEvent and toggleMouse share one turn-wide hold scope across run_code and cua_run_code calls. An explicit up releases input immediately at its original recipient. Program return or failure does not end a continuing turn. After turn/end, cleanup releases remaining keys and buttons together in reverse dispatch order, including on failure or user stop. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/snapshots/sdk/cua-run-code/system-prompt.expected.md b/snapshots/sdk/cua-run-code/system-prompt.expected.md index b4e44f643e..8322a79263 100644 --- a/snapshots/sdk/cua-run-code/system-prompt.expected.md +++ b/snapshots/sdk/cua-run-code/system-prompt.expected.md @@ -72,7 +72,7 @@ Use an explicit window for screenshots. ## Simulated mouse Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; platform guidance defines their cleanup scope. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Send 'up' to release a held button immediately. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], 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. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. @@ -86,6 +86,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. +Explicit downs from sendKeyEvent and toggleMouse share one turn-wide hold scope across run_code and cua_run_code calls. An explicit up releases input immediately at its original recipient. Program return or failure does not end a continuing turn. After turn/end, cleanup releases remaining keys and buttons together in reverse dispatch order, including on failure or user stop. pressKey, typeText, click, and complete drag release their own inputs within the operation. + click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. 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/snapshots/session/cua-native/system-prompt.expected.md b/snapshots/session/cua-native/system-prompt.expected.md index b2c566a0b6..035df22794 100644 --- a/snapshots/session/cua-native/system-prompt.expected.md +++ b/snapshots/session/cua-native/system-prompt.expected.md @@ -75,7 +75,7 @@ Leave useSystemPointer unset for ordinary mouseMove, drag, and toggleMouse calls Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemPointer?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemPointer omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemPointer?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; platform guidance defines their cleanup scope. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemPointer: true on down. Up uses the input route and window saved by down. Physical moves can then drag, including your own mouse movements. Both routes hold across programs in the same turn and release with held keys when the turn ends. click and drag release their own buttons within the operation. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemPointer?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Send 'up' to release a held button immediately. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemPointer: true on down. Up uses the input route and window saved by down. Physical moves can then drag, including your own mouse movements. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], 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. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying. - 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. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemPointer?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control. An explicit system drag shares the session decision with mouseMove and holds the chosen button along the path in the unobscured foreground window. @@ -87,7 +87,9 @@ Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - 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?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across run_code and cua_run_code calls in the same turn, for example W down, D down, D up, W up. Send 'up' to release it immediately at its original recipient. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. A program returning or throwing keeps its holds while the turn continues. When the turn completes, fails, or is stopped, macOS releases remaining keys and mouse buttons together in reverse press order. pressKey and typeText still release their own presses within the operation. +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. + +Explicit downs from sendKeyEvent and toggleMouse share one turn-wide hold scope across run_code and cua_run_code calls. An explicit up releases input immediately at its original recipient. Program return or failure does not end a continuing turn. After turn/end, cleanup releases remaining keys and buttons together in reverse dispatch order, including on failure or user stop. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index 688b1de8ac..7515c1eb12 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -77,7 +77,7 @@ Leave useSystemPointer unset for ordinary mouseMove, drag, and toggleMouse calls Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemPointer?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemPointer omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemPointer?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; platform guidance defines their cleanup scope. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemPointer: true on down. Up uses the input route and window saved by down. Physical moves can then drag, including your own mouse movements. Both routes hold across programs in the same turn and release with held keys when the turn ends. click and drag release their own buttons within the operation. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemPointer?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Send 'up' to release a held button immediately. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemPointer: true on down. Up uses the input route and window saved by down. Physical moves can then drag, including your own mouse movements. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], 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. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying. - 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. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemPointer?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control. An explicit system drag shares the session decision with mouseMove and holds the chosen button along the path in the unobscured foreground window. @@ -89,7 +89,9 @@ Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - 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?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across run_code and cua_run_code calls in the same turn, for example W down, D down, D up, W up. Send 'up' to release it immediately at its original recipient. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. A program returning or throwing keeps its holds while the turn continues. When the turn completes, fails, or is stopped, macOS releases remaining keys and mouse buttons together in reverse press order. pressKey and typeText still release their own presses within the operation. +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. + +Explicit downs from sendKeyEvent and toggleMouse share one turn-wide hold scope across run_code and cua_run_code calls. An explicit up releases input immediately at its original recipient. Program return or failure does not end a continuing turn. After turn/end, cleanup releases remaining keys and buttons together in reverse dispatch order, including on failure or user stop. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/snapshots/session/cua-run-code-ptc/system-prompt.expected.md b/snapshots/session/cua-run-code-ptc/system-prompt.expected.md index 6b0a3f5ef0..4feeec93dc 100644 --- a/snapshots/session/cua-run-code-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-run-code-ptc/system-prompt.expected.md @@ -73,7 +73,7 @@ Use an explicit window for screenshots. ## Simulated mouse Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; platform guidance defines their cleanup scope. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Send 'up' to release a held button immediately. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], 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. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. @@ -87,6 +87,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. +Explicit downs from sendKeyEvent and toggleMouse share one turn-wide hold scope across run_code and cua_run_code calls. An explicit up releases input immediately at its original recipient. Program return or failure does not end a continuing turn. After turn/end, cleanup releases remaining keys and buttons together in reverse dispatch order, including on failure or user stop. pressKey, typeText, click, and complete drag release their own inputs within the operation. + click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. 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/snapshots/session/cua-run-code/system-prompt.expected.md b/snapshots/session/cua-run-code/system-prompt.expected.md index 8eebb36749..0eca5d335d 100644 --- a/snapshots/session/cua-run-code/system-prompt.expected.md +++ b/snapshots/session/cua-run-code/system-prompt.expected.md @@ -71,7 +71,7 @@ Use an explicit window for screenshots. ## Simulated mouse Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; platform guidance defines their cleanup scope. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Send 'up' to release a held button immediately. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], 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. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. @@ -85,6 +85,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. +Explicit downs from sendKeyEvent and toggleMouse share one turn-wide hold scope across run_code and cua_run_code calls. An explicit up releases input immediately at its original recipient. Program return or failure does not end a continuing turn. After turn/end, cleanup releases remaining keys and buttons together in reverse dispatch order, including on failure or user stop. pressKey, typeText, click, and complete drag release their own inputs within the operation. + click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. 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/snapshots/session/ptc-script-retained/system-prompt.expected.md b/snapshots/session/ptc-script-retained/system-prompt.expected.md index 64e5e36174..0e648f3168 100644 --- a/snapshots/session/ptc-script-retained/system-prompt.expected.md +++ b/snapshots/session/ptc-script-retained/system-prompt.expected.md @@ -77,7 +77,7 @@ Leave useSystemPointer unset for ordinary mouseMove, drag, and toggleMouse calls Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemPointer?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemPointer omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemPointer?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; platform guidance defines their cleanup scope. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemPointer: true on down. Up uses the input route and window saved by down. Physical moves can then drag, including your own mouse movements. Both routes hold across programs in the same turn and release with held keys when the turn ends. click and drag release their own buttons within the operation. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemPointer?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Send 'up' to release a held button immediately. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemPointer: true on down. Up uses the input route and window saved by down. Physical moves can then drag, including your own mouse movements. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], 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. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying. - 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. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemPointer?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control. An explicit system drag shares the session decision with mouseMove and holds the chosen button along the path in the unobscured foreground window. @@ -89,7 +89,9 @@ Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - 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?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across run_code and cua_run_code calls in the same turn, for example W down, D down, D up, W up. Send 'up' to release it immediately at its original recipient. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. A program returning or throwing keeps its holds while the turn continues. When the turn completes, fails, or is stopped, macOS releases remaining keys and mouse buttons together in reverse press order. pressKey and typeText still release their own presses within the operation. +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. + +Explicit downs from sendKeyEvent and toggleMouse share one turn-wide hold scope across run_code and cua_run_code calls. An explicit up releases input immediately at its original recipient. Program return or failure does not end a continuing turn. After turn/end, cleanup releases remaining keys and buttons together in reverse dispatch order, including on failure or user stop. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. From 1feef12e616ee3859bc7bc596118bd9285cf9782 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 18:38:56 +0800 Subject: [PATCH 28/73] Keep CUA capability methods independent of turn state --- .../2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml | 8 ++++---- .../2026-11-05-cua-scoped-surfaces-and-input.md | 4 ++-- .../2026-11-05-cua-scoped-surfaces-and-input.zh.md | 4 ++-- .../cua-macos/tests/provider-lifecycle.spec.ts | 4 ++-- packages/experimental/cua-mcp/tests/composition.spec.ts | 3 ++- packages/experimental/cua/README.i18n.yaml | 4 ++-- packages/experimental/cua/README.md | 2 +- packages/experimental/cua/README.zh.md | 2 +- packages/experimental/cua/src/index.ts | 3 +-- 9 files changed, 17 insertions(+), 17 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 c2abf0a1c3..bb1e5cbd05 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,11 +9,11 @@ en: f72db0b79aa02fb5 zh: b91c1f177dc93ab4 /agent-note-cua-scoped-surfaces-and-separated-input-capabilities/decision: - en: b4814d1d835a27d0 - zh: d398a39c2d75756f + en: 41fd533d5be7642b + zh: c6fcbabec22bdbb7 /agent-note-cua-scoped-surfaces-and-separated-input-capabilities/alternatives-considered: en: 32c970ae153e0f6c zh: 8431be0a10ffed15 /agent-note-cua-scoped-surfaces-and-separated-input-capabilities/consequences: - en: 3a12a64b45e17f51 - zh: 28627d190a21b5b9 + en: d814ec2360363bc5 + zh: 3249ec743514f81b 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 2e021166cb..1ace831677 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 @@ -12,7 +12,7 @@ Application and window objects share accessibility operations, but only an expli `CuaSurface` declares operations shared by application and window objects; `CuaApp` and `CuaWindow` extend it with their own operations. One base factory builds the surface, and the derived factories inject scope parameters plus `requireAccessibility` and `requireKeyboard` checks. The shared base never branches on a capability that exists only for applications. -Provider startup capabilities are static. Platform, supported methods, application-level accessibility, keyboard scopes, browser support, and coordinate space are fixed when the provider is installed. The native `getCapabilities` RPC reports runtime permissions and session lock only; `installCua` merges the two layers for the model-visible result and omits turn-managed hold methods when the caller has no active turn. The neutral RPC is a common operation representation, not a capability inventory; provider guidance names the actions its platform supports. +Provider startup capabilities are static. Platform, supported methods, application-level accessibility, keyboard scopes, browser support, and coordinate space are fixed when the provider is installed. The native `getCapabilities` RPC reports runtime permissions and session lock only; `installCua` merges the two layers for the model-visible result. The neutral RPC is a common operation representation, not a capability inventory; provider guidance names the actions its platform supports. 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. @@ -34,6 +34,6 @@ Within one API instance, the object facade keeps one current accessibility snaps Element IDs belong to the application's current accessibility snapshot. Reading one window replaces the facade’s current snapshot for that application, so callers observe again and confirm the IDs they use. The new read does not guarantee that an old string is rejected or that an ID changes; callers must not assume an older ID still identifies the same control. Pointer input and screenshots require an explicit window object; callers enumerate windows first. -Keyboard behavior follows the provider's supported scopes. A caller that uses `sendKeyEvent` controls its down/up pairing. macOS holds explicit downs across programs within an active turn and releases remaining keys and mouse buttons together when the turn completes, fails, or is stopped. Keyboard modifier names are provider-defined, so the same string may have different support across providers. +Keyboard behavior follows the provider's supported scopes. A caller that uses `sendKeyEvent` controls its down/up pairing. The shared CUA hold scope is the active turn: explicit downs persist across programs, and cleanup after turn/end releases remaining keys and mouse buttons together. macOS implements this lifecycle; Windows implementation is pending. Keyboard modifier names are provider-defined, so the same string may have different support across providers. Provider guidance owns the list of supported actions. Adding a method to the shared schema does not claim that every provider implements it, and the merged `getCapabilities` result remains the runtime source for permissions and session lock. 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 7f62dbb167..9c488551ec 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 @@ -12,7 +12,7 @@ Status: implemented `CuaSurface` 声明应用对象与窗口对象共享的操作;`CuaApp` 与 `CuaWindow` 通过扩展它增加各自的操作。一个基类工厂负责构建表面,派生工厂注入作用域参数以及 `requireAccessibility`、`requireKeyboard` 检查。共享基类从不为只属于应用的能力分支。 -Provider 的启动能力是静态的。平台、支持的方法、应用级辅助功能、键盘作用域、浏览器支持和坐标空间在安装 provider 时固定。原生 `getCapabilities` RPC 只报告运行时权限和会话锁定状态;`installCua` 为模型可见结果合并两层,并在调用方没有活动回合时省略按回合管理的持有方法。中立的 RPC 是通用操作表示,不是能力清单;provider 指导文本说明其平台支持的动作。 +Provider 的启动能力是静态的。平台、支持的方法、应用级辅助功能、键盘作用域、浏览器支持和坐标空间在安装 provider 时固定。原生 `getCapabilities` RPC 只报告运行时权限和会话锁定状态;`installCua` 为模型可见结果合并两层。中立的 RPC 是通用操作表示,不是能力清单;provider 指导文本说明其平台支持的动作。 键盘输入把按键与修饰键分开:`pressKey(key, modifiers?)` 在按住所列修饰键时按下并释放一个键,其键盘修饰键列表是 provider 定义的普通字符串数组。`sendKeyEvent(key, direction)` 只发送一次按下或抬起,不隐式发送相反事件。因此调用方可以保持修饰键或拆分手势;两个方法都不接受组合键字符串,共享 schema 也不枚举平台按键名。 @@ -34,6 +34,6 @@ Provider 的启动能力是静态的。平台、支持的方法、应用级辅 元素 ID 属于应用当前的辅助功能快照。读取一个窗口会替换门面对该应用的当前快照,因此调用方需要重新观察并确认要使用的 ID。新的读取不保证拒绝旧字符串,也不保证 ID 会改变;调用方不得假定旧 ID 仍指向同一控件。指针输入和截图都要求显式的窗口对象;调用方先枚举窗口。 -键盘行为遵循 provider 支持的作用域。使用 `sendKeyEvent` 的调用方控制按下与抬起的配对。在 macOS 上,显式按下可在活动回合内跨程序保持;回合完成、失败或停止时统一释放剩余键盘键和鼠标按钮。键盘修饰键名称由 provider 定义,同一字符串在不同 provider 上可能支持不同。 +键盘行为遵循 provider 支持的作用域。使用 `sendKeyEvent` 的调用方控制按下与抬起的配对。共通 CUA 的持有范围是活动回合:显式按下跨程序保持,turn/end 之后统一清理剩余键盘键和鼠标按钮。macOS 已实现这套生命周期,Windows 待实现。键盘修饰键名称由 provider 定义,同一字符串在不同 provider 上可能支持不同。 Provider 指导文本负责支持动作的清单。把方法加入共享 schema 并不表示每个 provider 都已实现它;合并后的 `getCapabilities` 结果仍是权限和会话锁定状态的运行时来源。 diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index 8da8ef0b51..4734ec3510 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -336,7 +336,7 @@ it('correlates a native request with its logged tool invocation', async () => { expect(native.request).toHaveBeenCalledExactlyOnceWith('listApps', {}, expect.any(AbortSignal), brandString('lifecycle-1')) }) -it('merges startup capabilities into runtime native fields', async () => { +it('reports declared methods outside a turn while merging runtime native fields', async () => { const f = await setup() const runtime = { permissions: { accessibility: true, screenRecording: false }, sessionLocked: false } native.request.mockResolvedValueOnce(runtime) @@ -346,7 +346,7 @@ it('merges startup capabilities into runtime native fields', async () => { coordinateSpace: 'screenshot-pixels', methods: [ 'activate', 'click', 'drag', 'findApps', 'getApp', 'getCapabilities', 'getState', 'invoke', 'listActions', 'listApps', 'listWindows', 'mouseMove', 'paste', 'performAction', 'pressKey', 'screenshot', 'scroll', - 'selectText', 'setValue', 'show', 'typeText', + 'selectText', 'sendKeyEvent', 'setValue', 'show', 'toggleMouse', 'typeText', ] }) expect(native.request).toHaveBeenCalledExactlyOnceWith('getCapabilities', {}, expect.any(AbortSignal), brandString('lifecycle-1')) }) diff --git a/packages/experimental/cua-mcp/tests/composition.spec.ts b/packages/experimental/cua-mcp/tests/composition.spec.ts index b574ff5882..866e570a27 100644 --- a/packages/experimental/cua-mcp/tests/composition.spec.ts +++ b/packages/experimental/cua-mcp/tests/composition.spec.ts @@ -186,7 +186,8 @@ describe('Computer Use MCP composition', () => { const { client, native, run } = await setup() expect(client.getInstructions()).toContain('MCP programs cannot hold keys or mouse buttons') const capabilities = await run('inspect(JSON.stringify((await cua.getCapabilities()).methods))') - expect(texts(capabilities).join('')).not.toMatch(/sendKeyEvent|toggleMouse/) + expect(texts(capabilities).join('')).toContain('sendKeyEvent') + expect(texts(capabilities).join('')).toContain('toggleMouse') const selected = await run('var app = await cua.getApp("test.fixture"); var win = await app.getWindow("7"); await win.getAccessibilityTree()') expect(selected.isError).not.toBe(true) for (const code of ['await app.sendKeyEvent("w", "down")', 'await win.toggleMouse("left", "down")']) { diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index e16de6bfa6..83a1ccb07e 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -21,8 +21,8 @@ en: 3f638a4a76023fc5 zh: 515aeb5de6ae5b33 /deepseek-ai-dsh-cua/understand-the-implementation: - en: a18beb69352e7635 - zh: 6bfe96f036840427 + en: 92c7e05fc2066d8f + zh: c8b1484f4dcd79c3 /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 72b88efcf2..bd879bc1ac 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -89,7 +89,7 @@ Permission responses identify their platform and report only the state that plat
Shared execution and platform ownership -The shared CUA lifecycle uses one turn as the hold scope for explicit keyboard and mouse downs. Platform guidance describes implementation support, not a different hold scope. A provider enables `CuaBackend.turnInputLifecycle` only after its helper accepts `taskId` and `turn` on `sendKeyEvent`, `toggleMouse`, and system `mouseMove`, and acknowledges `releaseHeldInputs({ taskId, turn })`. Provider unload retains lifecycle listeners until program calls and native cleanup have settled. The shared owner starts cleanup from `turn/end`, closes input admission, and awaits native cancellation before independent bounded cleanup. It retains the completion promise through existing Agent maintenance and pre-step waits; `turn/end` and idle notifications alone do not confirm release. An unconfirmed release reports `agent/error` and disables all CUA operations for the task. Providers must record actual dispatch order, targets and routes before posting, implement explicit up and mixed reverse-order cleanup, reject stale turns, and clean only their connection on disconnect. For these providers, `getCapabilities().methods` omits `sendKeyEvent` and `toggleMouse` outside an active turn. Windows leaves this option unset until these native behaviors are implemented; it receives neither new parameters nor cleanup commands. +The shared CUA lifecycle uses one turn as the hold scope for explicit keyboard and mouse downs. Platform guidance describes implementation support, not a different hold scope. A provider enables `CuaBackend.turnInputLifecycle` only after its helper accepts `taskId` and `turn` on `sendKeyEvent`, `toggleMouse`, and system `mouseMove`, and acknowledges `releaseHeldInputs({ taskId, turn })`. Provider unload retains lifecycle listeners until program calls and native cleanup have settled. The shared owner starts cleanup from `turn/end`, closes input admission, and awaits native cancellation before independent bounded cleanup. It retains the completion promise through existing Agent maintenance and pre-step waits; `turn/end` and idle notifications alone do not confirm release. An unconfirmed release reports `agent/error` and disables all CUA operations for the task. Providers must record actual dispatch order, targets and routes before posting, implement explicit up and mixed reverse-order cleanup, reject stale turns, and clean only their connection on disconnect. `getCapabilities().methods` reports the provider’s declared methods independently of turn state; explicit hold operations require an active turn when dispatched. Windows leaves this option unset until these native behaviors are implemented; it receives neither new parameters nor cleanup commands. The [permission store](src/permission-store.ts) uses `storageDomain` with the configured backend. The default JSON backend writes `$DSH_HOME/storages/cua_permissions_.json`, where the digest identifies the canonical profile directory. Each authorization check opens fresh state under the profile's file lock and closes its domain afterward; native dispatch uses a separate application lock. Revocation waits for operations already admitted by another process; after it completes, every process rejects old handles. Files on different machines or PID namespaces must not share this lock. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index 0389e2b4a1..e864d67e6d 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -89,7 +89,7 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边
共享执行与平台职责 -共通 CUA 生命周期以一个回合作为显式键盘和鼠标按下的持有范围。平台指导说明实现支持情况,不定义另一套持有范围。提供方仅在 helper 已接受 `sendKeyEvent`、`toggleMouse` 和系统 `mouseMove` 的 `taskId`、`turn` 参数,并能确认 `releaseHeldInputs({ taskId, turn })` 后,才启用 `CuaBackend.turnInputLifecycle`。提供方卸载时保留生命周期监听器,直到程序调用和原生清理都已结束。共通持有方从 `turn/end` 开始清理,禁止新输入,等待原生取消后用独立且有超时限制的请求释放。它通过现有的 Agent maintenance 和 pre-step 等待保留清理完成结果;单独的 `turn/end` 或空闲通知不表示释放已经确认。释放未经确认时报告 `agent/error`,并禁用该任务的全部 CUA 操作。提供方必须在派发前记录实际顺序、目标与输入方式,实现显式释放和键鼠混合反序清理,拒绝旧回合输入,并在断连时只清理本连接。这些提供方在没有活动回合时,从 `getCapabilities().methods` 中省略 `sendKeyEvent` 和 `toggleMouse`。Windows 在实现这些原生行为前保持此选项未设置,不接收新增参数或清理命令。 +共通 CUA 生命周期以一个回合作为显式键盘和鼠标按下的持有范围。平台指导说明实现支持情况,不定义另一套持有范围。提供方仅在 helper 已接受 `sendKeyEvent`、`toggleMouse` 和系统 `mouseMove` 的 `taskId`、`turn` 参数,并能确认 `releaseHeldInputs({ taskId, turn })` 后,才启用 `CuaBackend.turnInputLifecycle`。提供方卸载时保留生命周期监听器,直到程序调用和原生清理都已结束。共通持有方从 `turn/end` 开始清理,禁止新输入,等待原生取消后用独立且有超时限制的请求释放。它通过现有的 Agent maintenance 和 pre-step 等待保留清理完成结果;单独的 `turn/end` 或空闲通知不表示释放已经确认。释放未经确认时报告 `agent/error`,并禁用该任务的全部 CUA 操作。提供方必须在派发前记录实际顺序、目标与输入方式,实现显式释放和键鼠混合反序清理,拒绝旧回合输入,并在断连时只清理本连接。`getCapabilities().methods` 报告提供方声明的方法,不随回合状态变化;显式持有操作在派发时要求活动回合。Windows 在实现这些原生行为前保持此选项未设置,不接收新增参数或清理命令。 [授权存储](src/permission-store.ts)复用 `storageDomain` 和配置的后端。默认 JSON 后端写入 `$DSH_HOME/storages/cua_permissions_.json`,摘要对应 profile 的真实目录。每次授权检查在 profile 文件锁内打开并读取最新状态,随后关闭存储域;原生操作使用单独的应用锁。撤销会等待其他进程已获准执行的操作结束;撤销完成后,各进程都拒绝旧句柄。不同电脑或 PID 命名空间不能共享这把锁。 diff --git a/packages/experimental/cua/src/index.ts b/packages/experimental/cua/src/index.ts index eaecbaac43..d5a1148bf1 100644 --- a/packages/experimental/cua/src/index.ts +++ b/packages/experimental/cua/src/index.ts @@ -363,11 +363,10 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) if (method === 'getCapabilities') { const runtime = z.record(z.string(), z.json()).parse(result) const capabilities = backend.capabilities - const canHoldInput = !inputTurns || inputTurns.scope(agent) !== undefined return { ...runtime, platform: capabilities.platform, systemPointer, - methods: capabilities.methods.filter(method => canHoldInput || (method !== 'sendKeyEvent' && method !== 'toggleMouse')), + methods: [...capabilities.methods], appLevelAccessibility: capabilities.appLevelAccessibility, keyboard: [...capabilities.keyboard], browser: capabilities.browser, From 68f939ae2de9bcc31a2335de72770a835120334e Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 19 Nov 2026 10:26:35 +0800 Subject: [PATCH 29/73] Report native held input after programs and release on failure or cancellation --- ...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-held-inputs/guide.i18n.yaml | 16 + .../v0.2.2-rc.4/cua-held-inputs/guide.md | 17 + .../v0.2.2-rc.4/cua-held-inputs/guide.zh.md | 17 + .../cua-turn-inputs/guide.i18n.yaml | 16 - .../v0.2.2-rc.4/cua-turn-inputs/guide.md | 19 -- .../v0.2.2-rc.4/cua-turn-inputs/guide.zh.md | 19 -- .../experimental/cua-macos/README.i18n.yaml | 8 +- packages/experimental/cua-macos/README.md | 4 +- packages/experimental/cua-macos/README.zh.md | 4 +- .../cua-macos/native/README.i18n.yaml | 4 +- .../experimental/cua-macos/native/README.md | 2 +- .../cua-macos/native/README.zh.md | 4 +- .../native/Sources/CuaNative/AXWorker.swift | 8 +- .../native/Sources/CuaNative/HeldInputs.swift | 76 +++-- .../Sources/CuaNative/KeyboardInput.swift | 8 +- .../CuaNative/NativeProtocol.generated.swift | 9 +- .../Sources/CuaNative/RequestAdmission.swift | 3 - .../CuaNative/RequestCoordinator.swift | 13 +- .../cua-macos/native/generate-protocol.ts | 10 +- .../cua-macos/native/protocol.schema.json | 65 ++-- .../native/tests/native_test_support.py | 7 +- .../native/tests/shared_helper_e2e.py | 7 +- .../native/tests/swift/HeldInputTests.swift | 52 +-- .../native/tests/test_ax_projection.py | 2 +- packages/experimental/cua-macos/src/index.ts | 2 +- .../cua-macos/tests/guidance.spec.ts | 4 +- ...ktop.e2e.ts => held-inputs.desktop.e2e.ts} | 9 +- .../tests/provider-lifecycle.spec.ts | 38 +-- .../experimental/cua-mcp/README.i18n.yaml | 4 +- packages/experimental/cua-mcp/README.md | 2 +- packages/experimental/cua-mcp/README.zh.md | 2 +- packages/experimental/cua-mcp/src/server.ts | 2 +- .../cua-mcp/tests/composition.spec.ts | 33 +- .../experimental/cua-windows/README.i18n.yaml | 4 +- packages/experimental/cua-windows/README.md | 2 +- .../experimental/cua-windows/README.zh.md | 2 +- .../experimental/cua-windows/src/guidance.ts | 2 +- .../tests/provider-lifecycle.spec.ts | 6 +- packages/experimental/cua/README.i18n.yaml | 4 +- packages/experimental/cua/README.md | 2 +- packages/experimental/cua/README.zh.md | 2 +- packages/experimental/cua/src/guidance.ts | 2 +- packages/experimental/cua/src/held-inputs.ts | 175 ++++++++++ packages/experimental/cua/src/index.ts | 33 +- .../experimental/cua/src/tool-registration.ts | 8 +- packages/experimental/cua/src/turn-inputs.ts | 121 ------- packages/experimental/cua/src/types.ts | 8 +- .../cua/tests/run-code-composition.spec.ts | 309 ++++++------------ .../session/cua-run-code/native-channel.d.mts | 2 +- .../session/cua-run-code/native-channel.mjs | 12 +- snapshots/session/cua-run-code/provider.mjs | 2 +- 54 files changed, 572 insertions(+), 618 deletions(-) create mode 100644 docs/upgrade-guide/v0.2.2-rc.4/cua-held-inputs/guide.i18n.yaml create mode 100644 docs/upgrade-guide/v0.2.2-rc.4/cua-held-inputs/guide.md create mode 100644 docs/upgrade-guide/v0.2.2-rc.4/cua-held-inputs/guide.zh.md delete mode 100644 docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.i18n.yaml delete mode 100644 docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.md delete mode 100644 docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.zh.md rename packages/experimental/cua-macos/tests/{turn-inputs.desktop.e2e.ts => held-inputs.desktop.e2e.ts} (93%) create mode 100644 packages/experimental/cua/src/held-inputs.ts delete mode 100644 packages/experimental/cua/src/turn-inputs.ts 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 bb1e5cbd05..db576d9053 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 @@ -15,5 +15,5 @@ en: 32c970ae153e0f6c zh: 8431be0a10ffed15 /agent-note-cua-scoped-surfaces-and-separated-input-capabilities/consequences: - en: d814ec2360363bc5 - zh: 3249ec743514f81b + en: 7bb0a5c23044b09c + zh: ca7c4b860660b5ce 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 1ace831677..ab108f5cae 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 @@ -34,6 +34,6 @@ Within one API instance, the object facade keeps one current accessibility snaps Element IDs belong to the application's current accessibility snapshot. Reading one window replaces the facade’s current snapshot for that application, so callers observe again and confirm the IDs they use. The new read does not guarantee that an old string is rejected or that an ID changes; callers must not assume an older ID still identifies the same control. Pointer input and screenshots require an explicit window object; callers enumerate windows first. -Keyboard behavior follows the provider's supported scopes. A caller that uses `sendKeyEvent` controls its down/up pairing. The shared CUA hold scope is the active turn: explicit downs persist across programs, and cleanup after turn/end releases remaining keys and mouse buttons together. macOS implements this lifecycle; Windows implementation is pending. Keyboard modifier names are provider-defined, so the same string may have different support across providers. +Keyboard behavior follows the provider's supported scopes. A caller that uses `sendKeyEvent` controls its down/up pairing. Native input ownership follows the task and connection. Successful programs report remaining held input; normal program and turn endings do not release it. Explicit up, program failure, user cancellation and resource disposal release owned input. macOS implements this lifecycle; Windows implementation is pending. Keyboard modifier names are provider-defined, so the same string may have different support across providers. Provider guidance owns the list of supported actions. Adding a method to the shared schema does not claim that every provider implements it, and the merged `getCapabilities` result remains the runtime source for permissions and session lock. 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 9c488551ec..a7370e5643 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 @@ -34,6 +34,6 @@ Provider 的启动能力是静态的。平台、支持的方法、应用级辅 元素 ID 属于应用当前的辅助功能快照。读取一个窗口会替换门面对该应用的当前快照,因此调用方需要重新观察并确认要使用的 ID。新的读取不保证拒绝旧字符串,也不保证 ID 会改变;调用方不得假定旧 ID 仍指向同一控件。指针输入和截图都要求显式的窗口对象;调用方先枚举窗口。 -键盘行为遵循 provider 支持的作用域。使用 `sendKeyEvent` 的调用方控制按下与抬起的配对。共通 CUA 的持有范围是活动回合:显式按下跨程序保持,turn/end 之后统一清理剩余键盘键和鼠标按钮。macOS 已实现这套生命周期,Windows 待实现。键盘修饰键名称由 provider 定义,同一字符串在不同 provider 上可能支持不同。 +键盘行为遵循 provider 支持的作用域。使用 `sendKeyEvent` 的调用方控制按下与抬起的配对。原生输入所有权属于任务和连接。成功结束的程序报告剩余持有输入,正常程序结束和回合结束不释放。显式 up、程序失败、用户取消和资源销毁释放所属输入。macOS 已实现这套生命周期,Windows 待实现。键盘修饰键名称由 provider 定义,同一字符串在不同 provider 上可能支持不同。 Provider 指导文本负责支持动作的清单。把方法加入共享 schema 并不表示每个 provider 都已实现它;合并后的 `getCapabilities` 结果仍是权限和会话锁定状态的运行时来源。 diff --git a/docs/upgrade-guide/v0.2.2-rc.4/cua-held-inputs/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.4/cua-held-inputs/guide.i18n.yaml new file mode 100644 index 0000000000..9464ae396a --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.4/cua-held-inputs/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.4/cua-held-inputs/guide.md +/: + en: aa41a4beebdac9bf + zh: 0c027e6be34dae49 +/cua-reports-held-input-after-programs: + en: 11e9deecba32e4e4 + zh: 3410b1430be58683 +/cua-reports-held-input-after-programs/change: + en: 5b321223d0dead45 + zh: d0d09bd63dd303c2 +/cua-reports-held-input-after-programs/migration: + en: ff2470e52eb67983 + zh: 8fd179145c4da20a diff --git a/docs/upgrade-guide/v0.2.2-rc.4/cua-held-inputs/guide.md b/docs/upgrade-guide/v0.2.2-rc.4/cua-held-inputs/guide.md new file mode 100644 index 0000000000..9a3bd7a9cd --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.4/cua-held-inputs/guide.md @@ -0,0 +1,17 @@ +--- +kind: upgrade-guide +description: Explicit macOS CUA input persists across programs and turns, with system reminders after successful programs. +--- +# CUA reports held input after programs + +English | [中文](guide.zh.md) + +## Change + +macOS explicit `sendKeyEvent('down')` and `toggleMouse('down')` remain held across programs and turns until an explicit `up`. Normal completion does not release them. After a successful `run_code` or `cua_run_code`, a system reminder lists any remaining keys and mouse buttons, their application or window and actual input mode. Program failure, user stop, connection closure, environment reset and disposal release owned input in reverse dispatch order. Complete `pressKey`, `typeText`, `click` and `drag` actions keep their operation-local cleanup. DSH and MCP use the same behavior. Windows reporting and unified cleanup remain unimplemented. + +## Migration + +1. Pair explicit downs with ups when input should stop. Read the reminder before continuing; no reminder is added when no input remains held. +2. Upgrade the macOS package and helper together. A custom `helperPath` must implement the task-owned `getHeldInputs` and `releaseHeldInputs` private operations. +3. Verify that one successful program can hold a key, receive its reminder, and release it in a later program. Program failure and cancellation must release it before they finish. If cleanup cannot be confirmed, CUA disables further operations for that task; inspect the desktop manually before starting another task. diff --git a/docs/upgrade-guide/v0.2.2-rc.4/cua-held-inputs/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.4/cua-held-inputs/guide.zh.md new file mode 100644 index 0000000000..0cf22a9379 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.4/cua-held-inputs/guide.zh.md @@ -0,0 +1,17 @@ +--- +kind: upgrade-guide +description: macOS CUA 的显式输入跨程序和回合保持,成功结束的程序通过 system reminder 报告持有状态。 +--- +# CUA 在程序结束后报告持有输入 + +[English](guide.md) | 中文 + +## 变更 + +macOS 的显式 `sendKeyEvent('down')` 和 `toggleMouse('down')` 跨程序、跨回合保持,直到显式 `up`。正常结束不释放它们。成功结束的 `run_code` 或 `cua_run_code` 通过 system reminder 列出剩余键盘键和鼠标按钮、所属应用或窗口及实际输入方式。程序失败、用户停止、断连、环境重置和销毁按派发顺序的反序释放所属输入。完整的 `pressKey`、`typeText`、`click` 和 `drag` 保持操作内清理。DSH 和 MCP 使用相同行为。Windows 的状态报告和统一清理仍未实现。 + +## 迁移 + +1. 输入不再需要保持时,将显式 down 与 up 配对。继续操作前阅读提醒;没有持有输入时不添加提醒。 +2. 同步升级 macOS 包和 helper。自定义 `helperPath` 必须实现按任务区分的 `getHeldInputs` 和 `releaseHeldInputs` 私有操作。 +3. 验证成功结束的程序能持有按键、收到提醒,并在后续程序中释放。程序失败和取消必须在结束前释放它。清理无法确认时,CUA 禁用该任务后续操作;请手动检查桌面后再创建其他任务。 diff --git a/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.i18n.yaml deleted file mode 100644 index ed6291975f..0000000000 --- a/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.i18n.yaml +++ /dev/null @@ -1,16 +0,0 @@ -# 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.4/cua-turn-inputs/guide.md -/: - en: 41907c88d906eadf - zh: 738dc3d3b4cc33e4 -/macos-cua-input-holds-last-for-one-turn: - en: 34b24b7c3428274b - zh: 7e73cf9ba46ff2dd -/macos-cua-input-holds-last-for-one-turn/change: - en: f090c924a02c6a40 - zh: 9690a60ffa37587b -/macos-cua-input-holds-last-for-one-turn/migration: - en: 87e09c9f8803105a - zh: 2408e5b6a29ef924 diff --git a/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.md b/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.md deleted file mode 100644 index e5bc626aff..0000000000 --- a/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -kind: upgrade-guide -description: macOS CUA explicit key and mouse downs now remain held across program executions within a turn. ---- -# macOS CUA input holds last for one turn - -English | [中文](guide.zh.md) - -## Change - -macOS `sendKeyEvent('down')` holds a key across `run_code` and `cua_run_code` calls in the same turn. Returning or throwing from a program no longer releases it while the turn continues. Explicit `up` releases it immediately at the original recipient. Window-directed and system `toggleMouse('down')` join the same lifecycle. After `turn/end`, including failure or user cancellation, CUA releases all remaining keys and mouse buttons in reverse dispatch order and waits for native acknowledgement. The end record can precede release; `whenIdle()` and subsequent CUA input wait for cleanup. Complete `pressKey`, `typeText`, `click` and `drag` operations keep their operation-local cleanup. The turn scope belongs to shared CUA behavior. Windows has not yet implemented this lifecycle and retains its current behavior. - -## Migration - -MCP does not supply DSH turn boundaries. Explicit macOS holds through `sendKeyEvent` or `toggleMouse` are unavailable there; replace them with complete `pressKey`, `click`, or `drag` actions. System pointer movement remains available. - -1. If a program requires release before it returns, send an explicit `up` in its `finally` block. Otherwise a later program in the same turn can release the held input. -2. Upgrade the macOS package and helper together. A custom `helperPath` must point to a rebuilt helper implementing the new private turn input protocol. -3. Verify a down in one program remains held until an up in a later program, or until cleanup after the turn ends. If cleanup cannot be confirmed, CUA disables all its operations for that task. Inspect the desktop manually before starting a new task. diff --git a/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.zh.md deleted file mode 100644 index 1690777d4d..0000000000 --- a/docs/upgrade-guide/v0.2.2-rc.4/cua-turn-inputs/guide.zh.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -kind: upgrade-guide -description: macOS CUA 的显式键盘和鼠标按下现在可在同一回合内跨程序执行保持。 ---- -# macOS CUA 输入以回合为持有范围 - -[English](guide.md) | 中文 - -## 变更 - -macOS 的 `sendKeyEvent('down')` 可在同一回合内跨 `run_code` 和 `cua_run_code` 调用持有按键。程序返回或抛错后,回合仍继续时不再自动释放。显式 `up` 立即向原接收方释放。窗口定向和系统 `toggleMouse('down')` 使用相同生命周期。`turn/end` 之后,包括异常结束和用户取消,CUA 按实际派发顺序的反序释放剩余键盘键和鼠标按钮,并等待原生确认。结束记录可以早于释放;`whenIdle()` 和后续 CUA 输入会等待清理完成。完整的 `pressKey`、`typeText`、`click` 和 `drag` 操作继续在本次操作内清理。回合持有范围属于共通 CUA 规则。Windows 尚未实现这套生命周期,保持现有行为。 - -## 迁移 - -MCP 不提供 DSH 回合边界。macOS 的 `sendKeyEvent` 和 `toggleMouse` 显式持有在该入口不可用,请改用完整的 `pressKey`、`click` 或 `drag` 动作。系统鼠标移动仍可使用。 - -1. 如果程序需要在返回前释放输入,在 `finally` 中显式发送 `up`。否则可由同一回合中的后续程序释放。 -2. 同步升级 macOS 包和 helper。自定义 `helperPath` 必须指向已重建、支持新回合输入私有协议的 helper。 -3. 验证前一次程序的 `down` 能保持到后一次程序发送 `up`,或回合结束后的清理。清理无法确认时,CUA 会禁用该任务的全部操作。请手动检查桌面状态后再创建新任务。 diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index 6aed2783ff..030715ccf2 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -15,14 +15,14 @@ en: 1777e7bf6785f986 zh: e3daac1074ebb74d /deepseek-ai-dsh-cua-macos/use-this-package: - en: 24149124235e72ee - zh: d02e5e844a5e0a83 + en: 28e620545509b621 + zh: 44a0482e0ce22a42 /deepseek-ai-dsh-cua-macos/use-this-package/connect-an-external-execution-environment: en: 3bf05d9ce5eb7224 zh: d8d0cd6429374860 /deepseek-ai-dsh-cua-macos/understand-the-implementation: - en: 3d88c0f7fa4ddf57 - zh: 7f9830bd8c3175bb + en: ee655e273363bb7b + zh: 7c2d60b4a6f7343f /deepseek-ai-dsh-cua-macos/further-exploration: en: ff9fac614001a98f zh: 329678941154aaea diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index 24caeed865..9997c7444f 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -83,7 +83,7 @@ The [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-cua-m `pressKey(key, modifiers?)` presses and releases one key. For shortcuts, pass held modifiers separately, as in `pressKey('a', ['command'])`. Pressing a modifier itself, as in `pressKey('shift')`, sets its flag on press and clears it on release. A single `+` or `plus` sends Shift+=. For `pressKey`, `click`, and `drag`, use `command`, `shift`, `option`/`alt`, `control`/`ctrl`, or `fn`. Only `pressKey` accepts `cmd` as a modifier alias for `command`. Key names are platform-defined; keypad names (`KP_0` through `KP_9`, `KP_Enter`, and keypad operators) retain their physical key codes. `typeText` sends literal text, including its line breaks and tabs. Use the App object's `pressKey` for a short press. -For a long press, call `app.sendKeyEvent('w', 'down')` in an active turn. The key stays down across `run_code` and `cua_run_code` executions, including a program failure when the turn continues. An explicit up releases the key immediately at its original recipient. Repeated down events for an ordinary key retain one hold. Turn completion, failure, and user cancellation release every remaining key and mouse button together in reverse dispatch order. Complete `pressKey`, `typeText`, `click`, and `drag` operations retain their own immediate cleanup. +For a long press, call `app.sendKeyEvent('w', 'down')`. Explicit key and mouse downs remain held across programs and turns until an explicit up releases them at their saved target. Successful programs report remaining holds in a system reminder, including the target and actual input mode. Program failure, user cancellation, connection closure, reset and disposal release owned keys and buttons together in reverse dispatch order. Complete `pressKey`, `typeText`, `click` and `drag` operations retain their immediate cleanup. Agent disposal and plugin unload cancel and await the complete tool call, including image admission and attachment storage. An image write already in progress must settle before disposal returns; a canceled call cannot return a successful screenshot. @@ -148,7 +148,7 @@ Element clicks use opaque element IDs from the current snapshot. Left clicks sup ## Understand the implementation -The shared helper's `HeldInputs` records task, turn, connection, process generation, application/window and actual input route before each explicit down is posted. One lock orders keyboard and pointer posts and releases. `turn/end` starts CUA cleanup: it closes host admission, cancels in-flight native work and awaits `releaseHeldInputs` with an independent bounded request. CUA uses the existing `runMaintenance()` and pre-step hooks to make `whenIdle()`, subsequent input and Agent disposal wait for cleanup. The turn record and idle notification can precede release acknowledgement; cleanup failure is reported separately through `agent/error` and disables CUA for the task. Connection shutdown cancels and joins native work before fallback release; a killed host relies on that disconnect path. Repeated cleanup cannot release a later turn's inputs. +The shared helper's `HeldInputs` records task, connection, process generation, application/window and actual input route before dispatch. One lock orders posts, state queries and releases. Program middleware queries native state after successful execution and defers a logged reminder to the outer tool result. Failure and cancellation close input admission and await `releaseHeldInputs` using an independent bounded request. Native connection shutdown cancels and joins in-flight work before fallback release. A killed host relies on that disconnect path; host callbacks cannot be guaranteed.
Dispatch and resource ownership diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index fba5586cf1..db4d39fffb 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -83,7 +83,7 @@ pnpm dsh headless --patch packages/experimental/cua-macos/examples/macos.cordis. `pressKey(key, modifiers?)` 按下并松开一个键。使用快捷键时单独传入修饰键,例如 `pressKey('a', ['command'])`。单独调用 `pressKey('shift')` 时,按下事件带有 Shift 标志,释放事件清除该标志。`+` 和 `plus` 都会发送 Shift 和等号。`pressKey`、`click` 和 `drag` 都接受修饰键 `command`、`shift`、`option`/`alt`、`control`/`ctrl` 和 `fn`。只有 `pressKey` 的修饰键参数还接受 `command` 的别名 `cmd`。按键名由平台定义;数字键盘名称(`KP_0` 到 `KP_9`、`KP_Enter` 和数字键盘运算键)保留独立的物理键码。`typeText` 发送字面文本,包括其中的换行和制表符。短按使用 App 对象上的 `pressKey`。 -长按时,在活动回合中调用 `app.sendKeyEvent('w', 'down')`。按键可跨 `run_code` 和 `cua_run_code` 执行保持;程序出错后回合仍继续时,也保留持有状态。显式 `up` 立即向原接收方释放按键。普通键的重复 `down` 只保留一条持有记录。回合正常完成、异常结束和用户停止时,所有仍按住的键盘键与鼠标按钮按实际派发顺序的反序统一释放。完整的 `pressKey`、`typeText`、`click` 和 `drag` 操作仍自行及时清理。 +长按时调用 `app.sendKeyEvent('w', 'down')`。显式键盘和鼠标按下会跨程序、跨回合保持,直到显式 up 按保存的目标释放。成功结束的程序通过 system reminder 报告剩余持有输入,包括目标和实际输入方式。程序失败、用户取消、断连、重置和销毁按实际派发顺序的反序统一释放所属键盘键和鼠标按钮。完整的 `pressKey`、`typeText`、`click` 和 `drag` 保持操作内及时清理。 Agent 销毁和插件卸载会取消并等待完整工具调用,包括图像接入检查和附件存储。已经开始的图像写入必须结束后,销毁才会返回;已取消的调用不会返回成功截图。 @@ -148,7 +148,7 @@ AppKit 的 sheet 可以出现在文档窗口的树里,并有独立的窗口 ID ## 理解实现 -共享 helper 的 `HeldInputs` 在每次显式按下派发前记录任务、回合、连接、进程代次、应用或窗口和实际输入方式。同一把锁维护键盘与鼠标的派发和释放顺序。`turn/end` 触发 CUA 清理:关闭宿主输入准入、取消在途原生操作,并通过独立且有超时限制的请求等待 `releaseHeldInputs` 确认。CUA 利用现有 `runMaintenance()` 和 pre-step 入口,使 `whenIdle()`、后续输入和 Agent 销毁等待清理完成。回合结束记录和空闲通知可以早于释放确认;清理失败单独通过 `agent/error` 报告,并禁用该任务的 CUA。连接关闭会先取消并等待原生操作停止,再做兜底释放;宿主被强杀时依靠这条断连路径。重复清理不会释放后续回合的输入。 +共享 helper 的 `HeldInputs` 在派发前记录任务、连接、进程代次、应用或窗口和实际输入方式。同一把锁维护派发、状态查询和释放。程序中间件在成功执行后查询原生状态,并把已记录的提醒附加到外层工具结果。失败和取消会关闭输入准入,通过独立且有超时限制的请求等待 `releaseHeldInputs`。原生连接关闭会先取消并等待在途操作,再做兜底释放。宿主被强杀时依赖断连清理,无法保证宿主回调执行。
操作分派与资源归属 diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index 02b2e58893..e406051bb4 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -21,8 +21,8 @@ en: bde8f9131c179da3 zh: bd5886c046505c4c /dsh-cua-native-helper/observation-and-input: - en: 168a837cd4af479a - zh: e046cda9ebc57d9c + en: f242f4dbb1e46342 + zh: ff87afc313433636 /dsh-cua-native-helper/verification: en: 11172b21e8ebf972 zh: dac6787e1e75a88e diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index a13e4e334b..43c3aafb8b 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -111,7 +111,7 @@ Capture and pointer delivery read CG bounds before and after an exact-window AX `typeText` and `pressKey` target the selected process's current focused control, not an exact window. `pressKey` presses the listed modifiers followed by one key, then releases all pressed keys in reverse order, including on cancellation. Keyboard events go directly to the target PID and bypass the global HID queue. Key names are platform-defined; keypad names such as `KP_0` and `KP_Enter` preserve their physical key codes. Background pointer actions may change that keyboard focus. Text injection sends Unicode characters individually and does not use the clipboard. LF, CR and CRLF send one Return; tabs send Tab. Applications apply their normal editing behavior, including indentation and focus navigation. Each `typeText` down/up event is followed by the configured text interval; `pressKey` keeps its own press and release timing, and dispatch completion does not confirm that the receiving application consumed every event. Cancellation can interrupt text or a gesture after partial input; it cannot undo received events. Very long text can exceed the host's operation deadline. Validate observed application state before deciding how to continue. -The Host attaches `taskId` and `turn` to directional input. `HeldInputs` records each explicit down with its connection, task, turn, application, original process identity, key or button, release event, and actual input route before dispatch. A repeated ordinary key-down sets `keyboardEventAutorepeat` and retains one record; AppKit may filter that repeat. Explicit up uses the saved recipient and route. PID-directed releases verify process identity; system-button releases still run after window closure or process exit. `releaseHeldInputs` releases a turn's keys and buttons together in reverse dispatch order and rejects later downs for that turn. The Host stops admission and waits for in-flight cancellation before requesting cleanup independently of the cancelled signal. Disconnect cleanup joins native work before releasing that connection's records. Complete key chords, text, clicks and drags keep their operation-local cleanup. +The Host attaches `taskId` to explicit input. `HeldInputs` records connection, task, application, original process identity, key code or button, release event and actual input mode before dispatch. Repeated key downs keep one record. Explicit up uses the saved target and input mode, skipping PID-directed releases after process exit or identity reuse. `getHeldInputs` reports only the requesting connection and task records, without reading physical user key state. Successful programs use this snapshot for their reminder. `releaseHeldInputs` releases keyboard and mouse records together in reverse dispatch order after program failure, cancellation or disposal. Normal program and turn endings do not release input. Connection shutdown joins native work before fallback release. Balanced key chords, text, clicks and drags keep their operation-local cleanup. The selected helper application needs macOS Accessibility permission for AX state and input, and Screen Recording permission for screenshots. Capability preflight and permission errors do not grant permissions. Capture refuses a window that moves or resizes while the image is being read. Unassociated system panels and accessory-only applications are not selectable. diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index e189f60282..2b732c7ef9 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -101,7 +101,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 窗口隐藏本身不会使 AX 快照失效。刷新清单时,只有同一窗口 ID 仍存在且观察到的尺寸未变,才能继续使用此前截图的像素坐标。观察到尺寸变化后需要重新截图;窗口销毁后不能继续操作。清单中省略窗口不会阻止按已知 ID 发起输入。窗口归属、尺寸和输入检查仍然生效,成功分派不代表应用已接收。 -窗口模式的 `toggleMouse` 向目标进程发送一次按下或松开。按下时使用当前指针位置,松开时允许指针移出。显式开启 `useSystemPointer` 后,helper 通过 HID 发送系统按键事件。只有按下该键的连接能通过原窗口显式松开。在同一窗口请求系统指针移动会发送该按键的拖动事件。Host 在回合结束时请求清理,连接关闭也会松开按键。 +窗口模式的 `toggleMouse` 向目标进程发送一次按下或松开。按下时使用当前指针位置,松开时允许指针移出。显式开启 `useSystemPointer` 后,helper 通过 HID 发送系统按键事件。只有按下该键的连接能通过原窗口显式松开。在同一窗口请求系统指针移动会发送该按键的拖动事件。正常程序结束和回合结束保持按钮;失败、取消和断连释放它。 点击在元素中心或给定坐标发送鼠标按下和抬起事件。执行默认 AX 动作用 `invoke`,执行指定动作用 `performAction`。点击、滚动和默认拖动核实窗口归属和边界后,向目标进程和窗口投递事件。事件优先使用 SkyLight,不可用时使用公开的 PID 定向 API;已发送的事件不通过另一 API 重发。坐标是整个窗口左上角起算的 macOS point,包含标题栏。`deltaLinesY` 为正时显示上方内容,为负时显示下方内容;`deltaLinesX` 为正时显示左侧内容,为负时显示右侧内容。每个轴接受 -10 到 10 的整数,至少一个轴非零。helper 直接发送按行计量的滚轮事件。点击和拖动支持左、右、中键及 command/control/option/shift/fn 修饰键,只有左键支持双击。拖动在一个窗口中完成一次按下、移动、抬起,调用方显式提供 durationMs(1..5000)和 steps(1..240)。移动延迟按小数精度分配到各段,按下和抬起的固定等待及调度延迟另计。显式传入 `useSystemPointer: true` 的拖动通过 HID 投递,起点及每段移动都要命中目标前台窗口。手势共用事件号,每段携带位移。取消时在最后投递的位置松开鼠标键。 @@ -111,7 +111,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 `typeText` 和 `pressKey` 面向所选进程当前获得焦点的控件,不指定窗口。`pressKey` 向目标 PID 依次发送修饰键和一个主键的按下事件,再逆序释放。操作中途取消也会逆序释放已按下的键。键盘事件直接发给目标进程,绕过全局 HID 队列。按键名由平台定义;KP_0 和 KP_Enter 等数字键盘名称保留物理键码。后台鼠标操作可能改变键盘焦点。文本逐个 Unicode 字符输入,不使用剪贴板。LF、CR 和 CRLF 发送一次 Return,制表符发送 Tab。应用保留缩进和焦点导航等正常编辑行为。`typeText` 的每次按下和抬起后等待配置的文本事件间隔;`pressKey` 使用自己的按下与释放节奏,分派完成不证明应用已消费全部事件。取消可能中断部分文本或手势,无法撤销已接收事件。很长的文本可能超过 Host 操作期限。继续输入前应核实应用状态。 -宿主为定向输入附上 `taskId` 和 `turn`。`HeldInputs` 在显式按下派发前记录连接、任务、回合、应用、原进程身份、键码或按钮、释放事件和实际输入方式。普通键的重复按下设置 `keyboardEventAutorepeat`,仍只保留一条记录;AppKit 可能过滤该重复事件。显式松开使用保存的接收方和输入方式。定向释放检查进程身份;系统按钮在窗口关闭或进程退出后仍会释放。`releaseHeldInputs` 按实际派发顺序的反序统一释放本回合的键盘键与鼠标按钮,并拒绝该回合后续的按下。宿主先禁止新输入并等待在途取消,再独立于已取消的 signal 请求清理。断连清理先等待原生操作结束,再释放本连接的记录。完整快捷键、文本输入、点击和拖动仍在本次操作内自行清理。 +宿主为显式输入附上 `taskId`。`HeldInputs` 在派发前记录连接、任务、应用、原进程身份、键码或按钮、释放事件和实际输入方式。重复按键只保留一条记录。显式 up 使用保存的目标和输入方式;进程退出或 PID 身份变化后跳过定向释放。`getHeldInputs` 只报告请求连接和任务的记录,不读取用户物理按键状态。成功结束的程序用该快照生成提醒。程序失败、取消或销毁时,`releaseHeldInputs` 按派发顺序的反序统一释放键盘和鼠标记录。正常程序结束和回合结束不释放输入。连接关闭先等待原生操作停止,再兜底释放。完整击键、文本、点击和拖动保留操作内清理。 所选 helper 应用需要 macOS 辅助功能权限以读取 AX 和输入,需要屏幕录制权限以截图。能力预检和权限错误不授予权限。截图会拒绝在读取图片期间移动或缩放的窗口。无法确认归属的系统面板及仅后台辅助类型的应用不可选择。 diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift index 5eeba2157f..47c9ec2e7e 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift @@ -204,7 +204,7 @@ actor AXWorker { var recovery = AXChildRecoveryBudget(maxElements: NativeProtocol.elementRange.upperBound, timeout: axTimeout) if method == "sendKeyEvent", try params.string("direction") == "up" { let handle = try params.string("appHandle") - let dispatched = try inputs().0.keyUp(params.string("key"), app: handle, scope: params.inputScope()) { + let dispatched = try inputs().0.keyUp(params.string("key"), app: handle, task: params.string("taskId")) { try NativePlatform.requireUnlocked(observeSession()) try NativePlatform.requireAccessibility() return try ax().keyboardRecipient(validateIdentity(handle), catalog: catalog, budget: &recovery) @@ -319,7 +319,7 @@ actor AXWorker { 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) + snapshots[scope] = NativeSnapshot(id: id, task: task, elements: projection.indexed) for observed in observedWindows where window == nil || observed.windowID == window { observedWindowBounds[handle, default: [:]][observed.windowID] = observed.bounds } @@ -346,7 +346,7 @@ actor AXWorker { readTimeout: .milliseconds(try params.integer("pasteReadTimeoutMs", in: 1...2147483647)), maxElements: try params.integer("maxElements", in: NativeProtocol.elementRange), maxDepth: try params.integer("maxDepth", in: NativeProtocol.depthRange))) case "sendKeyEvent": - try inputs().0.keyDown(params.string("key"), app: handle, scope: params.inputScope()) { + try inputs().0.keyDown(params.string("key"), app: handle, task: params.string("taskId")) { try ax().keyboardRecipient(identity, catalog: catalog, budget: &recovery) } case "typeText", "pressKey": @@ -378,7 +378,7 @@ actor AXWorker { if try params.optionalBoolean("useSystemPointer") == true { return .systemButtonDown(route, try WindowPointerInput.button(params.string("mouseButton"))) } - try await inputs().1.mouseDown(owner: .init(connection: connectionID, scope: params.inputScope(), app: handle), + try await inputs().1.mouseDown(owner: .init(connection: connectionID, task: params.string("taskId"), app: handle), in: route, button: params.string("mouseButton")) case "click", "mouseMove": let useSystemPointer = try params.optionalBoolean("useSystemPointer") ?? false diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/HeldInputs.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/HeldInputs.swift index ab4fefc77b..568d5b8af1 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/HeldInputs.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/HeldInputs.swift @@ -4,17 +4,13 @@ import Foundation /// The lock covers registration, dispatch, explicit release, and reverse-order cleanup. final class HeldInputs: @unchecked Sendable { - struct Scope: Equatable { - let task: String - let turn: Int - } struct Owner: Equatable { let connection: UUID - let scope: Scope + let task: String let app: String } enum Mode: Equatable { - case keyboard(CGKeyCode, CGEventFlags) + case keyboard(CGKeyCode, CGEventFlags, String) case windowPointer(CGMouseButton, UInt32) case systemPointer(CGMouseButton, UInt32) } @@ -28,37 +24,29 @@ final class HeldInputs: @unchecked Sendable { } private let lock = NSLock() private var pressed: [Press] = [] - private var ended: [UUID: [String: Int]] = [:] func snapshot(pid: Int32) -> [CGKeyCode: CGEventFlags] { lock.withLock { Dictionary(uniqueKeysWithValues: pressed.compactMap { - guard $0.recipient.pid == pid, case .keyboard(let code, let flag) = $0.mode else { return nil } + guard $0.recipient.pid == pid, case .keyboard(let code, let flag, _) = $0.mode else { return nil } return (code, flag) }) } } - private func admit(_ owner: Owner) throws { - if let last = ended[owner.connection]?[owner.scope.task], owner.scope.turn <= last { - throw NativeFailure(code: "INPUT_TURN_CLOSED", message: "Input for this turn has already been released") - } - } - private func conflict(_ name: String, holder: Owner, caller: Owner) -> NativeFailure { let source: String if holder.connection != caller.connection { source = "another session" } - else if holder.scope != caller.scope { source = "another turn" } - else { source = "a different application handle in this turn" } - return RequestParameters.invalid("Key '\(name)' is held for this target by \(source). No event was sent. Wait for the holder to release it or for its turn to end.") + else if holder.task != caller.task { source = "another task" } + else { source = "a different application handle" } + return RequestParameters.invalid("Key '\(name)' is held for this target by \(source). No event was sent. Wait for the holder to release it before using it.") } /// Repeats retain the original recipient and do not change the cleanup order. func repeatIfHeld(owner: Owner, name: String, code: CGKeyCode, down: CGEvent, post: (CGEvent, Int32) -> Void) throws -> Bool { try lock.withLock { - try admit(owner) guard let key = pressed.first(where: { $0.owner == owner && $0.mode.keyCode == code }) else { return false } - guard case .keyboard(_, let flag) = key.mode, flag.isEmpty, down.type == .keyDown else { + guard case .keyboard(_, let flag, _) = key.mode, flag.isEmpty, down.type == .keyDown else { throw RequestParameters.invalid("Modifier '\(name)' is already held. Send 'up' to release it.") } try NativePlatform.verify(key.recipient) @@ -72,11 +60,10 @@ final class HeldInputs: @unchecked Sendable { func keyDown(owner: Owner, recipient: ProcessIdentity, name: String, code: CGKeyCode, flag: CGEventFlags, down: CGEvent, up: CGEvent, post: @escaping (CGEvent, Int32) -> Void) throws { try lock.withLock { - try admit(owner) if let key = pressed.first(where: { $0.mode.keyCode == code && $0.recipient.pid == recipient.pid }) { throw conflict(name, holder: key.owner, caller: owner) } - pressed.append(Press(owner: owner, recipient: recipient, mode: .keyboard(code, flag), up: up, + pressed.append(Press(owner: owner, recipient: recipient, mode: .keyboard(code, flag, name), up: up, post: { post($0, recipient.pid) }, prepareRelease: nil)) down.flags = flags(for: recipient) post(down, recipient.pid) @@ -85,7 +72,7 @@ final class HeldInputs: @unchecked Sendable { private func flags(for recipient: ProcessIdentity) -> CGEventFlags { pressed.reduce(into: CGEventFlags()) { - if $1.recipient == recipient, case .keyboard(_, let flag) = $1.mode { $0.formUnion(flag) } + if $1.recipient == recipient, case .keyboard(_, let flag, _) = $1.mode { $0.formUnion(flag) } } } @@ -119,7 +106,7 @@ final class HeldInputs: @unchecked Sendable { if let key = pressed.first(where: { $0.mode.keyCode == code && $0.recipient == recipient }) { return conflict(name, holder: key.owner, caller: owner) } - return RequestParameters.invalid("Key '\(name)' is not held for this target. Send 'down' in this turn before 'up'.") + return RequestParameters.invalid("Key '\(name)' is not held for this target. Send 'down' before 'up'.") } } @@ -127,7 +114,6 @@ final class HeldInputs: @unchecked Sendable { down: CGEvent, up: CGEvent, post: @escaping (CGEvent) -> Void, prepareRelease: ((CGEvent) throws -> Void)? = nil) throws { try lock.withLock { - try admit(owner) try checkPointerAvailable(route: route, button: button, system: system) pressed.append(Press(owner: owner, recipient: route.owner, mode: system ? .systemPointer(button, route.windowID) : .windowPointer(button, route.windowID), up: up, post: post, prepareRelease: prepareRelease)) @@ -154,7 +140,7 @@ final class HeldInputs: @unchecked Sendable { func pointerUp(owner: Owner, window: UInt32, button: CGMouseButton) throws -> Bool { try lock.withLock { guard let index = pressed.firstIndex(where: { $0.owner == owner && $0.mode.pointer == button && $0.mode.window == window }) else { - throw RequestParameters.invalid("Release the mouse button through the same task, turn, application and window that pressed it") + throw RequestParameters.invalid("Release the mouse button through the same task, application and window that pressed it") } return try release(at: index) } @@ -163,7 +149,6 @@ final class HeldInputs: @unchecked Sendable { /// Create and post movement under the same lock as ownership and the saved release point. func moveSystem(owner: Owner?, route: WindowRoute, screen: CGPoint, checkCancellation: () throws -> Void) throws { try lock.withLock { - if let owner { try admit(owner) } let press = pressed.first { if case .systemPointer = $0.mode { return true }; return false } let event: CGEvent if let press { @@ -183,14 +168,43 @@ final class HeldInputs: @unchecked Sendable { } } - func release(connection: UUID, scope: Scope? = nil) throws { + /// Only the caller's registered input is disclosed; physical user input is never inferred. + func held(connection: UUID, task: String) throws -> JSONValue { + try lock.withLock { + for index in pressed.indices.reversed() { + let press = pressed[index] + guard press.owner.connection == connection, press.owner.task == task else { continue } + if case .systemPointer = press.mode { continue } + do { try NativePlatform.verify(press.recipient) } + catch let error as NativeFailure where error.code == "STALE_APP" || error.code == "APP_UNAVAILABLE" { + pressed.remove(at: index) + } + } + return .array(pressed.filter { $0.owner.connection == connection && $0.owner.task == task }.map { press in + var record: [String: JSONValue] = ["appHandle": .string(press.owner.app)] + switch press.mode { + case .keyboard(_, _, let name): + record["kind"] = .string("key") + record["key"] = .string(name) + record["mode"] = .string("application") + case .windowPointer(let button, let window), .systemPointer(let button, let window): + record["kind"] = .string("mouse") + record["button"] = .string(button == .left ? "left" : button == .right ? "right" : "middle") + record["windowId"] = .string(String(window)) + if case .systemPointer = press.mode { record["mode"] = .string("system") } + else { record["mode"] = .string("window") } + } + return .object(record) + }) + } + } + + func release(connection: UUID, task: String? = nil) throws { try lock.withLock { - if let scope { ended[connection, default: [:]][scope.task] = max(ended[connection]?[scope.task] ?? 0, scope.turn) } - defer { if scope == nil { ended.removeValue(forKey: connection) } } var failures: [String] = [] for index in pressed.indices.reversed() { let owner = pressed[index].owner - guard owner.connection == connection, scope == nil || owner.scope == scope else { continue } + guard owner.connection == connection, task == nil || owner.task == task else { continue } do { _ = try release(at: index) } catch { failures.append(String(describing: error)) } } @@ -204,7 +218,7 @@ final class HeldInputs: @unchecked Sendable { } private extension HeldInputs.Mode { - var keyCode: CGKeyCode? { if case .keyboard(let code, _) = self { return code }; return nil } + var keyCode: CGKeyCode? { if case .keyboard(let code, _, _) = self { return code }; return nil } var pointer: CGMouseButton? { switch self { case .keyboard: return nil; case .windowPointer(let button, _), .systemPointer(let button, _): return button } } diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift index cbceb54806..c15c922a67 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift @@ -23,8 +23,8 @@ final class KeyboardInput { self.checkCancellation = checkCancellation } - func keyDown(_ name: String, app: String, scope: HeldInputs.Scope, recipient: () throws -> ProcessIdentity) throws { - let owner = HeldInputs.Owner(connection: connection, scope: scope, app: app) + func keyDown(_ name: String, app: String, task: String, recipient: () throws -> ProcessIdentity) throws { + let owner = HeldInputs.Owner(connection: connection, task: task, app: app) let code = try Self.keyCode(name) let source = try Self.source() let down = try Self.keyEvent(source: source, code: code, down: true, flags: []) @@ -38,8 +38,8 @@ final class KeyboardInput { down: down, up: up, post: post) } - func keyUp(_ name: String, app: String, scope: HeldInputs.Scope, recipientIfUnheld: () throws -> ProcessIdentity) throws -> Bool { - try held.keyUp(owner: .init(connection: connection, scope: scope, app: app), name: name, code: Self.keyCode(name), + func keyUp(_ name: String, app: String, task: String, recipientIfUnheld: () throws -> ProcessIdentity) throws -> Bool { + try held.keyUp(owner: .init(connection: connection, task: task, app: app), name: name, code: Self.keyCode(name), recipientIfUnheld: recipientIfUnheld) } diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift index bb2ef0c7c0..95164e75e1 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift @@ -10,27 +10,28 @@ enum NativeProtocol { "findApps": ["maxAppMatches", "query"], "getApp": ["selector"], "getCapabilities": [], + "getHeldInputs": ["taskId"], "getState": ["appHandle", "details", "includeMenus", "maxDepth", "maxElements", "windowId"], "invoke": ["appHandle", "elementId", "snapshotId", "windowId"], "launchApp": ["appHandle"], "listActions": ["appHandle", "elementId", "snapshotId", "windowId"], "listApps": [], "listWindows": ["appHandle"], - "mouseMove": ["appHandle", "elementId", "snapshotId", "taskId", "turn", "useSystemPointer", "windowId", "x", "y"], + "mouseMove": ["appHandle", "elementId", "snapshotId", "taskId", "useSystemPointer", "windowId", "x", "y"], "openPermissionSettings": ["permission", "settingsMessage"], "paste": ["appHandle", "format", "maxClipboardBytes", "maxDepth", "maxElements", "pasteReadTimeoutMs", "text", "windowId"], "performAction": ["action", "appHandle", "argument", "elementId", "snapshotId", "windowId"], "permissionStatus": [], "pressKey": ["appHandle", "key", "modifiers", "windowId"], - "releaseHeldInputs": ["taskId", "turn"], + "releaseHeldInputs": ["taskId"], "requestPermission": ["backLabel", "finderLabel", "instruction", "permission", "pollIntervalMs", "settingsMessage", "unavailableMessage"], "screenshot": ["appHandle", "windowId"], "scroll": ["appHandle", "deltaLinesX", "deltaLinesY", "snapshotId", "windowId", "x", "y"], "selectText": ["appHandle", "elementId", "prefix", "selectionType", "snapshotId", "suffix", "text", "windowId"], - "sendKeyEvent": ["appHandle", "direction", "key", "taskId", "turn", "windowId"], + "sendKeyEvent": ["appHandle", "direction", "key", "taskId", "windowId"], "setValue": ["appHandle", "elementId", "snapshotId", "value", "windowId"], "show": ["appHandle", "windowId"], - "toggleMouse": ["appHandle", "direction", "mouseButton", "taskId", "turn", "useSystemPointer", "windowId"], + "toggleMouse": ["appHandle", "direction", "mouseButton", "taskId", "useSystemPointer", "windowId"], "typeText": ["appHandle", "text", "windowId"], ] static let stringEnums: [String: [String: Set]] = [ diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestAdmission.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestAdmission.swift index 0c1450889c..aa700cdcdd 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestAdmission.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestAdmission.swift @@ -83,7 +83,4 @@ struct RequestParameters: Sendable { } extension RequestParameters { - func inputScope() throws -> HeldInputs.Scope { - try HeldInputs.Scope(task: string("taskId"), turn: integer("turn", in: 1...Int.max)) - } } diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift index 2effd119e7..69e3772d8d 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift @@ -165,12 +165,15 @@ import Darwin private func execute(_ request: NativeRequest, trace: ScreenshotTrace?) async throws -> JSONValue { let params = try RequestParameters(request) try cancellation.check() + if request.method == "getHeldInputs" { + return try scheduler.heldInputs.held(connection: connectionID, task: params.string("taskId")) + } if request.method == "releaseHeldInputs" { - try scheduler.heldInputs.release(connection: connectionID, scope: params.inputScope()) + try scheduler.heldInputs.release(connection: connectionID, task: params.string("taskId")) return AXWorker.actionResult } if request.method == "toggleMouse", try params.string("direction") == "up" { - let dispatched = try scheduler.heldInputs.pointerUp(owner: .init(connection: connectionID, scope: params.inputScope(), + let dispatched = try scheduler.heldInputs.pointerUp(owner: .init(connection: connectionID, task: params.string("taskId"), app: params.string("appHandle")), window: params.windowID(), button: WindowPointerInput.button(params.string("mouseButton"))) return .object(["dispatched": .bool(dispatched)]) } @@ -223,12 +226,12 @@ import Darwin case .foreground(let plan): result = try await performForeground(plan, requestID: request.id) case .mouseMove(let route, let point): let latch = cancellation - let owner: HeldInputs.Owner? = try params.contains("taskId") || params.contains("turn") - ? .init(connection: connectionID, scope: params.inputScope(), app: params.string("appHandle")) : nil + let owner: HeldInputs.Owner? = try params.contains("taskId") + ? .init(connection: connectionID, task: params.string("taskId"), app: params.string("appHandle")) : nil try scheduler.systemPointer.move(owner: owner, in: route, at: point, checkCancellation: { try latch.check() }) result = AXWorker.mouseMoveResult(route: "system-pointer", pointerMoved: true) case .systemButtonDown(let route, let button): - try scheduler.systemPointer.down(owner: .init(connection: connectionID, scope: params.inputScope(), app: params.string("appHandle")), in: route, button: button, + try scheduler.systemPointer.down(owner: .init(connection: connectionID, task: params.string("taskId"), app: params.string("appHandle")), in: route, button: button, checkCancellation: { try cancellation.check() }) result = AXWorker.actionResult case .paste(let plan): diff --git a/packages/experimental/cua-macos/native/generate-protocol.ts b/packages/experimental/cua-macos/native/generate-protocol.ts index 4fc739d685..44ff6eec5b 100644 --- a/packages/experimental/cua-macos/native/generate-protocol.ts +++ b/packages/experimental/cua-macos/native/generate-protocol.ts @@ -15,19 +15,19 @@ export function renderNativeProtocol(): { json: string; swift: string } { maxElements: z.number().int().min(1).max(AX_TRAVERSAL_MAX.maxElements), maxDepth: z.number().int().min(1).max(AX_TRAVERSAL_MAX.maxDepth), } - const owner = { taskId: z.string().min(1), turn: z.number().int().positive() } + const owner = { taskId: z.string().min(1) } const systemPointer = { useSystemPointer: z.boolean().optional() } const { fields, enums, json } = nativeProtocol({ getState: NativeResourceParameters.getState.extend(traversal), paste: NativeResourceParameters.paste.extend(traversal), sendKeyEvent: z.object(owner), - mouseMove: z.object({ ...systemPointer, taskId: owner.taskId.optional(), turn: owner.turn.optional() }), + mouseMove: z.object({ ...systemPointer, taskId: owner.taskId.optional() }), toggleMouse: z.object({ ...systemPointer, ...owner }), drag: NativeResourceParameters.drag.extend(systemPointer), requestPermission: PermissionGuideParameters, openPermissionSettings: PermissionSettingsParameters, - }, [z.object({ - method: z.literal('releaseHeldInputs'), params: z.object(owner).strict(), - }).strict()]) + }, ['getHeldInputs', 'releaseHeldInputs'].map(method => z.object({ + method: z.literal(method), params: z.object(owner).strict(), + }).strict())) const quoted = (values: Iterable) => [...values].sort().map(value => JSON.stringify(value)).join(', ') const swift = [ '// Generated by native/generate-protocol.ts from @deepseek-ai/dsh-cua/native-schema. Do not edit.', diff --git a/packages/experimental/cua-macos/native/protocol.schema.json b/packages/experimental/cua-macos/native/protocol.schema.json index f79948b7cb..c97fd7612b 100644 --- a/packages/experimental/cua-macos/native/protocol.schema.json +++ b/packages/experimental/cua-macos/native/protocol.schema.json @@ -493,11 +493,6 @@ "taskId": { "type": "string", "minLength": 1 - }, - "turn": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 9007199254740991 } }, "required": [ @@ -505,8 +500,7 @@ "windowId", "mouseButton", "direction", - "taskId", - "turn" + "taskId" ], "additionalProperties": false } @@ -556,11 +550,6 @@ "taskId": { "type": "string", "minLength": 1 - }, - "turn": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 9007199254740991 } }, "required": [ @@ -599,11 +588,6 @@ "taskId": { "type": "string", "minLength": 1 - }, - "turn": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 9007199254740991 } }, "required": [ @@ -1129,19 +1113,13 @@ "taskId": { "type": "string", "minLength": 1 - }, - "turn": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 9007199254740991 } }, "required": [ "appHandle", "key", "direction", - "taskId", - "turn" + "taskId" ], "additionalProperties": false } @@ -1542,6 +1520,37 @@ ], "additionalProperties": false }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "getHeldInputs" + }, + "params": { + "type": "object", + "properties": { + "taskId": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "taskId" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, { "type": "object", "properties": { @@ -1558,16 +1567,10 @@ "taskId": { "type": "string", "minLength": 1 - }, - "turn": { - "type": "integer", - "exclusiveMinimum": 0, - "maximum": 9007199254740991 } }, "required": [ - "taskId", - "turn" + "taskId" ], "additionalProperties": false } diff --git a/packages/experimental/cua-macos/native/tests/native_test_support.py b/packages/experimental/cua-macos/native/tests/native_test_support.py index 22bf87aeb6..6bb8fee07b 100644 --- a/packages/experimental/cua-macos/native/tests/native_test_support.py +++ b/packages/experimental/cua-macos/native/tests/native_test_support.py @@ -106,14 +106,11 @@ class NativeHelper: self.process = subprocess.Popen([str(binary)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, start_new_session=True) self.sequence = 0 - self.input_turn = 1 self.transcript = transcript def call(self, method, params, error_code=None): - if method in ("sendKeyEvent", "toggleMouse", "releaseHeldInputs") or (method == "mouseMove" and params.get("useSystemPointer")): - params = {**params, "taskId": "native-fixture", "turn": self.input_turn} - if method == "releaseHeldInputs": - self.input_turn += 1 + if method in ("sendKeyEvent", "toggleMouse", "getHeldInputs", "releaseHeldInputs") or (method == "mouseMove" and params.get("useSystemPointer")): + params = {**params, "taskId": "native-fixture"} self.sequence += 1 request = {"id": str(self.sequence), "method": method, "params": params} self.process.stdin.write(json.dumps(request) + "\n") diff --git a/packages/experimental/cua-macos/native/tests/shared_helper_e2e.py b/packages/experimental/cua-macos/native/tests/shared_helper_e2e.py index ab0e0f4e99..295ee6a8ef 100644 --- a/packages/experimental/cua-macos/native/tests/shared_helper_e2e.py +++ b/packages/experimental/cua-macos/native/tests/shared_helper_e2e.py @@ -34,7 +34,6 @@ class Connection: self.socket.connect(str(path)) self.reader = self.socket.makefile("rb") self.sequence = 0 - self.input_turn = 1 self.diagnostics = [] self.cleanup_timeout = overrides.get("graceMs", CONFIG["graceMs"]) / 1000 self.send({"type": "hello", "protocol": 1, "runtimeKey": key, "config": {**CONFIG, **overrides}}) @@ -56,10 +55,8 @@ class Connection: return value def call(self, method, params, error=None): - if method in ("sendKeyEvent", "toggleMouse", "releaseHeldInputs") or (method == "mouseMove" and params.get("useSystemPointer")): - params = {**params, "taskId": "native-fixture", "turn": self.input_turn} - if method == "releaseHeldInputs": - self.input_turn += 1 + if method in ("sendKeyEvent", "toggleMouse", "getHeldInputs", "releaseHeldInputs") or (method == "mouseMove" and params.get("useSystemPointer")): + params = {**params, "taskId": "native-fixture"} self.sequence += 1 identifier = str(self.sequence) self.send({"id": identifier, "method": method, "params": params}) diff --git a/packages/experimental/cua-macos/native/tests/swift/HeldInputTests.swift b/packages/experimental/cua-macos/native/tests/swift/HeldInputTests.swift index d237d1efb4..6a43afd1ee 100644 --- a/packages/experimental/cua-macos/native/tests/swift/HeldInputTests.swift +++ b/packages/experimental/cua-macos/native/tests/swift/HeldInputTests.swift @@ -5,7 +5,7 @@ import Foundation import Testing @testable import CuaNative -private let scope = HeldInputs.Scope(task: "task", turn: 1) +private let task = "task" private func pointer(_ type: CGEventType) throws -> CGEvent { let event = try #require(CGEvent(mouseEventSource: nil, mouseType: type, mouseCursorPosition: .zero, mouseButton: .left)) @@ -18,19 +18,27 @@ func mixedInputsReleaseInDispatchOrder(_ system: Bool) throws { let held = HeldInputs() let connection = UUID() let target = try NativePlatform.identity(getpid()) - let owner = HeldInputs.Owner(connection: connection, scope: scope, app: "editor") + let owner = HeldInputs.Owner(connection: connection, task: task, app: "editor") let route = WindowRoute(owner: target, windowID: 7, bounds: .init(x: 0, y: 0, width: 100, height: 100)) var events: [String] = [] let input = KeyboardInput(post: { event, pid in #expect(pid == target.pid) events.append("key:\(event.getIntegerValueField(.keyboardEventKeycode)):\(event.type.rawValue)") }, textEventInterval: 0, held: held, connection: connection) - try input.keyDown("shift", app: "editor", scope: scope, recipient: { target }) + try input.keyDown("shift", app: "editor", task: task, recipient: { target }) try held.pointerDown(owner: owner, route: route, button: .left, system: system, down: pointer(.leftMouseDown), up: pointer(.leftMouseUp), post: { events.append("mouse:\($0.type.rawValue)") }) - try input.keyDown("w", app: "editor", scope: scope, recipient: { target }) - try held.release(connection: connection, scope: scope) - try held.release(connection: connection, scope: scope) + try input.keyDown("w", app: "editor", task: task, recipient: { target }) + let state = try held.held(connection: connection, task: task) + #expect(state == .array([ + .object(["kind": .string("key"), "key": .string("shift"), "appHandle": .string("editor"), "mode": .string("application")]), + .object(["kind": .string("mouse"), "button": .string("left"), "appHandle": .string("editor"), "windowId": .string("7"), "mode": .string(system ? "system" : "window")]), + .object(["kind": .string("key"), "key": .string("w"), "appHandle": .string("editor"), "mode": .string("application")]), + ])) + #expect(try held.held(connection: UUID(), task: task) == .array([])) + try held.release(connection: connection, task: task) + #expect(try held.held(connection: connection, task: task) == .array([])) + try held.release(connection: connection, task: task) #expect(events == ["key:56:12", "mouse:1", "key:13:10", "key:13:11", "mouse:2", "key:56:12"]) } @@ -41,34 +49,32 @@ func mixedInputsReleaseInDispatchOrder(_ system: Bool) throws { var events: [CGEvent] = [] let input = KeyboardInput(post: { event, _ in events.append(event) }, textEventInterval: 0, held: held, connection: connection) func changedFocus() throws -> ProcessIdentity { throw RequestParameters.invalid("Unexpected focus lookup") } - try input.keyDown("w", app: "editor", scope: scope, recipient: { target }) - try input.keyDown("w", app: "editor", scope: scope, recipient: changedFocus) - #expect(try input.keyUp("w", app: "editor", scope: scope, recipientIfUnheld: changedFocus)) - try input.keyDown("d", app: "editor", scope: scope, recipient: { target }) - try input.keyDown("w", app: "editor", scope: scope, recipient: { target }) - try held.release(connection: connection, scope: scope) + try input.keyDown("w", app: "editor", task: task, recipient: { target }) + try input.keyDown("w", app: "editor", task: task, recipient: changedFocus) + #expect(try input.keyUp("w", app: "editor", task: task, recipientIfUnheld: changedFocus)) + try input.keyDown("d", app: "editor", task: task, recipient: { target }) + try input.keyDown("w", app: "editor", task: task, recipient: { target }) + try held.release(connection: connection, task: task) #expect(events.map { $0.getIntegerValueField(.keyboardEventKeycode) } == [13, 13, 13, 2, 13, 13, 2]) #expect(events.map(\.type) == [.keyDown, .keyDown, .keyUp, .keyDown, .keyDown, .keyUp, .keyUp]) #expect(events.map { $0.getIntegerValueField(.keyboardEventAutorepeat) } == [0, 1, 0, 0, 0, 0, 0]) } -@Test func connectionsAndTurnsCannotReleaseEachOthersInput() throws { +@Test func connectionsAndTasksCannotReleaseEachOthersInput() throws { let held = HeldInputs() let a = UUID(), b = UUID() let target = try NativePlatform.identity(getpid()) var events: [CGEventType] = [] let input = KeyboardInput(post: { event, _ in events.append(event.type) }, textEventInterval: 0, held: held, connection: a) let peer = KeyboardInput(post: { _, _ in Issue.record("Foreign connection posted input") }, textEventInterval: 0, held: held, connection: b) - try input.keyDown("w", app: "editor", scope: scope, recipient: { target }) - #expect(throws: NativeFailure.self) { try peer.keyDown("w", app: "editor", scope: scope, recipient: { target }) } - #expect(throws: NativeFailure.self) { try peer.keyUp("w", app: "editor", scope: scope, recipientIfUnheld: { target }) } + try input.keyDown("w", app: "editor", task: task, recipient: { target }) + #expect(throws: NativeFailure.self) { try peer.keyDown("w", app: "editor", task: task, recipient: { target }) } + #expect(throws: NativeFailure.self) { try peer.keyUp("w", app: "editor", task: task, recipientIfUnheld: { target }) } try held.release(connection: b) #expect(events == [.keyDown]) - try held.release(connection: a, scope: scope) - #expect(throws: NativeFailure.self) { try input.keyDown("w", app: "editor", scope: scope, recipient: { target }) } - let next = HeldInputs.Scope(task: scope.task, turn: 2) - try input.keyDown("w", app: "editor", scope: next, recipient: { target }) - try held.release(connection: a, scope: scope) + try held.release(connection: a, task: task) + try input.keyDown("w", app: "editor", task: "another-task", recipient: { target }) + try held.release(connection: a, task: task) #expect(events == [.keyDown, .keyUp, .keyDown]) try held.release(connection: a) #expect(events == [.keyDown, .keyUp, .keyDown, .keyUp]) @@ -80,7 +86,7 @@ func pointerReleaseUsesSavedRouteAfterWindowAndProcessChanges(_ system: Bool) th let target = try NativePlatform.identity(getpid()) // The current PID with a different start identity models a reused process identifier. let stale = ProcessIdentity(pid: target.pid, startedSeconds: target.startedSeconds + 1, startedMicroseconds: target.startedMicroseconds) - let owner = HeldInputs.Owner(connection: UUID(), scope: scope, app: "old-window") + let owner = HeldInputs.Owner(connection: UUID(), task: task, app: "old-window") let route = WindowRoute(owner: stale, windowID: 987654, bounds: .init(x: 0, y: 0, width: 100, height: 100)) var events: [CGEventType] = [] try held.pointerDown(owner: owner, route: route, button: .left, system: system, @@ -94,7 +100,7 @@ func pointerReleaseUsesSavedRouteAfterWindowAndProcessChanges(_ system: Bool) th let held = HeldInputs() let target = try NativePlatform.identity(getpid()) let route = WindowRoute(owner: target, windowID: 7, bounds: .init(x: 0, y: 0, width: 100, height: 100)) - let owner = HeldInputs.Owner(connection: UUID(), scope: scope, app: "editor") + let owner = HeldInputs.Owner(connection: UUID(), task: task, app: "editor") try held.pointerDown(owner: owner, route: route, button: .left, system: false, down: pointer(.leftMouseDown), up: pointer(.leftMouseUp), post: { _ in }) #expect(throws: NativeFailure.self) { try held.requirePointerAvailable(route: route, button: .left, system: false) } diff --git a/packages/experimental/cua-macos/native/tests/test_ax_projection.py b/packages/experimental/cua-macos/native/tests/test_ax_projection.py index ad66437d6e..b882e51dfa 100644 --- a/packages/experimental/cua-macos/native/tests/test_ax_projection.py +++ b/packages/experimental/cua-macos/native/tests/test_ax_projection.py @@ -49,7 +49,7 @@ def check_input(executable, helper_path, root): ("click", {**scoped, "x": 20, "y": 40}), ("typeText", {**owner, "text": "a"}), ("pressKey", {**owner, "key": "a"}), - ("sendKeyEvent", {**owner, "key": "a", "direction": "down", "taskId": "fixture", "turn": 1})]: + ("sendKeyEvent", {**owner, "key": "a", "direction": "down", "taskId": "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 diff --git a/packages/experimental/cua-macos/src/index.ts b/packages/experimental/cua-macos/src/index.ts index 3a80984f98..b32a008f1b 100644 --- a/packages/experimental/cua-macos/src/index.ts +++ b/packages/experimental/cua-macos/src/index.ts @@ -63,7 +63,7 @@ export const Config = Schema.object({ * @returns Completion after native preparation and tool registration. */ export async function apply(ctx: Context, config: Config): Promise { - const backend = { createChannel: createSharedNativeChannel, turnInputLifecycle: true, + const backend = { createChannel: createSharedNativeChannel, heldInputState: true, getGuidance: (kind: 'raw' | 'standalone') => kind === 'raw' ? GUIDANCE : PROGRAM_GUIDANCE, capabilities: CAPABILITIES, acceptsPidSelector: true, permissionParameters: createPermissionParameters(config.permissionPollIntervalMs) } if (config.helperPath !== undefined) { diff --git a/packages/experimental/cua-macos/tests/guidance.spec.ts b/packages/experimental/cua-macos/tests/guidance.spec.ts index 08a21589b6..3846c81814 100644 --- a/packages/experimental/cua-macos/tests/guidance.spec.ts +++ b/packages/experimental/cua-macos/tests/guidance.spec.ts @@ -54,8 +54,8 @@ it('states the macOS accessibility, keyboard, and mouse levels', () => { expect(PLATFORM_GUIDANCE).toContain('Simulated mouse input is available at window level') const pressKey = GUIDANCE.split('\n').find(line => line.startsWith('- pressKey(')) expect(GUIDANCE).toContain("sendKeyEvent(key: string, direction: 'down' | 'up')") - expect(COMMON_GUIDANCE).toContain('sendKeyEvent and toggleMouse share one turn-wide hold scope') - expect(COMMON_GUIDANCE).toContain('After turn/end, cleanup releases remaining keys and buttons together in reverse dispatch order') + expect(COMMON_GUIDANCE).toContain('sendKeyEvent and toggleMouse remain held across programs and turns') + expect(COMMON_GUIDANCE).toContain('a system reminder lists any keys and mouse buttons still held') const sharedKeyEvent = COMMON_GUIDANCE.split('\n').find(line => line.startsWith('- sendKeyEvent(')) expect(sharedKeyEvent).toBeDefined() expect(GUIDANCE.split('\n').find(line => line.startsWith('- sendKeyEvent('))).toContain(sharedKeyEvent) diff --git a/packages/experimental/cua-macos/tests/turn-inputs.desktop.e2e.ts b/packages/experimental/cua-macos/tests/held-inputs.desktop.e2e.ts similarity index 93% rename from packages/experimental/cua-macos/tests/turn-inputs.desktop.e2e.ts rename to packages/experimental/cua-macos/tests/held-inputs.desktop.e2e.ts index fa90af8e1e..d5deb62d5f 100644 --- a/packages/experimental/cua-macos/tests/turn-inputs.desktop.e2e.ts +++ b/packages/experimental/cua-macos/tests/held-inputs.desktop.e2e.ts @@ -112,11 +112,18 @@ it.skipIf(process.platform !== 'darwin' || helperPath === undefined).each(['comp handle.agent.cancel({ kind: 'user' }) } await handle.agent.whenIdle() + if (ending === 'completed') { + expect((await received()).map(event => event.type)).toEqual([10, 1, 10]) + expect(JSON.stringify(handle.agent.session.snapshotEvents())).toContain('CUA inputs are still held') + programs[3] = "await app.sendKeyEvent('w', 'up'); await win.toggleMouse('left', 'up'); await app.sendKeyEvent('a', 'up')" + handle.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Release held input' }], source: { kind: 'user' } })) + await handle.agent.whenIdle() + } await expect.poll(async () => (await received()).map(event => [event.type, event.keyCode ?? null]), { timeout: 30_000 }).toEqual([ [10, 0], [1, null], [10, 13], [11, 13], [2, null], [11, 0], ]) const outcomes = handle.agent.session.snapshotEvents().filter(event => event.type === 'turn/end') - expect(outcomes).toHaveLength(1) + expect(outcomes).toHaveLength(ending === 'completed' ? 2 : 1) expect(outcomes[0]?.data.reason.kind).toBe(ending === 'completed' ? 'completed' : ending === 'error' ? 'error' : 'aborted') await handle.dispose() } finally { diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index 4734ec3510..22005bc421 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -216,26 +216,13 @@ async function selectApplication(f: Awaited>) { expect((await f.execute('getApp', { selector: 'Fixture' })).isError).toBe(false) } -it('requires an active turn before sending a directional key', async () => { +it('accepts task-owned directional input outside a turn', async () => { const f = await setup() await selectApplication(f) - native.request.mockClear() + native.request.mockResolvedValueOnce({ dispatched: true }) const result = await f.execute('sendKeyEvent', { appHandle: 'app-one', key: 'w', direction: 'down' }) - expect(result.isError).toBe(true) - expect(JSON.stringify(result.content)).toContain('active agent turn') - expect(native.request).not.toHaveBeenCalled() -}) - -it.each(['run_code', 'cua_run_code'] as const)('finishes a shortcut-only %s without requesting held-key cleanup', async (name) => { - const f = await setup(undefined, true) - await selectApplication(f) - native.request.mockClear().mockResolvedValue({ dispatched: true }) - const result = await executeProgram(f, name, - "return await tools.cua({ method: 'pressKey', params: { appHandle: 'app-one', key: 'a', modifiers: ['command'] } });", - 'Press Command+A') expect(result.isError).toBe(false) - expect(native.request.mock.calls.map(([method]) => method)).toEqual(['pressKey']) - expect(native.cleanup).not.toHaveBeenCalled() + expect(native.request).toHaveBeenLastCalledWith('sendKeyEvent', { appHandle: 'app-one', key: 'w', direction: 'down', taskId: f.handle.agent.id }, expect.any(AbortSignal), expect.any(String)) }) it('holds a key from run_code until a later cua_run_code explicitly releases it in the same turn', async () => { @@ -244,8 +231,9 @@ it('holds a key from run_code until a later cua_run_code explicitly releases it await selectApplication(f) const held = new Set() native.request.mockClear().mockImplementation(async (method, params) => { + if (method === 'getHeldInputs') return [...held].map(key => ({ kind: 'key', key, appHandle: 'app-one', mode: 'application' })) expect(method).toBe('sendKeyEvent') - expect(params).toMatchObject({ taskId: f.handle.agent.id, turn: 1 }) + expect(params).toMatchObject({ taskId: f.handle.agent.id }) const key = params.key if (typeof key !== 'string') throw new Error('The native fixture requires a key name') if (params.direction === 'down') held.add(key) @@ -262,7 +250,7 @@ it('holds a key from run_code until a later cua_run_code explicitly releases it expect(native.cleanup).not.toHaveBeenCalled() f.handle.agent.cancel({ kind: 'user' }) await f.handle.agent.whenIdle() - expect(native.cleanup).toHaveBeenCalledExactlyOnceWith('releaseHeldInputs', { taskId: f.handle.agent.id, turn: 1 }) + expect(native.cleanup).not.toHaveBeenCalled() }) it('rejects a relative helper path before publishing computer-use operations', async () => { @@ -1156,9 +1144,9 @@ it('requires an explicit system-pointer request on every move and asks only once [hoverTarget, false], [{ ...hoverTarget, useSystemPointer: false }, false], [physicalHover, true], ] as const) { expect((await f.execute('mouseMove', params)).isError).toBe(false) - expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...hoverTarget, useSystemPointer: physical, ...physical ? { taskId: f.handle.agent.id, turn: 1 } : {} }, expect.any(AbortSignal), expect.any(String)) + expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...hoverTarget, useSystemPointer: physical, ...physical ? { taskId: f.handle.agent.id } : {} }, expect.any(AbortSignal), expect.any(String)) } - expect(native.request.mock.calls[1]?.[1]).toEqual({ ...physicalHover, taskId: f.handle.agent.id, turn: 1 }) + expect(native.request.mock.calls[1]?.[1]).toEqual({ ...physicalHover, taskId: f.handle.agent.id }) expect(f.ask).toHaveBeenCalledTimes(1) }) @@ -1167,7 +1155,7 @@ it.each([true, false])('shares the mouse control decision for a system button wi const target = { appHandle: 'app-one', windowId: '7', mouseButton: 'left', direction: 'down' } for (const params of [target, { ...target, useSystemPointer: false }]) { expect((await f.execute('toggleMouse', params)).isError).toBe(false) - expect(native.request.mock.lastCall?.[1]).toEqual({ ...target, taskId: f.handle.agent.id, turn: 1 }) + expect(native.request.mock.lastCall?.[1]).toEqual({ ...target, taskId: f.handle.agent.id }) } expect(f.ask).not.toHaveBeenCalled() const answer = Promise.withResolvers() @@ -1188,7 +1176,7 @@ it.each([true, false])('shares the mouse control decision for a system button wi .toEqual([['toggleMouse', true], ['mouseMove', true], ['toggleMouse', undefined]]) f.handle.agent.cancel({ kind: 'user' }) await f.handle.agent.whenIdle() - expect(native.cleanup).toHaveBeenCalledWith('releaseHeldInputs', { taskId: f.handle.agent.id, turn: 1 }) + expect(native.cleanup).toHaveBeenCalledWith('releaseHeldInputs', { taskId: f.handle.agent.id }) } else { for (const result of results.slice(0, 2)) expect(JSON.stringify(result.content)).toContain('MOUSE_CONTROL_DENIED') expect(results[2]?.isError).toBe(false) @@ -1236,7 +1224,7 @@ it('keeps refusals and grants separate and forgets a closed session on reopen', expect((await f.call(agent, 'mouseMove', hoverTarget)).isError).toBe(false) expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...hoverTarget, useSystemPointer: false }, expect.any(AbortSignal), expect.any(String)) expect((await f.execute('mouseMove', physicalHover)).isError).toBe(false) - expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...physicalHover, taskId: f.handle.agent.id, turn: 1 }, expect.any(AbortSignal), expect.any(String)) + expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...physicalHover, taskId: f.handle.agent.id }, expect.any(AbortSignal), expect.any(String)) const sessionId = f.handle.agent.id await f.handle.dispose() const reopened = await f.ctx.agents.create({ sessionId }) @@ -1296,7 +1284,7 @@ it('allows only the explicitly requested physical move when approval is disabled const f = await hoverFixture(false) for (const [target, expected] of [[hoverTarget, false], [physicalHover, true], [hoverTarget, false]] as const) { expect((await f.execute('mouseMove', target)).isError).toBe(false) - expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...hoverTarget, useSystemPointer: expected, ...expected ? { taskId: f.handle.agent.id, turn: 1 } : {} }, expect.any(AbortSignal), expect.any(String)) + expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...hoverTarget, useSystemPointer: expected, ...expected ? { taskId: f.handle.agent.id } : {} }, expect.any(AbortSignal), expect.any(String)) } expect(f.ask).not.toHaveBeenCalled() }) @@ -1363,7 +1351,7 @@ it('keeps complete system moves available outside a turn without registering a p await selectApplication(f) native.request.mockClear() expect((await f.execute('mouseMove', physicalHover)).isError).toBe(false) - expect(native.request).toHaveBeenCalledExactlyOnceWith('mouseMove', physicalHover, expect.any(AbortSignal), expect.any(String)) + expect(native.request).toHaveBeenCalledExactlyOnceWith('mouseMove', { ...physicalHover, taskId: f.handle.agent.id }, expect.any(AbortSignal), expect.any(String)) await f.handle.dispose() expect(native.cleanup).not.toHaveBeenCalled() }) diff --git a/packages/experimental/cua-mcp/README.i18n.yaml b/packages/experimental/cua-mcp/README.i18n.yaml index 81f5e950ba..ff0e591dc7 100644 --- a/packages/experimental/cua-mcp/README.i18n.yaml +++ b/packages/experimental/cua-mcp/README.i18n.yaml @@ -51,8 +51,8 @@ en: 0b0c63281111993b zh: 45716a56b5a5ad12 /deepseek-ai-dsh-cua-mcp/known-limitations-and-deferred-work: - en: 743cd8c6a8c89453 - zh: 0d85356f5a9537a0 + en: 15a5daadd52dddd8 + zh: 5d4ddf2da4f31bba /deepseek-ai-dsh-cua-mcp/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 8ec3e73528ddb1a6 diff --git a/packages/experimental/cua-mcp/README.md b/packages/experimental/cua-mcp/README.md index efba38a3e1..4f245554dd 100644 --- a/packages/experimental/cua-mcp/README.md +++ b/packages/experimental/cua-mcp/README.md @@ -167,7 +167,7 @@ The tool catalog and instructions are stable for one installation. The reference -- macOS explicit `sendKeyEvent` and `toggleMouse` holds require an active DSH turn. MCP programs run as maintenance activities, so these operations are unavailable through MCP. Use complete `pressKey`, `typeText`, `click`, or `drag` actions; system pointer movement remains available. The server cannot infer the client's turn boundaries. +- Successful programs disclose remaining native-held keys and mouse buttons in a system reminder. Inputs persist across calls until explicit up. Program failure, cancellation, reset and connection closure release owned input; no client turn notification is required. - macOS and native Windows Hosts have a provider. Other Hosts, WSL included, list `cua_get_api_reference` and `cua_reset`, which both name the missing provider; a `cua_run_code` call fails as `unknown tool`. - On Windows the [provider's limits](../cua-windows/README.md#known-limitations-and-deferred-work) apply through MCP: it does not launch applications, grants no `Always allow`, and an npm installation needs `helperPath`. - Elicitation uses the 2025 MCP request model; a client that negotiates the 2026-07-28 revision receives an error for consent requests and should use `DSH_CUA_CONSENT=allow`. diff --git a/packages/experimental/cua-mcp/README.zh.md b/packages/experimental/cua-mcp/README.zh.md index a7342e3c43..269482828b 100644 --- a/packages/experimental/cua-mcp/README.zh.md +++ b/packages/experimental/cua-mcp/README.zh.md @@ -167,7 +167,7 @@ patch 还以 `screenshotTarget: { longEdge: 2048, maxBytes: 2097152 }` 挂载该 -- macOS 的 `sendKeyEvent` 和 `toggleMouse` 显式持有要求活动的 DSH 回合。MCP 程序以维护活动执行,因此这些操作在 MCP 中不可用。请使用完整的 `pressKey`、`typeText`、`click` 或 `drag` 动作;系统鼠标移动仍可使用。服务器无法推断客户端的回合边界。 +- 成功结束的程序通过 system reminder 报告原生仍按住的键盘键和鼠标按钮。输入跨调用保持,直到显式 up。程序失败、取消、重置和断连释放所属输入,不需要客户端发送回合通知。 - macOS 与原生 Windows Host 有提供方。其他 Host(包括 WSL)列出 `cua_get_api_reference` 与 `cua_reset`,二者都指出缺少提供方;调用 `cua_run_code` 以 `unknown tool` 失败。 - 在 Windows 上,[提供方的限制](../cua-windows/README.zh.md#known-limitations-and-deferred-work)经 MCP 同样适用:它不启动应用,不提供 `Always allow` 授权,npm 安装需要配置 `helperPath`。 - Elicitation 使用 2025 版 MCP 请求模型;协商到 2026-07-28 修订版的客户端在授权请求时收到错误,应改用 `DSH_CUA_CONSENT=allow`。 diff --git a/packages/experimental/cua-mcp/src/server.ts b/packages/experimental/cua-mcp/src/server.ts index 3c7f09b4c9..ee920fbd7c 100644 --- a/packages/experimental/cua-mcp/src/server.ts +++ b/packages/experimental/cua-mcp/src/server.ts @@ -96,7 +96,7 @@ const INSTRUCTIONS = 'DeepSeek Harness Computer Use: observe and operate desktop + 'written without it guess the API wrong. Then call cua_run_code with a TypeScript program that uses the global cua ' + 'object; program state persists across calls on this connection. A call may ask the user for application or pointer ' + 'consent before it proceeds. Call cua_reset to discard program state. ' - + 'On macOS, MCP programs cannot hold keys or mouse buttons with explicit down events. Use pressKey, click, or drag.' + + 'Explicit key and mouse downs can remain held across programs. A system reminder lists remaining held inputs after successful programs. Release them explicitly when finished; program failure, cancellation, reset, and connection closure release owned input.' const NO_PROVIDER = 'Computer Use is not available on this Host: the cua-mcp profile has no active CUA provider. ' + 'Providers exist for macOS and native Windows; on those Hosts the server\'s stderr names why the provider did not start.' diff --git a/packages/experimental/cua-mcp/tests/composition.spec.ts b/packages/experimental/cua-mcp/tests/composition.spec.ts index 866e570a27..75f52f853b 100644 --- a/packages/experimental/cua-mcp/tests/composition.spec.ts +++ b/packages/experimental/cua-mcp/tests/composition.spec.ts @@ -108,7 +108,7 @@ async function setup(options: SetupOptions = {}) { cua: { inject: ['computerUse', 'subprocess', 'tools', 'systemPrompt', 'agents'], Config: CuaConfig, apply(owner: Context, config: CuaConfig) { - installCua(owner, config, { helperPath: process.execPath, turnInputLifecycle: true, + installCua(owner, config, { helperPath: process.execPath, heldInputState: true, createChannel: options.cancellationAcknowledgementMs === undefined ? native.createChannel : delayCancellation(native.createChannel, options.cancellationAcknowledgementMs, () => { native.events.push('cancellation-acknowledged') }), @@ -182,22 +182,21 @@ async function setup(options: SetupOptions = {}) { } describe('Computer Use MCP composition', () => { - it('refuses persistent downs outside a turn and still completes clicks through MCP', async () => { - const { client, native, run } = await setup() - expect(client.getInstructions()).toContain('MCP programs cannot hold keys or mouse buttons') - const capabilities = await run('inspect(JSON.stringify((await cua.getCapabilities()).methods))') - expect(texts(capabilities).join('')).toContain('sendKeyEvent') - expect(texts(capabilities).join('')).toContain('toggleMouse') - const selected = await run('var app = await cua.getApp("test.fixture"); var win = await app.getWindow("7"); await win.getAccessibilityTree()') - expect(selected.isError).not.toBe(true) - for (const code of ['await app.sendKeyEvent("w", "down")', 'await win.toggleMouse("left", "down")']) { - const result = await run(code) - expect(result.isError).toBe(true) - expect(texts(result).join('\n')).toContain('active agent turn') - } - expect(native.calls.some(call => call.method === 'sendKeyEvent' || call.method === 'toggleMouse')).toBe(false) - expect((await run('await win.click("0")')).isError).not.toBe(true) - expect(native.state.count).toBe(1) + it('retains input across MCP programs, reminds after success, and releases on error and reset', async () => { + const { native, run, client } = await setup() + expect((await run('var app = await cua.getApp("test.fixture"); var win = await app.getWindow("7"); await win.getAccessibilityTree(); await app.sendKeyEvent("w", "down")')).isError).not.toBe(true) + expect(native.held.map(press => press.key)).toEqual(['w']) + const continuing = await run('inspect("continue")') + expect(texts(continuing).join('')).toContain('Key "w", appHandle "fixture-app"') + const released = await run('await app.sendKeyEvent("w", "up")') + expect(texts(released).join('')).not.toContain('') + expect(native.held).toEqual([]) + expect((await run('await win.toggleMouse("left", "down"); throw Error("failed program")')).isError).toBe(true) + expect(native.held).toEqual([]) + expect(texts(await run('await app.sendKeyEvent("d", "down")')).join('')).toContain('Key "d"') + await client.callTool({ name: 'cua_reset', arguments: {} }) + expect(native.held).toEqual([]) + expect((await run('var app = await cua.getApp("test.fixture"); var win = await app.getWindow("7"); await win.getAccessibilityTree(); await win.click("0")')).isError).not.toBe(true) }) it('serves three tools, returns the API reference on request, and retains program state in the workspace', async () => { diff --git a/packages/experimental/cua-windows/README.i18n.yaml b/packages/experimental/cua-windows/README.i18n.yaml index 244a61100c..3c3729b071 100644 --- a/packages/experimental/cua-windows/README.i18n.yaml +++ b/packages/experimental/cua-windows/README.i18n.yaml @@ -45,8 +45,8 @@ en: db3e2957041fafbb zh: 34f953887dff37f7 /deepseek-ai-dsh-cua-windows/known-limitations-and-deferred-work: - en: 7c590d6de4705041 - zh: 3dfa7cd99010308d + en: bf9fe6192869d744 + zh: 2994b8a0c3675a88 /deepseek-ai-dsh-cua-windows/known-limitations-and-deferred-work/dev-note: en: 0a1253c6f7b5e8b9 zh: 9f56528562c7c914 diff --git a/packages/experimental/cua-windows/README.md b/packages/experimental/cua-windows/README.md index f93dd523ee..1ac1567f6d 100644 --- a/packages/experimental/cua-windows/README.md +++ b/packages/experimental/cua-windows/README.md @@ -81,7 +81,7 @@ Inspected results append to model history. Retaining an App, Window, or returned - The npm package omits the Windows helper. Use the [standalone ZIP on x64 or a matching build on ARM64](#setup). - Hover, click, scroll and drag use the system pointer. `requireSystemPointerApproval` does not prompt separately for Windows pointer operations. - Drag checks the topmost window only at its starting point. An overlay from another application along the path or at the destination can receive the drop even while the selected window stays in the foreground. -- The shared CUA hold scope is one turn. Windows has not yet implemented that lifecycle or unified reverse-order cleanup. Explicitly pair every key and mouse down with up; do not rely on automatic turn cleanup. +- Windows has not yet implemented native held-input reporting or unified failure/cancellation cleanup. Explicitly pair every key and mouse down with up; do not rely on reminders or automatic release. - The helper does not check each key or button release during cleanup. If an input remains held after a failure, release it manually before continuing. - Helper identity hashes only the exe. Different DLLs with the same apphost can reuse the old service. Stop Hosts using the same output directory before rebuilding to avoid locked files. - The Windows handshake requires a positive `maxClickHoldMs`. With zero, it fails with `INVALID_CONFIG` before ordinary clicks or status queries can run. diff --git a/packages/experimental/cua-windows/README.zh.md b/packages/experimental/cua-windows/README.zh.md index d2441860f5..4ccc7c6c46 100644 --- a/packages/experimental/cua-windows/README.zh.md +++ b/packages/experimental/cua-windows/README.zh.md @@ -81,7 +81,7 @@ kind: "package-reference" - 通过 npm 安装的包不含 Windows helper。x64 可使用独立 ZIP,ARM64 需要对应架构的构建产物,见[配置说明](#setup)。 - 悬停、点击、滚动和拖拽使用系统指针。`requireSystemPointerApproval` 不会为 Windows 操作弹出单独的指针授权提示。 - 拖拽只检查起点处最上层的窗口。若其他应用遮住路径或终点,即使目标仍在前台,也可能把内容拖到其他应用。 -- 共通 CUA 的持有范围是一个回合。Windows 尚未实现这套生命周期和统一反序清理。每次键盘或鼠标 down 都须显式配对 up,不能依赖回合自动清理。 +- Windows 尚未实现原生持有状态报告和统一的异常或取消清理。每次键盘或鼠标 down 都须显式配对 up,不能依赖提醒或自动释放。 - 清理输入时,helper 不检查每个按键或鼠标按钮的释放结果。操作失败后如有按键或按钮仍处于按下状态,请先手动释放。 - helper 的身份摘要只覆盖 exe。同一 apphost 搭配不同 DLL 时可能复用旧服务。重新构建前请先关闭使用同一输出目录的 Host,避免文件被占用。 - Windows 握手要求 `maxClickHoldMs` 为正整数。设为 0 会使连接以 `INVALID_CONFIG` 失败,连普通点击和状态查询也不可用。 diff --git a/packages/experimental/cua-windows/src/guidance.ts b/packages/experimental/cua-windows/src/guidance.ts index f8f14225a5..ab0769c163 100644 --- a/packages/experimental/cua-windows/src/guidance.ts +++ b/packages/experimental/cua-windows/src/guidance.ts @@ -2,7 +2,7 @@ import { COMMON_GUIDANCE } from '@deepseek-ai/dsh-cua/guidance' /** Windows operation levels, application selectors, and input availability. */ -export const PLATFORM_GUIDANCE = 'Windows: accessibility tree operations are available only at window level. Simulated mouse and keyboard input are available at window level. Supported modifiers: ctrl, alt, shift, win. control is an alias for ctrl. Turn-wide held-input cleanup is not yet implemented on Windows. Explicitly release every held key and mouse button with up; do not rely on automatic release after turn/end.' +export const PLATFORM_GUIDANCE = 'Windows: accessibility tree operations are available only at window level. Simulated mouse and keyboard input are available at window level. Supported modifiers: ctrl, alt, shift, win. control is an alias for ctrl. Held-input reminders and unified failure/cancellation cleanup are not yet implemented on Windows. Explicitly release every held key and mouse button with up.' const methodDetails = new Map([ ['cua.getApp', 'Windows accepts an exact AUMID returned by listApps or an existing absolute .exe path, including an executable absent from listApps. Display names and PIDs are not alternative selectors. Selection uses the existing application consent flow and starts the application only when it is not running.'], diff --git a/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts index fa50c4eb64..21c1019b3f 100644 --- a/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts @@ -50,9 +50,9 @@ it('uses an absolute fixture without compiling and disposes the Host runtime', a expect(backend.capabilities).toMatchObject({ platform: 'windows', appLevelAccessibility: false, keyboard: ['window'] }) expect(backend.capabilities.methods).toContain('sendKeyEvent') expect(backend.capabilities.methods).toContain('toggleMouse') - expect(backend.turnInputLifecycle).toBeUndefined() - expect(GUIDANCE).toContain('sendKeyEvent and toggleMouse share one turn-wide hold scope') - expect(GUIDANCE).toContain('Turn-wide held-input cleanup is not yet implemented on Windows') + expect(backend.heldInputState).toBeUndefined() + expect(GUIDANCE).toContain('sendKeyEvent and toggleMouse remain held across programs and turns') + expect(GUIDANCE).toContain('Held-input reminders and unified failure/cancellation cleanup are not yet implemented on Windows') const channel = { marker: 'native stream' } native.connect.mockReturnValue(channel) const options = { ...config, helperPath: backend.helperPath, cwd: process.cwd() } diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index 83a1ccb07e..2f9213c60c 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -21,8 +21,8 @@ en: 3f638a4a76023fc5 zh: 515aeb5de6ae5b33 /deepseek-ai-dsh-cua/understand-the-implementation: - en: 92c7e05fc2066d8f - zh: c8b1484f4dcd79c3 + en: 3b13747971967c17 + zh: 8ce73ad7615b5f05 /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 bd879bc1ac..494de6b5b7 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -89,7 +89,7 @@ Permission responses identify their platform and report only the state that plat
Shared execution and platform ownership -The shared CUA lifecycle uses one turn as the hold scope for explicit keyboard and mouse downs. Platform guidance describes implementation support, not a different hold scope. A provider enables `CuaBackend.turnInputLifecycle` only after its helper accepts `taskId` and `turn` on `sendKeyEvent`, `toggleMouse`, and system `mouseMove`, and acknowledges `releaseHeldInputs({ taskId, turn })`. Provider unload retains lifecycle listeners until program calls and native cleanup have settled. The shared owner starts cleanup from `turn/end`, closes input admission, and awaits native cancellation before independent bounded cleanup. It retains the completion promise through existing Agent maintenance and pre-step waits; `turn/end` and idle notifications alone do not confirm release. An unconfirmed release reports `agent/error` and disables all CUA operations for the task. Providers must record actual dispatch order, targets and routes before posting, implement explicit up and mixed reverse-order cleanup, reject stale turns, and clean only their connection on disconnect. `getCapabilities().methods` reports the provider’s declared methods independently of turn state; explicit hold operations require an active turn when dispatched. Windows leaves this option unset until these native behaviors are implemented; it receives neither new parameters nor cleanup commands. +Providers implementing `CuaBackend.heldInputState` accept `taskId` on explicit input and system pointer movement, report their connection-owned records through `getHeldInputs({ taskId })`, and acknowledge `releaseHeldInputs({ taskId })`. Native records own the actual key/button, target, process identity and input mode. Successful `run_code` and `cua_run_code` programs query those records and append a system reminder only when input remains held; normal program and turn endings preserve input. The reminder travels through logged additional context in DSH and through the tool response in MCP. Program failure, cancellation, connection closure, environment reset and disposal stop owned dispatch and await reverse-order release. Cleanup failure disables further CUA operations for the task and reports the uncertainty. Provider unload retains these listeners until programs and native connections drain. Capability methods remain static. Windows leaves `heldInputState` unset until its helper implements reporting and cleanup; it receives no new commands. The [permission store](src/permission-store.ts) uses `storageDomain` with the configured backend. The default JSON backend writes `$DSH_HOME/storages/cua_permissions_.json`, where the digest identifies the canonical profile directory. Each authorization check opens fresh state under the profile's file lock and closes its domain afterward; native dispatch uses a separate application lock. Revocation waits for operations already admitted by another process; after it completes, every process rejects old handles. Files on different machines or PID namespaces must not share this lock. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index e864d67e6d..b51ad68d75 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -89,7 +89,7 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边
共享执行与平台职责 -共通 CUA 生命周期以一个回合作为显式键盘和鼠标按下的持有范围。平台指导说明实现支持情况,不定义另一套持有范围。提供方仅在 helper 已接受 `sendKeyEvent`、`toggleMouse` 和系统 `mouseMove` 的 `taskId`、`turn` 参数,并能确认 `releaseHeldInputs({ taskId, turn })` 后,才启用 `CuaBackend.turnInputLifecycle`。提供方卸载时保留生命周期监听器,直到程序调用和原生清理都已结束。共通持有方从 `turn/end` 开始清理,禁止新输入,等待原生取消后用独立且有超时限制的请求释放。它通过现有的 Agent maintenance 和 pre-step 等待保留清理完成结果;单独的 `turn/end` 或空闲通知不表示释放已经确认。释放未经确认时报告 `agent/error`,并禁用该任务的全部 CUA 操作。提供方必须在派发前记录实际顺序、目标与输入方式,实现显式释放和键鼠混合反序清理,拒绝旧回合输入,并在断连时只清理本连接。`getCapabilities().methods` 报告提供方声明的方法,不随回合状态变化;显式持有操作在派发时要求活动回合。Windows 在实现这些原生行为前保持此选项未设置,不接收新增参数或清理命令。 +实现 `CuaBackend.heldInputState` 的提供方为显式输入和系统指针移动接受 `taskId`,通过 `getHeldInputs({ taskId })` 报告本连接的持有记录,并确认 `releaseHeldInputs({ taskId })`。原生记录负责保存实际按键或按钮、目标、进程身份和输入方式。成功结束的 `run_code` 和 `cua_run_code` 查询这些记录,仅在仍有输入按住时添加 system reminder;正常程序结束和回合结束均保持输入。DSH 通过已记录的额外上下文传递提醒,MCP 通过工具响应传递。程序失败、取消、断连、环境重置和销毁会停止所属输入派发,并等待反序释放。清理失败会禁用该任务后续 CUA 操作并报告结果不确定。提供方卸载前保留监听器,直到程序和原生连接排空。能力方法列表保持静态。Windows 在 helper 实现报告和清理前不设置 `heldInputState`,不会收到新命令。 [授权存储](src/permission-store.ts)复用 `storageDomain` 和配置的后端。默认 JSON 后端写入 `$DSH_HOME/storages/cua_permissions_.json`,摘要对应 profile 的真实目录。每次授权检查在 profile 文件锁内打开并读取最新状态,随后关闭存储域;原生操作使用单独的应用锁。撤销会等待其他进程已获准执行的操作结束;撤销完成后,各进程都拒绝旧句柄。不同电脑或 PID 命名空间不能共享这把锁。 diff --git a/packages/experimental/cua/src/guidance.ts b/packages/experimental/cua/src/guidance.ts index 0aa590fe1d..7a33540720 100644 --- a/packages/experimental/cua/src/guidance.ts +++ b/packages/experimental/cua/src/guidance.ts @@ -57,7 +57,7 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. -Explicit downs from sendKeyEvent and toggleMouse share one turn-wide hold scope across run_code and cua_run_code calls. An explicit up releases input immediately at its original recipient. Program return or failure does not end a continuing turn. After turn/end, cleanup releases remaining keys and buttons together in reverse dispatch order, including on failure or user stop. pressKey, typeText, click, and complete drag release their own inputs within the operation. +Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any keys and mouse buttons still held, with their targets and input modes. No reminder is added when none remain. Program failure, user stop, connection closure, and disposal release owned inputs together in reverse dispatch order. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/packages/experimental/cua/src/held-inputs.ts b/packages/experimental/cua/src/held-inputs.ts new file mode 100644 index 0000000000..52f75407ec --- /dev/null +++ b/packages/experimental/cua/src/held-inputs.ts @@ -0,0 +1,175 @@ +/** Native-owned held input, program-end reminders, and failure/cancellation cleanup. */ +import type { Context } from '@deepseek-ai/cordis' +import { emitAgentEvent, type Agent } from '@deepseek-ai/dsh-agent' +import { createUserMessage, type ContextFormed } from '@deepseek-ai/dsh-llm' +import { RUN_CODE_NAME } from '@deepseek-ai/dsh-tools' +import { z } from 'zod' +import { NativeError, type NativeClient } from './native-client.ts' + +declare module '@deepseek-ai/dsh-llm' { + interface MessageSourceMap { + 'cua-held-inputs': { kind: 'cua-held-inputs' } & ContextFormed + } +} + +const target = { appHandle: z.string(), mode: z.enum(['application', 'window', 'system']) } +const heldInputs = z.array(z.discriminatedUnion('kind', [ + z.object({ ...target, kind: z.literal('key'), key: z.string() }), + z.object({ ...target, kind: z.literal('mouse'), button: z.enum(['left', 'right', 'middle']), windowId: z.string() }), +])) + +class InputOwner { + readonly controller = new AbortController() + private client: NativeClient | undefined + private removeCleanup: (() => void) | undefined + closing: Promise | undefined + + constructor(readonly agent: Agent, private readonly failed: (error: unknown) => void) {} + + track(client: NativeClient): void { + this.controller.signal.throwIfAborted() + if (this.client) return + this.removeCleanup = client.registerCleanup(canRequest => this.close(canRequest)) + this.client = client + } + + async reminder(): Promise { + if (!this.client) return + const inputs = heldInputs.parse(await this.client.request('getHeldInputs', { taskId: this.agent.id }, this.controller.signal)) + if (inputs.length === 0) { + this.removeCleanup?.() + this.removeCleanup = undefined + this.client = undefined + return + } + const rows = inputs.map(input => input.kind === 'key' + ? `- Key ${JSON.stringify(input.key)}, appHandle ${JSON.stringify(input.appHandle)} (${input.mode} input).` + : `- Mouse ${input.button}, appHandle ${JSON.stringify(input.appHandle)}, windowId ${JSON.stringify(input.windowId)} (${input.mode} input).`) + return ['', 'CUA inputs are still held:', ...rows, + "They remain pressed across programs and turns. Release them explicitly with sendKeyEvent(key, 'up') or toggleMouse(button, 'up') on the same target when no longer needed.", + ''].join('\n') + } + + close(canRequest = true): Promise { + this.controller.abort() + return this.closing ??= Promise.resolve().then(async () => { + try { + if (!this.client) return + if (!canRequest) throw new NativeError('INPUT_CLEANUP_UNCONFIRMED', 'Native connection closed before held-input cleanup was confirmed. Inspect the desktop manually before starting a new task') + await this.client.requestCleanup('releaseHeldInputs', { taskId: this.agent.id }) + } catch (error) { + this.failed(error) + throw error + } finally { + this.removeCleanup?.() + this.removeCleanup = undefined + } + }) + } + + async settled(): Promise { + try { await this.closing } + catch (_cleanupFailed) { /* close reports the failure and disables this task's CUA operations. */ } + } +} + +/** One provider's held input owners; the helper remains the authority for which inputs are pressed. */ +export class CuaHeldInputs { + private readonly owners = new WeakMap() + private readonly failures = new WeakMap() + private readonly turnSignals = new Map void }>() + + /** @param ctx - Provider scope owning input observers and program middleware. */ + constructor(private readonly ctx: Context) {} + + /** + * Wait for cleanup and obtain an owner for a new operation. + * @param agent - Agent issuing a CUA operation. + * @returns Ownership and cancellation shared by its held inputs. + */ + async ready(agent: Agent): Promise { + const previous = this.owners.get(agent) + if (previous?.closing) await previous.settled() + if (this.failures.has(agent)) throw new NativeError('INPUT_CLEANUP_UNCONFIRMED', + 'CUA cleanup was not confirmed. All CUA operations are disabled for this task; inspect the desktop manually before starting a new task', { cause: this.failures.get(agent) }) + const current = this.owners.get(agent) + if (current && !current.closing) return current + const owner = new InputOwner(agent, (error) => { + this.failures.set(agent, error) + this.ctx.logger.error('CUA cleanup was not confirmed; all CUA operations are disabled for task %s: %s', agent.id, error) + emitAgentEvent(this.ctx, agent, 'agent/error', { turn: this.ctx.agents.turnBoundaryOf(agent.session).lastTurn, step: 0, error }) + }) + this.owners.set(agent, owner) + return owner + } + + /** + * Stop owned dispatch and release held input with an independent bounded native request. + * @param agent - Agent whose input must be released. + * @returns Completion after native acknowledgement, or rejection if cleanup is unconfirmed. + */ + async release(agent: Agent): Promise { await this.owners.get(agent)?.close() } + + private stop(agent: Agent): void { + const owner = this.owners.get(agent) + if (!owner) return + void owner.close().catch(() => undefined) // close records and reports the failure; waiters join the same promise. + } + + /** @returns Exact disposers retained until programs and native connections have drained. */ + *install(): Generator<() => void> { + const ctx = this.ctx + yield ctx.on('tools/execute', async (execution, next) => { + if (!execution.agent || (execution.name !== RUN_CODE_NAME && execution.name !== 'cua_run_code')) return next() + const agent = execution.agent + const signal = execution.signal + const abort = (): void => { this.stop(agent) } + signal.addEventListener('abort', abort, { once: true }) + try { + const result = await next() + if (result.isError || signal.aborted) { + signal.removeEventListener('abort', abort) + try { await this.release(agent) } + catch (error) { throw new NativeError('INPUT_CLEANUP_UNCONFIRMED', + `${result.isError ? result.error.message : 'Program cancelled'}. Held-input cleanup failed: ${String(error)}`, { cause: error }) } + } else if (execution.parent === undefined) { + const text = await this.owners.get(agent)?.reminder() + if (text) execution.deferContext(createUserMessage({ content: [{ type: 'text', text }], + source: { kind: 'cua-held-inputs', form: 'notice', summary: 'CUA inputs remain held' } })) + } + return result + } catch (error) { + signal.removeEventListener('abort', abort) + try { await this.release(agent) } + catch (cleanupError) { throw new NativeError('INPUT_CLEANUP_UNCONFIRMED', `Program failed: ${String(error)}. Held-input cleanup failed: ${String(cleanupError)}`, { cause: error }) } + throw error + } finally { + signal.removeEventListener('abort', abort) + await this.owners.get(agent)?.settled() + } + }) + yield ctx.on('agent/pre-step', (event, next) => { + const previous = this.turnSignals.get(event.agent) + if (previous?.signal !== event.signal) { + previous?.remove() + const abort = (): void => { this.stop(event.agent) } + event.signal.addEventListener('abort', abort, { once: true }) + this.turnSignals.set(event.agent, { signal: event.signal, remove: () => { event.signal.removeEventListener('abort', abort) } }) + } + return next() + }) + yield ctx.on('session/event', (session, event) => { + if (event.type !== 'turn/end') return + const agent = ctx.agents.get(session.id) + if (agent?.session !== session) return + this.turnSignals.get(agent)?.remove() + this.turnSignals.delete(agent) + if (event.data.reason.kind === 'aborted' || event.data.reason.kind === 'error') this.stop(agent) + }) + yield ctx.on('agent/status', ({ agent, status }) => { + const owner = this.owners.get(agent) + if (status === 'idle' && owner?.closing) void agent.runMaintenance(() => owner.settled()) + }, { prepend: true }) + yield () => { for (const value of this.turnSignals.values()) value.remove(); this.turnSignals.clear() } + } +} diff --git a/packages/experimental/cua/src/index.ts b/packages/experimental/cua/src/index.ts index d5a1148bf1..c9034b8cf0 100644 --- a/packages/experimental/cua/src/index.ts +++ b/packages/experimental/cua/src/index.ts @@ -14,7 +14,7 @@ import type { JsonValue } from '@deepseek-ai/dsh-util-values' import { z } from 'zod' import { NativeClient, NativeError, type NativeClientConfig, type NativeChannelFactory } from './native-client.ts' import { MouseControl } from './mouse-control.ts' -import { CuaInputTurns } from './turn-inputs.ts' +import { CuaHeldInputs } from './held-inputs.ts' import { withSystemPointerGuidance } from './guidance.ts' import { CuaPermissionStore } from './permission-store.ts' import { ApplicationAuthorizationResult, installCuaAccess } from './access.ts' @@ -187,8 +187,8 @@ export interface CuaBackend { capabilities: CuaStartupCapabilities /** Preserve discovery PIDs when getApp accepts a decimal PID as an exact process selector. */ acceptsPidSelector?: boolean - /** Opt in to task/turn parameters and acknowledged releaseHeldInputs; omission preserves the provider's existing protocol. */ - turnInputLifecycle?: boolean + /** Opt in to task-owned getHeldInputs and releaseHeldInputs; omission preserves the provider's existing protocol. */ + heldInputState?: boolean /** * Build native permission parameters for the selected action and Client language. * @param method Native permission action. @@ -207,7 +207,7 @@ export interface CuaBackend { */ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend): void { const { helperPath } = backend - const inputTurns = backend.turnInputLifecycle ? new CuaInputTurns(ctx) : undefined + const heldInputs = backend.heldInputState ? new CuaHeldInputs(ctx) : undefined const systemPointer = backend.capabilities.systemPointer === true const mouseControl = systemPointer ? new MouseControl(ctx, config.requireSystemPointerApproval) : undefined const requestSchema = systemPointer ? SystemPointerRequest : Request @@ -264,7 +264,7 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) return owner } ctx.effect(function* () { - if (inputTurns) yield* inputTurns.install() + if (heldInputs) yield* heldInputs.install() yield ctx.computerUse.register(brandString('dsh-cua')) yield async () => { lifetime.abort() @@ -287,14 +287,10 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) // Earlier helpers accept an explicit false only for mouseMove. if (method !== 'mouseMove' && !useSystemPointer) delete params.useSystemPointer else if (useSystemPointer !== undefined) params.useSystemPointer = useSystemPointer - if (inputTurns && (method === 'sendKeyEvent' || method === 'toggleMouse' || (method === 'mouseMove' && useSystemPointer))) { - const turn = inputTurns.scope(agent) - if (!turn && method !== 'mouseMove') throw new ToolContextUnavailableError('Directional CUA input requires an active agent turn; external MCP programs can use pressKey, click, and drag') - if (turn) { - if (method !== 'mouseMove' && params.direction === 'down') turn.track(client) - params.taskId = agent.id - params.turn = turn.turn - } + if (heldInputs && (method === 'sendKeyEvent' || method === 'toggleMouse' || (method === 'mouseMove' && useSystemPointer))) { + const owner = await heldInputs.ready(agent) + if (method !== 'mouseMove' && params.direction === 'down') owner.track(client) + params.taskId = agent.id } const nativeParams = method === 'findApps' ? { ...params, maxAppMatches: config.maxAppMatches } @@ -389,9 +385,10 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) execution.signal.throwIfAborted() lifetime.signal.throwIfAborted() const owner = ownerFor(agent) - if (inputTurns) await inputTurns.ready(agent) - const turn = inputTurns?.scope(agent) - const signal = AbortSignal.any([execution.signal, lifetime.signal, owner.signal, ...turn ? [turn.signal] : []]) + const inputOwner = await heldInputs?.ready(agent) + const signal = AbortSignal.any([ + execution.signal, lifetime.signal, owner.signal, ...inputOwner ? [inputOwner.controller.signal] : [], + ]) signal.throwIfAborted() const operation = (async () => { const previous = clients.get(agent) @@ -420,7 +417,7 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) } const nativeClient = client const route = request.method === 'mouseMove' || request.method === 'drag' - || (request.method === 'toggleMouse' && !(inputTurns && request.params.direction === 'up')) + || (request.method === 'toggleMouse' && !(heldInputs && request.params.direction === 'up')) ? mouseControl?.resolve(agent, 'useSystemPointer' in request.params && request.params.useSystemPointer === true) : undefined if (route?.prepare) owner.coordinates.parameters(request) @@ -445,7 +442,7 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) } }, } - yield installCuaTools(ctx, config, tool, guidance, programGuidance) + yield installCuaTools(ctx, config, tool, guidance, programGuidance, agent => heldInputs?.release(agent) ?? Promise.resolve()) }, 'dsh-cua.runtime') } diff --git a/packages/experimental/cua/src/tool-registration.ts b/packages/experimental/cua/src/tool-registration.ts index 2d7f3d8012..308f1d6dd2 100644 --- a/packages/experimental/cua/src/tool-registration.ts +++ b/packages/experimental/cua/src/tool-registration.ts @@ -25,7 +25,7 @@ export interface CuaPrograms { * Release one Agent's retained program environment with the dedicated runtime's owner release. The program * process exits, a program of that Agent that is still running fails as aborted, and the next `cua_run_code` * call starts a fresh process that re-creates the `cua` global. The Agent, its application grants and native - * connection, and the desktop applications themselves are unaffected. The runtime rejects that Agent's + * connection, and the desktop applications themselves are unaffected. Held input is released. The runtime rejects that Agent's * programs until the release settles, so the caller holds them back; after a failed release it rejects them * until a later release succeeds. Resolves when no environment exists. * @param agent - Agent whose `cua_run_code` state owner is released. @@ -68,10 +68,12 @@ export function fixedScreenshotTarget(configured: CuaScreenshotTargetConfig, ima * @param tool Internal native tool; Agents off the configured preset can reach it only through the program. * @param guidance Raw-tool operation instructions for the configured preset. * @param programGuidance Operation instructions available inside cua_run_code. + * @param releaseInputs Release held input when resetting the program environment. * @returns Exact registration disposer, draining programs before native resources can close. */ export function installCuaTools( ctx: Context, config: CuaConfig, tool: ToolDefinition, guidance: string, programGuidance: string, + releaseInputs: (agent: Agent) => Promise, ): () => void | Promise { // PTC publishes the installed JS entry; automatic CUA initialization follows the Host's code format. const ptcBridgeUrl = JSON.stringify(new URL('../lib/bridge.js', import.meta.url).href) @@ -152,7 +154,9 @@ var cua = connectCua(() => tools.cua); }) // Hosts without a model (MCP frontends) end an Agent's environment with the runtime's owner release. consumer.provide('cuaPrograms', { - release: (agent: Agent) => consumer.ptcRuntime.release(agent), + release: async (agent: Agent) => { + try { await consumer.ptcRuntime.release(agent) } finally { await releaseInputs(agent) } + }, screenshotRequestTarget: image => config.screenshotTarget === undefined ? undefined : fixedScreenshotTarget(config.screenshotTarget, image), } satisfies CuaPrograms) diff --git a/packages/experimental/cua/src/turn-inputs.ts b/packages/experimental/cua/src/turn-inputs.ts deleted file mode 100644 index 82029dd8b8..0000000000 --- a/packages/experimental/cua/src/turn-inputs.ts +++ /dev/null @@ -1,121 +0,0 @@ -/** Turn-owned admission and acknowledged cleanup for providers implementing held input. */ -import type { Context } from '@deepseek-ai/cordis' -import { emitAgentEvent, type Agent } from '@deepseek-ai/dsh-agent' -import { NativeError, type NativeClient } from './native-client.ts' - -class InputTurn { - readonly controller = new AbortController() - readonly signal: AbortSignal - private client?: NativeClient - private removeCleanup: (() => void) | undefined - private closing?: Promise - - constructor(readonly agent: Agent, readonly turn: number, signal: AbortSignal, - private readonly failed: (error: unknown) => void) { - this.signal = AbortSignal.any([signal, this.controller.signal]) - } - - /** installCua retains one Agent connection until its registered cleanup closes admission here. */ - track(client: NativeClient): void { - this.signal.throwIfAborted() - if (!this.client) { - this.removeCleanup = client.registerCleanup(canRequest => this.close(canRequest)) - this.client = client - } - } - - get pending(): boolean { return this.removeCleanup !== undefined } - - /** Close reports and disables the failed owner; background and maintenance waits must still settle. */ - async settle(): Promise { - try { await this.close() } - catch (_error) { /* close has reported the failure and disabled this task's CUA operations. */ } - } - - close(canRequest = true): Promise { - this.controller.abort() - return this.closing ??= Promise.resolve().then(async () => { - try { - if (!this.client) return - if (!canRequest) throw new NativeError('INPUT_CLEANUP_UNCONFIRMED', 'Native connection closed before turn cleanup was confirmed. All CUA operations are disabled for this task; inspect the desktop manually before starting a new task') - await this.client.requestCleanup('releaseHeldInputs', { taskId: this.agent.id, turn: this.turn }) - } catch (error) { - this.failed(error) - throw error - } finally { - this.removeCleanup?.() - this.removeCleanup = undefined - } - }) - } -} - -/** A provider opts in only when its helper implements the turn-owned input protocol. */ -export class CuaInputTurns { - private readonly turns = new WeakMap() - private readonly failures = new WeakMap() - - /** @param ctx - Provider scope owning the lifecycle listeners. */ - constructor(private readonly ctx: Context) {} - - /** - * Install turn admission, post-turn cleanup and whole-agent maintenance waits. - * @returns Exact disposers for the runtime effect to retain through native cleanup. - */ - *install(): Generator<() => void> { - const ctx = this.ctx - yield ctx.on('agent/pre-step', async (event, next) => { - const previous = this.turns.get(event.agent) - if (previous?.turn !== event.turn) { - await previous?.settle() - this.turns.set(event.agent, new InputTurn(event.agent, event.turn, event.signal, (error) => { - this.failures.set(event.agent, error) - ctx.logger.error('CUA cleanup was not confirmed; all CUA operations are disabled for task %s: %s', event.agent.id, error) - emitAgentEvent(ctx, event.agent, 'agent/error', { turn: event.turn, step: 0, error }) - })) - } - return next() - }) - yield ctx.on('session/event', (session, event) => { - if (event.type !== 'turn/end') return - const agent = ctx.agents.get(session.id) - if (agent?.session !== session) return - const owner = this.turns.get(agent) - if (owner?.turn === event.data.turn) void owner.settle() - }) - yield ctx.on('agent/status', ({ agent, status }) => { - if (status !== 'idle') return - const owner = this.turns.get(agent) - if (!owner?.pending) return - // Claim the idle phase before notification consumers submit more work. whenIdle follows maintenance. - void agent.runMaintenance(() => owner.settle()) - }, { prepend: true }) - } - - /** - * Wait for an ended turn before a direct CUA operation can acquire the connection. - * @param agent - Task issuing the operation. - * @returns Completion after cleanup has settled and any failure has been reported. - */ - async ready(agent: Agent): Promise { - const owner = this.turns.get(agent) - if (owner?.controller.signal.aborted) { - await owner.settle() - } - } - - /** - * Resolve admission for the current turn; a failed cleanup blocks further CUA dispatch. - * @param agent - Task issuing the operation. - * @returns Turn signal and native ownership, or undefined before a turn starts. - */ - scope(agent: Agent): InputTurn | undefined { - if (this.failures.has(agent)) { - throw new NativeError('INPUT_CLEANUP_UNCONFIRMED', 'CUA cleanup was not confirmed. All CUA operations are disabled for this task; inspect the desktop manually before starting a new task', { cause: this.failures.get(agent) }) - } - const boundary = this.ctx.agents.turnBoundaryOf(agent.session) - if (boundary.openTurnStartSeq === null) return undefined - const owner = this.turns.get(agent) - return owner?.turn === boundary.lastTurn ? owner : undefined - } -} diff --git a/packages/experimental/cua/src/types.ts b/packages/experimental/cua/src/types.ts index 943e071c26..d61f39140f 100644 --- a/packages/experimental/cua/src/types.ts +++ b/packages/experimental/cua/src/types.ts @@ -157,8 +157,8 @@ export interface CuaSurface { pressKey(key: string, modifiers?: string[]): Promise /** * Send one key-down or key-up event at the current input focus. - * Explicit downs share the current turn across programs; cleanup after turn/end releases remaining input. - * macOS implements turn cleanup; Windows support is pending and requires explicit up. + * Explicit downs persist across programs and turns. Successful programs disclose remaining holds in a system reminder. + * Program failure, cancellation, connection closure and disposal release owned input. Windows support is pending. * Rejects when the provider does not support keyboard input at this scope. * @param key - Platform-defined key name; modifier keys may themselves be targets. * @param direction - Down establishes a hold; up immediately releases owned input at its saved recipient. @@ -193,8 +193,8 @@ export interface CuaWindow extends CuaSurface { options?: CuaCoordinateOptions & { useSystemPointer?: boolean }): Promise /** * Send one mouse-button down or up event without moving the pointer. - * Uses the same turn lifecycle as {@link CuaSurface.sendKeyEvent}; up uses the saved window and input route. - * Implemented turn cleanup releases keys and buttons together in reverse press order after turn/end. + * Uses the same held-input lifecycle as {@link CuaSurface.sendKeyEvent}; up uses the saved window and input route. + * Error and cancellation cleanup releases keys and buttons together in reverse dispatch order. * @param mouseButton - Mouse button to press or release. * @param direction - Explicit event direction. * @param options - Request a system button on a provider reporting systemPointer. diff --git a/packages/experimental/cua/tests/run-code-composition.spec.ts b/packages/experimental/cua/tests/run-code-composition.spec.ts index d0fe9bfdda..0a919e03a4 100644 --- a/packages/experimental/cua/tests/run-code-composition.spec.ts +++ b/packages/experimental/cua/tests/run-code-composition.spec.ts @@ -1,5 +1,4 @@ /** Standard-mode CUA through Loader, the native executor, and real persistent Node programs. */ -import { setImmediate } from 'node:timers/promises' import { mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -44,7 +43,8 @@ class ProgramModel extends LlmAdapter { beforeStream?: (index: number, options: GenerateOptions) => Promise /** Requests a test holds back until it has finished acting between two model steps. */ readonly gates = new Map>() - constructor(private readonly programs: readonly string[]) { super() } + constructor(private programs: readonly string[]) { super() } + restart(programs: readonly string[]): void { this.programs = programs; this.requests.length = 0 } override resolveModel(provider: string, model: string): Promise { return Promise.resolve({ provider, id: model, name: model, inputModalities: ['text', 'image'] }) } @@ -66,7 +66,7 @@ class ProgramModel extends LlmAdapter { } } -async function setup(programs: readonly string[], platform = 'macos', selectorPid?: number, presetFree = false, turnInputLifecycle = false, timeoutMs = 30_000) { +async function setup(programs: readonly string[], platform = 'macos', selectorPid?: number, presetFree = false, heldInputState = false, timeoutMs = 30_000) { const directory = await mkdtemp(join(tmpdir(), 'dsh-cua-run-code-')) const ctx = new Context() onTestFinished(async () => { @@ -106,7 +106,7 @@ async function setup(programs: readonly string[], platform = 'macos', selectorPi apply(owner: Context, config: CuaConfig) { installCua(owner, config, { helperPath: process.execPath, createChannel: native.createChannel, getGuidance: () => 'Use the CUA object API to inspect and control the selected application.', - acceptsPidSelector: selectorPid !== undefined, turnInputLifecycle, + acceptsPidSelector: selectorPid !== undefined, heldInputState, capabilities: { platform, methods: ['getCapabilities', 'listApps', 'getApp', 'getState', 'click', 'screenshot', 'sendKeyEvent', 'toggleMouse'], appLevelAccessibility: true, keyboard: ['app'], browser: false, coordinateSpace: 'screenshot-pixels' }, permissionParameters: (_method, permission, locale) => ({ permission, locale }), @@ -358,51 +358,75 @@ it('forwards per-read accessibility limits to the Windows backend', async () => const holdProgram = 'var app = await cua.getApp("test.fixture"); await app.sendKeyEvent("w", "down")' -it('keeps held keys across programs and a failed program until explicit up or turn completion', async () => { - const f = await setup([holdProgram, 'throw Error("program failed")', - 'await app.sendKeyEvent("w", "up"); await app.sendKeyEvent("shift", "down"); var win = await app.getWindow("7"); await win.toggleMouse("left", "down"); await app.sendKeyEvent("d", "down")'], +function reminders(agent: { session: { snapshotEvents(): readonly import('@deepseek-ai/dsh-session').SessionEvent[] } }) { + return agent.session.snapshotEvents().filter(event => event.type === 'user/message' && event.data.source.kind === 'cua-held-inputs') + .flatMap(event => event.type === 'user/message' ? event.data.content.filter(block => block.type === 'text').map(block => block.text) : []) +} + +it('reports native held input after programs, keeps it across turns, and stops reminding after explicit up', async () => { + const f = await setup([holdProgram, 'inspect("still holding")'], 'macos', undefined, true, true) + await f.run() + expect(f.native.held.map(press => press.key)).toEqual(['w']) + expect(f.native.events).toEqual(['w:down']) + expect(reminders(f.agent)).toHaveLength(2) + expect(reminders(f.agent)[0]).toContain('Key "w", appHandle "fixture-app"') + expect(f.model.requests[1]?.messages.some(message => JSON.stringify(message).includes('CUA inputs are still held'))).toBe(true) + expect(f.native.calls.some(call => call.method === 'releaseHeldInputs')).toBe(false) + f.model.restart(['await app.sendKeyEvent("w", "up")']) + await f.run() + expect(f.native.events).toEqual(['w:down', 'w:up']) + expect(reminders(f.agent)).toHaveLength(2) +}) + +it('releases keyboard and mouse in mixed reverse order on program failure', async () => { + const f = await setup([holdProgram, + 'await app.sendKeyEvent("shift", "down"); var win = await app.getWindow("7"); await win.toggleMouse("left", "down"); await app.sendKeyEvent("d", "down"); throw Error("program failed")'], 'macos', undefined, true, true) await f.run() - const results = f.agent.session.deriveMessages().filter(message => message.role === 'tool') - expect(results.map(result => result.isError)).toEqual([false, true, false]) - expect(f.native.events).toEqual(['w:down', 'w:up', 'shift:down', 'left:down', 'd:down', 'd:up', 'left:up', 'shift:up']) - const requests = f.native.calls.filter(call => call.method === 'sendKeyEvent') - expect(requests.map(call => [call.params.taskId, call.params.turn])).toEqual(Array(4).fill([f.agent.id, 1])) + expect(f.native.events).toEqual(['w:down', 'shift:down', 'left:down', 'd:down', 'd:up', 'left:up', 'shift:up', 'w:up']) + expect(f.native.held).toEqual([]) + expect(reminders(f.agent)).toHaveLength(1) expect(f.native.calls.filter(call => call.method === 'releaseHeldInputs')).toHaveLength(1) + const results = f.agent.session.deriveMessages().filter(message => message.role === 'tool') + expect(results.map(result => result.isError)).toEqual([false, true]) +}) + +it('reminders name the actual mouse target and omit explicitly released inputs', async () => { + const f = await setup([holdProgram, 'await app.sendKeyEvent("w", "up"); var win = await app.getWindow("7"); await win.toggleMouse("left", "down")'], + 'macos', undefined, true, true) + await f.run() + expect(reminders(f.agent)[1]).toContain('Mouse left, appHandle "fixture-app", windowId "7" (window input)') + expect(reminders(f.agent)[1]).not.toContain('Key "w"') + await f.handle.dispose() expect(f.native.held).toEqual([]) }) -it.each(['normal', 'model failure', 'thinking stop'] as const)('records turn/end before cleanup and makes whenIdle await native release on %s', async (ending) => { - const f = await setup([holdProgram], 'macos', undefined, true, true) +it.each(['model failure', 'thinking stop', 'tool stop'] as const)('awaits held input release on %s', async (ending) => { + const f = await setup([holdProgram + (ending === 'tool stop' ? '; await new Promise(() => {})' : '')], 'macos', undefined, true, true) const thinking: PromiseWithResolvers = Promise.withResolvers() - const idle: PromiseWithResolvers = Promise.withResolvers() - f.ctx.on('agent/status', ({ agent, status }) => { if (agent === f.agent && status === 'idle') idle.resolve() }) f.model.beforeStream = async (index, options) => { if (index !== 1) return - if (ending === 'model failure') throw new Error('Model request failed') - if (ending === 'thinking stop') { - thinking.resolve() - await new Promise((resolve) => { options.signal?.addEventListener('abort', () => { resolve() }, { once: true }) }) - } + if (ending === 'model failure') throw new Error('Model failed') + thinking.resolve() + await new Promise((resolve) => { options.signal?.addEventListener('abort', () => { resolve() }, { once: true }) }) } - const release = f.native.controlNext('releaseHeldInputs') + const down = ending === 'tool stop' ? f.native.controlNext('sendKeyEvent', { afterDispatch: true }) : undefined + const release = ending === 'tool stop' ? undefined : f.native.controlNext('releaseHeldInputs') let settled = false const running = f.run().then(() => { settled = true }) - if (ending === 'thinking stop') { await thinking.promise; f.agent.cancel({ kind: 'user' }) } - await Promise.all([release.entered, idle.promise]) - try { - expect(f.agent.status).toBe('idle') + if (down) { await down.entered; f.agent.cancel({ kind: 'user' }); down.reply() } + else if (ending === 'thinking stop') { await thinking.promise; f.agent.cancel({ kind: 'user' }) } + if (release) { + await release.entered expect(settled).toBe(false) - expect(f.agent.session.snapshotEvents().some(event => event.type === 'turn/end')).toBe(true) - expect(f.native.held.map(press => press.key)).toEqual(['w']) - } finally { release.reply(); await running } + release.reply() + } + await running expect(f.native.held).toEqual([]) - expect(f.agent.session.snapshotEvents().at(-1)).toMatchObject({ type: 'turn/end', data: { reason: { - kind: ending === 'normal' ? 'completed' : ending === 'model failure' ? 'error' : 'aborted', - } } }) + expect(f.native.events.filter(event => event === 'w:up')).toHaveLength(1) }) -it('stops an in-flight down before cleanup and does not release input from the next turn', async () => { +it('cancels an in-flight down before releasing input and allows later programs after confirmed cleanup', async () => { const f = await setup([holdProgram], 'macos', undefined, true, true) const down = f.native.controlNext('sendKeyEvent', { afterDispatch: true, waitForCancellation: true }) const running = f.run() @@ -411,219 +435,82 @@ it('stops an in-flight down before cleanup and does not release input from the n await down.cancelled expect(f.native.held.map(press => press.key)).toEqual(['w']) expect(f.native.calls.some(call => call.method === 'releaseHeldInputs')).toBe(false) - down.reply({ code: 'NATIVE_CANCELLED', message: 'Input stopped after dispatch' }) + down.reply({ code: 'NATIVE_CANCELLED', message: 'Stopped after dispatch' }) await running expect(f.native.held).toEqual([]) f.model.requests.length = 0 - const release = f.native.controlNext('releaseHeldInputs') - f.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Next turn' }], source: { kind: 'user' } })) - await release.entered - expect(f.native.held.map(press => press.turn)).toEqual([2]) - release.reply() - await f.agent.whenIdle() - expect(f.native.calls.filter(call => call.method === 'releaseHeldInputs').map(call => call.params.turn)).toEqual([1, 2]) - expect(f.native.events.filter(event => event === 'w:up')).toHaveLength(2) + await f.run() + expect(f.native.held.map(press => press.key)).toEqual(['w']) + expect(f.native.events.filter(event => event === 'w:up')).toHaveLength(1) }) -it.each(['refusal', 'disconnect', 'timeout'] as const)('reports cleanup %s and prevents this task from dispatching more input', async (failure) => { - const f = await setup([holdProgram], 'macos', undefined, true, true, failure === 'timeout' ? 200 : 30_000) +it.each(['refusal', 'disconnect', 'timeout'] as const)('reports cleanup %s and disables further CUA operations', async (failure) => { + const f = await setup([holdProgram + '; throw Error("program failed")'], 'macos', undefined, true, true, failure === 'timeout' ? 200 : 30_000) const errors: unknown[] = [] f.ctx.on('agent/error', (event) => { errors.push(event.error) }) const release = f.native.controlNext('releaseHeldInputs') const running = f.run() await release.entered - if (failure === 'refusal') release.reply({ code: 'INPUT_CLEANUP_FAILED', message: 'Fixture release rejected' }) - else if (failure === 'disconnect') release.disconnect() + if (failure === 'refusal') release.reply({ code: 'INPUT_CLEANUP_FAILED', message: 'Release rejected' }) + if (failure === 'disconnect') release.disconnect() await running expect(errors).toHaveLength(1) - expect(f.agent.session.snapshotEvents().at(-1)).toMatchObject({ type: 'turn/end', data: { reason: { kind: 'completed' } } }) const count = f.native.calls.length f.model.requests.length = 0 - f.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Try again' }], source: { kind: 'user' } })) - await f.agent.whenIdle() + await f.run() expect(f.native.calls).toHaveLength(count) expect(JSON.stringify(f.agent.session.deriveMessages())).toContain('INPUT_CLEANUP_UNCONFIRMED') }) -it.each(['agent', 'provider', 'context'] as const)('awaits held input cleanup when the %s is disposed', async (owner) => { +it('reports failed native state inspection and releases held input instead of claiming it is empty', async () => { const f = await setup([holdProgram], 'macos', undefined, true, true) - const thinking: PromiseWithResolvers = Promise.withResolvers() - f.model.beforeStream = async (index, options) => { - if (index !== 1) return - thinking.resolve() - await new Promise((resolve) => { options.signal?.addEventListener('abort', () => { resolve() }, { once: true }) }) - } + const query = f.native.controlNext('getHeldInputs') const running = f.run() - await thinking.promise + await query.entered + query.reply({ code: 'NATIVE_ERROR', message: 'Held state unavailable' }) + await running + expect(reminders(f.agent)).toEqual([]) + expect(f.native.held).toEqual([]) + expect(JSON.stringify(f.agent.session.deriveMessages())).toContain('Held state unavailable') +}) + +it.each(['agent', 'provider', 'context'] as const)('awaits native release when the %s is disposed after a completed turn', async (owner) => { + const f = await setup([holdProgram], 'macos', undefined, true, true) + await f.run() + expect(f.native.held).toHaveLength(1) const release = f.native.controlNext('releaseHeldInputs') let disposed = false const closing = (owner === 'agent' ? f.handle.dispose() : owner === 'provider' ? f.provider.dispose() : f.ctx.fiber.dispose()).then(() => { disposed = true }) - const first = await Promise.race([release.entered.then(() => 'cleanup'), closing.then(() => 'closed')]) - expect(first, JSON.stringify({ calls: f.native.calls, events: f.native.events, held: f.native.held })).toBe('cleanup') - try { - expect(disposed).toBe(false) - expect(f.native.state.closedChannels).toBe(0) - f.agent.cancel({ kind: 'user' }) - // Turn completion is observable while native acknowledgement remains behind its explicit barrier. - await setImmediate() - expect(f.agent.session.snapshotEvents().some(event => event.type === 'turn/end')).toBe(true) - } finally { - release.reply() - f.agent.cancel({ kind: 'user' }) - await closing - await running - } + await release.entered + expect(disposed).toBe(false) + expect(f.native.state.closedChannels).toBe(0) + release.reply() + await closing expect(f.native.held).toEqual([]) - expect(f.native.calls.filter(call => call.method === 'releaseHeldInputs')).toHaveLength(1) expect(f.native.state.closedChannels).toBe(1) }) -it('does not send turn input parameters or cleanup to a provider that has not opted in', async () => { +it('leaves providers without held-input state support on their existing protocol', async () => { const f = await setup([holdProgram, 'await app.sendKeyEvent("w", "up")'], 'windows', undefined, true) await f.run() - const input = f.native.calls.filter(call => call.method === 'sendKeyEvent') - expect(input).toHaveLength(2) - for (const call of input) { - expect(call.params).not.toHaveProperty('turn') - expect(call.params).not.toHaveProperty('taskId') - } - expect(f.native.calls.some(call => call.method === 'releaseHeldInputs')).toBe(false) + for (const call of f.native.calls.filter(call => call.method === 'sendKeyEvent')) expect(call.params).not.toHaveProperty('taskId') + expect(f.native.calls.some(call => ['getHeldInputs', 'releaseHeldInputs'].includes(call.method))).toBe(false) + expect(reminders(f.agent)).toEqual([]) }) -it('cleans one task without releasing another connection and prevents a queued turn from overtaking cleanup', async () => { +it('reports and releases only the owning task inputs', async () => { const f = await setup([holdProgram], 'macos', undefined, true, true) const peerModel = new ProgramModel([holdProgram.replace('"w"', '"d"')]) f.ctx.llm.registerAdapter(['peer-fixture'], peerModel) - const peer = await f.ctx.agents.create({ sessionId: brandString('peer-input-owner'), meta: { cwd: process.cwd() }, + const peer = await f.ctx.agents.create({ sessionId: brandString('peer-held-input'), meta: { cwd: process.cwd() }, agentOptions: { provider: 'peer-fixture', model: 'vision' } }) - const ready: Array> = [Promise.withResolvers(), Promise.withResolvers()] - for (const [index, model] of [f.model, peerModel].entries()) { - model.beforeStream = async (step, options) => { - if (step !== 1) return - ready[index]!.resolve() - await new Promise((resolve) => { options.signal?.addEventListener('abort', () => { resolve() }, { once: true }) }) - } - } - const running = f.run() + await f.run() peer.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Hold D' }], source: { kind: 'user' } })) - await Promise.all(ready.map(value => value.promise)) - expect(f.native.held.map(press => press.key).sort()).toEqual(['d', 'w']) - const cleanup = f.native.controlNext('releaseHeldInputs') - f.agent.cancel({ kind: 'user' }) - await cleanup.entered - const count = f.native.calls.length - f.model.requests.length = 0 - delete f.model.beforeStream - f.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Hold W again' }], source: { kind: 'user' } })) - expect(f.native.calls).toHaveLength(count) - const nextCleanup = f.native.controlNext('releaseHeldInputs') - cleanup.reply() - await nextCleanup.entered - try { - expect(f.native.held.map(press => [press.taskId, press.turn, press.key]).sort()) - .toEqual([[f.agent.id, 2, 'w'], [peer.agent.id, 1, 'd']].sort()) - } finally { - nextCleanup.reply() - peer.agent.cancel({ kind: 'user' }) - await Promise.all([running, f.agent.whenIdle(), peer.agent.whenIdle()]) - } - expect(f.native.held).toEqual([]) -}) - -it('reports disconnect after a dispatched down and blocks a later program in the same turn', async () => { - const f = await setup([holdProgram, 'await cua.getApp("test.fixture")'], 'macos', undefined, true, true) - const down = f.native.controlNext('sendKeyEvent', { afterDispatch: true }) - const running = f.run() - await down.entered - down.disconnect() - await running - const results = f.agent.session.deriveMessages().filter(message => message.role === 'tool') - expect(results.map(result => result.isError)).toEqual([true, true]) - expect(JSON.stringify(results[1])).toContain('INPUT_CLEANUP_UNCONFIRMED') - expect(f.native.calls.filter(call => call.method === 'getApp')).toHaveLength(1) - expect(f.native.calls.some(call => call.method === 'releaseHeldInputs')).toBe(false) - expect(f.agent.session.snapshotEvents().find(event => event.type === 'turn/end')?.data.reason.kind).toBe('completed') -}) - -it('ends without native cleanup when prompt assembly fails before input admission', async () => { - const f = await setup([holdProgram], 'macos', undefined, true, true) - f.ctx.on('system-prompt/assemble', async () => { throw new Error('Fixture assembly failed') }) - await f.run() - expect(f.native.calls).toEqual([]) - expect(f.agent.session.snapshotEvents().find(event => event.type === 'turn/end')?.data.reason.kind).toBe('error') -}) - -it('keeps held input while turn-stopping steering continues the same turn', async () => { - const f = await setup([holdProgram], 'macos', undefined, true, true) - let stops = 0 - f.ctx.on('agent/turn-stopping', ({ agent }) => { - if (agent !== f.agent || ++stops !== 1) return - agent.steer(createUserMessage({ content: [{ type: 'text', text: 'Continue this turn' }], source: { kind: 'user' } })) - }) - f.model.beforeStream = async (index) => { - if (index === 2) expect(f.native.held.map(press => press.key)).toEqual(['w']) - } - await f.run() - expect(stops).toBe(2) - expect(f.native.events).toEqual(['w:down', 'w:up']) - expect(f.native.calls.filter(call => call.method === 'releaseHeldInputs').map(call => call.params.turn)).toEqual([1]) -}) - -it('blocks a queued turn at pre-step until the previous native cleanup settles', async () => { - const f = await setup([holdProgram], 'macos', undefined, true, true) - const nextStep: PromiseWithResolvers = Promise.withResolvers() - f.ctx.on('agent/pre-step', (event, next) => { - if (event.agent === f.agent && event.turn === 2) nextStep.resolve() - return next() - }, { prepend: true }) - f.model.beforeStream = async (index) => { - if (index === 1) f.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Queued turn' }], source: { kind: 'user' } })) - } - const release = f.native.controlNext('releaseHeldInputs') - const running = f.run() - await Promise.all([release.entered, nextStep.promise]) - try { - expect(f.model.requests).toHaveLength(2) - expect(f.native.held.map(press => press.turn)).toEqual([1]) - expect(f.agent.session.snapshotEvents().filter(event => event.type === 'turn/end')).toHaveLength(1) - } finally { release.reply(); await running } - expect(f.model.requests).toHaveLength(3) - expect(f.native.held).toEqual([]) -}) - -it('does not resume retained inbox work when stopped during post-turn cleanup', async () => { - const f = await setup([holdProgram], 'macos', undefined, true, true) - const idle: PromiseWithResolvers = Promise.withResolvers() - f.ctx.on('agent/status', ({ status }) => { if (status === 'idle') idle.resolve() }) - const release = f.native.controlNext('releaseHeldInputs') - const running = f.run() - await Promise.all([release.entered, idle.promise]) - f.agent.inject(createUserMessage({ content: [{ type: 'text', text: 'Retained input' }], source: { kind: 'user' } })) - f.agent.cancel({ kind: 'user' }, { keepInbox: true }) - release.reply() - await running - expect(f.native.held).toEqual([]) - expect(f.agent.session.snapshotEvents().filter(event => event.type === 'turn/start')).toHaveLength(1) - expect(f.agent.inbox.nextStep).toHaveLength(1) -}) - -it('ignores an unattached Session ending while another task holds input', async () => { - const f = await setup([holdProgram], 'macos', undefined, true, true) - const thinking: PromiseWithResolvers = Promise.withResolvers() - const finish: PromiseWithResolvers = Promise.withResolvers() - f.model.beforeStream = async (index) => { - if (index !== 1) return - thinking.resolve() - await finish.promise - } - const running = f.run() - await thinking.promise - try { - const session = f.ctx.sessions.create(brandString('without-agent')) - session.append('turn/start', { turn: 1 }) - session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) - expect(f.native.held.map(press => press.key)).toEqual(['w']) - expect(f.native.calls.some(call => call.method === 'releaseHeldInputs')).toBe(false) - } finally { finish.resolve(); await running } + await peer.agent.whenIdle() + expect(reminders(f.agent).join('')).not.toContain('Key "d"') + expect(reminders(peer.agent).join('')).not.toContain('Key "w"') + await f.handle.dispose() + expect(f.native.held.map(press => press.key)).toEqual(['d']) + await peer.dispose() expect(f.native.held).toEqual([]) }) diff --git a/snapshots/session/cua-run-code/native-channel.d.mts b/snapshots/session/cua-run-code/native-channel.d.mts index aa3ac63e27..080aa206f1 100644 --- a/snapshots/session/cua-run-code/native-channel.d.mts +++ b/snapshots/session/cua-run-code/native-channel.d.mts @@ -12,7 +12,7 @@ export function createNativeFixture(selectorPid?: number): { createChannel: NativeChannelFactory calls: Array<{ id: string; method: string; params: Record }> events: string[] - held: Array<{ connection: number; taskId: string; turn: number; key: string }> + held: Array<{ connection: number; taskId: string; key: string }> /** Control one native reply or cancellation acknowledgement at a deterministic barrier. */ controlNext(method: string, options?: { afterDispatch?: boolean; waitForCancellation?: boolean }): { entered: Promise diff --git a/snapshots/session/cua-run-code/native-channel.mjs b/snapshots/session/cua-run-code/native-channel.mjs index aeb02c824f..a14a708e37 100644 --- a/snapshots/session/cua-run-code/native-channel.mjs +++ b/snapshots/session/cua-run-code/native-channel.mjs @@ -27,10 +27,13 @@ export function createNativeFixture(selectorPid) { let blocked let heldCallId function dispatch(method, params) { + if (method === 'getHeldInputs') return held.filter(press => press.connection === connection && press.taskId === params.taskId).map(press => press.kind === 'key' + ? { kind: 'key', key: press.key, appHandle: press.appHandle, mode: 'application' } + : { kind: 'mouse', button: press.key, appHandle: press.appHandle, windowId: press.windowId, mode: press.mode }) if (method === 'releaseHeldInputs') { for (let index = held.length - 1; index >= 0; index--) { const press = held[index] - if (press.connection === connection && press.taskId === params.taskId && press.turn === params.turn) { + if (press.connection === connection && press.taskId === params.taskId) { events.push(`${press.key}:up`) held.splice(index, 1) } @@ -50,10 +53,11 @@ export function createNativeFixture(selectorPid) { if (!acquired || params.appHandle !== 'fixture-app') throw new Error('Acquire the application before using its handle') if (method === 'sendKeyEvent' || method === 'toggleMouse') { const key = params.key ?? params.mouseButton - const index = held.findIndex(press => press.connection === connection && press.taskId === params.taskId && press.turn === params.turn && press.key === key) - if (params.direction === 'down' && index < 0) held.push({ connection, taskId: params.taskId, turn: params.turn, key }) + const index = held.findIndex(press => press.connection === connection && press.taskId === params.taskId && press.key === key) + if (params.direction === 'down' && index < 0) held.push({ connection, taskId: params.taskId, key, appHandle: params.appHandle, + kind: method === 'sendKeyEvent' ? 'key' : 'mouse', windowId: params.windowId, mode: params.useSystemPointer ? 'system' : 'window' }) if (params.direction === 'up') { - if (index < 0) throw new Error('Input was not held by this turn') + if (index < 0) throw new Error('Input was not held by this task') held.splice(index, 1) } events.push(`${key}:${params.direction}`) diff --git a/snapshots/session/cua-run-code/provider.mjs b/snapshots/session/cua-run-code/provider.mjs index f7ef100d80..6667f7fb6c 100644 --- a/snapshots/session/cua-run-code/provider.mjs +++ b/snapshots/session/cua-run-code/provider.mjs @@ -12,7 +12,7 @@ export function apply(ctx, config) { const fixture = createNativeFixture() installCua(ctx, config, { helperPath: process.execPath, - turnInputLifecycle: true, + heldInputState: true, createChannel: fixture.createChannel, getGuidance: () => COMMON_GUIDANCE, capabilities: { platform: 'macos', methods: ['getCapabilities', 'getApp', 'getState', 'click', 'screenshot', 'sendKeyEvent', 'toggleMouse'], From 1eb127200b9c67a527a4958d922d8d29c6edfa6b Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 19 Nov 2026 10:29:19 +0800 Subject: [PATCH 30/73] Use typed additional context and cover program cancellation races --- .../native/Sources/CuaNative/AXWorker.swift | 2 +- packages/experimental/cua/src/held-inputs.ts | 6 ++- .../cua/tests/run-code-composition.spec.ts | 54 ++++++++++++++++++- 3 files changed, 58 insertions(+), 4 deletions(-) diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift index 47c9ec2e7e..8d4b5e7ce6 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift @@ -319,7 +319,7 @@ actor AXWorker { let observedWindows = NativePlatform.applicationWindows(identity.pid) let id = try identifier("snapshot") let scope = SnapshotScope(appHandle: handle, windowID: window) - snapshots[scope] = NativeSnapshot(id: id, task: task, elements: projection.indexed) + snapshots[scope] = NativeSnapshot(id: id, scope: scope, elements: projection.indexed) for observed in observedWindows where window == nil || observed.windowID == window { observedWindowBounds[handle, default: [:]][observed.windowID] = observed.bounds } diff --git a/packages/experimental/cua/src/held-inputs.ts b/packages/experimental/cua/src/held-inputs.ts index 52f75407ec..c1766f5b20 100644 --- a/packages/experimental/cua/src/held-inputs.ts +++ b/packages/experimental/cua/src/held-inputs.ts @@ -134,8 +134,10 @@ export class CuaHeldInputs { `${result.isError ? result.error.message : 'Program cancelled'}. Held-input cleanup failed: ${String(error)}`, { cause: error }) } } else if (execution.parent === undefined) { const text = await this.owners.get(agent)?.reminder() - if (text) execution.deferContext(createUserMessage({ content: [{ type: 'text', text }], - source: { kind: 'cua-held-inputs', form: 'notice', summary: 'CUA inputs remain held' } })) + if (text) return { ...result, additionalContexts: [...result.additionalContexts ?? [], + createUserMessage({ content: [{ type: 'text', text }], + source: { kind: 'cua-held-inputs', form: 'notice', summary: 'CUA inputs remain held' } }), + ] } } return result } catch (error) { diff --git a/packages/experimental/cua/tests/run-code-composition.spec.ts b/packages/experimental/cua/tests/run-code-composition.spec.ts index 0a919e03a4..aac553683e 100644 --- a/packages/experimental/cua/tests/run-code-composition.spec.ts +++ b/packages/experimental/cua/tests/run-code-composition.spec.ts @@ -22,6 +22,7 @@ import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import Subprocess from '@deepseek-ai/dsh-subprocess-local' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import * as NativeToolExecutor from '@deepseek-ai/dsh-tool-executor-native' +import { createRunCodeTool } from '@deepseek-ai/dsh-tool-executor-ptc/run-code' import type {} from '@deepseek-ai/dsh-tool-executor-ptc/types' import ToolRuntime, { defineTool } from '@deepseek-ai/dsh-tools' import WorkingDirectory from '@deepseek-ai/dsh-working-directory' @@ -40,6 +41,7 @@ const programs = [ class ProgramModel extends LlmAdapter { readonly requests: GenerateOptions[] = [] + toolName = 'cua_run_code' beforeStream?: (index: number, options: GenerateOptions) => Promise /** Requests a test holds back until it has finished acting between two model steps. */ readonly gates = new Map>() @@ -56,7 +58,7 @@ class ProgramModel extends LlmAdapter { if (code !== undefined) { yield { type: 'block-start', index: 0, blockType: 'tool-call' } yield { type: 'block-end', index: 0, block: { type: 'tool-call', id: brandString(`cua-program-${this.requests.length}`), - name: 'cua_run_code', arguments: JSON.stringify({ code, description: 'Inspect and increment the fixture counter' }) } } + name: this.toolName, arguments: JSON.stringify({ code, description: 'Inspect and increment the fixture counter' }) } } yield { type: 'finish', reason: { kind: 'tool-calls' } } return } @@ -514,3 +516,53 @@ it('reports and releases only the owning task inputs', async () => { await peer.dispose() expect(f.native.held).toEqual([]) }) + +it('reports native connection loss after a dispatched down and rejects further input', async () => { + const f = await setup([holdProgram], 'macos', undefined, true, true) + const down = f.native.controlNext('sendKeyEvent', { afterDispatch: true }) + const running = f.run() + await down.entered + down.disconnect() + await running + expect(JSON.stringify(f.agent.session.deriveMessages())).toContain('INPUT_CLEANUP_UNCONFIRMED') + const calls = f.native.calls.length + f.model.restart([holdProgram]) + await f.run() + expect(f.native.calls).toHaveLength(calls) +}) + +it('waits and reports cleanup refusal when user stop arrives as the program returns', async () => { + const f = await setup([holdProgram], 'macos', undefined, true, true) + f.ctx.on('tools/execute', async (execution, next) => { + const result = await next() + if (execution.name === 'cua_run_code' && execution.parent === undefined) f.agent.cancel({ kind: 'user' }) + return result + }) + const release = f.native.controlNext('releaseHeldInputs') + const running = f.run() + await release.entered + release.reply({ code: 'INPUT_CLEANUP_FAILED', message: 'Release refused during stop' }) + await running + expect(JSON.stringify(f.agent.session.deriveMessages())).toContain('Release refused during stop') +}) + +it('emits only the final outer reminder for a nested CUA program', async () => { + const f = await setup([`await tools.cua_run_code({ code: ${JSON.stringify(holdProgram)}, description: "Hold W" })`], 'macos', undefined, true, true) + const program = f.ctx.tools.get('cua_run_code', f.agent) + if (!program) throw new Error('CUA program registration missing') + f.ctx.tools.register(createRunCodeTool(f.ctx, { name: 'run_code', description: 'Run nested programs', runtime: f.ctx.ptcRuntime, tools: [program] })) + f.model.toolName = 'run_code' + await f.run() + expect(reminders(f.agent)).toHaveLength(1) + expect(f.native.calls.filter(call => call.method === 'getHeldInputs')).toHaveLength(1) + expect(f.native.held.map(press => press.key)).toEqual(['w']) +}) + +it('ignores turn endings from Sessions without an Agent', async () => { + const f = await setup([holdProgram], 'macos', undefined, true, true) + await f.run() + const session = f.ctx.sessions.create(brandString('unattached-input-session')) + session.append('turn/start', { turn: 1 }) + session.append('turn/end', { turn: 1, reason: { kind: 'error', error: { code: 'UNKNOWN', message: 'Unrelated failure' } } }) + expect(f.native.held.map(press => press.key)).toEqual(['w']) +}) From 055150bf79f1df0483dee6cc91234fc91335e4cc Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 19 Nov 2026 10:31:35 +0800 Subject: [PATCH 31/73] Exercise nested reminders through the real PTC executor --- .../experimental/cua/tests/run-code-composition.spec.ts | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/packages/experimental/cua/tests/run-code-composition.spec.ts b/packages/experimental/cua/tests/run-code-composition.spec.ts index aac553683e..200bf77f18 100644 --- a/packages/experimental/cua/tests/run-code-composition.spec.ts +++ b/packages/experimental/cua/tests/run-code-composition.spec.ts @@ -22,7 +22,7 @@ import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import Subprocess from '@deepseek-ai/dsh-subprocess-local' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import * as NativeToolExecutor from '@deepseek-ai/dsh-tool-executor-native' -import { createRunCodeTool } from '@deepseek-ai/dsh-tool-executor-ptc/run-code' +import * as PtcToolExecutor from '@deepseek-ai/dsh-tool-executor-ptc' import type {} from '@deepseek-ai/dsh-tool-executor-ptc/types' import ToolRuntime, { defineTool } from '@deepseek-ai/dsh-tools' import WorkingDirectory from '@deepseek-ai/dsh-working-directory' @@ -548,9 +548,7 @@ it('waits and reports cleanup refusal when user stop arrives as the program retu it('emits only the final outer reminder for a nested CUA program', async () => { const f = await setup([`await tools.cua_run_code({ code: ${JSON.stringify(holdProgram)}, description: "Hold W" })`], 'macos', undefined, true, true) - const program = f.ctx.tools.get('cua_run_code', f.agent) - if (!program) throw new Error('CUA program registration missing') - f.ctx.tools.register(createRunCodeTool(f.ctx, { name: 'run_code', description: 'Run nested programs', runtime: f.ctx.ptcRuntime, tools: [program] })) + await f.agent.ctx.plugin(PtcToolExecutor) f.model.toolName = 'run_code' await f.run() expect(reminders(f.agent)).toHaveLength(1) From ebdad79678dec81feeb27768fb30b6258b7b51da Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 19 Nov 2026 10:34:32 +0800 Subject: [PATCH 32/73] Expose reminder source types and verify received native input state --- docs/event-producer-consumer.md | 2 +- docs/event-producer-consumer.zh.md | 2 +- docs/subsystems/computer-use.md | 2 +- docs/subsystems/computer-use.zh.md | 2 +- .../cua-macos/native/tests/capabilities_e2e.py | 7 +++++++ .../cua-macos/tests/held-inputs.desktop.e2e.ts | 2 +- packages/experimental/cua/src/held-inputs.ts | 8 +------- packages/experimental/cua/src/types.ts | 7 +++++++ packages/extensions/tool-cordis/src/api-catalog.ts | 2 +- 9 files changed, 21 insertions(+), 13 deletions(-) diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 3e35c75b1b..308141d929 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -86,7 +86,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `system-prompt/change` | `emit` | [`packages/core/system-prompt/src/index.ts:37`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`emit`) | - | | `timeline/priority` | `emit` | [`packages/experimental/timeline/src/storage.ts:56`](../packages/experimental/timeline/src/storage.ts) | [`timeline`](../packages/experimental/timeline) (`emit`) | [`timeline`](../packages/experimental/timeline) | | `tools/change` | `emit` | [`packages/core/tools/src/events.ts:56`](../packages/core/tools/src/events.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`), [`tools`](../packages/core/tools) (`emit`) | `browser-use-runtime`, [`timeline`](../packages/experimental/timeline) | -| `tools/execute` | `waterfall` | [`packages/core/tools/src/events.ts:29`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `browser-use-runtime`, `browser-use-stagehand-native`, `claude-code-mods`, `computer-use-cua-driver-native`, [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `timeout-policy` | +| `tools/execute` | `waterfall` | [`packages/core/tools/src/events.ts:29`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `browser-use-runtime`, `browser-use-stagehand-native`, `claude-code-mods`, `computer-use-cua-driver-native`, [`cua`](../packages/experimental/cua), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `timeout-policy` | | `tools/post-execute` | `waterfall` | [`packages/core/tools/src/events.ts:41`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `claude-code-mods`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`spill-policy`](../packages/spill/spill-policy), [`tool-fs-search`](../packages/fs/tool-fs-search) | | `tools/pre-execute` | `waterfall` | [`packages/core/tools/src/events.ts:18`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `auto-review`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`tool-jobs`](../packages/jobs/tool-jobs), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `tools/ptc-dispatch-log` | `waterfall` | [`packages/core/tool-executor-ptc/src/runtime-types.ts:46`](../packages/core/tool-executor-ptc/src/runtime-types.ts) | [`tool-executor-ptc`](../packages/core/tool-executor-ptc) (`waterfall`) | [`spill-policy`](../packages/spill/spill-policy) | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index b564549f87..a16bb75978 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -88,7 +88,7 @@ | `system-prompt/change` | `emit` | [`packages/core/system-prompt/src/index.ts:37`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`emit`) | - | | `timeline/priority` | `emit` | [`packages/experimental/timeline/src/storage.ts:56`](../packages/experimental/timeline/src/storage.ts) | [`timeline`](../packages/experimental/timeline) (`emit`) | [`timeline`](../packages/experimental/timeline) | | `tools/change` | `emit` | [`packages/core/tools/src/events.ts:56`](../packages/core/tools/src/events.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`), [`tools`](../packages/core/tools) (`emit`) | `browser-use-runtime`, [`timeline`](../packages/experimental/timeline) | -| `tools/execute` | `waterfall` | [`packages/core/tools/src/events.ts:29`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `browser-use-runtime`, `browser-use-stagehand-native`, `claude-code-mods`, `computer-use-cua-driver-native`, [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `timeout-policy` | +| `tools/execute` | `waterfall` | [`packages/core/tools/src/events.ts:29`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `browser-use-runtime`, `browser-use-stagehand-native`, `claude-code-mods`, `computer-use-cua-driver-native`, [`cua`](../packages/experimental/cua), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `timeout-policy` | | `tools/post-execute` | `waterfall` | [`packages/core/tools/src/events.ts:41`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `claude-code-mods`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`spill-policy`](../packages/spill/spill-policy), [`tool-fs-search`](../packages/fs/tool-fs-search) | | `tools/pre-execute` | `waterfall` | [`packages/core/tools/src/events.ts:18`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `auto-review`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`tool-jobs`](../packages/jobs/tool-jobs), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `tools/ptc-dispatch-log` | `waterfall` | [`packages/core/tool-executor-ptc/src/runtime-types.ts:46`](../packages/core/tool-executor-ptc/src/runtime-types.ts) | [`tool-executor-ptc`](../packages/core/tool-executor-ptc) (`waterfall`) | [`spill-policy`](../packages/spill/spill-policy) | diff --git a/docs/subsystems/computer-use.md b/docs/subsystems/computer-use.md index ccba1e55d8..b2b9e8d4bd 100644 --- a/docs/subsystems/computer-use.md +++ b/docs/subsystems/computer-use.md @@ -154,7 +154,7 @@ Host control over the dedicated `cua_run_code` environments; registered as `ctx. * Release one Agent's retained program environment with the dedicated runtime's owner release. The program * process exits, a program of that Agent that is still running fails as aborted, and the next `cua_run_code` * call starts a fresh process that re-creates the `cua` global. The Agent, its application grants and native - * connection, and the desktop applications themselves are unaffected. The runtime rejects that Agent's + * connection, and the desktop applications themselves are unaffected. Held input is released. The runtime rejects that Agent's * programs until the release settles, so the caller holds them back; after a failed release it rejects them * until a later release succeeds. Resolves when no environment exists. * @param agent - Agent whose `cua_run_code` state owner is released. diff --git a/docs/subsystems/computer-use.zh.md b/docs/subsystems/computer-use.zh.md index 2bed7a57e3..4405bc3fcc 100644 --- a/docs/subsystems/computer-use.zh.md +++ b/docs/subsystems/computer-use.zh.md @@ -154,7 +154,7 @@ Host control over the dedicated `cua_run_code` environments; registered as `ctx. * Release one Agent's retained program environment with the dedicated runtime's owner release. The program * process exits, a program of that Agent that is still running fails as aborted, and the next `cua_run_code` * call starts a fresh process that re-creates the `cua` global. The Agent, its application grants and native - * connection, and the desktop applications themselves are unaffected. The runtime rejects that Agent's + * connection, and the desktop applications themselves are unaffected. Held input is released. The runtime rejects that Agent's * programs until the release settles, so the caller holds them back; after a failed release it rejects them * until a later release succeeds. Resolves when no environment exists. * @param agent - Agent whose `cua_run_code` state owner is released. diff --git a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py index f247f6c2ed..58e658e0c5 100644 --- a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py +++ b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py @@ -289,7 +289,14 @@ def check_mixed_input(call, owner, state_file, executable): call("sendKeyEvent", {**owner, "key": "a", "direction": "down"}) call("toggleMouse", {**window, "mouseButton": "left", "direction": "down", "useSystemPointer": system}) call("sendKeyEvent", {**owner, "key": "w", "direction": "down"}) + assert call("getHeldInputs", {}) == [ + {"kind": "key", "key": "a", "appHandle": owner["appHandle"], "mode": "application"}, + {"kind": "mouse", "button": "left", "appHandle": owner["appHandle"], + "windowId": window["windowId"], "mode": "system" if system else "window"}, + {"kind": "key", "key": "w", "appHandle": owner["appHandle"], "mode": "application"}, + ] call("releaseHeldInputs", {}) + assert call("getHeldInputs", {}) == [] state = wait_for_state(state_file, lambda s: sum(e.get("sourcePid") == source_pid for e in s["events"][count:]) >= 6) events = [(e["type"], e.get("keyCode")) for e in state["events"][count:] if e.get("sourcePid") == source_pid] assert events == [(10, 0), (1, None), (10, 13), (11, 13), (2, None), (11, 0)], events diff --git a/packages/experimental/cua-macos/tests/held-inputs.desktop.e2e.ts b/packages/experimental/cua-macos/tests/held-inputs.desktop.e2e.ts index d5deb62d5f..bb92e6c6ec 100644 --- a/packages/experimental/cua-macos/tests/held-inputs.desktop.e2e.ts +++ b/packages/experimental/cua-macos/tests/held-inputs.desktop.e2e.ts @@ -113,7 +113,7 @@ it.skipIf(process.platform !== 'darwin' || helperPath === undefined).each(['comp } await handle.agent.whenIdle() if (ending === 'completed') { - expect((await received()).map(event => event.type)).toEqual([10, 1, 10]) + await expect.poll(async () => (await received()).map(event => event.type), { timeout: 30_000 }).toEqual([10, 1, 10]) expect(JSON.stringify(handle.agent.session.snapshotEvents())).toContain('CUA inputs are still held') programs[3] = "await app.sendKeyEvent('w', 'up'); await win.toggleMouse('left', 'up'); await app.sendKeyEvent('a', 'up')" handle.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Release held input' }], source: { kind: 'user' } })) diff --git a/packages/experimental/cua/src/held-inputs.ts b/packages/experimental/cua/src/held-inputs.ts index c1766f5b20..d44b2aa94e 100644 --- a/packages/experimental/cua/src/held-inputs.ts +++ b/packages/experimental/cua/src/held-inputs.ts @@ -1,17 +1,11 @@ /** Native-owned held input, program-end reminders, and failure/cancellation cleanup. */ import type { Context } from '@deepseek-ai/cordis' import { emitAgentEvent, type Agent } from '@deepseek-ai/dsh-agent' -import { createUserMessage, type ContextFormed } from '@deepseek-ai/dsh-llm' +import { createUserMessage } from '@deepseek-ai/dsh-llm' import { RUN_CODE_NAME } from '@deepseek-ai/dsh-tools' import { z } from 'zod' import { NativeError, type NativeClient } from './native-client.ts' -declare module '@deepseek-ai/dsh-llm' { - interface MessageSourceMap { - 'cua-held-inputs': { kind: 'cua-held-inputs' } & ContextFormed - } -} - const target = { appHandle: z.string(), mode: z.enum(['application', 'window', 'system']) } const heldInputs = z.array(z.discriminatedUnion('kind', [ z.object({ ...target, kind: z.literal('key'), key: z.string() }), diff --git a/packages/experimental/cua/src/types.ts b/packages/experimental/cua/src/types.ts index d61f39140f..f21751353a 100644 --- a/packages/experimental/cua/src/types.ts +++ b/packages/experimental/cua/src/types.ts @@ -1,9 +1,16 @@ /** Native application objects independent of evaluator ownership and persistence. */ import type { Branded } from '@deepseek-ai/dsh-brand' +import type { ContextFormed } from '@deepseek-ai/dsh-llm' import type { JsonValue } from '@deepseek-ai/dsh-util-values' import type { z } from 'zod' import type { ActionResult, CapabilitiesResult, FoundAppsResult, HoverResult, SystemPointerRequest, ShowResult, WindowsResult } from './protocol.ts' +declare module '@deepseek-ai/dsh-llm' { + interface MessageSourceMap { + 'cua-held-inputs': { kind: 'cua-held-inputs' } & ContextFormed + } +} + /** Helper-issued application selection; public app objects hold only this opaque handle. */ export type CuaAppHandle = Branded<'CuaAppHandle'> /** Helper-issued accessibility observation identity. */ diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index f7a5c48fe8..a6e6af4b99 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -1050,7 +1050,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ methods: [ { signature: 'release(agent: Agent): Promise', - description: 'Release one Agent\'s retained program environment with the dedicated runtime\'s owner release. The program process exits, a program of that Agent that is still running fails as aborted, and the next `cua_run_code` call starts a fresh process that re-creates the `cua` global. The Agent, its application grants and native connection, and the desktop applications themselves are unaffected. The runtime rejects that Agent\'s programs until the release settles, so the caller holds them back; after a failed release it rejects them until a later release succeeds. Resolves when no environment exists.', + description: 'Release one Agent\'s retained program environment with the dedicated runtime\'s owner release. The program process exits, a program of that Agent that is still running fails as aborted, and the next `cua_run_code` call starts a fresh process that re-creates the `cua` global. The Agent, its application grants and native connection, and the desktop applications themselves are unaffected. Held input is released. The runtime rejects that Agent\'s programs until the release settles, so the caller holds them back; after a failed release it rejects them until a later release succeeds. Resolves when no environment exists.', parameters: [{ name: 'agent', description: 'Agent whose `cua_run_code` state owner is released.' }], returns: 'Completion after the process has exited and its output has drained.', throws: ['When the process cleanup fails.'], From 4795e0fc20a67bdefe133b717da3ea493ce062c1 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 19 Nov 2026 10:47:12 +0800 Subject: [PATCH 33/73] Release MCP held input before returning and report acknowledged releases --- ...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-held-inputs/guide.i18n.yaml | 4 +- .../v0.2.2-rc.5/cua-held-inputs/guide.md | 2 +- .../v0.2.2-rc.5/cua-held-inputs/guide.zh.md | 2 +- .../experimental/cua-macos/README.i18n.yaml | 4 +- packages/experimental/cua-macos/README.md | 2 +- packages/experimental/cua-macos/README.zh.md | 2 +- .../cua-macos/native/README.i18n.yaml | 4 +- .../experimental/cua-macos/native/README.md | 2 +- .../cua-macos/native/README.zh.md | 2 +- .../native/Sources/CuaNative/HeldInputs.swift | 42 +++++++++++-------- .../CuaNative/RequestCoordinator.swift | 3 +- .../tests/provider-lifecycle.spec.ts | 2 +- .../experimental/cua-mcp/README.i18n.yaml | 4 +- packages/experimental/cua-mcp/README.md | 2 +- packages/experimental/cua-mcp/README.zh.md | 2 +- packages/experimental/cua-mcp/src/server.ts | 2 +- .../cua-mcp/tests/composition.spec.ts | 40 ++++++++++++------ packages/experimental/cua/README.i18n.yaml | 4 +- packages/experimental/cua/README.md | 2 +- packages/experimental/cua/README.zh.md | 2 +- packages/experimental/cua/src/guidance.ts | 2 +- packages/experimental/cua/src/held-inputs.ts | 39 +++++++++++------ packages/experimental/cua/src/types.ts | 3 +- .../session/cua-run-code/native-channel.mjs | 3 +- 27 files changed, 110 insertions(+), 74 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 db576d9053..6a4b33dacd 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 @@ -15,5 +15,5 @@ en: 32c970ae153e0f6c zh: 8431be0a10ffed15 /agent-note-cua-scoped-surfaces-and-separated-input-capabilities/consequences: - en: 7bb0a5c23044b09c - zh: ca7c4b860660b5ce + en: 7f4cb4b375fc8bdb + zh: bf273fdc4940d988 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 ab108f5cae..1744be0a66 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 @@ -34,6 +34,6 @@ Within one API instance, the object facade keeps one current accessibility snaps Element IDs belong to the application's current accessibility snapshot. Reading one window replaces the facade’s current snapshot for that application, so callers observe again and confirm the IDs they use. The new read does not guarantee that an old string is rejected or that an ID changes; callers must not assume an older ID still identifies the same control. Pointer input and screenshots require an explicit window object; callers enumerate windows first. -Keyboard behavior follows the provider's supported scopes. A caller that uses `sendKeyEvent` controls its down/up pairing. Native input ownership follows the task and connection. Successful programs report remaining held input; normal program and turn endings do not release it. Explicit up, program failure, user cancellation and resource disposal release owned input. macOS implements this lifecycle; Windows implementation is pending. Keyboard modifier names are provider-defined, so the same string may have different support across providers. +Keyboard behavior follows the provider's supported scopes. A caller that uses `sendKeyEvent` controls its down/up pairing. Native input ownership follows the task and connection. Successful programs in DSH turns report remaining held input without releasing it. Programs outside DSH turns, including MCP, release before returning and report confirmed releases because external clients provide no between-call pause notification. Explicit up, program failure, user cancellation and resource disposal release owned input. macOS implements this lifecycle; Windows implementation is pending. Keyboard modifier names are provider-defined, so the same string may have different support across providers. Provider guidance owns the list of supported actions. Adding a method to the shared schema does not claim that every provider implements it, and the merged `getCapabilities` result remains the runtime source for permissions and session lock. 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 a7370e5643..aa36b1f2f5 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 @@ -34,6 +34,6 @@ Provider 的启动能力是静态的。平台、支持的方法、应用级辅 元素 ID 属于应用当前的辅助功能快照。读取一个窗口会替换门面对该应用的当前快照,因此调用方需要重新观察并确认要使用的 ID。新的读取不保证拒绝旧字符串,也不保证 ID 会改变;调用方不得假定旧 ID 仍指向同一控件。指针输入和截图都要求显式的窗口对象;调用方先枚举窗口。 -键盘行为遵循 provider 支持的作用域。使用 `sendKeyEvent` 的调用方控制按下与抬起的配对。原生输入所有权属于任务和连接。成功结束的程序报告剩余持有输入,正常程序结束和回合结束不释放。显式 up、程序失败、用户取消和资源销毁释放所属输入。macOS 已实现这套生命周期,Windows 待实现。键盘修饰键名称由 provider 定义,同一字符串在不同 provider 上可能支持不同。 +键盘行为遵循 provider 支持的作用域。使用 `sendKeyEvent` 的调用方控制按下与抬起的配对。原生输入所有权属于任务和连接。DSH 回合中的程序成功结束时报告剩余持有输入,不自动释放。没有 DSH 回合的程序,包括 MCP,在返回前释放并报告确认结果,因为外部客户端不提供调用之间的暂停通知。显式 up、程序失败、用户取消和资源销毁释放所属输入。macOS 已实现这套生命周期,Windows 待实现。键盘修饰键名称由 provider 定义,同一字符串在不同 provider 上可能支持不同。 Provider 指导文本负责支持动作的清单。把方法加入共享 schema 并不表示每个 provider 都已实现它;合并后的 `getCapabilities` 结果仍是权限和会话锁定状态的运行时来源。 diff --git a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml index 2856f45a1b..e25fc0bd63 100644 --- a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml @@ -9,8 +9,8 @@ en: 37252a5d19c7fe09 zh: f1b33b7da3935155 /cua-reports-held-input-after-programs/change: - en: 5b321223d0dead45 - zh: d0d09bd63dd303c2 + en: e849a0f031b21621 + zh: ce75b936e290f185 /cua-reports-held-input-after-programs/migration: en: ff2470e52eb67983 zh: 8fd179145c4da20a diff --git a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md index 9a3bd7a9cd..a49e686346 100644 --- a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md @@ -8,7 +8,7 @@ English | [中文](guide.zh.md) ## Change -macOS explicit `sendKeyEvent('down')` and `toggleMouse('down')` remain held across programs and turns until an explicit `up`. Normal completion does not release them. After a successful `run_code` or `cua_run_code`, a system reminder lists any remaining keys and mouse buttons, their application or window and actual input mode. Program failure, user stop, connection closure, environment reset and disposal release owned input in reverse dispatch order. Complete `pressKey`, `typeText`, `click` and `drag` actions keep their operation-local cleanup. DSH and MCP use the same behavior. Windows reporting and unified cleanup remain unimplemented. +Within DSH turns, macOS explicit `sendKeyEvent('down')` and `toggleMouse('down')` remain held across programs and turns until an explicit `up`. Normal completion does not release them. After a successful `run_code` or `cua_run_code`, a system reminder lists any remaining keys and mouse buttons, their application or window and actual input mode. Program failure, user stop, connection closure, environment reset and disposal release owned input in reverse dispatch order. Complete `pressKey`, `typeText`, `click` and `drag` actions keep their operation-local cleanup. MCP programs release remaining input before returning and report confirmed automatic releases, because clients do not notify the server when paused between calls. Windows reporting and unified cleanup remain unimplemented. ## Migration diff --git a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md index 0cf22a9379..597588ee2f 100644 --- a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md @@ -8,7 +8,7 @@ description: macOS CUA 的显式输入跨程序和回合保持,成功结束的 ## 变更 -macOS 的显式 `sendKeyEvent('down')` 和 `toggleMouse('down')` 跨程序、跨回合保持,直到显式 `up`。正常结束不释放它们。成功结束的 `run_code` 或 `cua_run_code` 通过 system reminder 列出剩余键盘键和鼠标按钮、所属应用或窗口及实际输入方式。程序失败、用户停止、断连、环境重置和销毁按派发顺序的反序释放所属输入。完整的 `pressKey`、`typeText`、`click` 和 `drag` 保持操作内清理。DSH 和 MCP 使用相同行为。Windows 的状态报告和统一清理仍未实现。 +在 DSH 回合中,macOS 的显式 `sendKeyEvent('down')` 和 `toggleMouse('down')` 跨程序、跨回合保持,直到显式 `up`。正常结束不释放它们。成功结束的 `run_code` 或 `cua_run_code` 通过 system reminder 列出剩余键盘键和鼠标按钮、所属应用或窗口及实际输入方式。程序失败、用户停止、断连、环境重置和销毁按派发顺序的反序释放所属输入。完整的 `pressKey`、`typeText`、`click` 和 `drag` 保持操作内清理。MCP 程序在返回前释放剩余输入并报告确认的自动释放,因为客户端在两次调用之间暂停时不会通知服务端。Windows 的状态报告和统一清理仍未实现。 ## 迁移 diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index a27bcc4499..94c1de5de5 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -15,8 +15,8 @@ en: 1777e7bf6785f986 zh: e3daac1074ebb74d /deepseek-ai-dsh-cua-macos/use-this-package: - en: ba5ff17d83e875cd - zh: 3fc685617b240e00 + en: e6cc819a0e923ed9 + zh: 39c7ecd7d007d4a7 /deepseek-ai-dsh-cua-macos/use-this-package/connect-an-external-execution-environment: en: 3bf05d9ce5eb7224 zh: d8d0cd6429374860 diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index 17efc58c14..e1de0f17f1 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -83,7 +83,7 @@ The [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-cua-m `pressKey(key, modifiers?)` presses and releases one key. For shortcuts, pass held modifiers separately, as in `pressKey('a', ['command'])`. Pressing a modifier itself, as in `pressKey('shift')`, sets its flag on press and clears it on release. A single `+` or `plus` sends Shift+=. For `pressKey`, `click`, and `drag`, use `command`, `shift`, `option`/`alt`, `control`/`ctrl`, or `fn`. Only `pressKey` accepts `cmd` as a modifier alias for `command`. Key names are platform-defined; keypad names (`KP_0` through `KP_9`, `KP_Enter`, and keypad operators) retain their physical key codes. `typeText` sends literal text, including its line breaks and tabs. Use the App object's `pressKey` for a short press. -For a long press, call `app.sendKeyEvent('w', 'down')`. Explicit key and mouse downs remain held across programs and turns until an explicit up releases them at their saved target. Successful programs report remaining holds in a system reminder, including the target and actual input mode. Program failure, user cancellation, connection closure, reset and disposal release owned keys and buttons together in reverse dispatch order. Complete `pressKey`, `typeText`, `click` and `drag` operations retain their immediate cleanup. +For a long press, call `app.sendKeyEvent('w', 'down')`. In DSH, explicit key and mouse downs remain held across programs and turns until an explicit up releases them at their saved target. Successful programs report remaining holds in a system reminder, including the target and actual input mode. Program failure, user cancellation, connection closure, reset and disposal release owned keys and buttons together in reverse dispatch order. Complete `pressKey`, `typeText`, `click` and `drag` operations retain their immediate cleanup. Agent disposal and plugin unload cancel and await the complete tool call, including image admission and attachment storage. An image write already in progress must settle before disposal returns; a canceled call cannot return a successful screenshot. diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 691c1c3044..86584c45ef 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -83,7 +83,7 @@ pnpm dsh headless --patch packages/experimental/cua-macos/examples/macos.cordis. `pressKey(key, modifiers?)` 按下并松开一个键。使用快捷键时单独传入修饰键,例如 `pressKey('a', ['command'])`。单独调用 `pressKey('shift')` 时,按下事件带有 Shift 标志,释放事件清除该标志。`+` 和 `plus` 都会发送 Shift 和等号。`pressKey`、`click` 和 `drag` 都接受修饰键 `command`、`shift`、`option`/`alt`、`control`/`ctrl` 和 `fn`。只有 `pressKey` 的修饰键参数还接受 `command` 的别名 `cmd`。按键名由平台定义;数字键盘名称(`KP_0` 到 `KP_9`、`KP_Enter` 和数字键盘运算键)保留独立的物理键码。`typeText` 发送字面文本,包括其中的换行和制表符。短按使用 App 对象上的 `pressKey`。 -长按时调用 `app.sendKeyEvent('w', 'down')`。显式键盘和鼠标按下会跨程序、跨回合保持,直到显式 up 按保存的目标释放。成功结束的程序通过 system reminder 报告剩余持有输入,包括目标和实际输入方式。程序失败、用户取消、断连、重置和销毁按实际派发顺序的反序统一释放所属键盘键和鼠标按钮。完整的 `pressKey`、`typeText`、`click` 和 `drag` 保持操作内及时清理。 +长按时调用 `app.sendKeyEvent('w', 'down')`。在 DSH 中,显式键盘和鼠标按下会跨程序、跨回合保持,直到显式 up 按保存的目标释放。成功结束的程序通过 system reminder 报告剩余持有输入,包括目标和实际输入方式。程序失败、用户取消、断连、重置和销毁按实际派发顺序的反序统一释放所属键盘键和鼠标按钮。完整的 `pressKey`、`typeText`、`click` 和 `drag` 保持操作内及时清理。 Agent 销毁和插件卸载会取消并等待完整工具调用,包括图像接入检查和附件存储。已经开始的图像写入必须结束后,销毁才会返回;已取消的调用不会返回成功截图。 diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index 9ad89c09c8..b097b25b45 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -21,8 +21,8 @@ en: dea4de90fb3dd169 zh: 378ae657f5288807 /dsh-cua-native-helper/observation-and-input: - en: f242f4dbb1e46342 - zh: ff87afc313433636 + en: efbdd87d24ceb412 + zh: b9eb5d9d38dde450 /dsh-cua-native-helper/verification: en: 11172b21e8ebf972 zh: dac6787e1e75a88e diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index 60187ea512..d2b219acb6 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -112,7 +112,7 @@ Capture and pointer delivery read CG bounds before and after an exact-window AX `typeText` and `pressKey` target the selected process's current focused control, not an exact window. `pressKey` presses the listed modifiers followed by one key, then releases all pressed keys in reverse order, including on cancellation. Keyboard events go directly to the target PID and bypass the global HID queue. Key names are platform-defined; keypad names such as `KP_0` and `KP_Enter` preserve their physical key codes. Background pointer actions may change that keyboard focus. Text injection sends Unicode characters individually and does not use the clipboard. LF, CR and CRLF send one Return; tabs send Tab. Applications apply their normal editing behavior, including indentation and focus navigation. Each `typeText` down/up event is followed by the configured text interval; `pressKey` keeps its own press and release timing, and dispatch completion does not confirm that the receiving application consumed every event. Cancellation can interrupt text or a gesture after partial input; it cannot undo received events. Very long text can exceed the host's operation deadline. Validate observed application state before deciding how to continue. -The Host attaches `taskId` to explicit input. `HeldInputs` records connection, task, application, original process identity, key code or button, release event and actual input mode before dispatch. Repeated key downs keep one record. Explicit up uses the saved target and input mode, skipping PID-directed releases after process exit or identity reuse. `getHeldInputs` reports only the requesting connection and task records, without reading physical user key state. Successful programs use this snapshot for their reminder. `releaseHeldInputs` releases keyboard and mouse records together in reverse dispatch order after program failure, cancellation or disposal. Normal program and turn endings do not release input. Connection shutdown joins native work before fallback release. Balanced key chords, text, clicks and drags keep their operation-local cleanup. +The Host attaches `taskId` to explicit input. `HeldInputs` records connection, task, application, original process identity, key code or button, release event and actual input mode before dispatch. Repeated key downs keep one record. Explicit up uses the saved target and input mode, skipping PID-directed releases after process exit or identity reuse. `getHeldInputs` reports only the requesting connection and task records, without reading physical user key state. Successful programs use this snapshot for their reminder. `releaseHeldInputs` releases keyboard and mouse records together in reverse dispatch order after program failure, cancellation or disposal. Normal DSH program and turn endings do not release input. MCP program completion releases remaining input, and `releaseHeldInputs` returns the records whose up events were dispatched. Connection shutdown joins native work before fallback release. Balanced key chords, text, clicks and drags keep their operation-local cleanup. The selected helper application needs macOS Accessibility permission for AX state and input, and Screen Recording permission for screenshots. Capability preflight and permission errors do not grant permissions. Capture refuses a window that moves or resizes while the image is being read. Unassociated system panels and accessory-only applications are not selectable. diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index c0fca6b9a2..cf718a76f4 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -112,7 +112,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 `typeText` 和 `pressKey` 面向所选进程当前获得焦点的控件,不指定窗口。`pressKey` 向目标 PID 依次发送修饰键和一个主键的按下事件,再逆序释放。操作中途取消也会逆序释放已按下的键。键盘事件直接发给目标进程,绕过全局 HID 队列。按键名由平台定义;KP_0 和 KP_Enter 等数字键盘名称保留物理键码。后台鼠标操作可能改变键盘焦点。文本逐个 Unicode 字符输入,不使用剪贴板。LF、CR 和 CRLF 发送一次 Return,制表符发送 Tab。应用保留缩进和焦点导航等正常编辑行为。`typeText` 的每次按下和抬起后等待配置的文本事件间隔;`pressKey` 使用自己的按下与释放节奏,分派完成不证明应用已消费全部事件。取消可能中断部分文本或手势,无法撤销已接收事件。很长的文本可能超过 Host 操作期限。继续输入前应核实应用状态。 -宿主为显式输入附上 `taskId`。`HeldInputs` 在派发前记录连接、任务、应用、原进程身份、键码或按钮、释放事件和实际输入方式。重复按键只保留一条记录。显式 up 使用保存的目标和输入方式;进程退出或 PID 身份变化后跳过定向释放。`getHeldInputs` 只报告请求连接和任务的记录,不读取用户物理按键状态。成功结束的程序用该快照生成提醒。程序失败、取消或销毁时,`releaseHeldInputs` 按派发顺序的反序统一释放键盘和鼠标记录。正常程序结束和回合结束不释放输入。连接关闭先等待原生操作停止,再兜底释放。完整击键、文本、点击和拖动保留操作内清理。 +宿主为显式输入附上 `taskId`。`HeldInputs` 在派发前记录连接、任务、应用、原进程身份、键码或按钮、释放事件和实际输入方式。重复按键只保留一条记录。显式 up 使用保存的目标和输入方式;进程退出或 PID 身份变化后跳过定向释放。`getHeldInputs` 只报告请求连接和任务的记录,不读取用户物理按键状态。成功结束的程序用该快照生成提醒。程序失败、取消或销毁时,`releaseHeldInputs` 按派发顺序的反序统一释放键盘和鼠标记录。正常 DSH 程序结束和回合结束不释放输入。MCP 程序结束会释放剩余输入,`releaseHeldInputs` 返回已派发 up 的记录。连接关闭先等待原生操作停止,再兜底释放。完整击键、文本、点击和拖动保留操作内清理。 所选 helper 应用需要 macOS 辅助功能权限以读取 AX 和输入,需要屏幕录制权限以截图。能力预检和权限错误不授予权限。截图会拒绝在读取图片期间移动或缩放的窗口。无法确认归属的系统面板及仅后台辅助类型的应用不可选择。 diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/HeldInputs.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/HeldInputs.swift index 568d5b8af1..31d8a32e5c 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/HeldInputs.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/HeldInputs.swift @@ -168,6 +168,23 @@ final class HeldInputs: @unchecked Sendable { } } + private func record(_ press: Press) -> JSONValue { + var record: [String: JSONValue] = ["appHandle": .string(press.owner.app)] + switch press.mode { + case .keyboard(_, _, let name): + record["kind"] = .string("key") + record["key"] = .string(name) + record["mode"] = .string("application") + case .windowPointer(let button, let window), .systemPointer(let button, let window): + record["kind"] = .string("mouse") + record["button"] = .string(button == .left ? "left" : button == .right ? "right" : "middle") + record["windowId"] = .string(String(window)) + if case .systemPointer = press.mode { record["mode"] = .string("system") } + else { record["mode"] = .string("window") } + } + return .object(record) + } + /// Only the caller's registered input is disclosed; physical user input is never inferred. func held(connection: UUID, task: String) throws -> JSONValue { try lock.withLock { @@ -181,34 +198,25 @@ final class HeldInputs: @unchecked Sendable { } } return .array(pressed.filter { $0.owner.connection == connection && $0.owner.task == task }.map { press in - var record: [String: JSONValue] = ["appHandle": .string(press.owner.app)] - switch press.mode { - case .keyboard(_, _, let name): - record["kind"] = .string("key") - record["key"] = .string(name) - record["mode"] = .string("application") - case .windowPointer(let button, let window), .systemPointer(let button, let window): - record["kind"] = .string("mouse") - record["button"] = .string(button == .left ? "left" : button == .right ? "right" : "middle") - record["windowId"] = .string(String(window)) - if case .systemPointer = press.mode { record["mode"] = .string("system") } - else { record["mode"] = .string("window") } - } - return .object(record) + record(press) }) } } - func release(connection: UUID, task: String? = nil) throws { + @discardableResult + func release(connection: UUID, task: String? = nil) throws -> [JSONValue] { try lock.withLock { var failures: [String] = [] + var released: [JSONValue] = [] for index in pressed.indices.reversed() { - let owner = pressed[index].owner + let press = pressed[index] + let owner = press.owner guard owner.connection == connection, task == nil || owner.task == task else { continue } - do { _ = try release(at: index) } + do { if try release(at: index) { released.append(record(press)) } } catch { failures.append(String(describing: error)) } } if !failures.isEmpty { throw NativeFailure(code: "INPUT_CLEANUP_FAILED", message: failures.joined(separator: "; ")) } + return released } } diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift index 69e3772d8d..fa515072d0 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift @@ -169,8 +169,7 @@ import Darwin return try scheduler.heldInputs.held(connection: connectionID, task: params.string("taskId")) } if request.method == "releaseHeldInputs" { - try scheduler.heldInputs.release(connection: connectionID, task: params.string("taskId")) - return AXWorker.actionResult + return .array(try scheduler.heldInputs.release(connection: connectionID, task: params.string("taskId"))) } if request.method == "toggleMouse", try params.string("direction") == "up" { let dispatched = try scheduler.heldInputs.pointerUp(owner: .init(connection: connectionID, task: params.string("taskId"), diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index 3cba7a108d..3983459765 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -148,7 +148,7 @@ async function setup( model?: { provider: string; model: string }, ptc = false, overrides: Parameters[0] = {}, ) { native.connect.mockClear() - native.cleanup.mockReset().mockResolvedValue({ dispatched: true }) + native.cleanup.mockReset().mockResolvedValue([]) native.request.mockReset().mockResolvedValue([]) native.dispose.mockReset() native.instances.length = 0 diff --git a/packages/experimental/cua-mcp/README.i18n.yaml b/packages/experimental/cua-mcp/README.i18n.yaml index ff0e591dc7..71eff6076f 100644 --- a/packages/experimental/cua-mcp/README.i18n.yaml +++ b/packages/experimental/cua-mcp/README.i18n.yaml @@ -51,8 +51,8 @@ en: 0b0c63281111993b zh: 45716a56b5a5ad12 /deepseek-ai-dsh-cua-mcp/known-limitations-and-deferred-work: - en: 15a5daadd52dddd8 - zh: 5d4ddf2da4f31bba + en: 27085bbaf0a24801 + zh: 4fefe3ddbf60fea2 /deepseek-ai-dsh-cua-mcp/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 8ec3e73528ddb1a6 diff --git a/packages/experimental/cua-mcp/README.md b/packages/experimental/cua-mcp/README.md index 4f245554dd..9cbfd63d57 100644 --- a/packages/experimental/cua-mcp/README.md +++ b/packages/experimental/cua-mcp/README.md @@ -167,7 +167,7 @@ The tool catalog and instructions are stable for one installation. The reference -- Successful programs disclose remaining native-held keys and mouse buttons in a system reminder. Inputs persist across calls until explicit up. Program failure, cancellation, reset and connection closure release owned input; no client turn notification is required. +- Each program releases remaining native-held keys and mouse buttons before returning. A system reminder lists inputs automatically released after native acknowledgement. Input cannot remain held across MCP calls; no client pause notification is required. Program failure, cancellation, reset and connection closure also release owned input. - macOS and native Windows Hosts have a provider. Other Hosts, WSL included, list `cua_get_api_reference` and `cua_reset`, which both name the missing provider; a `cua_run_code` call fails as `unknown tool`. - On Windows the [provider's limits](../cua-windows/README.md#known-limitations-and-deferred-work) apply through MCP: it does not launch applications, grants no `Always allow`, and an npm installation needs `helperPath`. - Elicitation uses the 2025 MCP request model; a client that negotiates the 2026-07-28 revision receives an error for consent requests and should use `DSH_CUA_CONSENT=allow`. diff --git a/packages/experimental/cua-mcp/README.zh.md b/packages/experimental/cua-mcp/README.zh.md index 269482828b..b689ea92f2 100644 --- a/packages/experimental/cua-mcp/README.zh.md +++ b/packages/experimental/cua-mcp/README.zh.md @@ -167,7 +167,7 @@ patch 还以 `screenshotTarget: { longEdge: 2048, maxBytes: 2097152 }` 挂载该 -- 成功结束的程序通过 system reminder 报告原生仍按住的键盘键和鼠标按钮。输入跨调用保持,直到显式 up。程序失败、取消、重置和断连释放所属输入,不需要客户端发送回合通知。 +- 每个程序在返回前释放剩余的原生键盘键和鼠标按钮。原生确认后,通过 system reminder 列出自动释放的输入。输入不能跨 MCP 调用保持,不需要客户端提供暂停通知。程序失败、取消、重置和断连也会释放所属输入。 - macOS 与原生 Windows Host 有提供方。其他 Host(包括 WSL)列出 `cua_get_api_reference` 与 `cua_reset`,二者都指出缺少提供方;调用 `cua_run_code` 以 `unknown tool` 失败。 - 在 Windows 上,[提供方的限制](../cua-windows/README.zh.md#known-limitations-and-deferred-work)经 MCP 同样适用:它不启动应用,不提供 `Always allow` 授权,npm 安装需要配置 `helperPath`。 - Elicitation 使用 2025 版 MCP 请求模型;协商到 2026-07-28 修订版的客户端在授权请求时收到错误,应改用 `DSH_CUA_CONSENT=allow`。 diff --git a/packages/experimental/cua-mcp/src/server.ts b/packages/experimental/cua-mcp/src/server.ts index ee920fbd7c..0a5c880be6 100644 --- a/packages/experimental/cua-mcp/src/server.ts +++ b/packages/experimental/cua-mcp/src/server.ts @@ -96,7 +96,7 @@ const INSTRUCTIONS = 'DeepSeek Harness Computer Use: observe and operate desktop + 'written without it guess the API wrong. Then call cua_run_code with a TypeScript program that uses the global cua ' + 'object; program state persists across calls on this connection. A call may ask the user for application or pointer ' + 'consent before it proceeds. Call cua_reset to discard program state. ' - + 'Explicit key and mouse downs can remain held across programs. A system reminder lists remaining held inputs after successful programs. Release them explicitly when finished; program failure, cancellation, reset, and connection closure release owned input.' + + 'Remaining held keys and mouse buttons are released before each program returns. A system reminder lists inputs automatically released at program end. Explicit downs cannot stay held across MCP calls.' const NO_PROVIDER = 'Computer Use is not available on this Host: the cua-mcp profile has no active CUA provider. ' + 'Providers exist for macOS and native Windows; on those Hosts the server\'s stderr names why the provider did not start.' diff --git a/packages/experimental/cua-mcp/tests/composition.spec.ts b/packages/experimental/cua-mcp/tests/composition.spec.ts index 75f52f853b..80b14ea990 100644 --- a/packages/experimental/cua-mcp/tests/composition.spec.ts +++ b/packages/experimental/cua-mcp/tests/composition.spec.ts @@ -182,21 +182,35 @@ async function setup(options: SetupOptions = {}) { } describe('Computer Use MCP composition', () => { - it('retains input across MCP programs, reminds after success, and releases on error and reset', async () => { - const { native, run, client } = await setup() - expect((await run('var app = await cua.getApp("test.fixture"); var win = await app.getWindow("7"); await win.getAccessibilityTree(); await app.sendKeyEvent("w", "down")')).isError).not.toBe(true) - expect(native.held.map(press => press.key)).toEqual(['w']) - const continuing = await run('inspect("continue")') - expect(texts(continuing).join('')).toContain('Key "w", appHandle "fixture-app"') - const released = await run('await app.sendKeyEvent("w", "up")') - expect(texts(released).join('')).not.toContain('') + it('releases MCP input before returning and reports only confirmed automatic releases', async () => { + const { native, run } = await setup() + const held = await run('var app = await cua.getApp("test.fixture"); var win = await app.getWindow("7"); await win.getAccessibilityTree(); await app.sendKeyEvent("w", "down"); await win.toggleMouse("left", "down")') + expect(held.isError).not.toBe(true) expect(native.held).toEqual([]) - expect((await run('await win.toggleMouse("left", "down"); throw Error("failed program")')).isError).toBe(true) + expect(native.events).toEqual(['w:down', 'left:down', 'left:up', 'w:up']) + expect(texts(held).join('')).toContain('CUA inputs were automatically released at program end') + expect(texts(held).join('')).toContain('Mouse left') + expect(texts(held).join('')).toContain('Key "w"') + expect(texts(await run('inspect("next program")')).join('')).not.toContain('') + expect(texts(await run('await app.sendKeyEvent("d", "down"); await app.sendKeyEvent("d", "up")')).join('')).not.toContain('') + const failed = await run('await win.toggleMouse("left", "down"); throw Error("failed program")') + expect(failed.isError).toBe(true) expect(native.held).toEqual([]) - expect(texts(await run('await app.sendKeyEvent("d", "down")')).join('')).toContain('Key "d"') - await client.callTool({ name: 'cua_reset', arguments: {} }) - expect(native.held).toEqual([]) - expect((await run('var app = await cua.getApp("test.fixture"); var win = await app.getWindow("7"); await win.getAccessibilityTree(); await win.click("0")')).isError).not.toBe(true) + expect((await run('await win.click("0")')).isError).not.toBe(true) + }) + + it('waits for the native MCP cleanup reply and reports refusal without claiming release', async () => { + const { native, run } = await setup() + const release = native.controlNext('releaseHeldInputs') + let settled = false + const running = run('var app = await cua.getApp("test.fixture"); await app.sendKeyEvent("w", "down")').then((value) => { settled = true; return value }) + await release.entered + expect(settled).toBe(false) + release.reply({ code: 'INPUT_CLEANUP_FAILED', message: 'MCP release refused' }) + const result = await running + expect(result.isError).toBe(true) + expect(texts(result).join('')).toContain('MCP release refused') + expect(texts(result).join('')).not.toContain('inputs were automatically released') }) it('serves three tools, returns the API reference on request, and retains program state in the workspace', async () => { diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index 694b1f2509..fa1ed2ff58 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -21,8 +21,8 @@ en: 3f638a4a76023fc5 zh: 515aeb5de6ae5b33 /deepseek-ai-dsh-cua/understand-the-implementation: - en: 3b13747971967c17 - zh: 8ce73ad7615b5f05 + en: 78be79b4935a5a93 + zh: eb50cccc867fb1e9 /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 58ac832e6a..9378ea2548 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -91,7 +91,7 @@ Permission responses identify their platform and report only the state that plat
Shared execution and platform ownership -Providers implementing `CuaBackend.heldInputState` accept `taskId` on explicit input and system pointer movement, report their connection-owned records through `getHeldInputs({ taskId })`, and acknowledge `releaseHeldInputs({ taskId })`. Native records own the actual key/button, target, process identity and input mode. Successful `run_code` and `cua_run_code` programs query those records and append a system reminder only when input remains held; normal program and turn endings preserve input. The reminder travels through logged additional context in DSH and through the tool response in MCP. Program failure, cancellation, connection closure, environment reset and disposal stop owned dispatch and await reverse-order release. Cleanup failure disables further CUA operations for the task and reports the uncertainty. Provider unload retains these listeners until programs and native connections drain. Capability methods remain static. Windows leaves `heldInputState` unset until its helper implements reporting and cleanup; it receives no new commands. +Providers implementing `CuaBackend.heldInputState` accept `taskId` on explicit input and system pointer movement, report their connection-owned records through `getHeldInputs({ taskId })`, and acknowledge `releaseHeldInputs({ taskId })`. Native records own the actual key/button, target, process identity and input mode. Successful `run_code` and `cua_run_code` programs in DSH turns query those records and append a system reminder when input remains held; normal program and turn endings preserve input. Programs outside a DSH turn, including MCP, instead await release before returning and report only inputs the helper confirmed it released. Reminders travel through logged additional context in DSH and through the tool response in MCP. Program failure, cancellation, connection closure, environment reset and disposal stop owned dispatch and await reverse-order release. Cleanup failure disables further CUA operations for the task and reports the uncertainty. Provider unload retains these listeners until programs and native connections drain. Capability methods remain static. Windows leaves `heldInputState` unset until its helper implements reporting and cleanup; it receives no new commands. The [permission store](src/permission-store.ts) uses `storageDomain` with the configured backend. The default JSON backend writes `$DSH_HOME/storages/cua_permissions_.json`, where the digest identifies the canonical profile directory. Each authorization check opens fresh state under the profile's file lock and closes its domain afterward; native dispatch uses a separate application lock. Revocation waits for operations already admitted by another process; after it completes, every process rejects old handles. Files on different machines or PID namespaces must not share this lock. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index cf0e5ad797..d2f71e6987 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -91,7 +91,7 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边
共享执行与平台职责 -实现 `CuaBackend.heldInputState` 的提供方为显式输入和系统指针移动接受 `taskId`,通过 `getHeldInputs({ taskId })` 报告本连接的持有记录,并确认 `releaseHeldInputs({ taskId })`。原生记录负责保存实际按键或按钮、目标、进程身份和输入方式。成功结束的 `run_code` 和 `cua_run_code` 查询这些记录,仅在仍有输入按住时添加 system reminder;正常程序结束和回合结束均保持输入。DSH 通过已记录的额外上下文传递提醒,MCP 通过工具响应传递。程序失败、取消、断连、环境重置和销毁会停止所属输入派发,并等待反序释放。清理失败会禁用该任务后续 CUA 操作并报告结果不确定。提供方卸载前保留监听器,直到程序和原生连接排空。能力方法列表保持静态。Windows 在 helper 实现报告和清理前不设置 `heldInputState`,不会收到新命令。 +实现 `CuaBackend.heldInputState` 的提供方为显式输入和系统指针移动接受 `taskId`,通过 `getHeldInputs({ taskId })` 报告本连接的持有记录,并确认 `releaseHeldInputs({ taskId })`。原生记录负责保存实际按键或按钮、目标、进程身份和输入方式。DSH 回合中成功结束的 `run_code` 和 `cua_run_code` 查询这些记录,仍有输入按住时添加 system reminder;正常程序结束和回合结束均保持输入。没有 DSH 回合的程序,包括 MCP,在返回前等待释放,并只报告 helper 已确认释放的输入。DSH 通过已记录的额外上下文传递提醒,MCP 通过工具响应传递。程序失败、取消、断连、环境重置和销毁会停止所属输入派发,并等待反序释放。清理失败会禁用该任务后续 CUA 操作并报告结果不确定。提供方卸载前保留监听器,直到程序和原生连接排空。能力方法列表保持静态。Windows 在 helper 实现报告和清理前不设置 `heldInputState`,不会收到新命令。 [授权存储](src/permission-store.ts)复用 `storageDomain` 和配置的后端。默认 JSON 后端写入 `$DSH_HOME/storages/cua_permissions_.json`,摘要对应 profile 的真实目录。每次授权检查在 profile 文件锁内打开并读取最新状态,随后关闭存储域;原生操作使用单独的应用锁。撤销会等待其他进程已获准执行的操作结束;撤销完成后,各进程都拒绝旧句柄。不同电脑或 PID 命名空间不能共享这把锁。 diff --git a/packages/experimental/cua/src/guidance.ts b/packages/experimental/cua/src/guidance.ts index a76bd4f5fc..7a1aa2511f 100644 --- a/packages/experimental/cua/src/guidance.ts +++ b/packages/experimental/cua/src/guidance.ts @@ -58,7 +58,7 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. -Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any keys and mouse buttons still held, with their targets and input modes. No reminder is added when none remain. Program failure, user stop, connection closure, and disposal release owned inputs together in reverse dispatch order. pressKey, typeText, click, and complete drag release their own inputs within the operation. +In DSH, explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. MCP and other programs outside a DSH turn release remaining input before returning and report which inputs were automatically released. No reminder is added when there is nothing to report. Program failure, user stop, connection closure, and disposal release owned inputs together in reverse dispatch order. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/packages/experimental/cua/src/held-inputs.ts b/packages/experimental/cua/src/held-inputs.ts index d44b2aa94e..0564a8d391 100644 --- a/packages/experimental/cua/src/held-inputs.ts +++ b/packages/experimental/cua/src/held-inputs.ts @@ -12,18 +12,29 @@ const heldInputs = z.array(z.discriminatedUnion('kind', [ z.object({ ...target, kind: z.literal('mouse'), button: z.enum(['left', 'right', 'middle']), windowId: z.string() }), ])) +function renderInputs(inputs: z.infer, state: 'held' | 'released'): string { + const rows = inputs.map(input => input.kind === 'key' + ? `- Key ${JSON.stringify(input.key)}, appHandle ${JSON.stringify(input.appHandle)} (${input.mode} input).` + : `- Mouse ${input.button}, appHandle ${JSON.stringify(input.appHandle)}, windowId ${JSON.stringify(input.windowId)} (${input.mode} input).`) + return ['', state === 'held' ? 'CUA inputs are still held:' : 'CUA inputs were automatically released at program end:', ...rows, + state === 'held' + ? "They remain pressed across programs and turns. Release them explicitly with sendKeyEvent(key, 'up') or toggleMouse(button, 'up') on the same target when no longer needed." + : 'These inputs are no longer held. In this environment, keep any required hold sequence within one program.', + ''].join('\n') +} + class InputOwner { readonly controller = new AbortController() private client: NativeClient | undefined private removeCleanup: (() => void) | undefined - closing: Promise | undefined + closing: Promise> | undefined constructor(readonly agent: Agent, private readonly failed: (error: unknown) => void) {} track(client: NativeClient): void { this.controller.signal.throwIfAborted() if (this.client) return - this.removeCleanup = client.registerCleanup(canRequest => this.close(canRequest)) + this.removeCleanup = client.registerCleanup(async (canRequest) => { await this.close(canRequest) }) this.client = client } @@ -36,21 +47,21 @@ class InputOwner { this.client = undefined return } - const rows = inputs.map(input => input.kind === 'key' - ? `- Key ${JSON.stringify(input.key)}, appHandle ${JSON.stringify(input.appHandle)} (${input.mode} input).` - : `- Mouse ${input.button}, appHandle ${JSON.stringify(input.appHandle)}, windowId ${JSON.stringify(input.windowId)} (${input.mode} input).`) - return ['', 'CUA inputs are still held:', ...rows, - "They remain pressed across programs and turns. Release them explicitly with sendKeyEvent(key, 'up') or toggleMouse(button, 'up') on the same target when no longer needed.", - ''].join('\n') + return renderInputs(inputs, 'held') } - close(canRequest = true): Promise { + async releaseReminder(): Promise { + const released = await this.close() + return released.length > 0 ? renderInputs(released, 'released') : undefined + } + + close(canRequest = true): Promise> { this.controller.abort() return this.closing ??= Promise.resolve().then(async () => { try { - if (!this.client) return + if (!this.client) return [] if (!canRequest) throw new NativeError('INPUT_CLEANUP_UNCONFIRMED', 'Native connection closed before held-input cleanup was confirmed. Inspect the desktop manually before starting a new task') - await this.client.requestCleanup('releaseHeldInputs', { taskId: this.agent.id }) + return heldInputs.parse(await this.client.requestCleanup('releaseHeldInputs', { taskId: this.agent.id })) } catch (error) { this.failed(error) throw error @@ -127,10 +138,12 @@ export class CuaHeldInputs { catch (error) { throw new NativeError('INPUT_CLEANUP_UNCONFIRMED', `${result.isError ? result.error.message : 'Program cancelled'}. Held-input cleanup failed: ${String(error)}`, { cause: error }) } } else if (execution.parent === undefined) { - const text = await this.owners.get(agent)?.reminder() + const owner = this.owners.get(agent) + const inTurn = ctx.agents.turnBoundaryOf(agent.session).openTurnStartSeq !== null + const text = inTurn ? await owner?.reminder() : await owner?.releaseReminder() if (text) return { ...result, additionalContexts: [...result.additionalContexts ?? [], createUserMessage({ content: [{ type: 'text', text }], - source: { kind: 'cua-held-inputs', form: 'notice', summary: 'CUA inputs remain held' } }), + source: { kind: 'cua-held-inputs', form: 'notice', summary: inTurn ? 'CUA inputs remain held' : 'CUA inputs released' } }), ] } } return result diff --git a/packages/experimental/cua/src/types.ts b/packages/experimental/cua/src/types.ts index 283da80c2e..bcf78c025c 100644 --- a/packages/experimental/cua/src/types.ts +++ b/packages/experimental/cua/src/types.ts @@ -182,7 +182,8 @@ export interface CuaSurface { pressKey(key: string, modifiers?: string[]): Promise /** * Send one key-down or key-up event at the current input focus. - * Explicit downs persist across programs and turns. Successful programs disclose remaining holds in a system reminder. + * In DSH turns, explicit downs persist across programs and turns; successful programs remind about remaining holds. + * Programs outside a DSH turn, including MCP, release remaining input before returning and report the release. * Program failure, cancellation, connection closure and disposal release owned input. Windows support is pending. * Rejects when the provider does not support keyboard input at this scope. * @param key - Platform-defined key name; modifier keys may themselves be targets. diff --git a/snapshots/session/cua-run-code/native-channel.mjs b/snapshots/session/cua-run-code/native-channel.mjs index a14a708e37..2b6bc41a85 100644 --- a/snapshots/session/cua-run-code/native-channel.mjs +++ b/snapshots/session/cua-run-code/native-channel.mjs @@ -31,6 +31,7 @@ export function createNativeFixture(selectorPid) { ? { kind: 'key', key: press.key, appHandle: press.appHandle, mode: 'application' } : { kind: 'mouse', button: press.key, appHandle: press.appHandle, windowId: press.windowId, mode: press.mode }) if (method === 'releaseHeldInputs') { + const released = dispatch('getHeldInputs', params).reverse() for (let index = held.length - 1; index >= 0; index--) { const press = held[index] if (press.connection === connection && press.taskId === params.taskId) { @@ -38,7 +39,7 @@ export function createNativeFixture(selectorPid) { held.splice(index, 1) } } - return { dispatched: true } + return released } if (method === 'getCapabilities') return { sessionLocked: false, permissions: { accessibility: true, screenRecording: true } } if (method === 'listApps') return [{ id: 'test.fixture', name: 'Fixture', isRunning: true, pid: selectorPid ?? 4 }] From 81a6eca92b3636f844216854dde1b1d4b0f59232 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 19 Nov 2026 10:52:04 +0800 Subject: [PATCH 34/73] Report release receipts once and keep recovery programs usable --- packages/experimental/cua-macos/tests/guidance.spec.ts | 2 +- packages/experimental/cua/src/held-inputs.ts | 3 ++- packages/experimental/cua/tests/run-code-composition.spec.ts | 4 ++-- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/packages/experimental/cua-macos/tests/guidance.spec.ts b/packages/experimental/cua-macos/tests/guidance.spec.ts index bc7dac7edc..34534f3a9e 100644 --- a/packages/experimental/cua-macos/tests/guidance.spec.ts +++ b/packages/experimental/cua-macos/tests/guidance.spec.ts @@ -56,7 +56,7 @@ it('states the macOS accessibility, keyboard, and mouse levels', () => { const pressKey = GUIDANCE.split('\n').find(line => line.startsWith('- pressKey(')) expect(GUIDANCE).toContain("sendKeyEvent(key: string, direction: 'down' | 'up')") expect(COMMON_GUIDANCE).toContain('sendKeyEvent and toggleMouse remain held across programs and turns') - expect(COMMON_GUIDANCE).toContain('a system reminder lists any keys and mouse buttons still held') + expect(COMMON_GUIDANCE).toContain('a system reminder lists any remaining keys and mouse buttons') const sharedKeyEvent = COMMON_GUIDANCE.split('\n').find(line => line.startsWith('- sendKeyEvent(')) expect(sharedKeyEvent).toBeDefined() expect(GUIDANCE.split('\n').find(line => line.startsWith('- sendKeyEvent('))).toContain(sharedKeyEvent) diff --git a/packages/experimental/cua/src/held-inputs.ts b/packages/experimental/cua/src/held-inputs.ts index 0564a8d391..9467c12789 100644 --- a/packages/experimental/cua/src/held-inputs.ts +++ b/packages/experimental/cua/src/held-inputs.ts @@ -39,7 +39,7 @@ class InputOwner { } async reminder(): Promise { - if (!this.client) return + if (this.closing || !this.client) return const inputs = heldInputs.parse(await this.client.request('getHeldInputs', { taskId: this.agent.id }, this.controller.signal)) if (inputs.length === 0) { this.removeCleanup?.() @@ -51,6 +51,7 @@ class InputOwner { } async releaseReminder(): Promise { + if (this.closing) return const released = await this.close() return released.length > 0 ? renderInputs(released, 'released') : undefined } diff --git a/packages/experimental/cua/tests/run-code-composition.spec.ts b/packages/experimental/cua/tests/run-code-composition.spec.ts index 200bf77f18..4b5d700286 100644 --- a/packages/experimental/cua/tests/run-code-composition.spec.ts +++ b/packages/experimental/cua/tests/run-code-composition.spec.ts @@ -382,7 +382,7 @@ it('reports native held input after programs, keeps it across turns, and stops r it('releases keyboard and mouse in mixed reverse order on program failure', async () => { const f = await setup([holdProgram, - 'await app.sendKeyEvent("shift", "down"); var win = await app.getWindow("7"); await win.toggleMouse("left", "down"); await app.sendKeyEvent("d", "down"); throw Error("program failed")'], + 'await app.sendKeyEvent("shift", "down"); var win = await app.getWindow("7"); await win.toggleMouse("left", "down"); await app.sendKeyEvent("d", "down"); throw Error("program failed")', 'inspect("recovered")'], 'macos', undefined, true, true) await f.run() expect(f.native.events).toEqual(['w:down', 'shift:down', 'left:down', 'd:down', 'd:up', 'left:up', 'shift:up', 'w:up']) @@ -390,7 +390,7 @@ it('releases keyboard and mouse in mixed reverse order on program failure', asyn expect(reminders(f.agent)).toHaveLength(1) expect(f.native.calls.filter(call => call.method === 'releaseHeldInputs')).toHaveLength(1) const results = f.agent.session.deriveMessages().filter(message => message.role === 'tool') - expect(results.map(result => result.isError)).toEqual([false, true]) + expect(results.map(result => result.isError)).toEqual([false, true, false]) }) it('reminders name the actual mouse target and omit explicitly released inputs', async () => { From 6a143953f0897ae80eff06f67b229bdeb21109f7 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 19 Nov 2026 10:59:26 +0800 Subject: [PATCH 35/73] Record held-input reminders and cover MCP release receipts through the shipped profile --- .../profiles/cua-mcp/cua-mcp.expected.e2e.ts | 16 ++++++++++++++++ .../profiles/cua-mcp/expected/instructions.txt | 2 +- .../tests/profiles/cua-mcp/expected/reference.md | 2 +- packages/experimental/cua-macos/README.md | 4 ++-- packages/experimental/cua-macos/README.zh.md | 4 ++-- .../cua-macos/native/README.i18n.yaml | 4 ++-- packages/experimental/cua-macos/native/README.md | 2 +- .../experimental/cua-macos/native/README.zh.md | 2 +- .../sdk/cua-run-code/system-prompt.expected.md | 2 +- .../session/cua-native/system-prompt.expected.md | 2 +- .../session/cua-ptc/system-prompt.expected.md | 2 +- .../session/cua-run-code-ptc/session.v4.jsonl | 11 +++++++---- .../cua-run-code-ptc/system-prompt.expected.md | 2 +- snapshots/session/cua-run-code/session.v4.jsonl | 14 ++++++++++---- .../cua-run-code/system-prompt.expected.md | 2 +- .../system-prompt.expected.md | 2 +- 16 files changed, 49 insertions(+), 24 deletions(-) diff --git a/apps/cli/tests/profiles/cua-mcp/cua-mcp.expected.e2e.ts b/apps/cli/tests/profiles/cua-mcp/cua-mcp.expected.e2e.ts index c1b88715c3..d66b065d9f 100644 --- a/apps/cli/tests/profiles/cua-mcp/cua-mcp.expected.e2e.ts +++ b/apps/cli/tests/profiles/cua-mcp/cua-mcp.expected.e2e.ts @@ -91,6 +91,22 @@ describe.skipIf(!existsSync(bin))('cua-mcp profile', { retry: 0 }, () => { expect(second.content).toHaveLength(1) expect(JSON.parse(textOf(second.content[0]))).toEqual({ visits: 2, sameWindow: true, pid: state.pid }) + const held = await probe.request('tools/call', { name: 'cua_run_code', arguments: { + code: 'await app.sendKeyEvent("shift", "down"); await win.toggleMouse("left", "down"); await app.sendKeyEvent("w", "down"); inspect("Input sequence finished.")', + description: 'Hold mixed input within one MCP program', + } }) as CallResult + expect(held.isError).toBeUndefined() + await expect(`${JSON.stringify(held, null, 2)}\n`).toMatchFileSnapshot('./expected/input-release.json') + const up = await probe.request('tools/call', { name: 'cua_run_code', arguments: { + code: 'await app.sendKeyEvent("w", "up")', description: 'Confirm W was released', + } }) as CallResult + expect(up.isError).toBe(true) + expect(up.content.some(block => block.type === 'text' && block.text.includes('not held'))).toBe(true) + const afterRelease = await probe.request('tools/call', { name: 'cua_run_code', arguments: { + code: 'inspect("After release")', description: 'Continue without held input', + } }) as CallResult + expect(afterRelease.content).toEqual([{ type: 'text', text: 'After release\n' }]) + const reset = await probe.request('tools/call', { name: 'cua_reset', arguments: {} }) as CallResult expect(reset.isError).toBeUndefined() expect(textOf(reset.content[0])).toContain('Program environment cleared') diff --git a/apps/cli/tests/profiles/cua-mcp/expected/instructions.txt b/apps/cli/tests/profiles/cua-mcp/expected/instructions.txt index 3414fe6ee5..fe2768f3dc 100644 --- a/apps/cli/tests/profiles/cua-mcp/expected/instructions.txt +++ b/apps/cli/tests/profiles/cua-mcp/expected/instructions.txt @@ -1 +1 @@ -DeepSeek Harness Computer Use: observe and operate desktop applications on this machine. Start every conversation by calling cua_get_api_reference: it returns the complete cua API reference, and programs written without it guess the API wrong. Then call cua_run_code with a TypeScript program that uses the global cua object; program state persists across calls on this connection. A call may ask the user for application or pointer consent before it proceeds. Call cua_reset to discard program state. On macOS, MCP programs cannot hold keys or mouse buttons with explicit down events. Use pressKey, click, or drag. +DeepSeek Harness Computer Use: observe and operate desktop applications on this machine. Start every conversation by calling cua_get_api_reference: it returns the complete cua API reference, and programs written without it guess the API wrong. Then call cua_run_code with a TypeScript program that uses the global cua object; program state persists across calls on this connection. A call may ask the user for application or pointer consent before it proceeds. Call cua_reset to discard program state. Remaining held keys and mouse buttons are released before each program returns. A system reminder lists inputs automatically released at program end. Explicit downs cannot stay held across MCP calls. diff --git a/apps/cli/tests/profiles/cua-mcp/expected/reference.md b/apps/cli/tests/profiles/cua-mcp/expected/reference.md index b628aa9f9d..167cfd894c 100644 --- a/apps/cli/tests/profiles/cua-mcp/expected/reference.md +++ b/apps/cli/tests/profiles/cua-mcp/expected/reference.md @@ -53,7 +53,7 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. -Explicit downs from sendKeyEvent and toggleMouse share one turn-wide hold scope across run_code and cua_run_code calls. An explicit up releases input immediately at its original recipient. Program return or failure does not end a continuing turn. After turn/end, cleanup releases remaining keys and buttons together in reverse dispatch order, including on failure or user stop. pressKey, typeText, click, and complete drag release their own inputs within the operation. +In DSH, explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. MCP and other programs outside a DSH turn release remaining input before returning and report which inputs were automatically released. No reminder is added when there is nothing to report. Program failure, user stop, connection closure, and disposal release owned inputs together in reverse dispatch order. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index e1de0f17f1..0fae8dc4ea 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -236,7 +236,7 @@ Use an explicit window for pointer input. Before coordinate input, including rel - 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. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemPointer?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control. An explicit system drag shares the session decision with mouseMove and holds the chosen button along the path in the unobscured foreground window. -A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current AX observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. FOREGROUND_REQUIRED means explain the need, then explicitly activate the target and observe again; activation is never automatic. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry. +A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current accessibility observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. FOREGROUND_REQUIRED means explain the need, then explicitly activate the target and observe again; activation is never automatic. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry. ## Simulated keyboard Available at app or window level depending on the platform. @@ -245,7 +245,7 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. -Explicit downs from sendKeyEvent and toggleMouse share one turn-wide hold scope across run_code and cua_run_code calls. An explicit up releases input immediately at its original recipient. Program return or failure does not end a continuing turn. After turn/end, cleanup releases remaining keys and buttons together in reverse dispatch order, including on failure or user stop. pressKey, typeText, click, and complete drag release their own inputs within the operation. +In DSH, explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. MCP and other programs outside a DSH turn release remaining input before returning and report which inputs were automatically released. No reminder is added when there is nothing to report. Program failure, user stop, connection closure, and disposal release owned inputs together in reverse dispatch order. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 86584c45ef..f2c6288389 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -236,7 +236,7 @@ Use an explicit window for pointer input. Before coordinate input, including rel - 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. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemPointer?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control. An explicit system drag shares the session decision with mouseMove and holds the chosen button along the path in the unobscured foreground window. -A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current AX observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. FOREGROUND_REQUIRED means explain the need, then explicitly activate the target and observe again; activation is never automatic. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry. +A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current accessibility observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. FOREGROUND_REQUIRED means explain the need, then explicitly activate the target and observe again; activation is never automatic. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry. ## Simulated keyboard Available at app or window level depending on the platform. @@ -245,7 +245,7 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. -Explicit downs from sendKeyEvent and toggleMouse share one turn-wide hold scope across run_code and cua_run_code calls. An explicit up releases input immediately at its original recipient. Program return or failure does not end a continuing turn. After turn/end, cleanup releases remaining keys and buttons together in reverse dispatch order, including on failure or user stop. pressKey, typeText, click, and complete drag release their own inputs within the operation. +In DSH, explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. MCP and other programs outside a DSH turn release remaining input before returning and report which inputs were automatically released. No reminder is added when there is nothing to report. Program failure, user stop, connection closure, and disposal release owned inputs together in reverse dispatch order. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index b097b25b45..cb05281b15 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -21,8 +21,8 @@ en: dea4de90fb3dd169 zh: 378ae657f5288807 /dsh-cua-native-helper/observation-and-input: - en: efbdd87d24ceb412 - zh: b9eb5d9d38dde450 + en: 3ca2ccd0ee8d549c + zh: 1ada0c7b7c38a1a8 /dsh-cua-native-helper/verification: en: 11172b21e8ebf972 zh: dac6787e1e75a88e diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index d2b219acb6..e9592a4ad8 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -102,7 +102,7 @@ Input target discovery uses the same range recovery as observation. All recovery 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. -Window-directed `toggleMouse` posts one press or release to the selected process at the current pointer. A press must hit the foreground window; a release may be outside. Explicit `useSystemPointer` posts through the HID event tap. The connection that pressed the button can move it with system `mouseMove` on that window or release it through the same window handle. The Host requests release at turn end; disconnect also releases the button. +Window-directed `toggleMouse` posts one press or release to the selected process at the current pointer. A press must hit the foreground window; a release may be outside. Explicit `useSystemPointer` posts through the HID event tap. The connection that pressed the button can move it with system `mouseMove` on that window or release it through the same window handle. 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 default drag validate window ownership and bounds, then post to the target PID and window. 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. An explicit `useSystemPointer: true` drag posts through the HID event tap, checks the foreground window at the start and each movement, and supplies one gesture event number and per-segment deltas. Cancellation releases at the last posted point. diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index cf718a76f4..af7fda19a7 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -102,7 +102,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 窗口隐藏本身不会使 AX 快照失效。刷新清单时,只有同一窗口 ID 仍存在且观察到的尺寸未变,才能继续使用此前截图的像素坐标。观察到尺寸变化后需要重新截图;窗口销毁后不能继续操作。清单中省略窗口不会阻止按已知 ID 发起输入。窗口归属、尺寸和输入检查仍然生效,成功分派不代表应用已接收。 -窗口模式的 `toggleMouse` 向目标进程发送一次按下或松开。按下时使用当前指针位置,松开时允许指针移出。显式开启 `useSystemPointer` 后,helper 通过 HID 发送系统按键事件。只有按下该键的连接能通过原窗口显式松开。在同一窗口请求系统指针移动会发送该按键的拖动事件。正常程序结束和回合结束保持按钮;失败、取消和断连释放它。 +窗口模式的 `toggleMouse` 向目标进程发送一次按下或松开。按下时使用当前指针位置,松开时允许指针移出。显式开启 `useSystemPointer` 后,helper 通过 HID 发送系统按键事件。只有按下该键的连接能通过原窗口显式松开。在同一窗口请求系统指针移动会发送该按键的拖动事件。 点击在元素中心或给定坐标发送鼠标按下和抬起事件。执行默认 AX 动作用 `invoke`,执行指定动作用 `performAction`。点击、滚动和默认拖动核实窗口归属和边界后,向目标进程和窗口投递事件。事件优先使用 SkyLight,不可用时使用公开的 PID 定向 API;已发送的事件不通过另一 API 重发。坐标是整个窗口左上角起算的 macOS point,包含标题栏。`deltaLinesY` 为正时显示上方内容,为负时显示下方内容;`deltaLinesX` 为正时显示左侧内容,为负时显示右侧内容。每个轴接受 -10 到 10 的整数,至少一个轴非零。helper 直接发送按行计量的滚轮事件。点击和拖动支持左、右、中键及 command/control/option/shift/fn 修饰键,只有左键支持双击。拖动在一个窗口中完成一次按下、移动、抬起,调用方显式提供 durationMs(1..5000)和 steps(1..240)。移动延迟按小数精度分配到各段,按下和抬起的固定等待及调度延迟另计。显式传入 `useSystemPointer: true` 的拖动通过 HID 投递,起点及每段移动都要命中目标前台窗口。手势共用事件号,每段携带位移。取消时在最后投递的位置松开鼠标键。 diff --git a/snapshots/sdk/cua-run-code/system-prompt.expected.md b/snapshots/sdk/cua-run-code/system-prompt.expected.md index 5cf9f50161..969740e8a0 100644 --- a/snapshots/sdk/cua-run-code/system-prompt.expected.md +++ b/snapshots/sdk/cua-run-code/system-prompt.expected.md @@ -87,7 +87,7 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. -Explicit downs from sendKeyEvent and toggleMouse share one turn-wide hold scope across run_code and cua_run_code calls. An explicit up releases input immediately at its original recipient. Program return or failure does not end a continuing turn. After turn/end, cleanup releases remaining keys and buttons together in reverse dispatch order, including on failure or user stop. pressKey, typeText, click, and complete drag release their own inputs within the operation. +In DSH, explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. MCP and other programs outside a DSH turn release remaining input before returning and report which inputs were automatically released. No reminder is added when there is nothing to report. Program failure, user stop, connection closure, and disposal release owned inputs together in reverse dispatch order. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/snapshots/session/cua-native/system-prompt.expected.md b/snapshots/session/cua-native/system-prompt.expected.md index bf28472413..f88245aff2 100644 --- a/snapshots/session/cua-native/system-prompt.expected.md +++ b/snapshots/session/cua-native/system-prompt.expected.md @@ -90,7 +90,7 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. -Explicit downs from sendKeyEvent and toggleMouse share one turn-wide hold scope across run_code and cua_run_code calls. An explicit up releases input immediately at its original recipient. Program return or failure does not end a continuing turn. After turn/end, cleanup releases remaining keys and buttons together in reverse dispatch order, including on failure or user stop. pressKey, typeText, click, and complete drag release their own inputs within the operation. +In DSH, explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. MCP and other programs outside a DSH turn release remaining input before returning and report which inputs were automatically released. No reminder is added when there is nothing to report. Program failure, user stop, connection closure, and disposal release owned inputs together in reverse dispatch order. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index 1fa73370aa..10e7e79a27 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -92,7 +92,7 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. -Explicit downs from sendKeyEvent and toggleMouse share one turn-wide hold scope across run_code and cua_run_code calls. An explicit up releases input immediately at its original recipient. Program return or failure does not end a continuing turn. After turn/end, cleanup releases remaining keys and buttons together in reverse dispatch order, including on failure or user stop. pressKey, typeText, click, and complete drag release their own inputs within the operation. +In DSH, explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. MCP and other programs outside a DSH turn release remaining input before returning and report which inputs were automatically released. No reminder is added when there is nothing to report. Program failure, user stop, connection closure, and disposal release owned inputs together in reverse dispatch order. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/snapshots/session/cua-run-code-ptc/session.v4.jsonl b/snapshots/session/cua-run-code-ptc/session.v4.jsonl index c56c1f134b..76fc2f6aba 100644 --- a/snapshots/session/cua-run-code-ptc/session.v4.jsonl +++ b/snapshots/session/cua-run-code-ptc/session.v4.jsonl @@ -12,7 +12,7 @@ {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"From run_code, call tools.cua_run_code t","messageSeqs":[8],"source":{"kind":"fallback"}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua_first","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"globalThis.visits = 1; var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"down\\\\\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))\\\", description: \\\"Select the fixture window and click Increment\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Select the fixture window and click Increment\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"stream":[{"type":"chunk","time":1794990891271,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794990891272,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_first","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"globalThis.visits = 1; var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"down\\\\\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))\\\", description: \\\"Select the fixture window and click Increment\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Select the fixture window and click Increment\"}"}}},{"type":"chunk","time":1794990891272,"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_first","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"globalThis.visits = 1; var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"down\\\\\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))\\\", description: \\\"Select the fixture window and click Increment\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Select the fixture window and click Increment\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"stream":[{"type":"chunk","time":1795057088827,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1795057088827,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_first","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"globalThis.visits = 1; var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"down\\\\\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))\\\", description: \\\"Select the fixture window and click Increment\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Select the fixture window and click Increment\"}"}}},{"type":"chunk","time":1795057088827,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua_first","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"globalThis.visits = 1; var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"down\\\\\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))\\\", description: \\\"Select the fixture window and click Increment\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Select the fixture window and click Increment\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua_run_code","arguments":{"code":"globalThis.visits = 1; var app = await cua.getApp(\"test.fixture\"); await app.sendKeyEvent(\"w\", \"down\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\"0\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))","description":"Select the fixture window and click Increment"}}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}}}} @@ -27,9 +27,12 @@ {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:5","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-1","elementId":"0"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua_run_code","arguments":{"code":"globalThis.visits = 1; var app = await cua.getApp(\"test.fixture\"); await app.sendKeyEvent(\"w\", \"down\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\"0\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))","description":"Select the fixture window and click Increment"},"isError":false,"content":[{"type":"text","text":"{\"visits\":1,\"bindings\":[\"cua\"],\"app\":\"fixture-app\",\"window\":\"7\"}\n"}]}} {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"cua_first"},"toolCallId":"cua_first","content":[{"type":"text","text":"{\"cuaTools\":[\"cua_run_code\"],\"logs\":[\"{\\\"visits\\\":1,\\\"bindings\\\":[\\\"cua\\\"],\\\"app\\\":\\\"fixture-app\\\",\\\"window\\\":\\\"7\\\"}\\n\"]}\n"}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"\nCUA inputs are still held:\n- Key \"w\", appHandle \"fixture-app\" (application input).\nThey remain pressed across programs and turns. Release them explicitly with sendKeyEvent(key, 'up') or toggleMouse(button, 'up') on the same target when no longer needed.\n"}],"source":{"kind":"cua-held-inputs","form":"notice","summary":"CUA inputs remain held"},"role":"user","id":"{{message:6}}"}]}} {"type":"step/end","data":{"turn":1,"step":1}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"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_reuse","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"up\\\\\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\\\", description: \\\"Reuse the retained application and window\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Reuse the retained application and window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"stream":[{"type":"chunk","time":1794990891775,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794990891775,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_reuse","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"up\\\\\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\\\", description: \\\"Reuse the retained application and window\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Reuse the retained application and window\"}"}}},{"type":"chunk","time":1794990891775,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nCUA inputs are still held:\n- Key \"w\", appHandle \"fixture-app\" (application input).\nThey remain pressed across programs and turns. Release them explicitly with sendKeyEvent(key, 'up') or toggleMouse(button, 'up') on the same target when no longer needed.\n"}],"source":{"kind":"cua-held-inputs","form":"notice","summary":"CUA inputs remain held"},"role":"user","id":"{{message:6}}"},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua_reuse","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"up\\\\\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\\\", description: \\\"Reuse the retained application and window\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Reuse the retained application and window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:7}}"},"stream":[{"type":"chunk","time":1795057089246,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1795057089246,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_reuse","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"up\\\\\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\\\", description: \\\"Reuse the retained application and window\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Reuse the retained application and window\"}"}}},{"type":"chunk","time":1795057089246,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"cua_reuse","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"up\\\\\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\\\", description: \\\"Reuse the retained application and window\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Reuse the retained application and window\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:1","name":"cua_run_code","arguments":{"code":"await app.sendKeyEvent(\"w\", \"up\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\"0\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))","description":"Reuse the retained application and window"}}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse:ptc:1","subCallId":"cua_reuse:ptc:1:ptc:1","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"w","direction":"up"}}}} @@ -41,9 +44,9 @@ {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse:ptc:1","subCallId":"cua_reuse:ptc:1:ptc:4","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse:ptc:1","subCallId":"cua_reuse:ptc:1:ptc:4","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"snapshotId\":\"fixture-snapshot-3\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 2\\\"\",\"windows\":[{\"windowId\":\"7\",\"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_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:1","name":"cua_run_code","arguments":{"code":"await app.sendKeyEvent(\"w\", \"up\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\"0\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))","description":"Reuse the retained application and window"},"isError":false,"content":[{"type":"text","text":"{\"visits\":2,\"app\":\"fixture-app\",\"window\":\"7\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 2\\\"\",\"bindings\":[\"cua\"]}\n"}]}} -{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"cua_reuse"},"toolCallId":"cua_reuse","content":[{"type":"text","text":"{\"cuaTools\":[\"cua_run_code\"],\"logs\":[\"{\\\"visits\\\":2,\\\"app\\\":\\\"fixture-app\\\",\\\"window\\\":\\\"7\\\",\\\"tree\\\":\\\"- [0] AXButton \\\\\\\"Increment\\\\\\\"\\\\n- AXStaticText \\\\\\\"Count: 2\\\\\\\"\\\",\\\"bindings\\\":[\\\"cua\\\"]}\\n\"]}\n"}],"isError":false,"id":"{{message:7}}"}},"sourceEventSeqs":[31],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"cua_reuse"},"toolCallId":"cua_reuse","content":[{"type":"text","text":"{\"cuaTools\":[\"cua_run_code\"],\"logs\":[\"{\\\"visits\\\":2,\\\"app\\\":\\\"fixture-app\\\",\\\"window\\\":\\\"7\\\",\\\"tree\\\":\\\"- [0] AXButton \\\\\\\"Increment\\\\\\\"\\\\n- AXStaticText \\\\\\\"Count: 2\\\\\\\"\\\",\\\"bindings\\\":[\\\"cua\\\"]}\\n\"]}\n"}],"isError":false,"id":"{{message:8}}"}},"sourceEventSeqs":[34],"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":"text","text":"Both programs ran through tools.cua_run_code inside run_code. The retained window reports Count: 2, the counter persisted across calls, run_code exposes cua_run_code as its only CUA tool, and each nested program can call only tools.cua."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:8}}"},"stream":[{"type":"chunk","time":1794990892006,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1794990892006,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Both programs ran through tools.cua_run_code inside run_code. The retained window reports Count: 2, the counter persisted across calls, run_code exposes cua_run_code as its only CUA tool, and each nested program can call only tools.cua."}}},{"type":"chunk","time":1794990892006,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"text","text":"Both programs ran through tools.cua_run_code inside run_code. The retained window reports Count: 2, the counter persisted across calls, run_code exposes cua_run_code as its only CUA tool, and each nested program can call only tools.cua."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:9}}"},"stream":[{"type":"chunk","time":1795057089410,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1795057089410,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Both programs ran through tools.cua_run_code inside run_code. The retained window reports Count: 2, the counter persisted across calls, run_code exposes cua_run_code as its only CUA tool, and each nested program can call only tools.cua."}}},{"type":"chunk","time":1795057089410,"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-run-code-ptc/system-prompt.expected.md b/snapshots/session/cua-run-code-ptc/system-prompt.expected.md index ebdf4836ef..b950ec6f8d 100644 --- a/snapshots/session/cua-run-code-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-run-code-ptc/system-prompt.expected.md @@ -88,7 +88,7 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. -Explicit downs from sendKeyEvent and toggleMouse share one turn-wide hold scope across run_code and cua_run_code calls. An explicit up releases input immediately at its original recipient. Program return or failure does not end a continuing turn. After turn/end, cleanup releases remaining keys and buttons together in reverse dispatch order, including on failure or user stop. pressKey, typeText, click, and complete drag release their own inputs within the operation. +In DSH, explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. MCP and other programs outside a DSH turn release remaining input before returning and report which inputs were automatically released. No reminder is added when there is nothing to report. Program failure, user stop, connection closure, and disposal release owned inputs together in reverse dispatch order. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/snapshots/session/cua-run-code/session.v4.jsonl b/snapshots/session/cua-run-code/session.v4.jsonl index 93709c6714..36e038510b 100644 --- a/snapshots/session/cua-run-code/session.v4.jsonl +++ b/snapshots/session/cua-run-code/session.v4.jsonl @@ -13,7 +13,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 cua_run_code to select test.fixture,","messageSeqs":[9],"source":{"kind":"fallback"}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); await app.sendKeyEvent(\\\"w\\\", \\\"down\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"stream":[{"type":"chunk","time":1794984911025,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794984911026,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); await app.sendKeyEvent(\\\"w\\\", \\\"down\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}}},{"type":"chunk","time":1794984911026,"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_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); await app.sendKeyEvent(\\\"w\\\", \\\"down\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"stream":[{"type":"chunk","time":1795057086972,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1795057086972,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); await app.sendKeyEvent(\\\"w\\\", \\\"down\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}}},{"type":"chunk","time":1795057086972,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); await app.sendKeyEvent(\\\"w\\\", \\\"down\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemPointer\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\",\"sendKeyEvent\",\"toggleMouse\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} @@ -28,9 +28,12 @@ {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:6","name":"cua","arguments":{"method":"screenshot","params":{"appHandle":"fixture-app","windowId":"7"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first: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":1,"message":{"role":"tool","source":{"kind":"tool","callId":"cua_first"},"toolCallId":"cua_first","content":[{"type":"text","text":"{\"visits\":1,\"bindings\":[\"cua\"],\"app\":\"fixture-app\",\"window\":\"7\"}\n"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[15],"surfaceOp":"append"} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"\nCUA inputs are still held:\n- Key \"w\", appHandle \"fixture-app\" (application input).\nThey remain pressed across programs and turns. Release them explicitly with sendKeyEvent(key, 'up') or toggleMouse(button, 'up') on the same target when no longer needed.\n"}],"source":{"kind":"cua-held-inputs","form":"notice","summary":"CUA inputs remain held"},"role":"user","id":"{{message:6}}"}]}} {"type":"step/end","data":{"turn":1,"step":1}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"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_reuse","name":"cua_run_code","arguments":"{\"code\":\"await app.sendKeyEvent(\\\"w\\\", \\\"up\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) })); await win.toggleMouse(\\\"left\\\", \\\"down\\\"); await app.sendKeyEvent(\\\"d\\\", \\\"down\\\")\",\"description\":\"Reuse the retained application and window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:6}}"},"stream":[{"type":"chunk","time":1794984911395,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794984911395,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_reuse","name":"cua_run_code","arguments":"{\"code\":\"await app.sendKeyEvent(\\\"w\\\", \\\"up\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) })); await win.toggleMouse(\\\"left\\\", \\\"down\\\"); await app.sendKeyEvent(\\\"d\\\", \\\"down\\\")\",\"description\":\"Reuse the retained application and window\"}"}}},{"type":"chunk","time":1794984911395,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nCUA inputs are still held:\n- Key \"w\", appHandle \"fixture-app\" (application input).\nThey remain pressed across programs and turns. Release them explicitly with sendKeyEvent(key, 'up') or toggleMouse(button, 'up') on the same target when no longer needed.\n"}],"source":{"kind":"cua-held-inputs","form":"notice","summary":"CUA inputs remain held"},"role":"user","id":"{{message:6}}"},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua_reuse","name":"cua_run_code","arguments":"{\"code\":\"await app.sendKeyEvent(\\\"w\\\", \\\"up\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) })); await win.toggleMouse(\\\"left\\\", \\\"down\\\"); await app.sendKeyEvent(\\\"d\\\", \\\"down\\\")\",\"description\":\"Reuse the retained application and window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:7}}"},"stream":[{"type":"chunk","time":1795057087286,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1795057087286,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_reuse","name":"cua_run_code","arguments":"{\"code\":\"await app.sendKeyEvent(\\\"w\\\", \\\"up\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) })); await win.toggleMouse(\\\"left\\\", \\\"down\\\"); await app.sendKeyEvent(\\\"d\\\", \\\"down\\\")\",\"description\":\"Reuse the retained application and window\"}"}}},{"type":"chunk","time":1795057087286,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"cua_reuse","name":"cua_run_code","arguments":"{\"code\":\"await app.sendKeyEvent(\\\"w\\\", \\\"up\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) })); await win.toggleMouse(\\\"left\\\", \\\"down\\\"); await app.sendKeyEvent(\\\"d\\\", \\\"down\\\")\",\"description\":\"Reuse the retained application and window\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:1","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"w","direction":"up"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:1","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"w","direction":"up"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} @@ -44,9 +47,12 @@ {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:5","name":"cua","arguments":{"method":"toggleMouse","params":{"appHandle":"fixture-app","windowId":"7","mouseButton":"left","direction":"down"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:6","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"d","direction":"down"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:6","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"d","direction":"down"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} -{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"cua_reuse"},"toolCallId":"cua_reuse","content":[{"type":"text","text":"{\"visits\":2,\"app\":\"fixture-app\",\"window\":\"7\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 2\\\"\",\"bindings\":[\"cua\"]}\n"}],"isError":false,"id":"{{message:7}}"}},"sourceEventSeqs":[32],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"cua_reuse"},"toolCallId":"cua_reuse","content":[{"type":"text","text":"{\"visits\":2,\"app\":\"fixture-app\",\"window\":\"7\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 2\\\"\",\"bindings\":[\"cua\"]}\n"}],"isError":false,"id":"{{message:8}}"}},"sourceEventSeqs":[35],"surfaceOp":"append"} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"\nCUA inputs are still held:\n- Mouse left, appHandle \"fixture-app\", windowId \"7\" (window input).\n- Key \"d\", appHandle \"fixture-app\" (application input).\nThey remain pressed across programs and turns. Release them explicitly with sendKeyEvent(key, 'up') or toggleMouse(button, 'up') on the same target when no longer needed.\n"}],"source":{"kind":"cua-held-inputs","form":"notice","summary":"CUA inputs remain held"},"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":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"text","text":"The retained application and window report Count: 2. The counter persisted across calls, and the program exposes only tools.cua. The screenshot was attached after the first call."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:8}}"},"stream":[{"type":"chunk","time":1794984911492,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1794984911492,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"The retained application and window report Count: 2. The counter persisted across calls, and the program exposes only tools.cua. The screenshot was attached after the first call."}}},{"type":"chunk","time":1794984911492,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nCUA inputs are still held:\n- Mouse left, appHandle \"fixture-app\", windowId \"7\" (window input).\n- Key \"d\", appHandle \"fixture-app\" (application input).\nThey remain pressed across programs and turns. Release them explicitly with sendKeyEvent(key, 'up') or toggleMouse(button, 'up') on the same target when no longer needed.\n"}],"source":{"kind":"cua-held-inputs","form":"notice","summary":"CUA inputs remain held"},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"text","text":"The retained application and window report Count: 2. The counter persisted across calls, and the program exposes only tools.cua. The screenshot was attached after the first call."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:10}}"},"stream":[{"type":"chunk","time":1795057087322,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1795057087322,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"The retained application and window report Count: 2. The counter persisted across calls, and the program exposes only tools.cua. The screenshot was attached after the first call."}}},{"type":"chunk","time":1795057087322,"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-run-code/system-prompt.expected.md b/snapshots/session/cua-run-code/system-prompt.expected.md index 79484f8228..d0d5cf3e23 100644 --- a/snapshots/session/cua-run-code/system-prompt.expected.md +++ b/snapshots/session/cua-run-code/system-prompt.expected.md @@ -86,7 +86,7 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. -Explicit downs from sendKeyEvent and toggleMouse share one turn-wide hold scope across run_code and cua_run_code calls. An explicit up releases input immediately at its original recipient. Program return or failure does not end a continuing turn. After turn/end, cleanup releases remaining keys and buttons together in reverse dispatch order, including on failure or user stop. pressKey, typeText, click, and complete drag release their own inputs within the operation. +In DSH, explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. MCP and other programs outside a DSH turn release remaining input before returning and report which inputs were automatically released. No reminder is added when there is nothing to report. Program failure, user stop, connection closure, and disposal release owned inputs together in reverse dispatch order. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/snapshots/session/ptc-script-retained/system-prompt.expected.md b/snapshots/session/ptc-script-retained/system-prompt.expected.md index f1807bbbc6..a15bda60c7 100644 --- a/snapshots/session/ptc-script-retained/system-prompt.expected.md +++ b/snapshots/session/ptc-script-retained/system-prompt.expected.md @@ -92,7 +92,7 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. -Explicit downs from sendKeyEvent and toggleMouse share one turn-wide hold scope across run_code and cua_run_code calls. An explicit up releases input immediately at its original recipient. Program return or failure does not end a continuing turn. After turn/end, cleanup releases remaining keys and buttons together in reverse dispatch order, including on failure or user stop. pressKey, typeText, click, and complete drag release their own inputs within the operation. +In DSH, explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. MCP and other programs outside a DSH turn release remaining input before returning and report which inputs were automatically released. No reminder is added when there is nothing to report. Program failure, user stop, connection closure, and disposal release owned inputs together in reverse dispatch order. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. From b7b5a0114e49fc89b4604792fbde3cee3f323532 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 19 Nov 2026 11:16:10 +0800 Subject: [PATCH 36/73] Record confirmed pause releases and discard stale held-state notices --- packages/experimental/cua/README.i18n.yaml | 4 +- packages/experimental/cua/README.md | 2 + packages/experimental/cua/README.zh.md | 2 + packages/experimental/cua/src/held-inputs.ts | 49 ++++++++--- packages/experimental/cua/src/index.ts | 4 +- packages/experimental/cua/src/types.ts | 1 + .../cua/tests/run-code-composition.spec.ts | 81 ++++++++++++++++++- .../session/cua-run-code/native-channel.mjs | 2 + 8 files changed, 129 insertions(+), 16 deletions(-) diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index fa1ed2ff58..e344906b88 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -21,8 +21,8 @@ en: 3f638a4a76023fc5 zh: 515aeb5de6ae5b33 /deepseek-ai-dsh-cua/understand-the-implementation: - en: 78be79b4935a5a93 - zh: eb50cccc867fb1e9 + en: 7e8694a4435a1186 + zh: 8070eb8cabf9fd83 /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 9378ea2548..e9f233d464 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -93,6 +93,8 @@ Permission responses identify their platform and report only the state that plat Providers implementing `CuaBackend.heldInputState` accept `taskId` on explicit input and system pointer movement, report their connection-owned records through `getHeldInputs({ taskId })`, and acknowledge `releaseHeldInputs({ taskId })`. Native records own the actual key/button, target, process identity and input mode. Successful `run_code` and `cua_run_code` programs in DSH turns query those records and append a system reminder when input remains held; normal program and turn endings preserve input. Programs outside a DSH turn, including MCP, instead await release before returning and report only inputs the helper confirmed it released. Reminders travel through logged additional context in DSH and through the tool response in MCP. Program failure, cancellation, connection closure, environment reset and disposal stop owned dispatch and await reverse-order release. Cleanup failure disables further CUA operations for the task and reports the uncertainty. Provider unload retains these listeners until programs and native connections drain. Capability methods remain static. Windows leaves `heldInputState` unset until its helper implements reporting and cleanup; it receives no new commands. +Held input belongs to the task and native connection, outside program processes. DSH observes the turn cancellation signal while the model is thinking. Confirmed cleanup queues a release notice for the resumed model; held-state snapshots arriving after cleanup starts are discarded. + The [permission store](src/permission-store.ts) uses `storageDomain` with the configured backend. The default JSON backend writes `$DSH_HOME/storages/cua_permissions_.json`, where the digest identifies the canonical profile directory. Each authorization check opens fresh state under the profile's file lock and closes its domain afterward; native dispatch uses a separate application lock. Revocation waits for operations already admitted by another process; after it completes, every process rejects old handles. Files on different machines or PID namespaces must not share this lock. Legacy `allowedApps` are imported on first store access and never reapplied after migration. The old configuration can be removed after checking the permission page. Grants, denials and the option to ask again are durable; the page still omits conversation-only grants. Standalone compositions without a profile retain only process-local decisions; a profile without domain storage refuses authorization operations. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index d2f71e6987..a345d6cee7 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -93,6 +93,8 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边 实现 `CuaBackend.heldInputState` 的提供方为显式输入和系统指针移动接受 `taskId`,通过 `getHeldInputs({ taskId })` 报告本连接的持有记录,并确认 `releaseHeldInputs({ taskId })`。原生记录负责保存实际按键或按钮、目标、进程身份和输入方式。DSH 回合中成功结束的 `run_code` 和 `cua_run_code` 查询这些记录,仍有输入按住时添加 system reminder;正常程序结束和回合结束均保持输入。没有 DSH 回合的程序,包括 MCP,在返回前等待释放,并只报告 helper 已确认释放的输入。DSH 通过已记录的额外上下文传递提醒,MCP 通过工具响应传递。程序失败、取消、断连、环境重置和销毁会停止所属输入派发,并等待反序释放。清理失败会禁用该任务后续 CUA 操作并报告结果不确定。提供方卸载前保留监听器,直到程序和原生连接排空。能力方法列表保持静态。Windows 在 helper 实现报告和清理前不设置 `heldInputState`,不会收到新命令。 +持有输入属于任务和原生连接,保存在程序进程之外。模型思考期间,DSH 仍监听回合取消信号。清理确认后,释放提醒进入会话队列,供恢复后的模型读取;清理开始后才到达的旧持有状态提醒会被丢弃。 + [授权存储](src/permission-store.ts)复用 `storageDomain` 和配置的后端。默认 JSON 后端写入 `$DSH_HOME/storages/cua_permissions_.json`,摘要对应 profile 的真实目录。每次授权检查在 profile 文件锁内打开并读取最新状态,随后关闭存储域;原生操作使用单独的应用锁。撤销会等待其他进程已获准执行的操作结束;撤销完成后,各进程都拒绝旧句柄。不同电脑或 PID 命名空间不能共享这把锁。 旧 `allowedApps` 只在首次访问存储时导入,迁移后不再应用。确认权限页显示正确后,可以删除旧配置。授权、拒绝和允许再次询问均持久化,页面仍不显示仅对某个会话生效的许可。没有 profile 的独立组合只保留进程内决定;有 profile 但缺少域存储的组合会拒绝授权操作。 diff --git a/packages/experimental/cua/src/held-inputs.ts b/packages/experimental/cua/src/held-inputs.ts index 9467c12789..eb4721fa30 100644 --- a/packages/experimental/cua/src/held-inputs.ts +++ b/packages/experimental/cua/src/held-inputs.ts @@ -12,14 +12,17 @@ const heldInputs = z.array(z.discriminatedUnion('kind', [ z.object({ ...target, kind: z.literal('mouse'), button: z.enum(['left', 'right', 'middle']), windowId: z.string() }), ])) -function renderInputs(inputs: z.infer, state: 'held' | 'released'): string { +function renderInputs(inputs: z.infer, state: 'held' | 'released' | 'program-end'): string { const rows = inputs.map(input => input.kind === 'key' ? `- Key ${JSON.stringify(input.key)}, appHandle ${JSON.stringify(input.appHandle)} (${input.mode} input).` : `- Mouse ${input.button}, appHandle ${JSON.stringify(input.appHandle)}, windowId ${JSON.stringify(input.windowId)} (${input.mode} input).`) - return ['', state === 'held' ? 'CUA inputs are still held:' : 'CUA inputs were automatically released at program end:', ...rows, + const title = state === 'held' ? 'CUA inputs are still held:' + : state === 'program-end' ? 'CUA inputs were automatically released at program end:' : 'CUA inputs were released during cleanup:' + return ['', title, ...rows, state === 'held' ? "They remain pressed across programs and turns. Release them explicitly with sendKeyEvent(key, 'up') or toggleMouse(button, 'up') on the same target when no longer needed." - : 'These inputs are no longer held. In this environment, keep any required hold sequence within one program.', + : state === 'program-end' ? 'These inputs are no longer held. In this environment, keep any required hold sequence within one program.' + : 'These inputs are no longer held.', ''].join('\n') } @@ -27,12 +30,15 @@ class InputOwner { readonly controller = new AbortController() private client: NativeClient | undefined private removeCleanup: (() => void) | undefined + private notifySessionOnRelease = false closing: Promise> | undefined - constructor(readonly agent: Agent, private readonly failed: (error: unknown) => void) {} + constructor(readonly agent: Agent, private readonly failed: (error: unknown) => void, + private readonly released: (inputs: z.infer) => void) {} - track(client: NativeClient): void { + track(client: NativeClient, inTurn: boolean): void { this.controller.signal.throwIfAborted() + this.notifySessionOnRelease ||= inTurn if (this.client) return this.removeCleanup = client.registerCleanup(async (canRequest) => { await this.close(canRequest) }) this.client = client @@ -47,13 +53,14 @@ class InputOwner { this.client = undefined return } + this.notifySessionOnRelease = true return renderInputs(inputs, 'held') } async releaseReminder(): Promise { if (this.closing) return const released = await this.close() - return released.length > 0 ? renderInputs(released, 'released') : undefined + return released.length > 0 ? renderInputs(released, 'program-end') : undefined } close(canRequest = true): Promise> { @@ -62,7 +69,9 @@ class InputOwner { try { if (!this.client) return [] if (!canRequest) throw new NativeError('INPUT_CLEANUP_UNCONFIRMED', 'Native connection closed before held-input cleanup was confirmed. Inspect the desktop manually before starting a new task') - return heldInputs.parse(await this.client.requestCleanup('releaseHeldInputs', { taskId: this.agent.id })) + const released = heldInputs.parse(await this.client.requestCleanup('releaseHeldInputs', { taskId: this.agent.id })) + if (this.notifySessionOnRelease && released.length > 0) this.released(released) + return released } catch (error) { this.failed(error) throw error @@ -104,6 +113,17 @@ export class CuaHeldInputs { this.failures.set(agent, error) this.ctx.logger.error('CUA cleanup was not confirmed; all CUA operations are disabled for task %s: %s', agent.id, error) emitAgentEvent(this.ctx, agent, 'agent/error', { turn: this.ctx.agents.turnBoundaryOf(agent.session).lastTurn, step: 0, error }) + }, (inputs) => { + try { + agent.inject(createUserMessage({ + content: [{ type: 'text', text: renderInputs(inputs, 'released') }], + source: { kind: 'cua-inputs-released', form: 'notice', summary: 'CUA inputs released' }, + })) + } catch (error) { + this.ctx.logger.error('CUA inputs were released but their notice could not be recorded for task %s: %s', agent.id, error) + emitAgentEvent(this.ctx, agent, 'agent/error', { turn: this.ctx.agents.turnBoundaryOf(agent.session).lastTurn, step: 0, + error: new NativeError('INPUT_NOTICE_FAILED', 'CUA inputs were released, but their notice could not be recorded', { cause: error }) }) + } }) this.owners.set(agent, owner) return owner @@ -142,9 +162,11 @@ export class CuaHeldInputs { const owner = this.owners.get(agent) const inTurn = ctx.agents.turnBoundaryOf(agent.session).openTurnStartSeq !== null const text = inTurn ? await owner?.reminder() : await owner?.releaseReminder() - if (text) return { ...result, additionalContexts: [...result.additionalContexts ?? [], + if (signal.aborted) { await this.release(agent); return result } + if (text && (!inTurn || !owner?.closing)) return { ...result, additionalContexts: [...result.additionalContexts ?? [], createUserMessage({ content: [{ type: 'text', text }], - source: { kind: 'cua-held-inputs', form: 'notice', summary: inTurn ? 'CUA inputs remain held' : 'CUA inputs released' } }), + source: { kind: inTurn ? 'cua-held-inputs' : 'cua-inputs-released', + form: 'notice', summary: inTurn ? 'CUA inputs remain held' : 'CUA inputs released' } }), ] } } return result @@ -169,9 +191,16 @@ export class CuaHeldInputs { return next() }) yield ctx.on('session/event', (session, event) => { - if (event.type !== 'turn/end') return + if (event.type !== 'turn/end' && event.type !== 'agent/inbox/spliced') return const agent = ctx.agents.get(session.id) if (agent?.session !== session) return + if (event.type === 'agent/inbox/spliced') { + // Cancellation can finish cleanup before a delayed tool result queues its earlier held-state snapshot. + if (this.owners.get(agent)?.closing) { + for (const message of event.data.inserted) if (message.source.kind === 'cua-held-inputs') agent.inbox.remove(message.id) + } + return + } this.turnSignals.get(agent)?.remove() this.turnSignals.delete(agent) if (event.data.reason.kind === 'aborted' || event.data.reason.kind === 'error') this.stop(agent) diff --git a/packages/experimental/cua/src/index.ts b/packages/experimental/cua/src/index.ts index c9034b8cf0..0df8c40e4b 100644 --- a/packages/experimental/cua/src/index.ts +++ b/packages/experimental/cua/src/index.ts @@ -289,7 +289,9 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) else if (useSystemPointer !== undefined) params.useSystemPointer = useSystemPointer if (heldInputs && (method === 'sendKeyEvent' || method === 'toggleMouse' || (method === 'mouseMove' && useSystemPointer))) { const owner = await heldInputs.ready(agent) - if (method !== 'mouseMove' && params.direction === 'down') owner.track(client) + if (method !== 'mouseMove' && params.direction === 'down') { + owner.track(client, ctx.agents.turnBoundaryOf(agent.session).openTurnStartSeq !== null) + } params.taskId = agent.id } const nativeParams = method === 'findApps' diff --git a/packages/experimental/cua/src/types.ts b/packages/experimental/cua/src/types.ts index bcf78c025c..cc34ca370c 100644 --- a/packages/experimental/cua/src/types.ts +++ b/packages/experimental/cua/src/types.ts @@ -9,6 +9,7 @@ import type { ActionResult, CapabilitiesResult, FoundAppsResult, HoverResult, Sy declare module '@deepseek-ai/dsh-llm' { interface MessageSourceMap { 'cua-held-inputs': { kind: 'cua-held-inputs' } & ContextFormed + 'cua-inputs-released': { kind: 'cua-inputs-released' } & ContextFormed } } diff --git a/packages/experimental/cua/tests/run-code-composition.spec.ts b/packages/experimental/cua/tests/run-code-composition.spec.ts index 4b5d700286..962d207049 100644 --- a/packages/experimental/cua/tests/run-code-composition.spec.ts +++ b/packages/experimental/cua/tests/run-code-composition.spec.ts @@ -26,7 +26,7 @@ import * as PtcToolExecutor from '@deepseek-ai/dsh-tool-executor-ptc' import type {} from '@deepseek-ai/dsh-tool-executor-ptc/types' import ToolRuntime, { defineTool } from '@deepseek-ai/dsh-tools' import WorkingDirectory from '@deepseek-ai/dsh-working-directory' -import { expect, it, onTestFinished } from 'vitest' +import { expect, it, onTestFinished, vi } from 'vitest' import { z } from 'zod' import { createNativeFixture, png } from '../../../../snapshots/session/cua-run-code/native-channel.mjs' import { CuaConfig, installCua } from '../src/index.ts' @@ -360,8 +360,9 @@ it('forwards per-read accessibility limits to the Windows backend', async () => const holdProgram = 'var app = await cua.getApp("test.fixture"); await app.sendKeyEvent("w", "down")' -function reminders(agent: { session: { snapshotEvents(): readonly import('@deepseek-ai/dsh-session').SessionEvent[] } }) { - return agent.session.snapshotEvents().filter(event => event.type === 'user/message' && event.data.source.kind === 'cua-held-inputs') +function reminders(agent: { session: { snapshotEvents(): readonly import('@deepseek-ai/dsh-session').SessionEvent[] } }, + kind: 'cua-held-inputs' | 'cua-inputs-released' = 'cua-held-inputs') { + return agent.session.snapshotEvents().filter(event => event.type === 'user/message' && event.data.source.kind === kind) .flatMap(event => event.type === 'user/message' ? event.data.content.filter(block => block.type === 'text').map(block => block.text) : []) } @@ -564,3 +565,77 @@ it('ignores turn endings from Sessions without an Agent', async () => { session.append('turn/end', { turn: 1, reason: { kind: 'error', error: { code: 'UNKNOWN', message: 'Unrelated failure' } } }) expect(f.native.held.map(press => press.key)).toEqual(['w']) }) + +it('records release after a thinking pause so the resumed model sees the new input state', async () => { + const f = await setup([holdProgram], 'macos', undefined, true, true) + const thinking: PromiseWithResolvers = Promise.withResolvers() + f.model.beforeStream = async (index, options) => { + if (index !== 1) return + thinking.resolve() + await new Promise((resolve) => { options.signal?.addEventListener('abort', () => { resolve() }, { once: true }) }) + } + const running = f.run() + await thinking.promise + f.agent.cancel({ kind: 'user' }) + await running + expect(f.native.held).toEqual([]) + expect(f.agent.inbox.nextStep.some(message => message.source.kind === 'cua-inputs-released')).toBe(true) + delete f.model.beforeStream + f.model.restart(['inspect("resumed")']) + await f.run() + expect(reminders(f.agent, 'cua-inputs-released')).toHaveLength(1) + expect(JSON.stringify(f.model.requests[0]?.messages)).toContain('CUA inputs were released during cleanup') +}) + +it('drops a delayed held-state reminder after cancellation has already released the input', async () => { + const f = await setup([holdProgram], 'macos', undefined, true, true) + const post: PromiseWithResolvers = Promise.withResolvers() + const finish: PromiseWithResolvers = Promise.withResolvers() + const released: PromiseWithResolvers = Promise.withResolvers() + f.ctx.on('tools/post-execute', async (execution, _result, next) => { + const decision = await next() + if (execution.name === 'cua_run_code' && execution.parent === undefined) { post.resolve(); await finish.promise } + return decision + }) + f.ctx.on('session/event', (_session, event) => { + if (event.type === 'agent/inbox/spliced' && event.data.inserted.some(message => message.source.kind === 'cua-inputs-released')) released.resolve() + }) + const running = f.run() + await post.promise + try { + f.agent.cancel({ kind: 'user' }) + await released.promise + expect(f.native.held).toEqual([]) + } finally { finish.resolve(); await running } + expect(f.agent.inbox.nextStep.some(message => message.source.kind === 'cua-held-inputs')).toBe(false) + f.model.restart(['inspect("resumed")']) + await f.run() + expect(reminders(f.agent)).toEqual([]) + expect(reminders(f.agent, 'cua-inputs-released')).toHaveLength(1) +}) + +it('does not report held input when stopped as its native state query replies', async () => { + const f = await setup([holdProgram], 'macos', undefined, true, true) + const query = f.native.controlNext('getHeldInputs', { afterDispatch: true }) + const running = f.run() + await query.entered + query.reply() + f.agent.cancel({ kind: 'user' }) + await running + expect(f.native.held).toEqual([]) + expect(f.agent.inbox.nextStep.some(message => message.source.kind === 'cua-held-inputs')).toBe(false) +}) + +it('reports notice-write failure without treating confirmed native release as unknown', async () => { + const f = await setup([holdProgram + '; throw Error("failed program")'], 'macos', undefined, true, true) + const errors: unknown[] = [] + f.ctx.on('agent/error', (event) => { errors.push(event.error) }) + const inject = vi.spyOn(f.agent, 'inject').mockImplementationOnce(() => { throw new Error('Notice write failed') }) + onTestFinished(() => { inject.mockRestore() }) + await f.run() + expect(errors).toEqual([expect.objectContaining({ code: 'INPUT_NOTICE_FAILED' })]) + expect(f.native.held).toEqual([]) + f.model.restart([holdProgram]) + await f.run() + expect(f.native.held.map(press => press.key)).toEqual(['w']) +}) diff --git a/snapshots/session/cua-run-code/native-channel.mjs b/snapshots/session/cua-run-code/native-channel.mjs index 2b6bc41a85..2d732e933b 100644 --- a/snapshots/session/cua-run-code/native-channel.mjs +++ b/snapshots/session/cua-run-code/native-channel.mjs @@ -90,6 +90,8 @@ export function createNativeFixture(selectorPid) { heldCallId = undefined events.push('native-cancelled') stdout.write(JSON.stringify({ id, error: { code: 'NATIVE_CANCELLED', message: 'Fixture click cancelled.' } }) + '\n') + } else if (type === 'cancel') { + // A reply can settle immediately before the caller's cancellation reaches the helper. } else { calls.push({ id, method, params }) if (controlled?.method === method) { From e9d19c9d3598bcc7d8ba770c60616674d598afc1 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 19 Nov 2026 11:21:15 +0800 Subject: [PATCH 37/73] Discard stale held notices through the committed inbox notification --- packages/experimental/cua/src/held-inputs.ts | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/packages/experimental/cua/src/held-inputs.ts b/packages/experimental/cua/src/held-inputs.ts index eb4721fa30..a2b407502a 100644 --- a/packages/experimental/cua/src/held-inputs.ts +++ b/packages/experimental/cua/src/held-inputs.ts @@ -190,17 +190,14 @@ export class CuaHeldInputs { } return next() }) + yield ctx.on('agent/inbox/inserted', ({ agent, message }) => { + // This live notification runs after append publication, so removal can safely write its own event. + if (message.source.kind === 'cua-held-inputs' && this.owners.get(agent)?.closing) agent.inbox.remove(message.id) + }, { prepend: true }) yield ctx.on('session/event', (session, event) => { - if (event.type !== 'turn/end' && event.type !== 'agent/inbox/spliced') return + if (event.type !== 'turn/end') return const agent = ctx.agents.get(session.id) if (agent?.session !== session) return - if (event.type === 'agent/inbox/spliced') { - // Cancellation can finish cleanup before a delayed tool result queues its earlier held-state snapshot. - if (this.owners.get(agent)?.closing) { - for (const message of event.data.inserted) if (message.source.kind === 'cua-held-inputs') agent.inbox.remove(message.id) - } - return - } this.turnSignals.get(agent)?.remove() this.turnSignals.delete(agent) if (event.data.reason.kind === 'aborted' || event.data.reason.kind === 'error') this.stop(agent) From 1100abfac4e2e3ace3de29dee50f15709dba9724 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 19 Nov 2026 11:56:11 +0800 Subject: [PATCH 38/73] Keep successful MCP input held and clean only on observed cancellation --- ...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 +- .../profiles/cua-mcp/cua-mcp.expected.e2e.ts | 10 ++--- docs/event-producer-consumer.md | 2 +- docs/event-producer-consumer.zh.md | 2 +- .../cua-held-inputs/guide.i18n.yaml | 4 +- .../v0.2.2-rc.5/cua-held-inputs/guide.md | 2 +- .../v0.2.2-rc.5/cua-held-inputs/guide.zh.md | 2 +- .../experimental/cua-macos/README.i18n.yaml | 4 +- packages/experimental/cua-macos/README.md | 4 +- packages/experimental/cua-macos/README.zh.md | 4 +- .../cua-macos/native/README.i18n.yaml | 4 +- .../experimental/cua-macos/native/README.md | 2 +- .../cua-macos/native/README.zh.md | 2 +- .../experimental/cua-mcp/README.i18n.yaml | 4 +- packages/experimental/cua-mcp/README.md | 2 +- packages/experimental/cua-mcp/README.zh.md | 2 +- packages/experimental/cua-mcp/src/server.ts | 41 +++++++++++------ .../cua-mcp/tests/composition.spec.ts | 45 ++++++++++++++----- .../experimental/cua-mcp/tests/server.spec.ts | 2 +- packages/experimental/cua/README.i18n.yaml | 4 +- packages/experimental/cua/README.md | 4 +- packages/experimental/cua/README.zh.md | 4 +- packages/experimental/cua/src/guidance.ts | 2 +- packages/experimental/cua/src/held-inputs.ts | 24 ++++------ .../experimental/cua/src/tool-registration.ts | 10 ++++- packages/experimental/cua/src/types.ts | 4 +- 28 files changed, 118 insertions(+), 80 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 6a4b33dacd..8507be2693 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 @@ -15,5 +15,5 @@ en: 32c970ae153e0f6c zh: 8431be0a10ffed15 /agent-note-cua-scoped-surfaces-and-separated-input-capabilities/consequences: - en: 7f4cb4b375fc8bdb - zh: bf273fdc4940d988 + en: f1efc14ced052492 + zh: 9834bb2cf09c536e 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 1744be0a66..4701db9150 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 @@ -34,6 +34,6 @@ Within one API instance, the object facade keeps one current accessibility snaps Element IDs belong to the application's current accessibility snapshot. Reading one window replaces the facade’s current snapshot for that application, so callers observe again and confirm the IDs they use. The new read does not guarantee that an old string is rejected or that an ID changes; callers must not assume an older ID still identifies the same control. Pointer input and screenshots require an explicit window object; callers enumerate windows first. -Keyboard behavior follows the provider's supported scopes. A caller that uses `sendKeyEvent` controls its down/up pairing. Native input ownership follows the task and connection. Successful programs in DSH turns report remaining held input without releasing it. Programs outside DSH turns, including MCP, release before returning and report confirmed releases because external clients provide no between-call pause notification. Explicit up, program failure, user cancellation and resource disposal release owned input. macOS implements this lifecycle; Windows implementation is pending. Keyboard modifier names are provider-defined, so the same string may have different support across providers. +Keyboard behavior follows the provider's supported scopes. A caller that uses `sendKeyEvent` controls its down/up pairing. Native input ownership follows the task and connection. Successful DSH and MCP programs report remaining held input without releasing it. A client pause between completed MCP calls does not notify this server and can leave input held; native ownership still permits explicit release and connection cleanup. Explicit up, program failure, user cancellation and resource disposal release owned input. macOS implements this lifecycle; Windows implementation is pending. Keyboard modifier names are provider-defined, so the same string may have different support across providers. Provider guidance owns the list of supported actions. Adding a method to the shared schema does not claim that every provider implements it, and the merged `getCapabilities` result remains the runtime source for permissions and session lock. 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 aa36b1f2f5..7323a58adf 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 @@ -34,6 +34,6 @@ Provider 的启动能力是静态的。平台、支持的方法、应用级辅 元素 ID 属于应用当前的辅助功能快照。读取一个窗口会替换门面对该应用的当前快照,因此调用方需要重新观察并确认要使用的 ID。新的读取不保证拒绝旧字符串,也不保证 ID 会改变;调用方不得假定旧 ID 仍指向同一控件。指针输入和截图都要求显式的窗口对象;调用方先枚举窗口。 -键盘行为遵循 provider 支持的作用域。使用 `sendKeyEvent` 的调用方控制按下与抬起的配对。原生输入所有权属于任务和连接。DSH 回合中的程序成功结束时报告剩余持有输入,不自动释放。没有 DSH 回合的程序,包括 MCP,在返回前释放并报告确认结果,因为外部客户端不提供调用之间的暂停通知。显式 up、程序失败、用户取消和资源销毁释放所属输入。macOS 已实现这套生命周期,Windows 待实现。键盘修饰键名称由 provider 定义,同一字符串在不同 provider 上可能支持不同。 +键盘行为遵循 provider 支持的作用域。使用 `sendKeyEvent` 的调用方控制按下与抬起的配对。原生输入所有权属于任务和连接。DSH 和 MCP 程序成功结束时报告剩余持有输入,不自动释放。客户端在两次 MCP 调用之间暂停时不会通知服务端,输入可能继续按住;原生所有权仍支持显式释放和连接清理。显式 up、程序失败、用户取消和资源销毁释放所属输入。macOS 已实现这套生命周期,Windows 待实现。键盘修饰键名称由 provider 定义,同一字符串在不同 provider 上可能支持不同。 Provider 指导文本负责支持动作的清单。把方法加入共享 schema 并不表示每个 provider 都已实现它;合并后的 `getCapabilities` 结果仍是权限和会话锁定状态的运行时来源。 diff --git a/apps/cli/tests/profiles/cua-mcp/cua-mcp.expected.e2e.ts b/apps/cli/tests/profiles/cua-mcp/cua-mcp.expected.e2e.ts index d66b065d9f..69c451d5a8 100644 --- a/apps/cli/tests/profiles/cua-mcp/cua-mcp.expected.e2e.ts +++ b/apps/cli/tests/profiles/cua-mcp/cua-mcp.expected.e2e.ts @@ -93,15 +93,15 @@ describe.skipIf(!existsSync(bin))('cua-mcp profile', { retry: 0 }, () => { const held = await probe.request('tools/call', { name: 'cua_run_code', arguments: { code: 'await app.sendKeyEvent("shift", "down"); await win.toggleMouse("left", "down"); await app.sendKeyEvent("w", "down"); inspect("Input sequence finished.")', - description: 'Hold mixed input within one MCP program', + description: 'Hold mixed input across MCP programs', } }) as CallResult expect(held.isError).toBeUndefined() - await expect(`${JSON.stringify(held, null, 2)}\n`).toMatchFileSnapshot('./expected/input-release.json') + await expect(`${JSON.stringify(held, null, 2)}\n`).toMatchFileSnapshot('./expected/held-inputs.json') const up = await probe.request('tools/call', { name: 'cua_run_code', arguments: { - code: 'await app.sendKeyEvent("w", "up")', description: 'Confirm W was released', + code: 'await app.sendKeyEvent("w", "up"); await win.toggleMouse("left", "up"); await app.sendKeyEvent("shift", "up")', description: 'Release the held input', } }) as CallResult - expect(up.isError).toBe(true) - expect(up.content.some(block => block.type === 'text' && block.text.includes('not held'))).toBe(true) + expect(up.isError).toBeUndefined() + expect(up.content.some(block => block.type === 'text' && block.text.includes(''))).toBe(false) const afterRelease = await probe.request('tools/call', { name: 'cua_run_code', arguments: { code: 'inspect("After release")', description: 'Continue without held input', } }) as CallResult diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index c6cbc1640b..b050a7f3e3 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -18,7 +18,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:430`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`), [`cua`](../packages/experimental/cua) (`emitAgentEvent`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | | `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:329`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | | `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:337`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:318`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | +| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:318`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`cua`](../packages/experimental/cua), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | | `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:351`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`cua`](../packages/experimental/cua), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | | `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:390`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | | `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:310`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`cua`](../packages/experimental/cua), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`timeline`](../packages/experimental/timeline) | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index 79da87ebc7..680505dd29 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -20,7 +20,7 @@ | `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:430`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`), [`cua`](../packages/experimental/cua) (`emitAgentEvent`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | | `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:329`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | | `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:337`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:318`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | +| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:318`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`cua`](../packages/experimental/cua), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | | `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:351`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`cua`](../packages/experimental/cua), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | | `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:390`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | | `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:310`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`cua`](../packages/experimental/cua), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`timeline`](../packages/experimental/timeline) | diff --git a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml index e25fc0bd63..53d804443b 100644 --- a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml @@ -9,8 +9,8 @@ en: 37252a5d19c7fe09 zh: f1b33b7da3935155 /cua-reports-held-input-after-programs/change: - en: e849a0f031b21621 - zh: ce75b936e290f185 + en: 4bd67513168d23c2 + zh: 62139119ecfdc51e /cua-reports-held-input-after-programs/migration: en: ff2470e52eb67983 zh: 8fd179145c4da20a diff --git a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md index a49e686346..7a95370903 100644 --- a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md @@ -8,7 +8,7 @@ English | [中文](guide.zh.md) ## Change -Within DSH turns, macOS explicit `sendKeyEvent('down')` and `toggleMouse('down')` remain held across programs and turns until an explicit `up`. Normal completion does not release them. After a successful `run_code` or `cua_run_code`, a system reminder lists any remaining keys and mouse buttons, their application or window and actual input mode. Program failure, user stop, connection closure, environment reset and disposal release owned input in reverse dispatch order. Complete `pressKey`, `typeText`, `click` and `drag` actions keep their operation-local cleanup. MCP programs release remaining input before returning and report confirmed automatic releases, because clients do not notify the server when paused between calls. Windows reporting and unified cleanup remain unimplemented. +macOS explicit `sendKeyEvent('down')` and `toggleMouse('down')` remain held across programs and turns until an explicit `up`. Normal completion does not release them. After a successful `run_code` or `cua_run_code`, a system reminder lists any remaining keys and mouse buttons, their application or window and actual input mode. Program failure, user stop, connection closure, environment reset and disposal release owned input in reverse dispatch order. Complete `pressKey`, `typeText`, `click` and `drag` actions keep their operation-local cleanup. DSH and MCP both preserve input after successful programs. A client pause between completed MCP calls is not observable by the server and can leave input held. Windows reporting and unified cleanup remain unimplemented. ## Migration diff --git a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md index 597588ee2f..c9418b085d 100644 --- a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md @@ -8,7 +8,7 @@ description: macOS CUA 的显式输入跨程序和回合保持,成功结束的 ## 变更 -在 DSH 回合中,macOS 的显式 `sendKeyEvent('down')` 和 `toggleMouse('down')` 跨程序、跨回合保持,直到显式 `up`。正常结束不释放它们。成功结束的 `run_code` 或 `cua_run_code` 通过 system reminder 列出剩余键盘键和鼠标按钮、所属应用或窗口及实际输入方式。程序失败、用户停止、断连、环境重置和销毁按派发顺序的反序释放所属输入。完整的 `pressKey`、`typeText`、`click` 和 `drag` 保持操作内清理。MCP 程序在返回前释放剩余输入并报告确认的自动释放,因为客户端在两次调用之间暂停时不会通知服务端。Windows 的状态报告和统一清理仍未实现。 +macOS 的显式 `sendKeyEvent('down')` 和 `toggleMouse('down')` 跨程序、跨回合保持,直到显式 `up`。正常结束不释放它们。成功结束的 `run_code` 或 `cua_run_code` 通过 system reminder 列出剩余键盘键和鼠标按钮、所属应用或窗口及实际输入方式。程序失败、用户停止、断连、环境重置和销毁按派发顺序的反序释放所属输入。完整的 `pressKey`、`typeText`、`click` 和 `drag` 保持操作内清理。DSH 和 MCP 都在程序成功后保持输入。客户端在两次 MCP 调用之间暂停时,服务端无法观察到,输入可能继续按住。Windows 的状态报告和统一清理仍未实现。 ## 迁移 diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index 94c1de5de5..a27bcc4499 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -15,8 +15,8 @@ en: 1777e7bf6785f986 zh: e3daac1074ebb74d /deepseek-ai-dsh-cua-macos/use-this-package: - en: e6cc819a0e923ed9 - zh: 39c7ecd7d007d4a7 + en: ba5ff17d83e875cd + zh: 3fc685617b240e00 /deepseek-ai-dsh-cua-macos/use-this-package/connect-an-external-execution-environment: en: 3bf05d9ce5eb7224 zh: d8d0cd6429374860 diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index 0fae8dc4ea..b43643f064 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -83,7 +83,7 @@ The [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-cua-m `pressKey(key, modifiers?)` presses and releases one key. For shortcuts, pass held modifiers separately, as in `pressKey('a', ['command'])`. Pressing a modifier itself, as in `pressKey('shift')`, sets its flag on press and clears it on release. A single `+` or `plus` sends Shift+=. For `pressKey`, `click`, and `drag`, use `command`, `shift`, `option`/`alt`, `control`/`ctrl`, or `fn`. Only `pressKey` accepts `cmd` as a modifier alias for `command`. Key names are platform-defined; keypad names (`KP_0` through `KP_9`, `KP_Enter`, and keypad operators) retain their physical key codes. `typeText` sends literal text, including its line breaks and tabs. Use the App object's `pressKey` for a short press. -For a long press, call `app.sendKeyEvent('w', 'down')`. In DSH, explicit key and mouse downs remain held across programs and turns until an explicit up releases them at their saved target. Successful programs report remaining holds in a system reminder, including the target and actual input mode. Program failure, user cancellation, connection closure, reset and disposal release owned keys and buttons together in reverse dispatch order. Complete `pressKey`, `typeText`, `click` and `drag` operations retain their immediate cleanup. +For a long press, call `app.sendKeyEvent('w', 'down')`. Explicit key and mouse downs remain held across programs and turns until an explicit up releases them at their saved target. Successful programs report remaining holds in a system reminder, including the target and actual input mode. Program failure, user cancellation, connection closure, reset and disposal release owned keys and buttons together in reverse dispatch order. Complete `pressKey`, `typeText`, `click` and `drag` operations retain their immediate cleanup. Agent disposal and plugin unload cancel and await the complete tool call, including image admission and attachment storage. An image write already in progress must settle before disposal returns; a canceled call cannot return a successful screenshot. @@ -245,7 +245,7 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. -In DSH, explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. MCP and other programs outside a DSH turn release remaining input before returning and report which inputs were automatically released. No reminder is added when there is nothing to report. Program failure, user stop, connection closure, and disposal release owned inputs together in reverse dispatch order. pressKey, typeText, click, and complete drag release their own inputs within the operation. +Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index f2c6288389..7cbd800b27 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -83,7 +83,7 @@ pnpm dsh headless --patch packages/experimental/cua-macos/examples/macos.cordis. `pressKey(key, modifiers?)` 按下并松开一个键。使用快捷键时单独传入修饰键,例如 `pressKey('a', ['command'])`。单独调用 `pressKey('shift')` 时,按下事件带有 Shift 标志,释放事件清除该标志。`+` 和 `plus` 都会发送 Shift 和等号。`pressKey`、`click` 和 `drag` 都接受修饰键 `command`、`shift`、`option`/`alt`、`control`/`ctrl` 和 `fn`。只有 `pressKey` 的修饰键参数还接受 `command` 的别名 `cmd`。按键名由平台定义;数字键盘名称(`KP_0` 到 `KP_9`、`KP_Enter` 和数字键盘运算键)保留独立的物理键码。`typeText` 发送字面文本,包括其中的换行和制表符。短按使用 App 对象上的 `pressKey`。 -长按时调用 `app.sendKeyEvent('w', 'down')`。在 DSH 中,显式键盘和鼠标按下会跨程序、跨回合保持,直到显式 up 按保存的目标释放。成功结束的程序通过 system reminder 报告剩余持有输入,包括目标和实际输入方式。程序失败、用户取消、断连、重置和销毁按实际派发顺序的反序统一释放所属键盘键和鼠标按钮。完整的 `pressKey`、`typeText`、`click` 和 `drag` 保持操作内及时清理。 +长按时调用 `app.sendKeyEvent('w', 'down')`。显式键盘和鼠标按下会跨程序、跨回合保持,直到显式 up 按保存的目标释放。成功结束的程序通过 system reminder 报告剩余持有输入,包括目标和实际输入方式。程序失败、用户取消、断连、重置和销毁按实际派发顺序的反序统一释放所属键盘键和鼠标按钮。完整的 `pressKey`、`typeText`、`click` 和 `drag` 保持操作内及时清理。 Agent 销毁和插件卸载会取消并等待完整工具调用,包括图像接入检查和附件存储。已经开始的图像写入必须结束后,销毁才会返回;已取消的调用不会返回成功截图。 @@ -245,7 +245,7 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. -In DSH, explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. MCP and other programs outside a DSH turn release remaining input before returning and report which inputs were automatically released. No reminder is added when there is nothing to report. Program failure, user stop, connection closure, and disposal release owned inputs together in reverse dispatch order. pressKey, typeText, click, and complete drag release their own inputs within the operation. +Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index cb05281b15..487d7491ef 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -21,8 +21,8 @@ en: dea4de90fb3dd169 zh: 378ae657f5288807 /dsh-cua-native-helper/observation-and-input: - en: 3ca2ccd0ee8d549c - zh: 1ada0c7b7c38a1a8 + en: 968548e7bc74562d + zh: 29ef183d9dd98734 /dsh-cua-native-helper/verification: en: 11172b21e8ebf972 zh: dac6787e1e75a88e diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index e9592a4ad8..d782ac91fd 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -112,7 +112,7 @@ Capture and pointer delivery read CG bounds before and after an exact-window AX `typeText` and `pressKey` target the selected process's current focused control, not an exact window. `pressKey` presses the listed modifiers followed by one key, then releases all pressed keys in reverse order, including on cancellation. Keyboard events go directly to the target PID and bypass the global HID queue. Key names are platform-defined; keypad names such as `KP_0` and `KP_Enter` preserve their physical key codes. Background pointer actions may change that keyboard focus. Text injection sends Unicode characters individually and does not use the clipboard. LF, CR and CRLF send one Return; tabs send Tab. Applications apply their normal editing behavior, including indentation and focus navigation. Each `typeText` down/up event is followed by the configured text interval; `pressKey` keeps its own press and release timing, and dispatch completion does not confirm that the receiving application consumed every event. Cancellation can interrupt text or a gesture after partial input; it cannot undo received events. Very long text can exceed the host's operation deadline. Validate observed application state before deciding how to continue. -The Host attaches `taskId` to explicit input. `HeldInputs` records connection, task, application, original process identity, key code or button, release event and actual input mode before dispatch. Repeated key downs keep one record. Explicit up uses the saved target and input mode, skipping PID-directed releases after process exit or identity reuse. `getHeldInputs` reports only the requesting connection and task records, without reading physical user key state. Successful programs use this snapshot for their reminder. `releaseHeldInputs` releases keyboard and mouse records together in reverse dispatch order after program failure, cancellation or disposal. Normal DSH program and turn endings do not release input. MCP program completion releases remaining input, and `releaseHeldInputs` returns the records whose up events were dispatched. Connection shutdown joins native work before fallback release. Balanced key chords, text, clicks and drags keep their operation-local cleanup. +The Host attaches `taskId` to explicit input. `HeldInputs` records connection, task, application, original process identity, key code or button, release event and actual input mode before dispatch. Repeated key downs keep one record. Explicit up uses the saved target and input mode, skipping PID-directed releases after process exit or identity reuse. `getHeldInputs` reports only the requesting connection and task records, without reading physical user key state. Successful programs use this snapshot for their reminder. `releaseHeldInputs` releases keyboard and mouse records together in reverse dispatch order after program failure, cancellation or disposal. Normal program and turn endings do not release input. `releaseHeldInputs` returns the records whose up events were dispatched, for confirmed cleanup notices. Connection shutdown joins native work before fallback release. Balanced key chords, text, clicks and drags keep their operation-local cleanup. The selected helper application needs macOS Accessibility permission for AX state and input, and Screen Recording permission for screenshots. Capability preflight and permission errors do not grant permissions. Capture refuses a window that moves or resizes while the image is being read. Unassociated system panels and accessory-only applications are not selectable. diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index af7fda19a7..e27d380f72 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -112,7 +112,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 `typeText` 和 `pressKey` 面向所选进程当前获得焦点的控件,不指定窗口。`pressKey` 向目标 PID 依次发送修饰键和一个主键的按下事件,再逆序释放。操作中途取消也会逆序释放已按下的键。键盘事件直接发给目标进程,绕过全局 HID 队列。按键名由平台定义;KP_0 和 KP_Enter 等数字键盘名称保留物理键码。后台鼠标操作可能改变键盘焦点。文本逐个 Unicode 字符输入,不使用剪贴板。LF、CR 和 CRLF 发送一次 Return,制表符发送 Tab。应用保留缩进和焦点导航等正常编辑行为。`typeText` 的每次按下和抬起后等待配置的文本事件间隔;`pressKey` 使用自己的按下与释放节奏,分派完成不证明应用已消费全部事件。取消可能中断部分文本或手势,无法撤销已接收事件。很长的文本可能超过 Host 操作期限。继续输入前应核实应用状态。 -宿主为显式输入附上 `taskId`。`HeldInputs` 在派发前记录连接、任务、应用、原进程身份、键码或按钮、释放事件和实际输入方式。重复按键只保留一条记录。显式 up 使用保存的目标和输入方式;进程退出或 PID 身份变化后跳过定向释放。`getHeldInputs` 只报告请求连接和任务的记录,不读取用户物理按键状态。成功结束的程序用该快照生成提醒。程序失败、取消或销毁时,`releaseHeldInputs` 按派发顺序的反序统一释放键盘和鼠标记录。正常 DSH 程序结束和回合结束不释放输入。MCP 程序结束会释放剩余输入,`releaseHeldInputs` 返回已派发 up 的记录。连接关闭先等待原生操作停止,再兜底释放。完整击键、文本、点击和拖动保留操作内清理。 +宿主为显式输入附上 `taskId`。`HeldInputs` 在派发前记录连接、任务、应用、原进程身份、键码或按钮、释放事件和实际输入方式。重复按键只保留一条记录。显式 up 使用保存的目标和输入方式;进程退出或 PID 身份变化后跳过定向释放。`getHeldInputs` 只报告请求连接和任务的记录,不读取用户物理按键状态。成功结束的程序用该快照生成提醒。程序失败、取消或销毁时,`releaseHeldInputs` 按派发顺序的反序统一释放键盘和鼠标记录。正常程序结束和回合结束不释放输入。`releaseHeldInputs` 返回已派发 up 的记录,用于确认后的清理提醒。连接关闭先等待原生操作停止,再兜底释放。完整击键、文本、点击和拖动保留操作内清理。 所选 helper 应用需要 macOS 辅助功能权限以读取 AX 和输入,需要屏幕录制权限以截图。能力预检和权限错误不授予权限。截图会拒绝在读取图片期间移动或缩放的窗口。无法确认归属的系统面板及仅后台辅助类型的应用不可选择。 diff --git a/packages/experimental/cua-mcp/README.i18n.yaml b/packages/experimental/cua-mcp/README.i18n.yaml index 71eff6076f..02dea6227d 100644 --- a/packages/experimental/cua-mcp/README.i18n.yaml +++ b/packages/experimental/cua-mcp/README.i18n.yaml @@ -51,8 +51,8 @@ en: 0b0c63281111993b zh: 45716a56b5a5ad12 /deepseek-ai-dsh-cua-mcp/known-limitations-and-deferred-work: - en: 27085bbaf0a24801 - zh: 4fefe3ddbf60fea2 + en: b1ce029c37a771af + zh: 42390a45e6c440e4 /deepseek-ai-dsh-cua-mcp/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 8ec3e73528ddb1a6 diff --git a/packages/experimental/cua-mcp/README.md b/packages/experimental/cua-mcp/README.md index 9cbfd63d57..1fcae5a636 100644 --- a/packages/experimental/cua-mcp/README.md +++ b/packages/experimental/cua-mcp/README.md @@ -167,7 +167,7 @@ The tool catalog and instructions are stable for one installation. The reference -- Each program releases remaining native-held keys and mouse buttons before returning. A system reminder lists inputs automatically released after native acknowledgement. Input cannot remain held across MCP calls; no client pause notification is required. Program failure, cancellation, reset and connection closure also release owned input. +- Successful programs retain held keys and mouse buttons across calls and report them in a system reminder. Program failure, a received cancellation of an active cua_run_code request, reset and connection closure release owned input. If a call sends down and returns, and the client pauses while its model is thinking, this server receives no cancellation: that input can remain pressed until explicit up or later cleanup. - macOS and native Windows Hosts have a provider. Other Hosts, WSL included, list `cua_get_api_reference` and `cua_reset`, which both name the missing provider; a `cua_run_code` call fails as `unknown tool`. - On Windows the [provider's limits](../cua-windows/README.md#known-limitations-and-deferred-work) apply through MCP: it does not launch applications, grants no `Always allow`, and an npm installation needs `helperPath`. - Elicitation uses the 2025 MCP request model; a client that negotiates the 2026-07-28 revision receives an error for consent requests and should use `DSH_CUA_CONSENT=allow`. diff --git a/packages/experimental/cua-mcp/README.zh.md b/packages/experimental/cua-mcp/README.zh.md index b689ea92f2..b3b7674590 100644 --- a/packages/experimental/cua-mcp/README.zh.md +++ b/packages/experimental/cua-mcp/README.zh.md @@ -167,7 +167,7 @@ patch 还以 `screenshotTarget: { longEdge: 2048, maxBytes: 2097152 }` 挂载该 -- 每个程序在返回前释放剩余的原生键盘键和鼠标按钮。原生确认后,通过 system reminder 列出自动释放的输入。输入不能跨 MCP 调用保持,不需要客户端提供暂停通知。程序失败、取消、重置和断连也会释放所属输入。 +- 成功结束的程序跨调用保持键盘键和鼠标按钮,并通过 system reminder 报告。程序失败、执行中的 cua_run_code 请求收到取消、重置和断连会释放所属输入。如果一次调用发送 down 后返回,客户端随后在模型思考期间暂停,服务端收不到取消:该输入可能持续按住,直到显式 up 或后续清理。 - macOS 与原生 Windows Host 有提供方。其他 Host(包括 WSL)列出 `cua_get_api_reference` 与 `cua_reset`,二者都指出缺少提供方;调用 `cua_run_code` 以 `unknown tool` 失败。 - 在 Windows 上,[提供方的限制](../cua-windows/README.zh.md#known-limitations-and-deferred-work)经 MCP 同样适用:它不启动应用,不提供 `Always allow` 授权,npm 安装需要配置 `helperPath`。 - Elicitation 使用 2025 版 MCP 请求模型;协商到 2026-07-28 修订版的客户端在授权请求时收到错误,应改用 `DSH_CUA_CONSENT=allow`。 diff --git a/packages/experimental/cua-mcp/src/server.ts b/packages/experimental/cua-mcp/src/server.ts index 0a5c880be6..609a56439c 100644 --- a/packages/experimental/cua-mcp/src/server.ts +++ b/packages/experimental/cua-mcp/src/server.ts @@ -96,7 +96,7 @@ const INSTRUCTIONS = 'DeepSeek Harness Computer Use: observe and operate desktop + 'written without it guess the API wrong. Then call cua_run_code with a TypeScript program that uses the global cua ' + 'object; program state persists across calls on this connection. A call may ask the user for application or pointer ' + 'consent before it proceeds. Call cua_reset to discard program state. ' - + 'Remaining held keys and mouse buttons are released before each program returns. A system reminder lists inputs automatically released at program end. Explicit downs cannot stay held across MCP calls.' + + 'Explicit key and mouse downs remain held across successful programs; a system reminder lists remaining holds. Explicit up, program failure, request cancellation, reset, and connection closure release owned input. Client pause between completed calls is not observable by this server and does not release input.' const NO_PROVIDER = 'Computer Use is not available on this Host: the cua-mcp profile has no active CUA provider. ' + 'Providers exist for macOS and native Windows; on those Hosts the server\'s stderr names why the provider did not start.' @@ -203,21 +203,34 @@ export async function createCuaMcpServer(ctx: Context, options: CuaMcpServerOpti } // The program runtime rejects a run while the Agent's previous process is still exiting. while (resetting !== undefined) await resetting - // The call is the Agent's maintenance activity: Agent disposal cancels it and waits for it, with its nested - // calls, to settle before the Agent's scope and Session close. - const batch = await agent.runMaintenance(maintenance => ctx.agents.withInitiator(agent, () => ctx.tools.execute({ - calls: [{ - type: 'tool-call', id: brandString(`cua-mcp-${String(++calls)}`), name: PROGRAM_TOOL, arguments: JSON.stringify(args), - }], - agent, signal: AbortSignal.any([signal, maintenance]), - }))) - const outcome = batch.results[0] - if (outcome === undefined) throw new Error(`The tool executor settled without a ${PROGRAM_TOOL} result`) const programs = ctx.get('cuaPrograms') - return projectToolResult(outcome.result, batch.additionalContexts, { - attachments: ctx.attachments, target: image => programs?.screenshotRequestTarget(image), - }, signal) + let cleanup: Promise | undefined + const cancel = (): void => { + cleanup ??= programs?.releaseInputs(agent) ?? Promise.resolve() + void cleanup.catch(() => undefined) // The native owner reports failure; finally joins this same cleanup. + } + signal.addEventListener('abort', cancel, { once: true }) + if (signal.aborted) cancel() + try { + // The call is the Agent's maintenance activity: Agent disposal cancels it and waits for it, with its nested + // calls, to settle before the Agent's scope and Session close. + const batch = await agent.runMaintenance(maintenance => ctx.agents.withInitiator(agent, () => ctx.tools.execute({ + calls: [{ + type: 'tool-call', id: brandString(`cua-mcp-${String(++calls)}`), name: PROGRAM_TOOL, arguments: JSON.stringify(args), + }], + agent, signal: AbortSignal.any([signal, maintenance]), + }))) + const outcome = batch.results[0] + if (outcome === undefined) throw new Error(`The tool executor settled without a ${PROGRAM_TOOL} result`) + return await projectToolResult(outcome.result, batch.additionalContexts, { + attachments: ctx.attachments, target: image => programs?.screenshotRequestTarget(image), + }, signal) + } finally { + signal.removeEventListener('abort', cancel) + await cleanup + } } + const resetEnvironment = (): CallToolResult | Promise => { const programs = ctx.get('cuaPrograms') if (programs === undefined) return failure(NO_PROVIDER) diff --git a/packages/experimental/cua-mcp/tests/composition.spec.ts b/packages/experimental/cua-mcp/tests/composition.spec.ts index 80b14ea990..2083f55215 100644 --- a/packages/experimental/cua-mcp/tests/composition.spec.ts +++ b/packages/experimental/cua-mcp/tests/composition.spec.ts @@ -182,35 +182,60 @@ async function setup(options: SetupOptions = {}) { } describe('Computer Use MCP composition', () => { - it('releases MCP input before returning and reports only confirmed automatic releases', async () => { + it('retains input across successful MCP programs and reports remaining holds', async () => { const { native, run } = await setup() const held = await run('var app = await cua.getApp("test.fixture"); var win = await app.getWindow("7"); await win.getAccessibilityTree(); await app.sendKeyEvent("w", "down"); await win.toggleMouse("left", "down")') expect(held.isError).not.toBe(true) + expect(native.held.map(press => press.key)).toEqual(['w', 'left']) + expect(native.calls.some(call => call.method === 'releaseHeldInputs')).toBe(false) + expect(texts(held).join('')).toContain('CUA inputs are still held') + expect(texts(await run('inspect("next program")')).join('')).toContain('Key "w"') + const released = await run('await win.toggleMouse("left", "up"); await app.sendKeyEvent("w", "up")') + expect(texts(released).join('')).not.toContain('') expect(native.held).toEqual([]) - expect(native.events).toEqual(['w:down', 'left:down', 'left:up', 'w:up']) - expect(texts(held).join('')).toContain('CUA inputs were automatically released at program end') - expect(texts(held).join('')).toContain('Mouse left') - expect(texts(held).join('')).toContain('Key "w"') - expect(texts(await run('inspect("next program")')).join('')).not.toContain('') - expect(texts(await run('await app.sendKeyEvent("d", "down"); await app.sendKeyEvent("d", "up")')).join('')).not.toContain('') const failed = await run('await win.toggleMouse("left", "down"); throw Error("failed program")') expect(failed.isError).toBe(true) expect(native.held).toEqual([]) expect((await run('await win.click("0")')).isError).not.toBe(true) }) - it('waits for the native MCP cleanup reply and reports refusal without claiming release', async () => { + it('waits for cleanup after a failed MCP program and reports native refusal', async () => { const { native, run } = await setup() const release = native.controlNext('releaseHeldInputs') let settled = false - const running = run('var app = await cua.getApp("test.fixture"); await app.sendKeyEvent("w", "down")').then((value) => { settled = true; return value }) + const running = run('var app = await cua.getApp("test.fixture"); await app.sendKeyEvent("w", "down"); throw Error("program failed")').then((value) => { settled = true; return value }) await release.entered expect(settled).toBe(false) release.reply({ code: 'INPUT_CLEANUP_FAILED', message: 'MCP release refused' }) const result = await running expect(result.isError).toBe(true) expect(texts(result).join('')).toContain('MCP release refused') - expect(texts(result).join('')).not.toContain('inputs were automatically released') + }) + + it('cleans up a cancelled MCP request even after its program has finished and image delivery is pending', async () => { + const { ctx, native, run } = await setup() + const entered: PromiseWithResolvers = Promise.withResolvers() + const finish: PromiseWithResolvers = Promise.withResolvers() + const original = ctx.attachments.readImageRequest.bind(ctx.attachments) + const read = vi.spyOn(ctx.attachments, 'readImageRequest').mockImplementation(async (...args) => { + if (native.calls.some(call => call.method === 'getHeldInputs')) { entered.resolve(); await finish.promise } + return original(...args) + }) + onTestFinished(() => { finish.resolve(); read.mockRestore() }) + const controller = new AbortController() + const running = run('var app = await cua.getApp("test.fixture"); var win = await app.getWindow("7"); await app.sendKeyEvent("w", "down"); inspect(await win.getScreenshot())', {}, controller.signal) + const cancelled = expect(running).rejects.toThrow(/abort/i) + await entered.promise + const release = native.controlNext('releaseHeldInputs') + try { + controller.abort() + await release.entered + expect(native.held.map(press => press.key)).toEqual(['w']) + release.reply() + } finally { finish.resolve() } + await cancelled + await run('inspect("after cancellation")') + expect(native.held).toEqual([]) }) it('serves three tools, returns the API reference on request, and retains program state in the workspace', async () => { diff --git a/packages/experimental/cua-mcp/tests/server.spec.ts b/packages/experimental/cua-mcp/tests/server.spec.ts index ac75b00aa4..c91a843507 100644 --- a/packages/experimental/cua-mcp/tests/server.spec.ts +++ b/packages/experimental/cua-mcp/tests/server.spec.ts @@ -102,7 +102,7 @@ function fixture(options: SetupOptions = {}) { ctx.provide('tools', { execute, get } as never) ctx.provide('systemPrompt', { assemble } as never) ctx.provide('attachments', {} as never) - if (options.programs !== false) ctx.provide('cuaPrograms', { release, screenshotRequestTarget: () => undefined, ...options.programs } as never) + if (options.programs !== false) ctx.provide('cuaPrograms', { release, releaseInputs: vi.fn(async () => {}), screenshotRequestTarget: () => undefined, ...options.programs } as never) onTestFinished(async () => { await ctx.fiber.dispose() }) return { ctx, agent, maintenance, runMaintenance, cancel, whenIdle, create, withInitiator, initiators, mount, execute, get, assemble, diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index e344906b88..b7c42a4fa3 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -21,8 +21,8 @@ en: 3f638a4a76023fc5 zh: 515aeb5de6ae5b33 /deepseek-ai-dsh-cua/understand-the-implementation: - en: 7e8694a4435a1186 - zh: 8070eb8cabf9fd83 + en: 7e40a3ed87af41a5 + zh: a0ad1cbf2c70c285 /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 e9f233d464..69f028ab60 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -91,9 +91,9 @@ Permission responses identify their platform and report only the state that plat
Shared execution and platform ownership -Providers implementing `CuaBackend.heldInputState` accept `taskId` on explicit input and system pointer movement, report their connection-owned records through `getHeldInputs({ taskId })`, and acknowledge `releaseHeldInputs({ taskId })`. Native records own the actual key/button, target, process identity and input mode. Successful `run_code` and `cua_run_code` programs in DSH turns query those records and append a system reminder when input remains held; normal program and turn endings preserve input. Programs outside a DSH turn, including MCP, instead await release before returning and report only inputs the helper confirmed it released. Reminders travel through logged additional context in DSH and through the tool response in MCP. Program failure, cancellation, connection closure, environment reset and disposal stop owned dispatch and await reverse-order release. Cleanup failure disables further CUA operations for the task and reports the uncertainty. Provider unload retains these listeners until programs and native connections drain. Capability methods remain static. Windows leaves `heldInputState` unset until its helper implements reporting and cleanup; it receives no new commands. +Providers implementing `CuaBackend.heldInputState` accept `taskId` on explicit input and system pointer movement, report their connection-owned records through `getHeldInputs({ taskId })`, and acknowledge `releaseHeldInputs({ taskId })`. Native records own the actual key/button, target, process identity and input mode. Successful `run_code` and `cua_run_code` programs query those records and append a system reminder when input remains held; normal program and turn endings preserve input in both DSH and MCP. Reminders travel through logged additional context in DSH and through the tool response in MCP. Program failure, cancellation, connection closure, environment reset and disposal stop owned dispatch and await reverse-order release. Cleanup failure disables further CUA operations for the task and reports the uncertainty. Provider unload retains these listeners until programs and native connections drain. Capability methods remain static. Windows leaves `heldInputState` unset until its helper implements reporting and cleanup; it receives no new commands. -Held input belongs to the task and native connection, outside program processes. DSH observes the turn cancellation signal while the model is thinking. Confirmed cleanup queues a release notice for the resumed model; held-state snapshots arriving after cleanup starts are discarded. +Held input belongs to the task and native connection, outside program processes. DSH observes the turn cancellation signal while the model is thinking. DSH queues confirmed cleanup as a release notice for the resumed model; held-state snapshots arriving after cleanup starts are discarded. The [permission store](src/permission-store.ts) uses `storageDomain` with the configured backend. The default JSON backend writes `$DSH_HOME/storages/cua_permissions_.json`, where the digest identifies the canonical profile directory. Each authorization check opens fresh state under the profile's file lock and closes its domain afterward; native dispatch uses a separate application lock. Revocation waits for operations already admitted by another process; after it completes, every process rejects old handles. Files on different machines or PID namespaces must not share this lock. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index a345d6cee7..4df07c07ca 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -91,9 +91,9 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边
共享执行与平台职责 -实现 `CuaBackend.heldInputState` 的提供方为显式输入和系统指针移动接受 `taskId`,通过 `getHeldInputs({ taskId })` 报告本连接的持有记录,并确认 `releaseHeldInputs({ taskId })`。原生记录负责保存实际按键或按钮、目标、进程身份和输入方式。DSH 回合中成功结束的 `run_code` 和 `cua_run_code` 查询这些记录,仍有输入按住时添加 system reminder;正常程序结束和回合结束均保持输入。没有 DSH 回合的程序,包括 MCP,在返回前等待释放,并只报告 helper 已确认释放的输入。DSH 通过已记录的额外上下文传递提醒,MCP 通过工具响应传递。程序失败、取消、断连、环境重置和销毁会停止所属输入派发,并等待反序释放。清理失败会禁用该任务后续 CUA 操作并报告结果不确定。提供方卸载前保留监听器,直到程序和原生连接排空。能力方法列表保持静态。Windows 在 helper 实现报告和清理前不设置 `heldInputState`,不会收到新命令。 +实现 `CuaBackend.heldInputState` 的提供方为显式输入和系统指针移动接受 `taskId`,通过 `getHeldInputs({ taskId })` 报告本连接的持有记录,并确认 `releaseHeldInputs({ taskId })`。原生记录负责保存实际按键或按钮、目标、进程身份和输入方式。成功结束的 `run_code` 和 `cua_run_code` 查询这些记录,仍有输入按住时添加 system reminder;DSH 和 MCP 的正常程序结束和回合结束均保持输入。DSH 通过已记录的额外上下文传递提醒,MCP 通过工具响应传递。程序失败、取消、断连、环境重置和销毁会停止所属输入派发,并等待反序释放。清理失败会禁用该任务后续 CUA 操作并报告结果不确定。提供方卸载前保留监听器,直到程序和原生连接排空。能力方法列表保持静态。Windows 在 helper 实现报告和清理前不设置 `heldInputState`,不会收到新命令。 -持有输入属于任务和原生连接,保存在程序进程之外。模型思考期间,DSH 仍监听回合取消信号。清理确认后,释放提醒进入会话队列,供恢复后的模型读取;清理开始后才到达的旧持有状态提醒会被丢弃。 +持有输入属于任务和原生连接,保存在程序进程之外。模型思考期间,DSH 仍监听回合取消信号。DSH 在清理确认后将释放提醒写入会话队列,供恢复后的模型读取;清理开始后才到达的旧持有状态提醒会被丢弃。 [授权存储](src/permission-store.ts)复用 `storageDomain` 和配置的后端。默认 JSON 后端写入 `$DSH_HOME/storages/cua_permissions_.json`,摘要对应 profile 的真实目录。每次授权检查在 profile 文件锁内打开并读取最新状态,随后关闭存储域;原生操作使用单独的应用锁。撤销会等待其他进程已获准执行的操作结束;撤销完成后,各进程都拒绝旧句柄。不同电脑或 PID 命名空间不能共享这把锁。 diff --git a/packages/experimental/cua/src/guidance.ts b/packages/experimental/cua/src/guidance.ts index 7a1aa2511f..05152bd6ce 100644 --- a/packages/experimental/cua/src/guidance.ts +++ b/packages/experimental/cua/src/guidance.ts @@ -58,7 +58,7 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. -In DSH, explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. MCP and other programs outside a DSH turn release remaining input before returning and report which inputs were automatically released. No reminder is added when there is nothing to report. Program failure, user stop, connection closure, and disposal release owned inputs together in reverse dispatch order. pressKey, typeText, click, and complete drag release their own inputs within the operation. +Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/packages/experimental/cua/src/held-inputs.ts b/packages/experimental/cua/src/held-inputs.ts index a2b407502a..115ea8a653 100644 --- a/packages/experimental/cua/src/held-inputs.ts +++ b/packages/experimental/cua/src/held-inputs.ts @@ -12,17 +12,15 @@ const heldInputs = z.array(z.discriminatedUnion('kind', [ z.object({ ...target, kind: z.literal('mouse'), button: z.enum(['left', 'right', 'middle']), windowId: z.string() }), ])) -function renderInputs(inputs: z.infer, state: 'held' | 'released' | 'program-end'): string { +function renderInputs(inputs: z.infer, state: 'held' | 'released'): string { const rows = inputs.map(input => input.kind === 'key' ? `- Key ${JSON.stringify(input.key)}, appHandle ${JSON.stringify(input.appHandle)} (${input.mode} input).` : `- Mouse ${input.button}, appHandle ${JSON.stringify(input.appHandle)}, windowId ${JSON.stringify(input.windowId)} (${input.mode} input).`) - const title = state === 'held' ? 'CUA inputs are still held:' - : state === 'program-end' ? 'CUA inputs were automatically released at program end:' : 'CUA inputs were released during cleanup:' + const title = state === 'held' ? 'CUA inputs are still held:' : 'CUA inputs were released during cleanup:' return ['', title, ...rows, state === 'held' ? "They remain pressed across programs and turns. Release them explicitly with sendKeyEvent(key, 'up') or toggleMouse(button, 'up') on the same target when no longer needed." - : state === 'program-end' ? 'These inputs are no longer held. In this environment, keep any required hold sequence within one program.' - : 'These inputs are no longer held.', + : 'These inputs are no longer held.', ''].join('\n') } @@ -44,7 +42,7 @@ class InputOwner { this.client = client } - async reminder(): Promise { + async reminder(inTurn: boolean): Promise { if (this.closing || !this.client) return const inputs = heldInputs.parse(await this.client.request('getHeldInputs', { taskId: this.agent.id }, this.controller.signal)) if (inputs.length === 0) { @@ -53,15 +51,10 @@ class InputOwner { this.client = undefined return } - this.notifySessionOnRelease = true + this.notifySessionOnRelease ||= inTurn return renderInputs(inputs, 'held') } - async releaseReminder(): Promise { - if (this.closing) return - const released = await this.close() - return released.length > 0 ? renderInputs(released, 'program-end') : undefined - } close(canRequest = true): Promise> { this.controller.abort() @@ -161,12 +154,11 @@ export class CuaHeldInputs { } else if (execution.parent === undefined) { const owner = this.owners.get(agent) const inTurn = ctx.agents.turnBoundaryOf(agent.session).openTurnStartSeq !== null - const text = inTurn ? await owner?.reminder() : await owner?.releaseReminder() + const text = await owner?.reminder(inTurn) if (signal.aborted) { await this.release(agent); return result } - if (text && (!inTurn || !owner?.closing)) return { ...result, additionalContexts: [...result.additionalContexts ?? [], + if (text && !owner?.closing) return { ...result, additionalContexts: [...result.additionalContexts ?? [], createUserMessage({ content: [{ type: 'text', text }], - source: { kind: inTurn ? 'cua-held-inputs' : 'cua-inputs-released', - form: 'notice', summary: inTurn ? 'CUA inputs remain held' : 'CUA inputs released' } }), + source: { kind: 'cua-held-inputs', form: 'notice', summary: 'CUA inputs remain held' } }), ] } } return result diff --git a/packages/experimental/cua/src/tool-registration.ts b/packages/experimental/cua/src/tool-registration.ts index 308f1d6dd2..35e3c9c097 100644 --- a/packages/experimental/cua/src/tool-registration.ts +++ b/packages/experimental/cua/src/tool-registration.ts @@ -33,6 +33,13 @@ export interface CuaPrograms { * @throws When the process cleanup fails. */ release(agent: Agent): Promise + /** + * Release the Agent's tracked input while retaining its program variables and application grants. + * Providers without held-input state support retain their existing cancellation behavior. + * @param agent - Owner of the input to release. + * @returns Completion after native acknowledgement, or rejection when cleanup is unconfirmed. + */ + releaseInputs(agent: Agent): Promise /** * Request-image target the provider delivered for a stored screenshot when `screenshotTarget` is configured. * A host that forwards screenshots outside a model request reads the same request version with it, so the @@ -68,7 +75,7 @@ export function fixedScreenshotTarget(configured: CuaScreenshotTargetConfig, ima * @param tool Internal native tool; Agents off the configured preset can reach it only through the program. * @param guidance Raw-tool operation instructions for the configured preset. * @param programGuidance Operation instructions available inside cua_run_code. - * @param releaseInputs Release held input when resetting the program environment. + * @param releaseInputs Release tracked input on cancellation or environment reset. * @returns Exact registration disposer, draining programs before native resources can close. */ export function installCuaTools( @@ -157,6 +164,7 @@ var cua = connectCua(() => tools.cua); release: async (agent: Agent) => { try { await consumer.ptcRuntime.release(agent) } finally { await releaseInputs(agent) } }, + releaseInputs, screenshotRequestTarget: image => config.screenshotTarget === undefined ? undefined : fixedScreenshotTarget(config.screenshotTarget, image), } satisfies CuaPrograms) diff --git a/packages/experimental/cua/src/types.ts b/packages/experimental/cua/src/types.ts index cc34ca370c..e4b9f0c993 100644 --- a/packages/experimental/cua/src/types.ts +++ b/packages/experimental/cua/src/types.ts @@ -183,8 +183,8 @@ export interface CuaSurface { pressKey(key: string, modifiers?: string[]): Promise /** * Send one key-down or key-up event at the current input focus. - * In DSH turns, explicit downs persist across programs and turns; successful programs remind about remaining holds. - * Programs outside a DSH turn, including MCP, release remaining input before returning and report the release. + * Explicit downs persist across programs and turns; successful programs remind about remaining holds. + * MCP client pauses between completed calls do not notify the provider and leave held input unchanged. * Program failure, cancellation, connection closure and disposal release owned input. Windows support is pending. * Rejects when the provider does not support keyboard input at this scope. * @param key - Platform-defined key name; modifier keys may themselves be targets. From 5f156cfcbd123220d9dde0954650952c1f3b73ed Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 19 Nov 2026 12:11:11 +0800 Subject: [PATCH 39/73] Cover queued MCP cancellation and failed input cleanup --- .../cua-mcp/tests/composition.spec.ts | 24 +++++++++++++++++++ .../experimental/cua-mcp/tests/server.spec.ts | 20 ++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/packages/experimental/cua-mcp/tests/composition.spec.ts b/packages/experimental/cua-mcp/tests/composition.spec.ts index 2083f55215..d4ea33ad45 100644 --- a/packages/experimental/cua-mcp/tests/composition.spec.ts +++ b/packages/experimental/cua-mcp/tests/composition.spec.ts @@ -238,6 +238,30 @@ describe('Computer Use MCP composition', () => { expect(native.held).toEqual([]) }) + it('reports refused cleanup after a cancelled MCP request and prevents further native input', async () => { + const { ctx, native, run } = await setup() + await run('var app = await cua.getApp("test.fixture"); await app.sendKeyEvent("w", "down")') + const entered: PromiseWithResolvers = Promise.withResolvers() + ctx.on('tools/execute', (execution, next) => { + if (execution.name === 'cua_run_code' && execution.parent === undefined) entered.resolve() + return next() + }) + const release = native.controlNext('releaseHeldInputs') + const controller = new AbortController() + const running = run('await new Promise(() => {})', {}, controller.signal) + const cancelled = expect(running).rejects.toThrow(/abort/i) + await entered.promise + controller.abort() + await release.entered + release.reply({ code: 'INPUT_CLEANUP_FAILED', message: 'Cancellation release refused' }) + await cancelled + const count = native.calls.length + const result = await run('await cua.getApp("test.fixture")') + expect(result.isError).toBe(true) + expect(texts(result).join('')).toContain('INPUT_CLEANUP_UNCONFIRMED') + expect(native.calls).toHaveLength(count) + }) + it('serves three tools, returns the API reference on request, and retains program state in the workspace', async () => { const { ctx, native, client, run, adapter, directory } = await setup() expect(client.getInstructions()).toContain('Start every conversation by calling cua_get_api_reference') diff --git a/packages/experimental/cua-mcp/tests/server.spec.ts b/packages/experimental/cua-mcp/tests/server.spec.ts index c91a843507..1f4ab1a5b7 100644 --- a/packages/experimental/cua-mcp/tests/server.spec.ts +++ b/packages/experimental/cua-mcp/tests/server.spec.ts @@ -347,4 +347,24 @@ describe('Computer Use MCP server', () => { expect(served.dispose).toHaveBeenCalledOnce() await served.client.close() }) + + it('settles a queued request cancelled before admission even without optional input controls', async () => { + const served = await setup({ programs: false }) + const entered: PromiseWithResolvers = Promise.withResolvers() + const finish: PromiseWithResolvers = Promise.withResolvers() + served.execute.mockImplementationOnce(async () => { entered.resolve(); await finish.promise; return batch('first') }) + const first = served.run({ code: 'first' }) + await entered.promise + const controller = new AbortController() + const queued = served.client.callTool({ name: 'cua_run_code', arguments: { code: 'queued' } }, { signal: controller.signal }) + const cancelled = expect(queued).rejects.toThrow(/abort/i) + try { + await served.client.listTools() + controller.abort() + } finally { finish.resolve() } + await Promise.all([first, cancelled]) + await served.run({ code: 'after cancellation' }) + expect(served.execute.mock.calls[1]?.[0].signal.aborted).toBe(true) + }) + }) From 3f328850c19eea2ffb6070d81f34fc8c3819f987 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 19 Nov 2026 12:19:50 +0800 Subject: [PATCH 40/73] Record unified held-input behavior and pause release notices --- .../tests/profiles/cua-mcp/expected/held-inputs.json | 12 ++++++++++++ .../tests/profiles/cua-mcp/expected/instructions.txt | 2 +- .../cli/tests/profiles/cua-mcp/expected/reference.md | 2 +- docs/subsystems/computer-use.md | 8 ++++++++ docs/subsystems/computer-use.zh.md | 8 ++++++++ packages/extensions/tool-cordis/src/api-catalog.ts | 6 ++++++ snapshots/sdk/cua-run-code/system-prompt.expected.md | 2 +- .../session/cua-native/system-prompt.expected.md | 2 +- snapshots/session/cua-ptc/system-prompt.expected.md | 2 +- .../cua-run-code-ptc/system-prompt.expected.md | 2 +- snapshots/session/cua-run-code/session.v4.jsonl | 7 ++++--- .../session/cua-run-code/system-prompt.expected.md | 2 +- .../ptc-script-retained/system-prompt.expected.md | 2 +- 13 files changed, 46 insertions(+), 11 deletions(-) create mode 100644 apps/cli/tests/profiles/cua-mcp/expected/held-inputs.json diff --git a/apps/cli/tests/profiles/cua-mcp/expected/held-inputs.json b/apps/cli/tests/profiles/cua-mcp/expected/held-inputs.json new file mode 100644 index 0000000000..099ba2ed86 --- /dev/null +++ b/apps/cli/tests/profiles/cua-mcp/expected/held-inputs.json @@ -0,0 +1,12 @@ +{ + "content": [ + { + "type": "text", + "text": "Input sequence finished.\n" + }, + { + "type": "text", + "text": "\nCUA inputs are still held:\n- Key \"shift\", appHandle \"fixture-app\" (application input).\n- Mouse left, appHandle \"fixture-app\", windowId \"7\" (window input).\n- Key \"w\", appHandle \"fixture-app\" (application input).\nThey remain pressed across programs and turns. Release them explicitly with sendKeyEvent(key, 'up') or toggleMouse(button, 'up') on the same target when no longer needed.\n" + } + ] +} diff --git a/apps/cli/tests/profiles/cua-mcp/expected/instructions.txt b/apps/cli/tests/profiles/cua-mcp/expected/instructions.txt index fe2768f3dc..aaa6234dad 100644 --- a/apps/cli/tests/profiles/cua-mcp/expected/instructions.txt +++ b/apps/cli/tests/profiles/cua-mcp/expected/instructions.txt @@ -1 +1 @@ -DeepSeek Harness Computer Use: observe and operate desktop applications on this machine. Start every conversation by calling cua_get_api_reference: it returns the complete cua API reference, and programs written without it guess the API wrong. Then call cua_run_code with a TypeScript program that uses the global cua object; program state persists across calls on this connection. A call may ask the user for application or pointer consent before it proceeds. Call cua_reset to discard program state. Remaining held keys and mouse buttons are released before each program returns. A system reminder lists inputs automatically released at program end. Explicit downs cannot stay held across MCP calls. +DeepSeek Harness Computer Use: observe and operate desktop applications on this machine. Start every conversation by calling cua_get_api_reference: it returns the complete cua API reference, and programs written without it guess the API wrong. Then call cua_run_code with a TypeScript program that uses the global cua object; program state persists across calls on this connection. A call may ask the user for application or pointer consent before it proceeds. Call cua_reset to discard program state. Explicit key and mouse downs remain held across successful programs; a system reminder lists remaining holds. Explicit up, program failure, request cancellation, reset, and connection closure release owned input. Client pause between completed calls is not observable by this server and does not release input. diff --git a/apps/cli/tests/profiles/cua-mcp/expected/reference.md b/apps/cli/tests/profiles/cua-mcp/expected/reference.md index 167cfd894c..ca24cca04d 100644 --- a/apps/cli/tests/profiles/cua-mcp/expected/reference.md +++ b/apps/cli/tests/profiles/cua-mcp/expected/reference.md @@ -53,7 +53,7 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. -In DSH, explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. MCP and other programs outside a DSH turn release remaining input before returning and report which inputs were automatically released. No reminder is added when there is nothing to report. Program failure, user stop, connection closure, and disposal release owned inputs together in reverse dispatch order. pressKey, typeText, click, and complete drag release their own inputs within the operation. +Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/docs/subsystems/computer-use.md b/docs/subsystems/computer-use.md index b2b9e8d4bd..51fa464352 100644 --- a/docs/subsystems/computer-use.md +++ b/docs/subsystems/computer-use.md @@ -163,6 +163,14 @@ Host control over the dedicated `cua_run_code` environments; registered as `ctx. */ release(agent: Agent): Promise +/** + * Release the Agent's tracked input while retaining its program variables and application grants. + * Providers without held-input state support retain their existing cancellation behavior. + * @param agent - Owner of the input to release. + * @returns Completion after native acknowledgement, or rejection when cleanup is unconfirmed. + */ +releaseInputs(agent: Agent): Promise + /** * Request-image target the provider delivered for a stored screenshot when `screenshotTarget` is configured. * A host that forwards screenshots outside a model request reads the same request version with it, so the diff --git a/docs/subsystems/computer-use.zh.md b/docs/subsystems/computer-use.zh.md index 4405bc3fcc..cd30d15255 100644 --- a/docs/subsystems/computer-use.zh.md +++ b/docs/subsystems/computer-use.zh.md @@ -163,6 +163,14 @@ Host control over the dedicated `cua_run_code` environments; registered as `ctx. */ release(agent: Agent): Promise +/** + * Release the Agent's tracked input while retaining its program variables and application grants. + * Providers without held-input state support retain their existing cancellation behavior. + * @param agent - Owner of the input to release. + * @returns Completion after native acknowledgement, or rejection when cleanup is unconfirmed. + */ +releaseInputs(agent: Agent): Promise + /** * Request-image target the provider delivered for a stored screenshot when `screenshotTarget` is configured. * A host that forwards screenshots outside a model request reads the same request version with it, so the diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index f6385c3ca0..29fa13bf11 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -1055,6 +1055,12 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ returns: 'Completion after the process has exited and its output has drained.', throws: ['When the process cleanup fails.'], }, + { + signature: 'releaseInputs(agent: Agent): Promise', + description: 'Release the Agent\'s tracked input while retaining its program variables and application grants. Providers without held-input state support retain their existing cancellation behavior.', + parameters: [{ name: 'agent', description: 'Owner of the input to release.' }], + returns: 'Completion after native acknowledgement, or rejection when cleanup is unconfirmed.', + }, { signature: 'screenshotRequestTarget(image: ImageAttachmentRef): ImageRequestTarget | undefined', description: 'Request-image target the provider delivered for a stored screenshot when `screenshotTarget` is configured. A host that forwards screenshots outside a model request reads the same request version with it, so the image a caller sees matches the coordinate space the provider mapped.', diff --git a/snapshots/sdk/cua-run-code/system-prompt.expected.md b/snapshots/sdk/cua-run-code/system-prompt.expected.md index 969740e8a0..7b90ddb906 100644 --- a/snapshots/sdk/cua-run-code/system-prompt.expected.md +++ b/snapshots/sdk/cua-run-code/system-prompt.expected.md @@ -87,7 +87,7 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. -In DSH, explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. MCP and other programs outside a DSH turn release remaining input before returning and report which inputs were automatically released. No reminder is added when there is nothing to report. Program failure, user stop, connection closure, and disposal release owned inputs together in reverse dispatch order. pressKey, typeText, click, and complete drag release their own inputs within the operation. +Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/snapshots/session/cua-native/system-prompt.expected.md b/snapshots/session/cua-native/system-prompt.expected.md index f88245aff2..d4064ef6eb 100644 --- a/snapshots/session/cua-native/system-prompt.expected.md +++ b/snapshots/session/cua-native/system-prompt.expected.md @@ -90,7 +90,7 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. -In DSH, explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. MCP and other programs outside a DSH turn release remaining input before returning and report which inputs were automatically released. No reminder is added when there is nothing to report. Program failure, user stop, connection closure, and disposal release owned inputs together in reverse dispatch order. pressKey, typeText, click, and complete drag release their own inputs within the operation. +Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index 10e7e79a27..a8f33aac4e 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -92,7 +92,7 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. -In DSH, explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. MCP and other programs outside a DSH turn release remaining input before returning and report which inputs were automatically released. No reminder is added when there is nothing to report. Program failure, user stop, connection closure, and disposal release owned inputs together in reverse dispatch order. pressKey, typeText, click, and complete drag release their own inputs within the operation. +Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/snapshots/session/cua-run-code-ptc/system-prompt.expected.md b/snapshots/session/cua-run-code-ptc/system-prompt.expected.md index b950ec6f8d..155346b4eb 100644 --- a/snapshots/session/cua-run-code-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-run-code-ptc/system-prompt.expected.md @@ -88,7 +88,7 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. -In DSH, explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. MCP and other programs outside a DSH turn release remaining input before returning and report which inputs were automatically released. No reminder is added when there is nothing to report. Program failure, user stop, connection closure, and disposal release owned inputs together in reverse dispatch order. pressKey, typeText, click, and complete drag release their own inputs within the operation. +Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/snapshots/session/cua-run-code/session.v4.jsonl b/snapshots/session/cua-run-code/session.v4.jsonl index 36e038510b..00c3bf66a5 100644 --- a/snapshots/session/cua-run-code/session.v4.jsonl +++ b/snapshots/session/cua-run-code/session.v4.jsonl @@ -13,7 +13,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 cua_run_code to select test.fixture,","messageSeqs":[9],"source":{"kind":"fallback"}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); await app.sendKeyEvent(\\\"w\\\", \\\"down\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"stream":[{"type":"chunk","time":1795057086972,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1795057086972,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); await app.sendKeyEvent(\\\"w\\\", \\\"down\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}}},{"type":"chunk","time":1795057086972,"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_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); await app.sendKeyEvent(\\\"w\\\", \\\"down\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"stream":[{"type":"chunk","time":1795061770766,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1795061770766,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); await app.sendKeyEvent(\\\"w\\\", \\\"down\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}}},{"type":"chunk","time":1795061770767,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); await app.sendKeyEvent(\\\"w\\\", \\\"down\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemPointer\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\",\"sendKeyEvent\",\"toggleMouse\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} @@ -33,7 +33,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":"\nCUA inputs are still held:\n- Key \"w\", appHandle \"fixture-app\" (application input).\nThey remain pressed across programs and turns. Release them explicitly with sendKeyEvent(key, 'up') or toggleMouse(button, 'up') on the same target when no longer needed.\n"}],"source":{"kind":"cua-held-inputs","form":"notice","summary":"CUA inputs remain held"},"role":"user","id":"{{message:6}}"},"surfaceOp":"append"} -{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua_reuse","name":"cua_run_code","arguments":"{\"code\":\"await app.sendKeyEvent(\\\"w\\\", \\\"up\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) })); await win.toggleMouse(\\\"left\\\", \\\"down\\\"); await app.sendKeyEvent(\\\"d\\\", \\\"down\\\")\",\"description\":\"Reuse the retained application and window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:7}}"},"stream":[{"type":"chunk","time":1795057087286,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1795057087286,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_reuse","name":"cua_run_code","arguments":"{\"code\":\"await app.sendKeyEvent(\\\"w\\\", \\\"up\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) })); await win.toggleMouse(\\\"left\\\", \\\"down\\\"); await app.sendKeyEvent(\\\"d\\\", \\\"down\\\")\",\"description\":\"Reuse the retained application and window\"}"}}},{"type":"chunk","time":1795057087286,"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_reuse","name":"cua_run_code","arguments":"{\"code\":\"await app.sendKeyEvent(\\\"w\\\", \\\"up\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) })); await win.toggleMouse(\\\"left\\\", \\\"down\\\"); await app.sendKeyEvent(\\\"d\\\", \\\"down\\\")\",\"description\":\"Reuse the retained application and window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:7}}"},"stream":[{"type":"chunk","time":1795061771077,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1795061771077,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_reuse","name":"cua_run_code","arguments":"{\"code\":\"await app.sendKeyEvent(\\\"w\\\", \\\"up\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) })); await win.toggleMouse(\\\"left\\\", \\\"down\\\"); await app.sendKeyEvent(\\\"d\\\", \\\"down\\\")\",\"description\":\"Reuse the retained application and window\"}"}}},{"type":"chunk","time":1795061771077,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"cua_reuse","name":"cua_run_code","arguments":"{\"code\":\"await app.sendKeyEvent(\\\"w\\\", \\\"up\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) })); await win.toggleMouse(\\\"left\\\", \\\"down\\\"); await app.sendKeyEvent(\\\"d\\\", \\\"down\\\")\",\"description\":\"Reuse the retained application and window\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:1","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"w","direction":"up"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:1","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"w","direction":"up"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} @@ -53,6 +53,7 @@ {"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":"\nCUA inputs are still held:\n- Mouse left, appHandle \"fixture-app\", windowId \"7\" (window input).\n- Key \"d\", appHandle \"fixture-app\" (application input).\nThey remain pressed across programs and turns. Release them explicitly with sendKeyEvent(key, 'up') or toggleMouse(button, 'up') on the same target when no longer needed.\n"}],"source":{"kind":"cua-held-inputs","form":"notice","summary":"CUA inputs remain held"},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} -{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"text","text":"The retained application and window report Count: 2. The counter persisted across calls, and the program exposes only tools.cua. The screenshot was attached after the first call."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:10}}"},"stream":[{"type":"chunk","time":1795057087322,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1795057087322,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"The retained application and window report Count: 2. The counter persisted across calls, and the program exposes only tools.cua. The screenshot was attached after the first call."}}},{"type":"chunk","time":1795057087322,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"text","text":"The retained application and window report Count: 2. The counter persisted across calls, and the program exposes only tools.cua. The screenshot was attached after the first call."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:10}}"},"stream":[{"type":"chunk","time":1795061771116,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1795061771116,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"The retained application and window report Count: 2. The counter persisted across calls, and the program exposes only tools.cua. The screenshot was attached after the first call."}}},{"type":"chunk","time":1795061771116,"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"}}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"\nCUA inputs were released during cleanup:\n- Key \"d\", appHandle \"fixture-app\" (application input).\n- Mouse left, appHandle \"fixture-app\", windowId \"7\" (window input).\nThese inputs are no longer held.\n"}],"source":{"kind":"cua-inputs-released","form":"notice","summary":"CUA inputs released"},"role":"user","id":"{{message:11}}"}]}} diff --git a/snapshots/session/cua-run-code/system-prompt.expected.md b/snapshots/session/cua-run-code/system-prompt.expected.md index d0d5cf3e23..7acc0f5667 100644 --- a/snapshots/session/cua-run-code/system-prompt.expected.md +++ b/snapshots/session/cua-run-code/system-prompt.expected.md @@ -86,7 +86,7 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. -In DSH, explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. MCP and other programs outside a DSH turn release remaining input before returning and report which inputs were automatically released. No reminder is added when there is nothing to report. Program failure, user stop, connection closure, and disposal release owned inputs together in reverse dispatch order. pressKey, typeText, click, and complete drag release their own inputs within the operation. +Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/snapshots/session/ptc-script-retained/system-prompt.expected.md b/snapshots/session/ptc-script-retained/system-prompt.expected.md index a15bda60c7..37e5d1d56e 100644 --- a/snapshots/session/ptc-script-retained/system-prompt.expected.md +++ b/snapshots/session/ptc-script-retained/system-prompt.expected.md @@ -92,7 +92,7 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. -In DSH, explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. MCP and other programs outside a DSH turn release remaining input before returning and report which inputs were automatically released. No reminder is added when there is nothing to report. Program failure, user stop, connection closure, and disposal release owned inputs together in reverse dispatch order. pressKey, typeText, click, and complete drag release their own inputs within the operation. +Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. From 862f20df85638eea08df1e3c84e3c08ac2b32324 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 19 Nov 2026 12:24:16 +0800 Subject: [PATCH 41/73] Declare precise input notice sources and refresh persisted output catalogs --- docs/persistence-catalog.i18n.yaml | 120 +++++++++-------- docs/persistence-catalog.md | 128 ++++++++++++------- docs/persistence-catalog.zh.md | 128 ++++++++++++------- docs/persistence-schema.json | 68 +++++----- packages/experimental/cua/src/held-inputs.ts | 5 +- packages/experimental/cua/src/types.ts | 4 +- snapshots/web/cua-run-code/ui.expected.md | 2 + 7 files changed, 282 insertions(+), 173 deletions(-) diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index 73ca9368d8..abe33f4766 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -9,8 +9,8 @@ en: 1387c4505dde2faf zh: 48570fa1c13d6910 /session-persistence-event-catalog/persistence-type-fingerprints: - en: 3de1bc82a91b1fda - zh: e4268205f18b81e8 + en: f044805846548e03 + zh: 56f2cadf60d53f07 /session-persistence-event-catalog/event-envelope: en: 5cae0233560db4d6 zh: c8f5efc48be52095 @@ -447,8 +447,14 @@ en: 1139922866668927 zh: 1139922866668927 /session-persistence-event-catalog/resolved-persistence-types/create: - en: 43008071d7f2787a - zh: 43008071d7f2787a + en: 3b01b31b73b97f9b + zh: 3b01b31b73b97f9b +/session-persistence-event-catalog/resolved-persistence-types/cua-held-inputs: + en: 32bea85c24c54dc6 + zh: 32bea85c24c54dc6 +/session-persistence-event-catalog/resolved-persistence-types/cua-inputs-released: + en: 41141c29ec14954f + zh: 41141c29ec14954f /session-persistence-event-catalog/resolved-persistence-types/danger-full-access: en: f7c17b7b2874f5f4 zh: f7c17b7b2874f5f4 @@ -1038,11 +1044,11 @@ en: a6a2e38fdd6d127a zh: 1fe82356d89f5769 /session-persistence-event-catalog/resolved-persistence-types/deepseeksearchllmrequest: - en: c2b2df63604aa276 - zh: ae73f57f53bb85a0 + en: 0f1edca41122c80b + zh: 2580cfdc1c15d6dc /session-persistence-event-catalog/resolved-persistence-types/developermessage: - en: a3f7241ba795de1e - zh: 084d2dd90601b2b3 + en: e62053309e27edca + zh: 65928e2b5a34e2aa /session-persistence-event-catalog/resolved-persistence-types/epochheader: en: fa7fd1a765a494e2 zh: fd8e6fdd37d986cf @@ -1152,11 +1158,11 @@ en: 6dbe099c62f7c226 zh: 6fd788f63c038c91 /session-persistence-event-catalog/resolved-persistence-types/llmretrystartedeventdata: - en: 43a03018774afdb4 - zh: 5759aca7d706bf82 + en: f296cf148adbc514 + zh: dcba18cde27563c5 /session-persistence-event-catalog/resolved-persistence-types/message: - en: 306e5ce73c068078 - zh: ea083b295f6821ad + en: 78cf1230219784a0 + zh: 1e89d2c4ae367d2a /session-persistence-event-catalog/resolved-persistence-types/messagefeedbackdelete: en: c582953270d4ca44 zh: 966ccfe2e7660a2a @@ -1167,14 +1173,14 @@ en: f58575a1fc96df42 zh: 9f0c6ed9033e5c9d /session-persistence-event-catalog/resolved-persistence-types/messagefeedbackrating: - en: d2a0b0ad71c0d335 - zh: d11dd6deea395886 + en: 23dee8a05b584a0c + zh: e184d6f6796cea33 /session-persistence-event-catalog/resolved-persistence-types/messagesource: - en: 9521558a9dc6d38d - zh: 8f6f0e1ff972d32c + en: 0129498e95a07fb1 + zh: 49a4e778c15f7ce5 /session-persistence-event-catalog/resolved-persistence-types/message~2: - en: c0e7625fd450e041 - zh: 3dcfa3d131de5897 + en: 61129eaa2afc7793 + zh: 74902afb703bf311 /session-persistence-event-catalog/resolved-persistence-types/modelmessagesource: en: 65a618e2ec94bbc4 zh: 622197f4b127068b @@ -1233,11 +1239,11 @@ en: 9a54c4478ad3b620 zh: 02c4c1fd7e252770 /session-persistence-event-catalog/resolved-persistence-types/sessiontitleeventdata: - en: 6cf1e7c94a274a24 - zh: 2bce42bf52d0e574 + en: 2203fea5be127453 + zh: be02e9a6dd9b24c3 /session-persistence-event-catalog/resolved-persistence-types/sessiontitlellmrequesteventdata: - en: 20ffa8747ad5abab - zh: 836ca9717eafedf3 + en: a00fc8f0fbb62a99 + zh: 18746c84576db00a /session-persistence-event-catalog/resolved-persistence-types/sessiontitlemodelidentity: en: 7a7245bb23c38655 zh: 6d96a94c367fbe64 @@ -1347,14 +1353,14 @@ en: 73fde4d98617b19f zh: adae612c15a67764 /session-persistence-event-catalog/resolved-persistence-types/turnendreason: - en: 8b69c6e26f5843ad - zh: 7515d5a3f2419709 + en: d3512b982a190e1e + zh: c8c77b4627e2e2c7 /session-persistence-event-catalog/resolved-persistence-types/usermessage: - en: da2ff374580fcaa8 - zh: b92e64d68122c337 + en: 6176209d594c2db2 + zh: 745b411d0dc5f266 /session-persistence-event-catalog/resolved-persistence-types/usermessage~2: - en: 6410d8545a391c2b - zh: d9e90b3c5796f76a + en: 7a002d97d64132cd + zh: 3d651597a6a17e6b /session-persistence-event-catalog/resolved-persistence-types/workflowagentoutcome: en: 711564ea7898e156 zh: 36b88b84a6dc3c7e @@ -1551,11 +1557,11 @@ en: 4cb1c48095df98dc zh: 5a03e44761af559e /session-persistence-event-catalog/resolved-persistence-types/header-reason-startsseries: - en: 025df3bb1bbc5369 - zh: 52015f4decd2f1e5 + en: a930063441ca3f59 + zh: 8c17328c4cbcd66c /session-persistence-event-catalog/resolved-persistence-types/headerseq-message-step-turn: - en: e06f7b64a1665de2 - zh: cc2280a56d63cb50 + en: 20a8f7e459f18c6c + zh: 32c66d976656d9fe /session-persistence-event-catalog/resolved-persistence-types/height-width: en: a5df50710083ac25 zh: aad3ccf6f6de70e4 @@ -1572,11 +1578,11 @@ en: 41f73c58a77dfa28 zh: af77f4aee3cb4a40 /session-persistence-event-catalog/resolved-persistence-types/inherited: - en: 828241cf325d2bec - zh: f53b66d8e6e8a41c + en: 35ff867953cfe7ac + zh: e70e7a6d3b536ed6 /session-persistence-event-catalog/resolved-persistence-types/inserted-outcome-removedcount-start: - en: cdd4832101b8d5c1 - zh: a98f9c6cb6701d78 + en: cf0ff21353dd80ca + zh: 6fc4775c2e1e5ee3 /session-persistence-event-catalog/resolved-persistence-types/interrupted-message-step-stream: en: 35e45d462a41e963 zh: 89953d22ddada652 @@ -1611,8 +1617,14 @@ en: 816fb33ba156fb05 zh: 313418efece50a66 /session-persistence-event-catalog/resolved-persistence-types/kind-cordis-host-runner: - en: e1fa1148ddbc8aa5 - zh: 1b8e71ec4dd6cbb3 + en: 5fe1073ecf3d288a + zh: 9a6921c6f2c42066 +/session-persistence-event-catalog/resolved-persistence-types/kind-cua-held-inputs-form-notice: + en: f4925e26d98a7ce7 + zh: 059d7b9474f7c9de +/session-persistence-event-catalog/resolved-persistence-types/kind-cua-inputs-released-form-notice: + en: 3dbe03c5f2048836 + zh: 723cd5f33af39a76 /session-persistence-event-catalog/resolved-persistence-types/kind-disposed: en: e373f887d953f75f zh: 61fe50b74eaf2040 @@ -2001,11 +2013,11 @@ en: e0d6826170f96136 zh: c684a666de7cee7c /session-persistence-event-catalog/resolved-persistence-types/type-agent-preset-selected: - en: 3ffd4ea16273b2e2 - zh: 0f8cc2f25c129db2 + en: eb0e9f71aa92b3cd + zh: 6288421ef585fdfb /session-persistence-event-catalog/resolved-persistence-types/type-agent-inbox-spliced: - en: 8595e5be01110031 - zh: e53835bbc7208402 + en: 234800e94184ff42 + zh: bb685369ff3a79d2 /session-persistence-event-catalog/resolved-persistence-types/type-approval-asked: en: 9c77f18b0dad22f0 zh: 8894cf2878fe90db @@ -2049,11 +2061,11 @@ en: ba73fb10b7e2ffc9 zh: 8d5c97e63e5f16da /session-persistence-event-catalog/resolved-persistence-types/type-deliverables-presented: - en: dee59c4cab27840e - zh: d2203a7a79799d1d + en: a4a14fdc238315d8 + zh: 696a87834f826e13 /session-persistence-event-catalog/resolved-persistence-types/type-developer-message: - en: 5c0287505cfa913b - zh: 5e783b2e19464855 + en: ab59e7867ea561e0 + zh: 0760e8e9127632e4 /session-persistence-event-catalog/resolved-persistence-types/type-disabled: en: 04db8a26a3befdd4 zh: 8b24a37ac00bac8a @@ -2127,11 +2139,11 @@ en: acf7e21e4d21ebff zh: fb83a853634d204a /session-persistence-event-catalog/resolved-persistence-types/type-session-title: - en: d138c51e1202a7f0 - zh: 80bc77ae672ad43e + en: 122888f402720093 + zh: 741a0f027ff93079 /session-persistence-event-catalog/resolved-persistence-types/type-session-title-llm-request: - en: 88d1abda906b892d - zh: 010692a91ea0139d + en: 08d5b992a2f2594c + zh: abc86bfb0229a052 /session-persistence-event-catalog/resolved-persistence-types/type-step-end: en: 7fc233c4a569dae2 zh: bc2b3fed4a397c00 @@ -2211,11 +2223,11 @@ en: 1b045de96172be4b zh: 8a15c6f35b576b37 /session-persistence-event-catalog/resolved-persistence-types/type-usage: - en: 0ce623d4c59f5a2f - zh: 2d830e6e1badb1ba + en: 95fa337640c4bf55 + zh: 06d27ee9c089f2ce /session-persistence-event-catalog/resolved-persistence-types/type-user-message: - en: 6e4884da342f291a - zh: 454973316ff24910 + en: d7078bb1c19c08ea + zh: 4281deb82d1d260e /session-persistence-event-catalog/resolved-persistence-types/type-web-deepseek-search-llm-request: en: 99c8837344178a47 zh: bf746f5678346596 diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index ea4be01ac2..1f7d6491c9 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -23,7 +23,7 @@ The [format references](persistence-changes/historical-formats/README.md) cover | `JsonlHeaderLine` | header | `18ee62b8900a4c3d046700f05d7a4d49d6cab2a660a020c87481d1603dd8bd4f` | [`HeaderLine`](#persistence-type-sha256-18ee62b8900a4c3d046700f05d7a4d49d6cab2a660a020c87481d1603dd8bd4f) | | `SessionEventEnvelope` | envelope | `5776e5553ff2dfe3f5bc202dbb1e7c9f93e35a531aebb7764c23b2b6153b2ccc` | [`union (3 variants)`](#persistence-type-sha256-5776e5553ff2dfe3f5bc202dbb1e7c9f93e35a531aebb7764c23b2b6153b2ccc) | | `event:agent-preset/selected` | event | `a10c17474eaf2ddab7095a099e0fe3d046fc18e56c3e344fc8894c05ff9ef97b` | [`{ type: "agent-preset/selected" }`](#persistence-type-sha256-a10c17474eaf2ddab7095a099e0fe3d046fc18e56c3e344fc8894c05ff9ef97b) | -| `event:agent/inbox/spliced` | event | `f5d843edb0eeef61c9f5328599d5f92b61112b7710b0310b043196b15b390d64` | [`{ type: "agent/inbox/spliced" }`](#persistence-type-sha256-f5d843edb0eeef61c9f5328599d5f92b61112b7710b0310b043196b15b390d64) | +| `event:agent/inbox/spliced` | event | `0880996d224033d9a668528f51edf5f229d9b07dda42fb65f7d1cc1150c12836` | [`{ type: "agent/inbox/spliced" }`](#persistence-type-sha256-0880996d224033d9a668528f51edf5f229d9b07dda42fb65f7d1cc1150c12836) | | `event:approval/asked` | event | `3bfeb47b58606f4661904bc723da612782214c463d01e6d61cd6d6193d7374e1` | [`{ type: "approval/asked" }`](#persistence-type-sha256-3bfeb47b58606f4661904bc723da612782214c463d01e6d61cd6d6193d7374e1) | | `event:approval/decided` | event | `bb1ab3d08f49a9f3b265f844cd78d5c49813062a7b34b54904b426f85d0ff6e3` | [`{ type: "approval/decided" }`](#persistence-type-sha256-bb1ab3d08f49a9f3b265f844cd78d5c49813062a7b34b54904b426f85d0ff6e3) | | `event:approval/policy` | event | `26718e15e7e395bce9642dba5bbe09b3b1a4ce2213d20d566cd9207d7fc5fb78` | [`{ type: "approval/policy" }`](#persistence-type-sha256-26718e15e7e395bce9642dba5bbe09b3b1a4ce2213d20d566cd9207d7fc5fb78) | @@ -36,7 +36,7 @@ The [format references](persistence-changes/historical-formats/README.md) cover | `event:compaction/start` | event | `db874d463b0fdec77e9da1c4568f37cb70bd6596781eb93800db44fb8a116965` | [`{ type: "compaction/start" }`](#persistence-type-sha256-db874d463b0fdec77e9da1c4568f37cb70bd6596781eb93800db44fb8a116965) | | `event:compaction/summary` | event | `e2f9a41e0989f54ed8cee80f8db2bcf9d60a5c810dc9d45b83fa050b9dce7602` | [`{ type: "compaction/summary" }`](#persistence-type-sha256-e2f9a41e0989f54ed8cee80f8db2bcf9d60a5c810dc9d45b83fa050b9dce7602) | | `event:deliverables/presented` | event | `13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176` | [`{ type: "deliverables/presented" }`](#persistence-type-sha256-13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176) | -| `event:developer/message` | event | `7ee5a828196d9e4b1672f94f977e68f37125da4297c23029dd682823c09e12fd` | [`{ type: "developer/message" }`](#persistence-type-sha256-7ee5a828196d9e4b1672f94f977e68f37125da4297c23029dd682823c09e12fd) | +| `event:developer/message` | event | `3a6f3e4354a90287bb3a1fb19e7a2f643cdbd7c6472c865abd11f8fa2d3358d5` | [`{ type: "developer/message" }`](#persistence-type-sha256-3a6f3e4354a90287bb3a1fb19e7a2f643cdbd7c6472c865abd11f8fa2d3358d5) | | `event:feedback/message-delete` | event | `3ee93b06f3a125850337602bcdf155d2538c43a5c944ec55b1b3c365152d6796` | [`{ type: "feedback/message-delete" }`](#persistence-type-sha256-3ee93b06f3a125850337602bcdf155d2538c43a5c944ec55b1b3c365152d6796) | | `event:feedback/message-put` | event | `b5086d249e8502e9ead1d39156bb8d559bde7951cac0f14ce150345b4e42a2bf` | [`{ type: "feedback/message-put" }`](#persistence-type-sha256-b5086d249e8502e9ead1d39156bb8d559bde7951cac0f14ce150345b4e42a2bf) | | `event:feedback/record` | event | `b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8` | [`{ type: "feedback/record" }`](#persistence-type-sha256-b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8) | @@ -58,7 +58,7 @@ The [format references](persistence-changes/historical-formats/README.md) cover | `event:session-log-deepseek/delivery-accepted` | event | `d63b8b8ffad9c02fd80c43a17df4f240c1fe8118ecca9de34f9d5871838ab5b9` | [`{ type: "session-log-deepseek/delivery-accepted" }`](#persistence-type-sha256-d63b8b8ffad9c02fd80c43a17df4f240c1fe8118ecca9de34f9d5871838ab5b9) | | `event:session/end-seed` | event | `5e6db6e24948d4a853c71cb9fabd252ad051ce93d4672c1266cf837c1c17b84e` | [`{ type: "session/end-seed" }`](#persistence-type-sha256-5e6db6e24948d4a853c71cb9fabd252ad051ce93d4672c1266cf837c1c17b84e) | | `event:session/title` | event | `1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5` | [`{ type: "session/title" }`](#persistence-type-sha256-1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5) | -| `event:session/title-llm-request` | event | `4ee17e4219bd5fab6148ec0a8b3ec0fb939edb8f211374cf779bc8135ef9bed2` | [`{ type: "session/title-llm-request" }`](#persistence-type-sha256-4ee17e4219bd5fab6148ec0a8b3ec0fb939edb8f211374cf779bc8135ef9bed2) | +| `event:session/title-llm-request` | event | `4e81b0490558b80c87cd09b214cd958ce0df1bf2bb431c930ff8fd441a8d1df5` | [`{ type: "session/title-llm-request" }`](#persistence-type-sha256-4e81b0490558b80c87cd09b214cd958ce0df1bf2bb431c930ff8fd441a8d1df5) | | `event:step/end` | event | `e0a787e6ec76c7c94fecbc501b489164ab0293db05bc947914077ad01e674f05` | [`{ type: "step/end" }`](#persistence-type-sha256-e0a787e6ec76c7c94fecbc501b489164ab0293db05bc947914077ad01e674f05) | | `event:step/start` | event | `4513e088d43e6c68425be30451b9f961cc264fe7318ca62681c41d4d78615986` | [`{ type: "step/start" }`](#persistence-type-sha256-4513e088d43e6c68425be30451b9f961cc264fe7318ca62681c41d4d78615986) | | `event:subagent/catalog` | event | `d49164d37eab0f0f70fa787c65d887abbea869c010ccb103d717fab3519c3a41` | [`{ type: "subagent/catalog" }`](#persistence-type-sha256-d49164d37eab0f0f70fa787c65d887abbea869c010ccb103d717fab3519c3a41) | @@ -81,7 +81,7 @@ The [format references](persistence-changes/historical-formats/README.md) cover | `event:tool/result` | event | `7c9f44e90a0058f4cc532ae20dad0c10afa6eba22e70a6c79fc79490bad64397` | [`{ type: "tool/result" }`](#persistence-type-sha256-7c9f44e90a0058f4cc532ae20dad0c10afa6eba22e70a6c79fc79490bad64397) | | `event:turn/end` | event | `0f8512903d94f57a4748fa1a2092e64342856796684e6b8343db685b192745ce` | [`{ type: "turn/end" }`](#persistence-type-sha256-0f8512903d94f57a4748fa1a2092e64342856796684e6b8343db685b192745ce) | | `event:turn/start` | event | `aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8` | [`{ type: "turn/start" }`](#persistence-type-sha256-aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8) | -| `event:user/message` | event | `fb6a6e338625067ac582f55dde412a583040cd738bb8fc6820cb0b941c59f05a` | [`{ type: "user/message" }`](#persistence-type-sha256-fb6a6e338625067ac582f55dde412a583040cd738bb8fc6820cb0b941c59f05a) | +| `event:user/message` | event | `507043f63e859f272ce78f6bc65a7361ee087e5e06301f9c100302230bc887a7` | [`{ type: "user/message" }`](#persistence-type-sha256-507043f63e859f272ce78f6bc65a7361ee087e5e06301f9c100302230bc887a7) | | `event:web/deepseek-search-llm-request` | event | `0c556c9b9f2a96238a6b9bbb99e748206cbff2ed6203041c9571f04ae5802f52` | [`{ type: "web/deepseek-search-llm-request" }`](#persistence-type-sha256-0c556c9b9f2a96238a6b9bbb99e748206cbff2ed6203041c9571f04ae5802f52) | | `event:working-directory/change` | event | `124aa62078ca3311353b39cc3bf6c75da281338be6bbf672f8b361d828cddca3` | [`{ type: "working-directory/change" }`](#persistence-type-sha256-124aa62078ca3311353b39cc3bf6c75da281338be6bbf672f8b361d828cddca3) | | `event:workspace-root/change` | event | `025f11632cd02aaecc23a46c3b5bf43b9009d88293ed9b35ccbc1139d73334dc` | [`{ type: "workspace-root/change" }`](#persistence-type-sha256-025f11632cd02aaecc23a46c3b5bf43b9009d88293ed9b35ccbc1139d73334dc) | @@ -1726,6 +1726,22 @@ SHA-256: `7624ca28c61ca0eaa4f015140f3cea6e0c16cce2f2960fab5f531203d253903e` `"create"` + + +### `"cua-held-inputs"` + +SHA-256: `9d42da116fccdc399c2877bb46488c6690e3968c02de6ff2a55e83adc67cc496` + +`"cua-held-inputs"` + + + +### `"cua-inputs-released"` + +SHA-256: `a6816f39283ae26f0cd16cfce35724eb676a1f1b57afbc91094a36b2d2a40b2d` + +`"cua-inputs-released"` + ### `"danger-full-access"` @@ -3464,7 +3480,7 @@ Sources: [`packages/web/web-search-deepseek/src/provider.ts:56`](../packages/web | `body` | required | [`{ max_tokens, messages, model, thinking?, … }`](#persistence-type-sha256-9c001ecb5e1d3c3894410db2a1e383842e5f8454fb52182338686158abc1b3ee) | | `endpoint` | required | `string` | - + @@ -3472,7 +3488,7 @@ Sources: [`packages/web/web-search-deepseek/src/provider.ts:56`](../packages/web ### `DeveloperMessage` -SHA-256: `010783c095f1d9bddbdd2000f3f0a2d31e2ba4a687f2dabf169c5703b98c9def` +SHA-256: `b0e809a7fc2b90682c073e6a137f65fc2e93730ff28e3d6df39b785e71e8a497` Sources: [`packages/llm/llm/src/message.ts:156`](../packages/llm/llm/src/message.ts) @@ -3481,7 +3497,7 @@ Sources: [`packages/llm/llm/src/message.ts:156`](../packages/llm/llm/src/message | `content` | required | [`ContentBlock[]`](#persistence-type-sha256-b52f215a6cd691058a3413c12f161fa3b563a2f4895adb3df6f744ec4b0a6ef1) | | `id` | required | `string` | | `role` | required | `"developer"` | -| `source` | required | [`MessageSource`](#persistence-type-sha256-394ffa61d7dc84ebfd56ad772b59e47be136b95b9549ebf0b77a3bbebf4ce6cc) | +| `source` | required | [`MessageSource`](#persistence-type-sha256-694b070275bbc9a60149e8c669757eab8852dce090484c1a4b45f4c5343be2c8) | Source compatibility: `source` — `session-source-attribution` v1; `session.developer-message.source`; `kind`; `preserve`. @@ -4180,7 +4196,7 @@ Sources: [`packages/llm/llm-retry/src/types.ts:43`](../packages/llm/llm-retry/sr | `step` | required | `number` | | `turn` | required | `number` | - + @@ -4188,15 +4204,15 @@ Sources: [`packages/llm/llm-retry/src/types.ts:43`](../packages/llm/llm-retry/sr ### `Message` -SHA-256: `45e3a4c397121e1a2a455c990b4d45852111b64909ced474d41b9f977ac592a4` +SHA-256: `e744baea6a5d54efc05ce47ebae956fc138a76dad8e605f49b5a7f1c294823a8` Sources: [`packages/llm/llm/src/message.ts:195`](../packages/llm/llm/src/message.ts) One of: - [`ToolResultMessage`](#persistence-type-sha256-4b259f7f8f0a44ad5e90b70a73553ced1df27012d126921d397ff403b6c86731) -- [`DeveloperMessage`](#persistence-type-sha256-010783c095f1d9bddbdd2000f3f0a2d31e2ba4a687f2dabf169c5703b98c9def) -- [`UserMessage`](#persistence-type-sha256-0aed9f5c80e82b6e80e92eace5b9e23cd5e58c567d37b4321cd147d51342e212) +- [`DeveloperMessage`](#persistence-type-sha256-b0e809a7fc2b90682c073e6a137f65fc2e93730ff28e3d6df39b785e71e8a497) +- [`UserMessage`](#persistence-type-sha256-69668f0ad0aabae22bb371efe471e202bcd915f88ca269b95e7ba9b062880f48) - [`SystemMessage`](#persistence-type-sha256-09f3f8dc417f278257202714132f98ba7b52957d7b558c4a04456603890eb363) - [`AssistantMessage`](#persistence-type-sha256-fa87537f4a9c1e25602990a8bf686b383e9e00352ec8946e16ae24ba7c1625be) @@ -4273,7 +4289,7 @@ One of: - `"negative"` - `"positive"` - + @@ -4281,7 +4297,7 @@ One of: ### `MessageSource` -SHA-256: `394ffa61d7dc84ebfd56ad772b59e47be136b95b9549ebf0b77a3bbebf4ce6cc` +SHA-256: `694b070275bbc9a60149e8c669757eab8852dce090484c1a4b45f4c5343be2c8` Sources: [`packages/llm/llm/src/message.ts:135`](../packages/llm/llm/src/message.ts) @@ -4298,6 +4314,8 @@ Sources: [`packages/llm/llm/src/message.ts:135`](../packages/llm/llm/src/message | `agent-message` | `"relay"` | `senderSessionId`: `string` | [`AgentMessageSource`](#persistence-type-sha256-4a9bef9f27a942520cc2279ca7dd3082556e4bff543f66b5c0333e1bbed1cd86) | | `compact-checkpoint` | not declared | `compactionId`: `string` | [`CompactionCheckpointSource`](#persistence-type-sha256-31907de9563751822af6d9be02bafaf26faa098bbd1cb412524134d577cc1648) | | `cordis-host-runner` | not declared | none | [`{ kind: "cordis-host-runner" }`](#persistence-type-sha256-02b2c23f2d94b028c9588a8faace3fce1217405db346da3389368b495457bf79) | +| `cua-held-inputs` | `"notice"` | `summary`: `string` | [`{ kind: "cua-held-inputs", form: "notice" }`](#persistence-type-sha256-8a2e3e7a523e622b440e444ab934154ba53c0037ad6502437abba4365a852e21) | +| `cua-inputs-released` | `"notice"` | `summary`: `string` | [`{ kind: "cua-inputs-released", form: "notice" }`](#persistence-type-sha256-ce6e647c9e653b5d496d551f9e48980ceafc8eb0e6b4093f0b3e4da55164c99b) | | `dsh-session-title-llm` | `"catalog"` | none | [`{ kind: "dsh-session-title-llm", form: "catalog" }`](#persistence-type-sha256-80677c8c8b804189a0fde8aa70dd4ad7af8bb12dfd03027e8e023c8592c838bc) | | `dsh-session-title-llm` | `"instructions"` | none | [`{ kind: "dsh-session-title-llm", form: "instructions" }`](#persistence-type-sha256-224aa11d4d5f88c450822d01b99e6ca5e3a9c7f26a5ede10bae33384a09ef4dc) | | `dsh-session-title-llm` | `"notice"` | `summary`: `string` | [`{ kind: "dsh-session-title-llm", form: "notice" }`](#persistence-type-sha256-8338ee303e2bd448e9e6144069942f63e3cfd5868962bddc9347d7009e8919d6) | @@ -4408,13 +4426,13 @@ Sources: [`packages/llm/llm/src/message.ts:135`](../packages/llm/llm/src/message | `webhook` | `"notice"` | `deliveryId`: `string`; `provider`: `string`; `ruleId`: `string`; `source`: `string`; `summary`: `string` | [`{ kind: "webhook", form: "notice" }`](#persistence-type-sha256-9edc162949abf93bd5ff049191b345454ba104f583937ce5580fb50f067d2b94) | | `working-directory` | not declared | none | [`{ kind: "working-directory" }`](#persistence-type-sha256-2235d957bf4b7c6cf959231d480f0ba1f3a6d72d82981493fb6c7c963021d3d5) | - + ### `Message[]` -SHA-256: `39fe981d6583647fe76f121c43bd6eac1f1a0d6707297f0901b3078899f9ac92` +SHA-256: `e973903c6f32109ccaaceba75f6c6cec33fe7f8d684e24627760cc53916af848` -Array of [`Message`](#persistence-type-sha256-45e3a4c397121e1a2a455c990b4d45852111b64909ced474d41b9f977ac592a4). +Array of [`Message`](#persistence-type-sha256-e744baea6a5d54efc05ce47ebae956fc138a76dad8e605f49b5a7f1c294823a8). @@ -4782,7 +4800,7 @@ Sources: [`packages/session/session-title/src/types.ts:41`](../packages/session/ | `source` | required | [`SessionTitleSource`](#persistence-type-sha256-30d5a537b296685770b1241c4b4bbde19d5a31ff81aa23df73fab5e90b8fc65f) | | `title` | required | `string` | - + @@ -4790,7 +4808,7 @@ Sources: [`packages/session/session-title/src/types.ts:41`](../packages/session/ ### `SessionTitleLlmRequestEventData` -SHA-256: `ee4277d9b4c96ab0a024b3c65d294712b6721808c564162bce7f7feed40c139f` +SHA-256: `c071d01c76a37f9fee2f29616b0aac535c87d4375d6131ef2794962be950b55e` Sources: [`packages/session/session-title-llm/src/index.ts:43`](../packages/session/session-title-llm/src/index.ts) @@ -4798,7 +4816,7 @@ Sources: [`packages/session/session-title-llm/src/index.ts:43`](../packages/sess |---|---|---| | `maxTokens` | required | `number` | | `messageSeqs` | required | [`number[]`](#persistence-type-sha256-5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78) | -| `messages` | required | [`Message[]`](#persistence-type-sha256-39fe981d6583647fe76f121c43bd6eac1f1a0d6707297f0901b3078899f9ac92) | +| `messages` | required | [`Message[]`](#persistence-type-sha256-e973903c6f32109ccaaceba75f6c6cec33fe7f8d684e24627760cc53916af848) | | `reasoningEffort` | optional | `string` | | `route` | required | [`SessionTitleModelIdentity`](#persistence-type-sha256-07e1a58c58b593f507b8e7f25723bb0aa42baae6e00f5ecfddf28cb1e64d3235) | | `system` | required | `string` | @@ -5477,7 +5495,7 @@ Sources: [`packages/core/session/src/types.ts:242`](../packages/core/session/src | `interrupted` | not declared | none | [`{ kind: "interrupted" }`](#persistence-type-sha256-56b7c047694875a843ba020dfea3c8380d54ae4ff88ab349e72004dc21e07c23) | | `max-tokens` | not declared | none | [`{ kind: "max-tokens" }`](#persistence-type-sha256-ab7ec5f9eb2c6dfacca5da4c37cf7ba85d04172053ee6b1ebf1709ffcd99c1a7) | - + @@ -5485,7 +5503,7 @@ Sources: [`packages/core/session/src/types.ts:242`](../packages/core/session/src ### `UserMessage` -SHA-256: `0aed9f5c80e82b6e80e92eace5b9e23cd5e58c567d37b4321cd147d51342e212` +SHA-256: `69668f0ad0aabae22bb371efe471e202bcd915f88ca269b95e7ba9b062880f48` Sources: [`packages/llm/llm/src/message.ts:161`](../packages/llm/llm/src/message.ts) @@ -5494,19 +5512,19 @@ Sources: [`packages/llm/llm/src/message.ts:161`](../packages/llm/llm/src/message | `content` | required | [`ContentBlock[]`](#persistence-type-sha256-b52f215a6cd691058a3413c12f161fa3b563a2f4895adb3df6f744ec4b0a6ef1) | | `id` | required | `string` | | `role` | required | `"user"` | -| `source` | required | [`MessageSource`](#persistence-type-sha256-394ffa61d7dc84ebfd56ad772b59e47be136b95b9549ebf0b77a3bbebf4ce6cc) | +| `source` | required | [`MessageSource`](#persistence-type-sha256-694b070275bbc9a60149e8c669757eab8852dce090484c1a4b45f4c5343be2c8) | Source compatibility: `source` — `session-source-attribution` v1; `session.user-message.source`; `kind`; `preserve`. Attribution-only additions: `action-cards`, `tmux-context`, `user-question-reply`, `working-directory`. - + ### `UserMessage[]` -SHA-256: `300665af8bcc85dc20a65fd6681ee48d883178731c6f74457ed41539c607bc70` +SHA-256: `8c9911b902a2fda47058d4dd5113f99abc57ed97b098cf295ae64c49645623f8` -Array of [`UserMessage`](#persistence-type-sha256-0aed9f5c80e82b6e80e92eace5b9e23cd5e58c567d37b4321cd147d51342e212). +Array of [`UserMessage`](#persistence-type-sha256-69668f0ad0aabae22bb371efe471e202bcd915f88ca269b95e7ba9b062880f48). @@ -6471,18 +6489,18 @@ Sources: [`packages/core/session/src/types.ts:402`](../packages/core/session/src | `reason` | required | [`RequestHeaderReason`](#persistence-type-sha256-530da6c0267813bb4511af72883cc518834e624e3b3220a7062955fd57a788a6) | | `startsSeries` | optional | `true` | - + ### `{ headerSeq?, message, step, turn }` -SHA-256: `129f610271310df606674a5ce5c28b444bbf42c231b0f48ad26a0104ffeb6fde` +SHA-256: `3e2209934365160457426fe5b3f61df85987541ceac7e2ed27f4955bdc181ba2` Sources: [`packages/core/session/src/types.ts:321`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| | `headerSeq` | optional | `number` | -| `message` | required | [`DeveloperMessage`](#persistence-type-sha256-010783c095f1d9bddbdd2000f3f0a2d31e2ba4a687f2dabf169c5703b98c9def) | +| `message` | required | [`DeveloperMessage`](#persistence-type-sha256-b0e809a7fc2b90682c073e6a137f65fc2e93730ff28e3d6df39b785e71e8a497) | | `step` | required | `number` | | `turn` | required | `number` | @@ -6566,17 +6584,17 @@ Sources: [`packages/core/session/src/types.ts:439`](../packages/core/session/src |---|---|---| | `inherited` | optional | `true` | - + ### `{ inserted, outcome?, removedCount?, start, … }` -SHA-256: `261128de68865c1f92f2bfa2ccd21f362d6e624cb00fc0cf5558d9d7b82302c5` +SHA-256: `2314c3471cc0d31445cd2984ceea82f402a284bd31881d9df4423ed82dc49ebe` Sources: [`packages/core/agent/src/types.ts:110`](../packages/core/agent/src/types.ts) | Property | Presence | Type | |---|---|---| -| `inserted` | required | [`UserMessage[]`](#persistence-type-sha256-300665af8bcc85dc20a65fd6681ee48d883178731c6f74457ed41539c607bc70) | +| `inserted` | required | [`UserMessage[]`](#persistence-type-sha256-8c9911b902a2fda47058d4dd5113f99abc57ed97b098cf295ae64c49645623f8) | | `outcome` | optional | `"canceled"` | | `removedCount` | optional | `number` | | `start` | required | `number` | @@ -6733,6 +6751,30 @@ Sources: [`packages/extensions/cordis-host-runner/src/index.ts:15`](../packages/ |---|---|---| | `kind` | required | `"cordis-host-runner"` | + + +### `{ kind: "cua-held-inputs", form: "notice" }` + +SHA-256: `8a2e3e7a523e622b440e444ab934154ba53c0037ad6502437abba4365a852e21` + +| Property | Presence | Type | +|---|---|---| +| `form` | required | `"notice"` | +| `kind` | required | `"cua-held-inputs"` | +| `summary` | required | `string` | + + + +### `{ kind: "cua-inputs-released", form: "notice" }` + +SHA-256: `ce6e647c9e653b5d496d551f9e48980ceafc8eb0e6b4093f0b3e4da55164c99b` + +| Property | Presence | Type | +|---|---|---| +| `form` | required | `"notice"` | +| `kind` | required | `"cua-inputs-released"` | +| `summary` | required | `string` | + ### `{ kind: "disposed" }` @@ -8264,17 +8306,17 @@ SHA-256: `a10c17474eaf2ddab7095a099e0fe3d046fc18e56c3e344fc8894c05ff9ef97b` | `time` | required | `number` | | `type` | required | `"agent-preset/selected"` | - + ### `{ type: "agent/inbox/spliced" }` -SHA-256: `f5d843edb0eeef61c9f5328599d5f92b61112b7710b0310b043196b15b390d64` +SHA-256: `0880996d224033d9a668528f51edf5f229d9b07dda42fb65f7d1cc1150c12836` | Property | Presence | Type | |---|---|---| -| `data` | required | [`{ inserted, outcome?, removedCount?, start, … }`](#persistence-type-sha256-261128de68865c1f92f2bfa2ccd21f362d6e624cb00fc0cf5558d9d7b82302c5) | +| `data` | required | [`{ inserted, outcome?, removedCount?, start, … }`](#persistence-type-sha256-2314c3471cc0d31445cd2984ceea82f402a284bd31881d9df4423ed82dc49ebe) | | `ignorable` | optional | `true` | | `seq` | required | `number` | | `time` | required | `number` | @@ -8515,17 +8557,17 @@ SHA-256: `13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176` | `time` | required | `number` | | `type` | required | `"deliverables/presented"` | - + ### `{ type: "developer/message" }` -SHA-256: `7ee5a828196d9e4b1672f94f977e68f37125da4297c23029dd682823c09e12fd` +SHA-256: `3a6f3e4354a90287bb3a1fb19e7a2f643cdbd7c6472c865abd11f8fa2d3358d5` | Property | Presence | Type | |---|---|---| -| `data` | required | [`{ headerSeq?, message, step, turn }`](#persistence-type-sha256-129f610271310df606674a5ce5c28b444bbf42c231b0f48ad26a0104ffeb6fde) | +| `data` | required | [`{ headerSeq?, message, step, turn }`](#persistence-type-sha256-3e2209934365160457426fe5b3f61df85987541ceac7e2ed27f4955bdc181ba2) | | `ignorable` | optional | `true` | | `seq` | required | `number` | | `sourceEventSeqs` | optional | [`number[]`](#persistence-type-sha256-5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78) | @@ -8925,17 +8967,17 @@ SHA-256: `1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5` | `time` | required | `number` | | `type` | required | `"session/title"` | - + ### `{ type: "session/title-llm-request" }` -SHA-256: `4ee17e4219bd5fab6148ec0a8b3ec0fb939edb8f211374cf779bc8135ef9bed2` +SHA-256: `4e81b0490558b80c87cd09b214cd958ce0df1bf2bb431c930ff8fd441a8d1df5` | Property | Presence | Type | |---|---|---| -| `data` | required | [`SessionTitleLlmRequestEventData`](#persistence-type-sha256-ee4277d9b4c96ab0a024b3c65d294712b6721808c564162bce7f7feed40c139f) | +| `data` | required | [`SessionTitleLlmRequestEventData`](#persistence-type-sha256-c071d01c76a37f9fee2f29616b0aac535c87d4375d6131ef2794962be950b55e) | | `ignorable` | optional | `true` | | `seq` | required | `number` | | `time` | required | `number` | @@ -9374,17 +9416,17 @@ Sources: [`packages/llm/llm/src/types.ts:502`](../packages/llm/llm/src/types.ts) | `type` | required | `"usage"` | | `usage` | required | [`TokenUsage`](#persistence-type-sha256-fec5442b9ee4122e10514d81d5a43648003fe8bfb7ee2ba50c0cdbdd383ed394) | - + ### `{ type: "user/message" }` -SHA-256: `fb6a6e338625067ac582f55dde412a583040cd738bb8fc6820cb0b941c59f05a` +SHA-256: `507043f63e859f272ce78f6bc65a7361ee087e5e06301f9c100302230bc887a7` | Property | Presence | Type | |---|---|---| -| `data` | required | [`UserMessage`](#persistence-type-sha256-0aed9f5c80e82b6e80e92eace5b9e23cd5e58c567d37b4321cd147d51342e212) | +| `data` | required | [`UserMessage`](#persistence-type-sha256-69668f0ad0aabae22bb371efe471e202bcd915f88ca269b95e7ba9b062880f48) | | `ignorable` | optional | `true` | | `seq` | required | `number` | | `sourceEventSeqs` | optional | [`number[]`](#persistence-type-sha256-5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78) | diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index aa7a5f1a29..c8488a497b 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -25,7 +25,7 @@ | `JsonlHeaderLine` | header | `18ee62b8900a4c3d046700f05d7a4d49d6cab2a660a020c87481d1603dd8bd4f` | [`HeaderLine`](#persistence-type-sha256-18ee62b8900a4c3d046700f05d7a4d49d6cab2a660a020c87481d1603dd8bd4f) | | `SessionEventEnvelope` | envelope | `5776e5553ff2dfe3f5bc202dbb1e7c9f93e35a531aebb7764c23b2b6153b2ccc` | [`union (3 variants)`](#persistence-type-sha256-5776e5553ff2dfe3f5bc202dbb1e7c9f93e35a531aebb7764c23b2b6153b2ccc) | | `event:agent-preset/selected` | event | `a10c17474eaf2ddab7095a099e0fe3d046fc18e56c3e344fc8894c05ff9ef97b` | [`{ type: "agent-preset/selected" }`](#persistence-type-sha256-a10c17474eaf2ddab7095a099e0fe3d046fc18e56c3e344fc8894c05ff9ef97b) | -| `event:agent/inbox/spliced` | event | `f5d843edb0eeef61c9f5328599d5f92b61112b7710b0310b043196b15b390d64` | [`{ type: "agent/inbox/spliced" }`](#persistence-type-sha256-f5d843edb0eeef61c9f5328599d5f92b61112b7710b0310b043196b15b390d64) | +| `event:agent/inbox/spliced` | event | `0880996d224033d9a668528f51edf5f229d9b07dda42fb65f7d1cc1150c12836` | [`{ type: "agent/inbox/spliced" }`](#persistence-type-sha256-0880996d224033d9a668528f51edf5f229d9b07dda42fb65f7d1cc1150c12836) | | `event:approval/asked` | event | `3bfeb47b58606f4661904bc723da612782214c463d01e6d61cd6d6193d7374e1` | [`{ type: "approval/asked" }`](#persistence-type-sha256-3bfeb47b58606f4661904bc723da612782214c463d01e6d61cd6d6193d7374e1) | | `event:approval/decided` | event | `bb1ab3d08f49a9f3b265f844cd78d5c49813062a7b34b54904b426f85d0ff6e3` | [`{ type: "approval/decided" }`](#persistence-type-sha256-bb1ab3d08f49a9f3b265f844cd78d5c49813062a7b34b54904b426f85d0ff6e3) | | `event:approval/policy` | event | `26718e15e7e395bce9642dba5bbe09b3b1a4ce2213d20d566cd9207d7fc5fb78` | [`{ type: "approval/policy" }`](#persistence-type-sha256-26718e15e7e395bce9642dba5bbe09b3b1a4ce2213d20d566cd9207d7fc5fb78) | @@ -38,7 +38,7 @@ | `event:compaction/start` | event | `db874d463b0fdec77e9da1c4568f37cb70bd6596781eb93800db44fb8a116965` | [`{ type: "compaction/start" }`](#persistence-type-sha256-db874d463b0fdec77e9da1c4568f37cb70bd6596781eb93800db44fb8a116965) | | `event:compaction/summary` | event | `e2f9a41e0989f54ed8cee80f8db2bcf9d60a5c810dc9d45b83fa050b9dce7602` | [`{ type: "compaction/summary" }`](#persistence-type-sha256-e2f9a41e0989f54ed8cee80f8db2bcf9d60a5c810dc9d45b83fa050b9dce7602) | | `event:deliverables/presented` | event | `13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176` | [`{ type: "deliverables/presented" }`](#persistence-type-sha256-13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176) | -| `event:developer/message` | event | `7ee5a828196d9e4b1672f94f977e68f37125da4297c23029dd682823c09e12fd` | [`{ type: "developer/message" }`](#persistence-type-sha256-7ee5a828196d9e4b1672f94f977e68f37125da4297c23029dd682823c09e12fd) | +| `event:developer/message` | event | `3a6f3e4354a90287bb3a1fb19e7a2f643cdbd7c6472c865abd11f8fa2d3358d5` | [`{ type: "developer/message" }`](#persistence-type-sha256-3a6f3e4354a90287bb3a1fb19e7a2f643cdbd7c6472c865abd11f8fa2d3358d5) | | `event:feedback/message-delete` | event | `3ee93b06f3a125850337602bcdf155d2538c43a5c944ec55b1b3c365152d6796` | [`{ type: "feedback/message-delete" }`](#persistence-type-sha256-3ee93b06f3a125850337602bcdf155d2538c43a5c944ec55b1b3c365152d6796) | | `event:feedback/message-put` | event | `b5086d249e8502e9ead1d39156bb8d559bde7951cac0f14ce150345b4e42a2bf` | [`{ type: "feedback/message-put" }`](#persistence-type-sha256-b5086d249e8502e9ead1d39156bb8d559bde7951cac0f14ce150345b4e42a2bf) | | `event:feedback/record` | event | `b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8` | [`{ type: "feedback/record" }`](#persistence-type-sha256-b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8) | @@ -60,7 +60,7 @@ | `event:session-log-deepseek/delivery-accepted` | event | `d63b8b8ffad9c02fd80c43a17df4f240c1fe8118ecca9de34f9d5871838ab5b9` | [`{ type: "session-log-deepseek/delivery-accepted" }`](#persistence-type-sha256-d63b8b8ffad9c02fd80c43a17df4f240c1fe8118ecca9de34f9d5871838ab5b9) | | `event:session/end-seed` | event | `5e6db6e24948d4a853c71cb9fabd252ad051ce93d4672c1266cf837c1c17b84e` | [`{ type: "session/end-seed" }`](#persistence-type-sha256-5e6db6e24948d4a853c71cb9fabd252ad051ce93d4672c1266cf837c1c17b84e) | | `event:session/title` | event | `1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5` | [`{ type: "session/title" }`](#persistence-type-sha256-1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5) | -| `event:session/title-llm-request` | event | `4ee17e4219bd5fab6148ec0a8b3ec0fb939edb8f211374cf779bc8135ef9bed2` | [`{ type: "session/title-llm-request" }`](#persistence-type-sha256-4ee17e4219bd5fab6148ec0a8b3ec0fb939edb8f211374cf779bc8135ef9bed2) | +| `event:session/title-llm-request` | event | `4e81b0490558b80c87cd09b214cd958ce0df1bf2bb431c930ff8fd441a8d1df5` | [`{ type: "session/title-llm-request" }`](#persistence-type-sha256-4e81b0490558b80c87cd09b214cd958ce0df1bf2bb431c930ff8fd441a8d1df5) | | `event:step/end` | event | `e0a787e6ec76c7c94fecbc501b489164ab0293db05bc947914077ad01e674f05` | [`{ type: "step/end" }`](#persistence-type-sha256-e0a787e6ec76c7c94fecbc501b489164ab0293db05bc947914077ad01e674f05) | | `event:step/start` | event | `4513e088d43e6c68425be30451b9f961cc264fe7318ca62681c41d4d78615986` | [`{ type: "step/start" }`](#persistence-type-sha256-4513e088d43e6c68425be30451b9f961cc264fe7318ca62681c41d4d78615986) | | `event:subagent/catalog` | event | `d49164d37eab0f0f70fa787c65d887abbea869c010ccb103d717fab3519c3a41` | [`{ type: "subagent/catalog" }`](#persistence-type-sha256-d49164d37eab0f0f70fa787c65d887abbea869c010ccb103d717fab3519c3a41) | @@ -83,7 +83,7 @@ | `event:tool/result` | event | `7c9f44e90a0058f4cc532ae20dad0c10afa6eba22e70a6c79fc79490bad64397` | [`{ type: "tool/result" }`](#persistence-type-sha256-7c9f44e90a0058f4cc532ae20dad0c10afa6eba22e70a6c79fc79490bad64397) | | `event:turn/end` | event | `0f8512903d94f57a4748fa1a2092e64342856796684e6b8343db685b192745ce` | [`{ type: "turn/end" }`](#persistence-type-sha256-0f8512903d94f57a4748fa1a2092e64342856796684e6b8343db685b192745ce) | | `event:turn/start` | event | `aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8` | [`{ type: "turn/start" }`](#persistence-type-sha256-aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8) | -| `event:user/message` | event | `fb6a6e338625067ac582f55dde412a583040cd738bb8fc6820cb0b941c59f05a` | [`{ type: "user/message" }`](#persistence-type-sha256-fb6a6e338625067ac582f55dde412a583040cd738bb8fc6820cb0b941c59f05a) | +| `event:user/message` | event | `507043f63e859f272ce78f6bc65a7361ee087e5e06301f9c100302230bc887a7` | [`{ type: "user/message" }`](#persistence-type-sha256-507043f63e859f272ce78f6bc65a7361ee087e5e06301f9c100302230bc887a7) | | `event:web/deepseek-search-llm-request` | event | `0c556c9b9f2a96238a6b9bbb99e748206cbff2ed6203041c9571f04ae5802f52` | [`{ type: "web/deepseek-search-llm-request" }`](#persistence-type-sha256-0c556c9b9f2a96238a6b9bbb99e748206cbff2ed6203041c9571f04ae5802f52) | | `event:working-directory/change` | event | `124aa62078ca3311353b39cc3bf6c75da281338be6bbf672f8b361d828cddca3` | [`{ type: "working-directory/change" }`](#persistence-type-sha256-124aa62078ca3311353b39cc3bf6c75da281338be6bbf672f8b361d828cddca3) | | `event:workspace-root/change` | event | `025f11632cd02aaecc23a46c3b5bf43b9009d88293ed9b35ccbc1139d73334dc` | [`{ type: "workspace-root/change" }`](#persistence-type-sha256-025f11632cd02aaecc23a46c3b5bf43b9009d88293ed9b35ccbc1139d73334dc) | @@ -1728,6 +1728,22 @@ SHA-256: `7624ca28c61ca0eaa4f015140f3cea6e0c16cce2f2960fab5f531203d253903e` `"create"` + + +### `"cua-held-inputs"` + +SHA-256: `9d42da116fccdc399c2877bb46488c6690e3968c02de6ff2a55e83adc67cc496` + +`"cua-held-inputs"` + + + +### `"cua-inputs-released"` + +SHA-256: `a6816f39283ae26f0cd16cfce35724eb676a1f1b57afbc91094a36b2d2a40b2d` + +`"cua-inputs-released"` + ### `"danger-full-access"` @@ -3466,7 +3482,7 @@ SHA-256: `abd6ca62a5ab166553848324a23fef90eed7f59c8021bd63e7ea5bc6fd666b0c` | `body` | 必需 | [`{ max_tokens, messages, model, thinking?, … }`](#persistence-type-sha256-9c001ecb5e1d3c3894410db2a1e383842e5f8454fb52182338686158abc1b3ee) | | `endpoint` | 必需 | `string` | - + @@ -3474,7 +3490,7 @@ SHA-256: `abd6ca62a5ab166553848324a23fef90eed7f59c8021bd63e7ea5bc6fd666b0c` ### `DeveloperMessage` -SHA-256: `010783c095f1d9bddbdd2000f3f0a2d31e2ba4a687f2dabf169c5703b98c9def` +SHA-256: `b0e809a7fc2b90682c073e6a137f65fc2e93730ff28e3d6df39b785e71e8a497` 来源:[`packages/llm/llm/src/message.ts:156`](../packages/llm/llm/src/message.ts) @@ -3483,7 +3499,7 @@ SHA-256: `010783c095f1d9bddbdd2000f3f0a2d31e2ba4a687f2dabf169c5703b98c9def` | `content` | 必需 | [`ContentBlock[]`](#persistence-type-sha256-b52f215a6cd691058a3413c12f161fa3b563a2f4895adb3df6f744ec4b0a6ef1) | | `id` | 必需 | `string` | | `role` | 必需 | `"developer"` | -| `source` | 必需 | [`MessageSource`](#persistence-type-sha256-394ffa61d7dc84ebfd56ad772b59e47be136b95b9549ebf0b77a3bbebf4ce6cc) | +| `source` | 必需 | [`MessageSource`](#persistence-type-sha256-694b070275bbc9a60149e8c669757eab8852dce090484c1a4b45f4c5343be2c8) | 消息源兼容策略:`source` — `session-source-attribution` v1; `session.developer-message.source`; `kind`; `preserve`. @@ -4182,7 +4198,7 @@ SHA-256: `6f72ece8f317cd080c4f20a93f1bf709965f5b81ac4669528f5a023191cfcf20` | `step` | 必需 | `number` | | `turn` | 必需 | `number` | - + @@ -4190,15 +4206,15 @@ SHA-256: `6f72ece8f317cd080c4f20a93f1bf709965f5b81ac4669528f5a023191cfcf20` ### `Message` -SHA-256: `45e3a4c397121e1a2a455c990b4d45852111b64909ced474d41b9f977ac592a4` +SHA-256: `e744baea6a5d54efc05ce47ebae956fc138a76dad8e605f49b5a7f1c294823a8` 来源:[`packages/llm/llm/src/message.ts:195`](../packages/llm/llm/src/message.ts) 以下类型之一: - [`ToolResultMessage`](#persistence-type-sha256-4b259f7f8f0a44ad5e90b70a73553ced1df27012d126921d397ff403b6c86731) -- [`DeveloperMessage`](#persistence-type-sha256-010783c095f1d9bddbdd2000f3f0a2d31e2ba4a687f2dabf169c5703b98c9def) -- [`UserMessage`](#persistence-type-sha256-0aed9f5c80e82b6e80e92eace5b9e23cd5e58c567d37b4321cd147d51342e212) +- [`DeveloperMessage`](#persistence-type-sha256-b0e809a7fc2b90682c073e6a137f65fc2e93730ff28e3d6df39b785e71e8a497) +- [`UserMessage`](#persistence-type-sha256-69668f0ad0aabae22bb371efe471e202bcd915f88ca269b95e7ba9b062880f48) - [`SystemMessage`](#persistence-type-sha256-09f3f8dc417f278257202714132f98ba7b52957d7b558c4a04456603890eb363) - [`AssistantMessage`](#persistence-type-sha256-fa87537f4a9c1e25602990a8bf686b383e9e00352ec8946e16ae24ba7c1625be) @@ -4275,7 +4291,7 @@ SHA-256: `390eed1028aba02774f14408647acec10ec5516e97d4f15ecde2b9989d5a69f2` - `"negative"` - `"positive"` - + @@ -4283,7 +4299,7 @@ SHA-256: `390eed1028aba02774f14408647acec10ec5516e97d4f15ecde2b9989d5a69f2` ### `MessageSource` -SHA-256: `394ffa61d7dc84ebfd56ad772b59e47be136b95b9549ebf0b77a3bbebf4ce6cc` +SHA-256: `694b070275bbc9a60149e8c669757eab8852dce090484c1a4b45f4c5343be2c8` 来源:[`packages/llm/llm/src/message.ts:135`](../packages/llm/llm/src/message.ts) @@ -4300,6 +4316,8 @@ SHA-256: `394ffa61d7dc84ebfd56ad772b59e47be136b95b9549ebf0b77a3bbebf4ce6cc` | `agent-message` | `"relay"` | `senderSessionId`: `string` | [`AgentMessageSource`](#persistence-type-sha256-4a9bef9f27a942520cc2279ca7dd3082556e4bff543f66b5c0333e1bbed1cd86) | | `compact-checkpoint` | 未声明 | `compactionId`: `string` | [`CompactionCheckpointSource`](#persistence-type-sha256-31907de9563751822af6d9be02bafaf26faa098bbd1cb412524134d577cc1648) | | `cordis-host-runner` | 未声明 | 无 | [`{ kind: "cordis-host-runner" }`](#persistence-type-sha256-02b2c23f2d94b028c9588a8faace3fce1217405db346da3389368b495457bf79) | +| `cua-held-inputs` | `"notice"` | `summary`: `string` | [`{ kind: "cua-held-inputs", form: "notice" }`](#persistence-type-sha256-8a2e3e7a523e622b440e444ab934154ba53c0037ad6502437abba4365a852e21) | +| `cua-inputs-released` | `"notice"` | `summary`: `string` | [`{ kind: "cua-inputs-released", form: "notice" }`](#persistence-type-sha256-ce6e647c9e653b5d496d551f9e48980ceafc8eb0e6b4093f0b3e4da55164c99b) | | `dsh-session-title-llm` | `"catalog"` | 无 | [`{ kind: "dsh-session-title-llm", form: "catalog" }`](#persistence-type-sha256-80677c8c8b804189a0fde8aa70dd4ad7af8bb12dfd03027e8e023c8592c838bc) | | `dsh-session-title-llm` | `"instructions"` | 无 | [`{ kind: "dsh-session-title-llm", form: "instructions" }`](#persistence-type-sha256-224aa11d4d5f88c450822d01b99e6ca5e3a9c7f26a5ede10bae33384a09ef4dc) | | `dsh-session-title-llm` | `"notice"` | `summary`: `string` | [`{ kind: "dsh-session-title-llm", form: "notice" }`](#persistence-type-sha256-8338ee303e2bd448e9e6144069942f63e3cfd5868962bddc9347d7009e8919d6) | @@ -4410,13 +4428,13 @@ SHA-256: `394ffa61d7dc84ebfd56ad772b59e47be136b95b9549ebf0b77a3bbebf4ce6cc` | `webhook` | `"notice"` | `deliveryId`: `string`; `provider`: `string`; `ruleId`: `string`; `source`: `string`; `summary`: `string` | [`{ kind: "webhook", form: "notice" }`](#persistence-type-sha256-9edc162949abf93bd5ff049191b345454ba104f583937ce5580fb50f067d2b94) | | `working-directory` | 未声明 | 无 | [`{ kind: "working-directory" }`](#persistence-type-sha256-2235d957bf4b7c6cf959231d480f0ba1f3a6d72d82981493fb6c7c963021d3d5) | - + ### `Message[]` -SHA-256: `39fe981d6583647fe76f121c43bd6eac1f1a0d6707297f0901b3078899f9ac92` +SHA-256: `e973903c6f32109ccaaceba75f6c6cec33fe7f8d684e24627760cc53916af848` -[`Message`](#persistence-type-sha256-45e3a4c397121e1a2a455c990b4d45852111b64909ced474d41b9f977ac592a4) 的数组。 +[`Message`](#persistence-type-sha256-e744baea6a5d54efc05ce47ebae956fc138a76dad8e605f49b5a7f1c294823a8) 的数组。 @@ -4784,7 +4802,7 @@ SHA-256: `b56f6a885da3dc394c69a3e3cc5c0cfc4da15601b63fda4989eee8f40efc5be4` | `source` | 必需 | [`SessionTitleSource`](#persistence-type-sha256-30d5a537b296685770b1241c4b4bbde19d5a31ff81aa23df73fab5e90b8fc65f) | | `title` | 必需 | `string` | - + @@ -4792,7 +4810,7 @@ SHA-256: `b56f6a885da3dc394c69a3e3cc5c0cfc4da15601b63fda4989eee8f40efc5be4` ### `SessionTitleLlmRequestEventData` -SHA-256: `ee4277d9b4c96ab0a024b3c65d294712b6721808c564162bce7f7feed40c139f` +SHA-256: `c071d01c76a37f9fee2f29616b0aac535c87d4375d6131ef2794962be950b55e` 来源:[`packages/session/session-title-llm/src/index.ts:43`](../packages/session/session-title-llm/src/index.ts) @@ -4800,7 +4818,7 @@ SHA-256: `ee4277d9b4c96ab0a024b3c65d294712b6721808c564162bce7f7feed40c139f` |---|---|---| | `maxTokens` | 必需 | `number` | | `messageSeqs` | 必需 | [`number[]`](#persistence-type-sha256-5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78) | -| `messages` | 必需 | [`Message[]`](#persistence-type-sha256-39fe981d6583647fe76f121c43bd6eac1f1a0d6707297f0901b3078899f9ac92) | +| `messages` | 必需 | [`Message[]`](#persistence-type-sha256-e973903c6f32109ccaaceba75f6c6cec33fe7f8d684e24627760cc53916af848) | | `reasoningEffort` | 可选 | `string` | | `route` | 必需 | [`SessionTitleModelIdentity`](#persistence-type-sha256-07e1a58c58b593f507b8e7f25723bb0aa42baae6e00f5ecfddf28cb1e64d3235) | | `system` | 必需 | `string` | @@ -5479,7 +5497,7 @@ SHA-256: `f1687f982fa3d41ef29e159feed154ecd13af4dd209acaee16038f223f2e9402` | `interrupted` | 未声明 | 无 | [`{ kind: "interrupted" }`](#persistence-type-sha256-56b7c047694875a843ba020dfea3c8380d54ae4ff88ab349e72004dc21e07c23) | | `max-tokens` | 未声明 | 无 | [`{ kind: "max-tokens" }`](#persistence-type-sha256-ab7ec5f9eb2c6dfacca5da4c37cf7ba85d04172053ee6b1ebf1709ffcd99c1a7) | - + @@ -5487,7 +5505,7 @@ SHA-256: `f1687f982fa3d41ef29e159feed154ecd13af4dd209acaee16038f223f2e9402` ### `UserMessage` -SHA-256: `0aed9f5c80e82b6e80e92eace5b9e23cd5e58c567d37b4321cd147d51342e212` +SHA-256: `69668f0ad0aabae22bb371efe471e202bcd915f88ca269b95e7ba9b062880f48` 来源:[`packages/llm/llm/src/message.ts:161`](../packages/llm/llm/src/message.ts) @@ -5496,19 +5514,19 @@ SHA-256: `0aed9f5c80e82b6e80e92eace5b9e23cd5e58c567d37b4321cd147d51342e212` | `content` | 必需 | [`ContentBlock[]`](#persistence-type-sha256-b52f215a6cd691058a3413c12f161fa3b563a2f4895adb3df6f744ec4b0a6ef1) | | `id` | 必需 | `string` | | `role` | 必需 | `"user"` | -| `source` | 必需 | [`MessageSource`](#persistence-type-sha256-394ffa61d7dc84ebfd56ad772b59e47be136b95b9549ebf0b77a3bbebf4ce6cc) | +| `source` | 必需 | [`MessageSource`](#persistence-type-sha256-694b070275bbc9a60149e8c669757eab8852dce090484c1a4b45f4c5343be2c8) | 消息源兼容策略:`source` — `session-source-attribution` v1; `session.user-message.source`; `kind`; `preserve`. 仅表示归属的新增 kind:`action-cards`, `tmux-context`, `user-question-reply`, `working-directory`. - + ### `UserMessage[]` -SHA-256: `300665af8bcc85dc20a65fd6681ee48d883178731c6f74457ed41539c607bc70` +SHA-256: `8c9911b902a2fda47058d4dd5113f99abc57ed97b098cf295ae64c49645623f8` -[`UserMessage`](#persistence-type-sha256-0aed9f5c80e82b6e80e92eace5b9e23cd5e58c567d37b4321cd147d51342e212) 的数组。 +[`UserMessage`](#persistence-type-sha256-69668f0ad0aabae22bb371efe471e202bcd915f88ca269b95e7ba9b062880f48) 的数组。 @@ -6473,18 +6491,18 @@ SHA-256: `ad0c38a0adb82a94c925456df41586d9b5f9202fca18593eae2213d4445b4585` | `reason` | 必需 | [`RequestHeaderReason`](#persistence-type-sha256-530da6c0267813bb4511af72883cc518834e624e3b3220a7062955fd57a788a6) | | `startsSeries` | 可选 | `true` | - + ### `{ headerSeq?, message, step, turn }` -SHA-256: `129f610271310df606674a5ce5c28b444bbf42c231b0f48ad26a0104ffeb6fde` +SHA-256: `3e2209934365160457426fe5b3f61df85987541ceac7e2ed27f4955bdc181ba2` 来源:[`packages/core/session/src/types.ts:321`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| | `headerSeq` | 可选 | `number` | -| `message` | 必需 | [`DeveloperMessage`](#persistence-type-sha256-010783c095f1d9bddbdd2000f3f0a2d31e2ba4a687f2dabf169c5703b98c9def) | +| `message` | 必需 | [`DeveloperMessage`](#persistence-type-sha256-b0e809a7fc2b90682c073e6a137f65fc2e93730ff28e3d6df39b785e71e8a497) | | `step` | 必需 | `number` | | `turn` | 必需 | `number` | @@ -6568,17 +6586,17 @@ SHA-256: `17d1afb770d9941936130996da00dc86782cfef731d8d6526162c301256a4ac3` |---|---|---| | `inherited` | 可选 | `true` | - + ### `{ inserted, outcome?, removedCount?, start, … }` -SHA-256: `261128de68865c1f92f2bfa2ccd21f362d6e624cb00fc0cf5558d9d7b82302c5` +SHA-256: `2314c3471cc0d31445cd2984ceea82f402a284bd31881d9df4423ed82dc49ebe` 来源:[`packages/core/agent/src/types.ts:110`](../packages/core/agent/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| -| `inserted` | 必需 | [`UserMessage[]`](#persistence-type-sha256-300665af8bcc85dc20a65fd6681ee48d883178731c6f74457ed41539c607bc70) | +| `inserted` | 必需 | [`UserMessage[]`](#persistence-type-sha256-8c9911b902a2fda47058d4dd5113f99abc57ed97b098cf295ae64c49645623f8) | | `outcome` | 可选 | `"canceled"` | | `removedCount` | 可选 | `number` | | `start` | 必需 | `number` | @@ -6735,6 +6753,30 @@ SHA-256: `02b2c23f2d94b028c9588a8faace3fce1217405db346da3389368b495457bf79` |---|---|---| | `kind` | 必需 | `"cordis-host-runner"` | + + +### `{ kind: "cua-held-inputs", form: "notice" }` + +SHA-256: `8a2e3e7a523e622b440e444ab934154ba53c0037ad6502437abba4365a852e21` + +| 属性 | 存在性 | 类型 | +|---|---|---| +| `form` | 必需 | `"notice"` | +| `kind` | 必需 | `"cua-held-inputs"` | +| `summary` | 必需 | `string` | + + + +### `{ kind: "cua-inputs-released", form: "notice" }` + +SHA-256: `ce6e647c9e653b5d496d551f9e48980ceafc8eb0e6b4093f0b3e4da55164c99b` + +| 属性 | 存在性 | 类型 | +|---|---|---| +| `form` | 必需 | `"notice"` | +| `kind` | 必需 | `"cua-inputs-released"` | +| `summary` | 必需 | `string` | + ### `{ kind: "disposed" }` @@ -8266,17 +8308,17 @@ SHA-256: `a10c17474eaf2ddab7095a099e0fe3d046fc18e56c3e344fc8894c05ff9ef97b` | `time` | 必需 | `number` | | `type` | 必需 | `"agent-preset/selected"` | - + ### `{ type: "agent/inbox/spliced" }` -SHA-256: `f5d843edb0eeef61c9f5328599d5f92b61112b7710b0310b043196b15b390d64` +SHA-256: `0880996d224033d9a668528f51edf5f229d9b07dda42fb65f7d1cc1150c12836` | 属性 | 存在性 | 类型 | |---|---|---| -| `data` | 必需 | [`{ inserted, outcome?, removedCount?, start, … }`](#persistence-type-sha256-261128de68865c1f92f2bfa2ccd21f362d6e624cb00fc0cf5558d9d7b82302c5) | +| `data` | 必需 | [`{ inserted, outcome?, removedCount?, start, … }`](#persistence-type-sha256-2314c3471cc0d31445cd2984ceea82f402a284bd31881d9df4423ed82dc49ebe) | | `ignorable` | 可选 | `true` | | `seq` | 必需 | `number` | | `time` | 必需 | `number` | @@ -8517,17 +8559,17 @@ SHA-256: `13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176` | `time` | 必需 | `number` | | `type` | 必需 | `"deliverables/presented"` | - + ### `{ type: "developer/message" }` -SHA-256: `7ee5a828196d9e4b1672f94f977e68f37125da4297c23029dd682823c09e12fd` +SHA-256: `3a6f3e4354a90287bb3a1fb19e7a2f643cdbd7c6472c865abd11f8fa2d3358d5` | 属性 | 存在性 | 类型 | |---|---|---| -| `data` | 必需 | [`{ headerSeq?, message, step, turn }`](#persistence-type-sha256-129f610271310df606674a5ce5c28b444bbf42c231b0f48ad26a0104ffeb6fde) | +| `data` | 必需 | [`{ headerSeq?, message, step, turn }`](#persistence-type-sha256-3e2209934365160457426fe5b3f61df85987541ceac7e2ed27f4955bdc181ba2) | | `ignorable` | 可选 | `true` | | `seq` | 必需 | `number` | | `sourceEventSeqs` | 可选 | [`number[]`](#persistence-type-sha256-5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78) | @@ -8927,17 +8969,17 @@ SHA-256: `1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5` | `time` | 必需 | `number` | | `type` | 必需 | `"session/title"` | - + ### `{ type: "session/title-llm-request" }` -SHA-256: `4ee17e4219bd5fab6148ec0a8b3ec0fb939edb8f211374cf779bc8135ef9bed2` +SHA-256: `4e81b0490558b80c87cd09b214cd958ce0df1bf2bb431c930ff8fd441a8d1df5` | 属性 | 存在性 | 类型 | |---|---|---| -| `data` | 必需 | [`SessionTitleLlmRequestEventData`](#persistence-type-sha256-ee4277d9b4c96ab0a024b3c65d294712b6721808c564162bce7f7feed40c139f) | +| `data` | 必需 | [`SessionTitleLlmRequestEventData`](#persistence-type-sha256-c071d01c76a37f9fee2f29616b0aac535c87d4375d6131ef2794962be950b55e) | | `ignorable` | 可选 | `true` | | `seq` | 必需 | `number` | | `time` | 必需 | `number` | @@ -9376,17 +9418,17 @@ SHA-256: `f1a96afe7503ac1817de769cd0ba13d9b80111c7034c50106b3344ecc14cc515` | `type` | 必需 | `"usage"` | | `usage` | 必需 | [`TokenUsage`](#persistence-type-sha256-fec5442b9ee4122e10514d81d5a43648003fe8bfb7ee2ba50c0cdbdd383ed394) | - + ### `{ type: "user/message" }` -SHA-256: `fb6a6e338625067ac582f55dde412a583040cd738bb8fc6820cb0b941c59f05a` +SHA-256: `507043f63e859f272ce78f6bc65a7361ee087e5e06301f9c100302230bc887a7` | 属性 | 存在性 | 类型 | |---|---|---| -| `data` | 必需 | [`UserMessage`](#persistence-type-sha256-0aed9f5c80e82b6e80e92eace5b9e23cd5e58c567d37b4321cd147d51342e212) | +| `data` | 必需 | [`UserMessage`](#persistence-type-sha256-69668f0ad0aabae22bb371efe471e202bcd915f88ca269b95e7ba9b062880f48) | | `ignorable` | 可选 | `true` | | `seq` | 必需 | `number` | | `sourceEventSeqs` | 可选 | [`number[]`](#persistence-type-sha256-5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78) | diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json index cc446efccb..199bad4ae8 100644 --- a/docs/persistence-schema.json +++ b/docs/persistence-schema.json @@ -5,7 +5,7 @@ {"key":"JsonlHeaderLine","kind":"header","digest":"18ee62b8900a4c3d046700f05d7a4d49d6cab2a660a020c87481d1603dd8bd4f"}, {"key":"SessionEventEnvelope","kind":"envelope","digest":"5776e5553ff2dfe3f5bc202dbb1e7c9f93e35a531aebb7764c23b2b6153b2ccc"}, {"key":"event:agent-preset/selected","kind":"event","event":"agent-preset/selected","surface":false,"digest":"a10c17474eaf2ddab7095a099e0fe3d046fc18e56c3e344fc8894c05ff9ef97b"}, - {"key":"event:agent/inbox/spliced","kind":"event","event":"agent/inbox/spliced","surface":false,"digest":"f5d843edb0eeef61c9f5328599d5f92b61112b7710b0310b043196b15b390d64"}, + {"key":"event:agent/inbox/spliced","kind":"event","event":"agent/inbox/spliced","surface":false,"digest":"0880996d224033d9a668528f51edf5f229d9b07dda42fb65f7d1cc1150c12836"}, {"key":"event:approval/asked","kind":"event","event":"approval/asked","surface":false,"digest":"3bfeb47b58606f4661904bc723da612782214c463d01e6d61cd6d6193d7374e1"}, {"key":"event:approval/decided","kind":"event","event":"approval/decided","surface":false,"digest":"bb1ab3d08f49a9f3b265f844cd78d5c49813062a7b34b54904b426f85d0ff6e3"}, {"key":"event:approval/policy","kind":"event","event":"approval/policy","surface":false,"digest":"26718e15e7e395bce9642dba5bbe09b3b1a4ce2213d20d566cd9207d7fc5fb78"}, @@ -18,7 +18,7 @@ {"key":"event:compaction/start","kind":"event","event":"compaction/start","surface":false,"digest":"db874d463b0fdec77e9da1c4568f37cb70bd6596781eb93800db44fb8a116965"}, {"key":"event:compaction/summary","kind":"event","event":"compaction/summary","surface":false,"digest":"e2f9a41e0989f54ed8cee80f8db2bcf9d60a5c810dc9d45b83fa050b9dce7602"}, {"key":"event:deliverables/presented","kind":"event","event":"deliverables/presented","surface":false,"digest":"13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176"}, - {"key":"event:developer/message","kind":"event","event":"developer/message","surface":true,"digest":"7ee5a828196d9e4b1672f94f977e68f37125da4297c23029dd682823c09e12fd"}, + {"key":"event:developer/message","kind":"event","event":"developer/message","surface":true,"digest":"3a6f3e4354a90287bb3a1fb19e7a2f643cdbd7c6472c865abd11f8fa2d3358d5"}, {"key":"event:feedback/message-delete","kind":"event","event":"feedback/message-delete","surface":false,"digest":"3ee93b06f3a125850337602bcdf155d2538c43a5c944ec55b1b3c365152d6796"}, {"key":"event:feedback/message-put","kind":"event","event":"feedback/message-put","surface":false,"digest":"b5086d249e8502e9ead1d39156bb8d559bde7951cac0f14ce150345b4e42a2bf"}, {"key":"event:feedback/record","kind":"event","event":"feedback/record","surface":false,"digest":"b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8"}, @@ -40,7 +40,7 @@ {"key":"event:session-log-deepseek/delivery-accepted","kind":"event","event":"session-log-deepseek/delivery-accepted","surface":false,"digest":"d63b8b8ffad9c02fd80c43a17df4f240c1fe8118ecca9de34f9d5871838ab5b9"}, {"key":"event:session/end-seed","kind":"event","event":"session/end-seed","surface":false,"digest":"5e6db6e24948d4a853c71cb9fabd252ad051ce93d4672c1266cf837c1c17b84e"}, {"key":"event:session/title","kind":"event","event":"session/title","surface":false,"digest":"1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5"}, - {"key":"event:session/title-llm-request","kind":"event","event":"session/title-llm-request","surface":false,"digest":"4ee17e4219bd5fab6148ec0a8b3ec0fb939edb8f211374cf779bc8135ef9bed2"}, + {"key":"event:session/title-llm-request","kind":"event","event":"session/title-llm-request","surface":false,"digest":"4e81b0490558b80c87cd09b214cd958ce0df1bf2bb431c930ff8fd441a8d1df5"}, {"key":"event:step/end","kind":"event","event":"step/end","surface":false,"digest":"e0a787e6ec76c7c94fecbc501b489164ab0293db05bc947914077ad01e674f05"}, {"key":"event:step/start","kind":"event","event":"step/start","surface":false,"digest":"4513e088d43e6c68425be30451b9f961cc264fe7318ca62681c41d4d78615986"}, {"key":"event:subagent/catalog","kind":"event","event":"subagent/catalog","surface":false,"digest":"d49164d37eab0f0f70fa787c65d887abbea869c010ccb103d717fab3519c3a41"}, @@ -63,14 +63,13 @@ {"key":"event:tool/result","kind":"event","event":"tool/result","surface":true,"digest":"7c9f44e90a0058f4cc532ae20dad0c10afa6eba22e70a6c79fc79490bad64397"}, {"key":"event:turn/end","kind":"event","event":"turn/end","surface":false,"digest":"0f8512903d94f57a4748fa1a2092e64342856796684e6b8343db685b192745ce"}, {"key":"event:turn/start","kind":"event","event":"turn/start","surface":false,"digest":"aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8"}, - {"key":"event:user/message","kind":"event","event":"user/message","surface":true,"digest":"fb6a6e338625067ac582f55dde412a583040cd738bb8fc6820cb0b941c59f05a"}, + {"key":"event:user/message","kind":"event","event":"user/message","surface":true,"digest":"507043f63e859f272ce78f6bc65a7361ee087e5e06301f9c100302230bc887a7"}, {"key":"event:web/deepseek-search-llm-request","kind":"event","event":"web/deepseek-search-llm-request","surface":false,"digest":"0c556c9b9f2a96238a6b9bbb99e748206cbff2ed6203041c9571f04ae5802f52"}, {"key":"event:working-directory/change","kind":"event","event":"working-directory/change","surface":false,"digest":"124aa62078ca3311353b39cc3bf6c75da281338be6bbf672f8b361d828cddca3"}, {"key":"event:workspace-root/change","kind":"event","event":"workspace-root/change","surface":false,"digest":"025f11632cd02aaecc23a46c3b5bf43b9009d88293ed9b35ccbc1139d73334dc"}, {"key":"event:workspace/changes","kind":"event","event":"workspace/changes","surface":false,"digest":"e308ccf867a5398e316e0af8cb6ce238a8d33a63b9b384c8250a686786285f72"} ], "types": [ - {"digest":"010783c095f1d9bddbdd2000f3f0a2d31e2ba4a687f2dabf169c5703b98c9def","names":["packages/llm/llm/src/message.ts#DeveloperMessage"],"sources":["packages/llm/llm/src/message.ts:156"]}, {"digest":"0116b1f89c05221d56b0ba35c83d302bf4857bc7277d247e9bbaf74b27d2c66e","names":[],"sources":[]}, {"digest":"0203243b72fc867afc81aff5f4cf2167e564ed342534eb612fc92f295cf07789","names":[],"sources":[]}, {"digest":"022623b9ef98ec47ec3c3bae0c51027c70d2601141c5e92e26a0d83d1b4cef06","names":[],"sources":[]}, @@ -85,6 +84,7 @@ {"digest":"0657d3ca5ac4e7bf79b00bcf860b1c7159d01a9da137497221ec2f1776e365f7","names":["packages/core/session/src/types.ts#SessionSeq"],"sources":["packages/core/session/src/types.ts:33"]}, {"digest":"07e1a58c58b593f507b8e7f25723bb0aa42baae6e00f5ecfddf28cb1e64d3235","names":["packages/session/session-title/src/types.ts#SessionTitleModelIdentity","packages/subagent/tool-subagent/src/model-selection.ts#AllowedModelRoute"],"sources":["packages/session/session-title/src/types.ts:20","packages/subagent/tool-subagent/src/model-selection.ts:12"]}, {"digest":"07eccc9ea2f9b5439d76cc77d5e062936677d43f07a23da749819b0a22ee36b7","names":[],"sources":[]}, + {"digest":"0880996d224033d9a668528f51edf5f229d9b07dda42fb65f7d1cc1150c12836","names":[],"sources":[]}, {"digest":"09655b34d7f3cf1e9005974de2357de2d4a60deea165d16dac1eadaa6ec539a8","names":[],"sources":[]}, {"digest":"09f3f8dc417f278257202714132f98ba7b52957d7b558c4a04456603890eb363","names":["packages/llm/llm/src/message.ts#SystemMessage"],"sources":["packages/llm/llm/src/message.ts:150"]}, {"digest":"0a30c3be336cdd4f8f34e66543a3d46d611c43986edd9b3ce6cbb9b721d3b5d3","names":[],"sources":["packages/core/session/src/types.ts:213"]}, @@ -92,7 +92,6 @@ {"digest":"0a92c5bdfa06c2e2615b777728f3aa95f408d43b9012e7b754568311251db623","names":[],"sources":["packages/experimental/liveshare/src/host/viewer-principal.ts:29"]}, {"digest":"0aa62ab51b36c0e64b134bd03ba8725d758744180a1a447da49beaad194f219f","names":[],"sources":[]}, {"digest":"0acd94fe8794574c9ae72c7855ee16d29c546096d4af760d16d1225385764555","names":["packages/llm/llm/src/types.ts#ReplayEnvelope"],"sources":["packages/llm/llm/src/types.ts:474"]}, - {"digest":"0aed9f5c80e82b6e80e92eace5b9e23cd5e58c567d37b4321cd147d51342e212","names":["packages/llm/llm/src/message.ts#UserMessage"],"sources":["packages/llm/llm/src/message.ts:161"]}, {"digest":"0af3ecfb8c60d416fc40a7cc4fb2c4851a8e46608b2b38ab9e510670c971aa1f","names":[],"sources":[]}, {"digest":"0b6d718c693fdf7f06dcccb0bcbbabe78cc63514eafc62d6b2a3899735279d6f","names":["packages/goal/goal/src/types.ts#GoalRef"],"sources":["packages/goal/goal/src/types.ts:20"]}, {"digest":"0b9b8facbe2c19773b3fb0ecc824ccbcc603d41b8f18069faa3807d449572fce","names":[],"sources":[]}, @@ -114,7 +113,6 @@ {"digest":"119abe2b9c0b2f46ecb31d82b9acba4d4b30e049f655e2475e8b4ae12d5a9e25","names":[],"sources":["packages/experimental/hook-protocol/src/types.ts:19"]}, {"digest":"11f70b595aa76897fc4e25a352bfa718c659f44b799e5aa14e84e5a38fe72912","names":[],"sources":["packages/interaction/user-approval/src/index.ts:41"]}, {"digest":"124aa62078ca3311353b39cc3bf6c75da281338be6bbf672f8b361d828cddca3","names":[],"sources":[]}, - {"digest":"129f610271310df606674a5ce5c28b444bbf42c231b0f48ad26a0104ffeb6fde","names":[],"sources":["packages/core/session/src/types.ts:321"]}, {"digest":"12a0cfa619ac4a5fc6c3e8e359c8dae15769edc61497a575935c78d5842f8e42","names":[],"sources":[]}, {"digest":"12d5808fac1996b9b3c2afa806e03022252ba2d7b88f835862ae1896591f60c7","names":["packages/llm/llm/src/types.ts#ImageBlock"],"sources":["packages/llm/llm/src/types.ts:86"]}, {"digest":"1379f0b72275994d20f1ddca2d60a96ab16ec80397ca9f1af21bdc67ba5c269c","names":[],"sources":[]}, @@ -165,6 +163,7 @@ {"digest":"21fb6a90d5068f6a0003b7ab316ed2f56342477146a65c00db0f13c4d8df667d","names":[],"sources":[]}, {"digest":"2235d957bf4b7c6cf959231d480f0ba1f3a6d72d82981493fb6c7c963021d3d5","names":[],"sources":["packages/session/working-directory/src/index.ts:49"]}, {"digest":"224aa11d4d5f88c450822d01b99e6ca5e3a9c7f26a5ede10bae33384a09ef4dc","names":[],"sources":[]}, + {"digest":"2314c3471cc0d31445cd2984ceea82f402a284bd31881d9df4423ed82dc49ebe","names":[],"sources":["packages/core/agent/src/types.ts:110"]}, {"digest":"234142ee4f996f38cc9fa3b8b3e3de29b03c9aefe5ebf6c224eddd564505aa85","names":[],"sources":[]}, {"digest":"237c004c73b6b288246816e0d7fde16e09c63a47aa3b1227383d7afe58666163","names":[],"sources":[]}, {"digest":"23af3759678a30de1d11d946772da8c051c63caa67997c5da05d30d7a9fe8a97","names":[],"sources":[]}, @@ -173,7 +172,6 @@ {"digest":"24ce31aa528272e59f21cd26da9eca08968bcc97529756a749bfdab71746d9c8","names":[],"sources":[]}, {"digest":"254dce209e735f9cb6f6b7aec0354712b1611759ec02af4d35a96f2081e666f6","names":[],"sources":[]}, {"digest":"260523b412c19ad8c2bb00093b07f64245ff8ba6b2f76c5b545303772ac9704c","names":[],"sources":[]}, - {"digest":"261128de68865c1f92f2bfa2ccd21f362d6e624cb00fc0cf5558d9d7b82302c5","names":[],"sources":["packages/core/agent/src/types.ts:110"]}, {"digest":"26718e15e7e395bce9642dba5bbe09b3b1a4ce2213d20d566cd9207d7fc5fb78","names":[],"sources":[]}, {"digest":"26c879bdd130e8b8683a6ce588414fad2244783d6573ca399fa0de184a2b0bb1","names":[],"sources":[]}, {"digest":"2765e9119edf5816ac1ab4c95c5ee32c90403f3742962eff11544f7752d59d2e","names":[],"sources":[]}, @@ -196,7 +194,6 @@ {"digest":"2f1e6a7ebace43d727ae138ddcd352eb3813960009e5805b8c5ac84300c97716","names":["packages/attachment/attachment/src/types.ts#ImageMediaType"],"sources":["packages/attachment/attachment/src/types.ts:8"]}, {"digest":"2f3f201c8846e19c20bb75c02280e3d4eb3c57509e4715f0c0a4d1d4f91a7a06","names":[],"sources":[]}, {"digest":"2fe5026daf14bd4ff2b7bfb7cf9791c302d9cbba06802178b6dfec00b892698f","names":["packages/core/tool-executor-ptc/src/types.ts#PtcDispatchStartEventData"],"sources":["packages/core/tool-executor-ptc/src/types.ts:12"]}, - {"digest":"300665af8bcc85dc20a65fd6681ee48d883178731c6f74457ed41539c607bc70","names":[],"sources":[]}, {"digest":"30d5a537b296685770b1241c4b4bbde19d5a31ff81aa23df73fab5e90b8fc65f","names":["packages/session/session-title/src/types.ts#SessionTitleSource"],"sources":["packages/session/session-title/src/types.ts:28"]}, {"digest":"312aee2f0c42aabbae6cc60d92d596d8453c0aeb061c5868d1755a69ef49e69a","names":[],"sources":[]}, {"digest":"31907de9563751822af6d9be02bafaf26faa098bbd1cb412524134d577cc1648","names":["packages/compaction/compaction/src/checkpoint.ts#CompactionCheckpointSource"],"sources":["packages/compaction/compaction/src/checkpoint.ts:21"]}, @@ -217,9 +214,8 @@ {"digest":"383cf73ae4748e5beb281ae74857ba1ffb92ae01075b9fbf51af78b666007a8f","names":[],"sources":[]}, {"digest":"3860b4757d512a2869be833acb0faf834335b1b056bf3f83df5474dce95f8fa6","names":[],"sources":["packages/llm/llm/src/assistant-stream.ts:34"]}, {"digest":"390eed1028aba02774f14408647acec10ec5516e97d4f15ecde2b9989d5a69f2","names":["packages/feedback/message-feedback/src/types.ts#MessageFeedbackRating"],"sources":["packages/feedback/message-feedback/src/types.ts:17"]}, - {"digest":"394ffa61d7dc84ebfd56ad772b59e47be136b95b9549ebf0b77a3bbebf4ce6cc","names":["packages/llm/llm/src/message.ts#MessageSource"],"sources":["packages/llm/llm/src/message.ts:135"]}, {"digest":"39cf2d3ff8bac81c62d49ac2ba38a095b18e80f3ad700819fa1f650a4e60197f","names":["packages/jobs/jobs/src/types.ts#JobToolCall"],"sources":["packages/jobs/jobs/src/types.ts:16"]}, - {"digest":"39fe981d6583647fe76f121c43bd6eac1f1a0d6707297f0901b3078899f9ac92","names":[],"sources":[]}, + {"digest":"3a6f3e4354a90287bb3a1fb19e7a2f643cdbd7c6472c865abd11f8fa2d3358d5","names":[],"sources":[]}, {"digest":"3b04790e08b35241ffa0d38f6d7e4f8788aa921341f6c0d7574a329397c59408","names":[],"sources":[]}, {"digest":"3b1be838223869fe0a08210db85bf773796ed3f2373ac16555dff227cade0c48","names":[],"sources":[]}, {"digest":"3b4f2c9ef2c1217eac596c7b070173cb7896e2fae09e729bc7c56c801e56bb29","names":[],"sources":[]}, @@ -232,6 +228,7 @@ {"digest":"3cfc3a56502da1f8c6153c2c56657bab4b749056968634dd0991d325ec1c919f","names":["packages/core/tools/src/contracts.ts#ToolRestriction"],"sources":["packages/core/tools/src/contracts.ts:395"]}, {"digest":"3d7d07060a7be77984feb651ea2bf1925d3e0477911d9d3ed86330d1e8ca6182","names":["packages/feedback/message-feedback/src/types.ts#MessageFeedbackItem"],"sources":["packages/feedback/message-feedback/src/types.ts:20"]}, {"digest":"3e0eff5946255ff05d88a10839c60305135801f97794ea48d409f8503303317e","names":[],"sources":[]}, + {"digest":"3e2209934365160457426fe5b3f61df85987541ceac7e2ed27f4955bdc181ba2","names":[],"sources":["packages/core/session/src/types.ts:321"]}, {"digest":"3e2ece4967cfebe95f450a93f45523dff99d6749f6269f2f60f84dfecfcf3693","names":[],"sources":[]}, {"digest":"3e4e7683b0192c9f0e6a75c59076108f017892cdb302a98032c2632fd79c356f","names":[],"sources":["packages/compaction/compaction/src/types.ts:24"]}, {"digest":"3ee93b06f3a125850337602bcdf155d2538c43a5c944ec55b1b3c365152d6796","names":[],"sources":[]}, @@ -246,7 +243,6 @@ {"digest":"44818000e56acb97afdb5045ce235eb55e3fb1ccabc9fc7d0750bb38f36a7f8e","names":[],"sources":[]}, {"digest":"44c8c77aa9aa100b0d74d2deee85474b29faa6eee0ac0f662f7abe9931ddd7f2","names":[],"sources":[]}, {"digest":"4513e088d43e6c68425be30451b9f961cc264fe7318ca62681c41d4d78615986","names":[],"sources":[]}, - {"digest":"45e3a4c397121e1a2a455c990b4d45852111b64909ced474d41b9f977ac592a4","names":["packages/llm/llm/src/message.ts#Message"],"sources":["packages/llm/llm/src/message.ts:195"]}, {"digest":"45f005e6bbb7645248be792b715a74bc7fdf5a67f5381655d3a75dcc7aa2112e","names":[],"sources":[]}, {"digest":"45f2a07ea94573123b6ae14db787a40062dec3834f36d8be92c523d40ba28448","names":[],"sources":["packages/interaction/user-approval/src/types.ts:44"]}, {"digest":"477614bca595a9e7adb5a1870be446b9a8684f3ba8950259d6289f2d3b74f028","names":[],"sources":["packages/compaction/compaction-image-offload/src/projection.ts:25"]}, @@ -269,12 +265,13 @@ {"digest":"4d60dddaa65d3da8d4cd014d85ce3d2c2875664dd0433e331d8e9d395289686b","names":["packages/experimental/liveshare/src/host/viewer-principal.ts#ShareViewerPrincipal"],"sources":["packages/experimental/liveshare/src/host/viewer-principal.ts:24"]}, {"digest":"4e011753f8263f436efaabfbb3b4db53a98fc55342c5ded2daf7208b217be159","names":[],"sources":[]}, {"digest":"4e44c9118152f6829634bfd508e47669ab0497caffa380c94b4be91f9390d35d","names":[],"sources":[]}, + {"digest":"4e81b0490558b80c87cd09b214cd958ce0df1bf2bb431c930ff8fd441a8d1df5","names":[],"sources":[]}, {"digest":"4e887768586528565381dadbddee6cef555874148089f4579e0b4b1ad096fc9c","names":["packages/llm/llm/src/types.ts#TextBlock"],"sources":["packages/llm/llm/src/types.ts:69","packages/web/web-search-deepseek/src/provider.ts:67"]}, {"digest":"4edec1b770e8ec4ce1220bf42edc5ac46713a1b48d4caa778dcfc98bad1f28a3","names":[],"sources":[]}, - {"digest":"4ee17e4219bd5fab6148ec0a8b3ec0fb939edb8f211374cf779bc8135ef9bed2","names":[],"sources":[]}, {"digest":"4f507598cf476214aa7646ce7841a7064a9dcb05d0a1eaaefaf79c2b738f160f","names":[],"sources":[]}, {"digest":"4f91f187baeabef5c7950c4780d31bbe39f3345dff591a6cf26ac7e135ac1cf4","names":[],"sources":["packages/context/session-reference/src/types.ts:18"]}, {"digest":"4fb59762612c3e3ac3a3bd4f84c9c148d3c3893bd422ba2b201cc039fabd49bc","names":[],"sources":[]}, + {"digest":"507043f63e859f272ce78f6bc65a7361ee087e5e06301f9c100302230bc887a7","names":[],"sources":[]}, {"digest":"50cf02d875f8a1f1411f4a6fbcffab9120ccef5f74a47331fbf29480e5f68f48","names":[],"sources":[]}, {"digest":"511801b0a6470d98566e8385d3dffddb2b67f79fcf73ed6056f46c3cc0a245a7","names":[],"sources":[]}, {"digest":"516da4cdd6d2f1e5ce488e648578ca51f40e458f707b803e5b24de870e799415","names":[],"sources":[]}, @@ -337,6 +334,8 @@ {"digest":"68f44f59e91c41395076cb77265981a601680ec8a381bbbeb6ab754ffdc94573","names":[],"sources":[]}, {"digest":"69081694be231d56fd9580ba14645fd5e35373202605d5c5c841a9435b5fa3b1","names":[],"sources":[]}, {"digest":"693f4952fb5565da96c06bace8924b098ac2fbc915fde0ff8019701183abc057","names":[],"sources":["packages/llm/llm/src/types.ts:168"]}, + {"digest":"694b070275bbc9a60149e8c669757eab8852dce090484c1a4b45f4c5343be2c8","names":["packages/llm/llm/src/message.ts#MessageSource"],"sources":["packages/llm/llm/src/message.ts:135"]}, + {"digest":"69668f0ad0aabae22bb371efe471e202bcd915f88ca269b95e7ba9b062880f48","names":["packages/llm/llm/src/message.ts#UserMessage"],"sources":["packages/llm/llm/src/message.ts:161"]}, {"digest":"69d238a6e9b08d67f601b1825962963d8d3523cb69ebf6208c697dc5d058c199","names":[],"sources":[]}, {"digest":"6ab45ac76839722df912f3ba50f1c6b41f2d614bde11f1aabfae04117ccdc80d","names":[],"sources":[]}, {"digest":"6b23ed9ce1b397e602788dbe033693bf97642a69e23fcab1cc45bf6f13b6d619","names":[],"sources":[]}, @@ -383,7 +382,6 @@ {"digest":"7d65acf0a3a43a8f445ce5d3320b42eca492739fc931b2a7516bfb8368dc2c68","names":["packages/llm/llm/src/types.ts#ContentBlockType"],"sources":["packages/llm/llm/src/types.ts:155"]}, {"digest":"7df62978a2b7de8540e714152297743e0a622209a46a5ac9513fc0fad73ca23b","names":[],"sources":[]}, {"digest":"7eaef7a763ba5b949b8464bc8add8980a3a5ab566014b69787aeba71e5dfe07b","names":[],"sources":[]}, - {"digest":"7ee5a828196d9e4b1672f94f977e68f37125da4297c23029dd682823c09e12fd","names":[],"sources":[]}, {"digest":"7f13860ee89a2d35ce09f958e85a04566cd59cb1de1d73a9619a9b631961dc71","names":[],"sources":[]}, {"digest":"7f7fd5a6b0064f597534b29ff62ef26e786dffccf5e14f654a7d4fcea2c35f04","names":[],"sources":[]}, {"digest":"7f9365bae9fcb73e1e34061a1acfe0422c1a5fd351848cace9bebbe806f28462","names":["packages/workflow/tool-workflow/src/types.ts#ToolWorkflowRunEndData"],"sources":["packages/workflow/tool-workflow/src/types.ts:36"]}, @@ -418,6 +416,7 @@ {"digest":"88841202942c7683b3b7e5ea6a796047ec326b6701ac23e58cc236d85613b9fa","names":[],"sources":[]}, {"digest":"88a610b831be6d92612a464be5c7d0b88ec24d97bd299837bf74bf7672183c9a","names":[],"sources":["packages/llm/llm/src/types.ts:500"]}, {"digest":"8a046b52331959aa3394680d6acbe09b8a5447c6b61375f263445bfcef19b7f1","names":[],"sources":[]}, + {"digest":"8a2e3e7a523e622b440e444ab934154ba53c0037ad6502437abba4365a852e21","names":[],"sources":[]}, {"digest":"8a6e1ec9e8db346b0e02f027db73c07a94f067a26d40c1aef1abd09c47ce7ba0","names":[],"sources":[]}, {"digest":"8a9c990773f798eac10ca8878e6bcc531ee080bc589cac956730e462cc6a09ad","names":[],"sources":["packages/interaction/permission-presets/src/index.ts:61"]}, {"digest":"8ad45ad053b4d89f8865c17cc9ff3b8748e86045f3f0fb816269a34af2619141","names":[],"sources":["packages/experimental/hook-protocol/src/types.ts:31"]}, @@ -425,6 +424,7 @@ {"digest":"8bb8c3751a6ce64b61aba1ec7ae798c00a5803c4d868a0430873216c6569ed52","names":[],"sources":["packages/session/session-log-deepseek/src/types.ts:96"]}, {"digest":"8c1c4f72755a78ea163523a46565316e36e9b644382eb48e6635c71a6f412dd2","names":[],"sources":[]}, {"digest":"8c627d7a45fa406cea879a3922105e27ed4c3c7966e264afaf11ea7a330f2dd1","names":[],"sources":[]}, + {"digest":"8c9911b902a2fda47058d4dd5113f99abc57ed97b098cf295ae64c49645623f8","names":[],"sources":[]}, {"digest":"8cdd3fdd295cee53035de16a1b23411716f75e9f994fe9510cac5d7fef605c76","names":[],"sources":[]}, {"digest":"8e31bb958e9b015e6f8407eaade32217068159e816f3cc99c3ad76eb889732e0","names":[],"sources":["packages/llm/llm/src/types.ts:167"]}, {"digest":"8e611bf46821e5003a1605a73560a6f56388295149d449dfe2142d5ec335f29c","names":["packages/llm/llm/src/types.ts#ToolAdditionBlock"],"sources":["packages/llm/llm/src/types.ts:122"]}, @@ -463,6 +463,7 @@ {"digest":"9acbe713f3f641921dd3333b240aa72e176d795327c24e8d9db9b68b16771b49","names":[],"sources":[]}, {"digest":"9b4fd974c124c83743efe030ba4e1250e087505f3f74588716a521fb8d453267","names":[],"sources":[]}, {"digest":"9c001ecb5e1d3c3894410db2a1e383842e5f8454fb52182338686158abc1b3ee","names":[],"sources":["packages/web/web-search-deepseek/src/provider.ts:62"]}, + {"digest":"9d42da116fccdc399c2877bb46488c6690e3968c02de6ff2a55e83adc67cc496","names":[],"sources":[]}, {"digest":"9d80129e13edfb6feb03ed327e6085c6ef60b97ad074244b2f5fd4667424a6a4","names":[],"sources":[]}, {"digest":"9e07693fd7cd9babe0688c22c986e4d519ae1c0e40eeea13b2dc583bed2abc86","names":[],"sources":[]}, {"digest":"9e2c06d8653585b33d72d5c1a80da79c8a24a88c284409bca15cc0f0ead5ebfb","names":[],"sources":[]}, @@ -486,6 +487,7 @@ {"digest":"a43327a1739c3fa477f32981071fef7d8ba6ae5f32a84fd70f547b2eee59e93e","names":[],"sources":[]}, {"digest":"a4afec59b75aad5d13ef82d6931f35cc2d98918503916cf069355b77c5e42302","names":[],"sources":["packages/api/session-controller/src/types.ts:392"]}, {"digest":"a6567ccb2e530606b775371eb4fa31468d72084339968e8b0440a516a23b39dc","names":[],"sources":[]}, + {"digest":"a6816f39283ae26f0cd16cfce35724eb676a1f1b57afbc91094a36b2d2a40b2d","names":[],"sources":[]}, {"digest":"a6b41f5bede8094d7bf635be5d69b1bd7a25e006ca9cf9415bceb9322f1a7feb","names":["packages/experimental/hook-protocol/src/types.ts#HookDialect"],"sources":["packages/experimental/hook-protocol/src/types.ts:48"]}, {"digest":"a6da9ad5d42ae83a6833a8288b076688e8e0801633ea36cbdd8a30a6d9f3160c","names":["packages/workflow/tool-workflow/src/types.ts#ToolWorkflowRunStartData"],"sources":["packages/workflow/tool-workflow/src/types.ts:14"]}, {"digest":"a720757f704a2512e9d2f20da4a093e582472176236a75ab8b8eb7aaff17d85a","names":[],"sources":[]}, @@ -521,6 +523,7 @@ {"digest":"b0127044ab31a702bddfd785d345f5abd7a70876746e895ce443afa3e60ddf2d","names":[],"sources":[]}, {"digest":"b062078e899958f99ae464514578b8c093924dfe34bd9a835932b420ff2150b1","names":[],"sources":[]}, {"digest":"b0b0eb1b16490f6bee135b2377e8f8c39227974c799ad7d49ff418af23ecbc35","names":["packages/attachment/attachment/src/types.ts#ImageAttachmentRef"],"sources":["packages/attachment/attachment/src/types.ts:11"]}, + {"digest":"b0e809a7fc2b90682c073e6a137f65fc2e93730ff28e3d6df39b785e71e8a497","names":["packages/llm/llm/src/message.ts#DeveloperMessage"],"sources":["packages/llm/llm/src/message.ts:156"]}, {"digest":"b158f3ff6923714807c0d73882f0b05dc87f8fa85c9e90814852d48bbc866081","names":["packages/core/session/src/types.ts#RequestContext"],"sources":["packages/core/session/src/types.ts:264"]}, {"digest":"b1664fa89f8eab49a14e7e3168d8bc4da4aa9fd76332f6c4a053d839e5276ae7","names":[],"sources":[]}, {"digest":"b1ebd5cda47d90d980bb05bffc3f970c51537b9aff15b3bc3d639811727741b1","names":[],"sources":["packages/team/agent-team/src/types.ts:179"]}, @@ -567,6 +570,7 @@ {"digest":"bcf0caf62d964b2fcf5404bd5c909cfa9a21c3f3c96e6b7e36d9e33565223825","names":[],"sources":["packages/core/session/src/types.ts:476"]}, {"digest":"bd499eac047efe091a4df7382eadd06d25cf0cb31fee3981e8b24d85762841cd","names":[],"sources":[]}, {"digest":"bf16d2e98a7f13894ded2cffe5ce857bf473954a0e3c0ed9bc7739e2e1c7b78a","names":[],"sources":[]}, + {"digest":"c071d01c76a37f9fee2f29616b0aac535c87d4375d6131ef2794962be950b55e","names":["packages/session/session-title-llm/src/index.ts#SessionTitleLlmRequestEventData"],"sources":["packages/session/session-title-llm/src/index.ts:43"]}, {"digest":"c0ea97bc89dfc46fa94eab956f5c3ee6af2f964aa7db6327cb18b451f207bef7","names":["packages/workflow/tool-workflow/src/types.ts#ToolWorkflowAgentEndData"],"sources":["packages/workflow/tool-workflow/src/types.ts:29"]}, {"digest":"c170da8ab7c37635b10867b2571811d9e317ac3ec394e8ff8efe53f902fc41c1","names":["packages/llm/llm-retry/src/types.ts#LlmRetryEventData"],"sources":["packages/llm/llm-retry/src/types.ts:16"]}, {"digest":"c1f0f17b6493b85db6453bb30e01b208d703731b25bc1e68e5d4fc72eea9cdea","names":["packages/llm/llm/src/types.ts#ToolCallBlock"],"sources":["packages/llm/llm/src/types.ts:112"]}, @@ -594,6 +598,7 @@ {"digest":"cda2345a9be9d139df49ccbd16dcba716f3440178bf20ff8b801fda1f5eb77dc","names":[],"sources":[]}, {"digest":"cdca80b8dad24d4e7b1d5a288a8475ba8d8d46be385bd2da85f122ee836f1670","names":[],"sources":[]}, {"digest":"cdee10e87dbed8440d8b6935888624884878efc7af95402e94171b29f173dced","names":[],"sources":["packages/llm/llm-retry/src/types.ts:17"]}, + {"digest":"ce6e647c9e653b5d496d551f9e48980ceafc8eb0e6b4093f0b3e4da55164c99b","names":[],"sources":[]}, {"digest":"cef171adf021a1867d244618a3dbbaafc22beb17c7f3df3ee203393271c8c6f6","names":["packages/core/tool-executor-ptc/src/types.ts#PtcDispatchEventData"],"sources":["packages/core/tool-executor-ptc/src/types.ts:21"]}, {"digest":"cffcdc19881ab61ec0a9ce18743996f7ac44ac8889f34dfac36ae745574aa22f","names":["packages/goal/goal/src/domain.ts#GoalClearChangeMeta"],"sources":["packages/goal/goal/src/domain.ts:35"]}, {"digest":"d0fbb0ca1bbba059830826f33f801da1aced35a2504376d61e020bdfec8d50c0","names":[],"sources":[]}, @@ -648,6 +653,7 @@ {"digest":"e6063d0451dc02026fd9b54ad3f77c7b1b6392ad3e872a7737ac84e13ca72344","names":["packages/schedule/schedule/src/types.ts#EveryScheduleDispatchChange"],"sources":["packages/schedule/schedule/src/types.ts:220"]}, {"digest":"e6411b09c1d982f789bf741ca74e2bea69df56029847f86a6148e722039ee732","names":[],"sources":[]}, {"digest":"e72269f931559e901e5e8fe1cfcbd0669fb795f43cc038ff39fba62f60403c33","names":[],"sources":["packages/llm/llm/src/assistant-stream.ts:20"]}, + {"digest":"e744baea6a5d54efc05ce47ebae956fc138a76dad8e605f49b5a7f1c294823a8","names":["packages/llm/llm/src/message.ts#Message"],"sources":["packages/llm/llm/src/message.ts:195"]}, {"digest":"e75916628f3f10c2d50658bd143052a46285fbf1a9a700ba54947614603d26b4","names":[],"sources":[]}, {"digest":"e7ce49f12953583fad217bf80fb9f1463acff2c3e9471a823782661675fb124c","names":[],"sources":[]}, {"digest":"e7e154d47d5fbc5366330fb4dade1f108c6dfe4335044d21ded14b7bf1dce084","names":[],"sources":[]}, @@ -655,6 +661,7 @@ {"digest":"e7f4cbb3a57f4cbdb61ea41e95bcba626ad1fff6bb9b1e063b1d50a32da6e864","names":[],"sources":[]}, {"digest":"e8de0f457fed5b9ff94dc4950b59ef75fd8ba8af665cc7899485924a62653367","names":[],"sources":[]}, {"digest":"e95f957154b2b1b58692af53d4131180b6dd19e2264869f876dbaa959991494e","names":[],"sources":[]}, + {"digest":"e973903c6f32109ccaaceba75f6c6cec33fe7f8d684e24627760cc53916af848","names":[],"sources":[]}, {"digest":"ea08ec1df0c33108fd03345b9af199cf04dea450aa045d3c683f216311403403","names":[],"sources":["packages/team/agent-team/src/types.ts:183"]}, {"digest":"eaa71be0fbf0f702df8ea6c11d0aa2f9782263d45a10d0fb14eda662f4bfe04c","names":[],"sources":["packages/core/session/src/types.ts:205"]}, {"digest":"ebb768d85ec87fb68e42fc14fd7d8535b5ac11791b14d04c6770180f0a719bf8","names":[],"sources":[]}, @@ -662,7 +669,6 @@ {"digest":"ec8b5ff7c77ca6893ac7ba5a0c5b2aefeb52f12c64450b7359660c2a7e8a53d7","names":[],"sources":["packages/core/session/src/types.ts:238"]}, {"digest":"edbbfff1128099fda7b792c56330d2cb04debc9790988e66d1c3f4026e813e0e","names":[],"sources":[]}, {"digest":"edd37b1e4974af648633014435572089b1e8fb71910468a0767a7e28fdd22abf","names":[],"sources":[]}, - {"digest":"ee4277d9b4c96ab0a024b3c65d294712b6721808c564162bce7f7feed40c139f","names":["packages/session/session-title-llm/src/index.ts#SessionTitleLlmRequestEventData"],"sources":["packages/session/session-title-llm/src/index.ts:43"]}, {"digest":"ee577a0cc18664c9daee50e9455153321155604f8f1817362f8f4a4b6fb9e1ad","names":[],"sources":[]}, {"digest":"eea687d437880bd5f55fb447a561112800ca34334c0724d9cecb98493059d9e4","names":["packages/schedule/schedule/src/types.ts#ScheduleCreateChange"],"sources":["packages/schedule/schedule/src/types.ts:199"]}, {"digest":"eefbea819caeeea91ccb02dfafc16c68dd7f961cf9c1b2be25a2084509cf5c5a","names":[],"sources":[]}, @@ -682,7 +688,6 @@ {"digest":"f4a66f654996c093aae700ea4c434ff2ee3569fea9c0e5813ccf6afdccabd163","names":[],"sources":[]}, {"digest":"f5520c1d261ca86ea03735799c311a0a9ede8babb588cf0a65422576d2ee0ad1","names":[],"sources":[]}, {"digest":"f56c5b59ca0161310c338d31dd16cf14287ccd602ff4181058df178c1c286d7f","names":["packages/context/session-reference/src/types.ts#SessionReferenceSource"],"sources":["packages/context/session-reference/src/types.ts:13"]}, - {"digest":"f5d843edb0eeef61c9f5328599d5f92b61112b7710b0310b043196b15b390d64","names":[],"sources":[]}, {"digest":"f6329fb30c7ea8013e8975ca5e78284fb7685cc6bd620e8aa4e9a99bc81d45eb","names":[],"sources":[]}, {"digest":"f634871d1e18b1eb199497ac8ab72d3964f48d03fbf611dc7521a1970cf429d9","names":[],"sources":[]}, {"digest":"f6605d6c57933aeaaf10911b5fbd6c61e655baa181af7192d3240f49d255b90d","names":[],"sources":[]}, @@ -699,7 +704,6 @@ {"digest":"fab2bb09bc5e3b9db0685e8f5500b029af1a2b33e70bc703c1d5d0f596fbc1fd","names":["packages/sandbox/sandbox/src/index.ts#SandboxMode"],"sources":["packages/sandbox/sandbox/src/index.ts:38"]}, {"digest":"fab35c4520883c0d69e42d079c9f543fc5ac7a2d15b537b5572fcd99059c7018","names":[],"sources":[]}, {"digest":"fb5e0517050d2c6d40e5b8145db1f7c5ca7044d5d50fada6ff80e0b22c6ca973","names":[],"sources":[]}, - {"digest":"fb6a6e338625067ac582f55dde412a583040cd738bb8fc6820cb0b941c59f05a","names":[],"sources":[]}, {"digest":"fb8b6a2e53cb9cf44c551176de0fb77d1ddc60037b99a891ff8a860b6d5c29a0","names":[],"sources":[]}, {"digest":"fbd2c74b346a1595b376139c587fadd23e4a21acc9c0abce342975b6cfc60986","names":[],"sources":[]}, {"digest":"fc351843b8ecbd05d739c4ca4fcd4bc7cfad6c0beacbbd48389959bb1bf06cf3","names":[],"sources":[]}, @@ -712,7 +716,6 @@ {"digest":"fee1caf8ab6a65c1bc981f5a1730164490f22a2a89ffa3d0b76f1f432c44c8b5","names":[],"sources":[]} ], "nodes": { - "010783c095f1d9bd": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"589d0d91239681f8","optional":false},{"name":"source","type":"394ffa61d7dc84eb","optional":false,"compatibility":{"version":1,"policy":"session-source-attribution","binding":"session.developer-message.source","discriminator":"kind","unknownKinds":"preserve","attributionKinds":["action-cards","tmux-context","user-question-reply","working-directory"]}}],"indices":[]}, "0116b1f89c05221d": {"kind":"literal","value":"web_search_20250305"}, "0203243b72fc867a": {"kind":"object","properties":[{"name":"kind","type":"24b10f7cdae64928","optional":false}],"indices":[]}, "022623b9ef98ec47": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false}],"indices":[]}, @@ -727,6 +730,7 @@ "0657d3ca5ac4e7bf": {"kind":"primitive","type":"number"}, "07e1a58c58b593f5": {"kind":"object","properties":[{"name":"model","type":"4cd48f3e5108bd6e","optional":false},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "07eccc9ea2f9b543": {"kind":"literal","value":"security-privacy-permission"}, + "0880996d224033d9": {"kind":"object","properties":[{"name":"data","type":"2314c3471cc0d314","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"829a2fb3be6efd4b","optional":false}],"indices":[]}, "09655b34d7f3cf1e": {"kind":"literal","value":"system-prompt"}, "09f3f8dc417f2782": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"8af841fc9b265ade","optional":false},{"name":"source","type":"65a8400e451e667e","optional":false}],"indices":[]}, "0a30c3be336cdd4f": {"kind":"object","properties":[{"name":"kind","type":"1e0b0b66b6f0c53f","optional":false},{"name":"reason","type":"1f8c126cfab3df81","optional":false}],"indices":[]}, @@ -734,7 +738,6 @@ "0a92c5bdfa06c2e2": {"kind":"object","properties":[{"name":"displayName","type":"4cd48f3e5108bd6e","optional":true},{"name":"providerId","type":"4cd48f3e5108bd6e","optional":false},{"name":"subjectId","type":"4cd48f3e5108bd6e","optional":false},{"name":"tenantId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "0aa62ab51b36c0e6": {"kind":"object","properties":[],"indices":[{"key":"4cd48f3e5108bd6e","value":"bbc5696e3f13c758"}]}, "0acd94fe8794574c": {"kind":"object","properties":[{"name":"blocks","type":"b1664fa89f8eab49","optional":true},{"name":"response","type":"bbc5696e3f13c758","optional":false}],"indices":[]}, - "0aed9f5c80e82b6e": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"68f44f59e91c4139","optional":false},{"name":"source","type":"394ffa61d7dc84eb","optional":false,"compatibility":{"version":1,"policy":"session-source-attribution","binding":"session.user-message.source","discriminator":"kind","unknownKinds":"preserve","attributionKinds":["action-cards","tmux-context","user-question-reply","working-directory"]}}],"indices":[]}, "0af3ecfb8c60d416": {"kind":"literal","value":"turn/start"}, "0b6d718c693fdf7f": {"kind":"object","properties":[{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"revision","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "0b9b8facbe2c1977": {"kind":"literal","value":"disabled"}, @@ -756,7 +759,6 @@ "119abe2b9c0b2f46": {"kind":"object","properties":[{"name":"dialect","type":"a6b41f5bede8094d","optional":false},{"name":"handlerId","type":"4cd48f3e5108bd6e","optional":false},{"name":"matcher","type":"4cd48f3e5108bd6e","optional":true},{"name":"point","type":"4cd48f3e5108bd6e","optional":false},{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "11f70b595aa76897": {"kind":"object","properties":[{"name":"policy","type":"05d2ae1e0c7f8770","optional":false},{"name":"source","type":"76632533f67879dc","optional":true}],"indices":[]}, "124aa62078ca3311": {"kind":"object","properties":[{"name":"data","type":"da60ed58a8fa23d7","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"d4c799e3d51cae10","optional":false}],"indices":[]}, - "129f610271310df6": {"kind":"object","properties":[{"name":"headerSeq","type":"0657d3ca5ac4e7bf","optional":true},{"name":"message","type":"010783c095f1d9bd","optional":false},{"name":"step","type":"0657d3ca5ac4e7bf","optional":false},{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "12a0cfa619ac4a5f": {"kind":"literal","value":"read-only"}, "12d5808fac1996b9": {"kind":"object","properties":[{"name":"attachment","type":"b0b0eb1b16490f6b","optional":false},{"name":"offloaded","type":"dacf3d5f3e4ff619","optional":true},{"name":"type","type":"fb8b6a2e53cb9cf4","optional":false}],"indices":[]}, "1379f0b72275994d": {"kind":"literal","value":"developer/message"}, @@ -807,6 +809,7 @@ "21fb6a90d5068f6a": {"kind":"object","properties":[{"name":"data","type":"ea08ec1df0c33108","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"4e011753f8263f43","optional":false}],"indices":[]}, "2235d957bf4b7c6c": {"kind":"object","properties":[{"name":"kind","type":"7b1ce60193fa8b69","optional":false}],"indices":[]}, "224aa11d4d5f88c4": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false}],"indices":[]}, + "2314c3471cc0d314": {"kind":"object","properties":[{"name":"inserted","type":"8c9911b902a2fda4","optional":false},{"name":"outcome","type":"d4e4d575abeb4b72","optional":true},{"name":"removedCount","type":"0657d3ca5ac4e7bf","optional":true},{"name":"start","type":"0657d3ca5ac4e7bf","optional":false},{"name":"target","type":"96f4a9c81fc0f940","optional":false}],"indices":[]}, "234142ee4f996f38": {"kind":"literal","value":"pending"}, "237c004c73b6b288": {"kind":"literal","value":"goal/change"}, "23af3759678a30de": {"kind":"literal","value":"dsh-session-title-llm"}, @@ -815,7 +818,6 @@ "24ce31aa528272e5": {"kind":"object","properties":[{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, "254dce209e735f9c": {"kind":"literal","value":"blocked"}, "260523b412c19ad8": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false}],"indices":[]}, - "261128de68865c1f": {"kind":"object","properties":[{"name":"inserted","type":"300665af8bcc85dc","optional":false},{"name":"outcome","type":"d4e4d575abeb4b72","optional":true},{"name":"removedCount","type":"0657d3ca5ac4e7bf","optional":true},{"name":"start","type":"0657d3ca5ac4e7bf","optional":false},{"name":"target","type":"96f4a9c81fc0f940","optional":false}],"indices":[]}, "26718e15e7e395bc": {"kind":"object","properties":[{"name":"data","type":"11f70b595aa76897","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"36d6a9a871d949ea","optional":false}],"indices":[]}, "26c879bdd130e8b8": {"kind":"literal","value":"dispatch"}, "2765e9119edf5816": {"kind":"literal","value":"model"}, @@ -838,7 +840,6 @@ "2f1e6a7ebace43d7": {"kind":"union","types":["3f74ba74acd10644","58f94390b982f8a5","de30b1fa12c75f81","ebb768d85ec87fb6"]}, "2f3f201c8846e19c": {"kind":"literal","value":"tool-goal"}, "2fe5026daf14bd4f": {"kind":"object","properties":[{"name":"arguments","type":"bbc5696e3f13c758","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":false},{"name":"parentCallId","type":"4cd48f3e5108bd6e","optional":false},{"name":"rootCallId","type":"4cd48f3e5108bd6e","optional":false},{"name":"subCallId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, - "300665af8bcc85dc": {"kind":"array","element":"0aed9f5c80e82b6e"}, "30d5a537b2966857": {"kind":"union","types":["1b5649238876e288","ada310bf0bdb8fed","b81e9de81a481b24"]}, "312aee2f0c42aabb": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "31907de956375182": {"kind":"object","properties":[{"name":"compactionId","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"6b23ed9ce1b397e6","optional":false},{"name":"sourceCommandId","type":"4cd48f3e5108bd6e","optional":true}],"indices":[]}, @@ -859,9 +860,8 @@ "383cf73ae4748e5b": {"kind":"literal","value":"recall"}, "3860b4757d512a28": {"kind":"object","properties":[{"name":"args","type":"93c33d9687613293","optional":false},{"name":"dt","type":"5d03ba38734809bc","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"index","type":"0657d3ca5ac4e7bf","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":true},{"name":"time0","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"616f93a5047de668","optional":false}],"indices":[]}, "390eed1028aba027": {"kind":"union","types":["b1f62380f6746fed","df5d9709b7db2a72"]}, - "394ffa61d7dc84eb": {"kind":"union","types":["0203243b72fc867a","022623b9ef98ec47","02b2c23f2d94b028","0ed8d1108fe7a5e1","0eeb17e1df89b1eb","11638dc58a31496f","1938c8c20f1cba7c","1e709346005826eb","1fdad624334d3548","2152caf1a71e588e","2235d957bf4b7c6c","224aa11d4d5f88c4","24ce31aa528272e5","260523b412c19ad8","28936c614bd4e7e2","290f32bfd81ff85a","297fbd8067d7815a","2aad1179f9576314","312aee2f0c42aabb","31907de956375182","3247e566f4340029","3b04790e08b35241","3b4f2c9ef2c1217e","3bdb8dc6989655b0","408927267422a7b2","45f005e6bbb76452","4991dfc415c9efeb","49dab019d00e8c26","4a9bef9f27a94252","52c6113cb0e53f34","53cf1704ae0709c7","5654685d7557ec74","58015da1c1950a66","5bb69b88517f6214","5bc66269cfaf614c","5cdbf342b7748d15","5d7a64ed6aac5551","6085488d223aeffd","6292bcbedaa97fea","65a8400e451e667e","65d583e66518c523","672c4aa2a9b736e3","6ccb6bc423fb3952","6ea608bdc8a7a63d","6f22a9d02b9a1f11","6f44f32be9bcd9a8","719c51f67074f970","7554565be416b034","756b5e23a5cb2c7f","7df62978a2b7de85","7eaef7a763ba5b94","7f959241c24128b4","80677c8c8b804189","825ca23416b1ea9d","8338ee303e2bd448","848639f8787f035b","854db3efdfb0cd39","85fe96bf15d5c755","8620189c8e335827","87b1a33564b9a4d6","88841202942c7683","8a046b52331959aa","8c1c4f72755a78ea","8c627d7a45fa406c","8f1062573ea91841","8f324cea3916c051","8fcb0b44a575e998","96bfb916a727cd44","99135d8a39379779","99f0e98184709ad1","9edc162949abf93b","9f65c43e340bba31","a15a19ef63cf5d1b","a16e567c8cd2c55c","a2066bd52f61218b","a3c6f1ea38e9a61d","a4afec59b75aad5d","aa2bf9e82b9fdeb9","aae343bc3d663c83","ada310bf0bdb8fed","ade057f4fdc387ae","b062078e899958f9","b2a5c8c008a31e3d","b3681c026a0b98e9","b4ec0af39fd52ed9","b613f83572fe2fbf","b6f94c17dd9bbd7c","b70f3e81fe11b7a5","b79641a9d25e7566","ba2a1a8f194b1bb2","ba4c40b4381e0dcd","baccc97ec34be6c4","c5228b7a55498d84","c55827fba7018198","cb1c8959e1726f82","cda2345a9be9d139","d215701afb7aafbf","d85590a5675c6e2f","d9c462b9f62fdd3e","db06ef35b27a3842","dba54c09c6e7aafc","dd00cdccd0ba487b","dd5ee8762bd8a14b","dd6cc2bb2a8f2824","dde0cdf9d426768b","deaae5cd30987d4f","e7f4cbb3a57f4cbd","edbbfff1128099fd","ee577a0cc18664c9","f230c0b583e23b25","f29d63336e8266d8","f4a66f654996c093","f56c5b59ca016131","f6329fb30c7ea801","f6605d6c57933aea","f6afe41e3926f422","f7283223aacdc39b","f97f47b0eb87905e","fcf81d3c58c13593","fe1a7acdeed4d0f5"]}, "39cf2d3ff8bac81c": {"kind":"object","properties":[{"name":"callId","type":"4cd48f3e5108bd6e","optional":false},{"name":"rootCallId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, - "39fe981d6583647f": {"kind":"array","element":"45e3a4c397121e1a"}, + "3a6f3e4354a90287": {"kind":"object","properties":[{"name":"data","type":"3e22099343651604","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sourceEventSeqs","type":"5d03ba38734809bc","optional":true},{"name":"surfaceOp","type":"335e242de1fcc17b","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"1379f0b72275994d","optional":false}],"indices":[]}, "3b04790e08b35241": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, "3b1be838223869fe": {"kind":"object","properties":[{"name":"data","type":"e4c18e294232c3ba","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"c589e938cc0e4989","optional":false}],"indices":[]}, "3b4f2c9ef2c1217e": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false}],"indices":[]}, @@ -874,6 +874,7 @@ "3cfc3a56502da1f8": {"kind":"object","properties":[{"name":"allow","type":"93c33d9687613293","optional":true},{"name":"deny","type":"93c33d9687613293","optional":true}],"indices":[]}, "3d7d07060a7be779": {"kind":"object","properties":[{"name":"category","type":"3305a4bb6b6c29b4","optional":true},{"name":"createdAt","type":"0657d3ca5ac4e7bf","optional":false},{"name":"messageId","type":"4cd48f3e5108bd6e","optional":false},{"name":"note","type":"4cd48f3e5108bd6e","optional":true},{"name":"rating","type":"390eed1028aba027","optional":false},{"name":"updatedAt","type":"0657d3ca5ac4e7bf","optional":false},{"name":"version","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "3e0eff5946255ff0": {"kind":"literal","value":"request/header"}, + "3e22099343651604": {"kind":"object","properties":[{"name":"headerSeq","type":"0657d3ca5ac4e7bf","optional":true},{"name":"message","type":"b0e809a7fc2b9068","optional":false},{"name":"step","type":"0657d3ca5ac4e7bf","optional":false},{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "3e2ece4967cfebe9": {"kind":"literal","value":"next-step"}, "3e4e7683b0192c9f": {"kind":"object","properties":[{"name":"compactionId","type":"4cd48f3e5108bd6e","optional":false},{"name":"sourceCommandId","type":"4cd48f3e5108bd6e","optional":true},{"name":"turn","type":"3bd652ebfa8726b3","optional":false}],"indices":[]}, "3ee93b06f3a12585": {"kind":"object","properties":[{"name":"data","type":"7c6129b6961cf4b2","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"44818000e56acb97","optional":false}],"indices":[]}, @@ -888,7 +889,6 @@ "44818000e56acb97": {"kind":"literal","value":"feedback/message-delete"}, "44c8c77aa9aa100b": {"kind":"literal","value":"subagent/catalog"}, "4513e088d43e6c68": {"kind":"object","properties":[{"name":"data","type":"ef11a3b7fa2033ae","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"2c64d4bc7264fd3f","optional":false}],"indices":[]}, - "45e3a4c397121e1a": {"kind":"union","types":["010783c095f1d9bd","09f3f8dc417f2782","0aed9f5c80e82b6e","4b259f7f8f0a44ad","fa87537f4a9c1e25"]}, "45f005e6bbb76452": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "45f2a07ea9457312": {"kind":"object","properties":[{"name":"callId","type":"4cd48f3e5108bd6e","optional":true},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"reason","type":"4cd48f3e5108bd6e","optional":true},{"name":"toolName","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "477614bca595a9e7": {"kind":"object","properties":[{"name":"targets","type":"9e2c06d8653585b3","optional":false}],"indices":[]}, @@ -911,12 +911,13 @@ "4d60dddaa65d3da8": {"kind":"object","properties":[{"name":"actor","type":"0a92c5bdfa06c2e2","optional":false},{"name":"kind","type":"6ba7edb6447b6a3e","optional":false},{"name":"shareId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "4e011753f8263f43": {"kind":"literal","value":"team/message/queued"}, "4e44c9118152f682": {"kind":"literal","value":"text"}, + "4e81b0490558b80c": {"kind":"object","properties":[{"name":"data","type":"c071d01c76a37f9f","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"587bb11da730e06a","optional":false}],"indices":[]}, "4e88776858652856": {"kind":"object","properties":[{"name":"text","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"4e44c9118152f682","optional":false}],"indices":[]}, "4edec1b770e8ec4c": {"kind":"literal","value":"ptc-mode"}, - "4ee17e4219bd5fab": {"kind":"object","properties":[{"name":"data","type":"ee4277d9b4c96ab0","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"587bb11da730e06a","optional":false}],"indices":[]}, "4f507598cf476214": {"kind":"literal","value":"series"}, "4f91f187baeabef5": {"kind":"object","properties":[{"name":"capturedFormatVersion","type":"0657d3ca5ac4e7bf","optional":true},{"name":"capturedThroughSeq","type":"3bd652ebfa8726b3","optional":false},{"name":"compacted","type":"aa93010d0e521ad7","optional":false},{"name":"inputIndex","type":"0657d3ca5ac4e7bf","optional":false},{"name":"label","type":"4cd48f3e5108bd6e","optional":false},{"name":"omittedBytes","type":"0657d3ca5ac4e7bf","optional":false},{"name":"omittedMessages","type":"0657d3ca5ac4e7bf","optional":false},{"name":"originalMessages","type":"0657d3ca5ac4e7bf","optional":false},{"name":"retainedMessages","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sessionId","type":"4cd48f3e5108bd6e","optional":false},{"name":"truncated","type":"aa93010d0e521ad7","optional":false}],"indices":[]}, "4fb59762612c3e3a": {"kind":"object","properties":[{"name":"data","type":"b1ebd5cda47d90d9","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"18fcdd273a2f2f9d","optional":false}],"indices":[]}, + "507043f63e859f27": {"kind":"object","properties":[{"name":"data","type":"69668f0ad0aabae2","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sourceEventSeqs","type":"5d03ba38734809bc","optional":true},{"name":"surfaceOp","type":"335e242de1fcc17b","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"de25352d2dc41963","optional":false}],"indices":[]}, "50cf02d875f8a1f1": {"kind":"union","types":["2da725e554cd8930","dd2780e7e0768433"]}, "511801b0a6470d98": {"kind":"literal","value":"success"}, "516da4cdd6d2f1e5": {"kind":"object","properties":[{"name":"data","type":"9890113e97dd3541","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"ca085dba2c877fec","optional":false}],"indices":[]}, @@ -979,6 +980,8 @@ "68f44f59e91c4139": {"kind":"literal","value":"user"}, "69081694be231d56": {"kind":"object","properties":[{"name":"data","type":"6bc8e51124d0874b","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sourceEventSeqs","type":"5d03ba38734809bc","optional":true},{"name":"surfaceOp","type":"335e242de1fcc17b","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"1c5a58f4599bd4a9","optional":false}],"indices":[]}, "693f4952fb5565da": {"kind":"object","properties":[{"name":"failure","type":"5f2117d1856a5ab4","optional":false},{"name":"kind","type":"a2be0f0cb59f0d4a","optional":false}],"indices":[]}, + "694b070275bbc9a6": {"kind":"union","types":["0203243b72fc867a","022623b9ef98ec47","02b2c23f2d94b028","0ed8d1108fe7a5e1","0eeb17e1df89b1eb","11638dc58a31496f","1938c8c20f1cba7c","1e709346005826eb","1fdad624334d3548","2152caf1a71e588e","2235d957bf4b7c6c","224aa11d4d5f88c4","24ce31aa528272e5","260523b412c19ad8","28936c614bd4e7e2","290f32bfd81ff85a","297fbd8067d7815a","2aad1179f9576314","312aee2f0c42aabb","31907de956375182","3247e566f4340029","3b04790e08b35241","3b4f2c9ef2c1217e","3bdb8dc6989655b0","408927267422a7b2","45f005e6bbb76452","4991dfc415c9efeb","49dab019d00e8c26","4a9bef9f27a94252","52c6113cb0e53f34","53cf1704ae0709c7","5654685d7557ec74","58015da1c1950a66","5bb69b88517f6214","5bc66269cfaf614c","5cdbf342b7748d15","5d7a64ed6aac5551","6085488d223aeffd","6292bcbedaa97fea","65a8400e451e667e","65d583e66518c523","672c4aa2a9b736e3","6ccb6bc423fb3952","6ea608bdc8a7a63d","6f22a9d02b9a1f11","6f44f32be9bcd9a8","719c51f67074f970","7554565be416b034","756b5e23a5cb2c7f","7df62978a2b7de85","7eaef7a763ba5b94","7f959241c24128b4","80677c8c8b804189","825ca23416b1ea9d","8338ee303e2bd448","848639f8787f035b","854db3efdfb0cd39","85fe96bf15d5c755","8620189c8e335827","87b1a33564b9a4d6","88841202942c7683","8a046b52331959aa","8a2e3e7a523e622b","8c1c4f72755a78ea","8c627d7a45fa406c","8f1062573ea91841","8f324cea3916c051","8fcb0b44a575e998","96bfb916a727cd44","99135d8a39379779","99f0e98184709ad1","9edc162949abf93b","9f65c43e340bba31","a15a19ef63cf5d1b","a16e567c8cd2c55c","a2066bd52f61218b","a3c6f1ea38e9a61d","a4afec59b75aad5d","aa2bf9e82b9fdeb9","aae343bc3d663c83","ada310bf0bdb8fed","ade057f4fdc387ae","b062078e899958f9","b2a5c8c008a31e3d","b3681c026a0b98e9","b4ec0af39fd52ed9","b613f83572fe2fbf","b6f94c17dd9bbd7c","b70f3e81fe11b7a5","b79641a9d25e7566","ba2a1a8f194b1bb2","ba4c40b4381e0dcd","baccc97ec34be6c4","c5228b7a55498d84","c55827fba7018198","cb1c8959e1726f82","cda2345a9be9d139","ce6e647c9e653b5d","d215701afb7aafbf","d85590a5675c6e2f","d9c462b9f62fdd3e","db06ef35b27a3842","dba54c09c6e7aafc","dd00cdccd0ba487b","dd5ee8762bd8a14b","dd6cc2bb2a8f2824","dde0cdf9d426768b","deaae5cd30987d4f","e7f4cbb3a57f4cbd","edbbfff1128099fd","ee577a0cc18664c9","f230c0b583e23b25","f29d63336e8266d8","f4a66f654996c093","f56c5b59ca016131","f6329fb30c7ea801","f6605d6c57933aea","f6afe41e3926f422","f7283223aacdc39b","f97f47b0eb87905e","fcf81d3c58c13593","fe1a7acdeed4d0f5"]}, + "69668f0ad0aabae2": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"68f44f59e91c4139","optional":false},{"name":"source","type":"694b070275bbc9a6","optional":false,"compatibility":{"version":1,"policy":"session-source-attribution","binding":"session.user-message.source","discriminator":"kind","unknownKinds":"preserve","attributionKinds":["action-cards","tmux-context","user-question-reply","working-directory"]}}],"indices":[]}, "69d238a6e9b08d67": {"kind":"literal","value":"interrupted"}, "6ab45ac76839722d": {"kind":"literal","value":"assistant/message"}, "6b23ed9ce1b397e6": {"kind":"literal","value":"compact-checkpoint"}, @@ -1025,7 +1028,6 @@ "7d65acf0a3a43a8f": {"kind":"union","types":["1f0133217eeeffd8","277b61f9c6f81704","3c2535ca0a2062f1","4e44c9118152f682","83d6916021eede8f","85f9b505b7bdff1f","fb8b6a2e53cb9cf4"]}, "7df62978a2b7de85": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false}],"indices":[]}, "7eaef7a763ba5b94": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false}],"indices":[]}, - "7ee5a828196d9e4b": {"kind":"object","properties":[{"name":"data","type":"129f610271310df6","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sourceEventSeqs","type":"5d03ba38734809bc","optional":true},{"name":"surfaceOp","type":"335e242de1fcc17b","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"1379f0b72275994d","optional":false}],"indices":[]}, "7f13860ee89a2d35": {"kind":"literal","value":"session-reference"}, "7f7fd5a6b0064f59": {"kind":"object","properties":[{"name":"data","type":"5dd766ccd1702a11","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"10e386801903f9d4","optional":false}],"indices":[]}, "7f9365bae9fcb73e": {"kind":"object","properties":[{"name":"runId","type":"4cd48f3e5108bd6e","optional":false},{"name":"stopReason","type":"8465ece5e9d9007c","optional":false}],"indices":[]}, @@ -1060,6 +1062,7 @@ "88841202942c7683": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, "88a610b831be6d92": {"kind":"object","properties":[{"name":"argumentsDelta","type":"4cd48f3e5108bd6e","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"index","type":"0657d3ca5ac4e7bf","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":true},{"name":"type","type":"9b4fd974c124c837","optional":false}],"indices":[]}, "8a046b52331959aa": {"kind":"object","properties":[{"name":"kind","type":"78a9be340090b735","optional":false}],"indices":[]}, + "8a2e3e7a523e622b": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"9d42da116fccdc39","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "8a6e1ec9e8db346b": {"kind":"object","properties":[{"name":"data","type":"119abe2b9c0b2f46","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"b9305f0ea75ccd6a","optional":false}],"indices":[]}, "8a9c990773f798ea": {"kind":"object","properties":[{"name":"preset","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "8ad45ad053b4d89f": {"kind":"object","properties":[{"name":"decision","type":"4cd48f3e5108bd6e","optional":false},{"name":"durationMs","type":"0657d3ca5ac4e7bf","optional":false},{"name":"exitCode","type":"0657d3ca5ac4e7bf","optional":true},{"name":"handlerId","type":"4cd48f3e5108bd6e","optional":false},{"name":"point","type":"4cd48f3e5108bd6e","optional":false},{"name":"stderrSummary","type":"4cd48f3e5108bd6e","optional":true},{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, @@ -1067,6 +1070,7 @@ "8bb8c3751a6ce64b": {"kind":"object","properties":[{"name":"sessionFormatVersion","type":"0657d3ca5ac4e7bf","optional":true},{"name":"sessionId","type":"4cd48f3e5108bd6e","optional":false},{"name":"throughSeq","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "8c1c4f72755a78ea": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, "8c627d7a45fa406c": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "8c9911b902a2fda4": {"kind":"array","element":"69668f0ad0aabae2"}, "8cdd3fdd295cee53": {"kind":"literal","value":"command/done"}, "8e31bb958e9b015e": {"kind":"object","properties":[{"name":"failure","type":"5f2117d1856a5ab4","optional":false},{"name":"kind","type":"1e0b0b66b6f0c53f","optional":false}],"indices":[]}, "8e611bf46821e500": {"kind":"object","properties":[{"name":"tool","type":"fcf427290c6213c2","optional":true},{"name":"toolName","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"85f9b505b7bdff1f","optional":false}],"indices":[]}, @@ -1105,6 +1109,7 @@ "9acbe713f3f64192": {"kind":"literal","value":"image/offload"}, "9b4fd974c124c837": {"kind":"literal","value":"tool-call-delta"}, "9c001ecb5e1d3c38": {"kind":"object","properties":[{"name":"max_tokens","type":"0657d3ca5ac4e7bf","optional":false},{"name":"messages","type":"b993441f8ce7d27b","optional":false},{"name":"model","type":"4cd48f3e5108bd6e","optional":false},{"name":"thinking","type":"37ff65426bcf130f","optional":true},{"name":"tools","type":"4aed17ec726b5397","optional":false}],"indices":[]}, + "9d42da116fccdc39": {"kind":"literal","value":"cua-held-inputs"}, "9d80129e13edfb6f": {"kind":"literal","value":"other"}, "9e07693fd7cd9bab": {"kind":"literal","value":"ask"}, "9e2c06d8653585b3": {"kind":"array","element":"1cde1bedde79c5e8"}, @@ -1128,6 +1133,7 @@ "a43327a1739c3fa4": {"kind":"object","properties":[{"name":"childCreatedAt","type":"0657d3ca5ac4e7bf","optional":false},{"name":"childId","type":"4cd48f3e5108bd6e","optional":false},{"name":"label","type":"4cd48f3e5108bd6e","optional":true},{"name":"mode","type":"fc351843b8ecbd05","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":false},{"name":"version","type":"137ac60e26bcb192","optional":false}],"indices":[]}, "a4afec59b75aad5d": {"kind":"object","properties":[{"name":"clientTimeZone","type":"4cd48f3e5108bd6e","optional":true},{"name":"kind","type":"68f44f59e91c4139","optional":false},{"name":"principal","type":"824a4aad44a54e24","optional":true},{"name":"rpcId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "a6567ccb2e530606": {"kind":"object","properties":[{"name":"data","type":"0d47a8f3d847243c","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"0a8a062bc9c3c0d9","optional":false}],"indices":[]}, + "a6816f39283ae26f": {"kind":"literal","value":"cua-inputs-released"}, "a6b41f5bede8094d": {"kind":"union","types":["15495614ccfa9cbd","aff60ef947c18b01"]}, "a6da9ad5d42ae83a": {"kind":"object","properties":[{"name":"name","type":"4cd48f3e5108bd6e","optional":false},{"name":"runId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "a720757f704a2512": {"kind":"literal","value":"tool-registry"}, @@ -1163,6 +1169,7 @@ "b0127044ab31a702": {"kind":"object","properties":[{"name":"data","type":"ca59530d1a4f3e19","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"1986c2664009c991","optional":false}],"indices":[]}, "b062078e899958f9": {"kind":"object","properties":[{"name":"kind","type":"1f1385dbc3e875c0","optional":false}],"indices":[]}, "b0b0eb1b16490f6b": {"kind":"object","properties":[{"name":"attachmentId","type":"4cd48f3e5108bd6e","optional":false},{"name":"bytes","type":"0657d3ca5ac4e7bf","optional":false},{"name":"height","type":"0657d3ca5ac4e7bf","optional":false},{"name":"mediaType","type":"2f1e6a7ebace43d7","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":true},{"name":"originalDimensions","type":"0f46153645c29784","optional":true},{"name":"width","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "b0e809a7fc2b9068": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"589d0d91239681f8","optional":false},{"name":"source","type":"694b070275bbc9a6","optional":false,"compatibility":{"version":1,"policy":"session-source-attribution","binding":"session.developer-message.source","discriminator":"kind","unknownKinds":"preserve","attributionKinds":["action-cards","tmux-context","user-question-reply","working-directory"]}}],"indices":[]}, "b158f3ff69237148": {"kind":"object","properties":[{"name":"contextWindow","type":"0657d3ca5ac4e7bf","optional":true},{"name":"model","type":"4cd48f3e5108bd6e","optional":false},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false},{"name":"systemPromptUpdate","type":"f311671e07bc7fa6","optional":true}],"indices":[]}, "b1664fa89f8eab49": {"kind":"array","element":"bbc5696e3f13c758"}, "b1ebd5cda47d90d9": {"kind":"object","properties":[{"name":"member","type":"6598cd6da253948d","optional":false},{"name":"teamId","type":"4cd48f3e5108bd6e","optional":false},{"name":"version","type":"a0f906856fc06f1c","optional":false}],"indices":[]}, @@ -1209,6 +1216,7 @@ "bcf0caf62d964b2f": {"kind":"object","properties":[{"name":"endSeq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"op","type":"f6cb462f808309e3","optional":false},{"name":"startSeq","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "bd499eac047efe09": {"kind":"literal","value":"finish"}, "bf16d2e98a7f1389": {"kind":"literal","value":"subagent-settled"}, + "c071d01c76a37f9f": {"kind":"object","properties":[{"name":"maxTokens","type":"0657d3ca5ac4e7bf","optional":false},{"name":"messageSeqs","type":"5d03ba38734809bc","optional":false},{"name":"messages","type":"e973903c6f32109c","optional":false},{"name":"reasoningEffort","type":"4cd48f3e5108bd6e","optional":true},{"name":"route","type":"07e1a58c58b593f5","optional":false},{"name":"system","type":"4cd48f3e5108bd6e","optional":false},{"name":"titleProvider","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "c0ea97bc89dfc46f": {"kind":"object","properties":[{"name":"outcome","type":"c2deb7c9183735d4","optional":false},{"name":"runId","type":"4cd48f3e5108bd6e","optional":false},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "c170da8ab7c37635": {"kind":"union","types":["374fdd68aee5ff84","cdee10e87dbed844"]}, "c1f0f17b6493b85d": {"kind":"object","properties":[{"name":"arguments","type":"4cd48f3e5108bd6e","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"1f0133217eeeffd8","optional":false}],"indices":[]}, @@ -1236,6 +1244,7 @@ "cda2345a9be9d139": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "cdca80b8dad24d4e": {"kind":"literal","value":"tool-workflow/run-start"}, "cdee10e87dbed844": {"kind":"object","properties":[{"name":"delayMs","type":"0657d3ca5ac4e7bf","optional":false},{"name":"failure","type":"5f2117d1856a5ab4","optional":false},{"name":"maxRetries","type":"0657d3ca5ac4e7bf","optional":false},{"name":"mode","type":"3bc287e765d58dc3","optional":false},{"name":"policyKey","type":"4cd48f3e5108bd6e","optional":false},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false},{"name":"retry","type":"0657d3ca5ac4e7bf","optional":false},{"name":"retryId","type":"4cd48f3e5108bd6e","optional":false},{"name":"step","type":"0657d3ca5ac4e7bf","optional":false},{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "ce6e647c9e653b5d": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"a6816f39283ae26f","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "cef171adf021a186": {"kind":"object","properties":[{"name":"arguments","type":"bbc5696e3f13c758","optional":false},{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"error","type":"a81059ca06999da1","optional":true},{"name":"isError","type":"aa93010d0e521ad7","optional":false},{"name":"meta","type":"c592ce75aab73fca","optional":true},{"name":"name","type":"4cd48f3e5108bd6e","optional":false},{"name":"parentCallId","type":"4cd48f3e5108bd6e","optional":false},{"name":"rootCallId","type":"4cd48f3e5108bd6e","optional":false},{"name":"subCallId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "cffcdc19881ab61e": {"kind":"object","properties":[{"name":"cleared","type":"0b6d718c693fdf7f","optional":false},{"name":"clearedAt","type":"0657d3ca5ac4e7bf","optional":false},{"name":"kind","type":"237c004c73b6b288","optional":false},{"name":"operation","type":"e7e154d47d5fbc53","optional":false},{"name":"version","type":"f88f1b7b6bb733f6","optional":false}],"indices":[]}, "d0fbb0ca1bbba059": {"kind":"literal","value":"delete"}, @@ -1290,6 +1299,7 @@ "e6063d0451dc0202": {"kind":"object","properties":[{"name":"acceptedAt","type":"4cd48f3e5108bd6e","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"operation","type":"26c879bdd130e8b8","optional":false},{"name":"version","type":"f88f1b7b6bb733f6","optional":false}],"indices":[]}, "e6411b09c1d982f7": {"kind":"literal","value":"parent"}, "e72269f931559e90": {"kind":"object","properties":[{"name":"dt","type":"5d03ba38734809bc","optional":false},{"name":"index","type":"0657d3ca5ac4e7bf","optional":false},{"name":"texts","type":"93c33d9687613293","optional":false},{"name":"time0","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"f9cfc89e8fe085b4","optional":false}],"indices":[]}, + "e744baea6a5d54ef": {"kind":"union","types":["09f3f8dc417f2782","4b259f7f8f0a44ad","69668f0ad0aabae2","b0e809a7fc2b9068","fa87537f4a9c1e25"]}, "e75916628f3f10c2": {"kind":"object","properties":[{"name":"data","type":"8ad45ad053b4d89f","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"a3a259a1aa5401af","optional":false}],"indices":[]}, "e7ce49f12953583f": {"kind":"literal","value":"initial"}, "e7e154d47d5fbc53": {"kind":"literal","value":"clear"}, @@ -1297,6 +1307,7 @@ "e7f4cbb3a57f4cbd": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "e8de0f457fed5b9f": {"kind":"literal","value":"notice"}, "e95f957154b2b1b5": {"kind":"literal","value":"assistant/attempt"}, + "e973903c6f32109c": {"kind":"array","element":"e744baea6a5d54ef"}, "ea08ec1df0c33108": {"kind":"object","properties":[{"name":"message","type":"2eafefdc6f79a492","optional":false},{"name":"teamId","type":"4cd48f3e5108bd6e","optional":false},{"name":"version","type":"a0f906856fc06f1c","optional":false}],"indices":[]}, "eaa71be0fbf0f702": {"kind":"object","properties":[{"name":"kind","type":"ad3b56aa2fc1ad42","optional":false}],"indices":[]}, "ebb768d85ec87fb6": {"kind":"literal","value":"image/webp"}, @@ -1304,7 +1315,6 @@ "ec8b5ff7c77ca689": {"kind":"object","properties":[{"name":"kind","type":"b2245a906e13aa94","optional":false}],"indices":[]}, "edbbfff1128099fd": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "edd37b1e4974af64": {"kind":"object","properties":[{"name":"data","type":"611d82d2dc50df70","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"347de3380f2da308","optional":false}],"indices":[]}, - "ee4277d9b4c96ab0": {"kind":"object","properties":[{"name":"maxTokens","type":"0657d3ca5ac4e7bf","optional":false},{"name":"messageSeqs","type":"5d03ba38734809bc","optional":false},{"name":"messages","type":"39fe981d6583647f","optional":false},{"name":"reasoningEffort","type":"4cd48f3e5108bd6e","optional":true},{"name":"route","type":"07e1a58c58b593f5","optional":false},{"name":"system","type":"4cd48f3e5108bd6e","optional":false},{"name":"titleProvider","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "ee577a0cc18664c9": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "eea687d437880bd5": {"kind":"object","properties":[{"name":"operation","type":"7624ca28c61ca0ea","optional":false},{"name":"schedule","type":"4b1e632e05776982","optional":false},{"name":"version","type":"f88f1b7b6bb733f6","optional":false}],"indices":[]}, "eefbea819caeeea9": {"kind":"literal","value":"block-end"}, @@ -1324,7 +1334,6 @@ "f4a66f654996c093": {"kind":"object","properties":[{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, "f5520c1d261ca86e": {"kind":"object","properties":[{"name":"data","type":"e3056e0dda3a379e","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"24a8188c4d61b70a","optional":false}],"indices":[]}, "f56c5b59ca016131": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"7f13860ee89a2d35","optional":false},{"name":"references","type":"df843efd87c78cf8","optional":false},{"name":"version","type":"f88f1b7b6bb733f6","optional":false}],"indices":[]}, - "f5d843edb0eeef61": {"kind":"object","properties":[{"name":"data","type":"261128de68865c1f","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"829a2fb3be6efd4b","optional":false}],"indices":[]}, "f6329fb30c7ea801": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, "f634871d1e18b1eb": {"kind":"literal","value":"plan/mode"}, "f6605d6c57933aea": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false}],"indices":[]}, @@ -1341,7 +1350,6 @@ "fab2bb09bc5e3b9d": {"kind":"union","types":["12a0cfa619ac4a5f","18fce9540bb20897","a3edd1efd1fef21b"]}, "fab35c4520883c0d": {"kind":"literal","value":"rejected"}, "fb5e0517050d2c6d": {"kind":"literal","value":"tool/ptc-dispatch"}, - "fb6a6e338625067a": {"kind":"object","properties":[{"name":"data","type":"0aed9f5c80e82b6e","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sourceEventSeqs","type":"5d03ba38734809bc","optional":true},{"name":"surfaceOp","type":"335e242de1fcc17b","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"de25352d2dc41963","optional":false}],"indices":[]}, "fb8b6a2e53cb9cf4": {"kind":"literal","value":"image"}, "fbd2c74b346a1595": {"kind":"literal","value":"agent-instructions"}, "fc351843b8ecbd05": {"kind":"literal","value":"external"}, diff --git a/packages/experimental/cua/src/held-inputs.ts b/packages/experimental/cua/src/held-inputs.ts index 115ea8a653..175f7be600 100644 --- a/packages/experimental/cua/src/held-inputs.ts +++ b/packages/experimental/cua/src/held-inputs.ts @@ -135,7 +135,10 @@ export class CuaHeldInputs { void owner.close().catch(() => undefined) // close records and reports the failure; waiters join the same promise. } - /** @returns Exact disposers retained until programs and native connections have drained. */ + /** + * Observe program outcomes and cancellation while retaining native cleanup dependencies. + * @returns Exact disposers retained until programs and native connections have drained. + */ *install(): Generator<() => void> { const ctx = this.ctx yield ctx.on('tools/execute', async (execution, next) => { diff --git a/packages/experimental/cua/src/types.ts b/packages/experimental/cua/src/types.ts index e4b9f0c993..47c3f623ba 100644 --- a/packages/experimental/cua/src/types.ts +++ b/packages/experimental/cua/src/types.ts @@ -8,8 +8,8 @@ import type { ActionResult, CapabilitiesResult, FoundAppsResult, HoverResult, Sy declare module '@deepseek-ai/dsh-llm' { interface MessageSourceMap { - 'cua-held-inputs': { kind: 'cua-held-inputs' } & ContextFormed - 'cua-inputs-released': { kind: 'cua-inputs-released' } & ContextFormed + 'cua-held-inputs': { kind: 'cua-held-inputs' } & Extract + 'cua-inputs-released': { kind: 'cua-inputs-released' } & Extract } } diff --git a/snapshots/web/cua-run-code/ui.expected.md b/snapshots/web/cua-run-code/ui.expected.md index d1edad4a0e..8c873862f4 100644 --- a/snapshots/web/cua-run-code/ui.expected.md +++ b/snapshots/web/cua-run-code/ui.expected.md @@ -29,6 +29,7 @@ - button "Tool call cua · getState" - button "Tool call cua · click" - button "Tool call cua · screenshot" +- button "Context injection cua-held-inputs CUA inputs remain held" - button "Code Reuse the retained application and window" - button "Tool call cua · sendKeyEvent" - button "Tool call cua · getState" @@ -36,6 +37,7 @@ - button "Tool call cua · getState" - button "Tool call cua · toggleMouse" - button "Tool call cua · sendKeyEvent" +- button "Context injection cua-held-inputs CUA inputs remain held" - paragraph: "The retained application and window report Count: 2. The counter persisted across calls, and the program exposes only tools.cua. The screenshot was attached after the first call." - button "Copy" - button "Good response" From 2df57db6e02bcf533e88df5799f1629f8768b9c3 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 19 Nov 2026 12:28:00 +0800 Subject: [PATCH 42/73] Acknowledge compatible persisted CUA notice sources --- .../2026-11-19-cua-input-notices.i18n.yaml | 28 ++ .../2026-11-19-cua-input-notices.md | 60 ++++ .../2026-11-19-cua-input-notices.schema.json | 267 ++++++++++++++++++ .../2026-11-19-cua-input-notices.zh.md | 60 ++++ 4 files changed, 415 insertions(+) create mode 100644 docs/persistence-changes/2026-11-19-cua-input-notices.i18n.yaml create mode 100644 docs/persistence-changes/2026-11-19-cua-input-notices.md create mode 100644 docs/persistence-changes/2026-11-19-cua-input-notices.schema.json create mode 100644 docs/persistence-changes/2026-11-19-cua-input-notices.zh.md diff --git a/docs/persistence-changes/2026-11-19-cua-input-notices.i18n.yaml b/docs/persistence-changes/2026-11-19-cua-input-notices.i18n.yaml new file mode 100644 index 0000000000..53b2626688 --- /dev/null +++ b/docs/persistence-changes/2026-11-19-cua-input-notices.i18n.yaml @@ -0,0 +1,28 @@ +# Bilingual-pair consistency record for 2026-11-19-cua-input-notices.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/persistence-changes/2026-11-19-cua-input-notices.md +/: + en: 3d5a424ae7d7e46b + zh: c22a8e4a62d8cc1a +/2026-11-19-cua-input-notices: + en: 05ad48d04065f2d6 + zh: 7d35d69bb75dbd82 +/2026-11-19-cua-input-notices/summary: + en: 99c8df735ac604f9 + zh: b7d7f1b6d2e53645 +/2026-11-19-cua-input-notices/table-of-contents: + en: 6cf314a069ceb451 + zh: 9adff678e9ecab3b +/2026-11-19-cua-input-notices/declaration: + en: 6907136f28e48c90 + zh: 02f8298485f3d8e7 +/2026-11-19-cua-input-notices/compatibility: + en: d9081b4686482328 + zh: 33254ef8c6e5c6a9 +/2026-11-19-cua-input-notices/verification: + en: e25c20c14355cfc6 + zh: 67b8b1adf15f80b6 +/2026-11-19-cua-input-notices/dev-note: + en: b75c8458928b72b9 + zh: 003ba4e17b4b5269 diff --git a/docs/persistence-changes/2026-11-19-cua-input-notices.md b/docs/persistence-changes/2026-11-19-cua-input-notices.md new file mode 100644 index 0000000000..d8ae9eb1de --- /dev/null +++ b/docs/persistence-changes/2026-11-19-cua-input-notices.md @@ -0,0 +1,60 @@ +--- +description: "Records a persistence type transition and its compatibility acknowledgement." +kind: persistence-change +--- + +# 2026-11-19-cua-input-notices + +English | [中文](2026-11-19-cua-input-notices.zh.md) + +## Summary + +Adds cua-held-inputs and cua-inputs-released producer attribution using the existing notice form and text content. + +## Table of Contents + +- [Declaration](#declaration) +- [Compatibility](#compatibility) +- [Verification](#verification) +- [Dev Note](#dev-note) + + +## Declaration + +```yaml persistence-change +schemaVersion: 1 +id: 2026-11-19-cua-input-notices +baseline: false +changes: + - root: "event:agent/inbox/spliced" + previous: "2026-11-05-timeline-priority-notice" + after: "0880996d224033d9a668528f51edf5f229d9b07dda42fb65f7d1cc1150c12836" + decision: same-version + - root: "event:developer/message" + previous: "2026-11-05-timeline-priority-notice" + after: "3a6f3e4354a90287bb3a1fb19e7a2f643cdbd7c6472c865abd11f8fa2d3358d5" + decision: same-version + - root: "event:session/title-llm-request" + previous: "2026-11-05-timeline-priority-notice" + after: "4e81b0490558b80c87cd09b214cd958ce0df1bf2bb431c930ff8fd441a8d1df5" + decision: same-version + - root: "event:user/message" + previous: "2026-11-05-timeline-priority-notice" + after: "507043f63e859f272ce78f6bc65a7361ee087e5e06301f9c100302230bc887a7" + decision: same-version +``` + + +## Compatibility + +This remains Session format V4. New readers retain every previous source kind and event field. Released V4 readers accept nonempty unknown producer kinds in user/developer messages, preserve their metadata and text, and already understand notice summaries. The same source objects occur in queued inbox messages and recorded title-request messages. These two kinds describe input state; restoring or deriving a Session does not replay native input or recreate holds. No event discriminator, header, message role or existing source meaning changes. + + +## Verification + +pnpm run test packages/session/session-format-v3-to-v4/tests/attribution.spec.ts packages/session/session-format-v3-to-v4/tests/message-sources.spec.ts: 12 tests passed. Seven focused headless/TypeScript SDK CUA snapshots, the shipped cua-mcp profile expectation, Web CUA replay and Python SDK replay passed. CUA behavior tests cover persisted held notices, confirmed release notices after pause, and removal of delayed stale notices. + + +## Dev Note + +None. diff --git a/docs/persistence-changes/2026-11-19-cua-input-notices.schema.json b/docs/persistence-changes/2026-11-19-cua-input-notices.schema.json new file mode 100644 index 0000000000..157de64492 --- /dev/null +++ b/docs/persistence-changes/2026-11-19-cua-input-notices.schema.json @@ -0,0 +1,267 @@ +{ + "formatVersion": 2, + "roots": [ + {"key":"event:agent/inbox/spliced","kind":"event","event":"agent/inbox/spliced","surface":false,"digest":"0880996d224033d9a668528f51edf5f229d9b07dda42fb65f7d1cc1150c12836"}, + {"key":"event:developer/message","kind":"event","event":"developer/message","surface":true,"digest":"3a6f3e4354a90287bb3a1fb19e7a2f643cdbd7c6472c865abd11f8fa2d3358d5"}, + {"key":"event:session/title-llm-request","kind":"event","event":"session/title-llm-request","surface":false,"digest":"4e81b0490558b80c87cd09b214cd958ce0df1bf2bb431c930ff8fd441a8d1df5"}, + {"key":"event:user/message","kind":"event","event":"user/message","surface":true,"digest":"507043f63e859f272ce78f6bc65a7361ee087e5e06301f9c100302230bc887a7"} + ], + "types": [], + "nodes": { + "0203243b72fc867a": {"kind":"object","properties":[{"name":"kind","type":"24b10f7cdae64928","optional":false}],"indices":[]}, + "022623b9ef98ec47": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false}],"indices":[]}, + "02b2c23f2d94b028": {"kind":"object","properties":[{"name":"kind","type":"c5687b1313206a6f","optional":false}],"indices":[]}, + "05205074b24d8340": {"kind":"literal","value":"action-cards"}, + "0657d3ca5ac4e7bf": {"kind":"primitive","type":"number"}, + "07e1a58c58b593f5": {"kind":"object","properties":[{"name":"model","type":"4cd48f3e5108bd6e","optional":false},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "0880996d224033d9": {"kind":"object","properties":[{"name":"data","type":"2314c3471cc0d314","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"829a2fb3be6efd4b","optional":false}],"indices":[]}, + "09655b34d7f3cf1e": {"kind":"literal","value":"system-prompt"}, + "09f3f8dc417f2782": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"8af841fc9b265ade","optional":false},{"name":"source","type":"65a8400e451e667e","optional":false}],"indices":[]}, + "0a92c5bdfa06c2e2": {"kind":"object","properties":[{"name":"displayName","type":"4cd48f3e5108bd6e","optional":true},{"name":"providerId","type":"4cd48f3e5108bd6e","optional":false},{"name":"subjectId","type":"4cd48f3e5108bd6e","optional":false},{"name":"tenantId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "0ed8d1108fe7a5e1": {"kind":"object","properties":[{"name":"kind","type":"a9059a81430b3207","optional":false}],"indices":[]}, + "0eeb17e1df89b1eb": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false}],"indices":[]}, + "0f46153645c29784": {"kind":"object","properties":[{"name":"height","type":"0657d3ca5ac4e7bf","optional":false},{"name":"width","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "0fe52387f6505270": {"kind":"literal","value":"plan-mode"}, + "11638dc58a31496f": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "12d5808fac1996b9": {"kind":"object","properties":[{"name":"attachment","type":"b0b0eb1b16490f6b","optional":false},{"name":"offloaded","type":"dacf3d5f3e4ff619","optional":true},{"name":"type","type":"fb8b6a2e53cb9cf4","optional":false}],"indices":[]}, + "1379f0b72275994d": {"kind":"literal","value":"developer/message"}, + "16d0507cb94b4cfc": {"kind":"literal","value":"relay"}, + "1922cd79a70806c1": {"kind":"literal","value":"skill-invocation"}, + "1938c8c20f1cba7c": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false}],"indices":[]}, + "1e0b0b66b6f0c53f": {"kind":"literal","value":"aborted"}, + "1e709346005826eb": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false}],"indices":[]}, + "1ebc6f9ff3aa9e3a": {"kind":"literal","value":"completed"}, + "1f0133217eeeffd8": {"kind":"literal","value":"tool-call"}, + "1f1385dbc3e875c0": {"kind":"literal","value":"repeat-tool-reminder"}, + "1fdad624334d3548": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false}],"indices":[]}, + "2152caf1a71e588e": {"kind":"object","properties":[{"name":"kind","type":"2e4debca12f2c449","optional":false},{"name":"messageId","type":"4cd48f3e5108bd6e","optional":false},{"name":"senderId","type":"4cd48f3e5108bd6e","optional":false},{"name":"senderName","type":"4cd48f3e5108bd6e","optional":false},{"name":"teamId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "2235d957bf4b7c6c": {"kind":"object","properties":[{"name":"kind","type":"7b1ce60193fa8b69","optional":false}],"indices":[]}, + "224aa11d4d5f88c4": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false}],"indices":[]}, + "2314c3471cc0d314": {"kind":"object","properties":[{"name":"inserted","type":"8c9911b902a2fda4","optional":false},{"name":"outcome","type":"d4e4d575abeb4b72","optional":true},{"name":"removedCount","type":"0657d3ca5ac4e7bf","optional":true},{"name":"start","type":"0657d3ca5ac4e7bf","optional":false},{"name":"target","type":"96f4a9c81fc0f940","optional":false}],"indices":[]}, + "23af3759678a30de": {"kind":"literal","value":"dsh-session-title-llm"}, + "24b10f7cdae64928": {"kind":"literal","value":"runtime-context"}, + "24ce31aa528272e5": {"kind":"object","properties":[{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, + "260523b412c19ad8": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false}],"indices":[]}, + "2765e9119edf5816": {"kind":"literal","value":"model"}, + "277b61f9c6f81704": {"kind":"literal","value":"file"}, + "28936c614bd4e7e2": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "290f32bfd81ff85a": {"kind":"object","properties":[{"name":"kind","type":"23af3759678a30de","optional":false}],"indices":[]}, + "297fbd8067d7815a": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false}],"indices":[]}, + "2aad1179f9576314": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "2ab12a0e345658f9": {"kind":"array","element":"83da72c6857601c7"}, + "2e4debca12f2c449": {"kind":"literal","value":"team-message"}, + "2f1e6a7ebace43d7": {"kind":"union","types":["3f74ba74acd10644","58f94390b982f8a5","de30b1fa12c75f81","ebb768d85ec87fb6"]}, + "2f3f201c8846e19c": {"kind":"literal","value":"tool-goal"}, + "312aee2f0c42aabb": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "31907de956375182": {"kind":"object","properties":[{"name":"compactionId","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"6b23ed9ce1b397e6","optional":false},{"name":"sourceCommandId","type":"4cd48f3e5108bd6e","optional":true}],"indices":[]}, + "3247e566f4340029": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "335e242de1fcc17b": {"kind":"union","types":["bcf0caf62d964b2f","e438a9d4fb883b3e"]}, + "383cf73ae4748e5b": {"kind":"literal","value":"recall"}, + "3a6f3e4354a90287": {"kind":"object","properties":[{"name":"data","type":"3e22099343651604","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sourceEventSeqs","type":"5d03ba38734809bc","optional":true},{"name":"surfaceOp","type":"335e242de1fcc17b","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"1379f0b72275994d","optional":false}],"indices":[]}, + "3b04790e08b35241": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, + "3b4f2c9ef2c1217e": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false}],"indices":[]}, + "3bd652ebfa8726b3": {"kind":"union","types":["0657d3ca5ac4e7bf","938f7c7357bc403e"]}, + "3bdb8dc6989655b0": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "3c2535ca0a2062f1": {"kind":"literal","value":"reasoning"}, + "3e22099343651604": {"kind":"object","properties":[{"name":"headerSeq","type":"0657d3ca5ac4e7bf","optional":true},{"name":"message","type":"b0e809a7fc2b9068","optional":false},{"name":"step","type":"0657d3ca5ac4e7bf","optional":false},{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "3e2ece4967cfebe9": {"kind":"literal","value":"next-step"}, + "3f74ba74acd10644": {"kind":"literal","value":"image/jpeg"}, + "408927267422a7b2": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, + "43e311235aa537df": {"kind":"object","properties":[{"name":"toolName","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"83d6916021eede8f","optional":false}],"indices":[]}, + "45f005e6bbb76452": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "4991dfc415c9efeb": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false}],"indices":[]}, + "49dab019d00e8c26": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "4a561c111a78d452": {"kind":"literal","value":"refusal"}, + "4a9bef9f27a94252": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"82470020b5bfcb1a","optional":false},{"name":"senderSessionId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "4b259f7f8f0a44ad": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"isError","type":"aa93010d0e521ad7","optional":true},{"name":"role","type":"a13d8f379222ece8","optional":false},{"name":"source","type":"d9c462b9f62fdd3e","optional":false},{"name":"toolCallId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "4cd48f3e5108bd6e": {"kind":"primitive","type":"string"}, + "4d60dddaa65d3da8": {"kind":"object","properties":[{"name":"actor","type":"0a92c5bdfa06c2e2","optional":false},{"name":"kind","type":"6ba7edb6447b6a3e","optional":false},{"name":"shareId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "4e44c9118152f682": {"kind":"literal","value":"text"}, + "4e81b0490558b80c": {"kind":"object","properties":[{"name":"data","type":"c071d01c76a37f9f","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"587bb11da730e06a","optional":false}],"indices":[]}, + "4e88776858652856": {"kind":"object","properties":[{"name":"text","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"4e44c9118152f682","optional":false}],"indices":[]}, + "4edec1b770e8ec4c": {"kind":"literal","value":"ptc-mode"}, + "4f91f187baeabef5": {"kind":"object","properties":[{"name":"capturedFormatVersion","type":"0657d3ca5ac4e7bf","optional":true},{"name":"capturedThroughSeq","type":"3bd652ebfa8726b3","optional":false},{"name":"compacted","type":"aa93010d0e521ad7","optional":false},{"name":"inputIndex","type":"0657d3ca5ac4e7bf","optional":false},{"name":"label","type":"4cd48f3e5108bd6e","optional":false},{"name":"omittedBytes","type":"0657d3ca5ac4e7bf","optional":false},{"name":"omittedMessages","type":"0657d3ca5ac4e7bf","optional":false},{"name":"originalMessages","type":"0657d3ca5ac4e7bf","optional":false},{"name":"retainedMessages","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sessionId","type":"4cd48f3e5108bd6e","optional":false},{"name":"truncated","type":"aa93010d0e521ad7","optional":false}],"indices":[]}, + "507043f63e859f27": {"kind":"object","properties":[{"name":"data","type":"69668f0ad0aabae2","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sourceEventSeqs","type":"5d03ba38734809bc","optional":true},{"name":"surfaceOp","type":"335e242de1fcc17b","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"de25352d2dc41963","optional":false}],"indices":[]}, + "52c6113cb0e53f34": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "53cf1704ae0709c7": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, + "5654685d7557ec74": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "58015da1c1950a66": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false}],"indices":[]}, + "587bb11da730e06a": {"kind":"literal","value":"session/title-llm-request"}, + "589d0d91239681f8": {"kind":"literal","value":"developer"}, + "58f94390b982f8a5": {"kind":"literal","value":"image/png"}, + "5bb69b88517f6214": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "5bc66269cfaf614c": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false}],"indices":[]}, + "5cdbf342b7748d15": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false}],"indices":[]}, + "5d03ba38734809bc": {"kind":"array","element":"0657d3ca5ac4e7bf"}, + "5d7a64ed6aac5551": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false}],"indices":[]}, + "6085488d223aeffd": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false}],"indices":[]}, + "6292bcbedaa97fea": {"kind":"object","properties":[{"name":"kind","type":"f68c335306535a00","optional":false}],"indices":[]}, + "62ecb62dc0fe1b5e": {"kind":"literal","value":"next-turn"}, + "63ba8895cc09e469": {"kind":"literal","value":"retry"}, + "65a8400e451e667e": {"kind":"object","properties":[{"name":"kind","type":"09655b34d7f3cf1e","optional":false}],"indices":[]}, + "65d583e66518c523": {"kind":"object","properties":[{"name":"entries","type":"aba175fb20ffc711","optional":false},{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"incomplete","type":"dacf3d5f3e4ff619","optional":true},{"name":"kind","type":"6ebcc2dbec9f2dab","optional":false},{"name":"update","type":"dacf3d5f3e4ff619","optional":true}],"indices":[]}, + "672c4aa2a9b736e3": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"1922cd79a70806c1","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "68141cbe3994a5ff": {"kind":"literal","value":"max-tokens"}, + "68f44f59e91c4139": {"kind":"literal","value":"user"}, + "694b070275bbc9a6": {"kind":"union","types":["0203243b72fc867a","022623b9ef98ec47","02b2c23f2d94b028","0ed8d1108fe7a5e1","0eeb17e1df89b1eb","11638dc58a31496f","1938c8c20f1cba7c","1e709346005826eb","1fdad624334d3548","2152caf1a71e588e","2235d957bf4b7c6c","224aa11d4d5f88c4","24ce31aa528272e5","260523b412c19ad8","28936c614bd4e7e2","290f32bfd81ff85a","297fbd8067d7815a","2aad1179f9576314","312aee2f0c42aabb","31907de956375182","3247e566f4340029","3b04790e08b35241","3b4f2c9ef2c1217e","3bdb8dc6989655b0","408927267422a7b2","45f005e6bbb76452","4991dfc415c9efeb","49dab019d00e8c26","4a9bef9f27a94252","52c6113cb0e53f34","53cf1704ae0709c7","5654685d7557ec74","58015da1c1950a66","5bb69b88517f6214","5bc66269cfaf614c","5cdbf342b7748d15","5d7a64ed6aac5551","6085488d223aeffd","6292bcbedaa97fea","65a8400e451e667e","65d583e66518c523","672c4aa2a9b736e3","6ccb6bc423fb3952","6ea608bdc8a7a63d","6f22a9d02b9a1f11","6f44f32be9bcd9a8","719c51f67074f970","7554565be416b034","756b5e23a5cb2c7f","7df62978a2b7de85","7eaef7a763ba5b94","7f959241c24128b4","80677c8c8b804189","825ca23416b1ea9d","8338ee303e2bd448","848639f8787f035b","854db3efdfb0cd39","85fe96bf15d5c755","8620189c8e335827","87b1a33564b9a4d6","88841202942c7683","8a046b52331959aa","8a2e3e7a523e622b","8c1c4f72755a78ea","8c627d7a45fa406c","8f1062573ea91841","8f324cea3916c051","8fcb0b44a575e998","96bfb916a727cd44","99135d8a39379779","99f0e98184709ad1","9edc162949abf93b","9f65c43e340bba31","a15a19ef63cf5d1b","a16e567c8cd2c55c","a2066bd52f61218b","a3c6f1ea38e9a61d","a4afec59b75aad5d","aa2bf9e82b9fdeb9","aae343bc3d663c83","ada310bf0bdb8fed","ade057f4fdc387ae","b062078e899958f9","b2a5c8c008a31e3d","b3681c026a0b98e9","b4ec0af39fd52ed9","b613f83572fe2fbf","b6f94c17dd9bbd7c","b70f3e81fe11b7a5","b79641a9d25e7566","ba2a1a8f194b1bb2","ba4c40b4381e0dcd","baccc97ec34be6c4","c5228b7a55498d84","c55827fba7018198","cb1c8959e1726f82","cda2345a9be9d139","ce6e647c9e653b5d","d215701afb7aafbf","d85590a5675c6e2f","d9c462b9f62fdd3e","db06ef35b27a3842","dba54c09c6e7aafc","dd00cdccd0ba487b","dd5ee8762bd8a14b","dd6cc2bb2a8f2824","dde0cdf9d426768b","deaae5cd30987d4f","e7f4cbb3a57f4cbd","edbbfff1128099fd","ee577a0cc18664c9","f230c0b583e23b25","f29d63336e8266d8","f4a66f654996c093","f56c5b59ca016131","f6329fb30c7ea801","f6605d6c57933aea","f6afe41e3926f422","f7283223aacdc39b","f97f47b0eb87905e","fcf81d3c58c13593","fe1a7acdeed4d0f5"]}, + "69668f0ad0aabae2": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"68f44f59e91c4139","optional":false},{"name":"source","type":"694b070275bbc9a6","optional":false,"compatibility":{"version":1,"policy":"session-source-attribution","binding":"session.user-message.source","discriminator":"kind","unknownKinds":"preserve","attributionKinds":["action-cards","tmux-context","user-question-reply","working-directory"]}}],"indices":[]}, + "6b23ed9ce1b397e6": {"kind":"literal","value":"compact-checkpoint"}, + "6ba7edb6447b6a3e": {"kind":"literal","value":"share-viewer"}, + "6ccb6bc423fb3952": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "6ea608bdc8a7a63d": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false}],"indices":[]}, + "6ebcc2dbec9f2dab": {"kind":"literal","value":"skill-catalog"}, + "6f22a9d02b9a1f11": {"kind":"object","properties":[{"name":"baseline","type":"dacf3d5f3e4ff619","optional":true},{"name":"baselineIdentity","type":"4cd48f3e5108bd6e","optional":true},{"name":"changes","type":"2ab12a0e345658f9","optional":false},{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"fbd2c74b346a1595","optional":false}],"indices":[]}, + "6f44f32be9bcd9a8": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false}],"indices":[]}, + "6f9e00383836275e": {"kind":"literal","value":"snapshot"}, + "719c51f67074f970": {"kind":"object","properties":[{"name":"kind","type":"2765e9119edf5816","optional":false},{"name":"model","type":"4cd48f3e5108bd6e","optional":false},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false},{"name":"replayState","type":"bbc5696e3f13c758","optional":true}],"indices":[]}, + "7382c4fc95fe8c5d": {"kind":"literal","value":"remove"}, + "7554565be416b034": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false}],"indices":[]}, + "756b5e23a5cb2c7f": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false}],"indices":[]}, + "78a9be340090b735": {"kind":"literal","value":"tmux-context"}, + "7b1ce60193fa8b69": {"kind":"literal","value":"working-directory"}, + "7df62978a2b7de85": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false}],"indices":[]}, + "7eaef7a763ba5b94": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false}],"indices":[]}, + "7f13860ee89a2d35": {"kind":"literal","value":"session-reference"}, + "7f959241c24128b4": {"kind":"object","properties":[{"name":"goalId","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"b815d7b91cdd9fc6","optional":false},{"name":"revision","type":"0657d3ca5ac4e7bf","optional":false},{"name":"round","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "8064c03c87c357fd": {"kind":"union","types":["12d5808fac1996b9","43e311235aa537df","4e88776858652856","814d9434e1ddf907","8e611bf46821e500","c1f0f17b6493b85d","f2da0f27c1e6add5"]}, + "80677c8c8b804189": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false}],"indices":[]}, + "8067b0d232c350f1": {"kind":"literal","value":"time-context"}, + "814d9434e1ddf907": {"kind":"object","properties":[{"name":"text","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"3c2535ca0a2062f1","optional":false}],"indices":[]}, + "82470020b5bfcb1a": {"kind":"literal","value":"agent-message"}, + "824a4aad44a54e24": {"kind":"union","types":["4d60dddaa65d3da8","deebfc7c62177ea8"]}, + "825ca23416b1ea9d": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false}],"indices":[]}, + "829a2fb3be6efd4b": {"kind":"literal","value":"agent/inbox/spliced"}, + "83079c8a3f733ac3": {"kind":"object","properties":[{"name":"description","type":"4cd48f3e5108bd6e","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "8338ee303e2bd448": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "83d6916021eede8f": {"kind":"literal","value":"tool-removal"}, + "83da72c6857601c7": {"kind":"object","properties":[{"name":"action","type":"904bf499d98be4a3","optional":false},{"name":"digest","type":"4cd48f3e5108bd6e","optional":true},{"name":"path","type":"4cd48f3e5108bd6e","optional":false},{"name":"scope","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "848639f8787f035b": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"bf16d2e98a7f1389","optional":false},{"name":"senderSessionId","type":"4cd48f3e5108bd6e","optional":false},{"name":"stopReason","type":"866f7b2dbdc5b421","optional":true},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "854db3efdfb0cd39": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "85d6d96ff8842974": {"kind":"literal","value":"answered"}, + "85f9b505b7bdff1f": {"kind":"literal","value":"tool-addition"}, + "85fe96bf15d5c755": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false}],"indices":[]}, + "8620189c8e335827": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false}],"indices":[]}, + "866f7b2dbdc5b421": {"kind":"union","types":["1e0b0b66b6f0c53f","1ebc6f9ff3aa9e3a","4a561c111a78d452","68141cbe3994a5ff","a2be0f0cb59f0d4a"]}, + "86e1e384495ee09a": {"kind":"object","properties":[{"name":"name","type":"4cd48f3e5108bd6e","optional":false},{"name":"text","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "87b1a33564b9a4d6": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false}],"indices":[]}, + "88841202942c7683": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "8a046b52331959aa": {"kind":"object","properties":[{"name":"kind","type":"78a9be340090b735","optional":false}],"indices":[]}, + "8a2e3e7a523e622b": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"9d42da116fccdc39","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "8af841fc9b265ade": {"kind":"literal","value":"system"}, + "8c1c4f72755a78ea": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "8c627d7a45fa406c": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "8c9911b902a2fda4": {"kind":"array","element":"69668f0ad0aabae2"}, + "8e611bf46821e500": {"kind":"object","properties":[{"name":"tool","type":"fcf427290c6213c2","optional":true},{"name":"toolName","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"85f9b505b7bdff1f","optional":false}],"indices":[]}, + "8f1062573ea91841": {"kind":"object","properties":[{"name":"clientTimeZone","type":"4cd48f3e5108bd6e","optional":true},{"name":"kind","type":"63ba8895cc09e469","optional":false},{"name":"principal","type":"824a4aad44a54e24","optional":true},{"name":"rpcId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "8f324cea3916c051": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false}],"indices":[]}, + "8fcb0b44a575e998": {"kind":"object","properties":[{"name":"kind","type":"a720757f704a2512","optional":false}],"indices":[]}, + "904bf499d98be4a3": {"kind":"union","types":["7382c4fc95fe8c5d","b765ee31033cea46","f6cb462f808309e3"]}, + "938f7c7357bc403e": {"kind":"primitive","type":"null"}, + "95a3ffccbf3c8afc": {"kind":"literal","value":"owner"}, + "95c0e88fcf0bafb2": {"kind":"literal","value":"assistant"}, + "9645cf93769a6dfb": {"kind":"literal","value":"user-question-reply"}, + "96bfb916a727cd44": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false}],"indices":[]}, + "96f4a9c81fc0f940": {"kind":"union","types":["3e2ece4967cfebe9","62ecb62dc0fe1b5e"]}, + "99135d8a39379779": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false}],"indices":[]}, + "99e7e7d7fed55ae6": {"kind":"literal","value":"tool-jobs"}, + "99f0e98184709ad1": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false}],"indices":[]}, + "9ac52f0f84fec2eb": {"kind":"literal","value":"model-selection"}, + "9d42da116fccdc39": {"kind":"literal","value":"cua-held-inputs"}, + "9edc162949abf93b": {"kind":"object","properties":[{"name":"deliveryId","type":"4cd48f3e5108bd6e","optional":false},{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"db6c5246911d47a7","optional":false},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false},{"name":"ruleId","type":"4cd48f3e5108bd6e","optional":false},{"name":"source","type":"4cd48f3e5108bd6e","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "9f65c43e340bba31": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false}],"indices":[]}, + "a13d8f379222ece8": {"kind":"literal","value":"tool"}, + "a15a19ef63cf5d1b": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false}],"indices":[]}, + "a16e567c8cd2c55c": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false}],"indices":[]}, + "a2066bd52f61218b": {"kind":"object","properties":[{"name":"kind","type":"2f3f201c8846e19c","optional":false}],"indices":[]}, + "a2be0f0cb59f0d4a": {"kind":"literal","value":"error"}, + "a3c6f1ea38e9a61d": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "a4afec59b75aad5d": {"kind":"object","properties":[{"name":"clientTimeZone","type":"4cd48f3e5108bd6e","optional":true},{"name":"kind","type":"68f44f59e91c4139","optional":false},{"name":"principal","type":"824a4aad44a54e24","optional":true},{"name":"rpcId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "a6816f39283ae26f": {"kind":"literal","value":"cua-inputs-released"}, + "a720757f704a2512": {"kind":"literal","value":"tool-registry"}, + "a9059a81430b3207": {"kind":"literal","value":"hooks-claude-code"}, + "aa2bf9e82b9fdeb9": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false}],"indices":[]}, + "aa93010d0e521ad7": {"kind":"primitive","type":"boolean"}, + "aae343bc3d663c83": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false}],"indices":[]}, + "aba175fb20ffc711": {"kind":"array","element":"83079c8a3f733ac3"}, + "ada310bf0bdb8fed": {"kind":"object","properties":[{"name":"kind","type":"68f44f59e91c4139","optional":false}],"indices":[]}, + "ade057f4fdc387ae": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, + "aec150797b655c5f": {"kind":"literal","value":"catalog"}, + "b062078e899958f9": {"kind":"object","properties":[{"name":"kind","type":"1f1385dbc3e875c0","optional":false}],"indices":[]}, + "b0b0eb1b16490f6b": {"kind":"object","properties":[{"name":"attachmentId","type":"4cd48f3e5108bd6e","optional":false},{"name":"bytes","type":"0657d3ca5ac4e7bf","optional":false},{"name":"height","type":"0657d3ca5ac4e7bf","optional":false},{"name":"mediaType","type":"2f1e6a7ebace43d7","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":true},{"name":"originalDimensions","type":"0f46153645c29784","optional":true},{"name":"width","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "b0e809a7fc2b9068": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"589d0d91239681f8","optional":false},{"name":"source","type":"694b070275bbc9a6","optional":false,"compatibility":{"version":1,"policy":"session-source-attribution","binding":"session.developer-message.source","discriminator":"kind","unknownKinds":"preserve","attributionKinds":["action-cards","tmux-context","user-question-reply","working-directory"]}}],"indices":[]}, + "b2a5c8c008a31e3d": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false}],"indices":[]}, + "b3681c026a0b98e9": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "b4ec0af39fd52ed9": {"kind":"object","properties":[{"name":"kind","type":"bb94f3217aa56c88","optional":false}],"indices":[]}, + "b52f215a6cd69105": {"kind":"array","element":"8064c03c87c357fd"}, + "b613f83572fe2fbf": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "b6f94c17dd9bbd7c": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false}],"indices":[]}, + "b70f3e81fe11b7a5": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false}],"indices":[]}, + "b765ee31033cea46": {"kind":"literal","value":"set"}, + "b79641a9d25e7566": {"kind":"object","properties":[{"name":"kind","type":"8067b0d232c350f1","optional":false}],"indices":[]}, + "b815d7b91cdd9fc6": {"kind":"literal","value":"goal"}, + "ba2a1a8f194b1bb2": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "ba4c40b4381e0dcd": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "baccc97ec34be6c4": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "bb94f3217aa56c88": {"kind":"literal","value":"hooks-codex"}, + "bbc5696e3f13c758": {"kind":"opaque","reason":"unknown"}, + "bcf0caf62d964b2f": {"kind":"object","properties":[{"name":"endSeq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"op","type":"f6cb462f808309e3","optional":false},{"name":"startSeq","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "bf16d2e98a7f1389": {"kind":"literal","value":"subagent-settled"}, + "c071d01c76a37f9f": {"kind":"object","properties":[{"name":"maxTokens","type":"0657d3ca5ac4e7bf","optional":false},{"name":"messageSeqs","type":"5d03ba38734809bc","optional":false},{"name":"messages","type":"e973903c6f32109c","optional":false},{"name":"reasoningEffort","type":"4cd48f3e5108bd6e","optional":true},{"name":"route","type":"07e1a58c58b593f5","optional":false},{"name":"system","type":"4cd48f3e5108bd6e","optional":false},{"name":"titleProvider","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "c1f0f17b6493b85d": {"kind":"object","properties":[{"name":"arguments","type":"4cd48f3e5108bd6e","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"1f0133217eeeffd8","optional":false}],"indices":[]}, + "c5228b7a55498d84": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "c55827fba7018198": {"kind":"object","properties":[{"name":"callId","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"9645cf93769a6dfb","optional":false},{"name":"outcome","type":"85d6d96ff8842974","optional":false}],"indices":[]}, + "c5687b1313206a6f": {"kind":"literal","value":"cordis-host-runner"}, + "c748fb42c80a1200": {"kind":"array","element":"86e1e384495ee09a"}, + "c77ac037cb8af460": {"kind":"literal","value":"timeline-priority"}, + "cb1c8959e1726f82": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false}],"indices":[]}, + "cda2345a9be9d139": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "ce6e647c9e653b5d": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"a6816f39283ae26f","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "d215701afb7aafbf": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"c77ac037cb8af460","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "d4e4d575abeb4b72": {"kind":"literal","value":"canceled"}, + "d85590a5675c6e2f": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false}],"indices":[]}, + "d9c462b9f62fdd3e": {"kind":"object","properties":[{"name":"callId","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"a13d8f379222ece8","optional":false}],"indices":[]}, + "d9edf1862e4471d6": {"kind":"literal","value":"schedule"}, + "dacf3d5f3e4ff619": {"kind":"literal","value":true}, + "db06ef35b27a3842": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "db6c5246911d47a7": {"kind":"literal","value":"webhook"}, + "dba54c09c6e7aafc": {"kind":"object","properties":[{"name":"kind","type":"4edec1b770e8ec4c","optional":false}],"indices":[]}, + "dd00cdccd0ba487b": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "dd5ee8762bd8a14b": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, + "dd6cc2bb2a8f2824": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, + "dde0cdf9d426768b": {"kind":"object","properties":[{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "de25352d2dc41963": {"kind":"literal","value":"user/message"}, + "de30b1fa12c75f81": {"kind":"literal","value":"image/gif"}, + "deaae5cd30987d4f": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, + "deebfc7c62177ea8": {"kind":"object","properties":[{"name":"kind","type":"95a3ffccbf3c8afc","optional":false}],"indices":[]}, + "df843efd87c78cf8": {"kind":"array","element":"4f91f187baeabef5"}, + "e438a9d4fb883b3e": {"kind":"literal","value":"append"}, + "e744baea6a5d54ef": {"kind":"union","types":["09f3f8dc417f2782","4b259f7f8f0a44ad","69668f0ad0aabae2","b0e809a7fc2b9068","fa87537f4a9c1e25"]}, + "e7f4cbb3a57f4cbd": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "e8de0f457fed5b9f": {"kind":"literal","value":"notice"}, + "e973903c6f32109c": {"kind":"array","element":"e744baea6a5d54ef"}, + "ebb768d85ec87fb6": {"kind":"literal","value":"image/webp"}, + "edbbfff1128099fd": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "ee577a0cc18664c9": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "f19bee84bf3d2090": {"kind":"object","properties":[{"name":"attachmentId","type":"4cd48f3e5108bd6e","optional":false},{"name":"bytes","type":"0657d3ca5ac4e7bf","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "f230c0b583e23b25": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "f29d63336e8266d8": {"kind":"object","properties":[{"name":"kind","type":"d9edf1862e4471d6","optional":false}],"indices":[]}, + "f2da0f27c1e6add5": {"kind":"object","properties":[{"name":"attachment","type":"f19bee84bf3d2090","optional":false},{"name":"type","type":"277b61f9c6f81704","optional":false}],"indices":[]}, + "f4a66f654996c093": {"kind":"object","properties":[{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, + "f56c5b59ca016131": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"7f13860ee89a2d35","optional":false},{"name":"references","type":"df843efd87c78cf8","optional":false},{"name":"version","type":"f88f1b7b6bb733f6","optional":false}],"indices":[]}, + "f6329fb30c7ea801": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, + "f6605d6c57933aea": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false}],"indices":[]}, + "f68c335306535a00": {"kind":"literal","value":"user-approval"}, + "f6afe41e3926f422": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false}],"indices":[]}, + "f6cb462f808309e3": {"kind":"literal","value":"replace"}, + "f7283223aacdc39b": {"kind":"object","properties":[{"name":"kind","type":"9ac52f0f84fec2eb","optional":false}],"indices":[]}, + "f88f1b7b6bb733f6": {"kind":"literal","value":1}, + "f97f47b0eb87905e": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false}],"indices":[]}, + "fa87537f4a9c1e25": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"95c0e88fcf0bafb2","optional":false},{"name":"source","type":"719c51f67074f970","optional":false}],"indices":[]}, + "fb8b6a2e53cb9cf4": {"kind":"literal","value":"image"}, + "fbd2c74b346a1595": {"kind":"literal","value":"agent-instructions"}, + "fcf427290c6213c2": {"kind":"primitive","type":"never"}, + "fcf81d3c58c13593": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false}],"indices":[]}, + "fe1a7acdeed4d0f5": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "fee1caf8ab6a65c1": {"kind":"literal","value":"instructions"} + } +} diff --git a/docs/persistence-changes/2026-11-19-cua-input-notices.zh.md b/docs/persistence-changes/2026-11-19-cua-input-notices.zh.md new file mode 100644 index 0000000000..9d6a72eef4 --- /dev/null +++ b/docs/persistence-changes/2026-11-19-cua-input-notices.zh.md @@ -0,0 +1,60 @@ +--- +description: "记录持久化类型更改及其兼容性确认。" +kind: persistence-change +--- + +# 2026-11-19-cua-input-notices + +[English](2026-11-19-cua-input-notices.md) | 中文 + +## 概述 + +新增 cua-held-inputs 和 cua-inputs-released 来源标识,使用现有 notice 形式和文本内容。 + +## 目录 + +- [声明](#declaration) +- [兼容性](#compatibility) +- [验证](#verification) +- [开发备注](#dev-note) + + +## 声明 + +```yaml persistence-change +schemaVersion: 1 +id: 2026-11-19-cua-input-notices +baseline: false +changes: + - root: "event:agent/inbox/spliced" + previous: "2026-11-05-timeline-priority-notice" + after: "0880996d224033d9a668528f51edf5f229d9b07dda42fb65f7d1cc1150c12836" + decision: same-version + - root: "event:developer/message" + previous: "2026-11-05-timeline-priority-notice" + after: "3a6f3e4354a90287bb3a1fb19e7a2f643cdbd7c6472c865abd11f8fa2d3358d5" + decision: same-version + - root: "event:session/title-llm-request" + previous: "2026-11-05-timeline-priority-notice" + after: "4e81b0490558b80c87cd09b214cd958ce0df1bf2bb431c930ff8fd441a8d1df5" + decision: same-version + - root: "event:user/message" + previous: "2026-11-05-timeline-priority-notice" + after: "507043f63e859f272ce78f6bc65a7361ee087e5e06301f9c100302230bc887a7" + decision: same-version +``` + + +## 兼容性 + +保持 Session 格式 V4。新读取器保留此前所有来源种类和事件字段。已发布的 V4 读取器允许用户或开发者消息使用非空的未知来源种类,保留其元数据和文本,并已支持 notice 摘要。收件箱排队消息和已记录的标题请求消息使用相同的来源对象。这两个种类描述输入状态;恢复或派生 Session 不会重放原生输入,也不会重新建立持有状态。事件判别字段、文件头、消息角色和既有来源含义均不改变。 + + +## 验证 + +pnpm run test packages/session/session-format-v3-to-v4/tests/attribution.spec.ts packages/session/session-format-v3-to-v4/tests/message-sources.spec.ts:12 项测试通过。7 个定向 headless/TypeScript SDK CUA 快照、发行配置 cua-mcp 的预期输出、Web CUA 回放及 Python SDK 回放通过。CUA 行为测试覆盖持有提醒入日志、暂停后确认的释放提醒,以及迟到旧提醒的移除。 + + +## 开发备注 + +无。 From f7b9547bb41c5ebd64f72e9546b7e0c01f53efbc Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 19 Nov 2026 12:30:13 +0800 Subject: [PATCH 43/73] Refresh format facts and retain the asynchronous cancellation recheck --- docs/persistence-changes/historical-formats/README.i18n.yaml | 4 ++-- docs/persistence-changes/historical-formats/README.md | 2 +- docs/persistence-changes/historical-formats/README.zh.md | 2 +- packages/experimental/cua/src/held-inputs.ts | 1 + 4 files changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/persistence-changes/historical-formats/README.i18n.yaml b/docs/persistence-changes/historical-formats/README.i18n.yaml index ae9ee0c4b5..3938fdf18d 100644 --- a/docs/persistence-changes/historical-formats/README.i18n.yaml +++ b/docs/persistence-changes/historical-formats/README.i18n.yaml @@ -15,8 +15,8 @@ en: 14c57f30e676f6e3 zh: b1a0ccf26fab3727 /session-persistence-formats/format-references: - en: d0b94efc6bce9073 - zh: 0bc584a91a013c98 + en: 3c29467018aea879 + zh: f9f844e3329bd26d /session-persistence-formats/scope-and-evidence: en: 44ba17a168ec63ac zh: c80a44bdbf17a174 diff --git a/docs/persistence-changes/historical-formats/README.md b/docs/persistence-changes/historical-formats/README.md index d54fdb1d18..73038a8dd7 100644 --- a/docs/persistence-changes/historical-formats/README.md +++ b/docs/persistence-changes/historical-formats/README.md @@ -32,7 +32,7 @@ The index is generated from validated snapshots and the current writer constant. | 1 | PR #3349 | [V1](v1.md) | [JSON](v1.schema.json) | 54 / 415 | | 2 | `dsh-v0.1.3-alpha.2` | [V2](v2.md) | [JSON](v2.schema.json) | 56 / 435 | | 3 | PR #4320 | [V3](v3.md) | [JSON](v3.schema.json) | 60 / 467 | -| 4 | Current checkout | [Current catalog](../../persistence-catalog.md) | [JSON](../../persistence-schema.json) | 67 / 640 | +| 4 | Current checkout | [Current catalog](../../persistence-catalog.md) | [JSON](../../persistence-schema.json) | 67 / 644 | diff --git a/docs/persistence-changes/historical-formats/README.zh.md b/docs/persistence-changes/historical-formats/README.zh.md index 1becff2660..0357bd5692 100644 --- a/docs/persistence-changes/historical-formats/README.zh.md +++ b/docs/persistence-changes/historical-formats/README.zh.md @@ -32,7 +32,7 @@ description: "查找从 V0 到工作区写入器版本的每个 Session 格式 | 1 | PR #3349 | [V1](v1.zh.md) | [JSON](v1.schema.json) | 54 / 415 | | 2 | `dsh-v0.1.3-alpha.2` | [V2](v2.zh.md) | [JSON](v2.schema.json) | 56 / 435 | | 3 | PR #4320 | [V3](v3.zh.md) | [JSON](v3.schema.json) | 60 / 467 | -| 4 | 当前工作树 | [当前目录](../../persistence-catalog.zh.md) | [JSON](../../persistence-schema.json) | 67 / 640 | +| 4 | 当前工作树 | [当前目录](../../persistence-catalog.zh.md) | [JSON](../../persistence-schema.json) | 67 / 644 | diff --git a/packages/experimental/cua/src/held-inputs.ts b/packages/experimental/cua/src/held-inputs.ts index 175f7be600..2eb45af25e 100644 --- a/packages/experimental/cua/src/held-inputs.ts +++ b/packages/experimental/cua/src/held-inputs.ts @@ -158,6 +158,7 @@ export class CuaHeldInputs { const owner = this.owners.get(agent) const inTurn = ctx.agents.turnBoundaryOf(agent.session).openTurnStartSeq !== null const text = await owner?.reminder(inTurn) + // oxlint-disable-next-line typescript/no-unnecessary-condition -- Cancellation can arrive while the native state query awaits. if (signal.aborted) { await this.release(agent); return result } if (text && !owner?.closing) return { ...result, additionalContexts: [...result.additionalContexts ?? [], createUserMessage({ content: [{ type: 'text', text }], From 06ff7d3a6c49305eea8062ddd82ad5fb915dd1bc Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 19 Nov 2026 12:38:29 +0800 Subject: [PATCH 44/73] Declare shared Agent dispatch and tool protocol dependencies for CUA --- packages/experimental/cua/package.json | 7 ++++--- pnpm-lock.yaml | 6 +++--- scripts/package-dependency-policy.ts | 4 +++- 3 files changed, 10 insertions(+), 7 deletions(-) diff --git a/packages/experimental/cua/package.json b/packages/experimental/cua/package.json index 426d042d73..63d4424cd8 100644 --- a/packages/experimental/cua/package.json +++ b/packages/experimental/cua/package.json @@ -102,7 +102,8 @@ "@deepseek-ai/dsh-scope": "workspace:*", "@deepseek-ai/dsh-ptc-runtime-node": "workspace:*", "@deepseek-ai/dsh-tools": "workspace:*", - "@deepseek-ai/dsh-tool-executor-ptc": "workspace:*" + "@deepseek-ai/dsh-tool-executor-ptc": "workspace:*", + "@deepseek-ai/dsh-agent": "workspace:*" }, "dependencies": { "@deepseek-ai/dsh-brand": "workspace:*", @@ -110,7 +111,8 @@ "zod": "4.6.6", "@deepseek-ai/dsh-atomic-write": "workspace:*", "@deepseek-ai/dsh-typert-protocol": "workspace:*", - "@deepseek-ai/dsh-storage-domain": "workspace:*" + "@deepseek-ai/dsh-storage-domain": "workspace:*", + "@deepseek-ai/dsh-llm": "workspace:*" }, "devDependencies": { "@deepseek-ai/dsh-computer-use": "workspace:*", @@ -126,7 +128,6 @@ "@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:*", "@deepseek-ai/dsh-system-prompt": "workspace:*", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 4964dd920d..8414a6d664 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -10572,6 +10572,9 @@ importers: '@deepseek-ai/dsh-brand': specifier: workspace:* version: link:../../util/brand + '@deepseek-ai/dsh-llm': + specifier: workspace:* + version: link:../../llm/llm '@deepseek-ai/dsh-storage-domain': specifier: workspace:* version: link:../../storage/storage-domain @@ -10675,9 +10678,6 @@ importers: '@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 diff --git a/scripts/package-dependency-policy.ts b/scripts/package-dependency-policy.ts index 25ab4379e6..13e290c5ca 100644 --- a/scripts/package-dependency-policy.ts +++ b/scripts/package-dependency-policy.ts @@ -76,6 +76,8 @@ const SAFE_HOST_DEPENDENCY_EXPORTS = { /** Runtime exports that require every consumer to resolve the provider's shared peer instance. */ const PEER_REQUIRED_HOST_EXPORTS = { + // Agent notifications must use the installed Agent and scope dispatch implementation. + '@deepseek-ai/dsh-agent': ['emitAgentEvent'], // Profile settings must match the installed Node provider's configuration schema. '@deepseek-ai/dsh-ptc-runtime-node/configuration': ['resolvePersistentExecution'], // CUA mounts the installed provider and shares executor error classes with PTC. @@ -102,7 +104,7 @@ const PEER_REQUIRED_HOST_EXPORTS = { // Imported titles follow the installed title service's normalization. '@deepseek-ai/dsh-session-title': ['normalizeSessionTitle'], // Error classes have instance identity; CUA and Liveshare throw the registry's own copy so `instanceof` against it matches. - '@deepseek-ai/dsh-tools': ['defineTool', 'ToolArgsError', 'ToolContextUnavailableError'], + '@deepseek-ai/dsh-tools': ['defineTool', 'ToolArgsError', 'ToolContextUnavailableError', 'RUN_CODE_NAME'], // Readers recognize a deadline's TimeoutReason only by `instanceof` against their own copy. '@deepseek-ai/dsh-timeout': ['deadline', 'timeoutOf'], // Imported web tool results must render exactly like the installed web tools' results and cards. From 02955c55d14ec78af32943a1af64dc9630f51c9c Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 19 Nov 2026 12:43:54 +0800 Subject: [PATCH 45/73] Refresh CUA shared Agent 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 2e18191e32..a5b7a1a9c6 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -1153,6 +1153,7 @@ flowchart TD pkg_api_settings_controller --> pkg_settings pkg_api_settings_controller --> pkg_typert_protocol pkg_web_app --> pkg_shell_env + pkg_cua --> pkg_agent pkg_cua --> pkg_attachment pkg_cua --> pkg_error pkg_cua --> pkg_ptc_runtime_node @@ -1943,7 +1944,7 @@ flowchart TD | [`session-query`](../packages/session-query/session-query) | `session-query` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-title`](../packages/session/session-title), [`tool-todo`](../packages/todo/tool-todo) | | [`api-settings-controller`](../packages/api/settings-controller) | `api` | [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`credentials`](../packages/credentials/credentials), [`native-command`](../packages/util/native-command), [`session`](../packages/core/session), [`settings`](../packages/settings/settings), [`typert-protocol`](../packages/typert/protocol) | | [`web-app`](../packages/bundle/web-app) | `bundle` | [`shell-env`](../packages/shell/shell-env) | -| [`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), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | +| [`cua`](../packages/experimental/cua) | `experimental` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | | [`deepseek-chat-import`](../packages/experimental/deepseek-chat-import) | `experimental` | [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`tool-web`](../packages/web/tool-web) | | [`experimental-auto-review`](../packages/experimental/auto-review) | `experimental` | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-forge-session`](../packages/experimental/forge-session) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`llm`](../packages/llm/llm), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`tools`](../packages/core/tools) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index c281107e79..4904ee226e 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -1155,6 +1155,7 @@ flowchart TD pkg_api_settings_controller --> pkg_settings pkg_api_settings_controller --> pkg_typert_protocol pkg_web_app --> pkg_shell_env + pkg_cua --> pkg_agent pkg_cua --> pkg_attachment pkg_cua --> pkg_error pkg_cua --> pkg_ptc_runtime_node @@ -1945,7 +1946,7 @@ flowchart TD | [`session-query`](../packages/session-query/session-query) | `session-query` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-title`](../packages/session/session-title), [`tool-todo`](../packages/todo/tool-todo) | | [`api-settings-controller`](../packages/api/settings-controller) | `api` | [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`credentials`](../packages/credentials/credentials), [`native-command`](../packages/util/native-command), [`session`](../packages/core/session), [`settings`](../packages/settings/settings), [`typert-protocol`](../packages/typert/protocol) | | [`web-app`](../packages/bundle/web-app) | `bundle` | [`shell-env`](../packages/shell/shell-env) | -| [`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), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | +| [`cua`](../packages/experimental/cua) | `experimental` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | | [`deepseek-chat-import`](../packages/experimental/deepseek-chat-import) | `experimental` | [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`tool-web`](../packages/web/tool-web) | | [`experimental-auto-review`](../packages/experimental/auto-review) | `experimental` | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-forge-session`](../packages/experimental/forge-session) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`llm`](../packages/llm/llm), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`tools`](../packages/core/tools) | From a09a0e997948996b9a140d301a4ec3ee31dc222b Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 19 Nov 2026 15:33:01 +0800 Subject: [PATCH 46/73] Track Windows CUA holds and settle cancelled responses before reset --- .../cua-held-inputs/guide.i18n.yaml | 12 +- .../v0.2.2-rc.5/cua-held-inputs/guide.md | 6 +- .../v0.2.2-rc.5/cua-held-inputs/guide.zh.md | 6 +- .../Sources/CuaNative/RequestAdmission.swift | 3 - .../CuaNative/WindowPointerInput.swift | 5 +- .../native/tests/CapabilitiesFixture.swift | 14 +- .../native/tests/capabilities_e2e.py | 7 + .../cua-macos/tests/guidance.spec.ts | 7 +- packages/experimental/cua-mcp/src/server.ts | 42 ++- .../cua-mcp/tests/composition.spec.ts | 36 +++ .../experimental/cua-windows/README.i18n.yaml | 12 +- packages/experimental/cua-windows/README.md | 6 +- .../experimental/cua-windows/README.zh.md | 8 +- .../native/desktop-tests/Program.cs | 12 + .../native/entry/DesktopExecutor.cs | 56 +++- .../cua-windows/native/entry/Dispatchers.cs | 3 +- .../cua-windows/native/entry/HeldInputs.cs | 253 ++++++++++++++++++ .../cua-windows/native/entry/Input.cs | 101 ++++--- .../cua-windows/native/entry/NativeServer.cs | 23 +- .../cua-windows/native/entry/Win32.cs | 5 + .../cua-windows/native/generate-protocol.ts | 9 +- .../cua-windows/native/protocol.schema.json | 76 +++++- .../native/tests/HeldInputChecks.cs | 87 ++++++ .../cua-windows/native/tests/Program.cs | 17 +- .../native/tests/Protocol.Tests.csproj | 2 + .../experimental/cua-windows/src/guidance.ts | 2 +- .../experimental/cua-windows/src/index.ts | 1 + .../tests/desktop-toggle-mouse.spec.ts | 39 ++- .../tests/loader-composition.spec.ts | 3 +- .../cua-windows/tests/protocol.spec.ts | 10 +- .../tests/provider-lifecycle.spec.ts | 5 +- packages/experimental/cua/src/guidance.ts | 12 +- packages/experimental/cua/src/held-inputs.ts | 38 +-- packages/experimental/cua/src/index.ts | 5 +- packages/experimental/cua/src/types.ts | 8 +- .../cua/tests/run-code-composition.spec.ts | 42 +++ 36 files changed, 834 insertions(+), 139 deletions(-) create mode 100644 packages/experimental/cua-windows/native/entry/HeldInputs.cs create mode 100644 packages/experimental/cua-windows/native/tests/HeldInputChecks.cs diff --git a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml index 53d804443b..1bb2901ef5 100644 --- a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml @@ -3,14 +3,14 @@ # 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.5/cua-held-inputs/guide.md /: - en: aa41a4beebdac9bf - zh: 0c027e6be34dae49 + en: 9256c8b808ebc45d + zh: ca6524b78cd7f365 /cua-reports-held-input-after-programs: en: 37252a5d19c7fe09 zh: f1b33b7da3935155 /cua-reports-held-input-after-programs/change: - en: 4bd67513168d23c2 - zh: 62139119ecfdc51e + en: 2812241cf189be50 + zh: ee90f8e5c6c55512 /cua-reports-held-input-after-programs/migration: - en: ff2470e52eb67983 - zh: 8fd179145c4da20a + en: e14ac0c327d75964 + zh: 7899f47c4a3cc78c diff --git a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md index 7a95370903..5eb055f55c 100644 --- a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md @@ -1,6 +1,6 @@ --- kind: upgrade-guide -description: Explicit macOS CUA input persists across programs and turns, with system reminders after successful programs. +description: Explicit CUA input on macOS and Windows persists across programs and turns, with system reminders after successful programs. --- # CUA reports held input after programs @@ -8,10 +8,10 @@ English | [中文](guide.zh.md) ## Change -macOS explicit `sendKeyEvent('down')` and `toggleMouse('down')` remain held across programs and turns until an explicit `up`. Normal completion does not release them. After a successful `run_code` or `cua_run_code`, a system reminder lists any remaining keys and mouse buttons, their application or window and actual input mode. Program failure, user stop, connection closure, environment reset and disposal release owned input in reverse dispatch order. Complete `pressKey`, `typeText`, `click` and `drag` actions keep their operation-local cleanup. DSH and MCP both preserve input after successful programs. A client pause between completed MCP calls is not observable by the server and can leave input held. Windows reporting and unified cleanup remain unimplemented. +On macOS and Windows, explicit `sendKeyEvent('down')` and `toggleMouse('down')` remain held across programs and turns until an explicit `up`. Normal completion does not release them. After a successful `run_code` or `cua_run_code`, a system reminder lists any remaining keys and mouse buttons, their application or window and actual input mode. Program failure, user stop, connection closure, environment reset and disposal release owned input in reverse dispatch order. Complete `pressKey`, `typeText`, `click` and `drag` actions keep their operation-local cleanup. DSH and MCP both preserve input after successful programs. A client pause between completed MCP calls is not observable by the server and can leave input held. On Windows, an up after focus changes releases desktop input without reactivating the original window. ## Migration 1. Pair explicit downs with ups when input should stop. Read the reminder before continuing; no reminder is added when no input remains held. -2. Upgrade the macOS package and helper together. A custom `helperPath` must implement the task-owned `getHeldInputs` and `releaseHeldInputs` private operations. +2. Upgrade the platform package and helper together. A custom `helperPath` must implement the task-owned `getHeldInputs` and `releaseHeldInputs` private operations. 3. Verify that one successful program can hold a key, receive its reminder, and release it in a later program. Program failure and cancellation must release it before they finish. If cleanup cannot be confirmed, CUA disables further operations for that task; inspect the desktop manually before starting another task. diff --git a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md index c9418b085d..4f88528585 100644 --- a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md @@ -1,6 +1,6 @@ --- kind: upgrade-guide -description: macOS CUA 的显式输入跨程序和回合保持,成功结束的程序通过 system reminder 报告持有状态。 +description: macOS 和 Windows 的 CUA 显式输入跨程序和回合保持,成功结束的程序通过 system reminder 报告持有状态。 --- # CUA 在程序结束后报告持有输入 @@ -8,10 +8,10 @@ description: macOS CUA 的显式输入跨程序和回合保持,成功结束的 ## 变更 -macOS 的显式 `sendKeyEvent('down')` 和 `toggleMouse('down')` 跨程序、跨回合保持,直到显式 `up`。正常结束不释放它们。成功结束的 `run_code` 或 `cua_run_code` 通过 system reminder 列出剩余键盘键和鼠标按钮、所属应用或窗口及实际输入方式。程序失败、用户停止、断连、环境重置和销毁按派发顺序的反序释放所属输入。完整的 `pressKey`、`typeText`、`click` 和 `drag` 保持操作内清理。DSH 和 MCP 都在程序成功后保持输入。客户端在两次 MCP 调用之间暂停时,服务端无法观察到,输入可能继续按住。Windows 的状态报告和统一清理仍未实现。 +macOS 和 Windows 的显式 `sendKeyEvent('down')` 和 `toggleMouse('down')` 跨程序、跨回合保持,直到显式 `up`。正常结束不释放它们。成功结束的 `run_code` 或 `cua_run_code` 通过 system reminder 列出剩余键盘键和鼠标按钮、所属应用或窗口及实际输入方式。程序失败、用户停止、断连、环境重置和销毁按派发顺序的反序释放所属输入。完整的 `pressKey`、`typeText`、`click` 和 `drag` 保持操作内清理。DSH 和 MCP 都在程序成功后保持输入。客户端在两次 MCP 调用之间暂停时,服务端无法观察到,输入可能继续按住。Windows 失焦后松开会释放桌面输入,不重新激活原窗口。 ## 迁移 1. 输入不再需要保持时,将显式 down 与 up 配对。继续操作前阅读提醒;没有持有输入时不添加提醒。 -2. 同步升级 macOS 包和 helper。自定义 `helperPath` 必须实现按任务区分的 `getHeldInputs` 和 `releaseHeldInputs` 私有操作。 +2. 同步升级平台包和 helper。自定义 `helperPath` 必须实现按任务区分的 `getHeldInputs` 和 `releaseHeldInputs` 私有操作。 3. 验证成功结束的程序能持有按键、收到提醒,并在后续程序中释放。程序失败和取消必须在结束前释放它。清理无法确认时,CUA 禁用该任务后续操作;请手动检查桌面后再创建其他任务。 diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestAdmission.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestAdmission.swift index aa700cdcdd..9ebb8c4877 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestAdmission.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestAdmission.swift @@ -81,6 +81,3 @@ struct RequestParameters: Sendable { } func point(_ x: String = "x", _ y: String = "y") throws -> WindowPoint { WindowPoint(x: try number(x), y: try number(y)) } } - -extension RequestParameters { -} diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/WindowPointerInput.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/WindowPointerInput.swift index 995b18a43f..c2a95c2af2 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/WindowPointerInput.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/WindowPointerInput.swift @@ -67,9 +67,12 @@ final class WindowPointerInput { try held.pointerDown(owner: owner, route: route, button: selected, system: false, down: pair.down, up: pair.up, post: { poster.post($0, to: route.owner.pid) }, prepareRelease: { event in guard let screen = CGEvent(source: nil)?.location else { return } + let current: WindowInfo + do { current = try NativePlatform.ownedWindow(route.owner.pid, route.windowID) } + catch let error as NativeFailure where error.code == "WINDOW_UNAVAILABLE" { return } event.location = screen try poster.stampWindow(event, pid: route.owner.pid, windowID: route.windowID, - point: WindowPoint(x: screen.x - route.bounds.x, y: screen.y - route.bounds.y)) + point: WindowPoint(x: screen.x - current.bounds.x, y: screen.y - current.bounds.y)) }) } diff --git a/packages/experimental/cua-macos/native/tests/CapabilitiesFixture.swift b/packages/experimental/cua-macos/native/tests/CapabilitiesFixture.swift index 862608c734..1bff6c4ddd 100644 --- a/packages/experimental/cua-macos/native/tests/CapabilitiesFixture.swift +++ b/packages/experimental/cua-macos/native/tests/CapabilitiesFixture.swift @@ -49,6 +49,8 @@ final class CapabilitiesFixture: NSObject, NSApplicationDelegate, NSWindowDelega var events: [[String: Any]] = [] var axPresses = 0 var axMenus = 0 + private var moveSignal: DispatchSourceSignal? + private var moved = false init(statePath: String) { self.statePath = statePath } func applicationDidFinishLaunching(_ notification: Notification) { let bar = NSMenu() @@ -66,6 +68,16 @@ final class CapabilitiesFixture: NSObject, NSApplicationDelegate, NSWindowDelega window.title = "DSH CUA capability checks" window.isReleasedWhenClosed = false window.animationBehavior = .none + signal(SIGUSR1, SIG_IGN) + let move = DispatchSource.makeSignalSource(signal: SIGUSR1, queue: .main) + move.setEventHandler { [weak self] in + guard let self else { return } + self.window.setFrameOrigin(NSPoint(x: self.window.frame.minX + (self.moved ? -40 : 40), y: self.window.frame.minY)) + self.moved.toggle() + self.persist() + } + move.resume() + moveSignal = move window.collectionBehavior = [.canJoinAllApplications, .stationary] text = CapabilityTextView(frame: NSRect(x: 20, y: 230, width: 600, height: 235)) text.isRichText = true @@ -135,7 +147,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 > 0 ? String(window.windowNumber) as Any : NSNull(), - "active": NSApplication.shared.isActive, "keyWindow": window.isKeyWindow, + "windowX": window.frame.minX, "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, "axMenus": axMenus, "pad": [frame.minX, window.frame.height - frame.maxY, frame.width, frame.height]] diff --git a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py index 812e8e4aa4..9662858540 100644 --- a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py +++ b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py @@ -94,6 +94,9 @@ def check_toggle_mouse(helper, owner, state_file, executable): assert cursor() == inside assert not state["events"][-1]["pressedButtons"] & (1 << index), state assert cursor(*outside) == outside + if button == "right": + os.kill(state["pid"], signal.SIGUSR1) + wait_owned(lambda s: s["windowX"] == bounds["x"] + 40) if button == "middle": other_state = state_file.with_name("other.json") other = subprocess.Popen([executable, other_state]) @@ -108,6 +111,10 @@ def check_toggle_mouse(helper, owner, state_file, executable): events = state["events"][count:] assert [(e["type"], e["button"]) for e in events] == [(down, index), (up, index)], events assert events[1]["point"][0] < 0, events + if button == "right": + assert events[1]["point"][0] == outside[0] - bounds["x"] - 40, events + os.kill(state["pid"], signal.SIGUSR1) + wait_owned(lambda s: s["windowX"] == bounds["x"]) if button != "middle": assert cursor() == outside call("activate", owner) diff --git a/packages/experimental/cua-macos/tests/guidance.spec.ts b/packages/experimental/cua-macos/tests/guidance.spec.ts index 34534f3a9e..24dd85e6b8 100644 --- a/packages/experimental/cua-macos/tests/guidance.spec.ts +++ b/packages/experimental/cua-macos/tests/guidance.spec.ts @@ -1,7 +1,7 @@ /** Model-facing guidance lists the object API with platform availability and input constraints. */ import { expect, it } from 'vitest' import type { CuaApi, CuaApp, CuaSurface, CuaWindow } from '@deepseek-ai/dsh-cua/api' -import { COMMON_GUIDANCE, withSystemPointerGuidance } from '@deepseek-ai/dsh-cua/guidance' +import { COMMON_GUIDANCE, withHeldInputGuidance, withSystemPointerGuidance } from '@deepseek-ai/dsh-cua/guidance' import { GUIDANCE, PLATFORM_GUIDANCE, PROGRAM_GUIDANCE } from '../src/guidance.ts' const apiNames: Array = ['getCapabilities', 'listApps', 'findApps', 'getState', 'getApp'] @@ -55,8 +55,9 @@ it('states the macOS accessibility, keyboard, and mouse levels', () => { expect(PLATFORM_GUIDANCE).toContain('Simulated mouse input is available at window level') const pressKey = GUIDANCE.split('\n').find(line => line.startsWith('- pressKey(')) expect(GUIDANCE).toContain("sendKeyEvent(key: string, direction: 'down' | 'up')") - expect(COMMON_GUIDANCE).toContain('sendKeyEvent and toggleMouse remain held across programs and turns') - expect(COMMON_GUIDANCE).toContain('a system reminder lists any remaining keys and mouse buttons') + expect(COMMON_GUIDANCE).not.toContain('sendKeyEvent and toggleMouse remain held across programs and turns') + expect(withHeldInputGuidance(COMMON_GUIDANCE)).toContain('sendKeyEvent and toggleMouse remain held across programs and turns') + expect(withHeldInputGuidance(COMMON_GUIDANCE)).toContain('a system reminder lists any remaining keys and mouse buttons') const sharedKeyEvent = COMMON_GUIDANCE.split('\n').find(line => line.startsWith('- sendKeyEvent(')) expect(sharedKeyEvent).toBeDefined() expect(GUIDANCE.split('\n').find(line => line.startsWith('- sendKeyEvent('))).toContain(sharedKeyEvent) diff --git a/packages/experimental/cua-mcp/src/server.ts b/packages/experimental/cua-mcp/src/server.ts index 609a56439c..f9c55bef29 100644 --- a/packages/experimental/cua-mcp/src/server.ts +++ b/packages/experimental/cua-mcp/src/server.ts @@ -95,8 +95,8 @@ const INSTRUCTIONS = 'DeepSeek Harness Computer Use: observe and operate desktop + 'Start every conversation by calling cua_get_api_reference: it returns the complete cua API reference, and programs ' + 'written without it guess the API wrong. Then call cua_run_code with a TypeScript program that uses the global cua ' + 'object; program state persists across calls on this connection. A call may ask the user for application or pointer ' - + 'consent before it proceeds. Call cua_reset to discard program state. ' - + 'Explicit key and mouse downs remain held across successful programs; a system reminder lists remaining holds. Explicit up, program failure, request cancellation, reset, and connection closure release owned input. Client pause between completed calls is not observable by this server and does not release input.' + + 'consent before it proceeds. Call cua_reset to discard program state.' + const NO_PROVIDER = 'Computer Use is not available on this Host: the cua-mcp profile has no active CUA provider. ' + 'Providers exist for macOS and native Windows; on those Hosts the server\'s stderr names why the provider did not start.' @@ -214,20 +214,34 @@ export async function createCuaMcpServer(ctx: Context, options: CuaMcpServerOpti try { // The call is the Agent's maintenance activity: Agent disposal cancels it and waits for it, with its nested // calls, to settle before the Agent's scope and Session close. - const batch = await agent.runMaintenance(maintenance => ctx.agents.withInitiator(agent, () => ctx.tools.execute({ - calls: [{ - type: 'tool-call', id: brandString(`cua-mcp-${String(++calls)}`), name: PROGRAM_TOOL, arguments: JSON.stringify(args), - }], - agent, signal: AbortSignal.any([signal, maintenance]), - }))) - const outcome = batch.results[0] - if (outcome === undefined) throw new Error(`The tool executor settled without a ${PROGRAM_TOOL} result`) - return await projectToolResult(outcome.result, batch.additionalContexts, { - attachments: ctx.attachments, target: image => programs?.screenshotRequestTarget(image), - }, signal) + const response = await agent.runMaintenance(async (maintenance) => { + const operation = AbortSignal.any([signal, maintenance]) + const batch = await ctx.agents.withInitiator(agent, () => ctx.tools.execute({ + calls: [{ + type: 'tool-call', id: brandString(`cua-mcp-${String(++calls)}`), name: PROGRAM_TOOL, arguments: JSON.stringify(args), + }], + agent, signal: operation, + })) + const outcome = batch.results[0] + if (outcome === undefined) throw new Error(`The tool executor settled without a ${PROGRAM_TOOL} result`) + const result = await projectToolResult(outcome.result, batch.additionalContexts, { + attachments: ctx.attachments, target: image => programs?.screenshotRequestTarget(image), + }, operation) + if (!outcome.result.isError) operation.throwIfAborted() + return result + }) + await cleanup + return response + } catch (error) { + cancel() + try { await cleanup } + catch (failure) { + if (failure === error) throw error + throw new AggregateError([error, failure], `Computer Use request failed: ${String(error)}. Held-input cleanup failed: ${String(failure)}`) + } + throw error } finally { signal.removeEventListener('abort', cancel) - await cleanup } } diff --git a/packages/experimental/cua-mcp/tests/composition.spec.ts b/packages/experimental/cua-mcp/tests/composition.spec.ts index d4ea33ad45..eeac8e47a0 100644 --- a/packages/experimental/cua-mcp/tests/composition.spec.ts +++ b/packages/experimental/cua-mcp/tests/composition.spec.ts @@ -238,6 +238,42 @@ describe('Computer Use MCP composition', () => { expect(native.held).toEqual([]) }) + it.each(['reset', 'image failure'] as const)('cleans up held input when %s interrupts response delivery', async (ending) => { + const { ctx, native, client, run } = await setup() + const entered: PromiseWithResolvers = Promise.withResolvers() + const finish: PromiseWithResolvers = Promise.withResolvers() + const original = ctx.attachments.readImageRequest.bind(ctx.attachments) + const read = vi.spyOn(ctx.attachments, 'readImageRequest').mockImplementation(async (...args) => { + if (native.calls.some(call => call.method === 'getHeldInputs')) { + entered.resolve() + await finish.promise + if (ending === 'image failure') throw new Error('Fixture screenshot could not be delivered') + } + return original(...args) + }) + onTestFinished(() => { finish.resolve(); read.mockRestore() }) + const running = run('var app = await cua.getApp("test.fixture"); var win = await app.getWindow("7"); await app.sendKeyEvent("w", "down"); inspect(await win.getScreenshot())') + .then(value => texts(value).join(' '), error => String(error)) + await entered.promise + let reset: ReturnType | undefined + try { + expect(native.held.map(press => press.key)).toEqual(['w']) + if (ending === 'reset') { + let resetDone = false + const release = native.controlNext('releaseHeldInputs') + reset = client.callTool({ name: 'cua_reset', arguments: {} }).then((result) => { resetDone = true; return result }) + await release.entered + release.reply() + expect(resetDone).toBe(false) + } + } finally { finish.resolve() } + const result = await running + expect(result).not.toContain('CUA inputs are still held') + if (ending === 'image failure') expect(result).toContain('Fixture screenshot could not be delivered') + expect((await reset)?.isError).not.toBe(true) + expect(native.held).toEqual([]) + }) + it('reports refused cleanup after a cancelled MCP request and prevents further native input', async () => { const { ctx, native, run } = await setup() await run('var app = await cua.getApp("test.fixture"); await app.sendKeyEvent("w", "down")') diff --git a/packages/experimental/cua-windows/README.i18n.yaml b/packages/experimental/cua-windows/README.i18n.yaml index eaa6512d71..fd884ad639 100644 --- a/packages/experimental/cua-windows/README.i18n.yaml +++ b/packages/experimental/cua-windows/README.i18n.yaml @@ -27,8 +27,8 @@ en: fc5753d540e79693 zh: 3f1fb40c623c6df1 /deepseek-ai-dsh-cua-windows/interaction-rules: - en: f482aa2488612eff - zh: c821c006a36e8f27 + en: f76e73e5ef38aced + zh: ad00327ec3607e0f /deepseek-ai-dsh-cua-windows/model-experience: en: 215e7ba838619b7b zh: a311da3843709f90 @@ -36,8 +36,8 @@ en: 38b3250d6ae0f3d6 zh: 33d056c416e11d75 /deepseek-ai-dsh-cua-windows/model-experience/explicit-application-and-window-operations/what-the-model-sees: - en: 8445a0a43022223e - zh: 48d5a3c726bc4bb6 + en: 81af5b1e782d3290 + zh: db72fcd496fd44e4 /deepseek-ai-dsh-cua-windows/model-experience/explicit-application-and-window-operations/token-effect: en: 39eebd53ee226af7 zh: ba7b352cf1e23c3c @@ -45,8 +45,8 @@ en: db3e2957041fafbb zh: 34f953887dff37f7 /deepseek-ai-dsh-cua-windows/known-limitations-and-deferred-work: - en: bf9fe6192869d744 - zh: 2994b8a0c3675a88 + en: 3e2cd5ed7118b7f3 + zh: c131f98f889bd728 /deepseek-ai-dsh-cua-windows/known-limitations-and-deferred-work/dev-note: en: 0a1253c6f7b5e8b9 zh: 9f56528562c7c914 diff --git a/packages/experimental/cua-windows/README.md b/packages/experimental/cua-windows/README.md index 46a183790b..c4373f8832 100644 --- a/packages/experimental/cua-windows/README.md +++ b/packages/experimental/cua-windows/README.md @@ -56,7 +56,7 @@ Each result contains `id`, `displayName`, and `isRunning`. The ID is an AUMID, i 4. Treat `dispatched` as dispatch evidence, not confirmation of the intended effect. Observe the result before continuing. On a changed window, stale snapshot, timeout, or cancellation, do not blindly repeat input or switch to another window. 5. Consent applies to the application within the conversation. Respect denial and revocation; do not use another tool to bypass them. Reconnects invalidate retained handles, so select the application again before further operations. -`win.toggleMouse(button, direction)` sends one system mouse button event at the current pointer. The selected window must be in the foreground for both directions. A press also requires a pointer hit on that window; a release can occur outside it. +`win.toggleMouse(button, direction)` sends one system mouse button event at the current pointer. A down requires the selected window to be in the foreground and under the pointer. Release through the original Window object. An up releases the desktop button without switching focus or moving the pointer. ## Model Experience @@ -65,7 +65,7 @@ Each result contains `id`, `displayName`, and `isRunning`. The ID is an AUMID, i #### What the model sees -The program receives application and window identifiers, observations, and action results. Selection alone does not provide an accessibility tree. +The program receives application and window identifiers, observations, and action results. Selection alone does not provide an accessibility tree. After a successful program, a reminder lists any held keys and buttons with their window and desktop input mode. Program failure, cancellation, reset and disconnect release owned input in reverse order. #### Token effect @@ -82,7 +82,7 @@ Inspected results append to model history. Retaining an App, Window, or returned - The npm package omits the Windows helper. Use the [standalone ZIP on x64 or a matching build on ARM64](#setup). - Hover, click, scroll and drag use the system pointer. `requireSystemPointerApproval` does not prompt separately for Windows pointer operations. - Drag checks the topmost window only at its starting point. An overlay from another application along the path or at the destination can receive the drop even while the selected window stays in the foreground. -- Windows has not yet implemented native held-input reporting or unified failure/cancellation cleanup. Explicitly pair every key and mouse down with up; do not rely on reminders or automatic release. +- Windows routes input through the desktop. After focus changes or the original window closes, a confirmed release means the desktop accepted the up. The original window may not receive the event. If the desktop is unavailable or refuses to confirm release, further CUA input for the task is blocked. Inspect the desktop before starting another task. - The helper does not check each key or button release during cleanup. If an input remains held after a failure, release it manually before continuing. - Helper identity hashes only the exe. Different DLLs with the same apphost can reuse the old service. Stop Hosts using the same output directory before rebuilding to avoid locked files. - The Windows handshake requires a positive `maxClickHoldMs`. With zero, it fails with `INVALID_CONFIG` before ordinary clicks or status queries can run. diff --git a/packages/experimental/cua-windows/README.zh.md b/packages/experimental/cua-windows/README.zh.md index f2072483d3..29ce54885f 100644 --- a/packages/experimental/cua-windows/README.zh.md +++ b/packages/experimental/cua-windows/README.zh.md @@ -56,7 +56,7 @@ kind: "package-reference" 4. `dispatched` 只表示分派情况,不证明预期效果已经发生。继续操作前先观察结果。窗口变化、快照过期、超时或取消后,不要盲目重放输入,也不要自动切换目标窗口。 5. 授权针对当前会话中的应用。尊重拒绝和撤销,不使用其他工具绕过。重新连接会使已保留的句柄失效,继续操作前必须重新选择应用。 -`win.toggleMouse(button, direction)` 在当前指针位置发送一次系统按键事件。按下和松开时,所选窗口都必须在前台。按下时指针还必须命中该窗口,松开时可以移出窗口。 +`win.toggleMouse(button, direction)` 在当前指针位置发送一次系统按键事件。按下时,所选窗口必须在前台,指针也必须命中该窗口。请通过原 Window 对象松开;松开只释放桌面按钮,不切换焦点,也不移动指针。 ## 模型体验 @@ -65,7 +65,7 @@ kind: "package-reference" #### 模型看到什么 -程序可以读取应用和窗口标识、观察结果及动作结果。仅执行选择操作不会提供辅助功能树。 +程序可以读取应用和窗口标识、观察结果及动作结果。仅执行选择操作不会提供辅助功能树。程序成功后,提醒会列出仍按住的键和鼠标按钮、所属窗口和桌面输入方式。程序异常、取消、重置和断连时,按派发顺序反序释放任务持有的输入。 #### Token 影响 @@ -82,8 +82,8 @@ kind: "package-reference" - 通过 npm 安装的包不含 Windows helper。x64 可使用独立 ZIP,ARM64 需要对应架构的构建产物,见[配置说明](#setup)。 - 悬停、点击、滚动和拖拽使用系统指针。`requireSystemPointerApproval` 不会为 Windows 操作弹出单独的指针授权提示。 - 拖拽只检查起点处最上层的窗口。若其他应用遮住路径或终点,即使目标仍在前台,也可能把内容拖到其他应用。 -- Windows 尚未实现原生持有状态报告和统一的异常或取消清理。每次键盘或鼠标 down 都须显式配对 up,不能依赖提醒或自动释放。 -- 清理输入时,helper 不检查每个按键或鼠标按钮的释放结果。操作失败后如有按键或按钮仍处于按下状态,请先手动释放。 +- Windows 通过桌面派发输入。焦点变化或原窗口关闭后,确认释放表示桌面接受了 up,原窗口可能收不到该事件。若桌面不可用或无法确认释放,本任务不能继续使用 CUA。请先检查桌面,再开始新任务。 +- 清理完整动作内的临时输入时,helper 不检查每个按键或鼠标按钮的释放结果。操作失败后如有按键或按钮仍处于按下状态,请先手动释放。 - helper 的身份摘要只覆盖 exe。同一 apphost 搭配不同 DLL 时可能复用旧服务。重新构建前请先关闭使用同一输出目录的 Host,避免文件被占用。 - Windows 握手要求 `maxClickHoldMs` 为正整数。设为 0 会使连接以 `INVALID_CONFIG` 失败,连普通点击和状态查询也不可用。 - 不支持 `findApps`、启动应用和应用级辅助功能。请让用户打开所需应用或窗口。 diff --git a/packages/experimental/cua-windows/native/desktop-tests/Program.cs b/packages/experimental/cua-windows/native/desktop-tests/Program.cs index 3371433909..5e96f96a96 100644 --- a/packages/experimental/cua-windows/native/desktop-tests/Program.cs +++ b/packages/experimental/cua-windows/native/desktop-tests/Program.cs @@ -11,6 +11,7 @@ internal sealed class FixtureForm : Form 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 List inputEvents = []; private int leftDowns, leftUps, rightDowns, rightUps, middleDowns, middleUps; private readonly ToolTip tooltip = new(); @@ -20,6 +21,9 @@ internal sealed class FixtureForm : Form StartPosition = FormStartPosition.Manual; Location = new(100, 100); ClientSize = new(500, 300); + KeyPreview = true; + KeyDown += (_, e) => WatchKey(e.KeyCode, "down"); + KeyUp += (_, e) => WatchKey(e.KeyCode, "up"); Controls.Add(Editor); Controls.Add(button); button.Click += (_, _) => clicks++; @@ -30,8 +34,14 @@ internal sealed class FixtureForm : Form tooltip.SetToolTip(button, "CUA hover is retained"); } + private void WatchKey(Keys key, string direction) + { + if (key is Keys.W or Keys.ShiftKey) inputEvents.Add($"{key}:{direction}"); + } + private void Count(MouseButtons pressed, bool down) { + inputEvents.Add($"{pressed}:{(down ? "down" : "up")}"); switch (pressed) { case MouseButtons.Left: if (down) leftDowns++; else leftUps++; break; @@ -74,6 +84,7 @@ internal sealed class FixtureForm : Form ups = new { left = leftUps, right = rightUps, middle = middleUps }, button = new { x = button.Left + button.Width / 2, y = button.Top + button.Height / 2 }, selection = new { start = Editor.SelectionStart, length = Editor.SelectionLength }, + inputEvents = inputEvents.ToArray(), wDown = (GetAsyncKeyState(87) & 0x8000) != 0, buttons = MouseButtons.ToString(), minimized = WindowState == FormWindowState.Minimized, visible = Visible, }; @@ -83,6 +94,7 @@ internal sealed class FixtureForm : Form base.Dispose(disposing); } + [DllImport("user32.dll")] private static extern short GetAsyncKeyState(int key); [DllImport("user32.dll")] private static extern nint GetForegroundWindow(); [DllImport("user32.dll")] private static extern nint WindowFromPoint(Point point); [DllImport("user32.dll")] private static extern nint GetAncestor(nint window, uint flags); diff --git a/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs b/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs index 8a308efc90..0bcad20693 100644 --- a/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs +++ b/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs @@ -8,14 +8,28 @@ namespace DeepSeek.Cua.Windows; internal sealed class ClientState { + internal Guid Connection { get; } = Guid.NewGuid(); 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(); } } -internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IAsyncDisposable +internal sealed class DesktopExecutor : IAsyncDisposable { + private readonly MtaDispatcher mta; + private readonly StaDispatcher sta; + private readonly HeldInputs inputs = new(control => (Win32.GetAsyncKeyState(control) & 0x8000) != 0, + input => Input.Send(input), DesktopSession.RequireInteractive); + private readonly HeldInputHooks hooks; + + internal DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) + { + this.mta = mta; + this.sta = sta; + hooks = new(inputs); + } + private readonly WindowCapture capture = new(); private readonly ClipboardPaste clipboard = new(); private readonly SemaphoreSlim queue = new(1); @@ -51,7 +65,7 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA internal async Task Execute(NativeRequest request, ClientState state, NativeConfig config, CancellationToken cancellation, Action reportFailure) { - var context = new RequestContext(config, cancellation, mta, sta, reportFailure); + var context = new RequestContext(config, cancellation, mta, sta, reportFailure, inputs); if (request.Method == "screenshot") { AppState app; @@ -84,6 +98,21 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA if (request.Method == "getActionSchema") return PatternActions.Schema(String(parameters, "action")); if (request.Method is "requestPermission" or "openPermissionSettings") throw new NativeFailure("UNSUPPORTED", "Windows desktop access has no macOS permission switches; inspect the Windows session status"); + if (request.Method == "getHeldInputs") return inputs.Get(state.Connection, String(parameters, "taskId")); + if (request.Method == "releaseHeldInputs") + return inputs.Release(state.Connection, String(parameters, "taskId"), cancellation, config.GraceMs); + + if (request.Method is "sendKeyEvent" or "toggleMouse" && String(parameters, "direction") == "up") + { + var window = WindowId(parameters) ?? throw new NativeFailure("INVALID_ARGUMENT", "Release through the original window"); + var task = String(parameters, "taskId"); + var recipient = String(parameters, "appHandle"); + var before = Win32.GetForegroundWindow(); + var dispatched = request.Method == "sendKeyEvent" + ? Input.ReleaseKey(state.Connection, task, recipient, window, String(parameters, "key"), context) + : Input.ReleaseButton(state.Connection, task, recipient, window, String(parameters, "mouseButton"), context); + return ActionResult(before, dispatched); + } DesktopSession.RequireInteractive(); if (request.Method == "listApps") return await DesktopWindows.ListApps(context); if (request.Method == "findApps") @@ -97,6 +126,8 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA } var app = state.App(String(parameters, "appHandle")); var foreground = Win32.GetForegroundWindow(); + if (request.Method is "sendKeyEvent" or "toggleMouse" or "pressKey" or "typeText" or "paste" or "mouseMove" or "scroll" or "drag" or "click") + inputs.RequireOwner(state.Connection, OptionalString(parameters, "taskId"), app.Handle, WindowId(parameters) ?? 0); switch (request.Method) { case "launchApp": @@ -143,7 +174,8 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA case "sendKeyEvent": { var target = Selected(app, parameters, context); - var dispatched = Input.KeyEvent(app, target, String(parameters, "key"), String(parameters, "direction"), context); + await sta.Invoke(hooks.Start, cancellation); + var dispatched = Input.KeyDown(state.Connection, String(parameters, "taskId"), app, target, String(parameters, "key"), context); return ActionResult(foreground, dispatched); } case "paste": @@ -174,8 +206,9 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA case "toggleMouse": { var target = Selected(app, parameters, context); - Input.ToggleMouse(app, target, String(parameters, "mouseButton"), String(parameters, "direction"), context); - return ActionResult(foreground); + await sta.Invoke(hooks.Start, cancellation); + var dispatched = Input.ButtonDown(state.Connection, String(parameters, "taskId"), app, target, String(parameters, "mouseButton"), context); + return ActionResult(foreground, dispatched); } case "scroll": { @@ -279,9 +312,18 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA finally { queue.Release(); } } - public ValueTask DisposeAsync() + internal async Task ReleaseConnection(ClientState state, int graceMs) { + if (!inputs.HasConnection(state.Connection)) return; + using var deadline = new CancellationTokenSource(graceMs); + await queue.WaitAsync(deadline.Token); + try { inputs.Release(state.Connection, null, deadline.Token, graceMs); } + finally { queue.Release(); } + } + + public async ValueTask DisposeAsync() + { + await sta.Invoke(hooks.Dispose, CancellationToken.None); queue.Dispose(); - return default; } } diff --git a/packages/experimental/cua-windows/native/entry/Dispatchers.cs b/packages/experimental/cua-windows/native/entry/Dispatchers.cs index 4fec3bd8a0..406420cd9a 100644 --- a/packages/experimental/cua-windows/native/entry/Dispatchers.cs +++ b/packages/experimental/cua-windows/native/entry/Dispatchers.cs @@ -157,12 +157,13 @@ internal sealed class StaDispatcher : IAsyncDisposable } internal sealed class RequestContext(NativeConfig config, CancellationToken cancellation, MtaDispatcher mta, StaDispatcher sta, - Action reportFailure) + Action reportFailure, HeldInputs heldInputs) { internal NativeConfig Config { get; } = config; internal CancellationToken Cancellation { get; } = cancellation; internal MtaDispatcher Mta { get; } = mta; internal StaDispatcher Sta { get; } = sta; + internal HeldInputs HeldInputs { get; } = heldInputs; internal void Check() => Cancellation.ThrowIfCancellationRequested(); internal T Ax(Func call) diff --git a/packages/experimental/cua-windows/native/entry/HeldInputs.cs b/packages/experimental/cua-windows/native/entry/HeldInputs.cs new file mode 100644 index 0000000000..55a133ac05 --- /dev/null +++ b/packages/experimental/cua-windows/native/entry/HeldInputs.cs @@ -0,0 +1,253 @@ +// The shared desktop executor serializes dispatch. Hooks arbitrate external input in the Windows input stream. +using System.Globalization; +using System.Runtime.InteropServices; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal sealed class HeldInputs(Func isDown, Action send, Action requireInteractive) +{ + internal readonly record struct Target(string AppHandle, nint Window, int ProcessId, long ProcessStarted); + private sealed record Press(Guid Connection, string Task, Target Target, ushort Control, string Name, Win32.Input Up) + { + internal bool Confirmed { get; set; } + internal object Describe() => new + { + kind = Up.Type == 1 ? "key" : "mouse", key = Up.Type == 1 ? Name : null, + button = Up.Type == 0 ? Name : null, appHandle = Target.AppHandle, + windowId = Target.Window.ToString(CultureInfo.InvariantCulture), mode = "system", + }; + } + + private sealed record Dispatch(Press Press, nuint Tag, TaskCompletionSource Completion); + + private readonly object gate = new(); + private readonly List pressed = []; + private readonly nuint prefix = unchecked((nuint)Random.Shared.NextInt64(1, int.MaxValue)) << 32; + private uint sequence; + private Dispatch? pending; + + internal static ushort CanonicalControl(ushort key) => key switch + { + 0xA0 or 0xA1 => 0x10, // Shift + 0xA2 or 0xA3 => 0x11, // Control + 0xA4 or 0xA5 => 0x12, // Alt + _ => key, + }; + + // An accepted external event supersedes an owned hold on the same global Windows input. + internal nint Observe(ushort control, nuint tag, Func next) + { + Dispatch? dispatch; + lock (gate) + { + dispatch = pending?.Tag == tag ? pending : null; + if (dispatch is not null && !pressed.Contains(dispatch.Press)) + { + dispatch.Completion.TrySetResult(false); + return 1; + } + // A delayed synthetic event without an admitted dispatch must not reach the desktop. + if (dispatch is null && tag >> 32 == prefix >> 32) return 1; + } + var outcome = next(); + lock (gate) + { + if (dispatch is not null) dispatch.Completion.TrySetResult(outcome == 0); + else if (outcome == 0) pressed.RemoveAll(press => press.Control == control); + } + return outcome; + } + + internal void RequireOwner(Guid connection, string? task, string app, nint window) + { + lock (gate) + { + if (pressed.Exists(press => !press.Confirmed)) + throw new NativeFailure("INPUT_DISPATCH_UNCONFIRMED", "Release unconfirmed held input before sending more desktop input"); + if (pressed.Any(press => press.Connection != connection + || (task is not null && press.Task != task) + || press.Target.AppHandle != app || press.Target.Window != window)) + throw new NativeFailure("INPUT_BUSY", "Another task or window owns held desktop input; release it before sending input to this window"); + } + } + + internal void RequireAvailable(ushort control) + { + lock (gate) + if (pressed.Any(press => press.Control == control) || isDown(control)) + throw new NativeFailure("INPUT_BUSY", "This key or button is already held; release it before a complete action uses it"); + } + + internal bool Down(Guid connection, string task, Target target, ushort control, string name, Win32.Input down, + Win32.Input up, CancellationToken cancellation, int graceMs) + { + Press press; + lock (gate) + { + cancellation.ThrowIfCancellationRequested(); + var existing = pressed.Find(press => press.Control == control); + if (existing is not null) + { + if (existing.Connection == connection && existing.Task == task && existing.Target == target && existing.Name == name) + return false; + throw new NativeFailure("INPUT_BUSY", "This key or button is already held by another input target"); + } + if (isDown(control)) + throw new NativeFailure("INPUT_BUSY", "This key or button is already down outside this task; ask the user to release it before retrying"); + press = new(connection, task, target, control, name, up); + pressed.Add(press); + } + try + { + if (Post(press, down, graceMs)) + { + lock (gate) press.Confirmed = true; + return true; + } + } + catch (NativeFailure error) when (error.Code == "INPUT_BLOCKED") + { + lock (gate) pressed.Remove(press); + throw; + } + lock (gate) pressed.Remove(press); + throw new NativeFailure("INPUT_BLOCKED", "Windows did not deliver the requested press to its input stream"); + } + + internal bool Up(Guid connection, string task, string app, nint window, string name, bool keyboard, int graceMs) + { + Press? press; + lock (gate) + press = pressed.Find(press => press.Connection == connection && press.Task == task && press.Target.AppHandle == app + && press.Target.Window == window && press.Name == name && (press.Up.Type == 1) == keyboard); + if (press is null) throw new NativeFailure("INPUT_NOT_HELD", "This task did not hold that input on the selected window"); + return Release(press, graceMs); + } + + internal object[] Get(Guid connection, string task) + { + lock (gate) + { + var owned = pressed.Where(press => press.Connection == connection && press.Task == task).ToArray(); + if (owned.Any(press => !press.Confirmed)) + throw new NativeFailure("INPUT_DISPATCH_UNCONFIRMED", "Windows did not confirm which inputs are held"); + return owned.Select(press => press.Describe()).ToArray(); + } + } + + internal bool HasConnection(Guid connection) + { + lock (gate) return pressed.Exists(press => press.Connection == connection); + } + + internal object[] Release(Guid connection, string? task, CancellationToken cancellation, int graceMs) + { + Press[] owned; + lock (gate) owned = pressed.Where(press => press.Connection == connection && (task is null || press.Task == task)).Reverse().ToArray(); + var released = new List(); + var failures = new List(); + foreach (var press in owned) + { + cancellation.ThrowIfCancellationRequested(); + try { if (Release(press, graceMs)) released.Add(press.Describe()); } + catch (NativeFailure error) { failures.Add(error.Message); } + } + if (failures.Count != 0) throw new NativeFailure("INPUT_CLEANUP_FAILED", string.Join("; ", failures)); + return released.ToArray(); + } + + private bool Release(Press press, int graceMs) + { + lock (gate) if (!pressed.Contains(press)) return false; + // SendInput releases the global input at its current destination; never reactivate an old HWND. + requireInteractive(); + var posted = Post(press, press.Up, graceMs); + lock (gate) + { + if (posted) pressed.Remove(press); + else if (pressed.Contains(press)) + throw new NativeFailure("INPUT_BLOCKED", "Windows did not deliver the requested release to its input stream"); + } + return posted; + } + + private bool Post(Press press, Win32.Input input, int graceMs) + { + Dispatch dispatch; + lock (gate) + { + if (!pressed.Contains(press)) return false; + if (pending is not null) throw new NativeFailure("INPUT_BUSY", "Another held input is being dispatched"); + dispatch = new(press, prefix | ++sequence, new(TaskCreationOptions.RunContinuationsAsynchronously)); + pending = dispatch; + } + try + { + if (input.Type == 1) input.Data.Keyboard.Extra = dispatch.Tag; + else input.Data.Mouse.Extra = dispatch.Tag; + send(input); + return dispatch.Completion.Task.WaitAsync(TimeSpan.FromMilliseconds(graceMs)).GetAwaiter().GetResult(); + } + catch (TimeoutException) + { + lock (gate) press.Confirmed = false; + throw new NativeFailure("INPUT_DISPATCH_UNCONFIRMED", "Windows did not confirm the held-input event; inspect the desktop before retrying"); + } + finally + { + lock (gate) pending = null; + } + } + +} + +internal sealed class HeldInputHooks(HeldInputs inputs) : IDisposable +{ + [StructLayout(LayoutKind.Sequential)] + private struct KeyEvent { internal uint Key, Scan, Flags, Time; internal nuint Extra; } + [StructLayout(LayoutKind.Sequential)] + private struct MouseEvent { internal Win32.Point Point; internal uint Data, Flags, Time; internal nuint Extra; } + + private nint keyboard; + private nint mouse; + private readonly Win32.InputHook keyHook = (code, message, value) => + { + if (code < 0) return Win32.CallNextHookEx(0, code, message, value); + var input = Marshal.PtrToStructure(value); + if (input.Key > ushort.MaxValue) return Win32.CallNextHookEx(0, code, message, value); + return inputs.Observe(HeldInputs.CanonicalControl((ushort)input.Key), input.Extra, () => Win32.CallNextHookEx(0, code, message, value)); + }; + private readonly Win32.InputHook mouseHook = (code, message, value) => + { + ushort control = message switch + { + 0x0201 or 0x0202 => 1, // Left down/up + 0x0204 or 0x0205 => 2, // Right down/up + 0x0207 or 0x0208 => 4, // Middle down/up + _ => 0, + }; + if (code < 0 || control == 0) return Win32.CallNextHookEx(0, code, message, value); + var input = Marshal.PtrToStructure(value); + return inputs.Observe(control, input.Extra, () => Win32.CallNextHookEx(0, code, message, value)); + }; + + // Low-level hooks must be installed on a thread that pumps Windows messages. + internal void Start() + { + if (keyboard != 0) return; + var module = Win32.GetModuleHandle(null); + keyboard = Win32.SetWindowsHookEx(13, keyHook, module, 0); + mouse = Win32.SetWindowsHookEx(14, mouseHook, module, 0); + if (keyboard != 0 && mouse != 0) return; + Dispose(); + throw new NativeFailure("INPUT_UNAVAILABLE", "Windows could not observe ownership of held desktop input"); + } + + public void Dispose() + { + if (keyboard != 0) Win32.UnhookWindowsHookEx(keyboard); + if (mouse != 0) Win32.UnhookWindowsHookEx(mouse); + keyboard = mouse = 0; + } +} diff --git a/packages/experimental/cua-windows/native/entry/Input.cs b/packages/experimental/cua-windows/native/entry/Input.cs index 9d186055d5..f213cd3769 100644 --- a/packages/experimental/cua-windows/native/entry/Input.cs +++ b/packages/experimental/cua-windows/native/entry/Input.cs @@ -22,21 +22,31 @@ internal static class Input 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) + internal static void Send(params Win32.Input[] events) => SendSequence(events); + + private static void SendSequence(Win32.Input[] events, Action? partial = null) { - 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"); + var dispatched = Win32.SendInput((uint)events.Length, events, Marshal.SizeOf()); + if (dispatched == events.Length) return; + partial?.Invoke((int)dispatched); + 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 WithModifiers(IEnumerable modifiers, Action action) + private static void WithModifiers(IEnumerable modifiers, RequestContext context, Action action) { var keys = modifiers.Select(KeyChord.NormalizeModifier).Select(Modifier).Distinct().ToArray(); var attempted = new List(); try { - foreach (var key in keys) { attempted.Add(key); Send(Keyboard(key, flags: key == VkLeftWin ? 1u : 0)); } + foreach (var key in keys) + { + context.Check(); + context.HeldInputs.RequireAvailable(key); + Send(Keyboard(key, flags: key == VkLeftWin ? 1u : 0)); + attempted.Add(key); + } action(); } finally { foreach (var key in attempted.AsEnumerable().Reverse()) Release(Keyboard(key, flags: 2u | (key == VkLeftWin ? 1u : 0))); } @@ -83,16 +93,30 @@ internal static class Input return ((ushort)(mapped & 0xFF), false, modifiers.ToArray()); } - internal static bool KeyEvent(AppState app, WindowState window, string name, string direction, RequestContext context) + private static string HoldKeyName(string name) => name.ToLowerInvariant() switch + { + "control" => "ctrl", + "return" => "enter", + "esc" => "escape", + "forwarddelete" => "delete", + "arrowleft" => "left", "arrowright" => "right", "arrowup" => "up", "arrowdown" => "down", + "kp_plus" => "kp_add", "kp_minus" => "kp_subtract", "kp_period" => "kp_decimal", + var key => key, + }; + + internal static bool ReleaseKey(Guid connection, string task, string app, nint window, string name, RequestContext context) + => context.HeldInputs.Up(connection, task, app, window, HoldKeyName(name), true, context.Config.GraceMs); + + internal static bool KeyDown(Guid connection, string task, AppState app, WindowState window, string name, RequestContext context) { Windows.RequireForeground(app, window, context); + name = HoldKeyName(name); var key = ResolveKey(name, includeModifiers: true); if (key.Modifiers.Length != 0) throw new NativeFailure("UNSUPPORTED", "This key requires modifiers in the target keyboard layout; send each modifier and the base key separately"); - var down = direction == "down"; - if (((Win32.GetAsyncKeyState(key.Key) & 0x8000) != 0) == down) return false; - Send(Keyboard(key.Key, flags: (key.Extended ? 1u : 0) | (down ? 0u : 2u))); - return true; + var flags = key.Extended ? 1u : 0; + return context.HeldInputs.Down(connection, task, new(app.Handle, window.Id, window.ProcessId, window.ProcessStarted), + key.Key, name, Keyboard(key.Key, flags: flags), Keyboard(key.Key, flags: flags | 2), context.Cancellation, context.Config.GraceMs); } internal static void Press(AppState app, WindowState window, string key, string[] modifiers, RequestContext context) @@ -100,12 +124,13 @@ internal static class Input Windows.RequireForeground(app, window, context); var held = KeyChord.ModifiersForPress(key, modifiers); var resolved = ResolveKey(key); - WithModifiers(held.Concat(resolved.Modifiers), () => + WithModifiers(held.Concat(resolved.Modifiers), context, () => { Windows.RequireForeground(app, window, context); + context.HeldInputs.RequireAvailable(resolved.Key); 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; } + SendSequence([Keyboard(resolved.Key, flags: flags), Keyboard(resolved.Key, flags: flags | 2)], + accepted => { if (accepted == 1) Release(Keyboard(resolved.Key, flags: flags | 2)); }); }); } @@ -123,8 +148,8 @@ internal static class Input } else { - try { Send(Keyboard(0, character, 4), Keyboard(0, character, 6)); } - catch { Release(Keyboard(0, character, 6)); throw; } + SendSequence([Keyboard(0, character, 4), Keyboard(0, character, 6)], + accepted => { if (accepted == 1) Release(Keyboard(0, character, 6)); }); } if (context.Config.TextEventIntervalMs > 0) await Task.Delay(TimeSpan.FromMilliseconds(context.Config.TextEventIntervalMs * 2), context.Cancellation); @@ -140,9 +165,9 @@ internal static class Input (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 + private static (ushort Control, uint Down, uint Up) Button(string button) => button switch { - "left" => (0x0002, 0x0004), "right" => (0x0008, 0x0010), "middle" => (0x0020, 0x0040), + "left" => (1, 0x0002, 0x0004), "right" => (2, 0x0008, 0x0010), "middle" => (4, 0x0020, 0x0040), _ => throw new NativeFailure("INVALID_ARGUMENT", "Unknown mouse button"), }; @@ -162,16 +187,16 @@ internal static class Input return new { dispatched = true, hoverRoute = "system-pointer", systemPointerMoved = before.X != point.X || before.Y != point.Y }; } - internal static void ToggleMouse(AppState app, WindowState window, string button, string direction, RequestContext context) + internal static bool ReleaseButton(Guid connection, string task, string app, nint window, string button, RequestContext context) + => context.HeldInputs.Up(connection, task, app, window, button, false, context.Config.GraceMs); + + internal static bool ButtonDown(Guid connection, string task, AppState app, WindowState window, string button, RequestContext context) { var flags = Button(button); - if (direction == "down") - { - if (!Win32.GetCursorPos(out var point)) throw new NativeFailure("INPUT_UNAVAILABLE", "The current pointer position is unavailable"); - Hit(app, window, point, context); - } - else Windows.RequireForeground(app, window, context); - Send(Mouse(direction == "down" ? flags.Down : flags.Up)); + if (!Win32.GetCursorPos(out var point)) throw new NativeFailure("INPUT_UNAVAILABLE", "The current pointer position is unavailable"); + Hit(app, window, point, context); + return context.HeldInputs.Down(connection, task, new(app.Handle, window.Id, window.ProcessId, window.ProcessStarted), + flags.Control, button, Mouse(flags.Down), Mouse(flags.Up), context.Cancellation, context.Config.GraceMs); } internal static void Click(AppState app, WindowState window, double x, double y, string button, int count, string[] modifiers, RequestContext context) @@ -180,14 +205,15 @@ internal static class Input var geometry = window.RequireObservation(app, context); var point = WindowState.Point(geometry, x, y); var flags = Button(button); + context.HeldInputs.RequireAvailable(flags.Control); Hit(app, window, point, context); - WithModifiers(modifiers, () => + WithModifiers(modifiers, context, () => { 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; } + SendSequence(events.ToArray(), accepted => { if (accepted >= 2 && accepted % 2 == 0) Release(Mouse(flags.Up)); }); }); } @@ -197,20 +223,27 @@ internal static class Input var point = WindowState.Point(window.RequireObservation(app, context), x, y); var flags = Button(button); var keys = modifiers.Select(KeyChord.NormalizeModifier).Select(Modifier).Distinct().ToArray(); + context.HeldInputs.RequireAvailable(flags.Control); Hit(app, window, point, context); var attempted = new List(); var buttonAttempted = false; try { - foreach (var key in keys) { attempted.Add(key); Send(Keyboard(key, flags: key == VkLeftWin ? 1u : 0)); } + foreach (var key in keys) + { + context.Check(); + context.HeldInputs.RequireAvailable(key); + Send(Keyboard(key, flags: key == VkLeftWin ? 1u : 0)); + attempted.Add(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)); + buttonAttempted = true; await Task.Delay(holdMs, context.Cancellation); Windows.RequireForeground(app, window, context); Send(Mouse(flags.Up)); @@ -251,12 +284,18 @@ internal static class Input var buttonAttempted = false; try { - foreach (var key in keys) { attempted.Add(key); Send(Keyboard(key, flags: key == VkLeftWin ? 1u : 0)); } + foreach (var key in keys) + { + context.Check(); + context.HeldInputs.RequireAvailable(key); + Send(Keyboard(key, flags: key == VkLeftWin ? 1u : 0)); + attempted.Add(key); + } geometry = window.RequireObservation(app, context); from = WindowState.Point(geometry, fromX, fromY); Hit(app, window, from, context); - buttonAttempted = true; Send(Move(from), Mouse(flags.Down)); + buttonAttempted = true; for (var step = 1; step <= steps; step++) { await Task.Delay(TimeSpan.FromMilliseconds(durationMs / (double)steps), context.Cancellation); diff --git a/packages/experimental/cua-windows/native/entry/NativeServer.cs b/packages/experimental/cua-windows/native/entry/NativeServer.cs index 9f973a8840..2b4941c723 100644 --- a/packages/experimental/cua-windows/native/entry/NativeServer.cs +++ b/packages/experimental/cua-windows/native/entry/NativeServer.cs @@ -97,6 +97,7 @@ internal static class NativeServer { var state = new ClientState(); Task? active = null; + TaskCompletionSource? replying = null; CancellationTokenSource? cancellation = null; string? latestRequestId = null; var closeRequested = false; @@ -136,7 +137,7 @@ internal static class NativeServer continue; } var request = NativeRequest.Parse(value); - if (active is { IsCompleted: false }) + if (active is { IsCompleted: false } && replying?.Task.IsCompleted != true) { await Write(pipe, writer, Failure(request.Id, "NATIVE_BUSY", "The previous native operation has not stopped; do not send further input until it finishes"), config.MaxResponseBytes, config.GraceMs, lifetime.Token); @@ -147,7 +148,8 @@ internal static class NativeServer 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); + replying = new(TaskCreationOptions.RunContinuationsAsynchronously); + active = Dispatch(request, state, executor, config, pipe, writer, replying, cancellation.Token, lifetime.Token); } } catch (Exception error) @@ -164,7 +166,11 @@ internal static class NativeServer } catch (NativeFailure error) when (error.Code == "NATIVE_CLEANUP") { throw; } catch (Exception error) { Report("NATIVE_CONNECTION", error); } - finally { cancellation?.Dispose(); } + finally + { + cancellation?.Dispose(); + await executor.ReleaseConnection(state, cleanupTimeoutMs); + } state.Clear(); if (closeRequested) await Write(pipe, writer, new { type = "closed" }, 8192, cleanupTimeoutMs, CancellationToken.None); @@ -173,16 +179,16 @@ internal static class NativeServer } private static async Task Dispatch(NativeRequest request, ClientState state, DesktopExecutor executor, NativeConfig config, - Stream pipe, SemaphoreSlim writer, CancellationToken cancellation, CancellationToken connection) + Stream pipe, SemaphoreSlim writer, TaskCompletionSource replying, CancellationToken cancellation, CancellationToken connection) { var operationStop = CancellationTokenSource.CreateLinkedTokenSource(cancellation); var failure = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); // A synchronous native call must not block the pipe reader or its timeout response. var operation = Task.Run(() => executor.Execute(request, state, config, operationStop.Token, error => { failure.TrySetResult(error); })); + object response; try { - object response; try { response = new { id = request.Id, result = await WatchOperation(operation, failure.Task, operationStop.Token, config.GraceMs) }; } catch (OperationCanceledException) { response = Failure(request.Id, "NATIVE_CANCELLED", "Native operation cancelled; observe before deciding on further input"); } catch (NativeFailure error) @@ -195,9 +201,6 @@ internal static class NativeServer 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"); } - 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); } finally { @@ -217,6 +220,10 @@ internal static class NativeServer }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } } + replying.SetResult(); + 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 } }; diff --git a/packages/experimental/cua-windows/native/entry/Win32.cs b/packages/experimental/cua-windows/native/entry/Win32.cs index 65ce6f8b58..d19f713cf3 100644 --- a/packages/experimental/cua-windows/native/entry/Win32.cs +++ b/packages/experimental/cua-windows/native/entry/Win32.cs @@ -62,6 +62,11 @@ internal static class Win32 [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); + internal delegate nint InputHook(int code, nuint message, nint value); + [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal static extern nint GetModuleHandle(string? module); + [DllImport("user32.dll", CharSet = CharSet.Unicode)] internal static extern nint SetWindowsHookEx(int kind, InputHook hook, nint module, uint thread); + [DllImport("user32.dll")] internal static extern nint CallNextHookEx(nint hook, int code, nuint message, nint value); + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool UnhookWindowsHookEx(nint hook); [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); diff --git a/packages/experimental/cua-windows/native/generate-protocol.ts b/packages/experimental/cua-windows/native/generate-protocol.ts index 3a23f8140f..9183594c68 100644 --- a/packages/experimental/cua-windows/native/generate-protocol.ts +++ b/packages/experimental/cua-windows/native/generate-protocol.ts @@ -1,9 +1,16 @@ /** 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' +import { z } from 'zod' const path = new URL('protocol.schema.json', import.meta.url) -const content = nativeProtocol().json +const owner = z.object({ taskId: z.string().min(1) }).strict() +const content = nativeProtocol({ + sendKeyEvent: owner, + toggleMouse: owner, +}, ['getHeldInputs', 'releaseHeldInputs'].map(method => z.object({ + method: z.literal(method), params: owner, +}).strict())).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/protocol.schema.json b/packages/experimental/cua-windows/native/protocol.schema.json index a7e177c875..485ba9c5ed 100644 --- a/packages/experimental/cua-windows/native/protocol.schema.json +++ b/packages/experimental/cua-windows/native/protocol.schema.json @@ -517,13 +517,18 @@ "down", "up" ] + }, + "taskId": { + "type": "string", + "minLength": 1 } }, "required": [ "appHandle", "windowId", "mouseButton", - "direction" + "direction", + "taskId" ], "additionalProperties": false } @@ -1118,12 +1123,17 @@ "down", "up" ] + }, + "taskId": { + "type": "string", + "minLength": 1 } }, "required": [ "appHandle", "key", - "direction" + "direction", + "taskId" ], "additionalProperties": false } @@ -1484,6 +1494,68 @@ "params" ], "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "getHeldInputs" + }, + "params": { + "type": "object", + "properties": { + "taskId": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "taskId" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "releaseHeldInputs" + }, + "params": { + "type": "object", + "properties": { + "taskId": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "taskId" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false } ] } diff --git a/packages/experimental/cua-windows/native/tests/HeldInputChecks.cs b/packages/experimental/cua-windows/native/tests/HeldInputChecks.cs new file mode 100644 index 0000000000..b29bd1e769 --- /dev/null +++ b/packages/experimental/cua-windows/native/tests/HeldInputChecks.cs @@ -0,0 +1,87 @@ +// The fake input stream drives the same admission and hook callbacks as SendInput. +using System.Text.Json; +using DeepSeek.Cua.Protocol; +using DeepSeek.Cua.Windows; + +internal static class HeldInputChecks +{ + internal static void Run(Action check, Action refuses) + { + var a = Guid.NewGuid(); + var b = Guid.NewGuid(); + var target = new HeldInputs.Target("app", 72, 122, 100); + var physical = new HashSet(); + var events = new List(); + var blocked = false; + var overlap = false; + var interactive = true; + HeldInputs inputs = null!; + inputs = new(physical.Contains, input => + { + if (blocked) throw new NativeFailure("INPUT_BLOCKED", "SendInput returned zero"); + var isKey = input.Type == 1; + var control = isKey ? input.Data.Keyboard.Key : (ushort)1; + var tag = isKey ? input.Data.Keyboard.Extra : input.Data.Mouse.Extra; + var up = isKey ? (input.Data.Keyboard.Flags & 2) != 0 : input.Data.Mouse.Flags == 4; + if (overlap) inputs.Observe(control, 0, () => 0); + inputs.Observe(control, tag, () => { events.Add($"{control}:{(up ? "up" : "down")}"); return 0; }); + }, () => + { + if (!interactive) throw new NativeFailure("SESSION_LOCKED", "The interactive desktop is unavailable"); + }); + + bool Key(Guid connection, string task, ushort key, string name, CancellationToken cancellation = default) + => inputs.Down(connection, task, target, key, name, + new() { Type = 1, Data = new() { Keyboard = new() { Key = key } } }, + new() { Type = 1, Data = new() { Keyboard = new() { Key = key, Flags = 2 } } }, + cancellation, 100); + + physical.Add(16); + refuses(() => Key(a, "task", 16, "shift"), "INPUT_BUSY"); + check(events.Count == 0, "Physical input cannot become an owned hold"); + physical.Clear(); + blocked = true; + refuses(() => Key(a, "task", 16, "shift"), "INPUT_BLOCKED"); + check(inputs.Get(a, "task").Length == 0, "A refused down does not cause an up"); + blocked = false; + check(Key(a, "task", 16, "shift"), "Record the accepted keyboard down"); + check(inputs.Down(a, "task", target, 1, "left", + new() { Data = new() { Mouse = new() { Flags = 2 } } }, + new() { Data = new() { Mouse = new() { Flags = 4 } } }, default, 100), "Record the accepted mouse down"); + check(Key(a, "task", 87, "w") && !Key(a, "task", 87, "w"), "A repeated key does not duplicate a hold"); + refuses(() => inputs.RequireOwner(b, "task", "app", 72), "INPUT_BUSY"); + refuses(() => inputs.RequireOwner(a, "other", "app", 72), "INPUT_BUSY"); + refuses(() => inputs.RequireAvailable(1), "INPUT_BUSY"); + refuses(() => inputs.Up(a, "other", "app", 72, "w", true, 100), "INPUT_NOT_HELD"); + refuses(() => inputs.Up(a, "task", "app", 73, "w", true, 100), "INPUT_NOT_HELD"); + check(inputs.Release(b, null, default, 100).Length == 0, "Another connection releases nothing"); + check(inputs.Get(a, "other").Length == 0 && inputs.Get(a, "task").Length == 3, "State query is task-scoped"); + var described = JsonSerializer.SerializeToElement(inputs.Get(a, "task"), WireJson.Options); + check(described[0].GetProperty("windowId").GetString() == "72" && described[0].GetProperty("mode").GetString() == "system", + "Keyboard reminders identify the window and actual desktop mode"); + check(inputs.Up(a, "task", "app", 72, "shift", true, 100) && Key(a, "task", 16, "shift"), + "Explicit up and repress update the dispatch order"); + check(inputs.Release(a, "task", default, 100).Length == 3 + && events.TakeLast(3).SequenceEqual(["16:up", "87:up", "1:up"]), "Release in mixed reverse order, including repress"); + check(inputs.Release(a, null, default, 100).Length == 0, "Duplicate connection cleanup sends no up"); + using (var cancelled = new CancellationTokenSource()) + { + cancelled.Cancel(); + try { Key(a, "task", 87, "w", cancelled.Token); throw new Exception("Expected cancelled down"); } + catch (OperationCanceledException) { check(inputs.Get(a, "task").Length == 0, "Cancelled down never dispatches"); } + } + Key(a, "task", 87, "w"); + interactive = false; + refuses(() => inputs.Release(a, null, default, 100), "INPUT_CLEANUP_FAILED"); + check(inputs.Get(a, "task").Length == 1, "A locked desktop leaves the failed release recorded"); + interactive = true; + blocked = true; + refuses(() => inputs.Release(a, null, default, 100), "INPUT_CLEANUP_FAILED"); + check(inputs.Get(a, "task").Length == 1, "A refused release stays recorded for disconnect fallback"); + blocked = false; + var count = events.Count; + overlap = true; + check(inputs.Release(a, null, default, 100).Length == 0 && inputs.Get(a, "task").Length == 0 && events.Count == count, + "An external event at dispatch time wins and the owned event cannot lift user input"); + } +} diff --git a/packages/experimental/cua-windows/native/tests/Program.cs b/packages/experimental/cua-windows/native/tests/Program.cs index d717dc3937..68c0ea57bb 100644 --- a/packages/experimental/cua-windows/native/tests/Program.cs +++ b/packages/experimental/cua-windows/native/tests/Program.cs @@ -66,7 +66,7 @@ foreach (var direction in new[] { "down", "up" }) { var toggle = NativeRequest.Parse(WireJson.Parse(System.Text.Json.JsonSerializer.Serialize(new { - id = "mouse", method = "toggleMouse", @params = new { appHandle = "app", windowId = "1", mouseButton, direction }, + id = "mouse", method = "toggleMouse", @params = new { appHandle = "app", windowId = "1", taskId = "task", mouseButton, direction }, }))); Check(toggle.Params.GetProperty("mouseButton").GetString() == mouseButton && toggle.Params.GetProperty("direction").GetString() == direction, @@ -74,15 +74,18 @@ foreach (var direction in new[] { "down", "up" }) } foreach (var invalid in new[] { - """{"appHandle":"app","windowId":"1","mouseButton":"left"}""", - """{"appHandle":"app","windowId":"1","direction":"down"}""", - """{"appHandle":"app","mouseButton":"left","direction":"down"}""", - """{"appHandle":"app","windowId":"1","mouseButton":"back","direction":"down"}""", - """{"appHandle":"app","windowId":"1","mouseButton":"left","direction":"press"}""", - """{"appHandle":"app","windowId":"1","mouseButton":"left","direction":"down","x":1,"y":2}""", + """{"appHandle":"app","windowId":"1","mouseButton":"left","direction":"down"}""", + """{"appHandle":"app","taskId":"task","windowId":"1","mouseButton":"left"}""", + """{"appHandle":"app","taskId":"task","windowId":"1","direction":"down"}""", + """{"appHandle":"app","taskId":"task","mouseButton":"left","direction":"down"}""", + """{"appHandle":"app","taskId":"task","windowId":"1","mouseButton":"back","direction":"down"}""", + """{"appHandle":"app","taskId":"task","windowId":"1","mouseButton":"left","direction":"press"}""", + """{"appHandle":"app","taskId":"task","windowId":"1","mouseButton":"left","direction":"down","x":1,"y":2}""", }) Refuses(() => NativeRequest.Parse(WireJson.Parse("{\"id\":\"mouse\",\"method\":\"toggleMouse\",\"params\":" + invalid + "}")), "INVALID_ARGUMENT"); +HeldInputChecks.Run(Check, Refuses); + var actionSchema = NativeRequest.Parse(WireJson.Parse("""{"id":"schema","method":"getActionSchema","params":{"action":"Invoke.Invoke"}}""")); Check(actionSchema.Params.EnumerateObject().Select(item => item.Name).SequenceEqual(["action"]), "Action schema requests carry only the exact action name"); diff --git a/packages/experimental/cua-windows/native/tests/Protocol.Tests.csproj b/packages/experimental/cua-windows/native/tests/Protocol.Tests.csproj index 7d1a1ef893..f919e04987 100644 --- a/packages/experimental/cua-windows/native/tests/Protocol.Tests.csproj +++ b/packages/experimental/cua-windows/native/tests/Protocol.Tests.csproj @@ -11,6 +11,8 @@ + + diff --git a/packages/experimental/cua-windows/src/guidance.ts b/packages/experimental/cua-windows/src/guidance.ts index ab0769c163..a3e6b7cab9 100644 --- a/packages/experimental/cua-windows/src/guidance.ts +++ b/packages/experimental/cua-windows/src/guidance.ts @@ -2,7 +2,7 @@ import { COMMON_GUIDANCE } from '@deepseek-ai/dsh-cua/guidance' /** Windows operation levels, application selectors, and input availability. */ -export const PLATFORM_GUIDANCE = 'Windows: accessibility tree operations are available only at window level. Simulated mouse and keyboard input are available at window level. Supported modifiers: ctrl, alt, shift, win. control is an alias for ctrl. Held-input reminders and unified failure/cancellation cleanup are not yet implemented on Windows. Explicitly release every held key and mouse button with up.' +export const PLATFORM_GUIDANCE = 'Windows: accessibility tree operations are available only at window level. Simulated mouse and keyboard input are available at window level. Supported modifiers: ctrl, alt, shift, win. control is an alias for ctrl. Key and mouse holds use desktop input. Keep the target in front while holding inputs. Release through the same window. After focus changes, an up releases desktop input without restoring focus; the original window may not receive that event.' const methodDetails = new Map([ ['cua.getApp', 'Windows accepts an exact AUMID returned by listApps or an existing absolute .exe path, including an executable absent from listApps. Display names and PIDs are not alternative selectors. Selection uses the existing application consent flow and starts the application only when it is not running.'], diff --git a/packages/experimental/cua-windows/src/index.ts b/packages/experimental/cua-windows/src/index.ts index a45cb2a8b2..292fc07b38 100644 --- a/packages/experimental/cua-windows/src/index.ts +++ b/packages/experimental/cua-windows/src/index.ts @@ -89,6 +89,7 @@ export async function apply(ctx: Context, config: Config): Promise { ctx.effect(() => () => runtime.dispose(), 'cua-windows.native-runtime') installCua(ctx, config, { helperPath, createChannel: (_owner, native) => runtime.connect(native), getGuidance: () => GUIDANCE, capabilities: CAPABILITIES, + heldInputState: true, permissionParameters: (_method, permission) => ({ permission }), }) } diff --git a/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts b/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts index 25a37bb8e2..a84b329811 100644 --- a/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts +++ b/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts @@ -15,6 +15,7 @@ const Counts = z.object({ left: z.number().int(), right: z.number().int(), middl const FixtureState = z.object({ window: z.string(), foreground: z.string(), cursor: z.object({ x: z.number().int(), y: z.number().int() }), + inputEvents: z.array(z.string()), wDown: z.boolean(), under: z.string(), buttons: z.string(), clicks: z.number().int(), downs: Counts, ups: Counts, }) const Initial = z.object({ pid: z.number().int(), state: FixtureState }) @@ -65,7 +66,7 @@ async function releaseAndClose(fixture: Fixture): Promise { } it.skipIf(process.platform !== 'win32' || !helperPath || !fixturePath)( - 'toggles mouse buttons without movement, observation, or implicit release', + 'holds Windows keys and buttons through the helper and releases owned input in dispatch order', async ({ onTestFinished, signal }) => { const fixture = fixtureProcess(fixturePath!) const ctx = new Context() @@ -73,7 +74,7 @@ it.skipIf(process.platform !== 'win32' || !helperPath || !fixturePath)( onTestFinished(async () => { const errors: unknown[] = [] for (const cleanup of [ - () => releaseAndClose(fixture), ...cleanups.toReversed(), () => ctx.fiber.dispose(), + ...cleanups.toReversed(), () => releaseAndClose(fixture), () => ctx.fiber.dispose(), ]) { try { await cleanup() } catch (error) { errors.push(error) } } @@ -103,7 +104,7 @@ it.skipIf(process.platform !== 'win32' || !helperPath || !fixturePath)( const windowId = initial.state.window expect(windows.some(window => window.windowId === windowId)).toBe(true) const toggle = async (mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') => - ToggleResult.parse(await native.request('toggleMouse', { appHandle: app.appHandle, windowId, mouseButton, direction }, signal)) + ToggleResult.parse(await native.request('toggleMouse', { appHandle: app.appHandle, windowId, taskId: 'desktop-test', mouseButton, direction }, signal)) const { cursor } = await fixture.command('pointer', FixtureState) for (const mouseButton of ['left', 'right', 'middle'] as const) { @@ -142,4 +143,36 @@ it.skipIf(process.platform !== 'win32' || !helperPath || !fixturePath)( expect(outside.under).not.toBe(outside.window) expect((await toggle('left', 'up')).dispatched).toBe(true) await observed({ buttons: 'None', cursor: outside.cursor, ups: { left: pressed.ups.left + 1 }, clicks: pressed.clicks }) + + const taskId = 'desktop-test' + const target = { appHandle: app.appHandle, windowId, taskId } + const key = (key: string, direction: 'down' | 'up') => native.request('sendKeyEvent', { ...target, key, direction }, signal) + const holds = () => native.request('getHeldInputs', { taskId }, signal) + const released = z.array(z.object({ kind: z.string(), key: z.string().nullable(), button: z.string().nullable(), mode: z.literal('system') })) + await fixture.command('pointer', FixtureState) + const offset = (await inspect()).inputEvents.length + await key('shift', 'down') + await toggle('left', 'down') + await key('w', 'down') + expect(released.parse(await holds()).map(input => input.key ?? input.button)).toEqual(['shift', 'left', 'w']) + + const other = new NativeClient(ctx, { ...Config({}), helperPath: helperPath!, cwd: process.cwd() }, + (_owner, config) => nativeRuntime.connect(config)) + cleanups.push(() => other.dispose()) + const otherApp = App.parse(await other.request('getApp', { selector: fixturePath! }, signal)) + expect(await other.request('getHeldInputs', { taskId }, signal)).toEqual([]) + await expect(other.request('sendKeyEvent', { ...target, appHandle: otherApp.appHandle, key: 'w', direction: 'up' }, signal)) + .rejects.toMatchObject({ code: 'INPUT_NOT_HELD' }) + const release = await native.requestCleanup('releaseHeldInputs', { taskId }) + expect(released.parse(release).map(input => input.key ?? input.button)).toEqual(['w', 'left', 'shift']) + await expect.poll(async () => (await inspect()).inputEvents.slice(offset)).toEqual( + ['ShiftKey:down', 'Left:down', 'W:down', 'W:up', 'Left:up', 'ShiftKey:up']) + + await key('w', 'down') + await observed({ wDown: true }) + const switched = await fixture.command('sibling', FixtureState) + expect(switched.foreground).toBe(switched.window) + await native.dispose() + await observed({ foreground: switched.window, wDown: false }) + }, 120_000) diff --git a/packages/experimental/cua-windows/tests/loader-composition.spec.ts b/packages/experimental/cua-windows/tests/loader-composition.spec.ts index e90acbbf49..d5a4dee031 100644 --- a/packages/experimental/cua-windows/tests/loader-composition.spec.ts +++ b/packages/experimental/cua-windows/tests/loader-composition.spec.ts @@ -31,10 +31,11 @@ it.skipIf(process.platform !== 'win32')('loads the Windows provider and rejects const prompt = await ctx.systemPrompt.assemble({ scope: agent }) expect(prompt.sections.find(section => section.name === 'computer-use:dsh-cua')?.text).toContain('Windows:') expect(prompt.sections.find(section => section.name === 'computer-use:dsh-cua')?.text).not.toContain('useSystemPointer') + expect(prompt.sections.find(section => section.name === 'computer-use:dsh-cua')?.text).toContain('a system reminder lists any remaining keys and mouse buttons') const toggleMouse = prompt.sections.find(section => section.name === 'computer-use:dsh-cua')?.text .split('\n').find(line => line.startsWith('- toggleMouse(')) expect(toggleMouse).toContain("toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult") - expect(toggleMouse).toContain("Release held buttons explicitly with 'up'; the opposite event is not sent automatically.") + expect(toggleMouse).toContain("Send 'up' to release a held button immediately.") expect(toggleMouse).toContain('press or release the specified mouse button at the current pointer position without moving it.') expect(toggleMouse).not.toContain('Not implemented') expect(JSON.stringify(ctx.tools.get('cua', agent)!.parameters)).not.toContain('useSystemPointer') diff --git a/packages/experimental/cua-windows/tests/protocol.spec.ts b/packages/experimental/cua-windows/tests/protocol.spec.ts index 081906f6fd..77e6c022b7 100644 --- a/packages/experimental/cua-windows/tests/protocol.spec.ts +++ b/packages/experimental/cua-windows/tests/protocol.spec.ts @@ -1,12 +1,14 @@ /** 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 { spawnSync } from 'node:child_process' +import { fileURLToPath } from 'node:url' 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('keeps the C# admission schema current with the Windows generator', () => { + const result = spawnSync(process.execPath, ['--import', 'tsx', fileURLToPath(new URL('../native/generate-protocol.ts', import.meta.url)), '--check'], + { encoding: 'utf8' }) + expect(result.status, result.stderr).toBe(0) }) it('preserves Windows physical capture units and observed foreground changes', () => { diff --git a/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts index f3fa7cac21..98103ec88d 100644 --- a/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts @@ -51,9 +51,8 @@ it('uses an absolute fixture without compiling and disposes the Host runtime', a expect(backend.capabilities.methods).toContain('getActionSchema') expect(backend.capabilities.methods).toContain('sendKeyEvent') expect(backend.capabilities.methods).toContain('toggleMouse') - expect(backend.heldInputState).toBeUndefined() - expect(GUIDANCE).toContain('sendKeyEvent and toggleMouse remain held across programs and turns') - expect(GUIDANCE).toContain('Held-input reminders and unified failure/cancellation cleanup are not yet implemented on Windows') + expect(backend.heldInputState).toBe(true) + expect(GUIDANCE).toContain('Key and mouse holds use desktop input.') const channel = { marker: 'native stream' } native.connect.mockReturnValue(channel) const options = { ...config, helperPath: backend.helperPath, cwd: process.cwd() } diff --git a/packages/experimental/cua/src/guidance.ts b/packages/experimental/cua/src/guidance.ts index 05152bd6ce..9de01757e0 100644 --- a/packages/experimental/cua/src/guidance.ts +++ b/packages/experimental/cua/src/guidance.ts @@ -58,12 +58,20 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. -Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. - click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. 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.` +/** Add held-input behavior where the provider supplies native ownership and cleanup. + * @param guidance - Provider instructions including the shared operation catalog. + * @returns Instructions for a provider with held-input state support. + */ +export function withHeldInputGuidance(guidance: string): string { + return guidance.replace('click, drag, and pressKey are convenience operations;', `Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. + +click, drag, and pressKey are convenience operations;`) +} + /** * Describe the system-pointer option for a provider that declares the capability. * @param guidance Provider instructions including the shared operation catalog. diff --git a/packages/experimental/cua/src/held-inputs.ts b/packages/experimental/cua/src/held-inputs.ts index 2eb45af25e..ba7164945c 100644 --- a/packages/experimental/cua/src/held-inputs.ts +++ b/packages/experimental/cua/src/held-inputs.ts @@ -8,13 +8,13 @@ import { NativeError, type NativeClient } from './native-client.ts' const target = { appHandle: z.string(), mode: z.enum(['application', 'window', 'system']) } const heldInputs = z.array(z.discriminatedUnion('kind', [ - z.object({ ...target, kind: z.literal('key'), key: z.string() }), + z.object({ ...target, kind: z.literal('key'), key: z.string(), windowId: z.string().optional() }), z.object({ ...target, kind: z.literal('mouse'), button: z.enum(['left', 'right', 'middle']), windowId: z.string() }), ])) function renderInputs(inputs: z.infer, state: 'held' | 'released'): string { const rows = inputs.map(input => input.kind === 'key' - ? `- Key ${JSON.stringify(input.key)}, appHandle ${JSON.stringify(input.appHandle)} (${input.mode} input).` + ? `- Key ${JSON.stringify(input.key)}, appHandle ${JSON.stringify(input.appHandle)}${input.windowId === undefined ? '' : `, windowId ${JSON.stringify(input.windowId)}`} (${input.mode} input).` : `- Mouse ${input.button}, appHandle ${JSON.stringify(input.appHandle)}, windowId ${JSON.stringify(input.windowId)} (${input.mode} input).`) const title = state === 'held' ? 'CUA inputs are still held:' : 'CUA inputs were released during cleanup:' return ['', title, ...rows, @@ -63,7 +63,7 @@ class InputOwner { if (!this.client) return [] if (!canRequest) throw new NativeError('INPUT_CLEANUP_UNCONFIRMED', 'Native connection closed before held-input cleanup was confirmed. Inspect the desktop manually before starting a new task') const released = heldInputs.parse(await this.client.requestCleanup('releaseHeldInputs', { taskId: this.agent.id })) - if (this.notifySessionOnRelease && released.length > 0) this.released(released) + if (this.notifySessionOnRelease) this.released(released) return released } catch (error) { this.failed(error) @@ -108,6 +108,10 @@ export class CuaHeldInputs { emitAgentEvent(this.ctx, agent, 'agent/error', { turn: this.ctx.agents.turnBoundaryOf(agent.session).lastTurn, step: 0, error }) }, (inputs) => { try { + for (const message of [...agent.inbox.nextStep, ...agent.inbox.nextTurn]) { + if (message.source.kind === 'cua-held-inputs') agent.inbox.remove(message.id) + } + if (inputs.length === 0) return agent.inject(createUserMessage({ content: [{ type: 'text', text: renderInputs(inputs, 'released') }], source: { kind: 'cua-inputs-released', form: 'notice', summary: 'CUA inputs released' }, @@ -147,30 +151,34 @@ export class CuaHeldInputs { const signal = execution.signal const abort = (): void => { this.stop(agent) } signal.addEventListener('abort', abort, { once: true }) + const releaseAfter = async (message: string): Promise => { + signal.removeEventListener('abort', abort) + try { await this.release(agent) } + catch (error) { throw new NativeError('INPUT_CLEANUP_UNCONFIRMED', + `${message}. Held-input cleanup failed: ${String(error)}`, { cause: error }) } + } try { - const result = await next() + const result = await next().catch(async (error: unknown) => { + await releaseAfter(`Program failed: ${String(error)}`) + throw error + }) if (result.isError || signal.aborted) { - signal.removeEventListener('abort', abort) - try { await this.release(agent) } - catch (error) { throw new NativeError('INPUT_CLEANUP_UNCONFIRMED', - `${result.isError ? result.error.message : 'Program cancelled'}. Held-input cleanup failed: ${String(error)}`, { cause: error }) } + await releaseAfter(result.isError ? result.error.message : 'Program cancelled') } else if (execution.parent === undefined) { const owner = this.owners.get(agent) const inTurn = ctx.agents.turnBoundaryOf(agent.session).openTurnStartSeq !== null - const text = await owner?.reminder(inTurn) + const text = await owner?.reminder(inTurn).catch(async (error: unknown) => { + await releaseAfter(signal.aborted ? 'Program cancelled' : `Held-input query failed: ${String(error)}`) + throw error + }) // oxlint-disable-next-line typescript/no-unnecessary-condition -- Cancellation can arrive while the native state query awaits. - if (signal.aborted) { await this.release(agent); return result } + if (signal.aborted) { await releaseAfter('Program cancelled'); return result } if (text && !owner?.closing) return { ...result, additionalContexts: [...result.additionalContexts ?? [], createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'cua-held-inputs', form: 'notice', summary: 'CUA inputs remain held' } }), ] } } return result - } catch (error) { - signal.removeEventListener('abort', abort) - try { await this.release(agent) } - catch (cleanupError) { throw new NativeError('INPUT_CLEANUP_UNCONFIRMED', `Program failed: ${String(error)}. Held-input cleanup failed: ${String(cleanupError)}`, { cause: error }) } - throw error } finally { signal.removeEventListener('abort', abort) await this.owners.get(agent)?.settled() diff --git a/packages/experimental/cua/src/index.ts b/packages/experimental/cua/src/index.ts index 0df8c40e4b..75ecd0081a 100644 --- a/packages/experimental/cua/src/index.ts +++ b/packages/experimental/cua/src/index.ts @@ -15,7 +15,7 @@ import { z } from 'zod' import { NativeClient, NativeError, type NativeClientConfig, type NativeChannelFactory } from './native-client.ts' import { MouseControl } from './mouse-control.ts' import { CuaHeldInputs } from './held-inputs.ts' -import { withSystemPointerGuidance } from './guidance.ts' +import { withHeldInputGuidance, withSystemPointerGuidance } from './guidance.ts' import { CuaPermissionStore } from './permission-store.ts' import { ApplicationAuthorizationResult, installCuaAccess } from './access.ts' import type { CuaApplicationGrant, CuaApplicationId, CuaSystemPermission } from './access-types.ts' @@ -212,7 +212,8 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) const mouseControl = systemPointer ? new MouseControl(ctx, config.requireSystemPointerApproval) : undefined const requestSchema = systemPointer ? SystemPointerRequest : Request const formatGuidance = (text: string): string => { - const instructions = systemPointer ? withSystemPointerGuidance(text) : text + const inputGuidance = heldInputs ? withHeldInputGuidance(text) : text + const instructions = systemPointer ? withSystemPointerGuidance(inputGuidance) : inputGuidance return `${instructions}\n\nAX read defaults: maxElements=${config.maxElements}, maxDepth=${config.maxDepth}.\n\nMaximum click holdMs: ${config.maxClickHoldMs} ms.` } const guidance = formatGuidance(backend.getGuidance('raw')) diff --git a/packages/experimental/cua/src/types.ts b/packages/experimental/cua/src/types.ts index 47c3f623ba..9976823132 100644 --- a/packages/experimental/cua/src/types.ts +++ b/packages/experimental/cua/src/types.ts @@ -185,10 +185,10 @@ export interface CuaSurface { * Send one key-down or key-up event at the current input focus. * Explicit downs persist across programs and turns; successful programs remind about remaining holds. * MCP client pauses between completed calls do not notify the provider and leave held input unchanged. - * Program failure, cancellation, connection closure and disposal release owned input. Windows support is pending. + * Program failure, cancellation, connection closure and disposal release owned input on supported providers. * Rejects when the provider does not support keyboard input at this scope. * @param key - Platform-defined key name; modifier keys may themselves be targets. - * @param direction - Down establishes a hold; up immediately releases owned input at its saved recipient. + * @param direction - Down establishes a hold; up immediately releases owned input through its original input route. * @returns Whether the provider successfully executed the requested operation. */ sendKeyEvent(key: string, direction: 'down' | 'up'): Promise @@ -275,8 +275,8 @@ export interface CuaApp extends CuaSurface { /** Native app API; its caller owns global bindings and variable persistence. */ export interface CuaApi { /** - * Inspect permissions without requesting them. Turn-managed providers omit explicit hold methods outside an active turn. - * @returns Reported native capabilities for this execution context. + * Inspect permissions and the provider’s supported methods without requesting access. + * @returns Reported native capabilities. */ getCapabilities(): Promise /** diff --git a/packages/experimental/cua/tests/run-code-composition.spec.ts b/packages/experimental/cua/tests/run-code-composition.spec.ts index 962d207049..e670aa4269 100644 --- a/packages/experimental/cua/tests/run-code-composition.spec.ts +++ b/packages/experimental/cua/tests/run-code-composition.spec.ts @@ -587,6 +587,48 @@ it('records release after a thinking pause so the resumed model sees the new inp expect(JSON.stringify(f.model.requests[0]?.messages)).toContain('CUA inputs were released during cleanup') }) +it('removes a pending held reminder when a pause preserves the inbox', async () => { + const f = await setup([holdProgram], 'macos', undefined, true, true) + const inserted: PromiseWithResolvers = Promise.withResolvers() + f.ctx.on('agent/inbox/inserted', ({ agent, message }) => { + if (agent !== f.agent || message.source.kind !== 'cua-held-inputs') return + inserted.resolve() + agent.cancel({ kind: 'user' }, { keepInbox: true }) + }) + const running = f.run() + await inserted.promise + await running + expect(f.agent.inbox.nextStep.map(message => message.source.kind)).toContain('cua-inputs-released') + expect(f.agent.inbox.nextStep.map(message => message.source.kind)).not.toContain('cua-held-inputs') + f.model.restart(['inspect("resumed")']) + await f.run() + const resumed = JSON.stringify(f.model.requests[0]?.messages) + expect(resumed).toContain('CUA inputs were released during cleanup') + expect(resumed).not.toContain('CUA inputs are still held') +}) + +it('drains an abnormal prior turn’s input before another program dispatches', async () => { + const f = await setup([holdProgram], 'macos', undefined, true, true) + await f.run() + expect(f.native.held).toHaveLength(1) + f.model.restart([]) + f.model.beforeStream = async () => { throw new Error('Model failed after the previous turn left a key held') } + const release = f.native.controlNext('releaseHeldInputs') + const failing = f.run() + await release.entered + let next: Promise | undefined + try { + expect(f.agent.session.snapshotEvents().at(-1)?.type).toBe('turn/end') + expect(f.native.held).toHaveLength(1) + delete f.model.beforeStream + f.model.restart([holdProgram]) + next = f.run() + expect(f.native.held).toHaveLength(1) + expect(f.native.events).toEqual(['w:down']) + } finally { release.reply(); await failing; await next } + expect(f.native.events).toEqual(['w:down', 'w:up', 'w:down']) +}) + it('drops a delayed held-state reminder after cancellation has already released the input', async () => { const f = await setup([holdProgram], 'macos', undefined, true, true) const post: PromiseWithResolvers = Promise.withResolvers() From 06e9d9c1f52a3686ce8bd76ce69dc7805433772e Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 19 Nov 2026 15:34:24 +0800 Subject: [PATCH 47/73] Give each MCP maintenance fixture its own cancellation signal --- .../experimental/cua-mcp/tests/server.spec.ts | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/packages/experimental/cua-mcp/tests/server.spec.ts b/packages/experimental/cua-mcp/tests/server.spec.ts index 1f4ab1a5b7..80e11960cf 100644 --- a/packages/experimental/cua-mcp/tests/server.spec.ts +++ b/packages/experimental/cua-mcp/tests/server.spec.ts @@ -60,11 +60,15 @@ interface SetupOptions { function fixture(options: SetupOptions = {}) { const ctx = new Context() - // The Agent runs a maintenance task at once and cancels it through this controller, as its cancel and disposal do. - const maintenance = new AbortController() + let active: AbortController | undefined const members: Pick = { - id: brandString('cua-mcp-fake'), ctx: new Context(), runMaintenance: task => task(maintenance.signal), - cancel: (cause) => { maintenance.abort(cause) }, whenIdle: async () => {}, + id: brandString('cua-mcp-fake'), ctx: new Context(), + runMaintenance: async (task) => { + const controller = new AbortController() + active = controller + try { return await task(controller.signal) } finally { active = undefined } + }, + cancel: (cause) => { active?.abort(cause) }, whenIdle: async () => {}, } const runMaintenance = vi.spyOn(members, 'runMaintenance') const cancel = vi.spyOn(members, 'cancel') @@ -105,7 +109,7 @@ function fixture(options: SetupOptions = {}) { if (options.programs !== false) ctx.provide('cuaPrograms', { release, releaseInputs: vi.fn(async () => {}), screenshotRequestTarget: () => undefined, ...options.programs } as never) onTestFinished(async () => { await ctx.fiber.dispose() }) return { - ctx, agent, maintenance, runMaintenance, cancel, whenIdle, create, withInitiator, initiators, mount, execute, get, assemble, + ctx, agent, runMaintenance, cancel, whenIdle, create, withInitiator, initiators, mount, execute, get, assemble, release, dispose, } } @@ -141,7 +145,7 @@ function texts(result: CallToolResult): string[] { describe('Computer Use MCP server', () => { it('creates the Agent before serving, projects its registration verbatim, and runs programs as Agent maintenance inside the initiator scope', async () => { - const { adapter, client, run, create, mount, execute, withInitiator, initiators, agent, runMaintenance, maintenance } = await setup() + const { adapter, client, run, create, mount, execute, withInitiator, initiators, agent, runMaintenance } = await setup() expect(create).toHaveBeenCalledOnce() expect(create.mock.calls[0]?.[0]).toMatchObject({ meta: { cwd: '/workspace', agentPreset: 'cua-mcp' } }) expect(mount).toHaveBeenCalledWith(agent.ctx) @@ -170,10 +174,6 @@ describe('Computer Use MCP server', () => { expect(withInitiator).toHaveBeenCalledOnce() expect(initiators).toEqual([agent]) expect(texts(await run({ code: '2', description: 'Again' }))).toEqual(['program output']) - // Cancelling the Agent's maintenance activity, as its disposal does, cancels the program's execution. - expect(input.signal.aborted).toBe(false) - maintenance.abort() - expect(input.signal.aborted).toBe(true) }) it('fails the listing when the registration is not representable as an MCP tool', async () => { From 34f4901dc7176dd79376c6e726920527eae279da Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 19 Nov 2026 15:40:35 +0800 Subject: [PATCH 48/73] Exercise CUA holds at the Windows keyboard scope --- .../experimental/cua-mcp/tests/composition.spec.ts | 4 +++- packages/experimental/cua-windows/README.i18n.yaml | 2 +- packages/experimental/cua-windows/README.md | 2 +- .../cua/tests/run-code-composition.spec.ts | 10 +++++----- 4 files changed, 10 insertions(+), 8 deletions(-) diff --git a/packages/experimental/cua-mcp/tests/composition.spec.ts b/packages/experimental/cua-mcp/tests/composition.spec.ts index b696d1014d..70300d5110 100644 --- a/packages/experimental/cua-mcp/tests/composition.spec.ts +++ b/packages/experimental/cua-mcp/tests/composition.spec.ts @@ -209,7 +209,9 @@ describe('Computer Use MCP composition', () => { release.reply({ code: 'INPUT_CLEANUP_FAILED', message: 'MCP release refused' }) const result = await running expect(result.isError).toBe(true) - expect(texts(result).join('')).toContain('MCP release refused') + const message = texts(result).join('') + expect(message).toContain('program failed') + expect(message.match(/MCP release refused/g)).toHaveLength(1) }) it('cleans up a cancelled MCP request even after its program has finished and image delivery is pending', async () => { diff --git a/packages/experimental/cua-windows/README.i18n.yaml b/packages/experimental/cua-windows/README.i18n.yaml index fd884ad639..b76643557f 100644 --- a/packages/experimental/cua-windows/README.i18n.yaml +++ b/packages/experimental/cua-windows/README.i18n.yaml @@ -45,7 +45,7 @@ en: db3e2957041fafbb zh: 34f953887dff37f7 /deepseek-ai-dsh-cua-windows/known-limitations-and-deferred-work: - en: 3e2cd5ed7118b7f3 + en: 81fc470f6b15444b zh: c131f98f889bd728 /deepseek-ai-dsh-cua-windows/known-limitations-and-deferred-work/dev-note: en: 0a1253c6f7b5e8b9 diff --git a/packages/experimental/cua-windows/README.md b/packages/experimental/cua-windows/README.md index c4373f8832..d5c96849f9 100644 --- a/packages/experimental/cua-windows/README.md +++ b/packages/experimental/cua-windows/README.md @@ -83,7 +83,7 @@ Inspected results append to model history. Retaining an App, Window, or returned - Hover, click, scroll and drag use the system pointer. `requireSystemPointerApproval` does not prompt separately for Windows pointer operations. - Drag checks the topmost window only at its starting point. An overlay from another application along the path or at the destination can receive the drop even while the selected window stays in the foreground. - Windows routes input through the desktop. After focus changes or the original window closes, a confirmed release means the desktop accepted the up. The original window may not receive the event. If the desktop is unavailable or refuses to confirm release, further CUA input for the task is blocked. Inspect the desktop before starting another task. -- The helper does not check each key or button release during cleanup. If an input remains held after a failure, release it manually before continuing. +- Cleanup of temporary input inside complete actions does not check each key or button release. If an input remains held after a failure, release it manually before continuing. - Helper identity hashes only the exe. Different DLLs with the same apphost can reuse the old service. Stop Hosts using the same output directory before rebuilding to avoid locked files. - The Windows handshake requires a positive `maxClickHoldMs`. With zero, it fails with `INVALID_CONFIG` before ordinary clicks or status queries can run. - `findApps`, application launch, and app-level accessibility are unavailable. Ask the user to open the required application or window. diff --git a/packages/experimental/cua/tests/run-code-composition.spec.ts b/packages/experimental/cua/tests/run-code-composition.spec.ts index 4f2778ba23..b0e0135425 100644 --- a/packages/experimental/cua/tests/run-code-composition.spec.ts +++ b/packages/experimental/cua/tests/run-code-composition.spec.ts @@ -111,7 +111,7 @@ async function setup(programs: readonly string[], platform = 'macos', selectorPi acceptsPidSelector: selectorPid !== undefined, heldInputState, ...disposeNative ? { disposeNative: () => disposeNative(native.state) } : {}, capabilities: { platform, methods: ['getCapabilities', 'listApps', 'getApp', 'getState', 'click', 'screenshot', 'sendKeyEvent', 'toggleMouse'], - appLevelAccessibility: true, keyboard: ['app'], browser: false, coordinateSpace: 'screenshot-pixels' }, + appLevelAccessibility: platform !== 'windows', keyboard: platform === 'windows' ? ['window'] : ['app'], browser: false, coordinateSpace: 'screenshot-pixels' }, permissionParameters: (_method, permission, locale) => ({ permission, locale }), }) }, @@ -360,6 +360,7 @@ it('forwards per-read accessibility limits to the Windows backend', async () => }) const holdProgram = 'var app = await cua.getApp("test.fixture"); await app.sendKeyEvent("w", "down")' +const holdWindowProgram = 'var app = await cua.getApp("test.fixture"); var win = await app.getWindow("7"); await win.sendKeyEvent("w", "down")' function reminders(agent: { session: { snapshotEvents(): readonly import('@deepseek-ai/dsh-session').SessionEvent[] } }, kind: 'cua-held-inputs' | 'cua-inputs-released' = 'cua-held-inputs') { @@ -383,8 +384,7 @@ it('reports native held input after programs, keeps it across turns, and stops r }) it('reports the Windows keyboard window and desktop input mode and supports a later explicit up', async () => { - const f = await setup(['var app = await cua.getApp("test.fixture"); var win = await app.getWindow("7"); await win.sendKeyEvent("w", "down")'], - 'windows', undefined, true, true) + const f = await setup([holdWindowProgram], 'windows', undefined, true, true) await f.run() expect(f.native.events).toEqual(['w:down']) expect(reminders(f.agent)[0]).toContain('Key "w", appHandle "fixture-app", windowId "7" (system input)') @@ -492,7 +492,7 @@ it('reports failed native state inspection and releases held input instead of cl it('keeps the Windows helper runtime alive until its Agent connection confirms release', async () => { const disposed = vi.fn(async (state: { closedChannels: number }) => state.closedChannels) - const f = await setup([holdProgram], 'windows', undefined, true, true, undefined, async (state) => { await disposed(state) }) + const f = await setup([holdWindowProgram], 'windows', undefined, true, true, undefined, async (state) => { await disposed(state) }) await f.run() const release = f.native.controlNext('releaseHeldInputs') const closing = f.provider.dispose() @@ -521,7 +521,7 @@ it.each(['agent', 'provider', 'context'] as const)('awaits native release when t }) it('leaves providers without held-input state support on their existing protocol', async () => { - const f = await setup([holdProgram, 'await app.sendKeyEvent("w", "up")'], 'windows', undefined, true) + const f = await setup([holdWindowProgram, 'await win.sendKeyEvent("w", "up")'], 'windows', undefined, true) await f.run() for (const call of f.native.calls.filter(call => call.method === 'sendKeyEvent')) expect(call.params).not.toHaveProperty('taskId') expect(f.native.calls.some(call => ['getHeldInputs', 'releaseHeldInputs'].includes(call.method))).toBe(false) From e5ee75a1eb7860debb951e46147ce63555fe510b Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 19 Nov 2026 15:42:52 +0800 Subject: [PATCH 49/73] Record capability-specific reminders and cover cleanup error combinations --- .../cua-mcp/expected/instructions.txt | 2 +- .../profiles/cua-mcp/expected/reference.md | 2 +- .../cua-mcp/tests/composition.spec.ts | 18 +++++++++++---- .../cua/tests/run-code-composition.spec.ts | 23 ++++++++++++++++--- .../cua-run-code/system-prompt.expected.md | 2 +- .../cua-native/system-prompt.expected.md | 2 +- .../session/cua-ptc/system-prompt.expected.md | 2 +- .../system-prompt.expected.md | 2 +- .../cua-run-code/system-prompt.expected.md | 2 +- .../system-prompt.expected.md | 2 -- 10 files changed, 41 insertions(+), 16 deletions(-) diff --git a/apps/cli/tests/profiles/cua-mcp/expected/instructions.txt b/apps/cli/tests/profiles/cua-mcp/expected/instructions.txt index aaa6234dad..4ae508c48b 100644 --- a/apps/cli/tests/profiles/cua-mcp/expected/instructions.txt +++ b/apps/cli/tests/profiles/cua-mcp/expected/instructions.txt @@ -1 +1 @@ -DeepSeek Harness Computer Use: observe and operate desktop applications on this machine. Start every conversation by calling cua_get_api_reference: it returns the complete cua API reference, and programs written without it guess the API wrong. Then call cua_run_code with a TypeScript program that uses the global cua object; program state persists across calls on this connection. A call may ask the user for application or pointer consent before it proceeds. Call cua_reset to discard program state. Explicit key and mouse downs remain held across successful programs; a system reminder lists remaining holds. Explicit up, program failure, request cancellation, reset, and connection closure release owned input. Client pause between completed calls is not observable by this server and does not release input. +DeepSeek Harness Computer Use: observe and operate desktop applications on this machine. Start every conversation by calling cua_get_api_reference: it returns the complete cua API reference, and programs written without it guess the API wrong. Then call cua_run_code with a TypeScript program that uses the global cua object; program state persists across calls on this connection. A call may ask the user for application or pointer consent before it proceeds. Call cua_reset to discard program state. diff --git a/apps/cli/tests/profiles/cua-mcp/expected/reference.md b/apps/cli/tests/profiles/cua-mcp/expected/reference.md index ca24cca04d..76eccd001e 100644 --- a/apps/cli/tests/profiles/cua-mcp/expected/reference.md +++ b/apps/cli/tests/profiles/cua-mcp/expected/reference.md @@ -53,7 +53,7 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. -Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. +Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/packages/experimental/cua-mcp/tests/composition.spec.ts b/packages/experimental/cua-mcp/tests/composition.spec.ts index 70300d5110..c8176b9bc2 100644 --- a/packages/experimental/cua-mcp/tests/composition.spec.ts +++ b/packages/experimental/cua-mcp/tests/composition.spec.ts @@ -240,7 +240,7 @@ describe('Computer Use MCP composition', () => { expect(native.held).toEqual([]) }) - it.each(['reset', 'image failure'] as const)('cleans up held input when %s interrupts response delivery', async (ending) => { + it.each(['reset', 'image failure', 'cleanup failure'] as const)('cleans up held input when %s interrupts response delivery', async (ending) => { const { ctx, native, client, run } = await setup() const entered: PromiseWithResolvers = Promise.withResolvers() const finish: PromiseWithResolvers = Promise.withResolvers() @@ -249,7 +249,7 @@ describe('Computer Use MCP composition', () => { if (native.calls.some(call => call.method === 'getHeldInputs')) { entered.resolve() await finish.promise - if (ending === 'image failure') throw new Error('Fixture screenshot could not be delivered') + if (ending !== 'reset') throw new Error('Fixture screenshot could not be delivered') } return original(...args) }) @@ -268,12 +268,22 @@ describe('Computer Use MCP composition', () => { release.reply() expect(resetDone).toBe(false) } + if (ending === 'cleanup failure') { + const release = native.controlNext('releaseHeldInputs') + finish.resolve() + await release.entered + release.reply({ code: 'INPUT_CLEANUP_FAILED', message: 'Fixture cleanup refused during response delivery' }) + } } finally { finish.resolve() } const result = await running expect(result).not.toContain('CUA inputs are still held') - if (ending === 'image failure') expect(result).toContain('Fixture screenshot could not be delivered') + if (ending !== 'reset') expect(result).toContain('Fixture screenshot could not be delivered') + if (ending === 'cleanup failure') { + expect(result).toContain('Fixture cleanup refused during response delivery') + const next = await run('await win.sendKeyEvent("w", "down")') + expect(texts(next).join(' ')).toContain('INPUT_CLEANUP_UNCONFIRMED') + } else expect(native.held).toEqual([]) expect((await reset)?.isError).not.toBe(true) - expect(native.held).toEqual([]) }) it('reports refused cleanup after a cancelled MCP request and prevents further native input', async () => { diff --git a/packages/experimental/cua/tests/run-code-composition.spec.ts b/packages/experimental/cua/tests/run-code-composition.spec.ts index b0e0135425..ae30997930 100644 --- a/packages/experimental/cua/tests/run-code-composition.spec.ts +++ b/packages/experimental/cua/tests/run-code-composition.spec.ts @@ -407,6 +407,19 @@ it('releases keyboard and mouse in mixed reverse order on program failure', asyn expect(results.map(result => result.isError)).toEqual([false, true, false]) }) +it('releases a previous hold when downstream execution throws before producing a result', async () => { + const f = await setup([holdProgram], 'macos', undefined, true, true) + await f.run() + f.model.restart(['inspect("unreachable")']) + f.ctx.on('tools/execute', (execution, next) => { + if (execution.name === 'cua_run_code') throw new Error('Executor middleware failed') + return next() + }) + await f.run() + expect(f.native.events).toEqual(['w:down', 'w:up']) + expect(JSON.stringify(f.agent.session.deriveMessages())).toContain('Executor middleware failed') +}) + it('reminders name the actual mouse target and omit explicitly released inputs', async () => { const f = await setup([holdProgram, 'await app.sendKeyEvent("w", "up"); var win = await app.getWindow("7"); await win.toggleMouse("left", "down")'], 'macos', undefined, true, true) @@ -683,13 +696,17 @@ it('drops a delayed held-state reminder after cancellation has already released expect(reminders(f.agent, 'cua-inputs-released')).toHaveLength(1) }) -it('does not report held input when stopped as its native state query replies', async () => { +it.each(['reply before stop', 'stop before reply'] as const)('does not report held input on %s', async (order) => { const f = await setup([holdProgram], 'macos', undefined, true, true) - const query = f.native.controlNext('getHeldInputs', { afterDispatch: true }) + const query = f.native.controlNext('getHeldInputs', { afterDispatch: true, waitForCancellation: order === 'stop before reply' }) const running = f.run() await query.entered - query.reply() + if (order === 'reply before stop') query.reply() f.agent.cancel({ kind: 'user' }) + if (order === 'stop before reply') { + await query.cancelled + query.reply({ code: 'NATIVE_CANCELLED', message: 'Held-state query cancelled' }) + } await running expect(f.native.held).toEqual([]) expect(f.agent.inbox.nextStep.some(message => message.source.kind === 'cua-held-inputs')).toBe(false) diff --git a/snapshots/sdk/cua-run-code/system-prompt.expected.md b/snapshots/sdk/cua-run-code/system-prompt.expected.md index 7b90ddb906..8d54a03167 100644 --- a/snapshots/sdk/cua-run-code/system-prompt.expected.md +++ b/snapshots/sdk/cua-run-code/system-prompt.expected.md @@ -87,7 +87,7 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. -Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. +Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/snapshots/session/cua-native/system-prompt.expected.md b/snapshots/session/cua-native/system-prompt.expected.md index d4064ef6eb..9fe44655d6 100644 --- a/snapshots/session/cua-native/system-prompt.expected.md +++ b/snapshots/session/cua-native/system-prompt.expected.md @@ -90,7 +90,7 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. -Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. +Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index a8f33aac4e..0a0eab2d43 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -92,7 +92,7 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. -Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. +Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/snapshots/session/cua-run-code-ptc/system-prompt.expected.md b/snapshots/session/cua-run-code-ptc/system-prompt.expected.md index 155346b4eb..28dfdd4e01 100644 --- a/snapshots/session/cua-run-code-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-run-code-ptc/system-prompt.expected.md @@ -88,7 +88,7 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. -Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. +Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/snapshots/session/cua-run-code/system-prompt.expected.md b/snapshots/session/cua-run-code/system-prompt.expected.md index 7acc0f5667..581d8faa76 100644 --- a/snapshots/session/cua-run-code/system-prompt.expected.md +++ b/snapshots/session/cua-run-code/system-prompt.expected.md @@ -86,7 +86,7 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. -Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. +Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/snapshots/session/ptc-script-retained/system-prompt.expected.md b/snapshots/session/ptc-script-retained/system-prompt.expected.md index 37e5d1d56e..7dae87ca27 100644 --- a/snapshots/session/ptc-script-retained/system-prompt.expected.md +++ b/snapshots/session/ptc-script-retained/system-prompt.expected.md @@ -92,8 +92,6 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. -Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them at their original recipient. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. - click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. 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. From 129e7f6ceb0c19aafea5fdde40db53d303c90478 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 19 Nov 2026 15:45:07 +0800 Subject: [PATCH 50/73] Release held input when tool middleware throws synchronously --- .../cua-macos/tests/held-inputs.desktop.e2e.ts | 8 ++++++-- packages/experimental/cua/src/held-inputs.ts | 6 ++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/packages/experimental/cua-macos/tests/held-inputs.desktop.e2e.ts b/packages/experimental/cua-macos/tests/held-inputs.desktop.e2e.ts index bb92e6c6ec..f2a20d04b5 100644 --- a/packages/experimental/cua-macos/tests/held-inputs.desktop.e2e.ts +++ b/packages/experimental/cua-macos/tests/held-inputs.desktop.e2e.ts @@ -66,7 +66,7 @@ it.skipIf(process.platform !== 'darwin' || helperPath === undefined).each(['comp const pad = initial.pad const programs = [ `var app = await cua.getApp(${JSON.stringify(String(initial.pid))}); await app.activate(); var win = await app.getWindow(${JSON.stringify(initial.windowId)}); await win.getAccessibilityTree(); var bounds = (await app.getWindows()).find(w => w.windowId === win.windowId).bounds; await win.mouseMove([Math.round(${pad[0] + 80} / bounds.width * 999), Math.round(${pad[1] + 70} / bounds.height * 999)], { relative: true, useSystemPointer: true }); await app.sendKeyEvent('a', 'down')`, - `await win.toggleMouse('left', 'down'); await app.sendKeyEvent('w', 'down'); ${ending === 'tool-stop' ? 'await new Promise(() => {})' : ''}`, + `await win.toggleMouse('left', 'down', { useSystemPointer: true }); await app.sendKeyEvent('w', 'down'); ${ending === 'tool-stop' ? 'await new Promise(() => {})' : ''}`, ] const thinking: PromiseWithResolvers = Promise.withResolvers() class Model extends LlmAdapter { @@ -112,10 +112,14 @@ it.skipIf(process.platform !== 'darwin' || helperPath === undefined).each(['comp handle.agent.cancel({ kind: 'user' }) } await handle.agent.whenIdle() + if (ending !== 'tool-stop') { + const failures = handle.agent.session.deriveMessages().filter(message => message.role === 'tool' && message.isError) + expect(failures, JSON.stringify(failures)).toEqual([]) + } if (ending === 'completed') { await expect.poll(async () => (await received()).map(event => event.type), { timeout: 30_000 }).toEqual([10, 1, 10]) expect(JSON.stringify(handle.agent.session.snapshotEvents())).toContain('CUA inputs are still held') - programs[3] = "await app.sendKeyEvent('w', 'up'); await win.toggleMouse('left', 'up'); await app.sendKeyEvent('a', 'up')" + programs[3] = "await app.sendKeyEvent('w', 'up'); await win.toggleMouse('left', 'up', { useSystemPointer: true }); await app.sendKeyEvent('a', 'up')" handle.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Release held input' }], source: { kind: 'user' } })) await handle.agent.whenIdle() } diff --git a/packages/experimental/cua/src/held-inputs.ts b/packages/experimental/cua/src/held-inputs.ts index ba7164945c..4856aa90a3 100644 --- a/packages/experimental/cua/src/held-inputs.ts +++ b/packages/experimental/cua/src/held-inputs.ts @@ -158,10 +158,12 @@ export class CuaHeldInputs { `${message}. Held-input cleanup failed: ${String(error)}`, { cause: error }) } } try { - const result = await next().catch(async (error: unknown) => { + let result: Awaited> + try { result = await next() } + catch (error) { await releaseAfter(`Program failed: ${String(error)}`) throw error - }) + } if (result.isError || signal.aborted) { await releaseAfter(result.isError ? result.error.message : 'Program cancelled') } else if (execution.parent === undefined) { From 32f69510651613ed87276908f8a8f0770aed9f4f Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 19 Nov 2026 15:47:11 +0800 Subject: [PATCH 51/73] Verify cleanup reporting after Windows helper lease failure --- .../cua/tests/run-code-composition.spec.ts | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/packages/experimental/cua/tests/run-code-composition.spec.ts b/packages/experimental/cua/tests/run-code-composition.spec.ts index ae30997930..7058eb9427 100644 --- a/packages/experimental/cua/tests/run-code-composition.spec.ts +++ b/packages/experimental/cua/tests/run-code-composition.spec.ts @@ -503,9 +503,15 @@ it('reports failed native state inspection and releases held input instead of cl expect(JSON.stringify(f.agent.session.deriveMessages())).toContain('Held state unavailable') }) -it('keeps the Windows helper runtime alive until its Agent connection confirms release', async () => { - const disposed = vi.fn(async (state: { closedChannels: number }) => state.closedChannels) - const f = await setup([holdWindowProgram], 'windows', undefined, true, true, undefined, async (state) => { await disposed(state) }) +it.each(['closes', 'fails to close'] as const)('waits for Agent release before the Windows helper runtime %s', async (outcome) => { + const failure = new Error('Windows helper lease could not close') + const disposed = vi.fn(async (state: { closedChannels: number }) => { + expect(state.closedChannels).toBe(1) + if (outcome === 'fails to close') throw failure + }) + const f = await setup([holdWindowProgram], 'windows', undefined, true, true, undefined, disposed) + const report = vi.spyOn(f.provider.ctx.logger, 'error').mockImplementation(() => {}) + onTestFinished(() => { report.mockRestore() }) await f.run() const release = f.native.controlNext('releaseHeldInputs') const closing = f.provider.dispose() @@ -513,8 +519,9 @@ it('keeps the Windows helper runtime alive until its Agent connection confirms r try { expect(disposed).not.toHaveBeenCalled() } finally { release.reply() } await closing expect(disposed).toHaveBeenCalledOnce() - expect(await disposed.mock.results[0]?.value).toBe(1) expect(f.native.held).toEqual([]) + if (outcome === 'fails to close') expect(report).toHaveBeenCalledWith(expect.objectContaining({ errors: [failure] })) + else expect(report).not.toHaveBeenCalled() }) it.each(['agent', 'provider', 'context'] as const)('awaits native release when the %s is disposed after a completed turn', async (owner) => { From 9f776b7e316962e0f6ffd9a4081f31b458559fe8 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 19 Nov 2026 17:49:05 +0800 Subject: [PATCH 52/73] Let Agent idle complete independently of background CUA release --- docs/event-producer-consumer.md | 2 +- docs/event-producer-consumer.zh.md | 2 +- .../cua-held-inputs/guide.i18n.yaml | 4 +- .../v0.2.2-rc.5/cua-held-inputs/guide.md | 2 +- .../v0.2.2-rc.5/cua-held-inputs/guide.zh.md | 2 +- packages/experimental/cua/README.i18n.yaml | 4 +- packages/experimental/cua/README.md | 4 +- packages/experimental/cua/README.zh.md | 4 +- packages/experimental/cua/src/guidance.ts | 2 +- packages/experimental/cua/src/held-inputs.ts | 4 - .../cua/tests/run-code-composition.spec.ts | 154 +++++++++++++----- 11 files changed, 125 insertions(+), 59 deletions(-) diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index ae616ceb5e..94c195f1ec 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -21,7 +21,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:318`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`cua`](../packages/experimental/cua), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | | `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:351`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`cua`](../packages/experimental/cua), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | | `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:390`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | -| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:310`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`cua`](../packages/experimental/cua), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`timeline`](../packages/experimental/timeline) | +| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:310`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`timeline`](../packages/experimental/timeline) | | `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:418`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:697`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:677`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index be0073083b..25c0ae866a 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -23,7 +23,7 @@ | `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:318`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`cua`](../packages/experimental/cua), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | | `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:351`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`cua`](../packages/experimental/cua), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | | `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:390`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | -| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:310`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`cua`](../packages/experimental/cua), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`timeline`](../packages/experimental/timeline) | +| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:310`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`timeline`](../packages/experimental/timeline) | | `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:418`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:697`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:677`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | diff --git a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml index 1bb2901ef5..2d11979d27 100644 --- a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml @@ -12,5 +12,5 @@ en: 2812241cf189be50 zh: ee90f8e5c6c55512 /cua-reports-held-input-after-programs/migration: - en: e14ac0c327d75964 - zh: 7899f47c4a3cc78c + en: c5edd5bf874d2a95 + zh: e26d4e6945da4eae diff --git a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md index 5eb055f55c..8ab3a4b3a8 100644 --- a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md @@ -14,4 +14,4 @@ On macOS and Windows, explicit `sendKeyEvent('down')` and `toggleMouse('down')` 1. Pair explicit downs with ups when input should stop. Read the reminder before continuing; no reminder is added when no input remains held. 2. Upgrade the platform package and helper together. A custom `helperPath` must implement the task-owned `getHeldInputs` and `releaseHeldInputs` private operations. -3. Verify that one successful program can hold a key, receive its reminder, and release it in a later program. Program failure and cancellation must release it before they finish. If cleanup cannot be confirmed, CUA disables further operations for that task; inspect the desktop manually before starting another task. +3. Verify that one successful program can hold a key, receive its reminder, and release it in a later program. A failed or cancelled program waits for its cleanup. If the model is thinking when DSH stops or fails, the Agent can finish before native release is confirmed. Subsequent CUA calls wait for the outcome. If cleanup cannot be confirmed, CUA disables further operations for that task; inspect the desktop manually before starting another task. diff --git a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md index 4f88528585..f53a8017e7 100644 --- a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md @@ -14,4 +14,4 @@ macOS 和 Windows 的显式 `sendKeyEvent('down')` 和 `toggleMouse('down')` 跨 1. 输入不再需要保持时,将显式 down 与 up 配对。继续操作前阅读提醒;没有持有输入时不添加提醒。 2. 同步升级平台包和 helper。自定义 `helperPath` 必须实现按任务区分的 `getHeldInputs` 和 `releaseHeldInputs` 私有操作。 -3. 验证成功结束的程序能持有按键、收到提醒,并在后续程序中释放。程序失败和取消必须在结束前释放它。清理无法确认时,CUA 禁用该任务后续操作;请手动检查桌面后再创建其他任务。 +3. 验证成功结束的程序能持有按键、收到提醒,并在后续程序中释放。程序失败或取消时会等待自身的清理。模型思考期间停止或报错,Agent 可以先结束,原生释放随后确认。后续 CUA 调用会等待清理结果。清理无法确认时,CUA 禁用该任务后续操作;请手动检查桌面后再创建其他任务。 diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index b7c42a4fa3..d4ae0b00e9 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -21,8 +21,8 @@ en: 3f638a4a76023fc5 zh: 515aeb5de6ae5b33 /deepseek-ai-dsh-cua/understand-the-implementation: - en: 7e40a3ed87af41a5 - zh: a0ad1cbf2c70c285 + en: b8b48032f8efe0fc + zh: a5e8224efa433c59 /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 69f028ab60..97aaa6cf4e 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -91,9 +91,9 @@ Permission responses identify their platform and report only the state that plat
Shared execution and platform ownership -Providers implementing `CuaBackend.heldInputState` accept `taskId` on explicit input and system pointer movement, report their connection-owned records through `getHeldInputs({ taskId })`, and acknowledge `releaseHeldInputs({ taskId })`. Native records own the actual key/button, target, process identity and input mode. Successful `run_code` and `cua_run_code` programs query those records and append a system reminder when input remains held; normal program and turn endings preserve input in both DSH and MCP. Reminders travel through logged additional context in DSH and through the tool response in MCP. Program failure, cancellation, connection closure, environment reset and disposal stop owned dispatch and await reverse-order release. Cleanup failure disables further CUA operations for the task and reports the uncertainty. Provider unload retains these listeners until programs and native connections drain. Capability methods remain static. Windows leaves `heldInputState` unset until its helper implements reporting and cleanup; it receives no new commands. +Providers implementing `CuaBackend.heldInputState` accept `taskId` on explicit input and system pointer movement, report their connection-owned records through `getHeldInputs({ taskId })`, and acknowledge `releaseHeldInputs({ taskId })`. Native records own the actual key/button, target, process identity and input mode. Successful `run_code` and `cua_run_code` programs query those records and append a system reminder when input remains held; normal program and turn endings preserve input in both DSH and MCP. Reminders travel through logged additional context in DSH and through the tool response in MCP. macOS and Windows both implement this protocol. -Held input belongs to the task and native connection, outside program processes. DSH observes the turn cancellation signal while the model is thinking. DSH queues confirmed cleanup as a release notice for the resumed model; held-state snapshots arriving after cleanup starts are discarded. +Held input belongs to the task and native connection, outside program processes. A DSH stop or model failure starts cleanup. The Agent can finish the turn and resolve `whenIdle()` while the native release is pending. Subsequent CUA calls wait for its outcome. Confirmed release queues a notice for the model and removes pending held-state reminders. A cleanup failure is reported through `agent/error` and disables CUA for that task. A failed or cancelled program, an active MCP request receiving cancellation, an environment reset, and connection or provider disposal each await their own cleanup. The [permission store](src/permission-store.ts) uses `storageDomain` with the configured backend. The default JSON backend writes `$DSH_HOME/storages/cua_permissions_.json`, where the digest identifies the canonical profile directory. Each authorization check opens fresh state under the profile's file lock and closes its domain afterward; native dispatch uses a separate application lock. Revocation waits for operations already admitted by another process; after it completes, every process rejects old handles. Files on different machines or PID namespaces must not share this lock. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index 4df07c07ca..ee5571f737 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -91,9 +91,9 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边
共享执行与平台职责 -实现 `CuaBackend.heldInputState` 的提供方为显式输入和系统指针移动接受 `taskId`,通过 `getHeldInputs({ taskId })` 报告本连接的持有记录,并确认 `releaseHeldInputs({ taskId })`。原生记录负责保存实际按键或按钮、目标、进程身份和输入方式。成功结束的 `run_code` 和 `cua_run_code` 查询这些记录,仍有输入按住时添加 system reminder;DSH 和 MCP 的正常程序结束和回合结束均保持输入。DSH 通过已记录的额外上下文传递提醒,MCP 通过工具响应传递。程序失败、取消、断连、环境重置和销毁会停止所属输入派发,并等待反序释放。清理失败会禁用该任务后续 CUA 操作并报告结果不确定。提供方卸载前保留监听器,直到程序和原生连接排空。能力方法列表保持静态。Windows 在 helper 实现报告和清理前不设置 `heldInputState`,不会收到新命令。 +实现 `CuaBackend.heldInputState` 的提供方为显式输入和系统指针移动接受 `taskId`,通过 `getHeldInputs({ taskId })` 报告本连接的持有记录,并确认 `releaseHeldInputs({ taskId })`。原生记录负责保存实际按键或按钮、目标、进程身份和输入方式。成功结束的 `run_code` 和 `cua_run_code` 查询这些记录,仍有输入按住时添加 system reminder;DSH 和 MCP 的正常程序结束和回合结束均保持输入。DSH 通过已记录的额外上下文传递提醒,MCP 通过工具响应传递。macOS 和 Windows 都实现了这套协议。 -持有输入属于任务和原生连接,保存在程序进程之外。模型思考期间,DSH 仍监听回合取消信号。DSH 在清理确认后将释放提醒写入会话队列,供恢复后的模型读取;清理开始后才到达的旧持有状态提醒会被丢弃。 +持有输入属于任务和原生连接,保存在程序进程之外。DSH 收到停止请求或模型报错时启动清理。原生释放尚未确认时,Agent 可以结束回合,`whenIdle()` 也可以返回。后续 CUA 调用等待清理结果。确认释放后,DSH 为模型记录释放提醒,并撤销仍在队列中的旧持有提醒。清理失败会通过 `agent/error` 单独报告,并禁用该任务后续的 CUA 操作。程序失败或取消、执行中的 MCP 请求收到取消、环境重置、连接关闭和提供方卸载,各自等待清理完成。 [授权存储](src/permission-store.ts)复用 `storageDomain` 和配置的后端。默认 JSON 后端写入 `$DSH_HOME/storages/cua_permissions_.json`,摘要对应 profile 的真实目录。每次授权检查在 profile 文件锁内打开并读取最新状态,随后关闭存储域;原生操作使用单独的应用锁。撤销会等待其他进程已获准执行的操作结束;撤销完成后,各进程都拒绝旧句柄。不同电脑或 PID 命名空间不能共享这把锁。 diff --git a/packages/experimental/cua/src/guidance.ts b/packages/experimental/cua/src/guidance.ts index 9de01757e0..c9fa89722c 100644 --- a/packages/experimental/cua/src/guidance.ts +++ b/packages/experimental/cua/src/guidance.ts @@ -67,7 +67,7 @@ Raw tools use { method, params }: include appHandle for app calls and windowId f * @returns Instructions for a provider with held-input state support. */ export function withHeldInputGuidance(guidance: string): string { - return guidance.replace('click, drag, and pressKey are convenience operations;', `Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. + return guidance.replace('click, drag, and pressKey are convenience operations;', `Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. After a DSH stop, the next CUA operation waits for any pending cleanup. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations;`) } diff --git a/packages/experimental/cua/src/held-inputs.ts b/packages/experimental/cua/src/held-inputs.ts index 4856aa90a3..0f424bb19c 100644 --- a/packages/experimental/cua/src/held-inputs.ts +++ b/packages/experimental/cua/src/held-inputs.ts @@ -208,10 +208,6 @@ export class CuaHeldInputs { this.turnSignals.delete(agent) if (event.data.reason.kind === 'aborted' || event.data.reason.kind === 'error') this.stop(agent) }) - yield ctx.on('agent/status', ({ agent, status }) => { - const owner = this.owners.get(agent) - if (status === 'idle' && owner?.closing) void agent.runMaintenance(() => owner.settled()) - }, { prepend: true }) yield () => { for (const value of this.turnSignals.values()) value.remove(); this.turnSignals.clear() } } } diff --git a/packages/experimental/cua/tests/run-code-composition.spec.ts b/packages/experimental/cua/tests/run-code-composition.spec.ts index 7058eb9427..fbb4938efa 100644 --- a/packages/experimental/cua/tests/run-code-composition.spec.ts +++ b/packages/experimental/cua/tests/run-code-composition.spec.ts @@ -31,6 +31,7 @@ import { z } from 'zod' import { createNativeFixture, png } from '../../../../snapshots/session/cua-run-code/native-channel.mjs' import { CuaConfig, installCua } from '../src/index.ts' import { Request } from '../src/protocol.ts' +import { NativeClient } from '../src/native-client.ts' import { brandString } from '@deepseek-ai/dsh-brand' const programs = [ @@ -430,41 +431,87 @@ it('reminders name the actual mouse target and omit explicitly released inputs', expect(f.native.held).toEqual([]) }) -it.each(['model failure', 'thinking stop', 'tool stop'] as const)('awaits held input release on %s', async (ending) => { - const f = await setup([holdProgram + (ending === 'tool stop' ? '; await new Promise(() => {})' : '')], 'macos', undefined, true, true) +function nextReleaseNotice(f: Awaited>): Promise { + const recorded: PromiseWithResolvers = Promise.withResolvers() + f.ctx.on('agent/inbox/inserted', ({ agent, message }) => { + if (agent === f.agent && message.source.kind === 'cua-inputs-released') recorded.resolve() + }) + return recorded.promise +} + +it.each([ + ['model failure', 'confirmed'], + ['thinking stop', 'confirmed'], + ['thinking stop', 'refused'], +] as const)('returns to idle after %s while new CUA input waits for cleanup (%s)', async (ending, outcome) => { + const f = await setup([holdProgram], 'macos', undefined, true, true) const thinking: PromiseWithResolvers = Promise.withResolvers() f.model.beforeStream = async (index, options) => { if (index !== 1) return - if (ending === 'model failure') throw new Error('Model failed') + if (ending === 'model failure') throw new Error('Model failed with W held') thinking.resolve() - await new Promise((resolve) => { options.signal?.addEventListener('abort', () => { resolve() }, { once: true }) }) + const signal = options.signal! + await new Promise((resolve) => { signal.addEventListener('abort', () => { resolve() }, { once: true }) }) } - const down = ending === 'tool stop' ? f.native.controlNext('sendKeyEvent', { afterDispatch: true }) : undefined - const release = ending === 'tool stop' ? undefined : f.native.controlNext('releaseHeldInputs') - let settled = false - const running = f.run().then(() => { settled = true }) - if (down) { await down.entered; f.agent.cancel({ kind: 'user' }); down.reply() } - else if (ending === 'thinking stop') { await thinking.promise; f.agent.cancel({ kind: 'user' }) } - if (release) { - await release.entered - expect(settled).toBe(false) - release.reply() + const release = f.native.controlNext('releaseHeldInputs') + const notice = nextReleaseNotice(f).then(() => [...f.native.events]) + const reported: PromiseWithResolvers = Promise.withResolvers() + f.ctx.on('agent/error', ({ error }) => { + if (error instanceof Error && error.message.includes('Release refused after idle')) reported.resolve(error) + }) + const idle = f.run() + if (ending === 'thinking stop') { await thinking.promise; f.agent.cancel({ kind: 'user' }, { keepInbox: true }) } + await release.entered + let following: Promise + const before = f.native.calls.length + try { + await idle + expect(f.native.held.map(press => press.key)).toEqual(['w']) + expect(f.agent.inbox.nextStep.some(message => message.source.kind === 'cua-inputs-released')).toBe(false) + const terminal = f.agent.session.snapshotEvents().find(event => event.type === 'turn/end') + expect(terminal?.data.reason.kind).toBe(ending === 'thinking stop' ? 'aborted' : 'error') + + const admitted: PromiseWithResolvers = Promise.withResolvers() + f.ctx.on('tools/execute', (execution, next) => { + const result = next() + if (execution.name === 'cua') admitted.resolve() + return result + }) + delete f.model.beforeStream + f.model.restart(['await app.sendKeyEvent("d", "down")']) + following = f.run() + await admitted.promise + expect(f.native.calls).toHaveLength(before) + } finally { + release.reply(outcome === 'refused' ? { code: 'INPUT_CLEANUP_FAILED', message: 'Release refused after idle' } : undefined) + } + await following + if (outcome === 'confirmed') { + expect(await notice).toEqual(['w:down', 'w:up']) + expect(f.native.events).toEqual(['w:down', 'w:up', 'd:down']) + } else { + expect(await reported.promise).toMatchObject({ code: 'INPUT_CLEANUP_FAILED' }) + expect(f.native.calls).toHaveLength(before) + expect(JSON.stringify(f.agent.session.deriveMessages())).toContain('INPUT_CLEANUP_UNCONFIRMED') + expect(f.agent.session.snapshotEvents().some(event => event.type === 'agent/inbox/spliced' + && event.data.inserted.some(message => message.source.kind === 'cua-inputs-released'))).toBe(false) } - await running - expect(f.native.held).toEqual([]) - expect(f.native.events.filter(event => event === 'w:up')).toHaveLength(1) }) it('cancels an in-flight down before releasing input and allows later programs after confirmed cleanup', async () => { const f = await setup([holdProgram], 'macos', undefined, true, true) const down = f.native.controlNext('sendKeyEvent', { afterDispatch: true, waitForCancellation: true }) - const running = f.run() + let finished = false + const running = f.run().then(() => { finished = true }) await down.entered f.agent.cancel({ kind: 'user' }) await down.cancelled expect(f.native.held.map(press => press.key)).toEqual(['w']) expect(f.native.calls.some(call => call.method === 'releaseHeldInputs')).toBe(false) + const release = f.native.controlNext('releaseHeldInputs') down.reply({ code: 'NATIVE_CANCELLED', message: 'Stopped after dispatch' }) + await release.entered + try { expect(finished).toBe(false) } finally { release.reply() } await running expect(f.native.held).toEqual([]) f.model.requests.length = 0 @@ -524,6 +571,43 @@ it.each(['closes', 'fails to close'] as const)('waits for Agent release before t else expect(report).not.toHaveBeenCalled() }) +it.each(['confirmed', 'refused'] as const)('joins background cleanup on concurrent provider disposal (%s)', async (outcome) => { + const f = await setup([holdProgram], 'macos', undefined, true, true) + f.model.beforeStream = async (index) => { if (index === 1) throw new Error('Model failed') } + const errors: unknown[] = [] + f.ctx.on('agent/error', ({ error }) => { errors.push(error) }) + const release = f.native.controlNext('releaseHeldInputs') + const idle = f.run() + await release.entered + await idle + + const entered: PromiseWithResolvers = Promise.withResolvers() + const dispose = NativeClient.prototype.dispose + const spy = vi.spyOn(NativeClient.prototype, 'dispose').mockImplementation(function (this: NativeClient) { + const closing = dispose.call(this) + entered.resolve() + return closing + }) + onTestFinished(() => { spy.mockRestore() }) + let disposed = false + const closing = f.provider.dispose().then(() => { disposed = true }) + try { + await entered.promise + expect(disposed).toBe(false) + expect(f.native.state.closedChannels).toBe(0) + } finally { + release.reply(outcome === 'refused' ? { code: 'INPUT_CLEANUP_FAILED', message: 'Release refused during disposal' } : undefined) + await closing + } + expect(f.native.calls.filter(call => call.method === 'releaseHeldInputs')).toHaveLength(1) + expect(f.native.state.closedChannels).toBe(1) + if (outcome === 'confirmed') expect(f.native.events).toEqual(['w:down', 'w:up', 'native-close']) + else { + expect(errors).toContainEqual(expect.objectContaining({ code: 'INPUT_CLEANUP_FAILED' })) + expect(f.agent.inbox.nextStep.some(message => message.source.kind === 'cua-inputs-released')).toBe(false) + } +}) + it.each(['agent', 'provider', 'context'] as const)('awaits native release when the %s is disposed after a completed turn', async (owner) => { const f = await setup([holdProgram], 'macos', undefined, true, true) await f.run() @@ -621,10 +705,14 @@ it('records release after a thinking pause so the resumed model sees the new inp thinking.resolve() await new Promise((resolve) => { options.signal?.addEventListener('abort', () => { resolve() }, { once: true }) }) } + const release = f.native.controlNext('releaseHeldInputs') + const notice = nextReleaseNotice(f) const running = f.run() await thinking.promise f.agent.cancel({ kind: 'user' }) - await running + await release.entered + release.reply() + await Promise.all([running, notice]) expect(f.native.held).toEqual([]) expect(f.agent.inbox.nextStep.some(message => message.source.kind === 'cua-inputs-released')).toBe(true) delete f.model.beforeStream @@ -642,9 +730,13 @@ it('removes a pending held reminder when a pause preserves the inbox', async () inserted.resolve() agent.cancel({ kind: 'user' }, { keepInbox: true }) }) + const release = f.native.controlNext('releaseHeldInputs') + const notice = nextReleaseNotice(f) const running = f.run() await inserted.promise - await running + await release.entered + release.reply() + await Promise.all([running, notice]) expect(f.agent.inbox.nextStep.map(message => message.source.kind)).toContain('cua-inputs-released') expect(f.agent.inbox.nextStep.map(message => message.source.kind)).not.toContain('cua-held-inputs') f.model.restart(['inspect("resumed")']) @@ -654,28 +746,6 @@ it('removes a pending held reminder when a pause preserves the inbox', async () expect(resumed).not.toContain('CUA inputs are still held') }) -it('drains an abnormal prior turn’s input before another program dispatches', async () => { - const f = await setup([holdProgram], 'macos', undefined, true, true) - await f.run() - expect(f.native.held).toHaveLength(1) - f.model.restart([]) - f.model.beforeStream = async () => { throw new Error('Model failed after the previous turn left a key held') } - const release = f.native.controlNext('releaseHeldInputs') - const failing = f.run() - await release.entered - let next: Promise | undefined - try { - expect(f.agent.session.snapshotEvents().at(-1)?.type).toBe('turn/end') - expect(f.native.held).toHaveLength(1) - delete f.model.beforeStream - f.model.restart([holdProgram]) - next = f.run() - expect(f.native.held).toHaveLength(1) - expect(f.native.events).toEqual(['w:down']) - } finally { release.reply(); await failing; await next } - expect(f.native.events).toEqual(['w:down', 'w:up', 'w:down']) -}) - it('drops a delayed held-state reminder after cancellation has already released the input', async () => { const f = await setup([holdProgram], 'macos', undefined, true, true) const post: PromiseWithResolvers = Promise.withResolvers() From c7d2a56ec51dabf711ad8233ef2edc1a7018f7e0 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 19 Nov 2026 17:51:10 +0800 Subject: [PATCH 53/73] Record cancellation timing and verify cleanup across turns --- apps/cli/tests/profiles/cua-mcp/expected/reference.md | 2 +- packages/experimental/cua/README.i18n.yaml | 4 ++-- packages/experimental/cua/README.md | 2 +- packages/experimental/cua/README.zh.md | 2 +- .../cua/tests/run-code-composition.spec.ts | 10 ++++++++-- snapshots/sdk/cua-run-code/system-prompt.expected.md | 2 +- snapshots/session/cua-native/system-prompt.expected.md | 2 +- snapshots/session/cua-ptc/system-prompt.expected.md | 2 +- .../session/cua-run-code-ptc/system-prompt.expected.md | 2 +- .../session/cua-run-code/system-prompt.expected.md | 2 +- 10 files changed, 18 insertions(+), 12 deletions(-) diff --git a/apps/cli/tests/profiles/cua-mcp/expected/reference.md b/apps/cli/tests/profiles/cua-mcp/expected/reference.md index 76eccd001e..769d817b35 100644 --- a/apps/cli/tests/profiles/cua-mcp/expected/reference.md +++ b/apps/cli/tests/profiles/cua-mcp/expected/reference.md @@ -53,7 +53,7 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. -Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. +Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. After a DSH stop, the next CUA operation waits for any pending cleanup. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index d4ae0b00e9..2bc0888b63 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -21,8 +21,8 @@ en: 3f638a4a76023fc5 zh: 515aeb5de6ae5b33 /deepseek-ai-dsh-cua/understand-the-implementation: - en: b8b48032f8efe0fc - zh: a5e8224efa433c59 + en: cf9d118b6080368b + zh: 70aa90a0b054dc9e /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 97aaa6cf4e..723c95e316 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -91,7 +91,7 @@ Permission responses identify their platform and report only the state that plat
Shared execution and platform ownership -Providers implementing `CuaBackend.heldInputState` accept `taskId` on explicit input and system pointer movement, report their connection-owned records through `getHeldInputs({ taskId })`, and acknowledge `releaseHeldInputs({ taskId })`. Native records own the actual key/button, target, process identity and input mode. Successful `run_code` and `cua_run_code` programs query those records and append a system reminder when input remains held; normal program and turn endings preserve input in both DSH and MCP. Reminders travel through logged additional context in DSH and through the tool response in MCP. macOS and Windows both implement this protocol. +Providers implementing `CuaBackend.heldInputState` accept `taskId` on explicit input and system pointer movement, report their connection-owned records through `getHeldInputs({ taskId })`, and acknowledge `releaseHeldInputs({ taskId })`. Native records own the actual key/button, target, process identity and input mode. Successful `run_code` and `cua_run_code` programs query those records and append a system reminder when input remains held; normal program and turn endings preserve input in both DSH and MCP. Reminders travel through logged additional context in DSH and through the tool response in MCP. macOS and Windows both implement this protocol. Capability methods remain static. Held input belongs to the task and native connection, outside program processes. A DSH stop or model failure starts cleanup. The Agent can finish the turn and resolve `whenIdle()` while the native release is pending. Subsequent CUA calls wait for its outcome. Confirmed release queues a notice for the model and removes pending held-state reminders. A cleanup failure is reported through `agent/error` and disables CUA for that task. A failed or cancelled program, an active MCP request receiving cancellation, an environment reset, and connection or provider disposal each await their own cleanup. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index ee5571f737..83f5de04dd 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -91,7 +91,7 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边
共享执行与平台职责 -实现 `CuaBackend.heldInputState` 的提供方为显式输入和系统指针移动接受 `taskId`,通过 `getHeldInputs({ taskId })` 报告本连接的持有记录,并确认 `releaseHeldInputs({ taskId })`。原生记录负责保存实际按键或按钮、目标、进程身份和输入方式。成功结束的 `run_code` 和 `cua_run_code` 查询这些记录,仍有输入按住时添加 system reminder;DSH 和 MCP 的正常程序结束和回合结束均保持输入。DSH 通过已记录的额外上下文传递提醒,MCP 通过工具响应传递。macOS 和 Windows 都实现了这套协议。 +实现 `CuaBackend.heldInputState` 的提供方为显式输入和系统指针移动接受 `taskId`,通过 `getHeldInputs({ taskId })` 报告本连接的持有记录,并确认 `releaseHeldInputs({ taskId })`。原生记录负责保存实际按键或按钮、目标、进程身份和输入方式。成功结束的 `run_code` 和 `cua_run_code` 查询这些记录,仍有输入按住时添加 system reminder;DSH 和 MCP 的正常程序结束和回合结束均保持输入。DSH 通过已记录的额外上下文传递提醒,MCP 通过工具响应传递。macOS 和 Windows 都实现了这套协议。能力方法列表保持静态。 持有输入属于任务和原生连接,保存在程序进程之外。DSH 收到停止请求或模型报错时启动清理。原生释放尚未确认时,Agent 可以结束回合,`whenIdle()` 也可以返回。后续 CUA 调用等待清理结果。确认释放后,DSH 为模型记录释放提醒,并撤销仍在队列中的旧持有提醒。清理失败会通过 `agent/error` 单独报告,并禁用该任务后续的 CUA 操作。程序失败或取消、执行中的 MCP 请求收到取消、环境重置、连接关闭和提供方卸载,各自等待清理完成。 diff --git a/packages/experimental/cua/tests/run-code-composition.spec.ts b/packages/experimental/cua/tests/run-code-composition.spec.ts index fbb4938efa..96d30a3947 100644 --- a/packages/experimental/cua/tests/run-code-composition.spec.ts +++ b/packages/experimental/cua/tests/run-code-composition.spec.ts @@ -446,9 +446,13 @@ it.each([ ] as const)('returns to idle after %s while new CUA input waits for cleanup (%s)', async (ending, outcome) => { const f = await setup([holdProgram], 'macos', undefined, true, true) const thinking: PromiseWithResolvers = Promise.withResolvers() + if (ending === 'model failure') { + await f.run() + f.model.restart([]) + } f.model.beforeStream = async (index, options) => { + if (ending === 'model failure') throw new Error('Model failed with W held from an earlier turn') if (index !== 1) return - if (ending === 'model failure') throw new Error('Model failed with W held') thinking.resolve() const signal = options.signal! await new Promise((resolve) => { signal.addEventListener('abort', () => { resolve() }, { once: true }) }) @@ -468,7 +472,7 @@ it.each([ await idle expect(f.native.held.map(press => press.key)).toEqual(['w']) expect(f.agent.inbox.nextStep.some(message => message.source.kind === 'cua-inputs-released')).toBe(false) - const terminal = f.agent.session.snapshotEvents().find(event => event.type === 'turn/end') + const terminal = f.agent.session.snapshotEvents().findLast(event => event.type === 'turn/end') expect(terminal?.data.reason.kind).toBe(ending === 'thinking stop' ? 'aborted' : 'error') const admitted: PromiseWithResolvers = Promise.withResolvers() @@ -735,6 +739,7 @@ it('removes a pending held reminder when a pause preserves the inbox', async () const running = f.run() await inserted.promise await release.entered + f.agent.inject(createUserMessage({ content: [{ type: 'text', text: 'Keep this pending instruction' }], source: { kind: 'user' } })) release.reply() await Promise.all([running, notice]) expect(f.agent.inbox.nextStep.map(message => message.source.kind)).toContain('cua-inputs-released') @@ -742,6 +747,7 @@ it('removes a pending held reminder when a pause preserves the inbox', async () f.model.restart(['inspect("resumed")']) await f.run() const resumed = JSON.stringify(f.model.requests[0]?.messages) + expect(resumed).toContain('Keep this pending instruction') expect(resumed).toContain('CUA inputs were released during cleanup') expect(resumed).not.toContain('CUA inputs are still held') }) diff --git a/snapshots/sdk/cua-run-code/system-prompt.expected.md b/snapshots/sdk/cua-run-code/system-prompt.expected.md index 8d54a03167..edf0466d15 100644 --- a/snapshots/sdk/cua-run-code/system-prompt.expected.md +++ b/snapshots/sdk/cua-run-code/system-prompt.expected.md @@ -87,7 +87,7 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. -Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. +Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. After a DSH stop, the next CUA operation waits for any pending cleanup. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/snapshots/session/cua-native/system-prompt.expected.md b/snapshots/session/cua-native/system-prompt.expected.md index 9fe44655d6..086fc4d026 100644 --- a/snapshots/session/cua-native/system-prompt.expected.md +++ b/snapshots/session/cua-native/system-prompt.expected.md @@ -90,7 +90,7 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. -Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. +Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. After a DSH stop, the next CUA operation waits for any pending cleanup. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index 0a0eab2d43..f84c97ed70 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -92,7 +92,7 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. -Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. +Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. After a DSH stop, the next CUA operation waits for any pending cleanup. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/snapshots/session/cua-run-code-ptc/system-prompt.expected.md b/snapshots/session/cua-run-code-ptc/system-prompt.expected.md index 28dfdd4e01..80f4b27e6c 100644 --- a/snapshots/session/cua-run-code-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-run-code-ptc/system-prompt.expected.md @@ -88,7 +88,7 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. -Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. +Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. After a DSH stop, the next CUA operation waits for any pending cleanup. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/snapshots/session/cua-run-code/system-prompt.expected.md b/snapshots/session/cua-run-code/system-prompt.expected.md index 581d8faa76..1e37589a04 100644 --- a/snapshots/session/cua-run-code/system-prompt.expected.md +++ b/snapshots/session/cua-run-code/system-prompt.expected.md @@ -86,7 +86,7 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. -Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. +Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. After a DSH stop, the next CUA operation waits for any pending cleanup. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. From d700af6b52f9ec99cea7192c9ebab45612b34b21 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 19 Nov 2026 17:53:53 +0800 Subject: [PATCH 54/73] Observe actual native disposal through its cleanup registration --- .../cua/tests/run-code-composition.spec.ts | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/packages/experimental/cua/tests/run-code-composition.spec.ts b/packages/experimental/cua/tests/run-code-composition.spec.ts index 96d30a3947..0f06725234 100644 --- a/packages/experimental/cua/tests/run-code-composition.spec.ts +++ b/packages/experimental/cua/tests/run-code-composition.spec.ts @@ -580,19 +580,17 @@ it.each(['confirmed', 'refused'] as const)('joins background cleanup on concurre f.model.beforeStream = async (index) => { if (index === 1) throw new Error('Model failed') } const errors: unknown[] = [] f.ctx.on('agent/error', ({ error }) => { errors.push(error) }) + const registered = vi.spyOn(NativeClient.prototype, 'registerCleanup') + onTestFinished(() => { registered.mockRestore() }) const release = f.native.controlNext('releaseHeldInputs') const idle = f.run() await release.entered await idle const entered: PromiseWithResolvers = Promise.withResolvers() - const dispose = NativeClient.prototype.dispose - const spy = vi.spyOn(NativeClient.prototype, 'dispose').mockImplementation(function (this: NativeClient) { - const closing = dispose.call(this) - entered.resolve() - return closing - }) - onTestFinished(() => { spy.mockRestore() }) + const [client] = registered.mock.contexts + if (!(client instanceof NativeClient)) throw new Error('Expected a native connection with a registered input owner') + client.registerCleanup(async () => { entered.resolve() }) let disposed = false const closing = f.provider.dispose().then(() => { disposed = true }) try { From 034143c24a9815b9a86c5cedc9d3c7e44135505f Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 19 Nov 2026 18:06:02 +0800 Subject: [PATCH 55/73] Reproduce obsolete held reminders from a single tool batch --- .../cua/tests/run-code-composition.spec.ts | 39 +++++++++++++++---- 1 file changed, 31 insertions(+), 8 deletions(-) diff --git a/packages/experimental/cua/tests/run-code-composition.spec.ts b/packages/experimental/cua/tests/run-code-composition.spec.ts index 0f06725234..b8d4f4d0d8 100644 --- a/packages/experimental/cua/tests/run-code-composition.spec.ts +++ b/packages/experimental/cua/tests/run-code-composition.spec.ts @@ -40,26 +40,32 @@ const programs = [ 'await win.click("0")', ] +type ProgramStep = string | readonly string[] + class ProgramModel extends LlmAdapter { readonly requests: GenerateOptions[] = [] toolName = 'cua_run_code' beforeStream?: (index: number, options: GenerateOptions) => Promise /** Requests a test holds back until it has finished acting between two model steps. */ readonly gates = new Map>() - constructor(private programs: readonly string[]) { super() } - restart(programs: readonly string[]): void { this.programs = programs; this.requests.length = 0 } + constructor(private programs: readonly ProgramStep[]) { super() } + restart(programs: readonly ProgramStep[]): void { this.programs = programs; this.requests.length = 0 } override resolveModel(provider: string, model: string): Promise { return Promise.resolve({ provider, id: model, name: model, inputModalities: ['text', 'image'] }) } async * stream(options: GenerateOptions): AsyncIterable { await this.beforeStream?.(this.requests.length, options) await this.gates.get(this.requests.length) - const code = this.programs[this.requests.length] + const step = this.programs[this.requests.length] this.requests.push(options) - if (code !== undefined) { - yield { type: 'block-start', index: 0, blockType: 'tool-call' } - yield { type: 'block-end', index: 0, block: { type: 'tool-call', id: brandString(`cua-program-${this.requests.length}`), - name: this.toolName, arguments: JSON.stringify({ code, description: 'Inspect and increment the fixture counter' }) } } + if (step !== undefined) { + const codes = typeof step === 'string' ? [step] : step + for (const [index, code] of codes.entries()) { + const id = brandString(`cua-program-${this.requests.length}${index === 0 ? '' : `-${index}`}`) + yield { type: 'block-start', index, blockType: 'tool-call' } + yield { type: 'block-end', index, block: { type: 'tool-call', id, name: this.toolName, + arguments: JSON.stringify({ code, description: 'Inspect and increment the fixture counter' }) } } + } yield { type: 'finish', reason: { kind: 'tool-calls' } } return } @@ -69,7 +75,7 @@ class ProgramModel extends LlmAdapter { } } -async function setup(programs: readonly string[], platform = 'macos', selectorPid?: number, presetFree = false, heldInputState = false, timeoutMs = 30_000, disposeNative?: (state: { closedChannels: number }) => Promise) { +async function setup(programs: readonly ProgramStep[], platform = 'macos', selectorPid?: number, presetFree = false, heldInputState = false, timeoutMs = 30_000, disposeNative?: (state: { closedChannels: number }) => Promise) { const directory = await mkdtemp(join(tmpdir(), 'dsh-cua-run-code-')) const ctx = new Context() onTestFinished(async () => { @@ -384,6 +390,23 @@ it('reports native held input after programs, keeps it across turns, and stops r expect(reminders(f.agent)).toHaveLength(2) }) +it.each([false, true])('delivers only the final held state from a model tool batch (D held: %s)', async (holdD) => { + const second = 'await app.sendKeyEvent("w", "up")' + (holdD ? '; await app.sendKeyEvent("d", "down")' : '') + const f = await setup([[holdProgram, second]], 'macos', undefined, true, true) + await f.run() + expect(f.native.events).toEqual(holdD ? ['w:down', 'w:up', 'd:down'] : ['w:down', 'w:up']) + expect(f.native.calls.filter(call => call.method === 'getHeldInputs')).toHaveLength(2) + expect(f.model.requests).toHaveLength(2) + const shown = f.model.requests[1]!.messages.map(message => JSON.stringify(message)) + .filter(message => message.includes('CUA inputs are still held:')) + expect(shown).toHaveLength(holdD ? 1 : 0) + expect(reminders(f.agent)).toHaveLength(shown.length) + if (holdD) { + expect(reminders(f.agent)[0]).toContain('Key "d"') + expect(reminders(f.agent)[0]).not.toContain('Key "w"') + } +}) + it('reports the Windows keyboard window and desktop input mode and supports a later explicit up', async () => { const f = await setup([holdWindowProgram], 'windows', undefined, true, true) await f.run() From fe0f9960e81072ebbb7bf5e44890c415bd7c41c3 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 19 Nov 2026 18:07:18 +0800 Subject: [PATCH 56/73] Supersede undelivered CUA notices on every held-state query --- packages/experimental/cua/README.i18n.yaml | 4 +-- packages/experimental/cua/README.md | 2 +- packages/experimental/cua/README.zh.md | 2 +- packages/experimental/cua/src/held-inputs.ts | 33 +++++++++++++------- 4 files changed, 25 insertions(+), 16 deletions(-) diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index 2bc0888b63..30b56a371c 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -21,8 +21,8 @@ en: 3f638a4a76023fc5 zh: 515aeb5de6ae5b33 /deepseek-ai-dsh-cua/understand-the-implementation: - en: cf9d118b6080368b - zh: 70aa90a0b054dc9e + en: f691467605a7eccb + zh: da0e7fbcfc654fc9 /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 723c95e316..8aa6f366aa 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -91,7 +91,7 @@ Permission responses identify their platform and report only the state that plat
Shared execution and platform ownership -Providers implementing `CuaBackend.heldInputState` accept `taskId` on explicit input and system pointer movement, report their connection-owned records through `getHeldInputs({ taskId })`, and acknowledge `releaseHeldInputs({ taskId })`. Native records own the actual key/button, target, process identity and input mode. Successful `run_code` and `cua_run_code` programs query those records and append a system reminder when input remains held; normal program and turn endings preserve input in both DSH and MCP. Reminders travel through logged additional context in DSH and through the tool response in MCP. macOS and Windows both implement this protocol. Capability methods remain static. +Providers implementing `CuaBackend.heldInputState` accept `taskId` on explicit input and system pointer movement, report their connection-owned records through `getHeldInputs({ taskId })`, and acknowledge `releaseHeldInputs({ taskId })`. Native records own the actual key/button, target, process identity and input mode. Successful `run_code` and `cua_run_code` programs query those records and append a system reminder when input remains held; normal program and turn endings preserve input in both DSH and MCP. DSH delivers the latest pending held-input reminder with the next model request. A later program in the same tool batch supersedes the earlier result, including when it releases all input. MCP returns the state in each program response. macOS and Windows both implement this protocol. Capability methods remain static. Held input belongs to the task and native connection, outside program processes. A DSH stop or model failure starts cleanup. The Agent can finish the turn and resolve `whenIdle()` while the native release is pending. Subsequent CUA calls wait for its outcome. Confirmed release queues a notice for the model and removes pending held-state reminders. A cleanup failure is reported through `agent/error` and disables CUA for that task. A failed or cancelled program, an active MCP request receiving cancellation, an environment reset, and connection or provider disposal each await their own cleanup. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index 83f5de04dd..bd3768ec77 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -91,7 +91,7 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边
共享执行与平台职责 -实现 `CuaBackend.heldInputState` 的提供方为显式输入和系统指针移动接受 `taskId`,通过 `getHeldInputs({ taskId })` 报告本连接的持有记录,并确认 `releaseHeldInputs({ taskId })`。原生记录负责保存实际按键或按钮、目标、进程身份和输入方式。成功结束的 `run_code` 和 `cua_run_code` 查询这些记录,仍有输入按住时添加 system reminder;DSH 和 MCP 的正常程序结束和回合结束均保持输入。DSH 通过已记录的额外上下文传递提醒,MCP 通过工具响应传递。macOS 和 Windows 都实现了这套协议。能力方法列表保持静态。 +实现 `CuaBackend.heldInputState` 的提供方为显式输入和系统指针移动接受 `taskId`,通过 `getHeldInputs({ taskId })` 报告本连接的持有记录,并确认 `releaseHeldInputs({ taskId })`。原生记录负责保存实际按键或按钮、目标、进程身份和输入方式。成功结束的 `run_code` 和 `cua_run_code` 查询这些记录,仍有输入按住时添加 system reminder;DSH 和 MCP 的正常程序结束和回合结束均保持输入。DSH 在下一次模型请求中只传递最新的待交付持有提醒。同一批中的后续程序松开全部输入后,这一批不会向模型报告仍有输入按住。MCP 在每次程序响应中返回当时的状态。macOS 和 Windows 都实现了这套协议。能力方法列表保持静态。 持有输入属于任务和原生连接,保存在程序进程之外。DSH 收到停止请求或模型报错时启动清理。原生释放尚未确认时,Agent 可以结束回合,`whenIdle()` 也可以返回。后续 CUA 调用等待清理结果。确认释放后,DSH 为模型记录释放提醒,并撤销仍在队列中的旧持有提醒。清理失败会通过 `agent/error` 单独报告,并禁用该任务后续的 CUA 操作。程序失败或取消、执行中的 MCP 请求收到取消、环境重置、连接关闭和提供方卸载,各自等待清理完成。 diff --git a/packages/experimental/cua/src/held-inputs.ts b/packages/experimental/cua/src/held-inputs.ts index 0f424bb19c..944c864730 100644 --- a/packages/experimental/cua/src/held-inputs.ts +++ b/packages/experimental/cua/src/held-inputs.ts @@ -1,7 +1,7 @@ /** Native-owned held input, program-end reminders, and failure/cancellation cleanup. */ import type { Context } from '@deepseek-ai/cordis' import { emitAgentEvent, type Agent } from '@deepseek-ai/dsh-agent' -import { createUserMessage } from '@deepseek-ai/dsh-llm' +import { createUserMessage, type MessageId, type UserMessage } from '@deepseek-ai/dsh-llm' import { RUN_CODE_NAME } from '@deepseek-ai/dsh-tools' import { z } from 'zod' import { NativeError, type NativeClient } from './native-client.ts' @@ -24,7 +24,15 @@ function renderInputs(inputs: z.infer, state: 'held' | 'relea ''].join('\n') } +function discardQueuedHeldNotices(agent: Agent): void { + for (const message of [...agent.inbox.nextStep, ...agent.inbox.nextTurn]) { + if (message.source.kind === 'cua-held-inputs') agent.inbox.remove(message.id) + } +} + class InputOwner { + // Batch delivery can enqueue this notice after another program has queried a newer state. + latestHeldNotice: MessageId | undefined readonly controller = new AbortController() private client: NativeClient | undefined private removeCleanup: (() => void) | undefined @@ -42,9 +50,11 @@ class InputOwner { this.client = client } - async reminder(inTurn: boolean): Promise { + async reminder(inTurn: boolean): Promise { if (this.closing || !this.client) return const inputs = heldInputs.parse(await this.client.request('getHeldInputs', { taskId: this.agent.id }, this.controller.signal)) + discardQueuedHeldNotices(this.agent) + this.latestHeldNotice = undefined if (inputs.length === 0) { this.removeCleanup?.() this.removeCleanup = undefined @@ -52,11 +62,15 @@ class InputOwner { return } this.notifySessionOnRelease ||= inTurn - return renderInputs(inputs, 'held') + const notice = createUserMessage({ content: [{ type: 'text', text: renderInputs(inputs, 'held') }], + source: { kind: 'cua-held-inputs', form: 'notice', summary: 'CUA inputs remain held' } }) + this.latestHeldNotice = notice.id + return notice } close(canRequest = true): Promise> { + this.latestHeldNotice = undefined this.controller.abort() return this.closing ??= Promise.resolve().then(async () => { try { @@ -108,9 +122,7 @@ export class CuaHeldInputs { emitAgentEvent(this.ctx, agent, 'agent/error', { turn: this.ctx.agents.turnBoundaryOf(agent.session).lastTurn, step: 0, error }) }, (inputs) => { try { - for (const message of [...agent.inbox.nextStep, ...agent.inbox.nextTurn]) { - if (message.source.kind === 'cua-held-inputs') agent.inbox.remove(message.id) - } + discardQueuedHeldNotices(agent) if (inputs.length === 0) return agent.inject(createUserMessage({ content: [{ type: 'text', text: renderInputs(inputs, 'released') }], @@ -169,16 +181,13 @@ export class CuaHeldInputs { } else if (execution.parent === undefined) { const owner = this.owners.get(agent) const inTurn = ctx.agents.turnBoundaryOf(agent.session).openTurnStartSeq !== null - const text = await owner?.reminder(inTurn).catch(async (error: unknown) => { + const notice = await owner?.reminder(inTurn).catch(async (error: unknown) => { await releaseAfter(signal.aborted ? 'Program cancelled' : `Held-input query failed: ${String(error)}`) throw error }) // oxlint-disable-next-line typescript/no-unnecessary-condition -- Cancellation can arrive while the native state query awaits. if (signal.aborted) { await releaseAfter('Program cancelled'); return result } - if (text && !owner?.closing) return { ...result, additionalContexts: [...result.additionalContexts ?? [], - createUserMessage({ content: [{ type: 'text', text }], - source: { kind: 'cua-held-inputs', form: 'notice', summary: 'CUA inputs remain held' } }), - ] } + if (notice && !owner?.closing) return { ...result, additionalContexts: [...result.additionalContexts ?? [], notice] } } return result } finally { @@ -198,7 +207,7 @@ export class CuaHeldInputs { }) yield ctx.on('agent/inbox/inserted', ({ agent, message }) => { // This live notification runs after append publication, so removal can safely write its own event. - if (message.source.kind === 'cua-held-inputs' && this.owners.get(agent)?.closing) agent.inbox.remove(message.id) + if (message.source.kind === 'cua-held-inputs' && message.id !== this.owners.get(agent)?.latestHeldNotice) agent.inbox.remove(message.id) }, { prepend: true }) yield ctx.on('session/event', (session, event) => { if (event.type !== 'turn/end') return From bfe2b3296165955cd22e1a2cb63d29efa5bf5172 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 19 Nov 2026 18:11:16 +0800 Subject: [PATCH 57/73] Record explicit release within a single CUA tool batch --- .../cua-run-code-scoped/session.v4.jsonl | 22 +++++++++++++------ 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/snapshots/session/cua-run-code-scoped/session.v4.jsonl b/snapshots/session/cua-run-code-scoped/session.v4.jsonl index 1052c75c7e..7b595719ce 100644 --- a/snapshots/session/cua-run-code-scoped/session.v4.jsonl +++ b/snapshots/session/cua-run-code-scoped/session.v4.jsonl @@ -3,18 +3,18 @@ {"type":"permission/preset","data":{"preset":"danger-full-access"}} {"type":"sandbox/mode","data":{"mode":"danger-full-access"}} {"type":"approval/policy","data":{"policy":"never"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Use cua_run_code to select test.fixture, retain its application and window objects, click Increment, and capture the window. In a second call reuse those objects and a retained counter, increment again, and report the observed count and available program tools."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Use cua_run_code to select test.fixture, retain its application and window objects, click Increment, and capture the window. In a second call reuse those objects and a retained counter, increment again, and report the observed count and available program tools. In the first batch, hold W and release it in a separate program before resuming."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"}]}} {"type":"turn/start","data":{"turn":1}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Use cua_run_code to select test.fixture, retain its application and window objects, click Increment, and capture the window. In a second call reuse those objects and a retained counter, increment again, and report the observed count and available program tools."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Use cua_run_code to select test.fixture, retain its application and window objects, click Increment, and capture the window. In a second call reuse those objects and a retained counter, increment again, and report the observed count and available program tools. In the first batch, hold W and release it in a separate program before resuming."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} {"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 cua_run_code to select test.fixture,","messageSeqs":[9],"source":{"kind":"fallback"}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"stream":[{"type":"chunk","time":1794291763110,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794291763110,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}}},{"type":"chunk","time":1794291763110,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot); await app.sendKeyEvent(\\\"w\\\", \\\"down\\\")\",\"description\":\"Select and capture the fixture window\"}"},{"type":"tool-call","id":"cua_release","name":"cua_run_code","arguments":"{\"code\":\"await app.sendKeyEvent(\\\"w\\\", \\\"up\\\")\",\"description\":\"Release W in the same tool batch\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"stream":[{"type":"chunk","time":1795082961728,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1795082961728,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot); await app.sendKeyEvent(\\\"w\\\", \\\"down\\\")\",\"description\":\"Select and capture the fixture window\"}"}}},{"type":"chunk","time":1795082961728,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}},{"type":"chunk","time":1795082961728,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"cua_release","name":"cua_run_code","arguments":"{\"code\":\"await app.sendKeyEvent(\\\"w\\\", \\\"up\\\")\",\"description\":\"Release W in the same tool batch\"}"}}},{"type":"chunk","time":1795082961728,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot); await app.sendKeyEvent(\\\"w\\\", \\\"down\\\")\",\"description\":\"Select and capture the fixture window\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemPointer\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\",\"sendKeyEvent\",\"toggleMouse\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}}}} @@ -25,10 +25,18 @@ {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:4","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-1","elementId":"0"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:5","name":"cua","arguments":{"method":"screenshot","params":{"appHandle":"fixture-app","windowId":"7"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:5","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_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:6","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"w","direction":"down"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:6","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"w","direction":"down"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"cua_first"},"toolCallId":"cua_first","content":[{"type":"text","text":"{\"visits\":1,\"bindings\":[\"cua\"],\"app\":\"fixture-app\",\"window\":\"7\"}\n"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[15],"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua_release","name":"cua_run_code","arguments":"{\"code\":\"await app.sendKeyEvent(\\\"w\\\", \\\"up\\\")\",\"description\":\"Release W in the same tool batch\"}"}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_release","parentCallId":"cua_release","subCallId":"cua_release:ptc:1","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"w","direction":"up"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_release","parentCallId":"cua_release","subCallId":"cua_release:ptc:1","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"w","direction":"up"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"cua_release"},"toolCallId":"cua_release","content":[{"type":"text","text":"(cua_run_code completed with no output)"}],"isError":false,"id":"{{message:6}}"}},"sourceEventSeqs":[29],"surfaceOp":"append"} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"\nCUA inputs are still held:\n- Key \"w\", appHandle \"fixture-app\" (application input).\nThey remain pressed across programs and turns. Release them explicitly with sendKeyEvent(key, 'up') or toggleMouse(button, 'up') on the same target when no longer needed.\n"}],"source":{"kind":"cua-held-inputs","form":"notice","summary":"CUA inputs remain held"},"role":"user","id":"{{message:7}}"}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[],"outcome":"canceled"}} {"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_reuse","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\",\"description\":\"Reuse the retained application and window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:6}}"},"stream":[{"type":"chunk","time":1794291763317,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794291763317,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_reuse","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\",\"description\":\"Reuse the retained application and window\"}"}}},{"type":"chunk","time":1794291763317,"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_reuse","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\",\"description\":\"Reuse the retained application and window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:8}}"},"stream":[{"type":"chunk","time":1795082962045,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1795082962045,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_reuse","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\",\"description\":\"Reuse the retained application and window\"}"}}},{"type":"chunk","time":1795082962045,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"cua_reuse","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\",\"description\":\"Reuse the retained application and window\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:1","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:1","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"snapshotId\":\"fixture-snapshot-2\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 1\\\"\",\"windows\":[{\"windowId\":\"7\",\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} @@ -36,9 +44,9 @@ {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:2","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-2","elementId":"0"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:3","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:3","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"snapshotId\":\"fixture-snapshot-3\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 2\\\"\",\"windows\":[{\"windowId\":\"7\",\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} -{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"cua_reuse"},"toolCallId":"cua_reuse","content":[{"type":"text","text":"{\"visits\":2,\"app\":\"fixture-app\",\"window\":\"7\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 2\\\"\",\"bindings\":[\"cua\"]}\n"}],"isError":false,"id":"{{message:7}}"}},"sourceEventSeqs":[30],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"cua_reuse"},"toolCallId":"cua_reuse","content":[{"type":"text","text":"{\"visits\":2,\"app\":\"fixture-app\",\"window\":\"7\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 2\\\"\",\"bindings\":[\"cua\"]}\n"}],"isError":false,"id":"{{message:9}}"}},"sourceEventSeqs":[38],"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":"text","text":"The retained application and window report Count: 2. The counter persisted across calls, and the program exposes only tools.cua. The screenshot was attached after the first call."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:8}}"},"stream":[{"type":"chunk","time":1794291763343,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1794291763343,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"The retained application and window report Count: 2. The counter persisted across calls, and the program exposes only tools.cua. The screenshot was attached after the first call."}}},{"type":"chunk","time":1794291763343,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"text","text":"The retained application and window report Count: 2. The counter persisted across calls, and the program exposes only tools.cua. The screenshot was attached after the first call."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:10}}"},"stream":[{"type":"chunk","time":1795082962071,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1795082962071,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"The retained application and window report Count: 2. The counter persisted across calls, and the program exposes only tools.cua. The screenshot was attached after the first call."}}},{"type":"chunk","time":1795082962071,"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"}}} From c452b982420fe5218a27c699fad6c97ec753a3a3 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 19 Nov 2026 21:20:45 +0800 Subject: [PATCH 58/73] Drop same-batch CUA reminder coalescing from this change --- packages/experimental/cua/README.i18n.yaml | 4 +- packages/experimental/cua/README.md | 2 +- packages/experimental/cua/README.zh.md | 2 +- packages/experimental/cua/src/held-inputs.ts | 33 ++++++---------- .../cua/tests/run-code-composition.spec.ts | 39 ++++--------------- .../cua-run-code-scoped/session.v4.jsonl | 22 ++++------- 6 files changed, 31 insertions(+), 71 deletions(-) diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index 30b56a371c..2bc0888b63 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -21,8 +21,8 @@ en: 3f638a4a76023fc5 zh: 515aeb5de6ae5b33 /deepseek-ai-dsh-cua/understand-the-implementation: - en: f691467605a7eccb - zh: da0e7fbcfc654fc9 + en: cf9d118b6080368b + zh: 70aa90a0b054dc9e /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 8aa6f366aa..723c95e316 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -91,7 +91,7 @@ Permission responses identify their platform and report only the state that plat
Shared execution and platform ownership -Providers implementing `CuaBackend.heldInputState` accept `taskId` on explicit input and system pointer movement, report their connection-owned records through `getHeldInputs({ taskId })`, and acknowledge `releaseHeldInputs({ taskId })`. Native records own the actual key/button, target, process identity and input mode. Successful `run_code` and `cua_run_code` programs query those records and append a system reminder when input remains held; normal program and turn endings preserve input in both DSH and MCP. DSH delivers the latest pending held-input reminder with the next model request. A later program in the same tool batch supersedes the earlier result, including when it releases all input. MCP returns the state in each program response. macOS and Windows both implement this protocol. Capability methods remain static. +Providers implementing `CuaBackend.heldInputState` accept `taskId` on explicit input and system pointer movement, report their connection-owned records through `getHeldInputs({ taskId })`, and acknowledge `releaseHeldInputs({ taskId })`. Native records own the actual key/button, target, process identity and input mode. Successful `run_code` and `cua_run_code` programs query those records and append a system reminder when input remains held; normal program and turn endings preserve input in both DSH and MCP. Reminders travel through logged additional context in DSH and through the tool response in MCP. macOS and Windows both implement this protocol. Capability methods remain static. Held input belongs to the task and native connection, outside program processes. A DSH stop or model failure starts cleanup. The Agent can finish the turn and resolve `whenIdle()` while the native release is pending. Subsequent CUA calls wait for its outcome. Confirmed release queues a notice for the model and removes pending held-state reminders. A cleanup failure is reported through `agent/error` and disables CUA for that task. A failed or cancelled program, an active MCP request receiving cancellation, an environment reset, and connection or provider disposal each await their own cleanup. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index bd3768ec77..83f5de04dd 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -91,7 +91,7 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边
共享执行与平台职责 -实现 `CuaBackend.heldInputState` 的提供方为显式输入和系统指针移动接受 `taskId`,通过 `getHeldInputs({ taskId })` 报告本连接的持有记录,并确认 `releaseHeldInputs({ taskId })`。原生记录负责保存实际按键或按钮、目标、进程身份和输入方式。成功结束的 `run_code` 和 `cua_run_code` 查询这些记录,仍有输入按住时添加 system reminder;DSH 和 MCP 的正常程序结束和回合结束均保持输入。DSH 在下一次模型请求中只传递最新的待交付持有提醒。同一批中的后续程序松开全部输入后,这一批不会向模型报告仍有输入按住。MCP 在每次程序响应中返回当时的状态。macOS 和 Windows 都实现了这套协议。能力方法列表保持静态。 +实现 `CuaBackend.heldInputState` 的提供方为显式输入和系统指针移动接受 `taskId`,通过 `getHeldInputs({ taskId })` 报告本连接的持有记录,并确认 `releaseHeldInputs({ taskId })`。原生记录负责保存实际按键或按钮、目标、进程身份和输入方式。成功结束的 `run_code` 和 `cua_run_code` 查询这些记录,仍有输入按住时添加 system reminder;DSH 和 MCP 的正常程序结束和回合结束均保持输入。DSH 通过已记录的额外上下文传递提醒,MCP 通过工具响应传递。macOS 和 Windows 都实现了这套协议。能力方法列表保持静态。 持有输入属于任务和原生连接,保存在程序进程之外。DSH 收到停止请求或模型报错时启动清理。原生释放尚未确认时,Agent 可以结束回合,`whenIdle()` 也可以返回。后续 CUA 调用等待清理结果。确认释放后,DSH 为模型记录释放提醒,并撤销仍在队列中的旧持有提醒。清理失败会通过 `agent/error` 单独报告,并禁用该任务后续的 CUA 操作。程序失败或取消、执行中的 MCP 请求收到取消、环境重置、连接关闭和提供方卸载,各自等待清理完成。 diff --git a/packages/experimental/cua/src/held-inputs.ts b/packages/experimental/cua/src/held-inputs.ts index 944c864730..0f424bb19c 100644 --- a/packages/experimental/cua/src/held-inputs.ts +++ b/packages/experimental/cua/src/held-inputs.ts @@ -1,7 +1,7 @@ /** Native-owned held input, program-end reminders, and failure/cancellation cleanup. */ import type { Context } from '@deepseek-ai/cordis' import { emitAgentEvent, type Agent } from '@deepseek-ai/dsh-agent' -import { createUserMessage, type MessageId, type UserMessage } from '@deepseek-ai/dsh-llm' +import { createUserMessage } from '@deepseek-ai/dsh-llm' import { RUN_CODE_NAME } from '@deepseek-ai/dsh-tools' import { z } from 'zod' import { NativeError, type NativeClient } from './native-client.ts' @@ -24,15 +24,7 @@ function renderInputs(inputs: z.infer, state: 'held' | 'relea ''].join('\n') } -function discardQueuedHeldNotices(agent: Agent): void { - for (const message of [...agent.inbox.nextStep, ...agent.inbox.nextTurn]) { - if (message.source.kind === 'cua-held-inputs') agent.inbox.remove(message.id) - } -} - class InputOwner { - // Batch delivery can enqueue this notice after another program has queried a newer state. - latestHeldNotice: MessageId | undefined readonly controller = new AbortController() private client: NativeClient | undefined private removeCleanup: (() => void) | undefined @@ -50,11 +42,9 @@ class InputOwner { this.client = client } - async reminder(inTurn: boolean): Promise { + async reminder(inTurn: boolean): Promise { if (this.closing || !this.client) return const inputs = heldInputs.parse(await this.client.request('getHeldInputs', { taskId: this.agent.id }, this.controller.signal)) - discardQueuedHeldNotices(this.agent) - this.latestHeldNotice = undefined if (inputs.length === 0) { this.removeCleanup?.() this.removeCleanup = undefined @@ -62,15 +52,11 @@ class InputOwner { return } this.notifySessionOnRelease ||= inTurn - const notice = createUserMessage({ content: [{ type: 'text', text: renderInputs(inputs, 'held') }], - source: { kind: 'cua-held-inputs', form: 'notice', summary: 'CUA inputs remain held' } }) - this.latestHeldNotice = notice.id - return notice + return renderInputs(inputs, 'held') } close(canRequest = true): Promise> { - this.latestHeldNotice = undefined this.controller.abort() return this.closing ??= Promise.resolve().then(async () => { try { @@ -122,7 +108,9 @@ export class CuaHeldInputs { emitAgentEvent(this.ctx, agent, 'agent/error', { turn: this.ctx.agents.turnBoundaryOf(agent.session).lastTurn, step: 0, error }) }, (inputs) => { try { - discardQueuedHeldNotices(agent) + for (const message of [...agent.inbox.nextStep, ...agent.inbox.nextTurn]) { + if (message.source.kind === 'cua-held-inputs') agent.inbox.remove(message.id) + } if (inputs.length === 0) return agent.inject(createUserMessage({ content: [{ type: 'text', text: renderInputs(inputs, 'released') }], @@ -181,13 +169,16 @@ export class CuaHeldInputs { } else if (execution.parent === undefined) { const owner = this.owners.get(agent) const inTurn = ctx.agents.turnBoundaryOf(agent.session).openTurnStartSeq !== null - const notice = await owner?.reminder(inTurn).catch(async (error: unknown) => { + const text = await owner?.reminder(inTurn).catch(async (error: unknown) => { await releaseAfter(signal.aborted ? 'Program cancelled' : `Held-input query failed: ${String(error)}`) throw error }) // oxlint-disable-next-line typescript/no-unnecessary-condition -- Cancellation can arrive while the native state query awaits. if (signal.aborted) { await releaseAfter('Program cancelled'); return result } - if (notice && !owner?.closing) return { ...result, additionalContexts: [...result.additionalContexts ?? [], notice] } + if (text && !owner?.closing) return { ...result, additionalContexts: [...result.additionalContexts ?? [], + createUserMessage({ content: [{ type: 'text', text }], + source: { kind: 'cua-held-inputs', form: 'notice', summary: 'CUA inputs remain held' } }), + ] } } return result } finally { @@ -207,7 +198,7 @@ export class CuaHeldInputs { }) yield ctx.on('agent/inbox/inserted', ({ agent, message }) => { // This live notification runs after append publication, so removal can safely write its own event. - if (message.source.kind === 'cua-held-inputs' && message.id !== this.owners.get(agent)?.latestHeldNotice) agent.inbox.remove(message.id) + if (message.source.kind === 'cua-held-inputs' && this.owners.get(agent)?.closing) agent.inbox.remove(message.id) }, { prepend: true }) yield ctx.on('session/event', (session, event) => { if (event.type !== 'turn/end') return diff --git a/packages/experimental/cua/tests/run-code-composition.spec.ts b/packages/experimental/cua/tests/run-code-composition.spec.ts index b8d4f4d0d8..0f06725234 100644 --- a/packages/experimental/cua/tests/run-code-composition.spec.ts +++ b/packages/experimental/cua/tests/run-code-composition.spec.ts @@ -40,32 +40,26 @@ const programs = [ 'await win.click("0")', ] -type ProgramStep = string | readonly string[] - class ProgramModel extends LlmAdapter { readonly requests: GenerateOptions[] = [] toolName = 'cua_run_code' beforeStream?: (index: number, options: GenerateOptions) => Promise /** Requests a test holds back until it has finished acting between two model steps. */ readonly gates = new Map>() - constructor(private programs: readonly ProgramStep[]) { super() } - restart(programs: readonly ProgramStep[]): void { this.programs = programs; this.requests.length = 0 } + constructor(private programs: readonly string[]) { super() } + restart(programs: readonly string[]): void { this.programs = programs; this.requests.length = 0 } override resolveModel(provider: string, model: string): Promise { return Promise.resolve({ provider, id: model, name: model, inputModalities: ['text', 'image'] }) } async * stream(options: GenerateOptions): AsyncIterable { await this.beforeStream?.(this.requests.length, options) await this.gates.get(this.requests.length) - const step = this.programs[this.requests.length] + const code = this.programs[this.requests.length] this.requests.push(options) - if (step !== undefined) { - const codes = typeof step === 'string' ? [step] : step - for (const [index, code] of codes.entries()) { - const id = brandString(`cua-program-${this.requests.length}${index === 0 ? '' : `-${index}`}`) - yield { type: 'block-start', index, blockType: 'tool-call' } - yield { type: 'block-end', index, block: { type: 'tool-call', id, name: this.toolName, - arguments: JSON.stringify({ code, description: 'Inspect and increment the fixture counter' }) } } - } + if (code !== undefined) { + yield { type: 'block-start', index: 0, blockType: 'tool-call' } + yield { type: 'block-end', index: 0, block: { type: 'tool-call', id: brandString(`cua-program-${this.requests.length}`), + name: this.toolName, arguments: JSON.stringify({ code, description: 'Inspect and increment the fixture counter' }) } } yield { type: 'finish', reason: { kind: 'tool-calls' } } return } @@ -75,7 +69,7 @@ class ProgramModel extends LlmAdapter { } } -async function setup(programs: readonly ProgramStep[], platform = 'macos', selectorPid?: number, presetFree = false, heldInputState = false, timeoutMs = 30_000, disposeNative?: (state: { closedChannels: number }) => Promise) { +async function setup(programs: readonly string[], platform = 'macos', selectorPid?: number, presetFree = false, heldInputState = false, timeoutMs = 30_000, disposeNative?: (state: { closedChannels: number }) => Promise) { const directory = await mkdtemp(join(tmpdir(), 'dsh-cua-run-code-')) const ctx = new Context() onTestFinished(async () => { @@ -390,23 +384,6 @@ it('reports native held input after programs, keeps it across turns, and stops r expect(reminders(f.agent)).toHaveLength(2) }) -it.each([false, true])('delivers only the final held state from a model tool batch (D held: %s)', async (holdD) => { - const second = 'await app.sendKeyEvent("w", "up")' + (holdD ? '; await app.sendKeyEvent("d", "down")' : '') - const f = await setup([[holdProgram, second]], 'macos', undefined, true, true) - await f.run() - expect(f.native.events).toEqual(holdD ? ['w:down', 'w:up', 'd:down'] : ['w:down', 'w:up']) - expect(f.native.calls.filter(call => call.method === 'getHeldInputs')).toHaveLength(2) - expect(f.model.requests).toHaveLength(2) - const shown = f.model.requests[1]!.messages.map(message => JSON.stringify(message)) - .filter(message => message.includes('CUA inputs are still held:')) - expect(shown).toHaveLength(holdD ? 1 : 0) - expect(reminders(f.agent)).toHaveLength(shown.length) - if (holdD) { - expect(reminders(f.agent)[0]).toContain('Key "d"') - expect(reminders(f.agent)[0]).not.toContain('Key "w"') - } -}) - it('reports the Windows keyboard window and desktop input mode and supports a later explicit up', async () => { const f = await setup([holdWindowProgram], 'windows', undefined, true, true) await f.run() diff --git a/snapshots/session/cua-run-code-scoped/session.v4.jsonl b/snapshots/session/cua-run-code-scoped/session.v4.jsonl index 7b595719ce..1052c75c7e 100644 --- a/snapshots/session/cua-run-code-scoped/session.v4.jsonl +++ b/snapshots/session/cua-run-code-scoped/session.v4.jsonl @@ -3,18 +3,18 @@ {"type":"permission/preset","data":{"preset":"danger-full-access"}} {"type":"sandbox/mode","data":{"mode":"danger-full-access"}} {"type":"approval/policy","data":{"policy":"never"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Use cua_run_code to select test.fixture, retain its application and window objects, click Increment, and capture the window. In a second call reuse those objects and a retained counter, increment again, and report the observed count and available program tools. In the first batch, hold W and release it in a separate program before resuming."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Use cua_run_code to select test.fixture, retain its application and window objects, click Increment, and capture the window. In a second call reuse those objects and a retained counter, increment again, and report the observed count and available program tools."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"}]}} {"type":"turn/start","data":{"turn":1}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Use cua_run_code to select test.fixture, retain its application and window objects, click Increment, and capture the window. In a second call reuse those objects and a retained counter, increment again, and report the observed count and available program tools. In the first batch, hold W and release it in a separate program before resuming."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Use cua_run_code to select test.fixture, retain its application and window objects, click Increment, and capture the window. In a second call reuse those objects and a retained counter, increment again, and report the observed count and available program tools."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} {"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 cua_run_code to select test.fixture,","messageSeqs":[9],"source":{"kind":"fallback"}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot); await app.sendKeyEvent(\\\"w\\\", \\\"down\\\")\",\"description\":\"Select and capture the fixture window\"}"},{"type":"tool-call","id":"cua_release","name":"cua_run_code","arguments":"{\"code\":\"await app.sendKeyEvent(\\\"w\\\", \\\"up\\\")\",\"description\":\"Release W in the same tool batch\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"stream":[{"type":"chunk","time":1795082961728,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1795082961728,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot); await app.sendKeyEvent(\\\"w\\\", \\\"down\\\")\",\"description\":\"Select and capture the fixture window\"}"}}},{"type":"chunk","time":1795082961728,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}},{"type":"chunk","time":1795082961728,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"cua_release","name":"cua_run_code","arguments":"{\"code\":\"await app.sendKeyEvent(\\\"w\\\", \\\"up\\\")\",\"description\":\"Release W in the same tool batch\"}"}}},{"type":"chunk","time":1795082961728,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot); await app.sendKeyEvent(\\\"w\\\", \\\"down\\\")\",\"description\":\"Select and capture the fixture window\"}"}} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"stream":[{"type":"chunk","time":1794291763110,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794291763110,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}}},{"type":"chunk","time":1794291763110,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemPointer\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\",\"sendKeyEvent\",\"toggleMouse\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}}}} @@ -25,18 +25,10 @@ {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:4","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-1","elementId":"0"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:5","name":"cua","arguments":{"method":"screenshot","params":{"appHandle":"fixture-app","windowId":"7"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:5","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_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:6","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"w","direction":"down"}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:6","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"w","direction":"down"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"cua_first"},"toolCallId":"cua_first","content":[{"type":"text","text":"{\"visits\":1,\"bindings\":[\"cua\"],\"app\":\"fixture-app\",\"window\":\"7\"}\n"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[15],"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua_release","name":"cua_run_code","arguments":"{\"code\":\"await app.sendKeyEvent(\\\"w\\\", \\\"up\\\")\",\"description\":\"Release W in the same tool batch\"}"}} -{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_release","parentCallId":"cua_release","subCallId":"cua_release:ptc:1","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"w","direction":"up"}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_release","parentCallId":"cua_release","subCallId":"cua_release:ptc:1","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"w","direction":"up"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"cua_release"},"toolCallId":"cua_release","content":[{"type":"text","text":"(cua_run_code completed with no output)"}],"isError":false,"id":"{{message:6}}"}},"sourceEventSeqs":[29],"surfaceOp":"append"} -{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"\nCUA inputs are still held:\n- Key \"w\", appHandle \"fixture-app\" (application input).\nThey remain pressed across programs and turns. Release them explicitly with sendKeyEvent(key, 'up') or toggleMouse(button, 'up') on the same target when no longer needed.\n"}],"source":{"kind":"cua-held-inputs","form":"notice","summary":"CUA inputs remain held"},"role":"user","id":"{{message:7}}"}]}} -{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[],"outcome":"canceled"}} {"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_reuse","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\",\"description\":\"Reuse the retained application and window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:8}}"},"stream":[{"type":"chunk","time":1795082962045,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1795082962045,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_reuse","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\",\"description\":\"Reuse the retained application and window\"}"}}},{"type":"chunk","time":1795082962045,"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_reuse","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\",\"description\":\"Reuse the retained application and window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:6}}"},"stream":[{"type":"chunk","time":1794291763317,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794291763317,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_reuse","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\",\"description\":\"Reuse the retained application and window\"}"}}},{"type":"chunk","time":1794291763317,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"cua_reuse","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\",\"description\":\"Reuse the retained application and window\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:1","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:1","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"snapshotId\":\"fixture-snapshot-2\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 1\\\"\",\"windows\":[{\"windowId\":\"7\",\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} @@ -44,9 +36,9 @@ {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:2","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-2","elementId":"0"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:3","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:3","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"snapshotId\":\"fixture-snapshot-3\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 2\\\"\",\"windows\":[{\"windowId\":\"7\",\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} -{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"cua_reuse"},"toolCallId":"cua_reuse","content":[{"type":"text","text":"{\"visits\":2,\"app\":\"fixture-app\",\"window\":\"7\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 2\\\"\",\"bindings\":[\"cua\"]}\n"}],"isError":false,"id":"{{message:9}}"}},"sourceEventSeqs":[38],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"cua_reuse"},"toolCallId":"cua_reuse","content":[{"type":"text","text":"{\"visits\":2,\"app\":\"fixture-app\",\"window\":\"7\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 2\\\"\",\"bindings\":[\"cua\"]}\n"}],"isError":false,"id":"{{message:7}}"}},"sourceEventSeqs":[30],"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":"text","text":"The retained application and window report Count: 2. The counter persisted across calls, and the program exposes only tools.cua. The screenshot was attached after the first call."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:10}}"},"stream":[{"type":"chunk","time":1795082962071,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1795082962071,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"The retained application and window report Count: 2. The counter persisted across calls, and the program exposes only tools.cua. The screenshot was attached after the first call."}}},{"type":"chunk","time":1795082962071,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"text","text":"The retained application and window report Count: 2. The counter persisted across calls, and the program exposes only tools.cua. The screenshot was attached after the first call."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:8}}"},"stream":[{"type":"chunk","time":1794291763343,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1794291763343,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"The retained application and window report Count: 2. The counter persisted across calls, and the program exposes only tools.cua. The screenshot was attached after the first call."}}},{"type":"chunk","time":1794291763343,"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"}}} From 99ecefea626cdb8b8e6e32a8ab04d7e00727ac16 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 19 Nov 2026 21:41:17 +0800 Subject: [PATCH 59/73] Await call-scoped failure cleanup before publishing rejected tool results --- ...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/subsystems/computer-use.md | 4 +-- docs/subsystems/computer-use.zh.md | 4 +-- docs/subsystems/tools.i18n.yaml | 4 +-- docs/subsystems/tools.md | 9 ++++- docs/subsystems/tools.zh.md | 9 ++++- .../cua-held-inputs/guide.i18n.yaml | 4 +-- .../v0.2.2-rc.5/cua-held-inputs/guide.md | 2 +- .../v0.2.2-rc.5/cua-held-inputs/guide.zh.md | 2 +- packages/core/tools/README.i18n.yaml | 4 +-- packages/core/tools/README.md | 2 +- packages/core/tools/README.zh.md | 2 +- packages/core/tools/src/contracts.ts | 7 ++++ packages/core/tools/src/pipeline.ts | 31 ++++++++++++++-- packages/core/tools/tests/tools.spec.ts | 33 +++++++++++++++++ .../cua-mcp/tests/composition.spec.ts | 19 ++++++++++ packages/experimental/cua/README.i18n.yaml | 4 +-- packages/experimental/cua/README.md | 2 +- packages/experimental/cua/README.zh.md | 2 +- packages/experimental/cua/src/held-inputs.ts | 25 ++++++++----- .../experimental/cua/src/tool-registration.ts | 14 ++++++-- .../cua/tests/run-code-composition.spec.ts | 35 +++++++++++++++++++ .../extensions/tool-cordis/src/api-catalog.ts | 6 ++-- 25 files changed, 191 insertions(+), 41 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 8507be2693..3ea19f8826 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 @@ -15,5 +15,5 @@ en: 32c970ae153e0f6c zh: 8431be0a10ffed15 /agent-note-cua-scoped-surfaces-and-separated-input-capabilities/consequences: - en: f1efc14ced052492 - zh: 9834bb2cf09c536e + en: fd10784f6cea2da6 + zh: f31891b0179334f8 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 4701db9150..9142a468d6 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 @@ -34,6 +34,6 @@ Within one API instance, the object facade keeps one current accessibility snaps Element IDs belong to the application's current accessibility snapshot. Reading one window replaces the facade’s current snapshot for that application, so callers observe again and confirm the IDs they use. The new read does not guarantee that an old string is rejected or that an ID changes; callers must not assume an older ID still identifies the same control. Pointer input and screenshots require an explicit window object; callers enumerate windows first. -Keyboard behavior follows the provider's supported scopes. A caller that uses `sendKeyEvent` controls its down/up pairing. Native input ownership follows the task and connection. Successful DSH and MCP programs report remaining held input without releasing it. A client pause between completed MCP calls does not notify this server and can leave input held; native ownership still permits explicit release and connection cleanup. Explicit up, program failure, user cancellation and resource disposal release owned input. macOS implements this lifecycle; Windows implementation is pending. Keyboard modifier names are provider-defined, so the same string may have different support across providers. +Keyboard behavior follows the provider's supported scopes. A caller that uses `sendKeyEvent` controls its down/up pairing. Native input ownership follows the task and connection. Successful DSH and MCP programs report remaining held input without releasing it. A client pause between completed MCP calls does not notify this server and can leave input held; native ownership still permits explicit release and connection cleanup. Explicit up, program failure, user cancellation and resource disposal release owned input. macOS and Windows both implement this lifecycle. Custom helpers must support the matching task-scoped query and release operations. Keyboard modifier names are provider-defined, so the same string may have different support across providers. Provider guidance owns the list of supported actions. Adding a method to the shared schema does not claim that every provider implements it, and the merged `getCapabilities` result remains the runtime source for permissions and session lock. 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 7323a58adf..4d220d0dce 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 @@ -34,6 +34,6 @@ Provider 的启动能力是静态的。平台、支持的方法、应用级辅 元素 ID 属于应用当前的辅助功能快照。读取一个窗口会替换门面对该应用的当前快照,因此调用方需要重新观察并确认要使用的 ID。新的读取不保证拒绝旧字符串,也不保证 ID 会改变;调用方不得假定旧 ID 仍指向同一控件。指针输入和截图都要求显式的窗口对象;调用方先枚举窗口。 -键盘行为遵循 provider 支持的作用域。使用 `sendKeyEvent` 的调用方控制按下与抬起的配对。原生输入所有权属于任务和连接。DSH 和 MCP 程序成功结束时报告剩余持有输入,不自动释放。客户端在两次 MCP 调用之间暂停时不会通知服务端,输入可能继续按住;原生所有权仍支持显式释放和连接清理。显式 up、程序失败、用户取消和资源销毁释放所属输入。macOS 已实现这套生命周期,Windows 待实现。键盘修饰键名称由 provider 定义,同一字符串在不同 provider 上可能支持不同。 +键盘行为遵循 provider 支持的作用域。使用 `sendKeyEvent` 的调用方控制按下与抬起的配对。原生输入所有权属于任务和连接。DSH 和 MCP 程序成功结束时报告剩余持有输入,不自动释放。客户端在两次 MCP 调用之间暂停时不会通知服务端,输入可能继续按住;原生所有权仍支持显式释放和连接清理。显式 up、程序失败、用户取消和资源销毁释放所属输入。macOS 和 Windows 都实现了这套生命周期。自定义 helper 必须支持对应的任务级状态查询和释放操作。键盘修饰键名称由 provider 定义,同一字符串在不同 provider 上可能支持不同。 Provider 指导文本负责支持动作的清单。把方法加入共享 schema 并不表示每个 provider 都已实现它;合并后的 `getCapabilities` 结果仍是权限和会话锁定状态的运行时来源。 diff --git a/docs/subsystems/computer-use.md b/docs/subsystems/computer-use.md index 51fa464352..0d3db58b7f 100644 --- a/docs/subsystems/computer-use.md +++ b/docs/subsystems/computer-use.md @@ -158,8 +158,8 @@ Host control over the dedicated `cua_run_code` environments; registered as `ctx. * programs until the release settles, so the caller holds them back; after a failed release it rejects them * until a later release succeeds. Resolves when no environment exists. * @param agent - Agent whose `cua_run_code` state owner is released. - * @returns Completion after the process has exited and its output has drained. - * @throws When the process cleanup fails. + * @returns Completion after the process has exited, its output has drained, and held-input cleanup has settled. + * @throws When environment or input cleanup fails, reporting both causes if both fail. */ release(agent: Agent): Promise diff --git a/docs/subsystems/computer-use.zh.md b/docs/subsystems/computer-use.zh.md index cd30d15255..8170748e7e 100644 --- a/docs/subsystems/computer-use.zh.md +++ b/docs/subsystems/computer-use.zh.md @@ -158,8 +158,8 @@ Host control over the dedicated `cua_run_code` environments; registered as `ctx. * programs until the release settles, so the caller holds them back; after a failed release it rejects them * until a later release succeeds. Resolves when no environment exists. * @param agent - Agent whose `cua_run_code` state owner is released. - * @returns Completion after the process has exited and its output has drained. - * @throws When the process cleanup fails. + * @returns Completion after the process has exited, its output has drained, and held-input cleanup has settled. + * @throws When environment or input cleanup fails, reporting both causes if both fail. */ release(agent: Agent): Promise diff --git a/docs/subsystems/tools.i18n.yaml b/docs/subsystems/tools.i18n.yaml index bcefbfdd3b..062e525e01 100644 --- a/docs/subsystems/tools.i18n.yaml +++ b/docs/subsystems/tools.i18n.yaml @@ -21,8 +21,8 @@ en: 14522295539ea2fb zh: 572c462f2c6b70ad /tools/execution-extensible-waterfalls-plus-monotonic-policy: - en: a6d9db4237438b2a - zh: 1fe07dedc426c5eb + en: f74b432c5ad7f78f + zh: 4e5487828ff17250 /tools/the-enforced-raw-json-schema-subset: en: 28e354bfa2f9cebb zh: be1f75abccf8afdf diff --git a/docs/subsystems/tools.md b/docs/subsystems/tools.md index 5a32c8e009..cfde7eee48 100644 --- a/docs/subsystems/tools.md +++ b/docs/subsystems/tools.md @@ -450,10 +450,17 @@ interface ToolExecution extends ToolExecutionInput { interface ToolDispatchExecution extends Omit { /** Cancellation signal visible to the next wrapper or tool body. */ signal: AbortSignal + /** + * Register cleanup during dispatch for this invocation. If the final result is an error, the executor + * awaits every registered cleanup in order before publishing it, including failures from post-execute policy. + * Cleanup failures add feedback to the original error. Successful calls discard the registrations. + * @param cleanup - Release this call's resources using the resource owner's cleanup deadline. + */ + onFailure(cleanup: () => void | Promise): void } ``` -`ToolExecutionToken` is an opaque runtime `Symbol` used only for identity comparison. Before policy, `execute()` materializes and freezes arguments, rejects non-JSON input, and assigns the token. Identity fields, the required caller signal, and the optional parent token remain readonly. A `ToolDispatchExecution` wrapper may replace but not remove the signal; the registry re-fuses the caller signal before invoking the body. Final observers receive the frozen execution identity. +`ToolExecutionToken` is an opaque runtime `Symbol` used only for identity comparison. Before policy, `execute()` materializes and freezes arguments, rejects non-JSON input, and assigns the token. Identity fields, the required caller signal, and the optional parent token remain readonly. A `ToolDispatchExecution` wrapper may replace but not remove the signal; the registry re-fuses the caller signal before invoking the body. Final observers receive the frozen execution identity. A dispatch wrapper can register `exec.onFailure(cleanup)` before returning. When the final outcome fails, including a post-execute block, the executor waits for that invocation’s cleanups before notifying result observers. A cleanup refusal appends feedback and preserves the original error code. A `ToolGuard` is scope-aware final pre-dispatch policy. Its return type deliberately has no allow result: `undefined` preserves the waterfall decision, while a returned reason or `ToolGuardDenial` can only reduce permission, so a later listener cannot undo it. A denial's optional `info` becomes the failed result's structured error identity. diff --git a/docs/subsystems/tools.zh.md b/docs/subsystems/tools.zh.md index 1b82c3b678..411a46642e 100644 --- a/docs/subsystems/tools.zh.md +++ b/docs/subsystems/tools.zh.md @@ -450,10 +450,17 @@ interface ToolExecution extends ToolExecutionInput { interface ToolDispatchExecution extends Omit { /** Cancellation signal visible to the next wrapper or tool body. */ signal: AbortSignal + /** + * Register cleanup during dispatch for this invocation. If the final result is an error, the executor + * awaits every registered cleanup in order before publishing it, including failures from post-execute policy. + * Cleanup failures add feedback to the original error. Successful calls discard the registrations. + * @param cleanup - Release this call's resources using the resource owner's cleanup deadline. + */ + onFailure(cleanup: () => void | Promise): void } ``` -`ToolExecutionToken` 是不透明的运行时 `Symbol`,仅用于身份比较。策略执行前,`execute()` 会物化并冻结参数、拒绝非 JSON 输入并分配 token。身份字段、调用方必需的 signal 和可选的 parent token 均保持 readonly。`ToolDispatchExecution` 包装层可以替换 signal 但不能移除;注册表会在调用工具函数体前重新融合调用方的 signal。最终观察者接收冻结的执行身份。 +`ToolExecutionToken` 是不透明的运行时 `Symbol`,仅用于身份比较。策略执行前,`execute()` 会物化并冻结参数、拒绝非 JSON 输入并分配 token。身份字段、调用方必需的 signal 和可选的 parent token 均保持 readonly。`ToolDispatchExecution` 包装层可以替换 signal 但不能移除;注册表会在调用工具函数体前重新融合调用方的 signal。最终观察者接收冻结的执行身份。 执行包装层可在返回前调用 `exec.onFailure(cleanup)`。若最终结果失败,包括被后置策略拒绝,执行器会先等待该次调用的清理,再通知结果观察者。清理失败时追加错误反馈,并保留原错误码。 `ToolGuard` 是感知作用域的最终预分派策略。其返回类型有意不包含 allow 结果:`undefined` 保留 waterfall 的决策,而返回的 reason 或 `ToolGuardDenial` 只能缩减权限,因此后续监听器无法撤销它。拒绝中可选的 `info` 会成为失败结果的结构化错误身份。 diff --git a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml index 2d11979d27..b88312ff7a 100644 --- a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml @@ -12,5 +12,5 @@ en: 2812241cf189be50 zh: ee90f8e5c6c55512 /cua-reports-held-input-after-programs/migration: - en: c5edd5bf874d2a95 - zh: e26d4e6945da4eae + en: 23893a11333ff744 + zh: e1dae0e424d6420f diff --git a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md index 8ab3a4b3a8..2ff3e9e007 100644 --- a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md @@ -14,4 +14,4 @@ On macOS and Windows, explicit `sendKeyEvent('down')` and `toggleMouse('down')` 1. Pair explicit downs with ups when input should stop. Read the reminder before continuing; no reminder is added when no input remains held. 2. Upgrade the platform package and helper together. A custom `helperPath` must implement the task-owned `getHeldInputs` and `releaseHeldInputs` private operations. -3. Verify that one successful program can hold a key, receive its reminder, and release it in a later program. A failed or cancelled program waits for its cleanup. If the model is thinking when DSH stops or fails, the Agent can finish before native release is confirmed. Subsequent CUA calls wait for the outcome. If cleanup cannot be confirmed, CUA disables further operations for that task; inspect the desktop manually before starting another task. +3. Verify that one successful program can hold a key, receive its reminder, and release it in a later program. A failed or cancelled program waits for its cleanup. This includes a program that sends input successfully before a post-execute policy rejects its result. Execution middleware can register call-scoped cleanup with `exec.onFailure(cleanup)`. If the model is thinking when DSH stops or fails, the Agent can finish before native release is confirmed. Subsequent CUA calls wait for the outcome. If cleanup cannot be confirmed, CUA disables further operations for that task; inspect the desktop manually before starting another task. diff --git a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md index f53a8017e7..5377e222a5 100644 --- a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md @@ -14,4 +14,4 @@ macOS 和 Windows 的显式 `sendKeyEvent('down')` 和 `toggleMouse('down')` 跨 1. 输入不再需要保持时,将显式 down 与 up 配对。继续操作前阅读提醒;没有持有输入时不添加提醒。 2. 同步升级平台包和 helper。自定义 `helperPath` 必须实现按任务区分的 `getHeldInputs` 和 `releaseHeldInputs` 私有操作。 -3. 验证成功结束的程序能持有按键、收到提醒,并在后续程序中释放。程序失败或取消时会等待自身的清理。模型思考期间停止或报错,Agent 可以先结束,原生释放随后确认。后续 CUA 调用会等待清理结果。清理无法确认时,CUA 禁用该任务后续操作;请手动检查桌面后再创建其他任务。 +3. 验证成功结束的程序能持有按键、收到提醒,并在后续程序中释放。程序失败或取消时会等待自身的清理,已发送输入、随后被后置策略拒绝的程序也适用。工具执行包装层可用 `exec.onFailure(cleanup)` 登记该次调用的失败清理。模型思考期间停止或报错,Agent 可以先结束,原生释放随后确认。后续 CUA 调用会等待清理结果。清理无法确认时,CUA 禁用该任务后续操作;请手动检查桌面后再创建其他任务。 diff --git a/packages/core/tools/README.i18n.yaml b/packages/core/tools/README.i18n.yaml index ff22c17d80..6bfdcf15a3 100644 --- a/packages/core/tools/README.i18n.yaml +++ b/packages/core/tools/README.i18n.yaml @@ -30,8 +30,8 @@ en: c6f98b2283cc2e47 zh: c2cdce5d13473f15 /deepseek-ai-dsh-tools/use-this-package/enforce-policy-on-calls: - en: cbfe8317565ac62d - zh: 1e71c66941e50881 + en: 979aa454c0c8705a + zh: 00bfbbedc9e43b10 /deepseek-ai-dsh-tools/use-this-package/host-presentation-descriptors: en: 258e16bb367229e5 zh: 7c1eb91062b4e4ad diff --git a/packages/core/tools/README.md b/packages/core/tools/README.md index 50732a3159..119988a8ab 100644 --- a/packages/core/tools/README.md +++ b/packages/core/tools/README.md @@ -91,7 +91,7 @@ Agent-step concurrency uses the [agent-loop configuration](../agent-loop/README. `ctx.tools.guard(guard)` registers a monotonic synchronous guard after the extensible `tools/pre-execute` waterfall: a returned reason denies the call, and no later listener can turn that denial back into permission. The pipeline's events give plugins more control — `tools/pre-execute` decides allow/deny/ask, `tools/execute` wraps dispatch for timeout or retry, `tools/post-execute` inspects or replaces the result, and `tools/result` observes the frozen final outcome. -A tool’s `projectContent` installs execution-prepared content before post-execute policies. Policies may still replace or block it; `finalizeContent` remains the final content transform after those policies. +A tool’s `projectContent` installs execution-prepared content before post-execute policies. Policies may still replace or block it; `finalizeContent` remains the final content transform after those policies. A dispatch wrapper can register `exec.onFailure(cleanup)` before returning. When the final outcome fails, including a post-execute block, the executor waits for that invocation’s cleanups before notifying result observers. A cleanup refusal appends feedback and preserves the original error code. ### Host presentation descriptors diff --git a/packages/core/tools/README.zh.md b/packages/core/tools/README.zh.md index 28abce32f4..f9c68321da 100644 --- a/packages/core/tools/README.zh.md +++ b/packages/core/tools/README.zh.md @@ -91,7 +91,7 @@ Agent 步骤的并发上限使用 [agent-loop 配置](../agent-loop/README.zh.md `ctx.tools.guard(guard)` 在可扩展的 `tools/pre-execute` waterfall(瀑布式事件)之后注册单调同步守卫:返回的理由会拒绝调用,后续监听器无法把该拒绝重新变为允许。流水线事件给插件更多控制——`tools/pre-execute` 决定允许/拒绝/询问,`tools/execute` 为超时或重试包装分发,`tools/post-execute` 检查或替换结果,`tools/result` 观测冻结的最终结果。 -工具的 `projectContent` 在执行后策略之前安装执行期间准备的图文内容。策略仍可替换或阻止这些内容;`finalizeContent` 保留为策略之后的最终内容处理。 +工具的 `projectContent` 在执行后策略之前安装执行期间准备的图文内容。策略仍可替换或阻止这些内容;`finalizeContent` 保留为策略之后的最终内容处理。 执行包装层可在返回前调用 `exec.onFailure(cleanup)`。若最终结果失败,包括被后置策略拒绝,执行器会先等待该次调用的清理,再通知结果观察者。清理失败时追加错误反馈,并保留原错误码。 ### Host 展示描述 diff --git a/packages/core/tools/src/contracts.ts b/packages/core/tools/src/contracts.ts index 51597b4107..9f939f98aa 100644 --- a/packages/core/tools/src/contracts.ts +++ b/packages/core/tools/src/contracts.ts @@ -232,6 +232,13 @@ export interface ToolExecution extends ToolExecutionInput { export interface ToolDispatchExecution extends Omit { /** Cancellation signal visible to the next wrapper or tool body. */ signal: AbortSignal + /** + * Register cleanup during dispatch for this invocation. If the final result is an error, the executor + * awaits every registered cleanup in order before publishing it, including failures from post-execute policy. + * Cleanup failures add feedback to the original error. Successful calls discard the registrations. + * @param cleanup - Release this call's resources using the resource owner's cleanup deadline. + */ + onFailure(cleanup: () => void | Promise): void } /** diff --git a/packages/core/tools/src/pipeline.ts b/packages/core/tools/src/pipeline.ts index 9db8bfc610..9db681684f 100644 --- a/packages/core/tools/src/pipeline.ts +++ b/packages/core/tools/src/pipeline.ts @@ -90,6 +90,8 @@ export class ToolExecutionPipeline { /** Original caller cancellation, kept outside the wrapper-mutable execution object. */ private cancellationStates = new WeakMap() + private readonly failureCleanups = new WeakMap void | Promise)[]>() + /** Definition-owned final content transform snapshotted before policy begins. */ private contentFinalizers = new WeakMap() @@ -304,8 +306,16 @@ export class ToolExecutionPipeline { * @returns whether the result still needs post-execute. */ async dispatch(exec: ToolRunContext): Promise { + let dispatching = true try { - const mutableExec = exec as MutableToolRunContext + const mutableExec = Object.assign(exec as MutableToolRunContext, { + onFailure: (cleanup: () => void | Promise) => { + if (!dispatching) throw new Error('Tool failure cleanup must be registered during dispatch') + const registered = this.failureCleanups.get(exec) + if (registered) registered.push(cleanup) + else this.failureCleanups.set(exec, [cleanup]) + }, + }) const carrier = scopeTarget(this.tools, exec.agent) const result = await this.ctx.waterfall( carrier, 'tools/execute', mutableExec, @@ -332,6 +342,8 @@ export class ToolExecutionPipeline { } } catch (error: unknown) { return { kind: 'final-result', result: this.wrapperFailureResult(exec, error) } + } finally { + dispatching = false } } @@ -391,7 +403,7 @@ export class ToolExecutionPipeline { * @returns the materialized final result. * @internal */ - private finish(exec: ToolRunContext, result: ToolExecutionResult): ToolExecutionResult { + private async finish(exec: ToolRunContext, result: ToolExecutionResult): Promise { let materializedResult: ToolExecutionResult try { materializedResult = this.materializeFinalResult(result) @@ -404,6 +416,21 @@ export class ToolExecutionPipeline { } catch (error: unknown) { finalResult = this.materializeFinalResult(toolErrorResult(error)) } + const cleanups = this.failureCleanups.get(exec) + this.failureCleanups.delete(exec) + if (finalResult.isError && cleanups) { + const errors: string[] = [] + for (const cleanup of cleanups) { + try { await cleanup() } catch (error) { errors.push(toolErrorMessage(error)) } + } + if (errors.length) { + const feedback = `Tool cleanup failed: ${errors.join('\n')}` + finalResult = this.materializeFinalResult({ + ...finalResult, error: { ...finalResult.error, message: `${finalResult.error.message}\n${feedback}` }, + content: [...finalResult.content, { type: 'text', text: feedback }], + }) + } + } this.notifyResult(exec, finalResult) return finalResult } diff --git a/packages/core/tools/tests/tools.spec.ts b/packages/core/tools/tests/tools.spec.ts index 3952e42194..da67785b70 100644 --- a/packages/core/tools/tests/tools.spec.ts +++ b/packages/core/tools/tests/tools.spec.ts @@ -573,6 +573,39 @@ describe('ToolRuntime', () => { expect(result.error?.message).toBe(message) }) + it('settles registered cleanups only on final failure, before reporting the policy result', async () => { + const ctx = await setup() + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + const events: string[] = [] + try { + ctx.tools.register(echoTool) + let registerLate: (() => void) | undefined + ctx.on('tools/execute', (exec, next) => { + registerLate = () => { exec.onFailure(() => {}) } + exec.onFailure(() => { events.push('first'); throw new Error('first cleanup failed') }) + exec.onFailure(async () => { entered.resolve(undefined); await release.promise; events.push('second') }) + return next() + }) + ctx.on('tools/result', (_exec, result) => { events.push(result.isError ? 'failed' : 'succeeded') }) + const call = (id: string) => executeToolFixture(ctx, { signal: testToolSignal, callId: brandString(id), name: 'echo', arguments: {} }) + expect((await call('ok')).isError).toBe(false) + expect(events).toEqual(['succeeded']) + expect(() => registerLate!()).toThrow('during dispatch') + ctx.on('tools/post-execute', async (): Promise => ({ + kind: 'block', feedback: [{ type: 'text', text: 'rejected' }], info: { name: 'PolicyError', code: 'BLOCKED' }, + }), { prepend: true }) + const blocked = call('block') + await entered.promise + expect(events).toEqual(['succeeded', 'first']) + release.resolve(undefined) + expect(await blocked).toMatchObject({ isError: true, error: { info: { code: 'BLOCKED' }, + message: 'rejected\nTool cleanup failed: first cleanup failed' }, + content: [{ text: 'rejected' }, { text: 'Tool cleanup failed: first cleanup failed' }] }) + expect(events).toEqual(['succeeded', 'first', 'second', 'failed']) + } finally { release.resolve(undefined); await ctx.fiber.dispose() } + }) + it('records the structured identity of a post-execute block', async () => { const ctx = await setup() ctx.tools.register(echoTool) diff --git a/packages/experimental/cua-mcp/tests/composition.spec.ts b/packages/experimental/cua-mcp/tests/composition.spec.ts index c8176b9bc2..3322edd7ab 100644 --- a/packages/experimental/cua-mcp/tests/composition.spec.ts +++ b/packages/experimental/cua-mcp/tests/composition.spec.ts @@ -396,6 +396,25 @@ describe('Computer Use MCP composition', () => { expect(texts(invalid)).toEqual(['invalid arguments: missing required property "description"']) }) + it.each([false, true])('reports environment reset failure after attempting input cleanup (input refused: %s)', async (refused) => { + const { native, client, run } = await setup() + await run('var app = await cua.getApp("test.fixture"); await app.sendKeyEvent("w", "down")') + const environment = vi.spyOn(NodeRuntime.prototype, 'release').mockRejectedValueOnce(new Error('Fixture process failed to exit')) + onTestFinished(() => { environment.mockRestore() }) + const release = native.controlNext('releaseHeldInputs') + const resetting = client.callTool({ name: 'cua_reset', arguments: {} }) + await release.entered + try { expect(environment).toHaveBeenCalledTimes(1) } finally { + release.reply(refused ? { code: 'INPUT_CLEANUP_FAILED', message: 'Fixture release refused' } : undefined) + } + const result = await resetting + expect(result.isError).toBe(true) + const message = texts(result).join(' ') + expect(message).toContain('Fixture process failed to exit') + if (refused) expect(message).toContain('Fixture release refused') + else expect(native.events).toEqual(['w:down', 'w:up']) + }) + it('resets only the program environment: a fresh process and cua object, the same Agent and native connection', async () => { const { ctx, native, run, client, adapter } = await setup() const first = await run('globalThis.visits = 1; var app = await cua.getApp("test.fixture"); var win = await app.getWindow("7"); inspect(process.pid)') diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index fc19284edd..2a9a605066 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -21,8 +21,8 @@ en: 3f638a4a76023fc5 zh: 515aeb5de6ae5b33 /deepseek-ai-dsh-cua/understand-the-implementation: - en: cf9d118b6080368b - zh: 70aa90a0b054dc9e + en: d6dc096630c274a5 + zh: d4e1b7fa718d6653 /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 decead58fe..3fd3a746a3 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -93,7 +93,7 @@ Permission responses identify their platform and report only the state that plat Providers implementing `CuaBackend.heldInputState` accept `taskId` on explicit input and system pointer movement, report their connection-owned records through `getHeldInputs({ taskId })`, and acknowledge `releaseHeldInputs({ taskId })`. Native records own the actual key/button, target, process identity and input mode. Successful `run_code` and `cua_run_code` programs query those records and append a system reminder when input remains held; normal program and turn endings preserve input in both DSH and MCP. Reminders travel through logged additional context in DSH and through the tool response in MCP. macOS and Windows both implement this protocol. Capability methods remain static. -Held input belongs to the task and native connection, outside program processes. A DSH stop or model failure starts cleanup. The Agent can finish the turn and resolve `whenIdle()` while the native release is pending. Subsequent CUA calls wait for its outcome. Confirmed release queues a notice for the model and removes pending held-state reminders. A cleanup failure is reported through `agent/error` and disables CUA for that task. A failed or cancelled program, an active MCP request receiving cancellation, an environment reset, and connection or provider disposal each await their own cleanup. +Held input belongs to the task and native connection, outside program processes. A DSH stop or model failure starts cleanup. The Agent can finish the turn and resolve `whenIdle()` while the native release is pending. Subsequent CUA calls wait for its outcome. A program rejected by post-execute policy releases its held input before the tool returns the rejection. If release also fails, the result reports both causes. Confirmed release queues a notice for the model and removes pending held-state reminders. A cleanup failure is reported through `agent/error` and disables CUA for that task. A failed or cancelled program, an active MCP request receiving cancellation, an environment reset, and connection or provider disposal each await their own cleanup. The [permission store](src/permission-store.ts) uses `storageDomain` with the configured backend. The default JSON backend writes `$DSH_HOME/storages/cua_permissions_.json`, where the digest identifies the canonical profile directory. Each authorization check opens fresh state under the profile's file lock and closes its domain afterward; native dispatch uses a separate application lock. Revocation waits for operations already admitted by another process; after it completes, every process rejects old handles. Files on different machines or PID namespaces must not share this lock. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index 2ab76c7ed8..d9e399bb26 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -93,7 +93,7 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边 实现 `CuaBackend.heldInputState` 的提供方为显式输入和系统指针移动接受 `taskId`,通过 `getHeldInputs({ taskId })` 报告本连接的持有记录,并确认 `releaseHeldInputs({ taskId })`。原生记录负责保存实际按键或按钮、目标、进程身份和输入方式。成功结束的 `run_code` 和 `cua_run_code` 查询这些记录,仍有输入按住时添加 system reminder;DSH 和 MCP 的正常程序结束和回合结束均保持输入。DSH 通过已记录的额外上下文传递提醒,MCP 通过工具响应传递。macOS 和 Windows 都实现了这套协议。能力方法列表保持静态。 -持有输入属于任务和原生连接,保存在程序进程之外。DSH 收到停止请求或模型报错时启动清理。原生释放尚未确认时,Agent 可以结束回合,`whenIdle()` 也可以返回。后续 CUA 调用等待清理结果。确认释放后,DSH 为模型记录释放提醒,并撤销仍在队列中的旧持有提醒。清理失败会通过 `agent/error` 单独报告,并禁用该任务后续的 CUA 操作。程序失败或取消、执行中的 MCP 请求收到取消、环境重置、连接关闭和提供方卸载,各自等待清理完成。 +持有输入属于任务和原生连接,保存在程序进程之外。DSH 收到停止请求或模型报错时启动清理。原生释放尚未确认时,Agent 可以结束回合,`whenIdle()` 也可以返回。后续 CUA 调用等待清理结果。后置策略拒绝程序结果时,工具等待持有输入释放后再返回拒绝原因。如果释放也失败,结果同时报告两个原因。确认释放后,DSH 为模型记录释放提醒,并撤销仍在队列中的旧持有提醒。清理失败会通过 `agent/error` 单独报告,并禁用该任务后续的 CUA 操作。程序失败或取消、执行中的 MCP 请求收到取消、环境重置、连接关闭和提供方卸载,各自等待清理完成。 [授权存储](src/permission-store.ts)复用 `storageDomain` 和配置的后端。默认 JSON 后端写入 `$DSH_HOME/storages/cua_permissions_.json`,摘要对应 profile 的真实目录。每次授权检查在 profile 文件锁内打开并读取最新状态,随后关闭存储域;原生操作使用单独的应用锁。撤销会等待其他进程已获准执行的操作结束;撤销完成后,各进程都拒绝旧句柄。不同电脑或 PID 命名空间不能共享这把锁。 diff --git a/packages/experimental/cua/src/held-inputs.ts b/packages/experimental/cua/src/held-inputs.ts index 0f424bb19c..328cb01de5 100644 --- a/packages/experimental/cua/src/held-inputs.ts +++ b/packages/experimental/cua/src/held-inputs.ts @@ -2,7 +2,7 @@ import type { Context } from '@deepseek-ai/cordis' import { emitAgentEvent, type Agent } from '@deepseek-ai/dsh-agent' import { createUserMessage } from '@deepseek-ai/dsh-llm' -import { RUN_CODE_NAME } from '@deepseek-ai/dsh-tools' +import { RUN_CODE_NAME, type ToolDispatchExecution } from '@deepseek-ai/dsh-tools' import { z } from 'zod' import { NativeError, type NativeClient } from './native-client.ts' @@ -55,6 +55,9 @@ class InputOwner { return renderInputs(inputs, 'held') } + registerFailureCleanup(execution: ToolDispatchExecution): void { + if (this.client) execution.onFailure(async () => { await this.close() }) + } close(canRequest = true): Promise> { this.controller.abort() @@ -166,15 +169,19 @@ export class CuaHeldInputs { } if (result.isError || signal.aborted) { await releaseAfter(result.isError ? result.error.message : 'Program cancelled') - } else if (execution.parent === undefined) { + } else { const owner = this.owners.get(agent) - const inTurn = ctx.agents.turnBoundaryOf(agent.session).openTurnStartSeq !== null - const text = await owner?.reminder(inTurn).catch(async (error: unknown) => { - await releaseAfter(signal.aborted ? 'Program cancelled' : `Held-input query failed: ${String(error)}`) - throw error - }) - // oxlint-disable-next-line typescript/no-unnecessary-condition -- Cancellation can arrive while the native state query awaits. - if (signal.aborted) { await releaseAfter('Program cancelled'); return result } + let text: string | undefined + if (execution.parent === undefined) { + const inTurn = ctx.agents.turnBoundaryOf(agent.session).openTurnStartSeq !== null + text = await owner?.reminder(inTurn).catch(async (error: unknown) => { + await releaseAfter(signal.aborted ? 'Program cancelled' : `Held-input query failed: ${String(error)}`) + throw error + }) + // oxlint-disable-next-line typescript/no-unnecessary-condition -- Cancellation can arrive while the native state query awaits. + if (signal.aborted) { await releaseAfter('Program cancelled'); return result } + } + owner?.registerFailureCleanup(execution) if (text && !owner?.closing) return { ...result, additionalContexts: [...result.additionalContexts ?? [], createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'cua-held-inputs', form: 'notice', summary: 'CUA inputs remain held' } }), diff --git a/packages/experimental/cua/src/tool-registration.ts b/packages/experimental/cua/src/tool-registration.ts index 5bb05512d8..87236da5fc 100644 --- a/packages/experimental/cua/src/tool-registration.ts +++ b/packages/experimental/cua/src/tool-registration.ts @@ -29,8 +29,8 @@ export interface CuaPrograms { * programs until the release settles, so the caller holds them back; after a failed release it rejects them * until a later release succeeds. Resolves when no environment exists. * @param agent - Agent whose `cua_run_code` state owner is released. - * @returns Completion after the process has exited and its output has drained. - * @throws When the process cleanup fails. + * @returns Completion after the process has exited, its output has drained, and held-input cleanup has settled. + * @throws When environment or input cleanup fails, reporting both causes if both fail. */ release(agent: Agent): Promise /** @@ -165,7 +165,15 @@ var cua = connectCua(() => tools.cua); // Hosts without a model (MCP frontends) end an Agent's environment with the runtime's owner release. consumer.provide('cuaPrograms', { release: async (agent: Agent) => { - try { await consumer.ptcRuntime.release(agent) } finally { await releaseInputs(agent) } + try { await consumer.ptcRuntime.release(agent) } + catch (error) { + try { await releaseInputs(agent) } + catch (cleanup) { + throw new AggregateError([error, cleanup], `Environment release failed: ${String(error)}. Held-input cleanup failed: ${String(cleanup)}`) + } + throw error + } + await releaseInputs(agent) }, releaseInputs, screenshotRequestTarget: image => config.screenshotTarget === undefined diff --git a/packages/experimental/cua/tests/run-code-composition.spec.ts b/packages/experimental/cua/tests/run-code-composition.spec.ts index dac4dc7493..41e68200ff 100644 --- a/packages/experimental/cua/tests/run-code-composition.spec.ts +++ b/packages/experimental/cua/tests/run-code-composition.spec.ts @@ -406,6 +406,41 @@ it('reports the Windows keyboard window and desktop input mode and supports a la expect(reminders(f.agent)).toHaveLength(1) }) +it.each([ + ['run_code', 'confirmed'], ['cua_run_code', 'confirmed'], ['cua_run_code', 'refused'], +] as const)('settles %s post-policy failure after native cleanup (%s)', async (tool, cleanup) => { + const code = tool === 'run_code' + ? `await tools.cua_run_code({ code: ${JSON.stringify(holdProgram)}, description: "Hold W" })` : holdProgram + const f = await setup([code], 'macos', undefined, true, true) + if (tool === 'run_code') await f.agent.ctx.plugin(PtcToolExecutor) + f.model.toolName = tool + f.ctx.on('tools/post-execute', async (exec, _result, next) => exec.name === tool + ? { kind: 'block', feedback: [{ type: 'text', text: 'Policy rejected output' }], info: { name: 'HookError', code: 'HOOK_BLOCKED' } } + : next(), { prepend: true }) + const release = f.native.controlNext('releaseHeldInputs') + const running = f.run() + await release.entered + try { + expect(f.native.held.map(input => input.key)).toEqual(['w']) + expect(f.agent.session.snapshotEvents().some(event => event.type === 'tool/result')).toBe(false) + } finally { + release.reply(cleanup === 'refused' ? { code: 'INPUT_CLEANUP_FAILED', message: 'Fixture refused release' } : undefined) + await running + } + const result = f.agent.session.snapshotEvents().find(event => event.type === 'tool/result') + expect(result?.data).toMatchObject({ error: { code: 'HOOK_BLOCKED' }, message: { isError: true } }) + const shown = JSON.stringify(f.model.requests[1]?.messages) + expect(shown).toContain('Policy rejected output') + expect(shown).not.toContain('CUA inputs are still held:') + if (cleanup === 'confirmed') { + expect(f.native.events).toEqual(['w:down', 'w:up']) + expect(shown).toContain('CUA inputs were released during cleanup') + } else { + expect(shown).toContain('Fixture refused release') + expect(shown).not.toContain('CUA inputs were released during cleanup') + } +}) + it('releases keyboard and mouse in mixed reverse order on program failure', async () => { const f = await setup([holdProgram, 'await app.sendKeyEvent("shift", "down"); var win = await app.getWindow("7"); await win.toggleMouse("left", "down"); await app.sendKeyEvent("d", "down"); throw Error("program failed")', 'inspect("recovered")'], diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 6f44b793a9..d9e399f8ae 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -1052,8 +1052,8 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ signature: 'release(agent: Agent): Promise', description: 'Release one Agent\'s retained program environment with the dedicated runtime\'s owner release. The program process exits, a program of that Agent that is still running fails as aborted, and the next `cua_run_code` call starts a fresh process that re-creates the `cua` global. The Agent, its application grants and native connection, and the desktop applications themselves are unaffected. Held input is released. The runtime rejects that Agent\'s programs until the release settles, so the caller holds them back; after a failed release it rejects them until a later release succeeds. Resolves when no environment exists.', parameters: [{ name: 'agent', description: 'Agent whose `cua_run_code` state owner is released.' }], - returns: 'Completion after the process has exited and its output has drained.', - throws: ['When the process cleanup fails.'], + returns: 'Completion after the process has exited, its output has drained, and held-input cleanup has settled.', + throws: ['When environment or input cleanup fails, reporting both causes if both fail.'], }, { signature: 'releaseInputs(agent: Agent): Promise', @@ -11115,7 +11115,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ToolDispatchExecution', - declaration: 'export interface ToolDispatchExecution extends Omit {\n signal: AbortSignal;\n}', + declaration: 'export interface ToolDispatchExecution extends Omit {\n signal: AbortSignal;\n onFailure(cleanup: () => void | Promise): void;\n}', }, { name: 'ToolErrorInfo', From 53dc377548d47d743381e7ee3d3a48d38d2b5b0f Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 19 Nov 2026 21:42:29 +0800 Subject: [PATCH 60/73] Keep unregistered tool results on their synchronous publication path --- packages/core/tools/src/pipeline.ts | 35 +++++++++++++++++------------ 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/packages/core/tools/src/pipeline.ts b/packages/core/tools/src/pipeline.ts index 9db681684f..5b0973e55f 100644 --- a/packages/core/tools/src/pipeline.ts +++ b/packages/core/tools/src/pipeline.ts @@ -11,7 +11,7 @@ import { TOOL_ABORTED, TOOL_ABORTED_BEFORE_DISPATCH, ToolNotFoundError, ToolOutp import { APPROVAL_CANCELLED, APPROVAL_ERROR_NAME, APPROVAL_REJECTED, APPROVAL_UNAVAILABLE, type ApprovalErrorCode } from './error-codes.ts' import { validateJsonSchemaValue } from './json-schema.ts' import type { ToolsService } from './index.ts' -import type { ResolvedToolSet, ToolDefinition, ToolExecutionInput, ToolExecutionMode, ToolExecution, ToolRunContext, ToolExecutionResult, ToolExecutionSuccess, ToolErrorInfo, ToolExecutionToken, PreToolDecision, PostToolDecision } from './contracts.ts' +import type { ResolvedToolSet, ToolDefinition, ToolExecutionInput, ToolExecutionMode, ToolExecution, ToolRunContext, ToolExecutionResult, ToolExecutionSuccess, ToolExecutionFailure, ToolErrorInfo, ToolExecutionToken, PreToolDecision, PostToolDecision } from './contracts.ts' /** Executor-owned lookup and restrictions applied before extensible execution policy. */ export interface ToolExecutionSource { @@ -403,7 +403,7 @@ export class ToolExecutionPipeline { * @returns the materialized final result. * @internal */ - private async finish(exec: ToolRunContext, result: ToolExecutionResult): Promise { + private finish(exec: ToolRunContext, result: ToolExecutionResult): ToolExecutionResult | Promise { let materializedResult: ToolExecutionResult try { materializedResult = this.materializeFinalResult(result) @@ -418,18 +418,25 @@ export class ToolExecutionPipeline { } const cleanups = this.failureCleanups.get(exec) this.failureCleanups.delete(exec) - if (finalResult.isError && cleanups) { - const errors: string[] = [] - for (const cleanup of cleanups) { - try { await cleanup() } catch (error) { errors.push(toolErrorMessage(error)) } - } - if (errors.length) { - const feedback = `Tool cleanup failed: ${errors.join('\n')}` - finalResult = this.materializeFinalResult({ - ...finalResult, error: { ...finalResult.error, message: `${finalResult.error.message}\n${feedback}` }, - content: [...finalResult.content, { type: 'text', text: feedback }], - }) - } + if (finalResult.isError && cleanups) return this.finishFailure(exec, finalResult, cleanups) + this.notifyResult(exec, finalResult) + return finalResult + } + + /** Await all cleanup for this failed call and preserve the original error identity and policy feedback. */ + private async finishFailure(exec: ToolRunContext, result: ToolExecutionFailure, + cleanups: readonly (() => void | Promise)[]): Promise { + const errors: string[] = [] + for (const cleanup of cleanups) { + try { await cleanup() } catch (error) { errors.push(toolErrorMessage(error)) } + } + let finalResult: ToolExecutionResult = result + if (errors.length) { + const feedback = `Tool cleanup failed: ${errors.join('\n')}` + finalResult = this.materializeFinalResult({ + ...result, error: { ...result.error, message: `${result.error.message}\n${feedback}` }, + content: [...result.content, { type: 'text', text: feedback }], + }) } this.notifyResult(exec, finalResult) return finalResult From 05bdc17ca481c5d0c2aff264ef1581171d000f82 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 19 Nov 2026 21:44:05 +0800 Subject: [PATCH 61/73] Record real PostToolUse rejection and verify each reset failure combination --- docs/persistence-catalog.i18n.yaml | 4 +-- docs/persistence-catalog.md | 2 +- docs/persistence-catalog.zh.md | 2 +- docs/persistence-schema.json | 2 +- .../cua-mcp/tests/composition.spec.ts | 7 ++-- .../cua-posttool-block/runtime.cordis.yml | 11 ++++++ .../cua-posttool-block/session.v4.jsonl | 35 +++++++++++++++++++ .../session/cua-posttool-block/snapshot.yml | 8 +++++ .../workspace/codex-hooks.json | 15 ++++++++ 9 files changed, 78 insertions(+), 8 deletions(-) create mode 100644 snapshots/session/cua-posttool-block/runtime.cordis.yml create mode 100644 snapshots/session/cua-posttool-block/session.v4.jsonl create mode 100644 snapshots/session/cua-posttool-block/snapshot.yml create mode 100644 snapshots/session/cua-posttool-block/workspace/codex-hooks.json diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index 0e9777c1b6..71a6d616d1 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -1335,8 +1335,8 @@ en: 0080c345c319a4b5 zh: de1a8b3ed621ce21 /session-persistence-event-catalog/resolved-persistence-types/toolrestriction: - en: b2488366535b5fdc - zh: b64d50345521eb99 + en: d7caf05599b9e837 + zh: 9ef405c0a4dc9b19 /session-persistence-event-catalog/resolved-persistence-types/toolresultmessage: en: 9258f30a9c4e2a3a zh: c44d997d719e863c diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 687a7217e5..167dfa9f88 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -5360,7 +5360,7 @@ Sources: [`packages/llm/llm/src/types.ts:134`](../packages/llm/llm/src/types.ts) SHA-256: `3cfc3a56502da1f8c6153c2c56657bab4b749056968634dd0991d325ec1c919f` -Sources: [`packages/core/tools/src/contracts.ts:395`](../packages/core/tools/src/contracts.ts) +Sources: [`packages/core/tools/src/contracts.ts:402`](../packages/core/tools/src/contracts.ts) | Property | Presence | Type | |---|---|---| diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index 3d7901528d..11005413cc 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -5362,7 +5362,7 @@ SHA-256: `43e311235aa537df1bacdd92d144df8a952337a76e9ac892cdf670f1a797bad8` SHA-256: `3cfc3a56502da1f8c6153c2c56657bab4b749056968634dd0991d325ec1c919f` -来源:[`packages/core/tools/src/contracts.ts:395`](../packages/core/tools/src/contracts.ts) +来源:[`packages/core/tools/src/contracts.ts:402`](../packages/core/tools/src/contracts.ts) | 属性 | 存在性 | 类型 | |---|---|---| diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json index ed6ca4c0ce..bb73fe792d 100644 --- a/docs/persistence-schema.json +++ b/docs/persistence-schema.json @@ -224,7 +224,7 @@ {"digest":"3bec87f9e6ab3da03346f49923d3c51621debc0159df68605e543c3b2a026f90","names":[],"sources":["packages/llm/llm/src/types.ts:497"]}, {"digest":"3bfeb47b58606f4661904bc723da612782214c463d01e6d61cd6d6193d7374e1","names":[],"sources":[]}, {"digest":"3c2535ca0a2062f172f15344f8040755002b5ac506cf94fc4ebaa822b15feb8c","names":[],"sources":[]}, - {"digest":"3cfc3a56502da1f8c6153c2c56657bab4b749056968634dd0991d325ec1c919f","names":["packages/core/tools/src/contracts.ts#ToolRestriction"],"sources":["packages/core/tools/src/contracts.ts:395"]}, + {"digest":"3cfc3a56502da1f8c6153c2c56657bab4b749056968634dd0991d325ec1c919f","names":["packages/core/tools/src/contracts.ts#ToolRestriction"],"sources":["packages/core/tools/src/contracts.ts:402"]}, {"digest":"3d1339bcc98cb53714bf31ac4a6e7c9ce15a412dd58451778a383627367a4666","names":["packages/llm/llm/src/message.ts#SystemPromptMessageSource"],"sources":["packages/llm/llm/src/message.ts:54"]}, {"digest":"3d7d07060a7be77984feb651ea2bf1925d3e0477911d9d3ed86330d1e8ca6182","names":["packages/feedback/message-feedback/src/types.ts#MessageFeedbackItem"],"sources":["packages/feedback/message-feedback/src/types.ts:20"]}, {"digest":"3e0eff5946255ff05d88a10839c60305135801f97794ea48d409f8503303317e","names":[],"sources":[]}, diff --git a/packages/experimental/cua-mcp/tests/composition.spec.ts b/packages/experimental/cua-mcp/tests/composition.spec.ts index 3322edd7ab..4eb28d6039 100644 --- a/packages/experimental/cua-mcp/tests/composition.spec.ts +++ b/packages/experimental/cua-mcp/tests/composition.spec.ts @@ -396,10 +396,11 @@ describe('Computer Use MCP composition', () => { expect(texts(invalid)).toEqual(['invalid arguments: missing required property "description"']) }) - it.each([false, true])('reports environment reset failure after attempting input cleanup (input refused: %s)', async (refused) => { + it.each([[true, false], [false, true], [true, true]])('reports reset failures (environment: %s, input: %s)', async (environmentFails, refused) => { const { native, client, run } = await setup() await run('var app = await cua.getApp("test.fixture"); await app.sendKeyEvent("w", "down")') - const environment = vi.spyOn(NodeRuntime.prototype, 'release').mockRejectedValueOnce(new Error('Fixture process failed to exit')) + const environment = vi.spyOn(NodeRuntime.prototype, 'release') + if (environmentFails) environment.mockRejectedValueOnce(new Error('Fixture process failed to exit')) onTestFinished(() => { environment.mockRestore() }) const release = native.controlNext('releaseHeldInputs') const resetting = client.callTool({ name: 'cua_reset', arguments: {} }) @@ -410,7 +411,7 @@ describe('Computer Use MCP composition', () => { const result = await resetting expect(result.isError).toBe(true) const message = texts(result).join(' ') - expect(message).toContain('Fixture process failed to exit') + if (environmentFails) expect(message).toContain('Fixture process failed to exit') if (refused) expect(message).toContain('Fixture release refused') else expect(native.events).toEqual(['w:down', 'w:up']) }) diff --git a/snapshots/session/cua-posttool-block/runtime.cordis.yml b/snapshots/session/cua-posttool-block/runtime.cordis.yml new file mode 100644 index 0000000000..0a38b473eb --- /dev/null +++ b/snapshots/session/cua-posttool-block/runtime.cordis.yml @@ -0,0 +1,11 @@ +# Computer Use with the provider's default preset selection under the PTC tool executor, on a profile that composes no presets. +- insert: + - id: computer-use + name: '@deepseek-ai/dsh-computer-use' + - id: cua-run-code-fixture + name: '../cua-run-code/provider.mjs' + config: + allowedApps: + - id: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + name: Fixture + executablePath: /fixture/app diff --git a/snapshots/session/cua-posttool-block/session.v4.jsonl b/snapshots/session/cua-posttool-block/session.v4.jsonl new file mode 100644 index 0000000000..7f674b0cd9 --- /dev/null +++ b/snapshots/session/cua-posttool-block/session.v4.jsonl @@ -0,0 +1,35 @@ +{"type":"session","version":4,"id":"{{session:1}}","createdAt":1794200000000,"cwd":"{{cwd}}","isSeeded":false,"delegationDepth":0} +{"type":"permission/preset","data":{"preset":"danger-full-access"}} +{"type":"sandbox/mode","data":{"mode":"danger-full-access"}} +{"type":"approval/policy","data":{"policy":"never"}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Hold W in test.fixture using a CUA program. Report the result and any confirmed cleanup."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"}]}} +{"type":"turn/start","data":{"turn":1}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} +{"type":"step/start","data":{"turn":1,"step":1}} +{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt","sections":[{"name":"harness:identity","order":-1000,"state":"active","contentIndex":0},{"name":"deployment:persona-prefix","order":0,"state":"active","contentIndex":1},{"name":"tools:ptc-only","order":800,"state":"active","contentIndex":2},{"name":"tool:bash","order":1000,"state":"active","contentIndex":3},{"name":"tool:read","order":1100,"state":"active","contentIndex":4},{"name":"tool:write","order":1200,"state":"active","contentIndex":5},{"name":"tool:edit","order":1300,"state":"active","contentIndex":6},{"name":"tool:apply_patch","order":1350,"state":"active","contentIndex":7},{"name":"tool:glob","order":1400,"state":"active","contentIndex":8},{"name":"tool:grep","order":1500,"state":"active","contentIndex":9},{"name":"tool:jobs","order":1600,"state":"active","contentIndex":10},{"name":"tool:web_search","order":2000,"state":"active","contentIndex":11},{"name":"tool:web_fetch","order":2100,"state":"active","contentIndex":12},{"name":"tool:goal","order":2400,"state":"active","contentIndex":13},{"name":"tool:workflow","order":2600,"state":"active","contentIndex":14},{"name":"tool:subagent","order":2800,"state":"active","contentIndex":15},{"name":"computer-use:dsh-cua","order":3000,"state":"active","contentIndex":16},{"name":"tools:sdk","order":5000,"state":"active","contentIndex":17}]},"id":"{{message:2}}"}},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Hold W in test.fixture using a CUA program. Report the result and any confirmed cleanup."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} +{"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} +{"type":"session/title","data":{"title":"Hold W in test.fixture using","messageSeqs":[8],"source":{"kind":"fallback"}}} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua_first","name":"run_code","arguments":"{\"code\":\"await tools.cua_run_code({\\\"code\\\": \\\"var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"down\\\\\\\")\\\", \\\"description\\\": \\\"Hold W in the fixture\\\"})\",\"description\":\"Hold W\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"stream":[{"type":"chunk","time":1795095784699,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1795095784700,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_first","name":"run_code","arguments":"{\"code\":\"await tools.cua_run_code({\\\"code\\\": \\\"var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"down\\\\\\\")\\\", \\\"description\\\": \\\"Hold W in the fixture\\\"})\",\"description\":\"Hold W\"}"}}},{"type":"chunk","time":1795095784700,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua_first","name":"run_code","arguments":"{\"code\":\"await tools.cua_run_code({\\\"code\\\": \\\"var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"down\\\\\\\")\\\", \\\"description\\\": \\\"Hold W in the fixture\\\"})\",\"description\":\"Hold W\"}"}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua_run_code","arguments":{"code":"var app = await cua.getApp(\"test.fixture\"); await app.sendKeyEvent(\"w\", \"down\")","description":"Hold W in the fixture"}}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemPointer\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\",\"sendKeyEvent\",\"toggleMouse\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} +{"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1: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_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:3","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"w","direction":"down"}}}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:3","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"w","direction":"down"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua_run_code","arguments":{"code":"var app = await cua.getApp(\"test.fixture\"); await app.sendKeyEvent(\"w\", \"down\")","description":"Hold W in the fixture"},"isError":false,"content":[{"type":"text","text":"(cua_run_code completed with no output)"}]}} +{"type":"hook/invoked","data":{"turn":1,"point":"PostToolUse","dialect":"codex","handlerId":"codex:PostToolUse:1","matcher":"^run_code$"}} +{"type":"hook/result","data":{"turn":1,"point":"PostToolUse","handlerId":"codex:PostToolUse:1","decision":"block","exitCode":2,"stderrSummary":"tool output rejected by codex policy: summarize instead","durationMs":5.269749999999931}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"\nCUA inputs were released during cleanup:\n- Key \"w\", appHandle \"fixture-app\" (application input).\nThese inputs are no longer held.\n"}],"source":{"kind":"cua-inputs-released","form":"notice","summary":"CUA inputs released"},"role":"user","id":"{{message:5}}"}]}} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"cua_first"},"toolCallId":"cua_first","content":[{"type":"text","text":"tool output rejected by codex policy: summarize instead"}],"isError":true,"id":"{{message:6}}"},"error":{"name":"HookError","code":"HOOK_BLOCKED"}},"sourceEventSeqs":[14],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":1}} +{"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":"\nCUA inputs were released during cleanup:\n- Key \"w\", appHandle \"fixture-app\" (application input).\nThese inputs are no longer held.\n"}],"source":{"kind":"cua-inputs-released","form":"notice","summary":"CUA inputs released"},"role":"user","id":"{{message:5}}"},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"text","text":"The post-tool policy rejected the program output. Cleanup confirmed W was released."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:7}}"},"stream":[{"type":"chunk","time":1795095785319,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1795095785319,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"The post-tool policy rejected the program output. Cleanup confirmed W was released."}}},{"type":"chunk","time":1795095785319,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":2}} +{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/snapshots/session/cua-posttool-block/snapshot.yml b/snapshots/session/cua-posttool-block/snapshot.yml new file mode 100644 index 0000000000..7b92a41d4f --- /dev/null +++ b/snapshots/session/cua-posttool-block/snapshot.yml @@ -0,0 +1,8 @@ +version: 1 +scenario: cua-posttool-block +profile: headless +composition: ptc +recording: authored +header: + class: cua-run-code-ptc +permission: danger-full-access diff --git a/snapshots/session/cua-posttool-block/workspace/codex-hooks.json b/snapshots/session/cua-posttool-block/workspace/codex-hooks.json new file mode 100644 index 0000000000..cb9ec4d11c --- /dev/null +++ b/snapshots/session/cua-posttool-block/workspace/codex-hooks.json @@ -0,0 +1,15 @@ +{ + "hooks": { + "PostToolUse": [ + { + "matcher": "^run_code$", + "hooks": [ + { + "type": "command", + "command": "echo 'tool output rejected by codex policy: summarize instead' >&2; exit 2" + } + ] + } + ] + } +} From 25927c6fdb41d54a55b77682e7361fd0173cf0ee Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 19 Nov 2026 21:46:15 +0800 Subject: [PATCH 62/73] Publish the final outcome after post-execute policy settles --- packages/core/tools/src/pipeline.ts | 13 ++++++------- packages/core/tools/tests/tools.spec.ts | 2 +- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/packages/core/tools/src/pipeline.ts b/packages/core/tools/src/pipeline.ts index 5b0973e55f..ef54d39eca 100644 --- a/packages/core/tools/src/pipeline.ts +++ b/packages/core/tools/src/pipeline.ts @@ -376,6 +376,7 @@ export class ToolExecutionPipeline { return assertNever(outcome, 'scheduled tool outcome') } const { result } = outcome + let final: ToolExecutionResult try { const project = this.contentProjectors.get(exec) this.contentProjectors.delete(exec) @@ -384,15 +385,13 @@ export class ToolExecutionPipeline { ? result : this.markCanonical(exec, this.materializeFinalResult({ ...result, content })) const postResult = await this.postExecute(exec, projected) - return this.finish( - exec, - this.callerCancelled(exec) && !postResult.isError - ? this.cancellationResult(exec, postResult) - : postResult, - ) + final = this.callerCancelled(exec) && !postResult.isError + ? this.cancellationResult(exec, postResult) + : postResult } catch (error: unknown) { - return this.finish(exec, toolErrorResult(error)) + final = toolErrorResult(error) } + return this.finish(exec, final) } /** diff --git a/packages/core/tools/tests/tools.spec.ts b/packages/core/tools/tests/tools.spec.ts index da67785b70..d77ffb8b7a 100644 --- a/packages/core/tools/tests/tools.spec.ts +++ b/packages/core/tools/tests/tools.spec.ts @@ -591,7 +591,7 @@ describe('ToolRuntime', () => { const call = (id: string) => executeToolFixture(ctx, { signal: testToolSignal, callId: brandString(id), name: 'echo', arguments: {} }) expect((await call('ok')).isError).toBe(false) expect(events).toEqual(['succeeded']) - expect(() => registerLate!()).toThrow('during dispatch') + expect(() => { registerLate!() }).toThrow('during dispatch') ctx.on('tools/post-execute', async (): Promise => ({ kind: 'block', feedback: [{ type: 'text', text: 'rejected' }], info: { name: 'PolicyError', code: 'BLOCKED' }, }), { prepend: true }) From 46ca2d0d1acbca4e54642e6292255c00534a2d41 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 20 Nov 2026 11:16:19 +0800 Subject: [PATCH 63/73] Align held-input reminders with system keyboard release options --- .../cua-macos/native/tests/swift/SystemInputTests.swift | 1 + packages/experimental/cua/src/held-inputs.ts | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/experimental/cua-macos/native/tests/swift/SystemInputTests.swift b/packages/experimental/cua-macos/native/tests/swift/SystemInputTests.swift index 34ceac1c0a..0f192c6f7e 100644 --- a/packages/experimental/cua-macos/native/tests/swift/SystemInputTests.swift +++ b/packages/experimental/cua-macos/native/tests/swift/SystemInputTests.swift @@ -1,6 +1,7 @@ // Record synthesized events and desktop state queries without posting input to the user's desktop. import CoreGraphics import Darwin +import Foundation import Testing @testable import CuaNative diff --git a/packages/experimental/cua/src/held-inputs.ts b/packages/experimental/cua/src/held-inputs.ts index 328cb01de5..845b8150fc 100644 --- a/packages/experimental/cua/src/held-inputs.ts +++ b/packages/experimental/cua/src/held-inputs.ts @@ -19,7 +19,7 @@ function renderInputs(inputs: z.infer, state: 'held' | 'relea const title = state === 'held' ? 'CUA inputs are still held:' : 'CUA inputs were released during cleanup:' return ['', title, ...rows, state === 'held' - ? "They remain pressed across programs and turns. Release them explicitly with sendKeyEvent(key, 'up') or toggleMouse(button, 'up') on the same target when no longer needed." + ? "They remain pressed across programs and turns. To release them, call sendKeyEvent or toggleMouse on the same target with direction 'up' and the same input options as the down." : 'These inputs are no longer held.', ''].join('\n') } From ab4cfd8dd7f288ba45fe43890d727bd90e7b5080 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 20 Nov 2026 11:19:47 +0800 Subject: [PATCH 64/73] Refresh CUA replay outputs for the merged system input protocol --- .../profiles/cua-mcp/expected/held-inputs.json | 2 +- snapshots/sdk/cua-run-code/session.v4.jsonl | 2 +- .../system-prompt.expected.md | 6 ++++-- .../cua-native/system-prompt.expected.md | 18 +++++++++--------- .../cua-posttool-block/session.v4.jsonl | 2 +- .../cua-ptc-scoped/system-prompt.expected.md | 6 ++++-- .../session/cua-ptc/system-prompt.expected.md | 18 +++++++++--------- .../cua-run-code-ptc-scoped/session.v4.jsonl | 2 +- .../system-prompt.expected.md | 4 +++- .../session/cua-run-code-ptc/session.v4.jsonl | 6 +++--- .../cua-run-code-scoped/session.v4.jsonl | 2 +- .../session/cua-run-code/session.v4.jsonl | 10 +++++----- .../system-prompt.expected.md | 18 +++++++++--------- 13 files changed, 51 insertions(+), 45 deletions(-) diff --git a/apps/cli/tests/profiles/cua-mcp/expected/held-inputs.json b/apps/cli/tests/profiles/cua-mcp/expected/held-inputs.json index 099ba2ed86..03817767b3 100644 --- a/apps/cli/tests/profiles/cua-mcp/expected/held-inputs.json +++ b/apps/cli/tests/profiles/cua-mcp/expected/held-inputs.json @@ -6,7 +6,7 @@ }, { "type": "text", - "text": "\nCUA inputs are still held:\n- Key \"shift\", appHandle \"fixture-app\" (application input).\n- Mouse left, appHandle \"fixture-app\", windowId \"7\" (window input).\n- Key \"w\", appHandle \"fixture-app\" (application input).\nThey remain pressed across programs and turns. Release them explicitly with sendKeyEvent(key, 'up') or toggleMouse(button, 'up') on the same target when no longer needed.\n" + "text": "\nCUA inputs are still held:\n- Key \"shift\", appHandle \"fixture-app\" (application input).\n- Mouse left, appHandle \"fixture-app\", windowId \"7\" (window input).\n- Key \"w\", appHandle \"fixture-app\" (application input).\nThey remain pressed across programs and turns. To release them, call sendKeyEvent or toggleMouse on the same target with direction 'up' and the same input options as the down.\n" } ] } diff --git a/snapshots/sdk/cua-run-code/session.v4.jsonl b/snapshots/sdk/cua-run-code/session.v4.jsonl index 1ae3106421..52686edd48 100644 --- a/snapshots/sdk/cua-run-code/session.v4.jsonl +++ b/snapshots/sdk/cua-run-code/session.v4.jsonl @@ -18,7 +18,7 @@ {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:6}}"},"stream":[{"type":"chunk","time":1792108800000,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792108800000,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}}},{"type":"chunk","time":1792108800000,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemPointer\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\",\"sendKeyEvent\",\"toggleMouse\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemInput\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\",\"sendKeyEvent\",\"toggleMouse\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first: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_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:3","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} diff --git a/snapshots/session/cua-native-scoped/system-prompt.expected.md b/snapshots/session/cua-native-scoped/system-prompt.expected.md index e754d2f50b..be6e2cff7b 100644 --- a/snapshots/session/cua-native-scoped/system-prompt.expected.md +++ b/snapshots/session/cua-native-scoped/system-prompt.expected.md @@ -75,7 +75,7 @@ Leave useSystemInput unset for ordinary mouseMove, toggleMouse, click, drag, pre Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemInput?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemInput omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemInput: true on both down and up. Physical moves can then drag, including your own mouse movements. The turn ending or the connection closing releases a remaining system hold. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Send 'up' to release a held button immediately. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemInput: true on down. Up uses the input route and window saved by down. Physical moves can then drag, including your own mouse movements. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean, useSystemInput?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. With useSystemInput: true, the system pointer moves to the target and keyboard modifiers are pressed around the click, including release on cancellation. Verify the expected effect before typing or retrying. - 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. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemInput?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemInput or passing false directs the drag to the window without asking for mouse control. System input requires an unobscured foreground target, presses the requested keyboard modifiers, and releases the mouse button before those modifiers, including on cancellation. @@ -87,7 +87,9 @@ Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - 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?: Modifier[], options?: { useSystemInput?: boolean }) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. System input requires the selected foreground application and sends modifiers and the main key through the system keyboard queue, then releases them in reverse order. -- sendKeyEvent(key: string, direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. System input requires the selected app in the foreground for down; match useSystemInput on up, which releases the held key even after focus changes. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +- sendKeyEvent(key: string, direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. System down requires the selected foreground app; use the same useSystemInput value for explicit key up. + +Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. After a DSH stop, the next CUA operation waits for any pending cleanup. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/snapshots/session/cua-native/system-prompt.expected.md b/snapshots/session/cua-native/system-prompt.expected.md index 8ae96768f3..728313151e 100644 --- a/snapshots/session/cua-native/system-prompt.expected.md +++ b/snapshots/session/cua-native/system-prompt.expected.md @@ -43,7 +43,7 @@ Signatures show resolved return values after await. ActionResult = { dispatched: Supported modifier names depend on the platform and the operation; see the platform guidance. Setup and discovery: -- cua.getCapabilities() -> { platform: string, permissions: { accessibility: boolean, screenRecording: boolean }, appLevelAccessibility: boolean, systemPointer: 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.getCapabilities() -> { platform: string, permissions: { accessibility: boolean, screenRecording: boolean }, appLevelAccessibility: boolean, systemInput: 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() -> { id: string, displayName: string, isRunning: boolean, pid?: number }[] — list applications the provider exposes for selection with their current running state; pass the returned id unchanged to cua.getApp. Each row represents one running process. To select one of several instances with the same name or bundle ID, pass String(row.pid) to cua.getApp. - cua.findApps(query: string) -> { id: string, displayName: string, path: string, isRunning: boolean, pid?: number }[] — search installed applications, including stopped matches. Running installation matches include their process ID. Stopped matches have no pid. - cua.getState() -> { apps: { id: string, displayName: string, isRunning: boolean, pid?: number }[], browsers: [] } — summarize the same provider discovery; this is not an accessibility observation. @@ -71,14 +71,14 @@ Use an explicit window for screenshots. - getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. ## Simulated mouse -Leave useSystemPointer unset for ordinary mouseMove, drag, and toggleMouse calls, even after approval. Prefer selectText for a supported text range and ordinary window-directed drag for a draggable control. If the effect is unclear, inspect the window before choosing another action. Request the system pointer only when the user explicitly asks for it or the intended effect requires it. +Leave useSystemInput unset for ordinary mouseMove, toggleMouse, click, drag, pressKey, and sendKeyEvent calls, even after approval. Prefer selectText for a supported text range and ordinary window-directed drag for a draggable control. If the effect is unclear, inspect the window before choosing another action. Request system input only when the user explicitly asks for it or the intended effect requires it. Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. -- mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemPointer?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemPointer omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemPointer?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Send 'up' to release a held button immediately. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemPointer: true on down. Up uses the input route and window saved by down. Physical moves can then drag, including your own mouse movements. -- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], 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. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying. +- mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemInput?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemInput omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Send 'up' to release a held button immediately. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemInput: true on down. Up uses the input route and window saved by down. Physical moves can then drag, including your own mouse movements. +- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean, useSystemInput?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. With useSystemInput: true, the system pointer moves to the target and keyboard modifiers are pressed around the click, including release on cancellation. Verify the expected effect before typing or retrying. - 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. -- drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemPointer?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control. An explicit system drag shares the session decision with mouseMove and holds the chosen button along the path in the unobscured foreground window. +- drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemInput?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemInput or passing false directs the drag to the window without asking for mouse control. System input requires an unobscured foreground target, presses the requested keyboard modifiers, and releases the mouse button before those modifiers, including on cancellation. A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current accessibility observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. FOREGROUND_REQUIRED means explain the need, then explicitly activate the target and observe again; activation is never automatic. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry. @@ -86,8 +86,8 @@ A string target is an element id; coordinate targets are [x, y] and are pixels i Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - 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?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. +- pressKey(key: string, modifiers?: Modifier[], options?: { useSystemInput?: boolean }) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. System input requires the selected foreground application and sends modifiers and the main key through the system keyboard queue, then releases them in reverse order. +- sendKeyEvent(key: string, direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. System down requires the selected foreground app; use the same useSystemInput value for explicit key up. Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. After a DSH stop, the next CUA operation waits for any pending cleanup. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. @@ -95,7 +95,7 @@ click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, a Recent activity notices identify when another agent or external input was last detected on a window you observed. You may continue using the window. Recheck its state if your next action depends on what you saw. -Only if the task cannot be completed without moving the user’s pointer, call await win.mouseMove(target, { useSystemPointer: true }). Prefer an advertised accessibility action, a click on a visible control, or browser tools when possible. The question interrupts the user. When approval is disabled an explicit move can act immediately. Pass true on every physical move, even after approval. Omitting the option or passing false uses the default hover route without prompting. Approval or refusal lasts until this session closes or DSH restarts. A refusal sends no input. If the user dismisses the request, ask again only if they request it. Wait for an outstanding request to finish. Subagents cannot request system mouse control. +Pass useSystemInput: true only when the task requires system keyboard or mouse input. Omitting the option or passing false uses the provider default. When approval is enabled, the first explicit system input requests permission; otherwise it executes immediately. Prefer a supported non-system action when it meets the task. The approval question interrupts the user; approval or refusal lasts until this session closes or DSH restarts. Approval does not change later calls: pass true on each system operation. If the user dismisses the request, ask again only if they request it. Wait for an outstanding request to finish. Subagents cannot request system input. AX read defaults: maxElements=5000, maxDepth=50. diff --git a/snapshots/session/cua-posttool-block/session.v4.jsonl b/snapshots/session/cua-posttool-block/session.v4.jsonl index 7f674b0cd9..ddfb71b416 100644 --- a/snapshots/session/cua-posttool-block/session.v4.jsonl +++ b/snapshots/session/cua-posttool-block/session.v4.jsonl @@ -16,7 +16,7 @@ {"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua_first","name":"run_code","arguments":"{\"code\":\"await tools.cua_run_code({\\\"code\\\": \\\"var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"down\\\\\\\")\\\", \\\"description\\\": \\\"Hold W in the fixture\\\"})\",\"description\":\"Hold W\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua_run_code","arguments":{"code":"var app = await cua.getApp(\"test.fixture\"); await app.sendKeyEvent(\"w\", \"down\")","description":"Hold W in the fixture"}}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemPointer\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\",\"sendKeyEvent\",\"toggleMouse\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemInput\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\",\"sendKeyEvent\",\"toggleMouse\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1: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_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:3","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"w","direction":"down"}}}} diff --git a/snapshots/session/cua-ptc-scoped/system-prompt.expected.md b/snapshots/session/cua-ptc-scoped/system-prompt.expected.md index c3e975f0d5..f002fde79b 100644 --- a/snapshots/session/cua-ptc-scoped/system-prompt.expected.md +++ b/snapshots/session/cua-ptc-scoped/system-prompt.expected.md @@ -77,7 +77,7 @@ Leave useSystemInput unset for ordinary mouseMove, toggleMouse, click, drag, pre Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemInput?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemInput omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemInput: true on both down and up. Physical moves can then drag, including your own mouse movements. The turn ending or the connection closing releases a remaining system hold. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Send 'up' to release a held button immediately. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemInput: true on down. Up uses the input route and window saved by down. Physical moves can then drag, including your own mouse movements. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean, useSystemInput?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. With useSystemInput: true, the system pointer moves to the target and keyboard modifiers are pressed around the click, including release on cancellation. Verify the expected effect before typing or retrying. - 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. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemInput?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemInput or passing false directs the drag to the window without asking for mouse control. System input requires an unobscured foreground target, presses the requested keyboard modifiers, and releases the mouse button before those modifiers, including on cancellation. @@ -89,7 +89,9 @@ Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - 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?: Modifier[], options?: { useSystemInput?: boolean }) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. System input requires the selected foreground application and sends modifiers and the main key through the system keyboard queue, then releases them in reverse order. -- sendKeyEvent(key: string, direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. System input requires the selected app in the foreground for down; match useSystemInput on up, which releases the held key even after focus changes. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +- sendKeyEvent(key: string, direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. System down requires the selected foreground app; use the same useSystemInput value for explicit key up. + +Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. After a DSH stop, the next CUA operation waits for any pending cleanup. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index 18bf822f0f..fd6b45241e 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -45,7 +45,7 @@ Signatures show resolved return values after await. ActionResult = { dispatched: Supported modifier names depend on the platform and the operation; see the platform guidance. Setup and discovery: -- cua.getCapabilities() -> { platform: string, permissions: { accessibility: boolean, screenRecording: boolean }, appLevelAccessibility: boolean, systemPointer: 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.getCapabilities() -> { platform: string, permissions: { accessibility: boolean, screenRecording: boolean }, appLevelAccessibility: boolean, systemInput: 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() -> { id: string, displayName: string, isRunning: boolean, pid?: number }[] — list applications the provider exposes for selection with their current running state; pass the returned id unchanged to cua.getApp. Each row represents one running process. To select one of several instances with the same name or bundle ID, pass String(row.pid) to cua.getApp. - cua.findApps(query: string) -> { id: string, displayName: string, path: string, isRunning: boolean, pid?: number }[] — search installed applications, including stopped matches. Running installation matches include their process ID. Stopped matches have no pid. - cua.getState() -> { apps: { id: string, displayName: string, isRunning: boolean, pid?: number }[], browsers: [] } — summarize the same provider discovery; this is not an accessibility observation. @@ -73,14 +73,14 @@ Use an explicit window for screenshots. - getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. ## Simulated mouse -Leave useSystemPointer unset for ordinary mouseMove, drag, and toggleMouse calls, even after approval. Prefer selectText for a supported text range and ordinary window-directed drag for a draggable control. If the effect is unclear, inspect the window before choosing another action. Request the system pointer only when the user explicitly asks for it or the intended effect requires it. +Leave useSystemInput unset for ordinary mouseMove, toggleMouse, click, drag, pressKey, and sendKeyEvent calls, even after approval. Prefer selectText for a supported text range and ordinary window-directed drag for a draggable control. If the effect is unclear, inspect the window before choosing another action. Request system input only when the user explicitly asks for it or the intended effect requires it. Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. -- mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemPointer?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemPointer omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemPointer?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Send 'up' to release a held button immediately. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemPointer: true on down. Up uses the input route and window saved by down. Physical moves can then drag, including your own mouse movements. -- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], 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. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying. +- mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemInput?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemInput omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Send 'up' to release a held button immediately. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemInput: true on down. Up uses the input route and window saved by down. Physical moves can then drag, including your own mouse movements. +- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean, useSystemInput?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. With useSystemInput: true, the system pointer moves to the target and keyboard modifiers are pressed around the click, including release on cancellation. Verify the expected effect before typing or retrying. - 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. -- drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemPointer?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control. An explicit system drag shares the session decision with mouseMove and holds the chosen button along the path in the unobscured foreground window. +- drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemInput?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemInput or passing false directs the drag to the window without asking for mouse control. System input requires an unobscured foreground target, presses the requested keyboard modifiers, and releases the mouse button before those modifiers, including on cancellation. A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current accessibility observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. FOREGROUND_REQUIRED means explain the need, then explicitly activate the target and observe again; activation is never automatic. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry. @@ -88,8 +88,8 @@ A string target is an element id; coordinate targets are [x, y] and are pixels i Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - 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?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. +- pressKey(key: string, modifiers?: Modifier[], options?: { useSystemInput?: boolean }) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. System input requires the selected foreground application and sends modifiers and the main key through the system keyboard queue, then releases them in reverse order. +- sendKeyEvent(key: string, direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. System down requires the selected foreground app; use the same useSystemInput value for explicit key up. Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. After a DSH stop, the next CUA operation waits for any pending cleanup. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. @@ -97,7 +97,7 @@ click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, a Recent activity notices identify when another agent or external input was last detected on a window you observed. You may continue using the window. Recheck its state if your next action depends on what you saw. -Only if the task cannot be completed without moving the user’s pointer, call await win.mouseMove(target, { useSystemPointer: true }). Prefer an advertised accessibility action, a click on a visible control, or browser tools when possible. The question interrupts the user. When approval is disabled an explicit move can act immediately. Pass true on every physical move, even after approval. Omitting the option or passing false uses the default hover route without prompting. Approval or refusal lasts until this session closes or DSH restarts. A refusal sends no input. If the user dismisses the request, ask again only if they request it. Wait for an outstanding request to finish. Subagents cannot request system mouse control. +Pass useSystemInput: true only when the task requires system keyboard or mouse input. Omitting the option or passing false uses the provider default. When approval is enabled, the first explicit system input requests permission; otherwise it executes immediately. Prefer a supported non-system action when it meets the task. The approval question interrupts the user; approval or refusal lasts until this session closes or DSH restarts. Approval does not change later calls: pass true on each system operation. If the user dismisses the request, ask again only if they request it. Wait for an outstanding request to finish. Subagents cannot request system input. AX read defaults: maxElements=5000, maxDepth=50. diff --git a/snapshots/session/cua-run-code-ptc-scoped/session.v4.jsonl b/snapshots/session/cua-run-code-ptc-scoped/session.v4.jsonl index a6866a4282..e4380520e5 100644 --- a/snapshots/session/cua-run-code-ptc-scoped/session.v4.jsonl +++ b/snapshots/session/cua-run-code-ptc-scoped/session.v4.jsonl @@ -16,7 +16,7 @@ {"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua_first","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"globalThis.visits = 1; var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))\\\", description: \\\"Select the fixture window and click Increment\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Select the fixture window and click Increment\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua_run_code","arguments":{"code":"globalThis.visits = 1; var app = await cua.getApp(\"test.fixture\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\"0\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))","description":"Select the fixture window and click Increment"}}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemInput\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemInput\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\",\"sendKeyEvent\",\"toggleMouse\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1: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_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:3","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} diff --git a/snapshots/session/cua-run-code-ptc-scoped/system-prompt.expected.md b/snapshots/session/cua-run-code-ptc-scoped/system-prompt.expected.md index 5046017207..012d55a6c4 100644 --- a/snapshots/session/cua-run-code-ptc-scoped/system-prompt.expected.md +++ b/snapshots/session/cua-run-code-ptc-scoped/system-prompt.expected.md @@ -73,7 +73,7 @@ Use an explicit window for screenshots. ## Simulated mouse Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Send 'up' to release a held button immediately. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], 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. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. @@ -87,6 +87,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. +Explicit downs from sendKeyEvent and toggleMouse remain held across programs and turns until an explicit up releases them through the same target. After a successful run_code or cua_run_code, a system reminder lists any remaining keys and mouse buttons, their targets and input modes. No reminder is added when none remain. Program failure, a received cancellation, connection closure, and disposal release owned inputs together in reverse dispatch order. After a DSH stop, the next CUA operation waits for any pending cleanup. A client pause between completed MCP calls is not observable by the server, so held input can remain pressed. pressKey, typeText, click, and complete drag release their own inputs within the operation. + click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. AX read defaults: maxElements=2000, maxDepth=25. diff --git a/snapshots/session/cua-run-code-ptc/session.v4.jsonl b/snapshots/session/cua-run-code-ptc/session.v4.jsonl index 1041a1d412..c64184299b 100644 --- a/snapshots/session/cua-run-code-ptc/session.v4.jsonl +++ b/snapshots/session/cua-run-code-ptc/session.v4.jsonl @@ -16,7 +16,7 @@ {"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua_first","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"globalThis.visits = 1; var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"down\\\\\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))\\\", description: \\\"Select the fixture window and click Increment\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Select the fixture window and click Increment\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua_run_code","arguments":{"code":"globalThis.visits = 1; var app = await cua.getApp(\"test.fixture\"); await app.sendKeyEvent(\"w\", \"down\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\"0\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))","description":"Select the fixture window and click Increment"}}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemPointer\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\",\"sendKeyEvent\",\"toggleMouse\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemInput\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\",\"sendKeyEvent\",\"toggleMouse\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1: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_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:3","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"w","direction":"down"}}}} @@ -27,11 +27,11 @@ {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:5","name":"cua","arguments":{"method":"click","params":{"appHandle":"fixture-app","windowId":"7","snapshotId":"fixture-snapshot-1","elementId":"0"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua_run_code","arguments":{"code":"globalThis.visits = 1; var app = await cua.getApp(\"test.fixture\"); await app.sendKeyEvent(\"w\", \"down\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\"0\"); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId }))","description":"Select the fixture window and click Increment"},"isError":false,"content":[{"type":"text","text":"{\"visits\":1,\"bindings\":[\"cua\"],\"app\":\"fixture-app\",\"window\":\"7\"}\n"}]}} {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"cua_first"},"toolCallId":"cua_first","content":[{"type":"text","text":"{\"cuaTools\":[\"cua_run_code\"],\"logs\":[\"{\\\"visits\\\":1,\\\"bindings\\\":[\\\"cua\\\"],\\\"app\\\":\\\"fixture-app\\\",\\\"window\\\":\\\"7\\\"}\\n\"]}\n"}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} -{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"\nCUA inputs are still held:\n- Key \"w\", appHandle \"fixture-app\" (application input).\nThey remain pressed across programs and turns. Release them explicitly with sendKeyEvent(key, 'up') or toggleMouse(button, 'up') on the same target when no longer needed.\n"}],"source":{"kind":"cua-held-inputs","form":"notice","summary":"CUA inputs remain held"},"role":"user","id":"{{message:6}}"}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"\nCUA inputs are still held:\n- Key \"w\", appHandle \"fixture-app\" (application input).\nThey remain pressed across programs and turns. To release them, call sendKeyEvent or toggleMouse on the same target with direction 'up' and the same input options as the down.\n"}],"source":{"kind":"cua-held-inputs","form":"notice","summary":"CUA inputs remain held"},"role":"user","id":"{{message:6}}"}]}} {"type":"step/end","data":{"turn":1,"step":1}} {"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":"\nCUA inputs are still held:\n- Key \"w\", appHandle \"fixture-app\" (application input).\nThey remain pressed across programs and turns. Release them explicitly with sendKeyEvent(key, 'up') or toggleMouse(button, 'up') on the same target when no longer needed.\n"}],"source":{"kind":"cua-held-inputs","form":"notice","summary":"CUA inputs remain held"},"role":"user","id":"{{message:6}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nCUA inputs are still held:\n- Key \"w\", appHandle \"fixture-app\" (application input).\nThey remain pressed across programs and turns. To release them, call sendKeyEvent or toggleMouse on the same target with direction 'up' and the same input options as the down.\n"}],"source":{"kind":"cua-held-inputs","form":"notice","summary":"CUA inputs remain held"},"role":"user","id":"{{message:6}}"},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua_reuse","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"up\\\\\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\\\", description: \\\"Reuse the retained application and window\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Reuse the retained application and window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:7}}"},"stream":[{"type":"chunk","time":1795057089246,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1795057089246,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_reuse","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"up\\\\\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\\\", description: \\\"Reuse the retained application and window\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Reuse the retained application and window\"}"}}},{"type":"chunk","time":1795057089246,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"cua_reuse","name":"run_code","arguments":"{\"code\":\"const program = await tools.cua_run_code({ code: \\\"await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"up\\\\\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\\\\\"0\\\\\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))\\\", description: \\\"Reuse the retained application and window\\\" });\\ninspect(JSON.stringify({ cuaTools: Object.keys(tools).filter(name => name.startsWith(\\\"cua\\\")), logs: program.logs }))\",\"description\":\"Reuse the retained application and window\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:1","name":"cua_run_code","arguments":{"code":"await app.sendKeyEvent(\"w\", \"up\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\"0\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) }))","description":"Reuse the retained application and window"}}} diff --git a/snapshots/session/cua-run-code-scoped/session.v4.jsonl b/snapshots/session/cua-run-code-scoped/session.v4.jsonl index 5caac1f81c..a9d670cd72 100644 --- a/snapshots/session/cua-run-code-scoped/session.v4.jsonl +++ b/snapshots/session/cua-run-code-scoped/session.v4.jsonl @@ -16,7 +16,7 @@ {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"stream":[{"type":"chunk","time":1794291763110,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1794291763110,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}}},{"type":"chunk","time":1794291763110,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemPointer\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\",\"sendKeyEvent\",\"toggleMouse\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemInput\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\",\"sendKeyEvent\",\"toggleMouse\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first: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_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:3","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":"7"}}}} diff --git a/snapshots/session/cua-run-code/session.v4.jsonl b/snapshots/session/cua-run-code/session.v4.jsonl index 4a60911d92..576f4fe563 100644 --- a/snapshots/session/cua-run-code/session.v4.jsonl +++ b/snapshots/session/cua-run-code/session.v4.jsonl @@ -16,7 +16,7 @@ {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); await app.sendKeyEvent(\\\"w\\\", \\\"down\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"stream":[{"type":"chunk","time":1795061770766,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1795061770766,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); await app.sendKeyEvent(\\\"w\\\", \\\"down\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}}},{"type":"chunk","time":1795061770767,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua_first","name":"cua_run_code","arguments":"{\"code\":\"globalThis.visits = 1; var app = await cua.getApp(\\\"test.fixture\\\"); await app.sendKeyEvent(\\\"w\\\", \\\"down\\\"); var win = await app.getWindow('7'); await win.getAccessibilityTree(); await win.click(\\\"0\\\"); var screenshot = await win.getScreenshot(); inspect(JSON.stringify({ visits, bindings: Object.keys(tools), app: app.appHandle, window: win.windowId })); inspect(screenshot)\",\"description\":\"Select and capture the fixture window\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemPointer\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\",\"sendKeyEvent\",\"toggleMouse\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}},"isError":false,"content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"systemInput\":false,\"methods\":[\"getCapabilities\",\"getApp\",\"getState\",\"click\",\"screenshot\",\"sendKeyEvent\",\"toggleMouse\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:2","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first: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_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:3","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"w","direction":"down"}}}} @@ -28,11 +28,11 @@ {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:6","name":"cua","arguments":{"method":"screenshot","params":{"appHandle":"fixture-app","windowId":"7"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first: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":1,"message":{"role":"tool","source":{"kind":"tool","callId":"cua_first"},"toolCallId":"cua_first","content":[{"type":"text","text":"{\"visits\":1,\"bindings\":[\"cua\"],\"app\":\"fixture-app\",\"window\":\"7\"}\n"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[15],"surfaceOp":"append"} -{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"\nCUA inputs are still held:\n- Key \"w\", appHandle \"fixture-app\" (application input).\nThey remain pressed across programs and turns. Release them explicitly with sendKeyEvent(key, 'up') or toggleMouse(button, 'up') on the same target when no longer needed.\n"}],"source":{"kind":"cua-held-inputs","form":"notice","summary":"CUA inputs remain held"},"role":"user","id":"{{message:6}}"}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"\nCUA inputs are still held:\n- Key \"w\", appHandle \"fixture-app\" (application input).\nThey remain pressed across programs and turns. To release them, call sendKeyEvent or toggleMouse on the same target with direction 'up' and the same input options as the down.\n"}],"source":{"kind":"cua-held-inputs","form":"notice","summary":"CUA inputs remain held"},"role":"user","id":"{{message:6}}"}]}} {"type":"step/end","data":{"turn":1,"step":1}} {"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":"\nCUA inputs are still held:\n- Key \"w\", appHandle \"fixture-app\" (application input).\nThey remain pressed across programs and turns. Release them explicitly with sendKeyEvent(key, 'up') or toggleMouse(button, 'up') on the same target when no longer needed.\n"}],"source":{"kind":"cua-held-inputs","form":"notice","summary":"CUA inputs remain held"},"role":"user","id":"{{message:6}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nCUA inputs are still held:\n- Key \"w\", appHandle \"fixture-app\" (application input).\nThey remain pressed across programs and turns. To release them, call sendKeyEvent or toggleMouse on the same target with direction 'up' and the same input options as the down.\n"}],"source":{"kind":"cua-held-inputs","form":"notice","summary":"CUA inputs remain held"},"role":"user","id":"{{message:6}}"},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua_reuse","name":"cua_run_code","arguments":"{\"code\":\"await app.sendKeyEvent(\\\"w\\\", \\\"up\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) })); await win.toggleMouse(\\\"left\\\", \\\"down\\\"); await app.sendKeyEvent(\\\"d\\\", \\\"down\\\")\",\"description\":\"Reuse the retained application and window\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:7}}"},"stream":[{"type":"chunk","time":1795061771077,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1795061771077,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_reuse","name":"cua_run_code","arguments":"{\"code\":\"await app.sendKeyEvent(\\\"w\\\", \\\"up\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) })); await win.toggleMouse(\\\"left\\\", \\\"down\\\"); await app.sendKeyEvent(\\\"d\\\", \\\"down\\\")\",\"description\":\"Reuse the retained application and window\"}"}}},{"type":"chunk","time":1795061771077,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"cua_reuse","name":"cua_run_code","arguments":"{\"code\":\"await app.sendKeyEvent(\\\"w\\\", \\\"up\\\"); globalThis.visits++; await win.getAccessibilityTree(); await win.click(\\\"0\\\"); inspect(JSON.stringify({ visits, app: app.appHandle, window: win.windowId, tree: await win.getAccessibilityTree(), bindings: Object.keys(tools) })); await win.toggleMouse(\\\"left\\\", \\\"down\\\"); await app.sendKeyEvent(\\\"d\\\", \\\"down\\\")\",\"description\":\"Reuse the retained application and window\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:1","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"w","direction":"up"}}}} @@ -48,11 +48,11 @@ {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:6","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"d","direction":"down"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_reuse","parentCallId":"cua_reuse","subCallId":"cua_reuse:ptc:6","name":"cua","arguments":{"method":"sendKeyEvent","params":{"appHandle":"fixture-app","key":"d","direction":"down"}},"isError":false,"content":[{"type":"text","text":"{\"dispatched\":true}"}]}} {"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"cua_reuse"},"toolCallId":"cua_reuse","content":[{"type":"text","text":"{\"visits\":2,\"app\":\"fixture-app\",\"window\":\"7\",\"tree\":\"- [0] AXButton \\\"Increment\\\"\\n- AXStaticText \\\"Count: 2\\\"\",\"bindings\":[\"cua\"]}\n"}],"isError":false,"id":"{{message:8}}"}},"sourceEventSeqs":[35],"surfaceOp":"append"} -{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"\nCUA inputs are still held:\n- Mouse left, appHandle \"fixture-app\", windowId \"7\" (window input).\n- Key \"d\", appHandle \"fixture-app\" (application input).\nThey remain pressed across programs and turns. Release them explicitly with sendKeyEvent(key, 'up') or toggleMouse(button, 'up') on the same target when no longer needed.\n"}],"source":{"kind":"cua-held-inputs","form":"notice","summary":"CUA inputs remain held"},"role":"user","id":"{{message:9}}"}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"\nCUA inputs are still held:\n- Mouse left, appHandle \"fixture-app\", windowId \"7\" (window input).\n- Key \"d\", appHandle \"fixture-app\" (application input).\nThey remain pressed across programs and turns. To release them, call sendKeyEvent or toggleMouse on the same target with direction 'up' and the same input options as the down.\n"}],"source":{"kind":"cua-held-inputs","form":"notice","summary":"CUA inputs remain held"},"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":"\nCUA inputs are still held:\n- Mouse left, appHandle \"fixture-app\", windowId \"7\" (window input).\n- Key \"d\", appHandle \"fixture-app\" (application input).\nThey remain pressed across programs and turns. Release them explicitly with sendKeyEvent(key, 'up') or toggleMouse(button, 'up') on the same target when no longer needed.\n"}],"source":{"kind":"cua-held-inputs","form":"notice","summary":"CUA inputs remain held"},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nCUA inputs are still held:\n- Mouse left, appHandle \"fixture-app\", windowId \"7\" (window input).\n- Key \"d\", appHandle \"fixture-app\" (application input).\nThey remain pressed across programs and turns. To release them, call sendKeyEvent or toggleMouse on the same target with direction 'up' and the same input options as the down.\n"}],"source":{"kind":"cua-held-inputs","form":"notice","summary":"CUA inputs remain held"},"role":"user","id":"{{message:9}}"},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"text","text":"The retained application and window report Count: 2. The counter persisted across calls, and the program exposes only tools.cua. The screenshot was attached after the first call."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:10}}"},"stream":[{"type":"chunk","time":1795061771116,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1795061771116,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"The retained application and window report Count: 2. The counter persisted across calls, and the program exposes only tools.cua. The screenshot was attached after the first call."}}},{"type":"chunk","time":1795061771116,"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/ptc-script-retained/system-prompt.expected.md b/snapshots/session/ptc-script-retained/system-prompt.expected.md index d790481984..e387577d3f 100644 --- a/snapshots/session/ptc-script-retained/system-prompt.expected.md +++ b/snapshots/session/ptc-script-retained/system-prompt.expected.md @@ -45,7 +45,7 @@ Signatures show resolved return values after await. ActionResult = { dispatched: Supported modifier names depend on the platform and the operation; see the platform guidance. Setup and discovery: -- cua.getCapabilities() -> { platform: string, permissions: { accessibility: boolean, screenRecording: boolean }, appLevelAccessibility: boolean, systemPointer: 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.getCapabilities() -> { platform: string, permissions: { accessibility: boolean, screenRecording: boolean }, appLevelAccessibility: boolean, systemInput: 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() -> { id: string, displayName: string, isRunning: boolean, pid?: number }[] — list applications the provider exposes for selection with their current running state; pass the returned id unchanged to cua.getApp. Each row represents one running process. To select one of several instances with the same name or bundle ID, pass String(row.pid) to cua.getApp. - cua.findApps(query: string) -> { id: string, displayName: string, path: string, isRunning: boolean, pid?: number }[] — search installed applications, including stopped matches. Running installation matches include their process ID. Stopped matches have no pid. - cua.getState() -> { apps: { id: string, displayName: string, isRunning: boolean, pid?: number }[], browsers: [] } — summarize the same provider discovery; this is not an accessibility observation. @@ -73,14 +73,14 @@ Use an explicit window for screenshots. - getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. ## Simulated mouse -Leave useSystemPointer unset for ordinary mouseMove, drag, and toggleMouse calls, even after approval. Prefer selectText for a supported text range and ordinary window-directed drag for a draggable control. If the effect is unclear, inspect the window before choosing another action. Request the system pointer only when the user explicitly asks for it or the intended effect requires it. +Leave useSystemInput unset for ordinary mouseMove, toggleMouse, click, drag, pressKey, and sendKeyEvent calls, even after approval. Prefer selectText for a supported text range and ordinary window-directed drag for a draggable control. If the effect is unclear, inspect the window before choosing another action. Request system input only when the user explicitly asks for it or the intended effect requires it. Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. -- mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemPointer?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemPointer omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. -- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemPointer?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Send 'up' to release a held button immediately. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemPointer: true on down. Up uses the input route and window saved by down. Physical moves can then drag, including your own mouse movements. -- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], 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. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying. +- mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemInput?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemInput omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Send 'up' to release a held button immediately. Press over the selected foreground window. By default the window receives the events, even a release outside it, and the system button stays up. For a system hold, pass useSystemInput: true on down. Up uses the input route and window saved by down. Physical moves can then drag, including your own mouse movements. +- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean, useSystemInput?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. With useSystemInput: true, the system pointer moves to the target and keyboard modifiers are pressed around the click, including release on cancellation. Verify the expected effect before typing or retrying. - 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. -- drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemPointer?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control. An explicit system drag shares the session decision with mouseMove and holds the chosen button along the path in the unobscured foreground window. +- drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemInput?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemInput or passing false directs the drag to the window without asking for mouse control. System input requires an unobscured foreground target, presses the requested keyboard modifiers, and releases the mouse button before those modifiers, including on cancellation. A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current accessibility observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. FOREGROUND_REQUIRED means explain the need, then explicitly activate the target and observe again; activation is never automatic. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry. @@ -88,14 +88,14 @@ A string target is an element id; coordinate targets are [x, y] and are pixels i Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - 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?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. +- pressKey(key: string, modifiers?: Modifier[], options?: { useSystemInput?: boolean }) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. System input requires the selected foreground application and sends modifiers and the main key through the system keyboard queue, then releases them in reverse order. +- sendKeyEvent(key: string, direction: 'down' | 'up', options?: { useSystemInput?: boolean }) -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. For example W down, D down, D up, W up. A repeated 'down' for an ordinary held key sends one repeat without adding another hold. System down requires the selected foreground app; use the same useSystemInput value for explicit key up. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. Recent activity notices identify when another agent or external input was last detected on a window you observed. You may continue using the window. Recheck its state if your next action depends on what you saw. -Only if the task cannot be completed without moving the user’s pointer, call await win.mouseMove(target, { useSystemPointer: true }). Prefer an advertised accessibility action, a click on a visible control, or browser tools when possible. The question interrupts the user. When approval is disabled an explicit move can act immediately. Pass true on every physical move, even after approval. Omitting the option or passing false uses the default hover route without prompting. Approval or refusal lasts until this session closes or DSH restarts. A refusal sends no input. If the user dismisses the request, ask again only if they request it. Wait for an outstanding request to finish. Subagents cannot request system mouse control. +Pass useSystemInput: true only when the task requires system keyboard or mouse input. Omitting the option or passing false uses the provider default. When approval is enabled, the first explicit system input requests permission; otherwise it executes immediately. Prefer a supported non-system action when it meets the task. The approval question interrupts the user; approval or refusal lasts until this session closes or DSH restarts. Approval does not change later calls: pass true on each system operation. If the user dismisses the request, ask again only if they request it. Wait for an outstanding request to finish. Subagents cannot request system input. AX read defaults: maxElements=2000, maxDepth=25. From 5b0b1f915dd7e6db961f4c55b5948b35a01bdd32 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 20 Nov 2026 12:25:21 +0800 Subject: [PATCH 65/73] Start post-policy input release from the CUA final result observer --- docs/event-producer-consumer.md | 2 +- docs/event-producer-consumer.zh.md | 2 +- docs/persistence-catalog.i18n.yaml | 4 +- docs/persistence-catalog.md | 2 +- docs/persistence-catalog.zh.md | 2 +- docs/persistence-schema.json | 2 +- docs/subsystems/tools.i18n.yaml | 4 +- docs/subsystems/tools.md | 9 +- docs/subsystems/tools.zh.md | 9 +- .../cua-held-inputs/guide.i18n.yaml | 4 +- .../v0.2.2-rc.5/cua-held-inputs/guide.md | 2 +- .../v0.2.2-rc.5/cua-held-inputs/guide.zh.md | 2 +- packages/core/tools/README.i18n.yaml | 4 +- packages/core/tools/README.md | 2 +- packages/core/tools/README.zh.md | 2 +- packages/core/tools/src/contracts.ts | 7 -- packages/core/tools/src/pipeline.ts | 53 ++------- packages/core/tools/tests/tools.spec.ts | 33 ------ packages/experimental/cua/README.i18n.yaml | 4 +- packages/experimental/cua/README.md | 2 +- packages/experimental/cua/README.zh.md | 2 +- packages/experimental/cua/src/held-inputs.ts | 24 ++-- .../cua/tests/run-code-composition.spec.ts | 110 +++++++++++++++--- .../extensions/tool-cordis/src/api-catalog.ts | 2 +- .../cua-posttool-block/runtime.cordis.yml | 1 + .../cua-posttool-block/session.v4.jsonl | 2 +- snapshots/session/cua-run-code/provider.mjs | 18 ++- 27 files changed, 155 insertions(+), 155 deletions(-) diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index e1f13bb935..56e555a4c2 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -90,7 +90,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `tools/post-execute` | `waterfall` | [`packages/core/tools/src/events.ts:41`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `claude-code-mods`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`spill-policy`](../packages/spill/spill-policy), [`tool-fs-search`](../packages/fs/tool-fs-search) | | `tools/pre-execute` | `waterfall` | [`packages/core/tools/src/events.ts:18`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `auto-review`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`tool-jobs`](../packages/jobs/tool-jobs), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `tools/ptc-dispatch-log` | `waterfall` | [`packages/core/tool-executor-ptc/src/runtime-types.ts:46`](../packages/core/tool-executor-ptc/src/runtime-types.ts) | [`tool-executor-ptc`](../packages/core/tool-executor-ptc) (`waterfall`) | [`spill-policy`](../packages/spill/spill-policy) | -| `tools/result` | `emit` | [`packages/core/tools/src/events.ts:49`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`events.dispatch`) | [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `forge-session`, `liveshare`, [`subagent`](../packages/subagent/subagent), [`timeline`](../packages/experimental/timeline), [`tool-office`](../packages/document/tool-office), [`tool-present`](../packages/deliverables/tool-present), `ui-trajectory` | +| `tools/result` | `emit` | [`packages/core/tools/src/events.ts:49`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`events.dispatch`) | [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, [`cua`](../packages/experimental/cua), `forge-session`, `liveshare`, [`subagent`](../packages/subagent/subagent), [`timeline`](../packages/experimental/timeline), [`tool-office`](../packages/document/tool-office), [`tool-present`](../packages/deliverables/tool-present), `ui-trajectory` | | `user-questions/request` | `waterfall` | [`packages/interaction/user-questions/src/types.ts:174`](../packages/interaction/user-questions/src/types.ts) | [`user-questions`](../packages/interaction/user-questions) (`waterfall`) | [`cua-mcp`](../packages/experimental/cua-mcp), `remotes`, `server` | | `web/providers-changed` | `emit` | [`packages/web/web/src/types.ts:21`](../packages/web/web/src/types.ts) | [`web`](../packages/web/web) (`events.dispatch`) | `remotes` | | `webserver/authorize` | `bail` | [`packages/host/webserver/src/index.ts:60`](../packages/host/webserver/src/index.ts) | `remote-connection` (`bail`), `webserver` (`bail`) | `connection` | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index b4d30dc8de..e588a55e62 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -92,7 +92,7 @@ | `tools/post-execute` | `waterfall` | [`packages/core/tools/src/events.ts:41`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `claude-code-mods`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`spill-policy`](../packages/spill/spill-policy), [`tool-fs-search`](../packages/fs/tool-fs-search) | | `tools/pre-execute` | `waterfall` | [`packages/core/tools/src/events.ts:18`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `auto-review`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`tool-jobs`](../packages/jobs/tool-jobs), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `tools/ptc-dispatch-log` | `waterfall` | [`packages/core/tool-executor-ptc/src/runtime-types.ts:46`](../packages/core/tool-executor-ptc/src/runtime-types.ts) | [`tool-executor-ptc`](../packages/core/tool-executor-ptc) (`waterfall`) | [`spill-policy`](../packages/spill/spill-policy) | -| `tools/result` | `emit` | [`packages/core/tools/src/events.ts:49`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`events.dispatch`) | [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `forge-session`, `liveshare`, [`subagent`](../packages/subagent/subagent), [`timeline`](../packages/experimental/timeline), [`tool-office`](../packages/document/tool-office), [`tool-present`](../packages/deliverables/tool-present), `ui-trajectory` | +| `tools/result` | `emit` | [`packages/core/tools/src/events.ts:49`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`events.dispatch`) | [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, [`cua`](../packages/experimental/cua), `forge-session`, `liveshare`, [`subagent`](../packages/subagent/subagent), [`timeline`](../packages/experimental/timeline), [`tool-office`](../packages/document/tool-office), [`tool-present`](../packages/deliverables/tool-present), `ui-trajectory` | | `user-questions/request` | `waterfall` | [`packages/interaction/user-questions/src/types.ts:174`](../packages/interaction/user-questions/src/types.ts) | [`user-questions`](../packages/interaction/user-questions) (`waterfall`) | [`cua-mcp`](../packages/experimental/cua-mcp), `remotes`, `server` | | `web/providers-changed` | `emit` | [`packages/web/web/src/types.ts:21`](../packages/web/web/src/types.ts) | [`web`](../packages/web/web) (`events.dispatch`) | `remotes` | | `webserver/authorize` | `bail` | [`packages/host/webserver/src/index.ts:60`](../packages/host/webserver/src/index.ts) | `remote-connection` (`bail`), `webserver` (`bail`) | `connection` | diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index e401698179..585e52c377 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -1338,8 +1338,8 @@ en: 0080c345c319a4b5 zh: de1a8b3ed621ce21 /session-persistence-event-catalog/resolved-persistence-types/toolrestriction: - en: d7caf05599b9e837 - zh: 9ef405c0a4dc9b19 + en: b2488366535b5fdc + zh: b64d50345521eb99 /session-persistence-event-catalog/resolved-persistence-types/toolresultmessage: en: 9258f30a9c4e2a3a zh: c44d997d719e863c diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 485e5c1fff..2b3b3baa6a 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -5369,7 +5369,7 @@ Sources: [`packages/llm/llm/src/types.ts:134`](../packages/llm/llm/src/types.ts) SHA-256: `3cfc3a56502da1f8c6153c2c56657bab4b749056968634dd0991d325ec1c919f` -Sources: [`packages/core/tools/src/contracts.ts:402`](../packages/core/tools/src/contracts.ts) +Sources: [`packages/core/tools/src/contracts.ts:395`](../packages/core/tools/src/contracts.ts) | Property | Presence | Type | |---|---|---| diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index e8808a31f7..ec3ecd47f0 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -5371,7 +5371,7 @@ SHA-256: `43e311235aa537df1bacdd92d144df8a952337a76e9ac892cdf670f1a797bad8` SHA-256: `3cfc3a56502da1f8c6153c2c56657bab4b749056968634dd0991d325ec1c919f` -来源:[`packages/core/tools/src/contracts.ts:402`](../packages/core/tools/src/contracts.ts) +来源:[`packages/core/tools/src/contracts.ts:395`](../packages/core/tools/src/contracts.ts) | 属性 | 存在性 | 类型 | |---|---|---| diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json index 6eb238d126..e87800d467 100644 --- a/docs/persistence-schema.json +++ b/docs/persistence-schema.json @@ -224,7 +224,7 @@ {"digest":"3bec87f9e6ab3da03346f49923d3c51621debc0159df68605e543c3b2a026f90","names":[],"sources":["packages/llm/llm/src/types.ts:497"]}, {"digest":"3bfeb47b58606f4661904bc723da612782214c463d01e6d61cd6d6193d7374e1","names":[],"sources":[]}, {"digest":"3c2535ca0a2062f172f15344f8040755002b5ac506cf94fc4ebaa822b15feb8c","names":[],"sources":[]}, - {"digest":"3cfc3a56502da1f8c6153c2c56657bab4b749056968634dd0991d325ec1c919f","names":["packages/core/tools/src/contracts.ts#ToolRestriction"],"sources":["packages/core/tools/src/contracts.ts:402"]}, + {"digest":"3cfc3a56502da1f8c6153c2c56657bab4b749056968634dd0991d325ec1c919f","names":["packages/core/tools/src/contracts.ts#ToolRestriction"],"sources":["packages/core/tools/src/contracts.ts:395"]}, {"digest":"3d1339bcc98cb53714bf31ac4a6e7c9ce15a412dd58451778a383627367a4666","names":["packages/llm/llm/src/message.ts#SystemPromptMessageSource"],"sources":["packages/llm/llm/src/message.ts:54"]}, {"digest":"3d7d07060a7be77984feb651ea2bf1925d3e0477911d9d3ed86330d1e8ca6182","names":["packages/feedback/message-feedback/src/types.ts#MessageFeedbackItem"],"sources":["packages/feedback/message-feedback/src/types.ts:20"]}, {"digest":"3e0eff5946255ff05d88a10839c60305135801f97794ea48d409f8503303317e","names":[],"sources":[]}, diff --git a/docs/subsystems/tools.i18n.yaml b/docs/subsystems/tools.i18n.yaml index 062e525e01..bcefbfdd3b 100644 --- a/docs/subsystems/tools.i18n.yaml +++ b/docs/subsystems/tools.i18n.yaml @@ -21,8 +21,8 @@ en: 14522295539ea2fb zh: 572c462f2c6b70ad /tools/execution-extensible-waterfalls-plus-monotonic-policy: - en: f74b432c5ad7f78f - zh: 4e5487828ff17250 + en: a6d9db4237438b2a + zh: 1fe07dedc426c5eb /tools/the-enforced-raw-json-schema-subset: en: 28e354bfa2f9cebb zh: be1f75abccf8afdf diff --git a/docs/subsystems/tools.md b/docs/subsystems/tools.md index cfde7eee48..5a32c8e009 100644 --- a/docs/subsystems/tools.md +++ b/docs/subsystems/tools.md @@ -450,17 +450,10 @@ interface ToolExecution extends ToolExecutionInput { interface ToolDispatchExecution extends Omit { /** Cancellation signal visible to the next wrapper or tool body. */ signal: AbortSignal - /** - * Register cleanup during dispatch for this invocation. If the final result is an error, the executor - * awaits every registered cleanup in order before publishing it, including failures from post-execute policy. - * Cleanup failures add feedback to the original error. Successful calls discard the registrations. - * @param cleanup - Release this call's resources using the resource owner's cleanup deadline. - */ - onFailure(cleanup: () => void | Promise): void } ``` -`ToolExecutionToken` is an opaque runtime `Symbol` used only for identity comparison. Before policy, `execute()` materializes and freezes arguments, rejects non-JSON input, and assigns the token. Identity fields, the required caller signal, and the optional parent token remain readonly. A `ToolDispatchExecution` wrapper may replace but not remove the signal; the registry re-fuses the caller signal before invoking the body. Final observers receive the frozen execution identity. A dispatch wrapper can register `exec.onFailure(cleanup)` before returning. When the final outcome fails, including a post-execute block, the executor waits for that invocation’s cleanups before notifying result observers. A cleanup refusal appends feedback and preserves the original error code. +`ToolExecutionToken` is an opaque runtime `Symbol` used only for identity comparison. Before policy, `execute()` materializes and freezes arguments, rejects non-JSON input, and assigns the token. Identity fields, the required caller signal, and the optional parent token remain readonly. A `ToolDispatchExecution` wrapper may replace but not remove the signal; the registry re-fuses the caller signal before invoking the body. Final observers receive the frozen execution identity. A `ToolGuard` is scope-aware final pre-dispatch policy. Its return type deliberately has no allow result: `undefined` preserves the waterfall decision, while a returned reason or `ToolGuardDenial` can only reduce permission, so a later listener cannot undo it. A denial's optional `info` becomes the failed result's structured error identity. diff --git a/docs/subsystems/tools.zh.md b/docs/subsystems/tools.zh.md index 411a46642e..1b82c3b678 100644 --- a/docs/subsystems/tools.zh.md +++ b/docs/subsystems/tools.zh.md @@ -450,17 +450,10 @@ interface ToolExecution extends ToolExecutionInput { interface ToolDispatchExecution extends Omit { /** Cancellation signal visible to the next wrapper or tool body. */ signal: AbortSignal - /** - * Register cleanup during dispatch for this invocation. If the final result is an error, the executor - * awaits every registered cleanup in order before publishing it, including failures from post-execute policy. - * Cleanup failures add feedback to the original error. Successful calls discard the registrations. - * @param cleanup - Release this call's resources using the resource owner's cleanup deadline. - */ - onFailure(cleanup: () => void | Promise): void } ``` -`ToolExecutionToken` 是不透明的运行时 `Symbol`,仅用于身份比较。策略执行前,`execute()` 会物化并冻结参数、拒绝非 JSON 输入并分配 token。身份字段、调用方必需的 signal 和可选的 parent token 均保持 readonly。`ToolDispatchExecution` 包装层可以替换 signal 但不能移除;注册表会在调用工具函数体前重新融合调用方的 signal。最终观察者接收冻结的执行身份。 执行包装层可在返回前调用 `exec.onFailure(cleanup)`。若最终结果失败,包括被后置策略拒绝,执行器会先等待该次调用的清理,再通知结果观察者。清理失败时追加错误反馈,并保留原错误码。 +`ToolExecutionToken` 是不透明的运行时 `Symbol`,仅用于身份比较。策略执行前,`execute()` 会物化并冻结参数、拒绝非 JSON 输入并分配 token。身份字段、调用方必需的 signal 和可选的 parent token 均保持 readonly。`ToolDispatchExecution` 包装层可以替换 signal 但不能移除;注册表会在调用工具函数体前重新融合调用方的 signal。最终观察者接收冻结的执行身份。 `ToolGuard` 是感知作用域的最终预分派策略。其返回类型有意不包含 allow 结果:`undefined` 保留 waterfall 的决策,而返回的 reason 或 `ToolGuardDenial` 只能缩减权限,因此后续监听器无法撤销它。拒绝中可选的 `info` 会成为失败结果的结构化错误身份。 diff --git a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml index b88312ff7a..a753c8369d 100644 --- a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml @@ -12,5 +12,5 @@ en: 2812241cf189be50 zh: ee90f8e5c6c55512 /cua-reports-held-input-after-programs/migration: - en: 23893a11333ff744 - zh: e1dae0e424d6420f + en: 1bd7668cac0efe0d + zh: 2122c9d5135283f7 diff --git a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md index 2ff3e9e007..b6c7ff0426 100644 --- a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md @@ -14,4 +14,4 @@ On macOS and Windows, explicit `sendKeyEvent('down')` and `toggleMouse('down')` 1. Pair explicit downs with ups when input should stop. Read the reminder before continuing; no reminder is added when no input remains held. 2. Upgrade the platform package and helper together. A custom `helperPath` must implement the task-owned `getHeldInputs` and `releaseHeldInputs` private operations. -3. Verify that one successful program can hold a key, receive its reminder, and release it in a later program. A failed or cancelled program waits for its cleanup. This includes a program that sends input successfully before a post-execute policy rejects its result. Execution middleware can register call-scoped cleanup with `exec.onFailure(cleanup)`. If the model is thinking when DSH stops or fails, the Agent can finish before native release is confirmed. Subsequent CUA calls wait for the outcome. If cleanup cannot be confirmed, CUA disables further operations for that task; inspect the desktop manually before starting another task. +3. Verify that one successful program can hold a key, receive its reminder, and release it in a later program. When a program fails or is cancelled during execution, it waits for cleanup. If the program succeeds but a post-execute policy rejects the output, the tool returns the policy error and CUA finishes cleanup independently. If the model is thinking when DSH stops or fails, the Agent can finish before native release is confirmed. Subsequent CUA calls wait for the outcome. If cleanup cannot be confirmed, CUA disables further operations for that task; inspect the desktop manually before starting another task. diff --git a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md index 5377e222a5..a342f3d78a 100644 --- a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md @@ -14,4 +14,4 @@ macOS 和 Windows 的显式 `sendKeyEvent('down')` 和 `toggleMouse('down')` 跨 1. 输入不再需要保持时,将显式 down 与 up 配对。继续操作前阅读提醒;没有持有输入时不添加提醒。 2. 同步升级平台包和 helper。自定义 `helperPath` 必须实现按任务区分的 `getHeldInputs` 和 `releaseHeldInputs` 私有操作。 -3. 验证成功结束的程序能持有按键、收到提醒,并在后续程序中释放。程序失败或取消时会等待自身的清理,已发送输入、随后被后置策略拒绝的程序也适用。工具执行包装层可用 `exec.onFailure(cleanup)` 登记该次调用的失败清理。模型思考期间停止或报错,Agent 可以先结束,原生释放随后确认。后续 CUA 调用会等待清理结果。清理无法确认时,CUA 禁用该任务后续操作;请手动检查桌面后再创建其他任务。 +3. 验证成功结束的程序能持有按键、收到提醒,并在后续程序中释放。程序执行中失败或取消时,会等待自身的清理。如果程序执行成功,但后置策略拒绝结果,工具返回策略错误,CUA 单独等待原生释放确认。模型思考期间停止或报错,Agent 可以先结束,原生释放随后确认。后续 CUA 调用会等待清理结果。清理无法确认时,CUA 禁用该任务后续操作;请手动检查桌面后再创建其他任务。 diff --git a/packages/core/tools/README.i18n.yaml b/packages/core/tools/README.i18n.yaml index 6bfdcf15a3..ff22c17d80 100644 --- a/packages/core/tools/README.i18n.yaml +++ b/packages/core/tools/README.i18n.yaml @@ -30,8 +30,8 @@ en: c6f98b2283cc2e47 zh: c2cdce5d13473f15 /deepseek-ai-dsh-tools/use-this-package/enforce-policy-on-calls: - en: 979aa454c0c8705a - zh: 00bfbbedc9e43b10 + en: cbfe8317565ac62d + zh: 1e71c66941e50881 /deepseek-ai-dsh-tools/use-this-package/host-presentation-descriptors: en: 258e16bb367229e5 zh: 7c1eb91062b4e4ad diff --git a/packages/core/tools/README.md b/packages/core/tools/README.md index 119988a8ab..50732a3159 100644 --- a/packages/core/tools/README.md +++ b/packages/core/tools/README.md @@ -91,7 +91,7 @@ Agent-step concurrency uses the [agent-loop configuration](../agent-loop/README. `ctx.tools.guard(guard)` registers a monotonic synchronous guard after the extensible `tools/pre-execute` waterfall: a returned reason denies the call, and no later listener can turn that denial back into permission. The pipeline's events give plugins more control — `tools/pre-execute` decides allow/deny/ask, `tools/execute` wraps dispatch for timeout or retry, `tools/post-execute` inspects or replaces the result, and `tools/result` observes the frozen final outcome. -A tool’s `projectContent` installs execution-prepared content before post-execute policies. Policies may still replace or block it; `finalizeContent` remains the final content transform after those policies. A dispatch wrapper can register `exec.onFailure(cleanup)` before returning. When the final outcome fails, including a post-execute block, the executor waits for that invocation’s cleanups before notifying result observers. A cleanup refusal appends feedback and preserves the original error code. +A tool’s `projectContent` installs execution-prepared content before post-execute policies. Policies may still replace or block it; `finalizeContent` remains the final content transform after those policies. ### Host presentation descriptors diff --git a/packages/core/tools/README.zh.md b/packages/core/tools/README.zh.md index f9c68321da..28abce32f4 100644 --- a/packages/core/tools/README.zh.md +++ b/packages/core/tools/README.zh.md @@ -91,7 +91,7 @@ Agent 步骤的并发上限使用 [agent-loop 配置](../agent-loop/README.zh.md `ctx.tools.guard(guard)` 在可扩展的 `tools/pre-execute` waterfall(瀑布式事件)之后注册单调同步守卫:返回的理由会拒绝调用,后续监听器无法把该拒绝重新变为允许。流水线事件给插件更多控制——`tools/pre-execute` 决定允许/拒绝/询问,`tools/execute` 为超时或重试包装分发,`tools/post-execute` 检查或替换结果,`tools/result` 观测冻结的最终结果。 -工具的 `projectContent` 在执行后策略之前安装执行期间准备的图文内容。策略仍可替换或阻止这些内容;`finalizeContent` 保留为策略之后的最终内容处理。 执行包装层可在返回前调用 `exec.onFailure(cleanup)`。若最终结果失败,包括被后置策略拒绝,执行器会先等待该次调用的清理,再通知结果观察者。清理失败时追加错误反馈,并保留原错误码。 +工具的 `projectContent` 在执行后策略之前安装执行期间准备的图文内容。策略仍可替换或阻止这些内容;`finalizeContent` 保留为策略之后的最终内容处理。 ### Host 展示描述 diff --git a/packages/core/tools/src/contracts.ts b/packages/core/tools/src/contracts.ts index 9f939f98aa..51597b4107 100644 --- a/packages/core/tools/src/contracts.ts +++ b/packages/core/tools/src/contracts.ts @@ -232,13 +232,6 @@ export interface ToolExecution extends ToolExecutionInput { export interface ToolDispatchExecution extends Omit { /** Cancellation signal visible to the next wrapper or tool body. */ signal: AbortSignal - /** - * Register cleanup during dispatch for this invocation. If the final result is an error, the executor - * awaits every registered cleanup in order before publishing it, including failures from post-execute policy. - * Cleanup failures add feedback to the original error. Successful calls discard the registrations. - * @param cleanup - Release this call's resources using the resource owner's cleanup deadline. - */ - onFailure(cleanup: () => void | Promise): void } /** diff --git a/packages/core/tools/src/pipeline.ts b/packages/core/tools/src/pipeline.ts index ef54d39eca..9db8bfc610 100644 --- a/packages/core/tools/src/pipeline.ts +++ b/packages/core/tools/src/pipeline.ts @@ -11,7 +11,7 @@ import { TOOL_ABORTED, TOOL_ABORTED_BEFORE_DISPATCH, ToolNotFoundError, ToolOutp import { APPROVAL_CANCELLED, APPROVAL_ERROR_NAME, APPROVAL_REJECTED, APPROVAL_UNAVAILABLE, type ApprovalErrorCode } from './error-codes.ts' import { validateJsonSchemaValue } from './json-schema.ts' import type { ToolsService } from './index.ts' -import type { ResolvedToolSet, ToolDefinition, ToolExecutionInput, ToolExecutionMode, ToolExecution, ToolRunContext, ToolExecutionResult, ToolExecutionSuccess, ToolExecutionFailure, ToolErrorInfo, ToolExecutionToken, PreToolDecision, PostToolDecision } from './contracts.ts' +import type { ResolvedToolSet, ToolDefinition, ToolExecutionInput, ToolExecutionMode, ToolExecution, ToolRunContext, ToolExecutionResult, ToolExecutionSuccess, ToolErrorInfo, ToolExecutionToken, PreToolDecision, PostToolDecision } from './contracts.ts' /** Executor-owned lookup and restrictions applied before extensible execution policy. */ export interface ToolExecutionSource { @@ -90,8 +90,6 @@ export class ToolExecutionPipeline { /** Original caller cancellation, kept outside the wrapper-mutable execution object. */ private cancellationStates = new WeakMap() - private readonly failureCleanups = new WeakMap void | Promise)[]>() - /** Definition-owned final content transform snapshotted before policy begins. */ private contentFinalizers = new WeakMap() @@ -306,16 +304,8 @@ export class ToolExecutionPipeline { * @returns whether the result still needs post-execute. */ async dispatch(exec: ToolRunContext): Promise { - let dispatching = true try { - const mutableExec = Object.assign(exec as MutableToolRunContext, { - onFailure: (cleanup: () => void | Promise) => { - if (!dispatching) throw new Error('Tool failure cleanup must be registered during dispatch') - const registered = this.failureCleanups.get(exec) - if (registered) registered.push(cleanup) - else this.failureCleanups.set(exec, [cleanup]) - }, - }) + const mutableExec = exec as MutableToolRunContext const carrier = scopeTarget(this.tools, exec.agent) const result = await this.ctx.waterfall( carrier, 'tools/execute', mutableExec, @@ -342,8 +332,6 @@ export class ToolExecutionPipeline { } } catch (error: unknown) { return { kind: 'final-result', result: this.wrapperFailureResult(exec, error) } - } finally { - dispatching = false } } @@ -376,7 +364,6 @@ export class ToolExecutionPipeline { return assertNever(outcome, 'scheduled tool outcome') } const { result } = outcome - let final: ToolExecutionResult try { const project = this.contentProjectors.get(exec) this.contentProjectors.delete(exec) @@ -385,13 +372,15 @@ export class ToolExecutionPipeline { ? result : this.markCanonical(exec, this.materializeFinalResult({ ...result, content })) const postResult = await this.postExecute(exec, projected) - final = this.callerCancelled(exec) && !postResult.isError - ? this.cancellationResult(exec, postResult) - : postResult + return this.finish( + exec, + this.callerCancelled(exec) && !postResult.isError + ? this.cancellationResult(exec, postResult) + : postResult, + ) } catch (error: unknown) { - final = toolErrorResult(error) + return this.finish(exec, toolErrorResult(error)) } - return this.finish(exec, final) } /** @@ -402,7 +391,7 @@ export class ToolExecutionPipeline { * @returns the materialized final result. * @internal */ - private finish(exec: ToolRunContext, result: ToolExecutionResult): ToolExecutionResult | Promise { + private finish(exec: ToolRunContext, result: ToolExecutionResult): ToolExecutionResult { let materializedResult: ToolExecutionResult try { materializedResult = this.materializeFinalResult(result) @@ -415,28 +404,6 @@ export class ToolExecutionPipeline { } catch (error: unknown) { finalResult = this.materializeFinalResult(toolErrorResult(error)) } - const cleanups = this.failureCleanups.get(exec) - this.failureCleanups.delete(exec) - if (finalResult.isError && cleanups) return this.finishFailure(exec, finalResult, cleanups) - this.notifyResult(exec, finalResult) - return finalResult - } - - /** Await all cleanup for this failed call and preserve the original error identity and policy feedback. */ - private async finishFailure(exec: ToolRunContext, result: ToolExecutionFailure, - cleanups: readonly (() => void | Promise)[]): Promise { - const errors: string[] = [] - for (const cleanup of cleanups) { - try { await cleanup() } catch (error) { errors.push(toolErrorMessage(error)) } - } - let finalResult: ToolExecutionResult = result - if (errors.length) { - const feedback = `Tool cleanup failed: ${errors.join('\n')}` - finalResult = this.materializeFinalResult({ - ...result, error: { ...result.error, message: `${result.error.message}\n${feedback}` }, - content: [...result.content, { type: 'text', text: feedback }], - }) - } this.notifyResult(exec, finalResult) return finalResult } diff --git a/packages/core/tools/tests/tools.spec.ts b/packages/core/tools/tests/tools.spec.ts index d77ffb8b7a..3952e42194 100644 --- a/packages/core/tools/tests/tools.spec.ts +++ b/packages/core/tools/tests/tools.spec.ts @@ -573,39 +573,6 @@ describe('ToolRuntime', () => { expect(result.error?.message).toBe(message) }) - it('settles registered cleanups only on final failure, before reporting the policy result', async () => { - const ctx = await setup() - const entered = Promise.withResolvers() - const release = Promise.withResolvers() - const events: string[] = [] - try { - ctx.tools.register(echoTool) - let registerLate: (() => void) | undefined - ctx.on('tools/execute', (exec, next) => { - registerLate = () => { exec.onFailure(() => {}) } - exec.onFailure(() => { events.push('first'); throw new Error('first cleanup failed') }) - exec.onFailure(async () => { entered.resolve(undefined); await release.promise; events.push('second') }) - return next() - }) - ctx.on('tools/result', (_exec, result) => { events.push(result.isError ? 'failed' : 'succeeded') }) - const call = (id: string) => executeToolFixture(ctx, { signal: testToolSignal, callId: brandString(id), name: 'echo', arguments: {} }) - expect((await call('ok')).isError).toBe(false) - expect(events).toEqual(['succeeded']) - expect(() => { registerLate!() }).toThrow('during dispatch') - ctx.on('tools/post-execute', async (): Promise => ({ - kind: 'block', feedback: [{ type: 'text', text: 'rejected' }], info: { name: 'PolicyError', code: 'BLOCKED' }, - }), { prepend: true }) - const blocked = call('block') - await entered.promise - expect(events).toEqual(['succeeded', 'first']) - release.resolve(undefined) - expect(await blocked).toMatchObject({ isError: true, error: { info: { code: 'BLOCKED' }, - message: 'rejected\nTool cleanup failed: first cleanup failed' }, - content: [{ text: 'rejected' }, { text: 'Tool cleanup failed: first cleanup failed' }] }) - expect(events).toEqual(['succeeded', 'first', 'second', 'failed']) - } finally { release.resolve(undefined); await ctx.fiber.dispose() } - }) - it('records the structured identity of a post-execute block', async () => { const ctx = await setup() ctx.tools.register(echoTool) diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index 64c069db3f..58f4e9537d 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -21,8 +21,8 @@ en: 3f638a4a76023fc5 zh: 515aeb5de6ae5b33 /deepseek-ai-dsh-cua/understand-the-implementation: - en: 2be36ce22ba367e0 - zh: ad4599b1cd5b4de3 + en: 60892f557adb5d01 + zh: 2e8483610017484a /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 f38fa04d53..b36d1a544d 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -93,7 +93,7 @@ Permission responses identify their platform and report only the state that plat Providers implementing `CuaBackend.heldInputState` accept `taskId` on explicit input and system pointer movement, report their connection-owned records through `getHeldInputs({ taskId })`, and acknowledge `releaseHeldInputs({ taskId })`. Native records own the actual key/button, target, process identity and input mode. Successful `run_code` and `cua_run_code` programs query those records and append a system reminder when input remains held; normal program and turn endings preserve input in both DSH and MCP. Reminders travel through logged additional context in DSH and through the tool response in MCP. macOS and Windows both implement this protocol. Capability methods remain static. -Held input belongs to the task and native connection, outside program processes. A DSH stop or model failure starts cleanup. The Agent can finish the turn and resolve `whenIdle()` while the native release is pending. Subsequent CUA calls wait for its outcome. A program rejected by post-execute policy releases its held input before the tool returns the rejection. If release also fails, the result reports both causes. Confirmed release queues a notice for the model and removes pending held-state reminders. A cleanup failure is reported through `agent/error` and disables CUA for that task. A failed or cancelled program, an active MCP request receiving cancellation, an environment reset, and connection or provider disposal each await their own cleanup. +Held input belongs to the task and native connection, outside program processes. A DSH stop or model failure starts cleanup. The Agent can finish the turn and resolve `whenIdle()` while the native release is pending. Subsequent CUA calls wait for its outcome. A final tool error after successful dispatch starts cleanup of that invocation’s input owner. The original tool error can return while native release is pending. Any cleanup failure is reported separately. Confirmed release queues a notice for the model and removes pending held-state reminders. A cleanup failure is reported through `agent/error` and disables CUA for that task. A failed or cancelled program, an active MCP request receiving cancellation, an environment reset, and connection or provider disposal each await their own cleanup. The [permission store](src/permission-store.ts) uses `storageDomain` with the configured backend. The default JSON backend writes `$DSH_HOME/storages/cua_permissions_.json`, where the digest identifies the canonical profile directory. Each authorization check opens fresh state under the profile's file lock and closes its domain afterward; native dispatch uses a separate application lock. Revocation waits for operations already admitted by another process; after it completes, every process rejects old handles. Files on different machines or PID namespaces must not share this lock. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index 2a2ecab14e..a7f270f27c 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -93,7 +93,7 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边 实现 `CuaBackend.heldInputState` 的提供方为显式输入和系统指针移动接受 `taskId`,通过 `getHeldInputs({ taskId })` 报告本连接的持有记录,并确认 `releaseHeldInputs({ taskId })`。原生记录负责保存实际按键或按钮、目标、进程身份和输入方式。成功结束的 `run_code` 和 `cua_run_code` 查询这些记录,仍有输入按住时添加 system reminder;DSH 和 MCP 的正常程序结束和回合结束均保持输入。DSH 通过已记录的额外上下文传递提醒,MCP 通过工具响应传递。macOS 和 Windows 都实现了这套协议。能力方法列表保持静态。 -持有输入属于任务和原生连接,保存在程序进程之外。DSH 收到停止请求或模型报错时启动清理。原生释放尚未确认时,Agent 可以结束回合,`whenIdle()` 也可以返回。后续 CUA 调用等待清理结果。后置策略拒绝程序结果时,工具等待持有输入释放后再返回拒绝原因。如果释放也失败,结果同时报告两个原因。确认释放后,DSH 为模型记录释放提醒,并撤销仍在队列中的旧持有提醒。清理失败会通过 `agent/error` 单独报告,并禁用该任务后续的 CUA 操作。程序失败或取消、执行中的 MCP 请求收到取消、环境重置、连接关闭和提供方卸载,各自等待清理完成。 +持有输入属于任务和原生连接,保存在程序进程之外。DSH 收到停止请求或模型报错时启动清理。原生释放尚未确认时,Agent 可以结束回合,`whenIdle()` 也可以返回。后续 CUA 调用等待清理结果。程序执行成功后,如果最终工具结果失败,CUA 立即清理这次调用所属的输入。原工具错误可以先返回,清理失败会另行报告。确认释放后,DSH 为模型记录释放提醒,并撤销仍在队列中的旧持有提醒。清理失败会通过 `agent/error` 单独报告,并禁用该任务后续的 CUA 操作。程序失败或取消、执行中的 MCP 请求收到取消、环境重置、连接关闭和提供方卸载,各自等待清理完成。 [授权存储](src/permission-store.ts)复用 `storageDomain` 和配置的后端。默认 JSON 后端写入 `$DSH_HOME/storages/cua_permissions_.json`,摘要对应 profile 的真实目录。每次授权检查在 profile 文件锁内打开并读取最新状态,随后关闭存储域;原生操作使用单独的应用锁。撤销会等待其他进程已获准执行的操作结束;撤销完成后,各进程都拒绝旧句柄。不同电脑或 PID 命名空间不能共享这把锁。 diff --git a/packages/experimental/cua/src/held-inputs.ts b/packages/experimental/cua/src/held-inputs.ts index 845b8150fc..074c08cce6 100644 --- a/packages/experimental/cua/src/held-inputs.ts +++ b/packages/experimental/cua/src/held-inputs.ts @@ -2,7 +2,7 @@ import type { Context } from '@deepseek-ai/cordis' import { emitAgentEvent, type Agent } from '@deepseek-ai/dsh-agent' import { createUserMessage } from '@deepseek-ai/dsh-llm' -import { RUN_CODE_NAME, type ToolDispatchExecution } from '@deepseek-ai/dsh-tools' +import { RUN_CODE_NAME, type ToolExecution } from '@deepseek-ai/dsh-tools' import { z } from 'zod' import { NativeError, type NativeClient } from './native-client.ts' @@ -55,10 +55,6 @@ class InputOwner { return renderInputs(inputs, 'held') } - registerFailureCleanup(execution: ToolDispatchExecution): void { - if (this.client) execution.onFailure(async () => { await this.close() }) - } - close(canRequest = true): Promise> { this.controller.abort() return this.closing ??= Promise.resolve().then(async () => { @@ -87,6 +83,8 @@ class InputOwner { /** One provider's held input owners; the helper remains the authority for which inputs are pressed. */ export class CuaHeldInputs { private readonly owners = new WeakMap() + // Post-execute policy may fail after a newer owner has acquired input for the same Agent. + private readonly programOwners = new WeakMap() private readonly failures = new WeakMap() private readonly turnSignals = new Map void }>() @@ -136,8 +134,7 @@ export class CuaHeldInputs { */ async release(agent: Agent): Promise { await this.owners.get(agent)?.close() } - private stop(agent: Agent): void { - const owner = this.owners.get(agent) + private stop(owner: InputOwner | undefined): void { if (!owner) return void owner.close().catch(() => undefined) // close records and reports the failure; waiters join the same promise. } @@ -152,7 +149,7 @@ export class CuaHeldInputs { if (!execution.agent || (execution.name !== RUN_CODE_NAME && execution.name !== 'cua_run_code')) return next() const agent = execution.agent const signal = execution.signal - const abort = (): void => { this.stop(agent) } + const abort = (): void => { this.stop(this.owners.get(agent)) } signal.addEventListener('abort', abort, { once: true }) const releaseAfter = async (message: string): Promise => { signal.removeEventListener('abort', abort) @@ -181,7 +178,7 @@ export class CuaHeldInputs { // oxlint-disable-next-line typescript/no-unnecessary-condition -- Cancellation can arrive while the native state query awaits. if (signal.aborted) { await releaseAfter('Program cancelled'); return result } } - owner?.registerFailureCleanup(execution) + if (owner) this.programOwners.set(execution, owner) if (text && !owner?.closing) return { ...result, additionalContexts: [...result.additionalContexts ?? [], createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'cua-held-inputs', form: 'notice', summary: 'CUA inputs remain held' } }), @@ -193,11 +190,16 @@ export class CuaHeldInputs { await this.owners.get(agent)?.settled() } }) + yield ctx.on('tools/result', (execution, result) => { + const owner = this.programOwners.get(execution) + this.programOwners.delete(execution) + if (result.isError) this.stop(owner) + }) yield ctx.on('agent/pre-step', (event, next) => { const previous = this.turnSignals.get(event.agent) if (previous?.signal !== event.signal) { previous?.remove() - const abort = (): void => { this.stop(event.agent) } + const abort = (): void => { this.stop(this.owners.get(event.agent)) } event.signal.addEventListener('abort', abort, { once: true }) this.turnSignals.set(event.agent, { signal: event.signal, remove: () => { event.signal.removeEventListener('abort', abort) } }) } @@ -213,7 +215,7 @@ export class CuaHeldInputs { if (agent?.session !== session) return this.turnSignals.get(agent)?.remove() this.turnSignals.delete(agent) - if (event.data.reason.kind === 'aborted' || event.data.reason.kind === 'error') this.stop(agent) + if (event.data.reason.kind === 'aborted' || event.data.reason.kind === 'error') this.stop(this.owners.get(agent)) }) yield () => { for (const value of this.turnSignals.values()) value.remove(); this.turnSignals.clear() } } diff --git a/packages/experimental/cua/tests/run-code-composition.spec.ts b/packages/experimental/cua/tests/run-code-composition.spec.ts index 41e68200ff..da0dcb4e1f 100644 --- a/packages/experimental/cua/tests/run-code-composition.spec.ts +++ b/packages/experimental/cua/tests/run-code-composition.spec.ts @@ -408,39 +408,109 @@ it('reports the Windows keyboard window and desktop input mode and supports a la it.each([ ['run_code', 'confirmed'], ['cua_run_code', 'confirmed'], ['cua_run_code', 'refused'], -] as const)('settles %s post-policy failure after native cleanup (%s)', async (tool, cleanup) => { - const code = tool === 'run_code' - ? `await tools.cua_run_code({ code: ${JSON.stringify(holdProgram)}, description: "Hold W" })` : holdProgram - const f = await setup([code], 'macos', undefined, true, true) +] as const)('publishes the %s policy error while subsequent CUA waits for cleanup (%s)', async (tool, cleanup) => { + const program = (code: string) => tool === 'run_code' + ? `await tools.cua_run_code({ code: ${JSON.stringify(code)}, description: "Use the fixture" })` : code + const f = await setup([program(holdProgram)], 'macos', undefined, true, true) if (tool === 'run_code') await f.agent.ctx.plugin(PtcToolExecutor) f.model.toolName = tool - f.ctx.on('tools/post-execute', async (exec, _result, next) => exec.name === tool + const removePolicy = f.ctx.on('tools/post-execute', async (exec, _result, next) => exec.name === tool ? { kind: 'block', feedback: [{ type: 'text', text: 'Policy rejected output' }], info: { name: 'HookError', code: 'HOOK_BLOCKED' } } : next(), { prepend: true }) + const calls = vi.spyOn(NativeClient.prototype, 'request') + onTestFinished(() => { calls.mockRestore() }) + let stoppedAtResult: boolean | undefined + f.ctx.on('tools/result', (exec, result) => { + if (exec.name === tool && result.isError) { + stoppedAtResult = calls.mock.calls.find(([name]) => name === 'sendKeyEvent')?.[2].aborted + } + }) + const reported: unknown[] = [] + f.ctx.on('agent/error', ({ error }) => { reported.push(error) }) + const notice = nextReleaseNotice(f) const release = f.native.controlNext('releaseHeldInputs') const running = f.run() await release.entered + let following: Promise + const before = f.native.calls.length try { + await running + expect(stoppedAtResult).toBe(true) expect(f.native.held.map(input => input.key)).toEqual(['w']) - expect(f.agent.session.snapshotEvents().some(event => event.type === 'tool/result')).toBe(false) + const result = f.agent.session.snapshotEvents().find(event => event.type === 'tool/result') + expect(result?.data).toMatchObject({ error: { code: 'HOOK_BLOCKED' }, message: { + isError: true, content: [{ type: 'text', text: 'Policy rejected output' }], + } }) + expect(JSON.stringify(f.model.requests[1]?.messages)).not.toContain('CUA inputs were released') + expect(reminders(f.agent)).toEqual([]) + removePolicy() + const admitted: PromiseWithResolvers = Promise.withResolvers() + f.ctx.on('tools/execute', (exec, next) => { + const result = next() + if (exec.name === 'cua') admitted.resolve() + return result + }) + f.model.restart([program('await app.sendKeyEvent("d", "down")')]) + following = f.run() + await admitted.promise + expect(f.native.calls.length).toBe(before) } finally { release.reply(cleanup === 'refused' ? { code: 'INPUT_CLEANUP_FAILED', message: 'Fixture refused release' } : undefined) - await running } - const result = f.agent.session.snapshotEvents().find(event => event.type === 'tool/result') - expect(result?.data).toMatchObject({ error: { code: 'HOOK_BLOCKED' }, message: { isError: true } }) - const shown = JSON.stringify(f.model.requests[1]?.messages) - expect(shown).toContain('Policy rejected output') - expect(shown).not.toContain('CUA inputs are still held:') + await following if (cleanup === 'confirmed') { - expect(f.native.events).toEqual(['w:down', 'w:up']) - expect(shown).toContain('CUA inputs were released during cleanup') + await notice + expect(f.native.events).toEqual(['w:down', 'w:up', 'd:down']) + expect(JSON.stringify(f.model.requests.at(-1)?.messages)).toContain('CUA inputs were released during cleanup') } else { - expect(shown).toContain('Fixture refused release') - expect(shown).not.toContain('CUA inputs were released during cleanup') + expect(reported).toEqual([expect.objectContaining({ code: 'INPUT_CLEANUP_FAILED' })]) + expect(f.native.calls.length).toBe(before) + expect(JSON.stringify(f.agent.session.deriveMessages())).toContain('INPUT_CLEANUP_UNCONFIRMED') + expect(f.agent.session.snapshotEvents().some(event => event.type === 'agent/inbox/spliced' + && event.data.inserted.some(message => message.source.kind === 'cua-inputs-released'))).toBe(false) } }) +it('cleans up a rejected nested program even when its enclosing run_code handles the failure', async () => { + const f = await setup([`try { await tools.cua_run_code({ code: ${JSON.stringify(holdProgram)}, description: "Hold W" }) } catch { inspect("handled") }`], + 'macos', undefined, true, true) + await f.agent.ctx.plugin(PtcToolExecutor) + f.model.toolName = 'run_code' + f.ctx.on('tools/post-execute', async (exec, _result, next) => exec.name === 'cua_run_code' && exec.parent + ? { kind: 'block', feedback: [{ type: 'text', text: 'Nested policy refusal' }] } : next()) + await f.run() + expect(f.native.events).toEqual(['w:down', 'w:up']) + expect(f.agent.session.snapshotEvents().find(event => event.type === 'tool/result')?.data.message.isError).toBe(false) +}) + +it('a late policy refusal closes only the owner captured by that execution', async () => { + const f = await setup([holdProgram], 'macos', undefined, true, true) + const entered: PromiseWithResolvers = Promise.withResolvers() + const finish: PromiseWithResolvers = Promise.withResolvers() + f.ctx.on('tools/post-execute', async (exec, _result, next) => { + if (exec.callId !== 'cua-program-1') return next() + entered.resolve() + await finish.promise + return { kind: 'block', feedback: [{ type: 'text', text: 'Late refusal' }] } + }) + const running = f.run() + await entered.promise + const execute = (id: string, code: string) => f.ctx.agents.withInitiator(f.agent, () => f.ctx.tools.execute({ + agent: f.agent, signal: new AbortController().signal, + calls: [{ type: 'tool-call', id: brandString(id), name: 'cua_run_code', arguments: JSON.stringify({ code, description: id }) }], + })) + try { + await f.ctx.cuaPrograms.releaseInputs(f.agent) + expect((await execute('hold-d', 'await app.sendKeyEvent("d", "down")')).results[0]?.result.isError).toBe(false) + f.ctx.on('tools/pre-execute', async (exec, next) => exec.callId === 'denied' + ? { kind: 'deny', reason: 'Not admitted' } : next()) + expect((await execute('denied', 'inspect("unused")')).results[0]?.result.isError).toBe(true) + } finally { finish.resolve(); await running } + expect((await execute('release-d', 'await app.sendKeyEvent("d", "up")')).results[0]?.result.isError).toBe(false) + expect(f.native.events).toEqual(['w:down', 'w:up', 'd:down', 'd:up']) + expect(f.native.calls.filter(call => call.method === 'releaseHeldInputs')).toHaveLength(1) +}) + it('releases keyboard and mouse in mixed reverse order on program failure', async () => { const f = await setup([holdProgram, 'await app.sendKeyEvent("shift", "down"); var win = await app.getWindow("7"); await win.toggleMouse("left", "down"); await app.sendKeyEvent("d", "down"); throw Error("program failed")', 'inspect("recovered")'], @@ -621,9 +691,13 @@ it.each(['closes', 'fails to close'] as const)('waits for Agent release before t else expect(report).not.toHaveBeenCalled() }) -it.each(['confirmed', 'refused'] as const)('joins background cleanup on concurrent provider disposal (%s)', async (outcome) => { +it.each([ + ['model error', 'confirmed'], ['model error', 'refused'], ['post-policy error', 'confirmed'], ['post-policy error', 'refused'], +] as const)('joins background cleanup on concurrent provider disposal (%s, %s)', async (ending, outcome) => { const f = await setup([holdProgram], 'macos', undefined, true, true) - f.model.beforeStream = async (index) => { if (index === 1) throw new Error('Model failed') } + if (ending === 'model error') f.model.beforeStream = async (index) => { if (index === 1) throw new Error('Model failed') } + else f.ctx.on('tools/post-execute', async (exec, _result, next) => exec.name === 'cua_run_code' + ? { kind: 'block', feedback: [{ type: 'text', text: 'Policy rejected output' }] } : next()) const errors: unknown[] = [] f.ctx.on('agent/error', ({ error }) => { errors.push(error) }) const registered = vi.spyOn(NativeClient.prototype, 'registerCleanup') diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 13e207dff5..3491fbaa74 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -11202,7 +11202,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ToolDispatchExecution', - declaration: 'export interface ToolDispatchExecution extends Omit {\n signal: AbortSignal;\n onFailure(cleanup: () => void | Promise): void;\n}', + declaration: 'export interface ToolDispatchExecution extends Omit {\n signal: AbortSignal;\n}', }, { name: 'ToolErrorInfo', diff --git a/snapshots/session/cua-posttool-block/runtime.cordis.yml b/snapshots/session/cua-posttool-block/runtime.cordis.yml index 0a38b473eb..e01fd12b60 100644 --- a/snapshots/session/cua-posttool-block/runtime.cordis.yml +++ b/snapshots/session/cua-posttool-block/runtime.cordis.yml @@ -5,6 +5,7 @@ - id: cua-run-code-fixture name: '../cua-run-code/provider.mjs' config: + confirmReleaseAtTurnEnd: true allowedApps: - id: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa name: Fixture diff --git a/snapshots/session/cua-posttool-block/session.v4.jsonl b/snapshots/session/cua-posttool-block/session.v4.jsonl index ddfb71b416..bb19188640 100644 --- a/snapshots/session/cua-posttool-block/session.v4.jsonl +++ b/snapshots/session/cua-posttool-block/session.v4.jsonl @@ -30,6 +30,6 @@ {"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":"\nCUA inputs were released during cleanup:\n- Key \"w\", appHandle \"fixture-app\" (application input).\nThese inputs are no longer held.\n"}],"source":{"kind":"cua-inputs-released","form":"notice","summary":"CUA inputs released"},"role":"user","id":"{{message:5}}"},"surfaceOp":"append"} -{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"text","text":"The post-tool policy rejected the program output. Cleanup confirmed W was released."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:7}}"},"stream":[{"type":"chunk","time":1795095785319,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1795095785319,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"The post-tool policy rejected the program output. Cleanup confirmed W was released."}}},{"type":"chunk","time":1795095785319,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"text","text":"The policy rejected the program output. I have not received confirmation that W was released."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:7}}"},"stream":[{"type":"chunk","time":1795095785319,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1795095785319,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"The policy rejected the program output. I have not received confirmation that W was released."}}},{"type":"chunk","time":1795095785319,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/snapshots/session/cua-run-code/provider.mjs b/snapshots/session/cua-run-code/provider.mjs index 6667f7fb6c..a2d1c35aca 100644 --- a/snapshots/session/cua-run-code/provider.mjs +++ b/snapshots/session/cua-run-code/provider.mjs @@ -1,15 +1,25 @@ /** Real CUA registration with an isolated fixture at the native byte-stream boundary. */ -import { CuaConfig, installCua } from '@deepseek-ai/dsh-cua' +import Schema from '@deepseek-ai/schemastery' +import { installCua } from '@deepseek-ai/dsh-cua' +import { CuaConfigFields } from '@deepseek-ai/dsh-cua/config' import { COMMON_GUIDANCE } from '@deepseek-ai/dsh-cua/guidance' import { createNativeFixture } from './native-channel.mjs' export const name = 'cua-run-code-fixture' export const inject = ['computerUse', 'tools', 'systemPrompt', 'subprocess', 'agents'] -export const Config = CuaConfig +export const Config = Schema.object({ ...CuaConfigFields, confirmReleaseAtTurnEnd: Schema.boolean().default(false) }) -/** @param {import('@deepseek-ai/cordis').Context} ctx @param {import('@deepseek-ai/dsh-cua').CuaConfig} config */ -export function apply(ctx, config) { +/** @param {import('@deepseek-ai/cordis').Context} ctx @param {import('@deepseek-ai/dsh-cua').CuaConfig & { confirmReleaseAtTurnEnd: boolean }} config */ +export function apply(ctx, { confirmReleaseAtTurnEnd, ...config }) { const fixture = createNativeFixture() + if (confirmReleaseAtTurnEnd) { + const release = fixture.controlNext('releaseHeldInputs') + const remove = ctx.on('session/event', (_session, event) => { + if (event.type !== 'turn/end') return + remove() + release.reply() + }) + } installCua(ctx, config, { helperPath: process.execPath, heldInputState: true, From 7715be3c895fe725c3f85cc34723830bf3a2de06 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 20 Nov 2026 12:29:42 +0800 Subject: [PATCH 66/73] Record policy rejection before native input release confirmation --- .../session/cua-posttool-block/provider.mjs | 16 +++++++++++ .../cua-posttool-block/runtime.cordis.yml | 3 +- .../cua-posttool-block/session.v4.jsonl | 11 ++++---- snapshots/session/cua-run-code/provider.mjs | 28 +++++++++---------- 4 files changed, 35 insertions(+), 23 deletions(-) create mode 100644 snapshots/session/cua-posttool-block/provider.mjs diff --git a/snapshots/session/cua-posttool-block/provider.mjs b/snapshots/session/cua-posttool-block/provider.mjs new file mode 100644 index 0000000000..56198ada39 --- /dev/null +++ b/snapshots/session/cua-posttool-block/provider.mjs @@ -0,0 +1,16 @@ +/** This policy scenario holds native confirmation until the model has received the final tool error. */ +import { installFixture } from '../cua-run-code/provider.mjs' +import { createNativeFixture } from '../cua-run-code/native-channel.mjs' +export { Config, inject, name } from '../cua-run-code/provider.mjs' + +/** @param {import('@deepseek-ai/cordis').Context} ctx @param {import('@deepseek-ai/dsh-cua').CuaConfig} config */ +export function apply(ctx, config) { + const fixture = createNativeFixture() + const release = fixture.controlNext('releaseHeldInputs') + const remove = ctx.on('session/event', (_session, event) => { + if (event.type !== 'turn/end') return + remove() + release.reply() + }) + installFixture(ctx, config, fixture) +} diff --git a/snapshots/session/cua-posttool-block/runtime.cordis.yml b/snapshots/session/cua-posttool-block/runtime.cordis.yml index e01fd12b60..93c86ab966 100644 --- a/snapshots/session/cua-posttool-block/runtime.cordis.yml +++ b/snapshots/session/cua-posttool-block/runtime.cordis.yml @@ -3,9 +3,8 @@ - id: computer-use name: '@deepseek-ai/dsh-computer-use' - id: cua-run-code-fixture - name: '../cua-run-code/provider.mjs' + name: './provider.mjs' config: - confirmReleaseAtTurnEnd: true allowedApps: - id: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa name: Fixture diff --git a/snapshots/session/cua-posttool-block/session.v4.jsonl b/snapshots/session/cua-posttool-block/session.v4.jsonl index bb19188640..a844e4860e 100644 --- a/snapshots/session/cua-posttool-block/session.v4.jsonl +++ b/snapshots/session/cua-posttool-block/session.v4.jsonl @@ -12,7 +12,7 @@ {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Hold W in test.fixture using","messageSeqs":[8],"source":{"kind":"fallback"}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua_first","name":"run_code","arguments":"{\"code\":\"await tools.cua_run_code({\\\"code\\\": \\\"var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"down\\\\\\\")\\\", \\\"description\\\": \\\"Hold W in the fixture\\\"})\",\"description\":\"Hold W\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"stream":[{"type":"chunk","time":1795095784699,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1795095784700,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_first","name":"run_code","arguments":"{\"code\":\"await tools.cua_run_code({\\\"code\\\": \\\"var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"down\\\\\\\")\\\", \\\"description\\\": \\\"Hold W in the fixture\\\"})\",\"description\":\"Hold W\"}"}}},{"type":"chunk","time":1795095784700,"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_first","name":"run_code","arguments":"{\"code\":\"await tools.cua_run_code({\\\"code\\\": \\\"var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"down\\\\\\\")\\\", \\\"description\\\": \\\"Hold W in the fixture\\\"})\",\"description\":\"Hold W\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"stream":[{"type":"chunk","time":1795148927697,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1795148927697,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua_first","name":"run_code","arguments":"{\"code\":\"await tools.cua_run_code({\\\"code\\\": \\\"var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"down\\\\\\\")\\\", \\\"description\\\": \\\"Hold W in the fixture\\\"})\",\"description\":\"Hold W\"}"}}},{"type":"chunk","time":1795148927697,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua_first","name":"run_code","arguments":"{\"code\":\"await tools.cua_run_code({\\\"code\\\": \\\"var app = await cua.getApp(\\\\\\\"test.fixture\\\\\\\"); await app.sendKeyEvent(\\\\\\\"w\\\\\\\", \\\\\\\"down\\\\\\\")\\\", \\\"description\\\": \\\"Hold W in the fixture\\\"})\",\"description\":\"Hold W\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua_run_code","arguments":{"code":"var app = await cua.getApp(\"test.fixture\"); await app.sendKeyEvent(\"w\", \"down\")","description":"Hold W in the fixture"}}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua_first","parentCallId":"cua_first:ptc:1","subCallId":"cua_first:ptc:1:ptc:1","name":"cua","arguments":{"method":"getCapabilities","params":{}}}} @@ -24,12 +24,11 @@ {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua_first","parentCallId":"cua_first","subCallId":"cua_first:ptc:1","name":"cua_run_code","arguments":{"code":"var app = await cua.getApp(\"test.fixture\"); await app.sendKeyEvent(\"w\", \"down\")","description":"Hold W in the fixture"},"isError":false,"content":[{"type":"text","text":"(cua_run_code completed with no output)"}]}} {"type":"hook/invoked","data":{"turn":1,"point":"PostToolUse","dialect":"codex","handlerId":"codex:PostToolUse:1","matcher":"^run_code$"}} {"type":"hook/result","data":{"turn":1,"point":"PostToolUse","handlerId":"codex:PostToolUse:1","decision":"block","exitCode":2,"stderrSummary":"tool output rejected by codex policy: summarize instead","durationMs":5.269749999999931}} -{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"\nCUA inputs were released during cleanup:\n- Key \"w\", appHandle \"fixture-app\" (application input).\nThese inputs are no longer held.\n"}],"source":{"kind":"cua-inputs-released","form":"notice","summary":"CUA inputs released"},"role":"user","id":"{{message:5}}"}]}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"cua_first"},"toolCallId":"cua_first","content":[{"type":"text","text":"tool output rejected by codex policy: summarize instead"}],"isError":true,"id":"{{message:6}}"},"error":{"name":"HookError","code":"HOOK_BLOCKED"}},"sourceEventSeqs":[14],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"cua_first"},"toolCallId":"cua_first","content":[{"type":"text","text":"tool output rejected by codex policy: summarize instead"}],"isError":true,"id":"{{message:5}}"},"error":{"name":"HookError","code":"HOOK_BLOCKED"}},"sourceEventSeqs":[14],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} -{"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":"\nCUA inputs were released during cleanup:\n- Key \"w\", appHandle \"fixture-app\" (application input).\nThese inputs are no longer held.\n"}],"source":{"kind":"cua-inputs-released","form":"notice","summary":"CUA inputs released"},"role":"user","id":"{{message:5}}"},"surfaceOp":"append"} -{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"text","text":"The policy rejected the program output. I have not received confirmation that W was released."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:7}}"},"stream":[{"type":"chunk","time":1795095785319,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1795095785319,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"The policy rejected the program output. I have not received confirmation that W was released."}}},{"type":"chunk","time":1795095785319,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"text","text":"The policy rejected the program output. I have not received confirmation that W was released."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"stream":[{"type":"chunk","time":1795148928147,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1795148928147,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"The policy rejected the program output. I have not received confirmation that W was released."}}},{"type":"chunk","time":1795148928147,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"\nCUA inputs were released during cleanup:\n- Key \"w\", appHandle \"fixture-app\" (application input).\nThese inputs are no longer held.\n"}],"source":{"kind":"cua-inputs-released","form":"notice","summary":"CUA inputs released"},"role":"user","id":"{{message:7}}"}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[],"outcome":"canceled"}} diff --git a/snapshots/session/cua-run-code/provider.mjs b/snapshots/session/cua-run-code/provider.mjs index a2d1c35aca..50dab3e1f0 100644 --- a/snapshots/session/cua-run-code/provider.mjs +++ b/snapshots/session/cua-run-code/provider.mjs @@ -1,25 +1,23 @@ /** Real CUA registration with an isolated fixture at the native byte-stream boundary. */ -import Schema from '@deepseek-ai/schemastery' -import { installCua } from '@deepseek-ai/dsh-cua' -import { CuaConfigFields } from '@deepseek-ai/dsh-cua/config' +import { CuaConfig, installCua } from '@deepseek-ai/dsh-cua' import { COMMON_GUIDANCE } from '@deepseek-ai/dsh-cua/guidance' import { createNativeFixture } from './native-channel.mjs' export const name = 'cua-run-code-fixture' export const inject = ['computerUse', 'tools', 'systemPrompt', 'subprocess', 'agents'] -export const Config = Schema.object({ ...CuaConfigFields, confirmReleaseAtTurnEnd: Schema.boolean().default(false) }) +export const Config = CuaConfig -/** @param {import('@deepseek-ai/cordis').Context} ctx @param {import('@deepseek-ai/dsh-cua').CuaConfig & { confirmReleaseAtTurnEnd: boolean }} config */ -export function apply(ctx, { confirmReleaseAtTurnEnd, ...config }) { - const fixture = createNativeFixture() - if (confirmReleaseAtTurnEnd) { - const release = fixture.controlNext('releaseHeldInputs') - const remove = ctx.on('session/event', (_session, event) => { - if (event.type !== 'turn/end') return - remove() - release.reply() - }) - } +/** @param {import('@deepseek-ai/cordis').Context} ctx @param {import('@deepseek-ai/dsh-cua').CuaConfig} config */ +export function apply(ctx, config) { + installFixture(ctx, config, createNativeFixture()) +} + +/** + * @param {import('@deepseek-ai/cordis').Context} ctx - Provider scope. + * @param {import('@deepseek-ai/dsh-cua').CuaConfig} config - CUA provider options. + * @param {ReturnType} fixture - Native request receiver for this scenario. + */ +export function installFixture(ctx, config, fixture) { installCua(ctx, config, { helperPath: process.execPath, heldInputState: true, From cb0f0ffa9ae2a83ea67a9e53b942d1c058688377 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 20 Nov 2026 13:34:08 +0800 Subject: [PATCH 67/73] Track only the Windows CUA helper's own input dispatches --- .../cua-held-inputs/guide.i18n.yaml | 4 +- .../v0.2.2-rc.5/cua-held-inputs/guide.md | 2 +- .../v0.2.2-rc.5/cua-held-inputs/guide.zh.md | 2 +- .../experimental/cua-windows/README.i18n.yaml | 4 +- packages/experimental/cua-windows/README.md | 1 + .../experimental/cua-windows/README.zh.md | 1 + .../native/desktop-tests/Program.cs | 8 +- .../native/entry/DesktopExecutor.cs | 35 +-- .../cua-windows/native/entry/HeldInputs.cs | 212 +++--------------- .../cua-windows/native/entry/Input.cs | 15 +- .../cua-windows/native/entry/Win32.cs | 6 - .../native/tests/HeldInputChecks.cs | 54 ++--- .../tests/desktop-toggle-mouse.spec.ts | 12 +- 13 files changed, 104 insertions(+), 252 deletions(-) diff --git a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml index a753c8369d..87f47f507c 100644 --- a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml @@ -9,8 +9,8 @@ en: 37252a5d19c7fe09 zh: f1b33b7da3935155 /cua-reports-held-input-after-programs/change: - en: 2812241cf189be50 - zh: ee90f8e5c6c55512 + en: cf9c1397e07dffa5 + zh: f1cce9fadf321d43 /cua-reports-held-input-after-programs/migration: en: 1bd7668cac0efe0d zh: 2122c9d5135283f7 diff --git a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md index b6c7ff0426..cda4b4f345 100644 --- a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md @@ -8,7 +8,7 @@ English | [中文](guide.zh.md) ## Change -On macOS and Windows, explicit `sendKeyEvent('down')` and `toggleMouse('down')` remain held across programs and turns until an explicit `up`. Normal completion does not release them. After a successful `run_code` or `cua_run_code`, a system reminder lists any remaining keys and mouse buttons, their application or window and actual input mode. Program failure, user stop, connection closure, environment reset and disposal release owned input in reverse dispatch order. Complete `pressKey`, `typeText`, `click` and `drag` actions keep their operation-local cleanup. DSH and MCP both preserve input after successful programs. A client pause between completed MCP calls is not observable by the server and can leave input held. On Windows, an up after focus changes releases desktop input without reactivating the original window. +On macOS and Windows, explicit `sendKeyEvent('down')` and `toggleMouse('down')` remain held across programs and turns until an explicit `up`. Normal completion does not release them. After a successful `run_code` or `cua_run_code`, a system reminder lists any remaining keys and mouse buttons, their application or window and actual input mode. Program failure, user stop, connection closure, environment reset and disposal release owned input in reverse dispatch order. Complete `pressKey`, `typeText`, `click` and `drag` actions keep their operation-local cleanup. DSH and MCP both preserve input after successful programs. A client pause between completed MCP calls is not observable by the server and can leave input held. On Windows, cleanup sends an up for each input the helper still holds. If you also hold the same key or button, that up may interrupt your press. A focus change sends the up to the desktop without reactivating the original window. ## Migration diff --git a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md index a342f3d78a..b9e7025603 100644 --- a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md @@ -8,7 +8,7 @@ description: macOS 和 Windows 的 CUA 显式输入跨程序和回合保持, ## 变更 -macOS 和 Windows 的显式 `sendKeyEvent('down')` 和 `toggleMouse('down')` 跨程序、跨回合保持,直到显式 `up`。正常结束不释放它们。成功结束的 `run_code` 或 `cua_run_code` 通过 system reminder 列出剩余键盘键和鼠标按钮、所属应用或窗口及实际输入方式。程序失败、用户停止、断连、环境重置和销毁按派发顺序的反序释放所属输入。完整的 `pressKey`、`typeText`、`click` 和 `drag` 保持操作内清理。DSH 和 MCP 都在程序成功后保持输入。客户端在两次 MCP 调用之间暂停时,服务端无法观察到,输入可能继续按住。Windows 失焦后松开会释放桌面输入,不重新激活原窗口。 +macOS 和 Windows 的显式 `sendKeyEvent('down')` 和 `toggleMouse('down')` 跨程序、跨回合保持,直到显式 `up`。正常结束不释放它们。成功结束的 `run_code` 或 `cua_run_code` 通过 system reminder 列出剩余键盘键和鼠标按钮、所属应用或窗口及实际输入方式。程序失败、用户停止、断连、环境重置和销毁按派发顺序的反序释放所属输入。完整的 `pressKey`、`typeText`、`click` 和 `drag` 保持操作内清理。DSH 和 MCP 都在程序成功后保持输入。客户端在两次 MCP 调用之间暂停时,服务端无法观察到,输入可能继续按住。Windows 清理时会为 helper 仍持有的输入发送 up。如果你也按住同一个键或按钮,这次 up 可能打断你的按压。焦点变化后,up 发往当前桌面,原窗口不会被重新激活。 ## 迁移 diff --git a/packages/experimental/cua-windows/README.i18n.yaml b/packages/experimental/cua-windows/README.i18n.yaml index 1ab20bd3f7..01777fdeb8 100644 --- a/packages/experimental/cua-windows/README.i18n.yaml +++ b/packages/experimental/cua-windows/README.i18n.yaml @@ -45,8 +45,8 @@ en: db3e2957041fafbb zh: 34f953887dff37f7 /deepseek-ai-dsh-cua-windows/known-limitations-and-deferred-work: - en: c68454f8d03edabe - zh: f4d41f22838a9eb9 + en: f36d057acb4e9ea3 + zh: a1a94877e51d9d66 /deepseek-ai-dsh-cua-windows/known-limitations-and-deferred-work/dev-note: en: 0a1253c6f7b5e8b9 zh: 9f56528562c7c914 diff --git a/packages/experimental/cua-windows/README.md b/packages/experimental/cua-windows/README.md index 44ffb568ba..7839f0934a 100644 --- a/packages/experimental/cua-windows/README.md +++ b/packages/experimental/cua-windows/README.md @@ -82,6 +82,7 @@ Inspected results append to model history. Retaining an App, Window, or returned - The npm package omits the Windows helper. Use the [standalone ZIP on x64 or a matching build on ARM64](#setup). - Hover, click, scroll and drag use the system pointer. `requireSystemInputApproval` does not prompt separately for Windows pointer operations. - Drag checks the topmost window only at its starting point. An overlay from another application along the path or at the destination can receive the drop even while the selected window stays in the foreground. +- Held-input reminders and cleanup use the helper's own dispatches. If you press the same key or button while the helper holds it, its next up can also interrupt your press. - Windows routes input through the desktop. After focus changes or the original window closes, a confirmed release means the desktop accepted the up. The original window may not receive the event. If the desktop is unavailable or refuses to confirm release, further CUA input for the task is blocked. Inspect the desktop before starting another task. - Cleanup of temporary input inside complete actions does not check each key or button release. If an input remains held after a failure, release it manually before continuing. - Helper identity hashes only the exe. Different DLLs with the same apphost can reuse the old service. Stop Hosts using the same output directory before rebuilding to avoid locked files. diff --git a/packages/experimental/cua-windows/README.zh.md b/packages/experimental/cua-windows/README.zh.md index dbc9067e2a..49c1558534 100644 --- a/packages/experimental/cua-windows/README.zh.md +++ b/packages/experimental/cua-windows/README.zh.md @@ -82,6 +82,7 @@ kind: "package-reference" - 通过 npm 安装的包不含 Windows helper。x64 可使用独立 ZIP,ARM64 需要对应架构的构建产物,见[配置说明](#setup)。 - 悬停、点击、滚动和拖拽使用系统指针。`requireSystemInputApproval` 不会为 Windows 操作弹出单独的指针授权提示。 - 拖拽只检查起点处最上层的窗口。若其他应用遮住路径或终点,即使目标仍在前台,也可能把内容拖到其他应用。 +- 持有提醒和清理只依据 helper 自己派发的输入。如果你也按住同一个键或按钮,helper 之后发送的 up 可能打断你的按压。 - Windows 通过桌面派发输入。焦点变化或原窗口关闭后,确认释放表示桌面接受了 up,原窗口可能收不到该事件。若桌面不可用或无法确认释放,本任务不能继续使用 CUA。请先检查桌面,再开始新任务。 - 清理完整动作内的临时输入时,helper 不检查每个按键或鼠标按钮的释放结果。操作失败后如有按键或按钮仍处于按下状态,请先手动释放。 - helper 的身份摘要只覆盖 exe。同一 apphost 搭配不同 DLL 时可能复用旧服务。重新构建前请先关闭使用同一输出目录的 Host,避免文件被占用。 diff --git a/packages/experimental/cua-windows/native/desktop-tests/Program.cs b/packages/experimental/cua-windows/native/desktop-tests/Program.cs index 5e96f96a96..fabce63383 100644 --- a/packages/experimental/cua-windows/native/desktop-tests/Program.cs +++ b/packages/experimental/cua-windows/native/desktop-tests/Program.cs @@ -12,6 +12,7 @@ internal sealed class FixtureForm : Form private readonly Button button = new() { Name = "submit", Text = "Record click", Bounds = new(20, 140, 180, 40) }; private int clicks; private readonly List inputEvents = []; + private MouseButtons receivedButtons; private int leftDowns, leftUps, rightDowns, rightUps, middleDowns, middleUps; private readonly ToolTip tooltip = new(); @@ -41,6 +42,7 @@ internal sealed class FixtureForm : Form private void Count(MouseButtons pressed, bool down) { + receivedButtons = down ? receivedButtons | pressed : receivedButtons & ~pressed; inputEvents.Add($"{pressed}:{(down ? "down" : "up")}"); switch (pressed) { @@ -84,8 +86,8 @@ internal sealed class FixtureForm : Form ups = new { left = leftUps, right = rightUps, middle = middleUps }, button = new { x = button.Left + button.Width / 2, y = button.Top + button.Height / 2 }, selection = new { start = Editor.SelectionStart, length = Editor.SelectionLength }, - inputEvents = inputEvents.ToArray(), wDown = (GetAsyncKeyState(87) & 0x8000) != 0, - buttons = MouseButtons.ToString(), minimized = WindowState == FormWindowState.Minimized, visible = Visible, + inputEvents = inputEvents.ToArray(), + buttons = receivedButtons.ToString(), minimized = WindowState == FormWindowState.Minimized, visible = Visible, }; protected override void Dispose(bool disposing) @@ -94,7 +96,6 @@ internal sealed class FixtureForm : Form base.Dispose(disposing); } - [DllImport("user32.dll")] private static extern short GetAsyncKeyState(int key); [DllImport("user32.dll")] private static extern nint GetForegroundWindow(); [DllImport("user32.dll")] private static extern nint WindowFromPoint(Point point); [DllImport("user32.dll")] private static extern nint GetAncestor(nint window, uint flags); @@ -141,6 +142,7 @@ internal static class Program { case "sibling": sibling.Show(); sibling.Activate(); sibling.Editor.Focus(); Write(sibling.Inspect()); break; case "inspect": Write(form.Inspect()); break; + case "inspect-sibling": Write(sibling.Inspect()); break; case "focus": form.Activate(); form.Editor.Focus(); Write(form.Inspect()); break; case "pointer": form.PointAtButton(); Write(form.Inspect()); break; case "pointer-outside": form.PointOutside(); Write(form.Inspect()); break; diff --git a/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs b/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs index 0bcad20693..e553283013 100644 --- a/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs +++ b/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs @@ -15,21 +15,9 @@ internal sealed class ClientState internal void Clear() { foreach (var app in Apps.Values) app.Dispose(); Apps.Clear(); } } -internal sealed class DesktopExecutor : IAsyncDisposable +internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IAsyncDisposable { - private readonly MtaDispatcher mta; - private readonly StaDispatcher sta; - private readonly HeldInputs inputs = new(control => (Win32.GetAsyncKeyState(control) & 0x8000) != 0, - input => Input.Send(input), DesktopSession.RequireInteractive); - private readonly HeldInputHooks hooks; - - internal DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) - { - this.mta = mta; - this.sta = sta; - hooks = new(inputs); - } - + private readonly HeldInputs inputs = new(input => Input.Send(input), DesktopSession.RequireInteractive); private readonly WindowCapture capture = new(); private readonly ClipboardPaste clipboard = new(); private readonly SemaphoreSlim queue = new(1); @@ -100,7 +88,7 @@ internal sealed class DesktopExecutor : IAsyncDisposable throw new NativeFailure("UNSUPPORTED", "Windows desktop access has no macOS permission switches; inspect the Windows session status"); if (request.Method == "getHeldInputs") return inputs.Get(state.Connection, String(parameters, "taskId")); if (request.Method == "releaseHeldInputs") - return inputs.Release(state.Connection, String(parameters, "taskId"), cancellation, config.GraceMs); + return inputs.Release(state.Connection, String(parameters, "taskId"), cancellation); if (request.Method is "sendKeyEvent" or "toggleMouse" && String(parameters, "direction") == "up") { @@ -108,10 +96,11 @@ internal sealed class DesktopExecutor : IAsyncDisposable var task = String(parameters, "taskId"); var recipient = String(parameters, "appHandle"); var before = Win32.GetForegroundWindow(); - var dispatched = request.Method == "sendKeyEvent" - ? Input.ReleaseKey(state.Connection, task, recipient, window, String(parameters, "key"), context) - : Input.ReleaseButton(state.Connection, task, recipient, window, String(parameters, "mouseButton"), context); - return ActionResult(before, dispatched); + if (request.Method == "sendKeyEvent") + Input.ReleaseKey(state.Connection, task, recipient, window, String(parameters, "key"), context); + else + Input.ReleaseButton(state.Connection, task, recipient, window, String(parameters, "mouseButton"), context); + return ActionResult(before); } DesktopSession.RequireInteractive(); if (request.Method == "listApps") return await DesktopWindows.ListApps(context); @@ -174,7 +163,6 @@ internal sealed class DesktopExecutor : IAsyncDisposable case "sendKeyEvent": { var target = Selected(app, parameters, context); - await sta.Invoke(hooks.Start, cancellation); var dispatched = Input.KeyDown(state.Connection, String(parameters, "taskId"), app, target, String(parameters, "key"), context); return ActionResult(foreground, dispatched); } @@ -206,7 +194,6 @@ internal sealed class DesktopExecutor : IAsyncDisposable case "toggleMouse": { var target = Selected(app, parameters, context); - await sta.Invoke(hooks.Start, cancellation); var dispatched = Input.ButtonDown(state.Connection, String(parameters, "taskId"), app, target, String(parameters, "mouseButton"), context); return ActionResult(foreground, dispatched); } @@ -317,13 +304,13 @@ internal sealed class DesktopExecutor : IAsyncDisposable if (!inputs.HasConnection(state.Connection)) return; using var deadline = new CancellationTokenSource(graceMs); await queue.WaitAsync(deadline.Token); - try { inputs.Release(state.Connection, null, deadline.Token, graceMs); } + try { inputs.Release(state.Connection, null, deadline.Token); } finally { queue.Release(); } } - public async ValueTask DisposeAsync() + public ValueTask DisposeAsync() { - await sta.Invoke(hooks.Dispose, CancellationToken.None); queue.Dispose(); + return ValueTask.CompletedTask; } } diff --git a/packages/experimental/cua-windows/native/entry/HeldInputs.cs b/packages/experimental/cua-windows/native/entry/HeldInputs.cs index 55a133ac05..47267898b5 100644 --- a/packages/experimental/cua-windows/native/entry/HeldInputs.cs +++ b/packages/experimental/cua-windows/native/entry/HeldInputs.cs @@ -1,16 +1,14 @@ -// The shared desktop executor serializes dispatch. Hooks arbitrate external input in the Windows input stream. +// Held keys and buttons share one dispatch order across all connections to this desktop executor. using System.Globalization; -using System.Runtime.InteropServices; using DeepSeek.Cua.Protocol; namespace DeepSeek.Cua.Windows; -internal sealed class HeldInputs(Func isDown, Action send, Action requireInteractive) +internal sealed class HeldInputs(Action send, Action requireInteractive) { internal readonly record struct Target(string AppHandle, nint Window, int ProcessId, long ProcessStarted); private sealed record Press(Guid Connection, string Task, Target Target, ushort Control, string Name, Win32.Input Up) { - internal bool Confirmed { get; set; } internal object Describe() => new { kind = Up.Type == 1 ? "key" : "mouse", key = Up.Type == 1 ? Name : null, @@ -19,70 +17,28 @@ internal sealed class HeldInputs(Func isDown, Action }; } - private sealed record Dispatch(Press Press, nuint Tag, TaskCompletionSource Completion); - private readonly object gate = new(); private readonly List pressed = []; - private readonly nuint prefix = unchecked((nuint)Random.Shared.NextInt64(1, int.MaxValue)) << 32; - private uint sequence; - private Dispatch? pending; - - internal static ushort CanonicalControl(ushort key) => key switch - { - 0xA0 or 0xA1 => 0x10, // Shift - 0xA2 or 0xA3 => 0x11, // Control - 0xA4 or 0xA5 => 0x12, // Alt - _ => key, - }; - - // An accepted external event supersedes an owned hold on the same global Windows input. - internal nint Observe(ushort control, nuint tag, Func next) - { - Dispatch? dispatch; - lock (gate) - { - dispatch = pending?.Tag == tag ? pending : null; - if (dispatch is not null && !pressed.Contains(dispatch.Press)) - { - dispatch.Completion.TrySetResult(false); - return 1; - } - // A delayed synthetic event without an admitted dispatch must not reach the desktop. - if (dispatch is null && tag >> 32 == prefix >> 32) return 1; - } - var outcome = next(); - lock (gate) - { - if (dispatch is not null) dispatch.Completion.TrySetResult(outcome == 0); - else if (outcome == 0) pressed.RemoveAll(press => press.Control == control); - } - return outcome; - } internal void RequireOwner(Guid connection, string? task, string app, nint window) { lock (gate) - { - if (pressed.Exists(press => !press.Confirmed)) - throw new NativeFailure("INPUT_DISPATCH_UNCONFIRMED", "Release unconfirmed held input before sending more desktop input"); if (pressed.Any(press => press.Connection != connection || (task is not null && press.Task != task) || press.Target.AppHandle != app || press.Target.Window != window)) throw new NativeFailure("INPUT_BUSY", "Another task or window owns held desktop input; release it before sending input to this window"); - } } internal void RequireAvailable(ushort control) { lock (gate) - if (pressed.Any(press => press.Control == control) || isDown(control)) + if (pressed.Any(press => press.Control == control)) throw new NativeFailure("INPUT_BUSY", "This key or button is already held; release it before a complete action uses it"); } internal bool Down(Guid connection, string task, Target target, ushort control, string name, Win32.Input down, - Win32.Input up, CancellationToken cancellation, int graceMs) + Win32.Input up, CancellationToken cancellation) { - Press press; lock (gate) { cancellation.ThrowIfCancellationRequested(); @@ -93,47 +49,35 @@ internal sealed class HeldInputs(Func isDown, Action return false; throw new NativeFailure("INPUT_BUSY", "This key or button is already held by another input target"); } - if (isDown(control)) - throw new NativeFailure("INPUT_BUSY", "This key or button is already down outside this task; ask the user to release it before retrying"); - press = new(connection, task, target, control, name, up); + + var press = new Press(connection, task, target, control, name, up); pressed.Add(press); - } - try - { - if (Post(press, down, graceMs)) + try { send(down); } + catch (NativeFailure error) when (error.Code == "INPUT_BLOCKED") { - lock (gate) press.Confirmed = true; - return true; + // SendInput accepted zero events, so there is no corresponding up to send. + pressed.Remove(press); + throw; } + return true; } - catch (NativeFailure error) when (error.Code == "INPUT_BLOCKED") - { - lock (gate) pressed.Remove(press); - throw; - } - lock (gate) pressed.Remove(press); - throw new NativeFailure("INPUT_BLOCKED", "Windows did not deliver the requested press to its input stream"); } - internal bool Up(Guid connection, string task, string app, nint window, string name, bool keyboard, int graceMs) + internal void Up(Guid connection, string task, string app, nint window, string name, bool keyboard) { - Press? press; lock (gate) - press = pressed.Find(press => press.Connection == connection && press.Task == task && press.Target.AppHandle == app + { + var index = pressed.FindIndex(press => press.Connection == connection && press.Task == task && press.Target.AppHandle == app && press.Target.Window == window && press.Name == name && (press.Up.Type == 1) == keyboard); - if (press is null) throw new NativeFailure("INPUT_NOT_HELD", "This task did not hold that input on the selected window"); - return Release(press, graceMs); + if (index < 0) throw new NativeFailure("INPUT_NOT_HELD", "This task did not hold that input on the selected window"); + ReleaseAt(index); + } } internal object[] Get(Guid connection, string task) { lock (gate) - { - var owned = pressed.Where(press => press.Connection == connection && press.Task == task).ToArray(); - if (owned.Any(press => !press.Confirmed)) - throw new NativeFailure("INPUT_DISPATCH_UNCONFIRMED", "Windows did not confirm which inputs are held"); - return owned.Select(press => press.Describe()).ToArray(); - } + return pressed.Where(press => press.Connection == connection && press.Task == task).Select(press => press.Describe()).ToArray(); } internal bool HasConnection(Guid connection) @@ -141,113 +85,29 @@ internal sealed class HeldInputs(Func isDown, Action lock (gate) return pressed.Exists(press => press.Connection == connection); } - internal object[] Release(Guid connection, string? task, CancellationToken cancellation, int graceMs) + internal object[] Release(Guid connection, string? task, CancellationToken cancellation) { - Press[] owned; - lock (gate) owned = pressed.Where(press => press.Connection == connection && (task is null || press.Task == task)).Reverse().ToArray(); - var released = new List(); - var failures = new List(); - foreach (var press in owned) + lock (gate) { - cancellation.ThrowIfCancellationRequested(); - try { if (Release(press, graceMs)) released.Add(press.Describe()); } - catch (NativeFailure error) { failures.Add(error.Message); } + var released = new List(); + var failures = new List(); + for (var index = pressed.Count - 1; index >= 0; index--) + { + var press = pressed[index]; + if (press.Connection != connection || (task is not null && press.Task != task)) continue; + cancellation.ThrowIfCancellationRequested(); + try { ReleaseAt(index); released.Add(press.Describe()); } + catch (NativeFailure error) { failures.Add(error.Message); } + } + if (failures.Count != 0) throw new NativeFailure("INPUT_CLEANUP_FAILED", string.Join("; ", failures)); + return released.ToArray(); } - if (failures.Count != 0) throw new NativeFailure("INPUT_CLEANUP_FAILED", string.Join("; ", failures)); - return released.ToArray(); } - private bool Release(Press press, int graceMs) + private void ReleaseAt(int index) { - lock (gate) if (!pressed.Contains(press)) return false; - // SendInput releases the global input at its current destination; never reactivate an old HWND. requireInteractive(); - var posted = Post(press, press.Up, graceMs); - lock (gate) - { - if (posted) pressed.Remove(press); - else if (pressed.Contains(press)) - throw new NativeFailure("INPUT_BLOCKED", "Windows did not deliver the requested release to its input stream"); - } - return posted; - } - - private bool Post(Press press, Win32.Input input, int graceMs) - { - Dispatch dispatch; - lock (gate) - { - if (!pressed.Contains(press)) return false; - if (pending is not null) throw new NativeFailure("INPUT_BUSY", "Another held input is being dispatched"); - dispatch = new(press, prefix | ++sequence, new(TaskCreationOptions.RunContinuationsAsynchronously)); - pending = dispatch; - } - try - { - if (input.Type == 1) input.Data.Keyboard.Extra = dispatch.Tag; - else input.Data.Mouse.Extra = dispatch.Tag; - send(input); - return dispatch.Completion.Task.WaitAsync(TimeSpan.FromMilliseconds(graceMs)).GetAwaiter().GetResult(); - } - catch (TimeoutException) - { - lock (gate) press.Confirmed = false; - throw new NativeFailure("INPUT_DISPATCH_UNCONFIRMED", "Windows did not confirm the held-input event; inspect the desktop before retrying"); - } - finally - { - lock (gate) pending = null; - } - } - -} - -internal sealed class HeldInputHooks(HeldInputs inputs) : IDisposable -{ - [StructLayout(LayoutKind.Sequential)] - private struct KeyEvent { internal uint Key, Scan, Flags, Time; internal nuint Extra; } - [StructLayout(LayoutKind.Sequential)] - private struct MouseEvent { internal Win32.Point Point; internal uint Data, Flags, Time; internal nuint Extra; } - - private nint keyboard; - private nint mouse; - private readonly Win32.InputHook keyHook = (code, message, value) => - { - if (code < 0) return Win32.CallNextHookEx(0, code, message, value); - var input = Marshal.PtrToStructure(value); - if (input.Key > ushort.MaxValue) return Win32.CallNextHookEx(0, code, message, value); - return inputs.Observe(HeldInputs.CanonicalControl((ushort)input.Key), input.Extra, () => Win32.CallNextHookEx(0, code, message, value)); - }; - private readonly Win32.InputHook mouseHook = (code, message, value) => - { - ushort control = message switch - { - 0x0201 or 0x0202 => 1, // Left down/up - 0x0204 or 0x0205 => 2, // Right down/up - 0x0207 or 0x0208 => 4, // Middle down/up - _ => 0, - }; - if (code < 0 || control == 0) return Win32.CallNextHookEx(0, code, message, value); - var input = Marshal.PtrToStructure(value); - return inputs.Observe(control, input.Extra, () => Win32.CallNextHookEx(0, code, message, value)); - }; - - // Low-level hooks must be installed on a thread that pumps Windows messages. - internal void Start() - { - if (keyboard != 0) return; - var module = Win32.GetModuleHandle(null); - keyboard = Win32.SetWindowsHookEx(13, keyHook, module, 0); - mouse = Win32.SetWindowsHookEx(14, mouseHook, module, 0); - if (keyboard != 0 && mouse != 0) return; - Dispose(); - throw new NativeFailure("INPUT_UNAVAILABLE", "Windows could not observe ownership of held desktop input"); - } - - public void Dispose() - { - if (keyboard != 0) Win32.UnhookWindowsHookEx(keyboard); - if (mouse != 0) Win32.UnhookWindowsHookEx(mouse); - keyboard = mouse = 0; + send(pressed[index].Up); + pressed.RemoveAt(index); } } diff --git a/packages/experimental/cua-windows/native/entry/Input.cs b/packages/experimental/cua-windows/native/entry/Input.cs index f213cd3769..36fc33b79d 100644 --- a/packages/experimental/cua-windows/native/entry/Input.cs +++ b/packages/experimental/cua-windows/native/entry/Input.cs @@ -104,8 +104,8 @@ internal static class Input var key => key, }; - internal static bool ReleaseKey(Guid connection, string task, string app, nint window, string name, RequestContext context) - => context.HeldInputs.Up(connection, task, app, window, HoldKeyName(name), true, context.Config.GraceMs); + internal static void ReleaseKey(Guid connection, string task, string app, nint window, string name, RequestContext context) + => context.HeldInputs.Up(connection, task, app, window, HoldKeyName(name), true); internal static bool KeyDown(Guid connection, string task, AppState app, WindowState window, string name, RequestContext context) { @@ -116,7 +116,7 @@ internal static class Input throw new NativeFailure("UNSUPPORTED", "This key requires modifiers in the target keyboard layout; send each modifier and the base key separately"); var flags = key.Extended ? 1u : 0; return context.HeldInputs.Down(connection, task, new(app.Handle, window.Id, window.ProcessId, window.ProcessStarted), - key.Key, name, Keyboard(key.Key, flags: flags), Keyboard(key.Key, flags: flags | 2), context.Cancellation, context.Config.GraceMs); + key.Key, name, Keyboard(key.Key, flags: flags), Keyboard(key.Key, flags: flags | 2), context.Cancellation); } internal static void Press(AppState app, WindowState window, string key, string[] modifiers, RequestContext context) @@ -187,8 +187,8 @@ internal static class Input return new { dispatched = true, hoverRoute = "system-pointer", systemPointerMoved = before.X != point.X || before.Y != point.Y }; } - internal static bool ReleaseButton(Guid connection, string task, string app, nint window, string button, RequestContext context) - => context.HeldInputs.Up(connection, task, app, window, button, false, context.Config.GraceMs); + internal static void ReleaseButton(Guid connection, string task, string app, nint window, string button, RequestContext context) + => context.HeldInputs.Up(connection, task, app, window, button, false); internal static bool ButtonDown(Guid connection, string task, AppState app, WindowState window, string button, RequestContext context) { @@ -196,7 +196,7 @@ internal static class Input if (!Win32.GetCursorPos(out var point)) throw new NativeFailure("INPUT_UNAVAILABLE", "The current pointer position is unavailable"); Hit(app, window, point, context); return context.HeldInputs.Down(connection, task, new(app.Handle, window.Id, window.ProcessId, window.ProcessStarted), - flags.Control, button, Mouse(flags.Down), Mouse(flags.Up), context.Cancellation, context.Config.GraceMs); + flags.Control, button, Mouse(flags.Down), Mouse(flags.Up), context.Cancellation); } internal static void Click(AppState app, WindowState window, double x, double y, string button, int count, string[] modifiers, RequestContext context) @@ -274,11 +274,12 @@ internal static class Input 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 flags = Button(button); + context.HeldInputs.RequireAvailable(flags.Control); 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(); var attempted = new List(); var buttonAttempted = false; diff --git a/packages/experimental/cua-windows/native/entry/Win32.cs b/packages/experimental/cua-windows/native/entry/Win32.cs index d19f713cf3..7f15ab66c4 100644 --- a/packages/experimental/cua-windows/native/entry/Win32.cs +++ b/packages/experimental/cua-windows/native/entry/Win32.cs @@ -62,12 +62,6 @@ internal static class Win32 [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); - internal delegate nint InputHook(int code, nuint message, nint value); - [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal static extern nint GetModuleHandle(string? module); - [DllImport("user32.dll", CharSet = CharSet.Unicode)] internal static extern nint SetWindowsHookEx(int kind, InputHook hook, nint module, uint thread); - [DllImport("user32.dll")] internal static extern nint CallNextHookEx(nint hook, int code, nuint message, nint value); - [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool UnhookWindowsHookEx(nint hook); - [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); diff --git a/packages/experimental/cua-windows/native/tests/HeldInputChecks.cs b/packages/experimental/cua-windows/native/tests/HeldInputChecks.cs index b29bd1e769..a805c24a81 100644 --- a/packages/experimental/cua-windows/native/tests/HeldInputChecks.cs +++ b/packages/experimental/cua-windows/native/tests/HeldInputChecks.cs @@ -1,4 +1,4 @@ -// The fake input stream drives the same admission and hook callbacks as SendInput. +// The receiver records accepted dispatches and can refuse an individual down or up. using System.Text.Json; using DeepSeek.Cua.Protocol; using DeepSeek.Cua.Windows; @@ -10,22 +10,18 @@ internal static class HeldInputChecks var a = Guid.NewGuid(); var b = Guid.NewGuid(); var target = new HeldInputs.Target("app", 72, 122, 100); - var physical = new HashSet(); var events = new List(); var blocked = false; - var overlap = false; var interactive = true; - HeldInputs inputs = null!; - inputs = new(physical.Contains, input => + void Receive(Win32.Input input) { if (blocked) throw new NativeFailure("INPUT_BLOCKED", "SendInput returned zero"); var isKey = input.Type == 1; var control = isKey ? input.Data.Keyboard.Key : (ushort)1; - var tag = isKey ? input.Data.Keyboard.Extra : input.Data.Mouse.Extra; var up = isKey ? (input.Data.Keyboard.Flags & 2) != 0 : input.Data.Mouse.Flags == 4; - if (overlap) inputs.Observe(control, 0, () => 0); - inputs.Observe(control, tag, () => { events.Add($"{control}:{(up ? "up" : "down")}"); return 0; }); - }, () => + events.Add($"{control}:{(up ? "up" : "down")}"); + } + var inputs = new HeldInputs(Receive, () => { if (!interactive) throw new NativeFailure("SESSION_LOCKED", "The interactive desktop is unavailable"); }); @@ -34,12 +30,10 @@ internal static class HeldInputChecks => inputs.Down(connection, task, target, key, name, new() { Type = 1, Data = new() { Keyboard = new() { Key = key } } }, new() { Type = 1, Data = new() { Keyboard = new() { Key = key, Flags = 2 } } }, - cancellation, 100); + cancellation); - physical.Add(16); - refuses(() => Key(a, "task", 16, "shift"), "INPUT_BUSY"); - check(events.Count == 0, "Physical input cannot become an owned hold"); - physical.Clear(); + refuses(() => inputs.Up(a, "task", "app", 72, "shift", true), "INPUT_NOT_HELD"); + check(events.Count == 0, "No up is sent for a key the helper never pressed"); blocked = true; refuses(() => Key(a, "task", 16, "shift"), "INPUT_BLOCKED"); check(inputs.Get(a, "task").Length == 0, "A refused down does not cause an up"); @@ -47,23 +41,23 @@ internal static class HeldInputChecks check(Key(a, "task", 16, "shift"), "Record the accepted keyboard down"); check(inputs.Down(a, "task", target, 1, "left", new() { Data = new() { Mouse = new() { Flags = 2 } } }, - new() { Data = new() { Mouse = new() { Flags = 4 } } }, default, 100), "Record the accepted mouse down"); + new() { Data = new() { Mouse = new() { Flags = 4 } } }, default), "Record the accepted mouse down"); check(Key(a, "task", 87, "w") && !Key(a, "task", 87, "w"), "A repeated key does not duplicate a hold"); refuses(() => inputs.RequireOwner(b, "task", "app", 72), "INPUT_BUSY"); refuses(() => inputs.RequireOwner(a, "other", "app", 72), "INPUT_BUSY"); refuses(() => inputs.RequireAvailable(1), "INPUT_BUSY"); - refuses(() => inputs.Up(a, "other", "app", 72, "w", true, 100), "INPUT_NOT_HELD"); - refuses(() => inputs.Up(a, "task", "app", 73, "w", true, 100), "INPUT_NOT_HELD"); - check(inputs.Release(b, null, default, 100).Length == 0, "Another connection releases nothing"); + refuses(() => inputs.Up(a, "other", "app", 72, "w", true), "INPUT_NOT_HELD"); + refuses(() => inputs.Up(a, "task", "app", 73, "w", true), "INPUT_NOT_HELD"); + check(inputs.Release(b, null, default).Length == 0, "Another connection releases nothing"); check(inputs.Get(a, "other").Length == 0 && inputs.Get(a, "task").Length == 3, "State query is task-scoped"); var described = JsonSerializer.SerializeToElement(inputs.Get(a, "task"), WireJson.Options); check(described[0].GetProperty("windowId").GetString() == "72" && described[0].GetProperty("mode").GetString() == "system", "Keyboard reminders identify the window and actual desktop mode"); - check(inputs.Up(a, "task", "app", 72, "shift", true, 100) && Key(a, "task", 16, "shift"), - "Explicit up and repress update the dispatch order"); - check(inputs.Release(a, "task", default, 100).Length == 3 + inputs.Up(a, "task", "app", 72, "shift", true); + check(Key(a, "task", 16, "shift"), "Explicit up and repress update the dispatch order"); + check(inputs.Release(a, "task", default).Length == 3 && events.TakeLast(3).SequenceEqual(["16:up", "87:up", "1:up"]), "Release in mixed reverse order, including repress"); - check(inputs.Release(a, null, default, 100).Length == 0, "Duplicate connection cleanup sends no up"); + check(inputs.Release(a, null, default).Length == 0, "Duplicate connection cleanup sends no up"); using (var cancelled = new CancellationTokenSource()) { cancelled.Cancel(); @@ -72,16 +66,22 @@ internal static class HeldInputChecks } Key(a, "task", 87, "w"); interactive = false; - refuses(() => inputs.Release(a, null, default, 100), "INPUT_CLEANUP_FAILED"); + refuses(() => inputs.Release(a, null, default), "INPUT_CLEANUP_FAILED"); check(inputs.Get(a, "task").Length == 1, "A locked desktop leaves the failed release recorded"); interactive = true; blocked = true; - refuses(() => inputs.Release(a, null, default, 100), "INPUT_CLEANUP_FAILED"); + refuses(() => inputs.Release(a, null, default), "INPUT_CLEANUP_FAILED"); check(inputs.Get(a, "task").Length == 1, "A refused release stays recorded for disconnect fallback"); blocked = false; + // Another source releases W and presses D at the same receiver. + Receive(new() { Type = 1, Data = new() { Keyboard = new() { Key = 87, Flags = 2 } } }); + Receive(new() { Type = 1, Data = new() { Keyboard = new() { Key = 68 } } }); + described = JsonSerializer.SerializeToElement(inputs.Get(a, "task"), WireJson.Options); + check(described.GetArrayLength() == 1 && described[0].GetProperty("key").GetString() == "w", + "The reminder still reports only the helper's W down"); var count = events.Count; - overlap = true; - check(inputs.Release(a, null, default, 100).Length == 0 && inputs.Get(a, "task").Length == 0 && events.Count == count, - "An external event at dispatch time wins and the owned event cannot lift user input"); + check(inputs.Release(a, null, default).Length == 1 && events.Skip(count).SequenceEqual(["87:up"]), + "Disconnect retries the helper's W release and leaves D alone"); + check(!inputs.HasConnection(a), "Accepted release removes the connection's last hold"); } } diff --git a/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts b/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts index a84b329811..1b2d41a34f 100644 --- a/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts +++ b/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts @@ -15,7 +15,7 @@ const Counts = z.object({ left: z.number().int(), right: z.number().int(), middl const FixtureState = z.object({ window: z.string(), foreground: z.string(), cursor: z.object({ x: z.number().int(), y: z.number().int() }), - inputEvents: z.array(z.string()), wDown: z.boolean(), + inputEvents: z.array(z.string()), under: z.string(), buttons: z.string(), clicks: z.number().int(), downs: Counts, ups: Counts, }) const Initial = z.object({ pid: z.number().int(), state: FixtureState }) @@ -153,6 +153,8 @@ it.skipIf(process.platform !== 'win32' || !helperPath || !fixturePath)( const offset = (await inspect()).inputEvents.length await key('shift', 'down') await toggle('left', 'down') + await expect(native.request('drag', { appHandle: app.appHandle, windowId, fromX: 20, fromY: 20, toX: 30, toY: 30, + mouseButton: 'left', durationMs: 100, steps: 2 }, signal)).rejects.toMatchObject({ code: 'INPUT_BUSY' }) await key('w', 'down') expect(released.parse(await holds()).map(input => input.key ?? input.button)).toEqual(['shift', 'left', 'w']) @@ -168,11 +170,15 @@ it.skipIf(process.platform !== 'win32' || !helperPath || !fixturePath)( await expect.poll(async () => (await inspect()).inputEvents.slice(offset)).toEqual( ['ShiftKey:down', 'Left:down', 'W:down', 'W:up', 'Left:up', 'ShiftKey:up']) + const beforeSwitch = (await inspect()).inputEvents.length await key('w', 'down') - await observed({ wDown: true }) + await expect.poll(async () => (await inspect()).inputEvents.slice(beforeSwitch)).toEqual(['W:down']) const switched = await fixture.command('sibling', FixtureState) expect(switched.foreground).toBe(switched.window) await native.dispose() - await observed({ foreground: switched.window, wDown: false }) + await expect.poll(async () => { + const sibling = await fixture.command('inspect-sibling', FixtureState) + return { foreground: sibling.foreground, events: sibling.inputEvents.slice(switched.inputEvents.length) } + }).toEqual({ foreground: switched.window, events: ['W:up'] }) }, 120_000) From ad535742cb329580e2230399e9cac72e53cb58d6 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 20 Nov 2026 13:35:57 +0800 Subject: [PATCH 68/73] Exercise an independent mouse release at the Windows desktop receiver --- .../cua-windows/native/desktop-tests/Program.cs | 10 +++++----- .../cua-windows/tests/desktop-toggle-mouse.spec.ts | 12 +++++++++++- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/packages/experimental/cua-windows/native/desktop-tests/Program.cs b/packages/experimental/cua-windows/native/desktop-tests/Program.cs index fabce63383..7d82b6da8b 100644 --- a/packages/experimental/cua-windows/native/desktop-tests/Program.cs +++ b/packages/experimental/cua-windows/native/desktop-tests/Program.cs @@ -105,13 +105,12 @@ internal static class Program { private static void Write(object value) { Console.WriteLine(JsonSerializer.Serialize(value)); Console.Out.Flush(); } - private static void ReleaseButtons() + private static void SendMouse(params uint[] flags) { - var inputs = new[] { 0x0004u, 0x0010u, 0x0040u } - .Select(flags => new Input { Type = 0, Data = new MouseInput { Flags = flags } }).ToArray(); + var inputs = flags.Select(flag => new Input { Type = 0, Data = new MouseInput { Flags = flag } }).ToArray(); if (SendInput((uint)inputs.Length, inputs, Marshal.SizeOf()) != inputs.Length) { - Console.Error.WriteLine("Fixture could not release every mouse button"); + Console.Error.WriteLine("Fixture could not dispatch all requested mouse events"); Environment.ExitCode = 1; } } @@ -148,7 +147,8 @@ internal static class Program case "pointer-outside": form.PointOutside(); Write(form.Inspect()); break; case "cover": form.Cover(sibling); Write(new { form = form.Inspect(), sibling = sibling.Inspect() }); break; case "uncover": form.Uncover(sibling); Write(form.Inspect()); break; - case "release-input": ReleaseButtons(); Write(form.Inspect()); break; + case "left-up": SendMouse(0x0004); Write(form.Inspect()); break; + case "release-input": SendMouse(0x0004, 0x0010, 0x0040); 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; diff --git a/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts b/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts index 1b2d41a34f..1c6d99ca7a 100644 --- a/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts +++ b/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts @@ -170,9 +170,19 @@ it.skipIf(process.platform !== 'win32' || !helperPath || !fixturePath)( await expect.poll(async () => (await inspect()).inputEvents.slice(offset)).toEqual( ['ShiftKey:down', 'Left:down', 'W:down', 'W:up', 'Left:up', 'ShiftKey:up']) + const beforeExternal = await inspect() + await toggle('left', 'down') + await observed({ downs: { left: beforeExternal.downs.left + 1 } }) + await fixture.command('left-up', FixtureState) + await observed({ ups: { left: beforeExternal.ups.left + 1 } }) + expect(released.parse(await holds()).map(input => input.button)).toEqual(['left']) + const afterExternal = await native.requestCleanup('releaseHeldInputs', { taskId }) + expect(released.parse(afterExternal).map(input => input.button)).toEqual(['left']) + expect(await holds()).toEqual([]) + const beforeSwitch = (await inspect()).inputEvents.length await key('w', 'down') - await expect.poll(async () => (await inspect()).inputEvents.slice(beforeSwitch)).toEqual(['W:down']) + await expect.poll(async () => (await inspect()).inputEvents.slice(beforeSwitch)).toContain('W:down') const switched = await fixture.command('sibling', FixtureState) expect(switched.foreground).toBe(switched.window) await native.dispose() From b39c243f4d9e94eb6142eb6fbdbe1e3be6d55d82 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 20 Nov 2026 15:04:08 +0800 Subject: [PATCH 69/73] Scope native CUA input holds to the issuing connection --- ...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-held-inputs/guide.i18n.yaml | 4 +- .../v0.2.2-rc.5/cua-held-inputs/guide.md | 2 +- .../v0.2.2-rc.5/cua-held-inputs/guide.zh.md | 2 +- .../experimental/cua-macos/README.i18n.yaml | 4 +- packages/experimental/cua-macos/README.md | 2 +- packages/experimental/cua-macos/README.zh.md | 2 +- .../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 | 6 +- .../native/Sources/CuaNative/HeldInputs.swift | 21 +++---- .../Sources/CuaNative/KeyboardInput.swift | 8 +-- .../CuaNative/NativeProtocol.generated.swift | 10 ++-- .../CuaNative/RequestCoordinator.swift | 11 ++-- .../CuaNative/SystemPointerInput.swift | 2 +- .../cua-macos/native/generate-protocol.ts | 10 +--- .../cua-macos/native/protocol.schema.json | 42 ++----------- .../native/tests/capabilities_e2e.py | 4 +- .../native/tests/native_test_support.py | 2 - .../native/tests/shared_helper_e2e.py | 11 +++- .../native/tests/swift/HeldInputTests.swift | 60 +++++++++---------- .../native/tests/swift/SystemInputTests.swift | 20 +++---- .../native/tests/test_ax_projection.py | 2 +- .../tests/protocol-generation.spec.ts | 11 +++- .../tests/provider-lifecycle.spec.ts | 19 +++--- .../experimental/cua-windows/README.i18n.yaml | 4 +- packages/experimental/cua-windows/README.md | 2 +- .../experimental/cua-windows/README.zh.md | 2 +- .../native/entry/DesktopExecutor.cs | 17 +++--- .../cua-windows/native/entry/HeldInputs.cs | 27 ++++----- .../cua-windows/native/entry/Input.cs | 16 ++--- .../cua-windows/native/generate-protocol.ts | 9 +-- .../cua-windows/native/protocol.schema.json | 34 ++--------- .../native/tests/HeldInputChecks.cs | 56 ++++++++--------- .../cua-windows/native/tests/Program.cs | 22 ++++--- .../tests/desktop-toggle-mouse.spec.ts | 14 ++--- packages/experimental/cua/README.i18n.yaml | 4 +- packages/experimental/cua/README.md | 4 +- packages/experimental/cua/README.zh.md | 4 +- packages/experimental/cua/src/held-inputs.ts | 8 +-- packages/experimental/cua/src/index.ts | 9 +-- packages/experimental/cua/src/protocol.ts | 3 +- .../cua/tests/run-code-composition.spec.ts | 2 + .../cua-native/workspace/native-helper.mjs | 12 ++-- .../session/cua-run-code/native-channel.d.mts | 2 +- .../session/cua-run-code/native-channel.mjs | 10 ++-- 49 files changed, 230 insertions(+), 302 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 3ea19f8826..6f42792274 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 @@ -15,5 +15,5 @@ en: 32c970ae153e0f6c zh: 8431be0a10ffed15 /agent-note-cua-scoped-surfaces-and-separated-input-capabilities/consequences: - en: fd10784f6cea2da6 - zh: f31891b0179334f8 + en: c6def9831c503e1f + zh: c4c2ac5cca9f0e07 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 9142a468d6..f359842afd 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 @@ -34,6 +34,6 @@ Within one API instance, the object facade keeps one current accessibility snaps Element IDs belong to the application's current accessibility snapshot. Reading one window replaces the facade’s current snapshot for that application, so callers observe again and confirm the IDs they use. The new read does not guarantee that an old string is rejected or that an ID changes; callers must not assume an older ID still identifies the same control. Pointer input and screenshots require an explicit window object; callers enumerate windows first. -Keyboard behavior follows the provider's supported scopes. A caller that uses `sendKeyEvent` controls its down/up pairing. Native input ownership follows the task and connection. Successful DSH and MCP programs report remaining held input without releasing it. A client pause between completed MCP calls does not notify this server and can leave input held; native ownership still permits explicit release and connection cleanup. Explicit up, program failure, user cancellation and resource disposal release owned input. macOS and Windows both implement this lifecycle. Custom helpers must support the matching task-scoped query and release operations. Keyboard modifier names are provider-defined, so the same string may have different support across providers. +Keyboard behavior follows the provider's supported scopes. A caller that uses `sendKeyEvent` controls its down/up pairing. Each Agent owns an input connection, and the helper tracks holds by that connection. Successful DSH and MCP programs report remaining held input without releasing it. A client pause between completed MCP calls does not notify this server and can leave input held; native ownership still permits explicit release and connection cleanup. Explicit up, program failure, user cancellation and resource disposal release owned input. macOS and Windows both implement this lifecycle. Custom helpers must support the matching connection-scoped query and release operations. Keyboard modifier names are provider-defined, so the same string may have different support across providers. Provider guidance owns the list of supported actions. Adding a method to the shared schema does not claim that every provider implements it, and the merged `getCapabilities` result remains the runtime source for permissions and session lock. 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 4d220d0dce..e41400e492 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 @@ -34,6 +34,6 @@ Provider 的启动能力是静态的。平台、支持的方法、应用级辅 元素 ID 属于应用当前的辅助功能快照。读取一个窗口会替换门面对该应用的当前快照,因此调用方需要重新观察并确认要使用的 ID。新的读取不保证拒绝旧字符串,也不保证 ID 会改变;调用方不得假定旧 ID 仍指向同一控件。指针输入和截图都要求显式的窗口对象;调用方先枚举窗口。 -键盘行为遵循 provider 支持的作用域。使用 `sendKeyEvent` 的调用方控制按下与抬起的配对。原生输入所有权属于任务和连接。DSH 和 MCP 程序成功结束时报告剩余持有输入,不自动释放。客户端在两次 MCP 调用之间暂停时不会通知服务端,输入可能继续按住;原生所有权仍支持显式释放和连接清理。显式 up、程序失败、用户取消和资源销毁释放所属输入。macOS 和 Windows 都实现了这套生命周期。自定义 helper 必须支持对应的任务级状态查询和释放操作。键盘修饰键名称由 provider 定义,同一字符串在不同 provider 上可能支持不同。 +键盘行为遵循 provider 支持的作用域。使用 `sendKeyEvent` 的调用方控制按下与抬起的配对。每个 Agent 使用独立的输入连接,helper 按连接记录持有输入。DSH 和 MCP 程序成功结束时报告剩余持有输入,不自动释放。客户端在两次 MCP 调用之间暂停时不会通知服务端,输入可能继续按住;原生所有权仍支持显式释放和连接清理。显式 up、程序失败、用户取消和资源销毁释放所属输入。macOS 和 Windows 都实现了这套生命周期。自定义 helper 必须支持按连接查询和释放持有输入。键盘修饰键名称由 provider 定义,同一字符串在不同 provider 上可能支持不同。 Provider 指导文本负责支持动作的清单。把方法加入共享 schema 并不表示每个 provider 都已实现它;合并后的 `getCapabilities` 结果仍是权限和会话锁定状态的运行时来源。 diff --git a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml index 87f47f507c..dd561e1a74 100644 --- a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml @@ -12,5 +12,5 @@ en: cf9c1397e07dffa5 zh: f1cce9fadf321d43 /cua-reports-held-input-after-programs/migration: - en: 1bd7668cac0efe0d - zh: 2122c9d5135283f7 + en: c26899347e7a24c9 + zh: ae78a24c58d6f80f diff --git a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md index cda4b4f345..b26416c840 100644 --- a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md @@ -13,5 +13,5 @@ On macOS and Windows, explicit `sendKeyEvent('down')` and `toggleMouse('down')` ## Migration 1. Pair explicit downs with ups when input should stop. Read the reminder before continuing; no reminder is added when no input remains held. -2. Upgrade the platform package and helper together. A custom `helperPath` must implement the task-owned `getHeldInputs` and `releaseHeldInputs` private operations. +2. Upgrade the platform package and helper together. A custom `helperPath` must accept `getHeldInputs({})` and `releaseHeldInputs({})` on the same connection that dispatched the input. 3. Verify that one successful program can hold a key, receive its reminder, and release it in a later program. When a program fails or is cancelled during execution, it waits for cleanup. If the program succeeds but a post-execute policy rejects the output, the tool returns the policy error and CUA finishes cleanup independently. If the model is thinking when DSH stops or fails, the Agent can finish before native release is confirmed. Subsequent CUA calls wait for the outcome. If cleanup cannot be confirmed, CUA disables further operations for that task; inspect the desktop manually before starting another task. diff --git a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md index b9e7025603..f776b6de47 100644 --- a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md @@ -13,5 +13,5 @@ macOS 和 Windows 的显式 `sendKeyEvent('down')` 和 `toggleMouse('down')` 跨 ## 迁移 1. 输入不再需要保持时,将显式 down 与 up 配对。继续操作前阅读提醒;没有持有输入时不添加提醒。 -2. 同步升级平台包和 helper。自定义 `helperPath` 必须实现按任务区分的 `getHeldInputs` 和 `releaseHeldInputs` 私有操作。 +2. 同步升级平台包和 helper。自定义 `helperPath` 必须在派发输入的同一条连接上接受 `getHeldInputs({})` 和 `releaseHeldInputs({})`。 3. 验证成功结束的程序能持有按键、收到提醒,并在后续程序中释放。程序执行中失败或取消时,会等待自身的清理。如果程序执行成功,但后置策略拒绝结果,工具返回策略错误,CUA 单独等待原生释放确认。模型思考期间停止或报错,Agent 可以先结束,原生释放随后确认。后续 CUA 调用会等待清理结果。清理无法确认时,CUA 禁用该任务后续操作;请手动检查桌面后再创建其他任务。 diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index 49e53af0aa..71fc1dcb96 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -21,8 +21,8 @@ en: 4764629c9d31b705 zh: 107fa3b77bce0734 /deepseek-ai-dsh-cua-macos/understand-the-implementation: - en: ee655e273363bb7b - zh: 7c2d60b4a6f7343f + en: 812aa05e9fc15883 + zh: bacb60868d67bd1d /deepseek-ai-dsh-cua-macos/further-exploration: en: ff9fac614001a98f zh: 329678941154aaea diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index 3820af30e7..33b5c2478d 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -155,7 +155,7 @@ Element clicks use opaque element IDs from the current snapshot. Left clicks sup ## Understand the implementation -The shared helper's `HeldInputs` records task, connection, process generation, application/window and actual input route before dispatch. One lock orders posts, state queries and releases. Program middleware queries native state after successful execution and defers a logged reminder to the outer tool result. Failure and cancellation close input admission and await `releaseHeldInputs` using an independent bounded request. Native connection shutdown cancels and joins in-flight work before fallback release. A killed host relies on that disconnect path; host callbacks cannot be guaranteed. +The shared helper's `HeldInputs` records connection, process generation, application/window and actual input route before dispatch. One lock orders posts, state queries and releases. Program middleware queries native state after successful execution and defers a logged reminder to the outer tool result. Failure and cancellation close input admission and await `releaseHeldInputs` using an independent bounded request. Native connection shutdown cancels and joins in-flight work before fallback release. A killed host relies on that disconnect path; host callbacks cannot be guaranteed.
Dispatch and resource ownership diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 3c7f2fc170..989a0197c0 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -155,7 +155,7 @@ AppKit 的 sheet 可以出现在文档窗口的树里,并有独立的窗口 ID ## 理解实现 -共享 helper 的 `HeldInputs` 在派发前记录任务、连接、进程代次、应用或窗口和实际输入方式。同一把锁维护派发、状态查询和释放。程序中间件在成功执行后查询原生状态,并把已记录的提醒附加到外层工具结果。失败和取消会关闭输入准入,通过独立且有超时限制的请求等待 `releaseHeldInputs`。原生连接关闭会先取消并等待在途操作,再做兜底释放。宿主被强杀时依赖断连清理,无法保证宿主回调执行。 +共享 helper 的 `HeldInputs` 在派发前记录连接、进程代次、应用或窗口和实际输入方式。同一把锁维护派发、状态查询和释放。程序中间件在成功执行后查询原生状态,并把已记录的提醒附加到外层工具结果。失败和取消会关闭输入准入,通过独立且有超时限制的请求等待 `releaseHeldInputs`。原生连接关闭会先取消并等待在途操作,再做兜底释放。宿主被强杀时依赖断连清理,无法保证宿主回调执行。
操作分派与资源归属 diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index b7f0558055..cf416c0a78 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -21,8 +21,8 @@ en: da316afc1edbe50e zh: a150c1dacc689f4b /dsh-cua-native-helper/observation-and-input: - en: fdbabf0b85e16486 - zh: 62c598d8b330ffdf + en: d52f2d056703e787 + zh: 70993f7d024d831d /dsh-cua-native-helper/verification: en: 40bb7339f914bb9a zh: 272a3aae64f55d87 diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index fdf9f8ea18..420b9a7fb8 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -114,7 +114,7 @@ Capture and pointer delivery read CG bounds before and after an exact-window AX `typeText` and `pressKey` target the selected process's current focused control, not an exact window. `pressKey` presses the listed modifiers followed by one key, then releases all pressed keys in reverse order, including on cancellation. Keyboard events go directly to the target PID and bypass the global HID queue. Key names are platform-defined; keypad names such as `KP_0` and `KP_Enter` preserve their physical key codes. Background pointer actions may change that keyboard focus. Text injection sends Unicode characters individually and does not use the clipboard. LF, CR and CRLF send one Return; tabs send Tab. Applications apply their normal editing behavior, including indentation and focus navigation. Each `typeText` down/up event is followed by the configured text interval; `pressKey` keeps its own press and release timing, and dispatch completion does not confirm that the receiving application consumed every event. Cancellation can interrupt text or a gesture after partial input; it cannot undo received events. Very long text can exceed the host's operation deadline. Validate observed application state before deciding how to continue. -The Host attaches `taskId` to explicit input. `HeldInputs` records connection, task, application, original process identity, key code or button, release event and actual input mode before dispatch. Repeated key downs keep one record. Explicit up uses the saved target and input mode, skipping PID-directed releases after process exit or identity reuse. `getHeldInputs` reports only the requesting connection and task records, without reading physical user key state. Successful programs use this snapshot for their reminder. `releaseHeldInputs` releases keyboard and mouse records together in reverse dispatch order after program failure, cancellation or disposal. Normal program and turn endings do not release input. `releaseHeldInputs` returns the records whose up events were dispatched, for confirmed cleanup notices. Connection shutdown joins native work before fallback release. Balanced key chords, text, clicks and drags keep their operation-local cleanup. +`HeldInputs` records the requesting connection, application, original process identity, key code or button, release event and actual input mode before dispatch. Repeated key downs keep one record. Explicit up uses the saved target and input mode, skipping PID-directed releases after process exit or identity reuse. `getHeldInputs` reports only the requesting connection’s holds, without reading physical user key state. Successful programs use this snapshot for their reminder. `releaseHeldInputs` releases keyboard and mouse records together in reverse dispatch order after program failure, cancellation or disposal. Normal program and turn endings do not release input. `releaseHeldInputs` returns the records whose up events were dispatched, for confirmed cleanup notices. Connection shutdown joins native work before fallback release. Balanced key chords, text, clicks and drags keep their operation-local cleanup. The selected helper application needs macOS Accessibility permission for AX state and input, and Screen Recording permission for screenshots. Capability preflight and permission errors do not grant permissions. Capture refuses a window that moves or resizes while the image is being read. Unassociated system panels and accessory-only applications are not selectable. diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index 74934d9654..6c3ba13175 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -114,7 +114,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 `typeText` 和 `pressKey` 面向所选进程当前获得焦点的控件,不指定窗口。`pressKey` 向目标 PID 依次发送修饰键和一个主键的按下事件,再逆序释放。操作中途取消也会逆序释放已按下的键。键盘事件直接发给目标进程,绕过全局 HID 队列。按键名由平台定义;KP_0 和 KP_Enter 等数字键盘名称保留物理键码。后台鼠标操作可能改变键盘焦点。文本逐个 Unicode 字符输入,不使用剪贴板。LF、CR 和 CRLF 发送一次 Return,制表符发送 Tab。应用保留缩进和焦点导航等正常编辑行为。`typeText` 的每次按下和抬起后等待配置的文本事件间隔;`pressKey` 使用自己的按下与释放节奏,分派完成不证明应用已消费全部事件。取消可能中断部分文本或手势,无法撤销已接收事件。很长的文本可能超过 Host 操作期限。继续输入前应核实应用状态。 -宿主为显式输入附上 `taskId`。`HeldInputs` 在派发前记录连接、任务、应用、原进程身份、键码或按钮、释放事件和实际输入方式。重复按键只保留一条记录。显式 up 使用保存的目标和输入方式;进程退出或 PID 身份变化后跳过定向释放。`getHeldInputs` 只报告请求连接和任务的记录,不读取用户物理按键状态。成功结束的程序用该快照生成提醒。程序失败、取消或销毁时,`releaseHeldInputs` 按派发顺序的反序统一释放键盘和鼠标记录。正常程序结束和回合结束不释放输入。`releaseHeldInputs` 返回已派发 up 的记录,用于确认后的清理提醒。连接关闭先等待原生操作停止,再兜底释放。完整击键、文本、点击和拖动保留操作内清理。 +`HeldInputs` 在派发前记录请求所属的连接、应用、原进程身份、键码或按钮、释放事件和实际输入方式。重复按键只保留一条记录。显式 up 使用保存的目标和输入方式;进程退出或 PID 身份变化后跳过定向释放。`getHeldInputs` 只报告当前连接的记录,不读取用户物理按键状态。成功结束的程序用该快照生成提醒。程序失败、取消或销毁时,`releaseHeldInputs` 按派发顺序的反序统一释放键盘和鼠标记录。正常程序结束和回合结束不释放输入。`releaseHeldInputs` 返回已派发 up 的记录,用于确认后的清理提醒。连接关闭先等待原生操作停止,再兜底释放。完整击键、文本、点击和拖动保留操作内清理。 所选 helper 应用需要 macOS 辅助功能权限以读取 AX 和输入,需要屏幕录制权限以截图。能力预检和权限错误不授予权限。截图会拒绝在读取图片期间移动或缩放的窗口。无法确认归属的系统面板及仅后台辅助类型的应用不可选择。 diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift index c1b30d8ac8..47a66d7552 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift @@ -218,7 +218,7 @@ actor AXWorker { var recovery = AXChildRecoveryBudget(maxElements: NativeProtocol.elementRange.upperBound, timeout: axTimeout) if method == "sendKeyEvent", try params.string("direction") == "up" { let handle = try params.string("appHandle") - let dispatched = try inputs().0.keyUp(params.string("key"), app: handle, task: params.string("taskId"), useSystemInput: params.optionalBoolean("useSystemInput") ?? false) { + let dispatched = try inputs().0.keyUp(params.string("key"), app: handle, useSystemInput: params.optionalBoolean("useSystemInput") ?? false) { try NativePlatform.requireUnlocked(observeSession()) try NativePlatform.requireAccessibility() return try ax().keyboardRecipient(validateIdentity(handle), catalog: catalog, budget: &recovery) @@ -361,7 +361,7 @@ actor AXWorker { maxElements: try params.integer("maxElements", in: NativeProtocol.elementRange), maxDepth: try params.integer("maxDepth", in: NativeProtocol.depthRange))) case "sendKeyEvent": let system = try params.optionalBoolean("useSystemInput") ?? false - try inputs().0.keyDown(params.string("key"), app: handle, task: params.string("taskId"), useSystemInput: system) { + try inputs().0.keyDown(params.string("key"), app: handle, useSystemInput: system) { if system { return identity } return try ax().keyboardRecipient(identity, catalog: catalog, budget: &recovery) } @@ -395,7 +395,7 @@ actor AXWorker { if try params.optionalBoolean("useSystemInput") == true { return .systemButtonDown(route, try WindowPointerInput.button(params.string("mouseButton"))) } - try await inputs().1.mouseDown(owner: .init(connection: connectionID, task: params.string("taskId"), app: handle), + try await inputs().1.mouseDown(owner: .init(connection: connectionID, app: handle), in: route, button: params.string("mouseButton")) case "click", "mouseMove": let useSystemInput = try params.optionalBoolean("useSystemInput") ?? false diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/HeldInputs.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/HeldInputs.swift index 5aac343a43..861dfb7f48 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/HeldInputs.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/HeldInputs.swift @@ -6,7 +6,6 @@ import Foundation final class HeldInputs: @unchecked Sendable { struct Owner: Equatable { let connection: UUID - let task: String let app: String } enum Mode: Equatable { @@ -42,10 +41,7 @@ final class HeldInputs: @unchecked Sendable { } private func conflict(_ name: String, holder: Owner, caller: Owner) -> NativeFailure { - let source: String - if holder.connection != caller.connection { source = "another session" } - else if holder.task != caller.task { source = "another task" } - else { source = "a different application handle" } + let source = holder.connection != caller.connection ? "another session" : "a different application handle" return RequestParameters.invalid("Key '\(name)' is held for this target by \(source). No event was sent. Wait for the holder to release it before using it.") } @@ -152,14 +148,14 @@ final class HeldInputs: @unchecked Sendable { func pointerUp(owner: Owner, window: UInt32, button: CGMouseButton) throws -> Bool { try lock.withLock { guard let index = pressed.firstIndex(where: { $0.owner == owner && $0.mode.pointer == button && $0.mode.window == window }) else { - throw RequestParameters.invalid("Release the mouse button through the same task, application and window that pressed it") + throw RequestParameters.invalid("Release the mouse button through the same connection, application and window that pressed it") } return try release(at: index) } } /// Create and post movement under the same lock as ownership and the saved release point. - func moveSystem(owner: Owner?, route: WindowRoute, screen: CGPoint, checkCancellation: () throws -> Void) throws { + func moveSystem(owner: Owner, route: WindowRoute, screen: CGPoint, checkCancellation: () throws -> Void) throws { try lock.withLock { let press = pressed.first { if case .systemPointer = $0.mode { return true }; return false } let event: CGEvent @@ -198,32 +194,31 @@ final class HeldInputs: @unchecked Sendable { } /// Only the caller's registered input is disclosed; physical user input is never inferred. - func held(connection: UUID, task: String) throws -> JSONValue { + func held(connection: UUID) throws -> JSONValue { try lock.withLock { for index in pressed.indices.reversed() { let press = pressed[index] - guard press.owner.connection == connection, press.owner.task == task else { continue } + guard press.owner.connection == connection else { continue } if press.mode.isSystem { continue } do { try NativePlatform.verify(press.recipient) } catch let error as NativeFailure where error.code == "STALE_APP" || error.code == "APP_UNAVAILABLE" { pressed.remove(at: index) } } - return .array(pressed.filter { $0.owner.connection == connection && $0.owner.task == task }.map { press in + return .array(pressed.filter { $0.owner.connection == connection }.map { press in record(press) }) } } @discardableResult - func release(connection: UUID, task: String? = nil) throws -> [JSONValue] { + func release(connection: UUID) throws -> [JSONValue] { try lock.withLock { var failures: [String] = [] var released: [JSONValue] = [] for index in pressed.indices.reversed() { let press = pressed[index] - let owner = press.owner - guard owner.connection == connection, task == nil || owner.task == task else { continue } + guard press.owner.connection == connection else { continue } do { if try release(at: index) { released.append(record(press)) } } catch { failures.append(String(describing: error)) } } diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift index 9458259846..8be9975889 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift @@ -30,8 +30,8 @@ final class KeyboardInput { else { postProcess(event, pid) } } - func keyDown(_ name: String, app: String, task: String, useSystemInput: Bool = false, recipient: () throws -> ProcessIdentity) throws { - let owner = HeldInputs.Owner(connection: connection, task: task, app: app) + func keyDown(_ name: String, app: String, useSystemInput: Bool = false, recipient: () throws -> ProcessIdentity) throws { + let owner = HeldInputs.Owner(connection: connection, app: app) let code = try Self.keyCode(name) let source = try Self.source(system: useSystemInput) let down = try Self.keyEvent(source: source, code: code, down: true, flags: []) @@ -49,8 +49,8 @@ final class KeyboardInput { }) } - func keyUp(_ name: String, app: String, task: String, useSystemInput: Bool = false, recipientIfUnheld: () throws -> ProcessIdentity) throws -> Bool { - try held.keyUp(owner: .init(connection: connection, task: task, app: app), name: name, code: Self.keyCode(name), system: useSystemInput, + func keyUp(_ name: String, app: String, useSystemInput: Bool = false, recipientIfUnheld: () throws -> ProcessIdentity) throws -> Bool { + try held.keyUp(owner: .init(connection: connection, app: app), name: name, code: Self.keyCode(name), system: useSystemInput, recipientIfUnheld: recipientIfUnheld) } diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift index 3af70c0847..bfab6c7adb 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift @@ -12,29 +12,29 @@ enum NativeProtocol { "getActionSchema": ["action"], "getApp": ["selector"], "getCapabilities": [], - "getHeldInputs": ["taskId"], + "getHeldInputs": [], "getState": ["appHandle", "details", "includeMenus", "maxDepth", "maxElements", "windowId"], "invoke": ["appHandle", "elementId", "snapshotId", "windowId"], "launchApp": ["appHandle"], "listActions": ["appHandle", "elementId", "snapshotId", "windowId"], "listApps": [], "listWindows": ["appHandle"], - "mouseMove": ["appHandle", "elementId", "snapshotId", "taskId", "useSystemInput", "windowId", "x", "y"], + "mouseMove": ["appHandle", "elementId", "snapshotId", "useSystemInput", "windowId", "x", "y"], "openPermissionSettings": ["permission", "settingsMessage"], "paste": ["appHandle", "format", "maxClipboardBytes", "maxDepth", "maxElements", "pasteReadTimeoutMs", "text", "windowId"], "performAction": ["action", "appHandle", "argument", "elementId", "snapshotId", "windowId"], "permissionStatus": [], "pressKey": ["appHandle", "key", "modifiers", "useSystemInput", "windowId"], - "releaseHeldInputs": ["taskId"], + "releaseHeldInputs": [], "requestPermission": ["backLabel", "finderLabel", "instruction", "permission", "pollIntervalMs", "settingsMessage", "unavailableMessage"], "screenshot": ["appHandle", "windowId"], "scroll": ["appHandle", "deltaLinesX", "deltaLinesY", "snapshotId", "windowId", "x", "y"], "selectText": ["appHandle", "elementId", "prefix", "selectionType", "snapshotId", "suffix", "text", "windowId"], - "sendKeyEvent": ["appHandle", "direction", "key", "taskId", "useSystemInput", "windowId"], + "sendKeyEvent": ["appHandle", "direction", "key", "useSystemInput", "windowId"], "setValue": ["appHandle", "elementId", "snapshotId", "value", "windowId"], "show": ["appHandle", "windowId"], "takeWindowActivity": ["appHandle", "observations"], - "toggleMouse": ["appHandle", "direction", "mouseButton", "taskId", "useSystemInput", "windowId"], + "toggleMouse": ["appHandle", "direction", "mouseButton", "useSystemInput", "windowId"], "typeText": ["appHandle", "text", "windowId"], ] static let stringEnums: [String: [String: Set]] = [ diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift index 657e9cb4ee..82103f609e 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift @@ -190,10 +190,10 @@ import Darwin let params = try RequestParameters(request) try cancellation.check() if request.method == "getHeldInputs" { - return try scheduler.heldInputs.held(connection: connectionID, task: params.string("taskId")) + return try scheduler.heldInputs.held(connection: connectionID) } if request.method == "releaseHeldInputs" { - return .array(try scheduler.heldInputs.release(connection: connectionID, task: params.string("taskId"))) + return .array(try scheduler.heldInputs.release(connection: connectionID)) } if request.method == "screenshot" { try capture.requireAvailable() } // A dispatched action can invalidate the snapshot that identifies its window. @@ -218,7 +218,7 @@ import Darwin let catalog = requiresCatalog ? ApplicationCatalog.snapshot() : ApplicationCatalogSnapshot(applications: [], frontPID: nil) let result: JSONValue if request.method == "toggleMouse", try params.string("direction") == "up" { - let dispatched = try scheduler.heldInputs.pointerUp(owner: .init(connection: connectionID, task: params.string("taskId"), + let dispatched = try scheduler.heldInputs.pointerUp(owner: .init(connection: connectionID, app: params.string("appHandle")), window: params.windowID(), button: WindowPointerInput.button(params.string("mouseButton"))) return .object(["dispatched": .bool(dispatched)]) } @@ -267,12 +267,11 @@ import Darwin case .foreground(let plan): result = try await performForeground(plan, requestID: request.id) case .mouseMove(let route, let point): let latch = cancellation - let owner: HeldInputs.Owner? = try params.contains("taskId") - ? .init(connection: connectionID, task: params.string("taskId"), app: params.string("appHandle")) : nil + let owner = HeldInputs.Owner(connection: connectionID, app: try params.string("appHandle")) try scheduler.systemPointer.move(owner: owner, in: route, at: point, checkCancellation: { try latch.check() }) result = AXWorker.mouseMoveResult(route: "system-pointer", pointerMoved: true) case .systemButtonDown(let route, let button): - try scheduler.systemPointer.down(owner: .init(connection: connectionID, task: params.string("taskId"), app: params.string("appHandle")), in: route, button: button, + try scheduler.systemPointer.down(owner: .init(connection: connectionID, app: params.string("appHandle")), in: route, button: button, checkCancellation: { try cancellation.check() }) result = AXWorker.actionResult case .paste(let plan): diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/SystemPointerInput.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/SystemPointerInput.swift index ff7437c300..598f6752c5 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/SystemPointerInput.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/SystemPointerInput.swift @@ -38,7 +38,7 @@ import Foundation try held.pointerDown(owner: owner, route: route, button: button, system: true, down: down, up: up, post: Self.post) } - func move(owner: HeldInputs.Owner?, in route: WindowRoute, at point: WindowPoint, checkCancellation: () throws -> Void) throws { + func move(owner: HeldInputs.Owner, in route: WindowRoute, at point: WindowPoint, checkCancellation: () throws -> Void) throws { try WindowPointerInput.validate(point, in: route) try WindowPointerInput.validateWindow(route) let screen = WindowPointerInput.screenPoint(point, in: route) diff --git a/packages/experimental/cua-macos/native/generate-protocol.ts b/packages/experimental/cua-macos/native/generate-protocol.ts index 7d7b228236..0a9ee3c049 100644 --- a/packages/experimental/cua-macos/native/generate-protocol.ts +++ b/packages/experimental/cua-macos/native/generate-protocol.ts @@ -15,22 +15,18 @@ export function renderNativeProtocol(): { json: string; swift: string } { maxElements: z.number().int().min(1).max(AX_TRAVERSAL_MAX.maxElements), maxDepth: z.number().int().min(1).max(AX_TRAVERSAL_MAX.maxDepth), } - const owner = { taskId: z.string().min(1) } const systemInput = { useSystemInput: z.boolean().optional() } const { fields, enums, json } = nativeProtocol({ getState: NativeResourceParameters.getState.extend(traversal), paste: NativeResourceParameters.paste.extend(traversal), - sendKeyEvent: z.object({ ...owner, ...systemInput }), + sendKeyEvent: z.object(systemInput), pressKey: z.object(systemInput), click: z.object(systemInput), - mouseMove: z.object({ ...systemInput, taskId: owner.taskId.optional() }), - toggleMouse: z.object({ ...systemInput, ...owner }), + mouseMove: z.object(systemInput), + toggleMouse: z.object(systemInput), drag: NativeResourceParameters.drag.extend(systemInput), requestPermission: PermissionGuideParameters, openPermissionSettings: PermissionSettingsParameters, }, [ - ...['getHeldInputs', 'releaseHeldInputs'].map(method => z.object({ - method: z.literal(method), params: z.object(owner).strict(), - }).strict()), z.object({ method: z.literal('takeWindowActivity'), params: z.object({ appHandle: z.string(), observations: z.record(z.string(), z.string().regex(/^[0-9]{1,20}$/)) }).strict() }).strict(), z.object({ method: z.literal('clearWindowActivity'), params: z.object({}).strict() }).strict(), diff --git a/packages/experimental/cua-macos/native/protocol.schema.json b/packages/experimental/cua-macos/native/protocol.schema.json index 47d482e65a..5312faf67b 100644 --- a/packages/experimental/cua-macos/native/protocol.schema.json +++ b/packages/experimental/cua-macos/native/protocol.schema.json @@ -520,18 +520,13 @@ }, "useSystemInput": { "type": "boolean" - }, - "taskId": { - "type": "string", - "minLength": 1 } }, "required": [ "appHandle", "windowId", "mouseButton", - "direction", - "taskId" + "direction" ], "additionalProperties": false } @@ -577,10 +572,6 @@ }, "useSystemInput": { "type": "boolean" - }, - "taskId": { - "type": "string", - "minLength": 1 } }, "required": [ @@ -615,10 +606,6 @@ }, "useSystemInput": { "type": "boolean" - }, - "taskId": { - "type": "string", - "minLength": 1 } }, "required": [ @@ -1150,10 +1137,6 @@ "up" ] }, - "taskId": { - "type": "string", - "minLength": 1 - }, "useSystemInput": { "type": "boolean" } @@ -1161,8 +1144,7 @@ "required": [ "appHandle", "key", - "direction", - "taskId" + "direction" ], "additionalProperties": false } @@ -1575,15 +1557,7 @@ }, "params": { "type": "object", - "properties": { - "taskId": { - "type": "string", - "minLength": 1 - } - }, - "required": [ - "taskId" - ], + "properties": {}, "additionalProperties": false } }, @@ -1606,15 +1580,7 @@ }, "params": { "type": "object", - "properties": { - "taskId": { - "type": "string", - "minLength": 1 - } - }, - "required": [ - "taskId" - ], + "properties": {}, "additionalProperties": false } }, diff --git a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py index 64b3ad0858..2b79ad4dd4 100644 --- a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py +++ b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py @@ -392,7 +392,7 @@ def check_system_input(helper, owner, state_file, executable): events = wait_for_state(state_file, lambda value: any(event["type"] == 11 for event in value["events"][count:]))["events"][count:] assert [(event["type"], event.get("keyCode")) for event in events] == [(10, 2), (11, 2)], events assert all(event["shift"] for event in events) and not any(keys().values()), events - held = {**owner, "key": "w", "taskId": "system-input-e2e", "useSystemInput": True} + held = {**owner, "key": "w", "useSystemInput": True} for cleanup in (False, True): count = len(json.loads(state_file.read_text())["events"]) call("sendKeyEvent", {**held, "direction": "down"}) @@ -403,7 +403,7 @@ def check_system_input(helper, owner, state_file, executable): assert down["systemW"], down finally: if cleanup: - call("releaseHeldInputs", {"taskId": held["taskId"]}) + call("releaseHeldInputs", {}) else: call("sendKeyEvent", {**held, "direction": "up"}) state = wait_for_state(state_file, lambda value: any( diff --git a/packages/experimental/cua-macos/native/tests/native_test_support.py b/packages/experimental/cua-macos/native/tests/native_test_support.py index dd067b434f..0e2f35846d 100644 --- a/packages/experimental/cua-macos/native/tests/native_test_support.py +++ b/packages/experimental/cua-macos/native/tests/native_test_support.py @@ -109,8 +109,6 @@ class NativeHelper: self.transcript = transcript def call(self, method, params, error_code=None): - if method in ("sendKeyEvent", "toggleMouse", "getHeldInputs", "releaseHeldInputs") or (method == "mouseMove" and params.get("useSystemInput")): - params = {**params, "taskId": "native-fixture"} self.sequence += 1 request = {"id": str(self.sequence), "method": method, "params": params} self.process.stdin.write(json.dumps(request) + "\n") diff --git a/packages/experimental/cua-macos/native/tests/shared_helper_e2e.py b/packages/experimental/cua-macos/native/tests/shared_helper_e2e.py index c85a499194..5f0550a0aa 100644 --- a/packages/experimental/cua-macos/native/tests/shared_helper_e2e.py +++ b/packages/experimental/cua-macos/native/tests/shared_helper_e2e.py @@ -55,8 +55,6 @@ class Connection: return value def call(self, method, params, error=None): - if method in ("sendKeyEvent", "toggleMouse", "getHeldInputs", "releaseHeldInputs") or (method == "mouseMove" and params.get("useSystemInput")): - params = {**params, "taskId": "native-fixture"} self.sequence += 1 identifier = str(self.sequence) self.send({"id": identifier, "method": method, "params": params}) @@ -301,6 +299,12 @@ def main(): assert b.call("listWindows", {"appHandle": app_b}) timed.close() clients.remove(timed) + a.call("sendKeyEvent", {"appHandle": app_a, "key": "w", "direction": "down"}) + assert b.call("getHeldInputs", {}) == [] + b.call("sendKeyEvent", {"appHandle": app_b, "key": "w", "direction": "up"}, error="INVALID_ARGUMENT") + assert b.call("releaseHeldInputs", {}) == [] + assert [entry["key"] for entry in a.call("getHeldInputs", {})] == ["w"] + b.call("sendKeyEvent", {"appHandle": app_b, "key": "d", "direction": "down"}) a.close() clients.remove(a) b.call("protocol-still-open", {}, error="UNSUPPORTED") @@ -308,6 +312,9 @@ def main(): if not args.without_desktop: assert b.call("listWindows", {"appHandle": app_b}) capture((b, app_b)) + assert [entry["key"] for entry in b.call("getHeldInputs", {})] == ["d"] + b.call("sendKeyEvent", {"appHandle": app_b, "key": "w", "direction": "down"}) + assert [entry["key"] for entry in b.call("releaseHeldInputs", {})] == ["w", "d"] b.close() clients.remove(b) if not args.without_desktop: diff --git a/packages/experimental/cua-macos/native/tests/swift/HeldInputTests.swift b/packages/experimental/cua-macos/native/tests/swift/HeldInputTests.swift index 771eedad96..58abbb9ddf 100644 --- a/packages/experimental/cua-macos/native/tests/swift/HeldInputTests.swift +++ b/packages/experimental/cua-macos/native/tests/swift/HeldInputTests.swift @@ -5,7 +5,6 @@ import Foundation import Testing @testable import CuaNative -private let task = "task" private func pointer(_ type: CGEventType) throws -> CGEvent { let event = try #require(CGEvent(mouseEventSource: nil, mouseType: type, mouseCursorPosition: .zero, mouseButton: .left)) @@ -18,7 +17,7 @@ func mixedInputsReleaseInDispatchOrder(_ system: Bool, _ systemKey: Bool) throws let held = HeldInputs() let connection = UUID() let target = try NativePlatform.identity(getpid()) - let owner = HeldInputs.Owner(connection: connection, task: task, app: "editor") + let owner = HeldInputs.Owner(connection: connection, app: "editor") let route = WindowRoute(owner: target, windowID: 7, bounds: .init(x: 0, y: 0, width: 100, height: 100)) var events: [String] = [] let keyboard = SystemKeyboardInput(post: { event in @@ -28,20 +27,20 @@ func mixedInputsReleaseInDispatchOrder(_ system: Bool, _ systemKey: Bool) throws #expect(pid == target.pid) events.append("key:\(event.getIntegerValueField(.keyboardEventKeycode)):\(event.type.rawValue)") }, textEventInterval: 0, held: held, connection: connection, system: keyboard) - try input.keyDown("shift", app: "editor", task: task, recipient: { target }) + try input.keyDown("shift", app: "editor", recipient: { target }) try held.pointerDown(owner: owner, route: route, button: .left, system: system, down: pointer(.leftMouseDown), up: pointer(.leftMouseUp), post: { events.append("mouse:\($0.type.rawValue)") }) - try input.keyDown("w", app: "editor", task: task, useSystemInput: systemKey, recipient: { target }) - let state = try held.held(connection: connection, task: task) + try input.keyDown("w", app: "editor", useSystemInput: systemKey, recipient: { target }) + let state = try held.held(connection: connection) #expect(state == .array([ .object(["kind": .string("key"), "key": .string("shift"), "appHandle": .string("editor"), "mode": .string("application")]), .object(["kind": .string("mouse"), "button": .string("left"), "appHandle": .string("editor"), "windowId": .string("7"), "mode": .string(system ? "system" : "window")]), .object(["kind": .string("key"), "key": .string("w"), "appHandle": .string("editor"), "mode": .string(systemKey ? "system" : "application")]), ])) - #expect(try held.held(connection: UUID(), task: task) == .array([])) - try held.release(connection: connection, task: task) - #expect(try held.held(connection: connection, task: task) == .array([])) - try held.release(connection: connection, task: task) + #expect(try held.held(connection: UUID()) == .array([])) + try held.release(connection: connection) + #expect(try held.held(connection: connection) == .array([])) + try held.release(connection: connection) let wRoute = systemKey ? "hid" : "key" #expect(events == ["key:56:12", "mouse:1", "\(wRoute):13:10", "\(wRoute):13:11", "mouse:2", "key:56:12"]) } @@ -53,35 +52,34 @@ func mixedInputsReleaseInDispatchOrder(_ system: Bool, _ systemKey: Bool) throws var events: [CGEvent] = [] let input = KeyboardInput(post: { event, _ in events.append(event) }, textEventInterval: 0, held: held, connection: connection) func changedFocus() throws -> ProcessIdentity { throw RequestParameters.invalid("Unexpected focus lookup") } - try input.keyDown("w", app: "editor", task: task, recipient: { target }) - try input.keyDown("w", app: "editor", task: task, recipient: changedFocus) - #expect(try input.keyUp("w", app: "editor", task: task, recipientIfUnheld: changedFocus)) - try input.keyDown("d", app: "editor", task: task, recipient: { target }) - try input.keyDown("w", app: "editor", task: task, recipient: { target }) - try held.release(connection: connection, task: task) + try input.keyDown("w", app: "editor", recipient: { target }) + try input.keyDown("w", app: "editor", recipient: changedFocus) + #expect(try input.keyUp("w", app: "editor", recipientIfUnheld: changedFocus)) + try input.keyDown("d", app: "editor", recipient: { target }) + try input.keyDown("w", app: "editor", recipient: { target }) + try held.release(connection: connection) #expect(events.map { $0.getIntegerValueField(.keyboardEventKeycode) } == [13, 13, 13, 2, 13, 13, 2]) #expect(events.map(\.type) == [.keyDown, .keyDown, .keyUp, .keyDown, .keyDown, .keyUp, .keyUp]) #expect(events.map { $0.getIntegerValueField(.keyboardEventAutorepeat) } == [0, 1, 0, 0, 0, 0, 0]) } -@Test func connectionsAndTasksCannotReleaseEachOthersInput() throws { +@Test func connectionsReleaseOnlyTheirOwnInput() throws { let held = HeldInputs() let a = UUID(), b = UUID() let target = try NativePlatform.identity(getpid()) - var events: [CGEventType] = [] - let input = KeyboardInput(post: { event, _ in events.append(event.type) }, textEventInterval: 0, held: held, connection: a) - let peer = KeyboardInput(post: { _, _ in Issue.record("Foreign connection posted input") }, textEventInterval: 0, held: held, connection: b) - try input.keyDown("w", app: "editor", task: task, recipient: { target }) - #expect(throws: NativeFailure.self) { try peer.keyDown("w", app: "editor", task: task, recipient: { target }) } - #expect(throws: NativeFailure.self) { try peer.keyUp("w", app: "editor", task: task, recipientIfUnheld: { target }) } - try held.release(connection: b) - #expect(events == [.keyDown]) - try held.release(connection: a, task: task) - try input.keyDown("w", app: "editor", task: "another-task", recipient: { target }) - try held.release(connection: a, task: task) - #expect(events == [.keyDown, .keyUp, .keyDown]) + var eventsA: [CGEventType] = [], eventsB: [CGEventType] = [] + let input = KeyboardInput(post: { event, _ in eventsA.append(event.type) }, textEventInterval: 0, held: held, connection: a) + let peer = KeyboardInput(post: { event, _ in eventsB.append(event.type) }, textEventInterval: 0, held: held, connection: b) + try input.keyDown("w", app: "editor", recipient: { target }) + #expect(try held.held(connection: b) == .array([])) + #expect(throws: NativeFailure.self) { try peer.keyDown("w", app: "editor", recipient: { target }) } + #expect(throws: NativeFailure.self) { try peer.keyUp("w", app: "editor", recipientIfUnheld: { target }) } + try peer.keyDown("d", app: "editor", recipient: { target }) try held.release(connection: a) - #expect(events == [.keyDown, .keyUp, .keyDown, .keyUp]) + #expect(eventsA == [.keyDown, .keyUp]) + #expect(eventsB == [.keyDown]) + #expect(try peer.keyUp("d", app: "editor", recipientIfUnheld: { target })) + #expect(eventsB == [.keyDown, .keyUp]) } @Test(arguments: [false, true]) @@ -90,7 +88,7 @@ func pointerReleaseUsesSavedRouteAfterWindowAndProcessChanges(_ system: Bool) th let target = try NativePlatform.identity(getpid()) // The current PID with a different start identity models a reused process identifier. let stale = ProcessIdentity(pid: target.pid, startedSeconds: target.startedSeconds + 1, startedMicroseconds: target.startedMicroseconds) - let owner = HeldInputs.Owner(connection: UUID(), task: task, app: "old-window") + let owner = HeldInputs.Owner(connection: UUID(), app: "old-window") let route = WindowRoute(owner: stale, windowID: 987654, bounds: .init(x: 0, y: 0, width: 100, height: 100)) var events: [CGEventType] = [] try held.pointerDown(owner: owner, route: route, button: .left, system: system, @@ -104,7 +102,7 @@ func pointerReleaseUsesSavedRouteAfterWindowAndProcessChanges(_ system: Bool) th let held = HeldInputs() let target = try NativePlatform.identity(getpid()) let route = WindowRoute(owner: target, windowID: 7, bounds: .init(x: 0, y: 0, width: 100, height: 100)) - let owner = HeldInputs.Owner(connection: UUID(), task: task, app: "editor") + let owner = HeldInputs.Owner(connection: UUID(), app: "editor") try held.pointerDown(owner: owner, route: route, button: .left, system: false, down: pointer(.leftMouseDown), up: pointer(.leftMouseUp), post: { _ in }) #expect(throws: NativeFailure.self) { try held.requirePointerAvailable(route: route, button: .left, system: false) } diff --git a/packages/experimental/cua-macos/native/tests/swift/SystemInputTests.swift b/packages/experimental/cua-macos/native/tests/swift/SystemInputTests.swift index 0f192c6f7e..e5e64b39f4 100644 --- a/packages/experimental/cua-macos/native/tests/swift/SystemInputTests.swift +++ b/packages/experimental/cua-macos/native/tests/swift/SystemInputTests.swift @@ -71,14 +71,14 @@ import Testing let held = HeldInputs() let connection = UUID() let keyboard = KeyboardInput(post: { _, _ in Issue.record("System key used process delivery") }, textEventInterval: 0, held: held, connection: connection, system: system) - try keyboard.keyDown("shift", app: "app", task: "task", useSystemInput: true, recipient: { target }) - #expect(throws: NativeFailure.self) { try keyboard.keyUp("shift", app: "app", task: "task", recipientIfUnheld: { target }) } + try keyboard.keyDown("shift", app: "app", useSystemInput: true, recipient: { target }) + #expect(throws: NativeFailure.self) { try keyboard.keyUp("shift", app: "app", recipientIfUnheld: { target }) } foreground = 99 - #expect(try keyboard.keyUp("shift", app: "app", task: "task", useSystemInput: true, recipientIfUnheld: { target })) + #expect(try keyboard.keyUp("shift", app: "app", useSystemInput: true, recipientIfUnheld: { target })) foreground = target.pid - try keyboard.keyDown("w", app: "app", task: "task", useSystemInput: true, recipient: { target }) + try keyboard.keyDown("w", app: "app", useSystemInput: true, recipient: { target }) foreground = 99 - try held.release(connection: connection, task: "task") + try held.release(connection: connection) #expect(events.map { $0.getIntegerValueField(.keyboardEventKeycode) } == [56, 56, 13, 13]) } @@ -97,12 +97,12 @@ import Testing var events: [CGEvent] = [] let system = SystemKeyboardInput(post: { events.append($0) }, keyState: { _ in false }, currentFlags: { ambient }, foreground: { target.pid }) let keyboard = KeyboardInput(post: { _, _ in Issue.record("System key used process delivery") }, textEventInterval: 0, held: held, connection: connection, system: system) - try keyboard.keyDown("w", app: "app", task: "task", useSystemInput: true, recipient: { target }) - try keyboard.keyDown("w", app: "app", task: "task", useSystemInput: true, recipient: { target }) - #expect(try keyboard.keyUp("w", app: "app", task: "task", useSystemInput: true, recipientIfUnheld: { target })) + try keyboard.keyDown("w", app: "app", useSystemInput: true, recipient: { target }) + try keyboard.keyDown("w", app: "app", useSystemInput: true, recipient: { target }) + #expect(try keyboard.keyUp("w", app: "app", useSystemInput: true, recipientIfUnheld: { target })) #expect(events.allSatisfy { $0.flags.contains(.maskAlternate) }) - try keyboard.keyDown("command", app: "app", task: "task", useSystemInput: true, recipient: { target }) + try keyboard.keyDown("command", app: "app", useSystemInput: true, recipient: { target }) ambient.formUnion(.maskCommand) - try held.release(connection: connection, task: "task") + try held.release(connection: connection) #expect(events.last?.flags == .maskAlternate) } diff --git a/packages/experimental/cua-macos/native/tests/test_ax_projection.py b/packages/experimental/cua-macos/native/tests/test_ax_projection.py index b882e51dfa..8b245a7cdb 100644 --- a/packages/experimental/cua-macos/native/tests/test_ax_projection.py +++ b/packages/experimental/cua-macos/native/tests/test_ax_projection.py @@ -49,7 +49,7 @@ def check_input(executable, helper_path, root): ("click", {**scoped, "x": 20, "y": 40}), ("typeText", {**owner, "text": "a"}), ("pressKey", {**owner, "key": "a"}), - ("sendKeyEvent", {**owner, "key": "a", "direction": "down", "taskId": "fixture"})]: + ("sendKeyEvent", {**owner, "key": "a", "direction": "down"})]: 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 diff --git a/packages/experimental/cua-macos/tests/protocol-generation.spec.ts b/packages/experimental/cua-macos/tests/protocol-generation.spec.ts index cca0ce3f93..4d5ca12cf2 100644 --- a/packages/experimental/cua-macos/tests/protocol-generation.spec.ts +++ b/packages/experimental/cua-macos/tests/protocol-generation.spec.ts @@ -12,6 +12,14 @@ describe('native protocol generation', () => { expect(await readFile(new URL('../native/Sources/CuaNative/NativeProtocol.generated.swift', import.meta.url), 'utf8')).toBe(generated.swift) }) + it('uses the requesting connection for held-input queries and cleanup', () => { + const validate = new Ajv2020().compile(JSON.parse(renderNativeProtocol().json)) + for (const method of ['getHeldInputs', 'releaseHeldInputs']) { + expect(validate({ id: 'held', method, params: {} })).toBe(true) + expect(validate({ id: 'foreign', method, params: { taskId: 'other' } })).toBe(false) + } + }) + it('resolves recursive JSON arguments in the complete native request schema', () => { const validate = new Ajv2020().compile(JSON.parse(renderNativeProtocol().json)) const target = { appHandle: 'app', snapshotId: 'snapshot', elementId: '0' } @@ -74,7 +82,8 @@ describe('native protocol generation', () => { { method: 'paste', params: { appHandle: 'app', text: 'text', pasteReadTimeoutMs: 1000 } }, { method: 'mouseMove', params: { appHandle: 'app', windowId: '1', x: 0, y: 0, allowSystemPointer: true } }, { method: 'findApps', params: { query: 'Editor', maxAppMatches: 1 } }, - { method: 'releaseHeldInputs', params: { taskId: 'task', turn: 1 } }, + { method: 'getHeldInputs', params: {} }, + { method: 'releaseHeldInputs', params: {} }, { method: 'takeWindowActivity', params: { appHandle: 'app', observations: { '7': '123' } } }, { method: 'clearWindowActivity', params: {} }, { method: 'launchApp', params: { appHandle: 'pending' } }, diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index 6760f27601..e7f8f09790 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -274,13 +274,13 @@ it('delivers window activity at the next accepted step and clears it at turn end expect(native.request).not.toHaveBeenCalled() }) -it('accepts task-owned directional input outside a turn', async () => { +it('accepts directional input on the Agent connection outside a turn', async () => { const f = await setup() await selectApplication(f) native.request.mockResolvedValueOnce({ dispatched: true }) const result = await f.execute('sendKeyEvent', { appHandle: 'app-one', key: 'w', direction: 'down' }) expect(result.isError).toBe(false) - expect(native.request).toHaveBeenLastCalledWith('sendKeyEvent', { appHandle: 'app-one', key: 'w', direction: 'down', taskId: f.handle.agent.id }, expect.any(AbortSignal), expect.any(String)) + expect(native.request).toHaveBeenLastCalledWith('sendKeyEvent', { appHandle: 'app-one', key: 'w', direction: 'down' }, expect.any(AbortSignal), expect.any(String)) }) it.each(PTC_MODES)('holds a key across $mode programs in the same turn', async (mode) => { @@ -291,7 +291,6 @@ it.each(PTC_MODES)('holds a key across $mode programs in the same turn', async ( native.request.mockClear().mockImplementation(async (method, params) => { if (method === 'getHeldInputs') return [...held].map(key => ({ kind: 'key', key, appHandle: 'app-one', mode: 'application' })) expect(method).toBe('sendKeyEvent') - expect(params).toMatchObject({ taskId: f.handle.agent.id }) const key = params.key if (typeof key !== 'string') throw new Error('The native fixture requires a key name') if (params.direction === 'down') held.add(key) @@ -1214,9 +1213,9 @@ it('requires an explicit system-pointer request on every move and asks only once [hoverTarget, false], [{ ...hoverTarget, useSystemInput: false }, false], [physicalHover, true], ] as const) { expect((await f.execute('mouseMove', params)).isError).toBe(false) - expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...hoverTarget, useSystemInput: physical, ...physical ? { taskId: f.handle.agent.id } : {} }, expect.any(AbortSignal), expect.any(String)) + expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...hoverTarget, useSystemInput: physical }, expect.any(AbortSignal), expect.any(String)) } - expect(native.request.mock.calls[1]?.[1]).toEqual({ ...physicalHover, taskId: f.handle.agent.id }) + expect(native.request.mock.calls[1]?.[1]).toEqual(physicalHover) expect(f.ask).toHaveBeenCalledTimes(1) }) @@ -1225,7 +1224,7 @@ it.each([true, false])('shares the system input decision for a system button wit const target = { appHandle: 'app-one', windowId: '7', mouseButton: 'left', direction: 'down' } for (const params of [target, { ...target, useSystemInput: false }]) { expect((await f.execute('toggleMouse', params)).isError).toBe(false) - expect(native.request.mock.lastCall?.[1]).toEqual({ ...target, taskId: f.handle.agent.id }) + expect(native.request.mock.lastCall?.[1]).toEqual(target) } expect(f.ask).not.toHaveBeenCalled() const answer = Promise.withResolvers() @@ -1246,7 +1245,7 @@ it.each([true, false])('shares the system input decision for a system button wit .toEqual([['toggleMouse', true], ['mouseMove', true], ['toggleMouse', undefined]]) f.handle.agent.cancel({ kind: 'user' }) await f.handle.agent.whenIdle() - expect(native.cleanup).toHaveBeenCalledWith('releaseHeldInputs', { taskId: f.handle.agent.id }) + expect(native.cleanup).toHaveBeenCalledWith('releaseHeldInputs', {}) } else { for (const result of results.slice(0, 2)) expect(JSON.stringify(result.content)).toContain('SYSTEM_INPUT_DENIED') expect(results[2]?.isError).toBe(false) @@ -1294,7 +1293,7 @@ it('keeps refusals and grants separate and forgets a closed session on reopen', expect((await f.call(agent, 'mouseMove', hoverTarget)).isError).toBe(false) expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...hoverTarget, useSystemInput: false }, expect.any(AbortSignal), expect.any(String)) expect((await f.execute('mouseMove', physicalHover)).isError).toBe(false) - expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...physicalHover, taskId: f.handle.agent.id }, expect.any(AbortSignal), expect.any(String)) + expect(native.request).toHaveBeenLastCalledWith('mouseMove', physicalHover, expect.any(AbortSignal), expect.any(String)) const sessionId = f.handle.agent.id await f.handle.dispose() const reopened = await f.ctx.agents.create({ sessionId }) @@ -1354,7 +1353,7 @@ it('allows only the explicitly requested physical move when approval is disabled const f = await hoverFixture(false) for (const [target, expected] of [[hoverTarget, false], [physicalHover, true], [hoverTarget, false]] as const) { expect((await f.execute('mouseMove', target)).isError).toBe(false) - expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...hoverTarget, useSystemInput: expected, ...expected ? { taskId: f.handle.agent.id } : {} }, expect.any(AbortSignal), expect.any(String)) + expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...hoverTarget, useSystemInput: expected }, expect.any(AbortSignal), expect.any(String)) } expect(f.ask).not.toHaveBeenCalled() }) @@ -1423,7 +1422,7 @@ it('keeps complete system moves available outside a turn without registering a p await selectApplication(f) native.request.mockClear() expect((await f.execute('mouseMove', physicalHover)).isError).toBe(false) - expect(native.request).toHaveBeenCalledExactlyOnceWith('mouseMove', { ...physicalHover, taskId: f.handle.agent.id }, expect.any(AbortSignal), expect.any(String)) + expect(native.request).toHaveBeenCalledExactlyOnceWith('mouseMove', physicalHover, expect.any(AbortSignal), expect.any(String)) await f.handle.dispose() expect(native.cleanup).not.toHaveBeenCalled() }) diff --git a/packages/experimental/cua-windows/README.i18n.yaml b/packages/experimental/cua-windows/README.i18n.yaml index 01777fdeb8..113cccc1f8 100644 --- a/packages/experimental/cua-windows/README.i18n.yaml +++ b/packages/experimental/cua-windows/README.i18n.yaml @@ -36,8 +36,8 @@ en: 38b3250d6ae0f3d6 zh: 33d056c416e11d75 /deepseek-ai-dsh-cua-windows/model-experience/explicit-application-and-window-operations/what-the-model-sees: - en: 81af5b1e782d3290 - zh: db72fcd496fd44e4 + en: bf6f99c4c1fafe72 + zh: 791930be8c5f80f4 /deepseek-ai-dsh-cua-windows/model-experience/explicit-application-and-window-operations/token-effect: en: 39eebd53ee226af7 zh: ba7b352cf1e23c3c diff --git a/packages/experimental/cua-windows/README.md b/packages/experimental/cua-windows/README.md index 7839f0934a..073e9d4056 100644 --- a/packages/experimental/cua-windows/README.md +++ b/packages/experimental/cua-windows/README.md @@ -65,7 +65,7 @@ Each result contains `id`, `displayName`, and `isRunning`. The ID is an AUMID, i #### What the model sees -The program receives application and window identifiers, observations, and action results. Selection alone does not provide an accessibility tree. After a successful program, a reminder lists any held keys and buttons with their window and desktop input mode. Program failure, cancellation, reset and disconnect release owned input in reverse order. +The program receives application and window identifiers, observations, and action results. Selection alone does not provide an accessibility tree. After a successful program, a reminder lists any held keys and buttons with their window and desktop input mode. Program failure, cancellation, reset and disconnect release the input held by that connection in reverse dispatch order. #### Token effect diff --git a/packages/experimental/cua-windows/README.zh.md b/packages/experimental/cua-windows/README.zh.md index 49c1558534..a84c963e1a 100644 --- a/packages/experimental/cua-windows/README.zh.md +++ b/packages/experimental/cua-windows/README.zh.md @@ -65,7 +65,7 @@ kind: "package-reference" #### 模型看到什么 -程序可以读取应用和窗口标识、观察结果及动作结果。仅执行选择操作不会提供辅助功能树。程序成功后,提醒会列出仍按住的键和鼠标按钮、所属窗口和桌面输入方式。程序异常、取消、重置和断连时,按派发顺序反序释放任务持有的输入。 +程序可以读取应用和窗口标识、观察结果及动作结果。仅执行选择操作不会提供辅助功能树。程序成功后,提醒会列出仍按住的键和鼠标按钮、所属窗口和桌面输入方式。程序异常、取消、重置和断连时,按派发顺序的反序释放这条连接持有的输入。 #### Token 影响 diff --git a/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs b/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs index e553283013..68b5c07029 100644 --- a/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs +++ b/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs @@ -86,20 +86,19 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA if (request.Method == "getActionSchema") return PatternActions.Schema(String(parameters, "action")); if (request.Method is "requestPermission" or "openPermissionSettings") throw new NativeFailure("UNSUPPORTED", "Windows desktop access has no macOS permission switches; inspect the Windows session status"); - if (request.Method == "getHeldInputs") return inputs.Get(state.Connection, String(parameters, "taskId")); + if (request.Method == "getHeldInputs") return inputs.Get(state.Connection); if (request.Method == "releaseHeldInputs") - return inputs.Release(state.Connection, String(parameters, "taskId"), cancellation); + return inputs.Release(state.Connection, cancellation); if (request.Method is "sendKeyEvent" or "toggleMouse" && String(parameters, "direction") == "up") { var window = WindowId(parameters) ?? throw new NativeFailure("INVALID_ARGUMENT", "Release through the original window"); - var task = String(parameters, "taskId"); var recipient = String(parameters, "appHandle"); var before = Win32.GetForegroundWindow(); if (request.Method == "sendKeyEvent") - Input.ReleaseKey(state.Connection, task, recipient, window, String(parameters, "key"), context); + Input.ReleaseKey(state.Connection, recipient, window, String(parameters, "key"), context); else - Input.ReleaseButton(state.Connection, task, recipient, window, String(parameters, "mouseButton"), context); + Input.ReleaseButton(state.Connection, recipient, window, String(parameters, "mouseButton"), context); return ActionResult(before); } DesktopSession.RequireInteractive(); @@ -116,7 +115,7 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA var app = state.App(String(parameters, "appHandle")); var foreground = Win32.GetForegroundWindow(); if (request.Method is "sendKeyEvent" or "toggleMouse" or "pressKey" or "typeText" or "paste" or "mouseMove" or "scroll" or "drag" or "click") - inputs.RequireOwner(state.Connection, OptionalString(parameters, "taskId"), app.Handle, WindowId(parameters) ?? 0); + inputs.RequireOwner(state.Connection, app.Handle, WindowId(parameters) ?? 0); switch (request.Method) { case "launchApp": @@ -163,7 +162,7 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA case "sendKeyEvent": { var target = Selected(app, parameters, context); - var dispatched = Input.KeyDown(state.Connection, String(parameters, "taskId"), app, target, String(parameters, "key"), context); + var dispatched = Input.KeyDown(state.Connection, app, target, String(parameters, "key"), context); return ActionResult(foreground, dispatched); } case "paste": @@ -194,7 +193,7 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA case "toggleMouse": { var target = Selected(app, parameters, context); - var dispatched = Input.ButtonDown(state.Connection, String(parameters, "taskId"), app, target, String(parameters, "mouseButton"), context); + var dispatched = Input.ButtonDown(state.Connection, app, target, String(parameters, "mouseButton"), context); return ActionResult(foreground, dispatched); } case "scroll": @@ -304,7 +303,7 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA if (!inputs.HasConnection(state.Connection)) return; using var deadline = new CancellationTokenSource(graceMs); await queue.WaitAsync(deadline.Token); - try { inputs.Release(state.Connection, null, deadline.Token); } + try { inputs.Release(state.Connection, deadline.Token); } finally { queue.Release(); } } diff --git a/packages/experimental/cua-windows/native/entry/HeldInputs.cs b/packages/experimental/cua-windows/native/entry/HeldInputs.cs index 47267898b5..4217bcb21a 100644 --- a/packages/experimental/cua-windows/native/entry/HeldInputs.cs +++ b/packages/experimental/cua-windows/native/entry/HeldInputs.cs @@ -7,7 +7,7 @@ namespace DeepSeek.Cua.Windows; internal sealed class HeldInputs(Action send, Action requireInteractive) { internal readonly record struct Target(string AppHandle, nint Window, int ProcessId, long ProcessStarted); - private sealed record Press(Guid Connection, string Task, Target Target, ushort Control, string Name, Win32.Input Up) + private sealed record Press(Guid Connection, Target Target, ushort Control, string Name, Win32.Input Up) { internal object Describe() => new { @@ -20,13 +20,12 @@ internal sealed class HeldInputs(Action send, Action requireInterac private readonly object gate = new(); private readonly List pressed = []; - internal void RequireOwner(Guid connection, string? task, string app, nint window) + internal void RequireOwner(Guid connection, string app, nint window) { lock (gate) if (pressed.Any(press => press.Connection != connection - || (task is not null && press.Task != task) || press.Target.AppHandle != app || press.Target.Window != window)) - throw new NativeFailure("INPUT_BUSY", "Another task or window owns held desktop input; release it before sending input to this window"); + throw new NativeFailure("INPUT_BUSY", "Another connection or window owns held desktop input; release it before sending input to this window"); } internal void RequireAvailable(ushort control) @@ -36,7 +35,7 @@ internal sealed class HeldInputs(Action send, Action requireInterac throw new NativeFailure("INPUT_BUSY", "This key or button is already held; release it before a complete action uses it"); } - internal bool Down(Guid connection, string task, Target target, ushort control, string name, Win32.Input down, + internal bool Down(Guid connection, Target target, ushort control, string name, Win32.Input down, Win32.Input up, CancellationToken cancellation) { lock (gate) @@ -45,12 +44,12 @@ internal sealed class HeldInputs(Action send, Action requireInterac var existing = pressed.Find(press => press.Control == control); if (existing is not null) { - if (existing.Connection == connection && existing.Task == task && existing.Target == target && existing.Name == name) + if (existing.Connection == connection && existing.Target == target && existing.Name == name) return false; throw new NativeFailure("INPUT_BUSY", "This key or button is already held by another input target"); } - var press = new Press(connection, task, target, control, name, up); + var press = new Press(connection, target, control, name, up); pressed.Add(press); try { send(down); } catch (NativeFailure error) when (error.Code == "INPUT_BLOCKED") @@ -63,21 +62,21 @@ internal sealed class HeldInputs(Action send, Action requireInterac } } - internal void Up(Guid connection, string task, string app, nint window, string name, bool keyboard) + internal void Up(Guid connection, string app, nint window, string name, bool keyboard) { lock (gate) { - var index = pressed.FindIndex(press => press.Connection == connection && press.Task == task && press.Target.AppHandle == app + var index = pressed.FindIndex(press => press.Connection == connection && press.Target.AppHandle == app && press.Target.Window == window && press.Name == name && (press.Up.Type == 1) == keyboard); - if (index < 0) throw new NativeFailure("INPUT_NOT_HELD", "This task did not hold that input on the selected window"); + if (index < 0) throw new NativeFailure("INPUT_NOT_HELD", "This connection did not hold that input on the selected window"); ReleaseAt(index); } } - internal object[] Get(Guid connection, string task) + internal object[] Get(Guid connection) { lock (gate) - return pressed.Where(press => press.Connection == connection && press.Task == task).Select(press => press.Describe()).ToArray(); + return pressed.Where(press => press.Connection == connection).Select(press => press.Describe()).ToArray(); } internal bool HasConnection(Guid connection) @@ -85,7 +84,7 @@ internal sealed class HeldInputs(Action send, Action requireInterac lock (gate) return pressed.Exists(press => press.Connection == connection); } - internal object[] Release(Guid connection, string? task, CancellationToken cancellation) + internal object[] Release(Guid connection, CancellationToken cancellation) { lock (gate) { @@ -94,7 +93,7 @@ internal sealed class HeldInputs(Action send, Action requireInterac for (var index = pressed.Count - 1; index >= 0; index--) { var press = pressed[index]; - if (press.Connection != connection || (task is not null && press.Task != task)) continue; + if (press.Connection != connection) continue; cancellation.ThrowIfCancellationRequested(); try { ReleaseAt(index); released.Add(press.Describe()); } catch (NativeFailure error) { failures.Add(error.Message); } diff --git a/packages/experimental/cua-windows/native/entry/Input.cs b/packages/experimental/cua-windows/native/entry/Input.cs index 36fc33b79d..adfcc4e600 100644 --- a/packages/experimental/cua-windows/native/entry/Input.cs +++ b/packages/experimental/cua-windows/native/entry/Input.cs @@ -104,10 +104,10 @@ internal static class Input var key => key, }; - internal static void ReleaseKey(Guid connection, string task, string app, nint window, string name, RequestContext context) - => context.HeldInputs.Up(connection, task, app, window, HoldKeyName(name), true); + internal static void ReleaseKey(Guid connection, string app, nint window, string name, RequestContext context) + => context.HeldInputs.Up(connection, app, window, HoldKeyName(name), true); - internal static bool KeyDown(Guid connection, string task, AppState app, WindowState window, string name, RequestContext context) + internal static bool KeyDown(Guid connection, AppState app, WindowState window, string name, RequestContext context) { Windows.RequireForeground(app, window, context); name = HoldKeyName(name); @@ -115,7 +115,7 @@ internal static class Input if (key.Modifiers.Length != 0) throw new NativeFailure("UNSUPPORTED", "This key requires modifiers in the target keyboard layout; send each modifier and the base key separately"); var flags = key.Extended ? 1u : 0; - return context.HeldInputs.Down(connection, task, new(app.Handle, window.Id, window.ProcessId, window.ProcessStarted), + return context.HeldInputs.Down(connection, new(app.Handle, window.Id, window.ProcessId, window.ProcessStarted), key.Key, name, Keyboard(key.Key, flags: flags), Keyboard(key.Key, flags: flags | 2), context.Cancellation); } @@ -187,15 +187,15 @@ internal static class Input return new { dispatched = true, hoverRoute = "system-pointer", systemPointerMoved = before.X != point.X || before.Y != point.Y }; } - internal static void ReleaseButton(Guid connection, string task, string app, nint window, string button, RequestContext context) - => context.HeldInputs.Up(connection, task, app, window, button, false); + internal static void ReleaseButton(Guid connection, string app, nint window, string button, RequestContext context) + => context.HeldInputs.Up(connection, app, window, button, false); - internal static bool ButtonDown(Guid connection, string task, AppState app, WindowState window, string button, RequestContext context) + internal static bool ButtonDown(Guid connection, AppState app, WindowState window, string button, RequestContext context) { var flags = Button(button); if (!Win32.GetCursorPos(out var point)) throw new NativeFailure("INPUT_UNAVAILABLE", "The current pointer position is unavailable"); Hit(app, window, point, context); - return context.HeldInputs.Down(connection, task, new(app.Handle, window.Id, window.ProcessId, window.ProcessStarted), + return context.HeldInputs.Down(connection, new(app.Handle, window.Id, window.ProcessId, window.ProcessStarted), flags.Control, button, Mouse(flags.Down), Mouse(flags.Up), context.Cancellation); } diff --git a/packages/experimental/cua-windows/native/generate-protocol.ts b/packages/experimental/cua-windows/native/generate-protocol.ts index 9183594c68..3a23f8140f 100644 --- a/packages/experimental/cua-windows/native/generate-protocol.ts +++ b/packages/experimental/cua-windows/native/generate-protocol.ts @@ -1,16 +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' -import { z } from 'zod' const path = new URL('protocol.schema.json', import.meta.url) -const owner = z.object({ taskId: z.string().min(1) }).strict() -const content = nativeProtocol({ - sendKeyEvent: owner, - toggleMouse: owner, -}, ['getHeldInputs', 'releaseHeldInputs'].map(method => z.object({ - method: z.literal(method), params: owner, -}).strict())).json +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/protocol.schema.json b/packages/experimental/cua-windows/native/protocol.schema.json index 485ba9c5ed..a0f3e7e40e 100644 --- a/packages/experimental/cua-windows/native/protocol.schema.json +++ b/packages/experimental/cua-windows/native/protocol.schema.json @@ -517,18 +517,13 @@ "down", "up" ] - }, - "taskId": { - "type": "string", - "minLength": 1 } }, "required": [ "appHandle", "windowId", "mouseButton", - "direction", - "taskId" + "direction" ], "additionalProperties": false } @@ -1123,17 +1118,12 @@ "down", "up" ] - }, - "taskId": { - "type": "string", - "minLength": 1 } }, "required": [ "appHandle", "key", - "direction", - "taskId" + "direction" ], "additionalProperties": false } @@ -1507,15 +1497,7 @@ }, "params": { "type": "object", - "properties": { - "taskId": { - "type": "string", - "minLength": 1 - } - }, - "required": [ - "taskId" - ], + "properties": {}, "additionalProperties": false } }, @@ -1538,15 +1520,7 @@ }, "params": { "type": "object", - "properties": { - "taskId": { - "type": "string", - "minLength": 1 - } - }, - "required": [ - "taskId" - ], + "properties": {}, "additionalProperties": false } }, diff --git a/packages/experimental/cua-windows/native/tests/HeldInputChecks.cs b/packages/experimental/cua-windows/native/tests/HeldInputChecks.cs index a805c24a81..1ed3d7b495 100644 --- a/packages/experimental/cua-windows/native/tests/HeldInputChecks.cs +++ b/packages/experimental/cua-windows/native/tests/HeldInputChecks.cs @@ -26,61 +26,61 @@ internal static class HeldInputChecks if (!interactive) throw new NativeFailure("SESSION_LOCKED", "The interactive desktop is unavailable"); }); - bool Key(Guid connection, string task, ushort key, string name, CancellationToken cancellation = default) - => inputs.Down(connection, task, target, key, name, + bool Key(Guid connection, ushort key, string name, CancellationToken cancellation = default) + => inputs.Down(connection, target, key, name, new() { Type = 1, Data = new() { Keyboard = new() { Key = key } } }, new() { Type = 1, Data = new() { Keyboard = new() { Key = key, Flags = 2 } } }, cancellation); - refuses(() => inputs.Up(a, "task", "app", 72, "shift", true), "INPUT_NOT_HELD"); + refuses(() => inputs.Up(a, "app", 72, "shift", true), "INPUT_NOT_HELD"); check(events.Count == 0, "No up is sent for a key the helper never pressed"); blocked = true; - refuses(() => Key(a, "task", 16, "shift"), "INPUT_BLOCKED"); - check(inputs.Get(a, "task").Length == 0, "A refused down does not cause an up"); + refuses(() => Key(a, 16, "shift"), "INPUT_BLOCKED"); + check(inputs.Get(a).Length == 0, "A refused down does not cause an up"); blocked = false; - check(Key(a, "task", 16, "shift"), "Record the accepted keyboard down"); - check(inputs.Down(a, "task", target, 1, "left", + check(Key(a, 16, "shift"), "Record the accepted keyboard down"); + check(inputs.Down(a, target, 1, "left", new() { Data = new() { Mouse = new() { Flags = 2 } } }, new() { Data = new() { Mouse = new() { Flags = 4 } } }, default), "Record the accepted mouse down"); - check(Key(a, "task", 87, "w") && !Key(a, "task", 87, "w"), "A repeated key does not duplicate a hold"); - refuses(() => inputs.RequireOwner(b, "task", "app", 72), "INPUT_BUSY"); - refuses(() => inputs.RequireOwner(a, "other", "app", 72), "INPUT_BUSY"); + check(Key(a, 87, "w") && !Key(a, 87, "w"), "A repeated key does not duplicate a hold"); + refuses(() => inputs.RequireOwner(b, "app", 72), "INPUT_BUSY"); + refuses(() => inputs.RequireOwner(a, "app", 73), "INPUT_BUSY"); refuses(() => inputs.RequireAvailable(1), "INPUT_BUSY"); - refuses(() => inputs.Up(a, "other", "app", 72, "w", true), "INPUT_NOT_HELD"); - refuses(() => inputs.Up(a, "task", "app", 73, "w", true), "INPUT_NOT_HELD"); - check(inputs.Release(b, null, default).Length == 0, "Another connection releases nothing"); - check(inputs.Get(a, "other").Length == 0 && inputs.Get(a, "task").Length == 3, "State query is task-scoped"); - var described = JsonSerializer.SerializeToElement(inputs.Get(a, "task"), WireJson.Options); + refuses(() => inputs.Up(b, "app", 72, "w", true), "INPUT_NOT_HELD"); + refuses(() => inputs.Up(a, "app", 73, "w", true), "INPUT_NOT_HELD"); + check(inputs.Release(b, default).Length == 0, "Another connection releases nothing"); + check(inputs.Get(b).Length == 0 && inputs.Get(a).Length == 3, "State query is connection-scoped"); + var described = JsonSerializer.SerializeToElement(inputs.Get(a), WireJson.Options); check(described[0].GetProperty("windowId").GetString() == "72" && described[0].GetProperty("mode").GetString() == "system", "Keyboard reminders identify the window and actual desktop mode"); - inputs.Up(a, "task", "app", 72, "shift", true); - check(Key(a, "task", 16, "shift"), "Explicit up and repress update the dispatch order"); - check(inputs.Release(a, "task", default).Length == 3 + inputs.Up(a, "app", 72, "shift", true); + check(Key(a, 16, "shift"), "Explicit up and repress update the dispatch order"); + check(inputs.Release(a, default).Length == 3 && events.TakeLast(3).SequenceEqual(["16:up", "87:up", "1:up"]), "Release in mixed reverse order, including repress"); - check(inputs.Release(a, null, default).Length == 0, "Duplicate connection cleanup sends no up"); + check(inputs.Release(a, default).Length == 0, "Duplicate connection cleanup sends no up"); using (var cancelled = new CancellationTokenSource()) { cancelled.Cancel(); - try { Key(a, "task", 87, "w", cancelled.Token); throw new Exception("Expected cancelled down"); } - catch (OperationCanceledException) { check(inputs.Get(a, "task").Length == 0, "Cancelled down never dispatches"); } + try { Key(a, 87, "w", cancelled.Token); throw new Exception("Expected cancelled down"); } + catch (OperationCanceledException) { check(inputs.Get(a).Length == 0, "Cancelled down never dispatches"); } } - Key(a, "task", 87, "w"); + Key(a, 87, "w"); interactive = false; - refuses(() => inputs.Release(a, null, default), "INPUT_CLEANUP_FAILED"); - check(inputs.Get(a, "task").Length == 1, "A locked desktop leaves the failed release recorded"); + refuses(() => inputs.Release(a, default), "INPUT_CLEANUP_FAILED"); + check(inputs.Get(a).Length == 1, "A locked desktop leaves the failed release recorded"); interactive = true; blocked = true; - refuses(() => inputs.Release(a, null, default), "INPUT_CLEANUP_FAILED"); - check(inputs.Get(a, "task").Length == 1, "A refused release stays recorded for disconnect fallback"); + refuses(() => inputs.Release(a, default), "INPUT_CLEANUP_FAILED"); + check(inputs.Get(a).Length == 1, "A refused release stays recorded for disconnect fallback"); blocked = false; // Another source releases W and presses D at the same receiver. Receive(new() { Type = 1, Data = new() { Keyboard = new() { Key = 87, Flags = 2 } } }); Receive(new() { Type = 1, Data = new() { Keyboard = new() { Key = 68 } } }); - described = JsonSerializer.SerializeToElement(inputs.Get(a, "task"), WireJson.Options); + described = JsonSerializer.SerializeToElement(inputs.Get(a), WireJson.Options); check(described.GetArrayLength() == 1 && described[0].GetProperty("key").GetString() == "w", "The reminder still reports only the helper's W down"); var count = events.Count; - check(inputs.Release(a, null, default).Length == 1 && events.Skip(count).SequenceEqual(["87:up"]), + check(inputs.Release(a, default).Length == 1 && events.Skip(count).SequenceEqual(["87:up"]), "Disconnect retries the helper's W release and leaves D alone"); check(!inputs.HasConnection(a), "Accepted release removes the connection's last hold"); } diff --git a/packages/experimental/cua-windows/native/tests/Program.cs b/packages/experimental/cua-windows/native/tests/Program.cs index 72c0d0c32a..15c4d3bb2a 100644 --- a/packages/experimental/cua-windows/native/tests/Program.cs +++ b/packages/experimental/cua-windows/native/tests/Program.cs @@ -66,7 +66,7 @@ foreach (var direction in new[] { "down", "up" }) { var toggle = NativeRequest.Parse(WireJson.Parse(System.Text.Json.JsonSerializer.Serialize(new { - id = "mouse", method = "toggleMouse", @params = new { appHandle = "app", windowId = "1", taskId = "task", mouseButton, direction }, + id = "mouse", method = "toggleMouse", @params = new { appHandle = "app", windowId = "1", mouseButton, direction }, }))); Check(toggle.Params.GetProperty("mouseButton").GetString() == mouseButton && toggle.Params.GetProperty("direction").GetString() == direction, @@ -75,22 +75,20 @@ foreach (var direction in new[] { "down", "up" }) foreach (var invalid in new[] { """{"appHandle":"app","windowId":"1","mouseButton":"left","direction":"down"}""", - """{"appHandle":"app","taskId":"task","windowId":"1","mouseButton":"left"}""", - """{"appHandle":"app","taskId":"task","windowId":"1","direction":"down"}""", - """{"appHandle":"app","taskId":"task","mouseButton":"left","direction":"down"}""", - """{"appHandle":"app","taskId":"task","windowId":"1","mouseButton":"back","direction":"down"}""", - """{"appHandle":"app","taskId":"task","windowId":"1","mouseButton":"left","direction":"press"}""", - """{"appHandle":"app","taskId":"task","windowId":"1","mouseButton":"left","direction":"down","x":1,"y":2}""", + """{"appHandle":"app","windowId":"1","mouseButton":"left"}""", + """{"appHandle":"app","windowId":"1","direction":"down"}""", + """{"appHandle":"app","mouseButton":"left","direction":"down"}""", + """{"appHandle":"app","windowId":"1","mouseButton":"back","direction":"down"}""", + """{"appHandle":"app","windowId":"1","mouseButton":"left","direction":"press"}""", + """{"appHandle":"app","windowId":"1","mouseButton":"left","direction":"down","x":1,"y":2}""", }) Refuses(() => NativeRequest.Parse(WireJson.Parse("{\"id\":\"mouse\",\"method\":\"toggleMouse\",\"params\":" + invalid + "}")), "INVALID_ARGUMENT"); foreach (var method in new[] { "getHeldInputs", "releaseHeldInputs" }) { - var query = $$$"""{"id":"holds","method":"{{{method}}}","params":{"taskId":"a"}}"""; - Check(NativeRequest.Parse(WireJson.Parse(query)).Params.GetProperty("taskId").GetString() == "a", - "Private held-input operations accept only the task owner"); - Refuses(() => NativeRequest.Parse(WireJson.Parse($$$"""{"id":"holds","method":"{{{method}}}","params":{}}""")), "INVALID_ARGUMENT"); - Refuses(() => NativeRequest.Parse(WireJson.Parse($$$"""{"id":"holds","method":"{{{method}}}","params":{"taskId":"a","appHandle":"app"}}""")), "INVALID_ARGUMENT"); + var query = $$$"""{"id":"holds","method":"{{{method}}}","params":{}}"""; + Check(NativeRequest.Parse(WireJson.Parse(query)).Method == method, "Held-input operations use the requesting connection"); + Refuses(() => NativeRequest.Parse(WireJson.Parse($$$"""{"id":"holds","method":"{{{method}}}","params":{"taskId":"other"}}""")), "INVALID_ARGUMENT"); } HeldInputChecks.Run(Check, Refuses); diff --git a/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts b/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts index 1c6d99ca7a..78e2bbecd2 100644 --- a/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts +++ b/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts @@ -104,7 +104,7 @@ it.skipIf(process.platform !== 'win32' || !helperPath || !fixturePath)( const windowId = initial.state.window expect(windows.some(window => window.windowId === windowId)).toBe(true) const toggle = async (mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') => - ToggleResult.parse(await native.request('toggleMouse', { appHandle: app.appHandle, windowId, taskId: 'desktop-test', mouseButton, direction }, signal)) + ToggleResult.parse(await native.request('toggleMouse', { appHandle: app.appHandle, windowId, mouseButton, direction }, signal)) const { cursor } = await fixture.command('pointer', FixtureState) for (const mouseButton of ['left', 'right', 'middle'] as const) { @@ -144,10 +144,9 @@ it.skipIf(process.platform !== 'win32' || !helperPath || !fixturePath)( expect((await toggle('left', 'up')).dispatched).toBe(true) await observed({ buttons: 'None', cursor: outside.cursor, ups: { left: pressed.ups.left + 1 }, clicks: pressed.clicks }) - const taskId = 'desktop-test' - const target = { appHandle: app.appHandle, windowId, taskId } + const target = { appHandle: app.appHandle, windowId } const key = (key: string, direction: 'down' | 'up') => native.request('sendKeyEvent', { ...target, key, direction }, signal) - const holds = () => native.request('getHeldInputs', { taskId }, signal) + const holds = () => native.request('getHeldInputs', {}, signal) const released = z.array(z.object({ kind: z.string(), key: z.string().nullable(), button: z.string().nullable(), mode: z.literal('system') })) await fixture.command('pointer', FixtureState) const offset = (await inspect()).inputEvents.length @@ -162,10 +161,11 @@ it.skipIf(process.platform !== 'win32' || !helperPath || !fixturePath)( (_owner, config) => nativeRuntime.connect(config)) cleanups.push(() => other.dispose()) const otherApp = App.parse(await other.request('getApp', { selector: fixturePath! }, signal)) - expect(await other.request('getHeldInputs', { taskId }, signal)).toEqual([]) + expect(await other.request('getHeldInputs', {}, signal)).toEqual([]) + expect(await other.requestCleanup('releaseHeldInputs', {})).toEqual([]) await expect(other.request('sendKeyEvent', { ...target, appHandle: otherApp.appHandle, key: 'w', direction: 'up' }, signal)) .rejects.toMatchObject({ code: 'INPUT_NOT_HELD' }) - const release = await native.requestCleanup('releaseHeldInputs', { taskId }) + const release = await native.requestCleanup('releaseHeldInputs', {}) expect(released.parse(release).map(input => input.key ?? input.button)).toEqual(['w', 'left', 'shift']) await expect.poll(async () => (await inspect()).inputEvents.slice(offset)).toEqual( ['ShiftKey:down', 'Left:down', 'W:down', 'W:up', 'Left:up', 'ShiftKey:up']) @@ -176,7 +176,7 @@ it.skipIf(process.platform !== 'win32' || !helperPath || !fixturePath)( await fixture.command('left-up', FixtureState) await observed({ ups: { left: beforeExternal.ups.left + 1 } }) expect(released.parse(await holds()).map(input => input.button)).toEqual(['left']) - const afterExternal = await native.requestCleanup('releaseHeldInputs', { taskId }) + const afterExternal = await native.requestCleanup('releaseHeldInputs', {}) expect(released.parse(afterExternal).map(input => input.button)).toEqual(['left']) expect(await holds()).toEqual([]) diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index 58f4e9537d..b4fc257373 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -21,8 +21,8 @@ en: 3f638a4a76023fc5 zh: 515aeb5de6ae5b33 /deepseek-ai-dsh-cua/understand-the-implementation: - en: 60892f557adb5d01 - zh: 2e8483610017484a + en: 7754a370ed7e54ff + zh: a3fa369e265746ad /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 b36d1a544d..c898816811 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -91,9 +91,9 @@ Permission responses identify their platform and report only the state that plat
Shared execution and platform ownership -Providers implementing `CuaBackend.heldInputState` accept `taskId` on explicit input and system pointer movement, report their connection-owned records through `getHeldInputs({ taskId })`, and acknowledge `releaseHeldInputs({ taskId })`. Native records own the actual key/button, target, process identity and input mode. Successful `run_code` and `cua_run_code` programs query those records and append a system reminder when input remains held; normal program and turn endings preserve input in both DSH and MCP. Reminders travel through logged additional context in DSH and through the tool response in MCP. macOS and Windows both implement this protocol. Capability methods remain static. +Providers implementing `CuaBackend.heldInputState` return the requesting connection’s holds through `getHeldInputs({})` and acknowledge their release through `releaseHeldInputs({})`. Native records own the actual key/button, target, process identity and input mode. Successful `run_code` and `cua_run_code` programs query those records and append a system reminder when input remains held; normal program and turn endings preserve input in both DSH and MCP. Reminders travel through logged additional context in DSH and through the tool response in MCP. macOS and Windows both implement this protocol. Capability methods remain static. -Held input belongs to the task and native connection, outside program processes. A DSH stop or model failure starts cleanup. The Agent can finish the turn and resolve `whenIdle()` while the native release is pending. Subsequent CUA calls wait for its outcome. A final tool error after successful dispatch starts cleanup of that invocation’s input owner. The original tool error can return while native release is pending. Any cleanup failure is reported separately. Confirmed release queues a notice for the model and removes pending held-state reminders. A cleanup failure is reported through `agent/error` and disables CUA for that task. A failed or cancelled program, an active MCP request receiving cancellation, an environment reset, and connection or provider disposal each await their own cleanup. +Each Agent uses its own native input connection across programs and turns. A DSH stop or model failure starts cleanup. The Agent can finish the turn and resolve `whenIdle()` while the native release is pending. Subsequent CUA calls wait for its outcome. A final tool error after successful dispatch starts cleanup of that invocation’s input owner. The original tool error can return while native release is pending. Any cleanup failure is reported separately. Confirmed release queues a notice for the model and removes pending held-state reminders. A cleanup failure is reported through `agent/error` and disables CUA for that task. A failed or cancelled program, an active MCP request receiving cancellation, an environment reset, and connection or provider disposal each await their own cleanup. The [permission store](src/permission-store.ts) uses `storageDomain` with the configured backend. The default JSON backend writes `$DSH_HOME/storages/cua_permissions_.json`, where the digest identifies the canonical profile directory. Each authorization check opens fresh state under the profile's file lock and closes its domain afterward; native dispatch uses a separate application lock. Revocation waits for operations already admitted by another process; after it completes, every process rejects old handles. Files on different machines or PID namespaces must not share this lock. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index a7f270f27c..4a3cc98123 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -91,9 +91,9 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边
共享执行与平台职责 -实现 `CuaBackend.heldInputState` 的提供方为显式输入和系统指针移动接受 `taskId`,通过 `getHeldInputs({ taskId })` 报告本连接的持有记录,并确认 `releaseHeldInputs({ taskId })`。原生记录负责保存实际按键或按钮、目标、进程身份和输入方式。成功结束的 `run_code` 和 `cua_run_code` 查询这些记录,仍有输入按住时添加 system reminder;DSH 和 MCP 的正常程序结束和回合结束均保持输入。DSH 通过已记录的额外上下文传递提醒,MCP 通过工具响应传递。macOS 和 Windows 都实现了这套协议。能力方法列表保持静态。 +实现 `CuaBackend.heldInputState` 的提供方通过 `getHeldInputs({})` 返回当前连接的持有记录,通过 `releaseHeldInputs({})` 释放这些输入并返回结果。原生记录负责保存实际按键或按钮、目标、进程身份和输入方式。成功结束的 `run_code` 和 `cua_run_code` 查询这些记录,仍有输入按住时添加 system reminder;DSH 和 MCP 的正常程序结束和回合结束均保持输入。DSH 通过已记录的额外上下文传递提醒,MCP 通过工具响应传递。macOS 和 Windows 都实现了这套协议。能力方法列表保持静态。 -持有输入属于任务和原生连接,保存在程序进程之外。DSH 收到停止请求或模型报错时启动清理。原生释放尚未确认时,Agent 可以结束回合,`whenIdle()` 也可以返回。后续 CUA 调用等待清理结果。程序执行成功后,如果最终工具结果失败,CUA 立即清理这次调用所属的输入。原工具错误可以先返回,清理失败会另行报告。确认释放后,DSH 为模型记录释放提醒,并撤销仍在队列中的旧持有提醒。清理失败会通过 `agent/error` 单独报告,并禁用该任务后续的 CUA 操作。程序失败或取消、执行中的 MCP 请求收到取消、环境重置、连接关闭和提供方卸载,各自等待清理完成。 +每个 Agent 使用独立的原生输入连接,多个程序和回合可以复用这条连接。DSH 收到停止请求或模型报错时启动清理。原生释放尚未确认时,Agent 可以结束回合,`whenIdle()` 也可以返回。后续 CUA 调用等待清理结果。程序执行成功后,如果最终工具结果失败,CUA 立即清理这次调用所属的输入。原工具错误可以先返回,清理失败会另行报告。确认释放后,DSH 为模型记录释放提醒,并撤销仍在队列中的旧持有提醒。清理失败会通过 `agent/error` 单独报告,并禁用该任务后续的 CUA 操作。程序失败或取消、执行中的 MCP 请求收到取消、环境重置、连接关闭和提供方卸载,各自等待清理完成。 [授权存储](src/permission-store.ts)复用 `storageDomain` 和配置的后端。默认 JSON 后端写入 `$DSH_HOME/storages/cua_permissions_.json`,摘要对应 profile 的真实目录。每次授权检查在 profile 文件锁内打开并读取最新状态,随后关闭存储域;原生操作使用单独的应用锁。撤销会等待其他进程已获准执行的操作结束;撤销完成后,各进程都拒绝旧句柄。不同电脑或 PID 命名空间不能共享这把锁。 diff --git a/packages/experimental/cua/src/held-inputs.ts b/packages/experimental/cua/src/held-inputs.ts index 074c08cce6..b21eea76a8 100644 --- a/packages/experimental/cua/src/held-inputs.ts +++ b/packages/experimental/cua/src/held-inputs.ts @@ -31,7 +31,7 @@ class InputOwner { private notifySessionOnRelease = false closing: Promise> | undefined - constructor(readonly agent: Agent, private readonly failed: (error: unknown) => void, + constructor(private readonly failed: (error: unknown) => void, private readonly released: (inputs: z.infer) => void) {} track(client: NativeClient, inTurn: boolean): void { @@ -44,7 +44,7 @@ class InputOwner { async reminder(inTurn: boolean): Promise { if (this.closing || !this.client) return - const inputs = heldInputs.parse(await this.client.request('getHeldInputs', { taskId: this.agent.id }, this.controller.signal)) + const inputs = heldInputs.parse(await this.client.request('getHeldInputs', {}, this.controller.signal)) if (inputs.length === 0) { this.removeCleanup?.() this.removeCleanup = undefined @@ -61,7 +61,7 @@ class InputOwner { try { if (!this.client) return [] if (!canRequest) throw new NativeError('INPUT_CLEANUP_UNCONFIRMED', 'Native connection closed before held-input cleanup was confirmed. Inspect the desktop manually before starting a new task') - const released = heldInputs.parse(await this.client.requestCleanup('releaseHeldInputs', { taskId: this.agent.id })) + const released = heldInputs.parse(await this.client.requestCleanup('releaseHeldInputs', {})) if (this.notifySessionOnRelease) this.released(released) return released } catch (error) { @@ -103,7 +103,7 @@ export class CuaHeldInputs { 'CUA cleanup was not confirmed. All CUA operations are disabled for this task; inspect the desktop manually before starting a new task', { cause: this.failures.get(agent) }) const current = this.owners.get(agent) if (current && !current.closing) return current - const owner = new InputOwner(agent, (error) => { + const owner = new InputOwner((error) => { this.failures.set(agent, error) this.ctx.logger.error('CUA cleanup was not confirmed; all CUA operations are disabled for task %s: %s', agent.id, error) emitAgentEvent(this.ctx, agent, 'agent/error', { turn: this.ctx.agents.turnBoundaryOf(agent.session).lastTurn, step: 0, error }) diff --git a/packages/experimental/cua/src/index.ts b/packages/experimental/cua/src/index.ts index ffe6671b81..17971d8f16 100644 --- a/packages/experimental/cua/src/index.ts +++ b/packages/experimental/cua/src/index.ts @@ -200,7 +200,7 @@ export interface CuaBackend { capabilities: CuaStartupCapabilities /** Preserve discovery PIDs when getApp accepts a decimal PID as an exact process selector. */ acceptsPidSelector?: boolean - /** Opt in to task-owned getHeldInputs and releaseHeldInputs; omission preserves the provider's existing protocol. */ + /** Opt in to connection-scoped getHeldInputs and releaseHeldInputs; omission preserves the provider's existing protocol. */ heldInputState?: boolean /** Registers a window read. The returned receipt handler sees the native reply only after Host decoding succeeds. */ windowRead?: (read: CuaWindowRead) => (reply: JsonValue) => void @@ -304,12 +304,9 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) // Earlier helpers accept an explicit false only for mouseMove. if (method !== 'mouseMove' && !useSystemInput) delete params.useSystemInput else if (useSystemInput !== undefined) params.useSystemInput = useSystemInput - if (heldInputs && (method === 'sendKeyEvent' || method === 'toggleMouse' || (method === 'mouseMove' && useSystemInput))) { + if (heldInputs && (method === 'sendKeyEvent' || method === 'toggleMouse') && params.direction === 'down') { const owner = await heldInputs.ready(agent) - if (method !== 'mouseMove' && params.direction === 'down') { - owner.track(client, ctx.agents.turnBoundaryOf(agent.session).openTurnStartSeq !== null) - } - params.taskId = agent.id + owner.track(client, ctx.agents.turnBoundaryOf(agent.session).openTurnStartSeq !== null) } const nativeParams = method === 'findApps' ? { ...params, maxAppMatches: config.maxAppMatches } diff --git a/packages/experimental/cua/src/protocol.ts b/packages/experimental/cua/src/protocol.ts index 345c04067a..32a7ce9068 100644 --- a/packages/experimental/cua/src/protocol.ts +++ b/packages/experimental/cua/src/protocol.ts @@ -116,12 +116,13 @@ export const NativeResourceParameters = { }).strict(), findApps: z.object({ maxAppMatches: z.number().int().min(1).max(1000) }).strict(), } -/** Host-only launch continuation and user-facing system permission controls; absent from model arguments. */ +/** Host-only launch, permission, and held-input operations; absent from model arguments. */ export const NativeOnlyOperations = [ operation('launchApp', app), operation('permissionStatus', {}), operation('applicationIcons', { paths: z.array(z.string().min(1)) }), operation('requestPermission', { permission: z.enum(['accessibility', 'screenRecording']) }), operation('openPermissionSettings', { permission: z.enum(['accessibility', 'screenRecording']) }), + operation('getHeldInputs', {}), operation('releaseHeldInputs', {}), ] as const /** Application selection returned only after a successful app selection. */ diff --git a/packages/experimental/cua/tests/run-code-composition.spec.ts b/packages/experimental/cua/tests/run-code-composition.spec.ts index da0dcb4e1f..e28316d702 100644 --- a/packages/experimental/cua/tests/run-code-composition.spec.ts +++ b/packages/experimental/cua/tests/run-code-composition.spec.ts @@ -495,6 +495,7 @@ it('a late policy refusal closes only the owner captured by that execution', asy }) const running = f.run() await entered.promise + const openedChannels = f.native.state.openedChannels const execute = (id: string, code: string) => f.ctx.agents.withInitiator(f.agent, () => f.ctx.tools.execute({ agent: f.agent, signal: new AbortController().signal, calls: [{ type: 'tool-call', id: brandString(id), name: 'cua_run_code', arguments: JSON.stringify({ code, description: id }) }], @@ -508,6 +509,7 @@ it('a late policy refusal closes only the owner captured by that execution', asy } finally { finish.resolve(); await running } expect((await execute('release-d', 'await app.sendKeyEvent("d", "up")')).results[0]?.result.isError).toBe(false) expect(f.native.events).toEqual(['w:down', 'w:up', 'd:down', 'd:up']) + expect(f.native.state.openedChannels).toBe(openedChannels) expect(f.native.calls.filter(call => call.method === 'releaseHeldInputs')).toHaveLength(1) }) diff --git a/snapshots/session/cua-native/workspace/native-helper.mjs b/snapshots/session/cua-native/workspace/native-helper.mjs index 74d47d638d..00cb4c3406 100755 --- a/snapshots/session/cua-native/workspace/native-helper.mjs +++ b/snapshots/session/cua-native/workspace/native-helper.mjs @@ -135,10 +135,10 @@ function createApplicationState(socket, record, application, captureBroker, conn function refuse(code, message) { throw Object.assign(new Error(message), { code }) } function call(requestId, method, params) { record('call', { requestId, method, params }) - if (method === 'getHeldInputs') return [...heldInputs.get(params.taskId)?.values() ?? []] + if (method === 'getHeldInputs') return [...heldInputs.values()] if (method === 'releaseHeldInputs') { - const released = [...heldInputs.get(params.taskId)?.values() ?? []].reverse() - heldInputs.delete(params.taskId) + const released = [...heldInputs.values()].reverse() + heldInputs.clear() return released } if (method === 'applicationIcons') return Object.fromEntries(params.paths.map(path => [path, `data:image/png;base64,${png}`])) @@ -289,14 +289,12 @@ function createApplicationState(socket, record, application, captureBroker, conn return { dispatched: true } } if (method === 'sendKeyEvent' || method === 'toggleMouse') { - const held = heldInputs.get(params.taskId) ?? new Map() const input = method === 'sendKeyEvent' ? { kind: 'key', key: params.key, appHandle: params.appHandle, mode: params.useSystemInput ? 'system' : 'application' } : { kind: 'mouse', button: params.mouseButton, appHandle: params.appHandle, windowId: params.windowId, mode: params.useSystemInput ? 'system' : 'window' } const id = JSON.stringify([params.appHandle, params.windowId, method, params.key ?? params.mouseButton]) - if (params.direction === 'down') held.set(id, input) - else if (!held.delete(id)) refuse('INVALID_ARGUMENT', 'Input was not held by this task') - heldInputs.set(params.taskId, held) + if (params.direction === 'down') heldInputs.set(id, input) + else if (!heldInputs.delete(id)) refuse('INVALID_ARGUMENT', 'Input was not held by this connection') return { dispatched: true } } if (method === 'typeText') application.value += params.text diff --git a/snapshots/session/cua-run-code/native-channel.d.mts b/snapshots/session/cua-run-code/native-channel.d.mts index 080aa206f1..a4c3a35136 100644 --- a/snapshots/session/cua-run-code/native-channel.d.mts +++ b/snapshots/session/cua-run-code/native-channel.d.mts @@ -12,7 +12,7 @@ export function createNativeFixture(selectorPid?: number): { createChannel: NativeChannelFactory calls: Array<{ id: string; method: string; params: Record }> events: string[] - held: Array<{ connection: number; taskId: string; key: string }> + held: Array<{ connection: number; key: string }> /** Control one native reply or cancellation acknowledgement at a deterministic barrier. */ controlNext(method: string, options?: { afterDispatch?: boolean; waitForCancellation?: boolean }): { entered: Promise diff --git a/snapshots/session/cua-run-code/native-channel.mjs b/snapshots/session/cua-run-code/native-channel.mjs index 1cd3d95785..7999648cfb 100644 --- a/snapshots/session/cua-run-code/native-channel.mjs +++ b/snapshots/session/cua-run-code/native-channel.mjs @@ -27,7 +27,7 @@ export function createNativeFixture(selectorPid) { let blocked let heldCallId function dispatch(method, params) { - if (method === 'getHeldInputs') return held.filter(press => press.connection === connection && press.taskId === params.taskId).map(press => press.kind === 'key' + if (method === 'getHeldInputs') return held.filter(press => press.connection === connection).map(press => press.kind === 'key' ? { kind: 'key', key: press.key, appHandle: press.appHandle, ...press.windowId === undefined ? { mode: 'application' } : { windowId: press.windowId, mode: 'system' } } : { kind: 'mouse', button: press.key, appHandle: press.appHandle, windowId: press.windowId, mode: press.mode }) @@ -35,7 +35,7 @@ export function createNativeFixture(selectorPid) { const released = dispatch('getHeldInputs', params).reverse() for (let index = held.length - 1; index >= 0; index--) { const press = held[index] - if (press.connection === connection && press.taskId === params.taskId) { + if (press.connection === connection) { events.push(`${press.key}:up`) held.splice(index, 1) } @@ -55,11 +55,11 @@ export function createNativeFixture(selectorPid) { if (!acquired || params.appHandle !== 'fixture-app') throw new Error('Acquire the application before using its handle') if (method === 'sendKeyEvent' || method === 'toggleMouse') { const key = params.key ?? params.mouseButton - const index = held.findIndex(press => press.connection === connection && press.taskId === params.taskId && press.key === key) - if (params.direction === 'down' && index < 0) held.push({ connection, taskId: params.taskId, key, appHandle: params.appHandle, + const index = held.findIndex(press => press.connection === connection && press.key === key) + if (params.direction === 'down' && index < 0) held.push({ connection, key, appHandle: params.appHandle, kind: method === 'sendKeyEvent' ? 'key' : 'mouse', windowId: params.windowId, mode: params.useSystemInput ? 'system' : 'window' }) if (params.direction === 'up') { - if (index < 0) throw new Error('Input was not held by this task') + if (index < 0) throw new Error('Input was not held by this connection') held.splice(index, 1) } events.push(`${key}:${params.direction}`) From 40be0a915d8065f373de9804aa8192cbce746134 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 20 Nov 2026 15:06:43 +0800 Subject: [PATCH 70/73] Check that native mouse input rejects a caller-supplied owner --- packages/experimental/cua-windows/native/tests/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/experimental/cua-windows/native/tests/Program.cs b/packages/experimental/cua-windows/native/tests/Program.cs index 15c4d3bb2a..ec1512f315 100644 --- a/packages/experimental/cua-windows/native/tests/Program.cs +++ b/packages/experimental/cua-windows/native/tests/Program.cs @@ -74,7 +74,7 @@ foreach (var direction in new[] { "down", "up" }) } foreach (var invalid in new[] { - """{"appHandle":"app","windowId":"1","mouseButton":"left","direction":"down"}""", + """{"appHandle":"app","windowId":"1","mouseButton":"left","direction":"down","taskId":"other"}""", """{"appHandle":"app","windowId":"1","mouseButton":"left"}""", """{"appHandle":"app","windowId":"1","direction":"down"}""", """{"appHandle":"app","mouseButton":"left","direction":"down"}""", From c9407e2be2ec6e4ecf1440f538ef02144bef9ce9 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 20 Nov 2026 16:26:45 +0800 Subject: [PATCH 71/73] Limit Windows held-input checks to the affected key or button --- .../experimental/cua-windows/README.i18n.yaml | 8 ++-- packages/experimental/cua-windows/README.md | 4 +- .../experimental/cua-windows/README.zh.md | 4 +- .../native/entry/DesktopExecutor.cs | 41 ++++++++----------- .../cua-windows/native/entry/HeldInputs.cs | 13 +----- .../cua-windows/native/entry/Input.cs | 9 +--- .../native/tests/HeldInputChecks.cs | 20 ++++----- .../tests/desktop-toggle-mouse.spec.ts | 7 +++- 8 files changed, 43 insertions(+), 63 deletions(-) diff --git a/packages/experimental/cua-windows/README.i18n.yaml b/packages/experimental/cua-windows/README.i18n.yaml index 113cccc1f8..1d4df0039b 100644 --- a/packages/experimental/cua-windows/README.i18n.yaml +++ b/packages/experimental/cua-windows/README.i18n.yaml @@ -36,8 +36,8 @@ en: 38b3250d6ae0f3d6 zh: 33d056c416e11d75 /deepseek-ai-dsh-cua-windows/model-experience/explicit-application-and-window-operations/what-the-model-sees: - en: bf6f99c4c1fafe72 - zh: 791930be8c5f80f4 + en: d1c83b32631c2146 + zh: fff241be17b13885 /deepseek-ai-dsh-cua-windows/model-experience/explicit-application-and-window-operations/token-effect: en: 39eebd53ee226af7 zh: ba7b352cf1e23c3c @@ -45,8 +45,8 @@ en: db3e2957041fafbb zh: 34f953887dff37f7 /deepseek-ai-dsh-cua-windows/known-limitations-and-deferred-work: - en: f36d057acb4e9ea3 - zh: a1a94877e51d9d66 + en: d778c226c2a8f2bd + zh: 27b06182ebf4ff66 /deepseek-ai-dsh-cua-windows/known-limitations-and-deferred-work/dev-note: en: 0a1253c6f7b5e8b9 zh: 9f56528562c7c914 diff --git a/packages/experimental/cua-windows/README.md b/packages/experimental/cua-windows/README.md index 073e9d4056..8bf999d3a6 100644 --- a/packages/experimental/cua-windows/README.md +++ b/packages/experimental/cua-windows/README.md @@ -65,7 +65,7 @@ Each result contains `id`, `displayName`, and `isRunning`. The ID is an AUMID, i #### What the model sees -The program receives application and window identifiers, observations, and action results. Selection alone does not provide an accessibility tree. After a successful program, a reminder lists any held keys and buttons with their window and desktop input mode. Program failure, cancellation, reset and disconnect release the input held by that connection in reverse dispatch order. +The program receives application and window identifiers, observations, and action results. Selection alone does not provide an accessibility tree. After a successful program, a reminder lists any held keys and buttons with their window and desktop input mode. While one connection holds a key or button, another connection can use different keys or buttons. Program failure, cancellation, reset and disconnect release the input held by that connection in reverse dispatch order. #### Token effect @@ -83,7 +83,7 @@ Inspected results append to model history. Retaining an App, Window, or returned - Hover, click, scroll and drag use the system pointer. `requireSystemInputApproval` does not prompt separately for Windows pointer operations. - Drag checks the topmost window only at its starting point. An overlay from another application along the path or at the destination can receive the drop even while the selected window stays in the foreground. - Held-input reminders and cleanup use the helper's own dispatches. If you press the same key or button while the helper holds it, its next up can also interrupt your press. -- Windows routes input through the desktop. After focus changes or the original window closes, a confirmed release means the desktop accepted the up. The original window may not receive the event. If the desktop is unavailable or refuses to confirm release, further CUA input for the task is blocked. Inspect the desktop before starting another task. +- Windows routes input through the desktop. After focus changes or the original window closes, a confirmed release means the desktop accepted the up. The original window may not receive the event. Releasing a held input does not check the current foreground window or lock state. The release uses the saved up event and reports `foregroundChanged: null` for an explicit up. If Windows refuses the up during cleanup, further CUA input for the task is blocked. Inspect the desktop before starting another task. - Cleanup of temporary input inside complete actions does not check each key or button release. If an input remains held after a failure, release it manually before continuing. - Helper identity hashes only the exe. Different DLLs with the same apphost can reuse the old service. Stop Hosts using the same output directory before rebuilding to avoid locked files. - The Windows handshake requires a positive `maxClickHoldMs`. With zero, it fails with `INVALID_CONFIG` before ordinary clicks or status queries can run. diff --git a/packages/experimental/cua-windows/README.zh.md b/packages/experimental/cua-windows/README.zh.md index a84c963e1a..8f019d5ee8 100644 --- a/packages/experimental/cua-windows/README.zh.md +++ b/packages/experimental/cua-windows/README.zh.md @@ -65,7 +65,7 @@ kind: "package-reference" #### 模型看到什么 -程序可以读取应用和窗口标识、观察结果及动作结果。仅执行选择操作不会提供辅助功能树。程序成功后,提醒会列出仍按住的键和鼠标按钮、所属窗口和桌面输入方式。程序异常、取消、重置和断连时,按派发顺序的反序释放这条连接持有的输入。 +程序可以读取应用和窗口标识、观察结果及动作结果。仅执行选择操作不会提供辅助功能树。程序成功后,提醒会列出仍按住的键和鼠标按钮、所属窗口和桌面输入方式。一条连接持有按键或鼠标按钮时,其他连接仍可使用不同的键或按钮。程序异常、取消、重置和断连时,按派发顺序的反序释放这条连接持有的输入。 #### Token 影响 @@ -83,7 +83,7 @@ kind: "package-reference" - 悬停、点击、滚动和拖拽使用系统指针。`requireSystemInputApproval` 不会为 Windows 操作弹出单独的指针授权提示。 - 拖拽只检查起点处最上层的窗口。若其他应用遮住路径或终点,即使目标仍在前台,也可能把内容拖到其他应用。 - 持有提醒和清理只依据 helper 自己派发的输入。如果你也按住同一个键或按钮,helper 之后发送的 up 可能打断你的按压。 -- Windows 通过桌面派发输入。焦点变化或原窗口关闭后,确认释放表示桌面接受了 up,原窗口可能收不到该事件。若桌面不可用或无法确认释放,本任务不能继续使用 CUA。请先检查桌面,再开始新任务。 +- Windows 通过桌面派发输入。焦点变化或原窗口关闭后,确认释放表示桌面接受了 up,原窗口可能收不到该事件。释放时直接发送保存的 up 事件,无需检查当前前台窗口或锁屏状态。显式 up 返回 `foregroundChanged: null`。若 Windows 在清理时拒绝 up,本任务不能继续使用 CUA。请先检查桌面,再开始新任务。 - 清理完整动作内的临时输入时,helper 不检查每个按键或鼠标按钮的释放结果。操作失败后如有按键或按钮仍处于按下状态,请先手动释放。 - helper 的身份摘要只覆盖 exe。同一 apphost 搭配不同 DLL 时可能复用旧服务。重新构建前请先关闭使用同一输出目录的 Host,避免文件被占用。 - Windows 握手要求 `maxClickHoldMs` 为正整数。设为 0 会使连接以 `INVALID_CONFIG` 失败,连普通点击和状态查询也不可用。 diff --git a/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs b/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs index 68b5c07029..a374db5376 100644 --- a/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs +++ b/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs @@ -17,12 +17,12 @@ internal sealed class ClientState internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IAsyncDisposable { - private readonly HeldInputs inputs = new(input => Input.Send(input), DesktopSession.RequireInteractive); + private readonly HeldInputs inputs = new(input => Input.Send(input)); private readonly WindowCapture capture = new(); private readonly ClipboardPaste clipboard = new(); private readonly SemaphoreSlim queue = new(1); - private static object ActionResult(nint before, bool dispatched = true) => new + private static object ActionResult(nint before = 0, bool dispatched = true) => new { dispatched, foregroundChanged = before == 0 || Win32.GetForegroundWindow() == 0 ? (bool?)null : before != Win32.GetForegroundWindow(), @@ -90,16 +90,23 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA if (request.Method == "releaseHeldInputs") return inputs.Release(state.Connection, cancellation); - if (request.Method is "sendKeyEvent" or "toggleMouse" && String(parameters, "direction") == "up") + if (request.Method is "sendKeyEvent" or "toggleMouse") { - var window = WindowId(parameters) ?? throw new NativeFailure("INVALID_ARGUMENT", "Release through the original window"); - var recipient = String(parameters, "appHandle"); + var handle = String(parameters, "appHandle"); + var keyboard = request.Method == "sendKeyEvent"; + var name = keyboard ? Input.HoldKeyName(String(parameters, "key")) : String(parameters, "mouseButton"); + if (String(parameters, "direction") == "up") + { + inputs.Up(state.Connection, handle, WindowId(parameters), name, keyboard); + return ActionResult(); + } + var recipient = state.App(handle); var before = Win32.GetForegroundWindow(); - if (request.Method == "sendKeyEvent") - Input.ReleaseKey(state.Connection, recipient, window, String(parameters, "key"), context); - else - Input.ReleaseButton(state.Connection, recipient, window, String(parameters, "mouseButton"), context); - return ActionResult(before); + var target = Selected(recipient, parameters, context); + var dispatched = keyboard + ? Input.KeyDown(state.Connection, recipient, target, name, context) + : Input.ButtonDown(state.Connection, recipient, target, name, context); + return ActionResult(before, dispatched); } DesktopSession.RequireInteractive(); if (request.Method == "listApps") return await DesktopWindows.ListApps(context); @@ -114,8 +121,6 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA } var app = state.App(String(parameters, "appHandle")); var foreground = Win32.GetForegroundWindow(); - if (request.Method is "sendKeyEvent" or "toggleMouse" or "pressKey" or "typeText" or "paste" or "mouseMove" or "scroll" or "drag" or "click") - inputs.RequireOwner(state.Connection, app.Handle, WindowId(parameters) ?? 0); switch (request.Method) { case "launchApp": @@ -159,12 +164,6 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA Input.Press(app, target, String(parameters, "key"), Modifiers(parameters), context); return ActionResult(foreground); } - case "sendKeyEvent": - { - var target = Selected(app, parameters, context); - var dispatched = Input.KeyDown(state.Connection, app, target, String(parameters, "key"), context); - return ActionResult(foreground, dispatched); - } case "paste": { var target = Selected(app, parameters, context); @@ -190,12 +189,6 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA var pointed = Coordinate(app, parameters, context); return Input.MouseMove(app, pointed.Window, pointed.X, pointed.Y, context); } - case "toggleMouse": - { - var target = Selected(app, parameters, context); - var dispatched = Input.ButtonDown(state.Connection, app, target, String(parameters, "mouseButton"), context); - return ActionResult(foreground, dispatched); - } case "scroll": { var target = Coordinate(app, parameters, context); diff --git a/packages/experimental/cua-windows/native/entry/HeldInputs.cs b/packages/experimental/cua-windows/native/entry/HeldInputs.cs index 4217bcb21a..56ca5b8807 100644 --- a/packages/experimental/cua-windows/native/entry/HeldInputs.cs +++ b/packages/experimental/cua-windows/native/entry/HeldInputs.cs @@ -4,7 +4,7 @@ using DeepSeek.Cua.Protocol; namespace DeepSeek.Cua.Windows; -internal sealed class HeldInputs(Action send, Action requireInteractive) +internal sealed class HeldInputs(Action send) { internal readonly record struct Target(string AppHandle, nint Window, int ProcessId, long ProcessStarted); private sealed record Press(Guid Connection, Target Target, ushort Control, string Name, Win32.Input Up) @@ -20,14 +20,6 @@ internal sealed class HeldInputs(Action send, Action requireInterac private readonly object gate = new(); private readonly List pressed = []; - internal void RequireOwner(Guid connection, string app, nint window) - { - lock (gate) - if (pressed.Any(press => press.Connection != connection - || press.Target.AppHandle != app || press.Target.Window != window)) - throw new NativeFailure("INPUT_BUSY", "Another connection or window owns held desktop input; release it before sending input to this window"); - } - internal void RequireAvailable(ushort control) { lock (gate) @@ -62,7 +54,7 @@ internal sealed class HeldInputs(Action send, Action requireInterac } } - internal void Up(Guid connection, string app, nint window, string name, bool keyboard) + internal void Up(Guid connection, string app, nint? window, string name, bool keyboard) { lock (gate) { @@ -105,7 +97,6 @@ internal sealed class HeldInputs(Action send, Action requireInterac private void ReleaseAt(int index) { - requireInteractive(); send(pressed[index].Up); pressed.RemoveAt(index); } diff --git a/packages/experimental/cua-windows/native/entry/Input.cs b/packages/experimental/cua-windows/native/entry/Input.cs index adfcc4e600..4463387700 100644 --- a/packages/experimental/cua-windows/native/entry/Input.cs +++ b/packages/experimental/cua-windows/native/entry/Input.cs @@ -93,7 +93,7 @@ internal static class Input return ((ushort)(mapped & 0xFF), false, modifiers.ToArray()); } - private static string HoldKeyName(string name) => name.ToLowerInvariant() switch + internal static string HoldKeyName(string name) => name.ToLowerInvariant() switch { "control" => "ctrl", "return" => "enter", @@ -104,13 +104,9 @@ internal static class Input var key => key, }; - internal static void ReleaseKey(Guid connection, string app, nint window, string name, RequestContext context) - => context.HeldInputs.Up(connection, app, window, HoldKeyName(name), true); - internal static bool KeyDown(Guid connection, AppState app, WindowState window, string name, RequestContext context) { Windows.RequireForeground(app, window, context); - name = HoldKeyName(name); var key = ResolveKey(name, includeModifiers: true); if (key.Modifiers.Length != 0) throw new NativeFailure("UNSUPPORTED", "This key requires modifiers in the target keyboard layout; send each modifier and the base key separately"); @@ -187,9 +183,6 @@ internal static class Input return new { dispatched = true, hoverRoute = "system-pointer", systemPointerMoved = before.X != point.X || before.Y != point.Y }; } - internal static void ReleaseButton(Guid connection, string app, nint window, string button, RequestContext context) - => context.HeldInputs.Up(connection, app, window, button, false); - internal static bool ButtonDown(Guid connection, AppState app, WindowState window, string button, RequestContext context) { var flags = Button(button); diff --git a/packages/experimental/cua-windows/native/tests/HeldInputChecks.cs b/packages/experimental/cua-windows/native/tests/HeldInputChecks.cs index 1ed3d7b495..d711dd6c7f 100644 --- a/packages/experimental/cua-windows/native/tests/HeldInputChecks.cs +++ b/packages/experimental/cua-windows/native/tests/HeldInputChecks.cs @@ -12,7 +12,6 @@ internal static class HeldInputChecks var target = new HeldInputs.Target("app", 72, 122, 100); var events = new List(); var blocked = false; - var interactive = true; void Receive(Win32.Input input) { if (blocked) throw new NativeFailure("INPUT_BLOCKED", "SendInput returned zero"); @@ -21,10 +20,7 @@ internal static class HeldInputChecks var up = isKey ? (input.Data.Keyboard.Flags & 2) != 0 : input.Data.Mouse.Flags == 4; events.Add($"{control}:{(up ? "up" : "down")}"); } - var inputs = new HeldInputs(Receive, () => - { - if (!interactive) throw new NativeFailure("SESSION_LOCKED", "The interactive desktop is unavailable"); - }); + var inputs = new HeldInputs(Receive); bool Key(Guid connection, ushort key, string name, CancellationToken cancellation = default) => inputs.Down(connection, target, key, name, @@ -43,8 +39,7 @@ internal static class HeldInputChecks new() { Data = new() { Mouse = new() { Flags = 2 } } }, new() { Data = new() { Mouse = new() { Flags = 4 } } }, default), "Record the accepted mouse down"); check(Key(a, 87, "w") && !Key(a, 87, "w"), "A repeated key does not duplicate a hold"); - refuses(() => inputs.RequireOwner(b, "app", 72), "INPUT_BUSY"); - refuses(() => inputs.RequireOwner(a, "app", 73), "INPUT_BUSY"); + refuses(() => Key(b, 87, "w"), "INPUT_BUSY"); refuses(() => inputs.RequireAvailable(1), "INPUT_BUSY"); refuses(() => inputs.Up(b, "app", 72, "w", true), "INPUT_NOT_HELD"); refuses(() => inputs.Up(a, "app", 73, "w", true), "INPUT_NOT_HELD"); @@ -58,6 +53,13 @@ internal static class HeldInputChecks check(inputs.Release(a, default).Length == 3 && events.TakeLast(3).SequenceEqual(["16:up", "87:up", "1:up"]), "Release in mixed reverse order, including repress"); check(inputs.Release(a, default).Length == 0, "Duplicate connection cleanup sends no up"); + Key(a, 87, "w"); + Key(b, 68, "d"); + var beforeRelease = events.Count; + inputs.Up(a, "app", 72, "w", true); + check(inputs.Get(b).Length == 1 && events.Skip(beforeRelease).SequenceEqual(["87:up"]), + "One connection can release W while another holds D"); + inputs.Up(b, "app", 72, "d", true); using (var cancelled = new CancellationTokenSource()) { cancelled.Cancel(); @@ -65,10 +67,6 @@ internal static class HeldInputChecks catch (OperationCanceledException) { check(inputs.Get(a).Length == 0, "Cancelled down never dispatches"); } } Key(a, 87, "w"); - interactive = false; - refuses(() => inputs.Release(a, default), "INPUT_CLEANUP_FAILED"); - check(inputs.Get(a).Length == 1, "A locked desktop leaves the failed release recorded"); - interactive = true; blocked = true; refuses(() => inputs.Release(a, default), "INPUT_CLEANUP_FAILED"); check(inputs.Get(a).Length == 1, "A refused release stays recorded for disconnect fallback"); diff --git a/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts b/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts index 78e2bbecd2..53b8ac4d8f 100644 --- a/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts +++ b/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts @@ -185,10 +185,15 @@ it.skipIf(process.platform !== 'win32' || !helperPath || !fixturePath)( await expect.poll(async () => (await inspect()).inputEvents.slice(beforeSwitch)).toContain('W:down') const switched = await fixture.command('sibling', FixtureState) expect(switched.foreground).toBe(switched.window) + const peerTarget = { appHandle: otherApp.appHandle, windowId: switched.window, key: 'd' } + await other.request('sendKeyEvent', { ...peerTarget, direction: 'down' }, signal) await native.dispose() await expect.poll(async () => { const sibling = await fixture.command('inspect-sibling', FixtureState) return { foreground: sibling.foreground, events: sibling.inputEvents.slice(switched.inputEvents.length) } }).toEqual({ foreground: switched.window, events: ['W:up'] }) - + expect(released.parse(await other.request('getHeldInputs', {}, signal)).map(input => input.key)).toEqual(['d']) + await fixture.command('focus', FixtureState) + expect(await other.request('sendKeyEvent', { ...peerTarget, direction: 'up' }, signal)) + .toMatchObject({ dispatched: true, foregroundChanged: null }) }, 120_000) From 430680a4c3ecd994b47c9cade9c5db71147ea1df Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 20 Nov 2026 17:04:34 +0800 Subject: [PATCH 72/73] Silently finish best-effort Windows input cleanup on disconnect --- .../cua-held-inputs/guide.i18n.yaml | 4 ++-- .../v0.2.2-rc.5/cua-held-inputs/guide.md | 2 +- .../v0.2.2-rc.5/cua-held-inputs/guide.zh.md | 2 +- .../experimental/cua-windows/README.i18n.yaml | 8 ++++---- packages/experimental/cua-windows/README.md | 4 ++-- .../experimental/cua-windows/README.zh.md | 4 ++-- .../native/entry/DesktopExecutor.cs | 10 ++-------- .../cua-windows/native/entry/HeldInputs.cs | 18 +++++++++++++++-- .../cua-windows/native/entry/NativeServer.cs | 7 +------ .../native/tests/HeldInputChecks.cs | 20 +++++++++++++++++-- 10 files changed, 49 insertions(+), 30 deletions(-) diff --git a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml index dd561e1a74..2bbea41110 100644 --- a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.i18n.yaml @@ -9,8 +9,8 @@ en: 37252a5d19c7fe09 zh: f1b33b7da3935155 /cua-reports-held-input-after-programs/change: - en: cf9c1397e07dffa5 - zh: f1cce9fadf321d43 + en: 80ab79f78e26ff43 + zh: e6ba8ac29eaabf50 /cua-reports-held-input-after-programs/migration: en: c26899347e7a24c9 zh: ae78a24c58d6f80f diff --git a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md index b26416c840..e04619385b 100644 --- a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.md @@ -8,7 +8,7 @@ English | [中文](guide.zh.md) ## Change -On macOS and Windows, explicit `sendKeyEvent('down')` and `toggleMouse('down')` remain held across programs and turns until an explicit `up`. Normal completion does not release them. After a successful `run_code` or `cua_run_code`, a system reminder lists any remaining keys and mouse buttons, their application or window and actual input mode. Program failure, user stop, connection closure, environment reset and disposal release owned input in reverse dispatch order. Complete `pressKey`, `typeText`, `click` and `drag` actions keep their operation-local cleanup. DSH and MCP both preserve input after successful programs. A client pause between completed MCP calls is not observable by the server and can leave input held. On Windows, cleanup sends an up for each input the helper still holds. If you also hold the same key or button, that up may interrupt your press. A focus change sends the up to the desktop without reactivating the original window. +On macOS and Windows, explicit `sendKeyEvent('down')` and `toggleMouse('down')` remain held across programs and turns until an explicit `up`. Normal completion does not release them. After a successful `run_code` or `cua_run_code`, a system reminder lists any remaining keys and mouse buttons, their application or window and actual input mode. Program failure, user stop, environment reset and disposal request release in reverse dispatch order. On disconnect the helper attempts a final release. Windows silently discards the disconnected owner’s records if that attempt fails or times out. Complete `pressKey`, `typeText`, `click` and `drag` actions keep their operation-local cleanup. DSH and MCP both preserve input after successful programs. A client pause between completed MCP calls is not observable by the server and can leave input held. On Windows, cleanup sends an up for each input the helper still holds. If you also hold the same key or button, that up may interrupt your press. A focus change sends the up to the desktop without reactivating the original window. ## Migration diff --git a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md index f776b6de47..96527ce8c3 100644 --- a/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.5/cua-held-inputs/guide.zh.md @@ -8,7 +8,7 @@ description: macOS 和 Windows 的 CUA 显式输入跨程序和回合保持, ## 变更 -macOS 和 Windows 的显式 `sendKeyEvent('down')` 和 `toggleMouse('down')` 跨程序、跨回合保持,直到显式 `up`。正常结束不释放它们。成功结束的 `run_code` 或 `cua_run_code` 通过 system reminder 列出剩余键盘键和鼠标按钮、所属应用或窗口及实际输入方式。程序失败、用户停止、断连、环境重置和销毁按派发顺序的反序释放所属输入。完整的 `pressKey`、`typeText`、`click` 和 `drag` 保持操作内清理。DSH 和 MCP 都在程序成功后保持输入。客户端在两次 MCP 调用之间暂停时,服务端无法观察到,输入可能继续按住。Windows 清理时会为 helper 仍持有的输入发送 up。如果你也按住同一个键或按钮,这次 up 可能打断你的按压。焦点变化后,up 发往当前桌面,原窗口不会被重新激活。 +macOS 和 Windows 的显式 `sendKeyEvent('down')` 和 `toggleMouse('down')` 跨程序、跨回合保持,直到显式 `up`。正常结束不释放它们。成功结束的 `run_code` 或 `cua_run_code` 通过 system reminder 列出剩余键盘键和鼠标按钮、所属应用或窗口及实际输入方式。程序失败、用户停止、环境重置和销毁时会请求按派发顺序的反序释放。断连时,helper 会最后尝试释放。若失败或超时,Windows helper 会静默丢弃该连接的持有记录。完整的 `pressKey`、`typeText`、`click` 和 `drag` 保持操作内清理。DSH 和 MCP 都在程序成功后保持输入。客户端在两次 MCP 调用之间暂停时,服务端无法观察到,输入可能继续按住。Windows 清理时会为 helper 仍持有的输入发送 up。如果你也按住同一个键或按钮,这次 up 可能打断你的按压。焦点变化后,up 发往当前桌面,原窗口不会被重新激活。 ## 迁移 diff --git a/packages/experimental/cua-windows/README.i18n.yaml b/packages/experimental/cua-windows/README.i18n.yaml index 1d4df0039b..d8f5691b5c 100644 --- a/packages/experimental/cua-windows/README.i18n.yaml +++ b/packages/experimental/cua-windows/README.i18n.yaml @@ -36,8 +36,8 @@ en: 38b3250d6ae0f3d6 zh: 33d056c416e11d75 /deepseek-ai-dsh-cua-windows/model-experience/explicit-application-and-window-operations/what-the-model-sees: - en: d1c83b32631c2146 - zh: fff241be17b13885 + en: 8949441c259efd34 + zh: 5526a527eb02a0ac /deepseek-ai-dsh-cua-windows/model-experience/explicit-application-and-window-operations/token-effect: en: 39eebd53ee226af7 zh: ba7b352cf1e23c3c @@ -45,8 +45,8 @@ en: db3e2957041fafbb zh: 34f953887dff37f7 /deepseek-ai-dsh-cua-windows/known-limitations-and-deferred-work: - en: d778c226c2a8f2bd - zh: 27b06182ebf4ff66 + en: ff80ed2855470176 + zh: d3ff1f845594caa1 /deepseek-ai-dsh-cua-windows/known-limitations-and-deferred-work/dev-note: en: 0a1253c6f7b5e8b9 zh: 9f56528562c7c914 diff --git a/packages/experimental/cua-windows/README.md b/packages/experimental/cua-windows/README.md index 8bf999d3a6..9b3fb24228 100644 --- a/packages/experimental/cua-windows/README.md +++ b/packages/experimental/cua-windows/README.md @@ -65,7 +65,7 @@ Each result contains `id`, `displayName`, and `isRunning`. The ID is an AUMID, i #### What the model sees -The program receives application and window identifiers, observations, and action results. Selection alone does not provide an accessibility tree. After a successful program, a reminder lists any held keys and buttons with their window and desktop input mode. While one connection holds a key or button, another connection can use different keys or buttons. Program failure, cancellation, reset and disconnect release the input held by that connection in reverse dispatch order. +The program receives application and window identifiers, observations, and action results. Selection alone does not provide an accessibility tree. After a successful program, a reminder lists any held keys and buttons with their window and desktop input mode. While one connection holds a key or button, another connection can use different keys or buttons. Program failure, cancellation and reset request release in reverse dispatch order. At disconnect, the helper makes a final bounded release attempt. If it fails or times out, the helper silently discards that connection’s records. #### Token effect @@ -83,7 +83,7 @@ Inspected results append to model history. Retaining an App, Window, or returned - Hover, click, scroll and drag use the system pointer. `requireSystemInputApproval` does not prompt separately for Windows pointer operations. - Drag checks the topmost window only at its starting point. An overlay from another application along the path or at the destination can receive the drop even while the selected window stays in the foreground. - Held-input reminders and cleanup use the helper's own dispatches. If you press the same key or button while the helper holds it, its next up can also interrupt your press. -- Windows routes input through the desktop. After focus changes or the original window closes, a confirmed release means the desktop accepted the up. The original window may not receive the event. Releasing a held input does not check the current foreground window or lock state. The release uses the saved up event and reports `foregroundChanged: null` for an explicit up. If Windows refuses the up during cleanup, further CUA input for the task is blocked. Inspect the desktop before starting another task. +- Windows routes input through the desktop. After focus changes or the original window closes, a confirmed release means the desktop accepted the up. The original window may not receive the event. Releasing a held input does not check the current foreground window or lock state. The release uses the saved up event and reports `foregroundChanged: null` for an explicit up. If Windows refuses an explicit cleanup request, further CUA input for the task is blocked. Inspect the desktop before starting another task. - Cleanup of temporary input inside complete actions does not check each key or button release. If an input remains held after a failure, release it manually before continuing. - Helper identity hashes only the exe. Different DLLs with the same apphost can reuse the old service. Stop Hosts using the same output directory before rebuilding to avoid locked files. - The Windows handshake requires a positive `maxClickHoldMs`. With zero, it fails with `INVALID_CONFIG` before ordinary clicks or status queries can run. diff --git a/packages/experimental/cua-windows/README.zh.md b/packages/experimental/cua-windows/README.zh.md index 8f019d5ee8..5d4f5e18fa 100644 --- a/packages/experimental/cua-windows/README.zh.md +++ b/packages/experimental/cua-windows/README.zh.md @@ -65,7 +65,7 @@ kind: "package-reference" #### 模型看到什么 -程序可以读取应用和窗口标识、观察结果及动作结果。仅执行选择操作不会提供辅助功能树。程序成功后,提醒会列出仍按住的键和鼠标按钮、所属窗口和桌面输入方式。一条连接持有按键或鼠标按钮时,其他连接仍可使用不同的键或按钮。程序异常、取消、重置和断连时,按派发顺序的反序释放这条连接持有的输入。 +程序可以读取应用和窗口标识、观察结果及动作结果。仅执行选择操作不会提供辅助功能树。程序成功后,提醒会列出仍按住的键和鼠标按钮、所属窗口和桌面输入方式。一条连接持有按键或鼠标按钮时,其他连接仍可使用不同的键或按钮。程序异常、取消或重置时会请求按派发顺序的反序释放。断连时,helper 会在关闭时限内最后尝试一次。失败或超时后,它会静默丢弃这条连接的持有记录。 #### Token 影响 @@ -83,7 +83,7 @@ kind: "package-reference" - 悬停、点击、滚动和拖拽使用系统指针。`requireSystemInputApproval` 不会为 Windows 操作弹出单独的指针授权提示。 - 拖拽只检查起点处最上层的窗口。若其他应用遮住路径或终点,即使目标仍在前台,也可能把内容拖到其他应用。 - 持有提醒和清理只依据 helper 自己派发的输入。如果你也按住同一个键或按钮,helper 之后发送的 up 可能打断你的按压。 -- Windows 通过桌面派发输入。焦点变化或原窗口关闭后,确认释放表示桌面接受了 up,原窗口可能收不到该事件。释放时直接发送保存的 up 事件,无需检查当前前台窗口或锁屏状态。显式 up 返回 `foregroundChanged: null`。若 Windows 在清理时拒绝 up,本任务不能继续使用 CUA。请先检查桌面,再开始新任务。 +- Windows 通过桌面派发输入。焦点变化或原窗口关闭后,确认释放表示桌面接受了 up,原窗口可能收不到该事件。释放时直接发送保存的 up 事件,无需检查当前前台窗口或锁屏状态。显式 up 返回 `foregroundChanged: null`。若 Windows 在处理显式清理请求时拒绝 up,本任务不能继续使用 CUA。请先检查桌面,再开始新任务。 - 清理完整动作内的临时输入时,helper 不检查每个按键或鼠标按钮的释放结果。操作失败后如有按键或按钮仍处于按下状态,请先手动释放。 - helper 的身份摘要只覆盖 exe。同一 apphost 搭配不同 DLL 时可能复用旧服务。重新构建前请先关闭使用同一输出目录的 Host,避免文件被占用。 - Windows 握手要求 `maxClickHoldMs` 为正整数。设为 0 会使连接以 `INVALID_CONFIG` 失败,连普通点击和状态查询也不可用。 diff --git a/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs b/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs index a374db5376..a3fcba8c11 100644 --- a/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs +++ b/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs @@ -291,14 +291,8 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA finally { queue.Release(); } } - internal async Task ReleaseConnection(ClientState state, int graceMs) - { - if (!inputs.HasConnection(state.Connection)) return; - using var deadline = new CancellationTokenSource(graceMs); - await queue.WaitAsync(deadline.Token); - try { inputs.Release(state.Connection, deadline.Token); } - finally { queue.Release(); } - } + internal Task ReleaseConnection(ClientState state, int graceMs) => + inputs.ReleaseOnDisconnect(state.Connection, queue, graceMs); public ValueTask DisposeAsync() { diff --git a/packages/experimental/cua-windows/native/entry/HeldInputs.cs b/packages/experimental/cua-windows/native/entry/HeldInputs.cs index 56ca5b8807..1ba8f89d10 100644 --- a/packages/experimental/cua-windows/native/entry/HeldInputs.cs +++ b/packages/experimental/cua-windows/native/entry/HeldInputs.cs @@ -71,9 +71,23 @@ internal sealed class HeldInputs(Action send) return pressed.Where(press => press.Connection == connection).Select(press => press.Describe()).ToArray(); } - internal bool HasConnection(Guid connection) + internal async Task ReleaseOnDisconnect(Guid connection, SemaphoreSlim desktopQueue, int graceMs) { - lock (gate) return pressed.Exists(press => press.Connection == connection); + lock (gate) + if (!pressed.Exists(press => press.Connection == connection)) return; + + using var deadline = new CancellationTokenSource(graceMs); + try + { + await desktopQueue.WaitAsync(deadline.Token); + try { Release(connection, deadline.Token); } + finally { desktopQueue.Release(); } + } + catch (Exception error) + { + _ = error; // The disconnected owner cannot retry or receive a cleanup result. + lock (gate) pressed.RemoveAll(press => press.Connection == connection); + } } internal object[] Release(Guid connection, CancellationToken cancellation) diff --git a/packages/experimental/cua-windows/native/entry/NativeServer.cs b/packages/experimental/cua-windows/native/entry/NativeServer.cs index 9310b1dd27..2b4941c723 100644 --- a/packages/experimental/cua-windows/native/entry/NativeServer.cs +++ b/packages/experimental/cua-windows/native/entry/NativeServer.cs @@ -169,12 +169,7 @@ internal static class NativeServer finally { cancellation?.Dispose(); - try { await executor.ReleaseConnection(state, cleanupTimeoutMs); } - catch (Exception error) - { - Report("INPUT_CLEANUP_UNCONFIRMED", error); - throw; - } + await executor.ReleaseConnection(state, cleanupTimeoutMs); } state.Clear(); if (closeRequested) diff --git a/packages/experimental/cua-windows/native/tests/HeldInputChecks.cs b/packages/experimental/cua-windows/native/tests/HeldInputChecks.cs index d711dd6c7f..3b3b017ef3 100644 --- a/packages/experimental/cua-windows/native/tests/HeldInputChecks.cs +++ b/packages/experimental/cua-windows/native/tests/HeldInputChecks.cs @@ -78,8 +78,24 @@ internal static class HeldInputChecks check(described.GetArrayLength() == 1 && described[0].GetProperty("key").GetString() == "w", "The reminder still reports only the helper's W down"); var count = events.Count; - check(inputs.Release(a, default).Length == 1 && events.Skip(count).SequenceEqual(["87:up"]), + using var desktopQueue = new SemaphoreSlim(1, 1); + inputs.ReleaseOnDisconnect(a, desktopQueue, 1000).GetAwaiter().GetResult(); + check(inputs.Get(a).Length == 0 && events.Skip(count).SequenceEqual(["87:up"]), "Disconnect retries the helper's W release and leaves D alone"); - check(!inputs.HasConnection(a), "Accepted release removes the connection's last hold"); + + Key(b, 68, "d"); + foreach (var occupied in new[] { false, true }) + { + Key(a, 87, "w"); + if (occupied) desktopQueue.Wait(); + blocked = !occupied; + inputs.ReleaseOnDisconnect(a, desktopQueue, occupied ? 0 : 1000).GetAwaiter().GetResult(); + blocked = false; + check(inputs.Get(a).Length == 0 && inputs.Get(b).Length == 1, + "Refused or expired disconnect cleanup drops only the disconnected owner's records"); + if (occupied) desktopQueue.Release(); + } + check(Key(b, 87, "w"), "The remaining connection can use W after disconnect cleanup fails"); + inputs.Release(b, default); } } From e7a81f4ae4e3f50d9b132ce6b88a1c34a9fc44e8 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 20 Nov 2026 18:36:56 +0800 Subject: [PATCH 73/73] Record held-input notices after the window activity notice format --- .../2026-11-19-cua-input-notices.md | 16 ++++----- .../2026-11-19-cua-input-notices.schema.json | 36 ++++++++++--------- .../2026-11-19-cua-input-notices.zh.md | 16 ++++----- 3 files changed, 35 insertions(+), 33 deletions(-) diff --git a/docs/persistence-changes/2026-11-19-cua-input-notices.md b/docs/persistence-changes/2026-11-19-cua-input-notices.md index 579d0e99fd..d65afe1035 100644 --- a/docs/persistence-changes/2026-11-19-cua-input-notices.md +++ b/docs/persistence-changes/2026-11-19-cua-input-notices.md @@ -27,20 +27,20 @@ id: 2026-11-19-cua-input-notices baseline: false changes: - root: "event:agent/inbox/spliced" - previous: "2026-10-21-system-section-admissions" - after: "a11e08189f96d25e03ccd0653567670f61acf64906c1c63c90ee9b893738bab7" + previous: "2026-11-18-cua-activity-context" + after: "41b562e6d6c59ac22c023d14fa1ae878bfb4573fe1b1dcb021e58ac2ee6bf049" decision: same-version - root: "event:developer/message" - previous: "2026-10-21-system-section-admissions" - after: "a73ee1696868d73a95bc7b611037794a4e0b5abe2151ddd18164303fe72fb9f4" + previous: "2026-11-18-cua-activity-context" + after: "8ecc75abd481f9eadd4bbe834120662d870e07d0ecc889e8631b03be5089e710" decision: same-version - root: "event:session/title-llm-request" - previous: "2026-10-21-system-section-admissions" - after: "a56439237396867aceecf24eea7328260ea78aa97487dda14cb40db6b0126ec4" + previous: "2026-11-18-cua-activity-context" + after: "64b6ec45d21f5aed32624819c44ba5c918bbe11ca9c464496d9dbe0606dcb829" decision: same-version - root: "event:user/message" - previous: "2026-10-21-system-section-admissions" - after: "6c2bcfd03238f2325c071320efaf8e78a25d430dfaeeba309d0a362f4e92b3a1" + previous: "2026-11-18-cua-activity-context" + after: "b9bcecf9562bc66102dad311fff56c8c0e694d39afa17b39f87a7b88992011c8" decision: same-version ``` diff --git a/docs/persistence-changes/2026-11-19-cua-input-notices.schema.json b/docs/persistence-changes/2026-11-19-cua-input-notices.schema.json index 3115db1be9..0a5d2a84e0 100644 --- a/docs/persistence-changes/2026-11-19-cua-input-notices.schema.json +++ b/docs/persistence-changes/2026-11-19-cua-input-notices.schema.json @@ -1,10 +1,10 @@ { "formatVersion": 2, "roots": [ - {"key":"event:agent/inbox/spliced","kind":"event","event":"agent/inbox/spliced","surface":false,"digest":"a11e08189f96d25e03ccd0653567670f61acf64906c1c63c90ee9b893738bab7"}, - {"key":"event:developer/message","kind":"event","event":"developer/message","surface":true,"digest":"a73ee1696868d73a95bc7b611037794a4e0b5abe2151ddd18164303fe72fb9f4"}, - {"key":"event:session/title-llm-request","kind":"event","event":"session/title-llm-request","surface":false,"digest":"a56439237396867aceecf24eea7328260ea78aa97487dda14cb40db6b0126ec4"}, - {"key":"event:user/message","kind":"event","event":"user/message","surface":true,"digest":"6c2bcfd03238f2325c071320efaf8e78a25d430dfaeeba309d0a362f4e92b3a1"} + {"key":"event:agent/inbox/spliced","kind":"event","event":"agent/inbox/spliced","surface":false,"digest":"41b562e6d6c59ac22c023d14fa1ae878bfb4573fe1b1dcb021e58ac2ee6bf049"}, + {"key":"event:developer/message","kind":"event","event":"developer/message","surface":true,"digest":"8ecc75abd481f9eadd4bbe834120662d870e07d0ecc889e8631b03be5089e710"}, + {"key":"event:session/title-llm-request","kind":"event","event":"session/title-llm-request","surface":false,"digest":"64b6ec45d21f5aed32624819c44ba5c918bbe11ca9c464496d9dbe0606dcb829"}, + {"key":"event:user/message","kind":"event","event":"user/message","surface":true,"digest":"b9bcecf9562bc66102dad311fff56c8c0e694d39afa17b39f87a7b88992011c8"} ], "types": [], "nodes": { @@ -24,6 +24,7 @@ "11638dc58a31496f": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, "12d5808fac1996b9": {"kind":"object","properties":[{"name":"attachment","type":"b0b0eb1b16490f6b","optional":false},{"name":"offloaded","type":"dacf3d5f3e4ff619","optional":true},{"name":"type","type":"fb8b6a2e53cb9cf4","optional":false}],"indices":[]}, "1379f0b72275994d": {"kind":"literal","value":"developer/message"}, + "14e81f18050da9ee": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"589d0d91239681f8","optional":false},{"name":"source","type":"c519fc9b5b12fa24","optional":false,"compatibility":{"version":1,"policy":"session-source-attribution","binding":"session.developer-message.source","discriminator":"kind","unknownKinds":"preserve","attributionKinds":["action-cards","tmux-context","user-question-reply","working-directory"]}}],"indices":[]}, "16d0507cb94b4cfc": {"kind":"literal","value":"relay"}, "1922cd79a70806c1": {"kind":"literal","value":"skill-invocation"}, "1938c8c20f1cba7c": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false}],"indices":[]}, @@ -40,12 +41,12 @@ "24b10f7cdae64928": {"kind":"literal","value":"runtime-context"}, "24ce31aa528272e5": {"kind":"object","properties":[{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, "260523b412c19ad8": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false}],"indices":[]}, + "26d2d4da493daea9": {"kind":"array","element":"b72ba9c86f4510fc"}, "2765e9119edf5816": {"kind":"literal","value":"model"}, "277b61f9c6f81704": {"kind":"literal","value":"file"}, "28936c614bd4e7e2": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, "290f32bfd81ff85a": {"kind":"object","properties":[{"name":"kind","type":"23af3759678a30de","optional":false}],"indices":[]}, "297fbd8067d7815a": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false}],"indices":[]}, - "2a8e707a5f5c273d": {"kind":"union","types":["04c12e59a9ed4d7a","4b259f7f8f0a44ad","dd85d6ce8245be2b","ed9c093c07b11934","fa87537f4a9c1e25"]}, "2aad1179f9576314": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, "2ab12a0e345658f9": {"kind":"array","element":"83da72c6857601c7"}, "2e4debca12f2c449": {"kind":"literal","value":"team-message"}, @@ -56,7 +57,6 @@ "3247e566f4340029": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "335e242de1fcc17b": {"kind":"union","types":["bcf0caf62d964b2f","e438a9d4fb883b3e"]}, "383cf73ae4748e5b": {"kind":"literal","value":"recall"}, - "3a012c110d7a2acb": {"kind":"object","properties":[{"name":"inserted","type":"842c4a0ea26c7302","optional":false},{"name":"outcome","type":"d4e4d575abeb4b72","optional":true},{"name":"removedCount","type":"0657d3ca5ac4e7bf","optional":true},{"name":"start","type":"0657d3ca5ac4e7bf","optional":false},{"name":"target","type":"96f4a9c81fc0f940","optional":false}],"indices":[]}, "3b04790e08b35241": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, "3b4f2c9ef2c1217e": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false}],"indices":[]}, "3bd652ebfa8726b3": {"kind":"union","types":["0657d3ca5ac4e7bf","938f7c7357bc403e"]}, @@ -66,6 +66,7 @@ "3e2ece4967cfebe9": {"kind":"literal","value":"next-step"}, "3f74ba74acd10644": {"kind":"literal","value":"image/jpeg"}, "408927267422a7b2": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, + "41b562e6d6c59ac2": {"kind":"object","properties":[{"name":"data","type":"72258a6fae4af8fd","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"829a2fb3be6efd4b","optional":false}],"indices":[]}, "43e311235aa537df": {"kind":"object","properties":[{"name":"toolName","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"83d6916021eede8f","optional":false}],"indices":[]}, "45f005e6bbb76452": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "4902846b72aabae5": {"kind":"literal","value":"retired"}, @@ -74,7 +75,6 @@ "4a561c111a78d452": {"kind":"literal","value":"refusal"}, "4a9bef9f27a94252": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"82470020b5bfcb1a","optional":false},{"name":"senderSessionId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "4b259f7f8f0a44ad": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"isError","type":"aa93010d0e521ad7","optional":true},{"name":"role","type":"a13d8f379222ece8","optional":false},{"name":"source","type":"d9c462b9f62fdd3e","optional":false},{"name":"toolCallId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, - "4c9da244fc4ca830": {"kind":"object","properties":[{"name":"maxTokens","type":"0657d3ca5ac4e7bf","optional":false},{"name":"messageSeqs","type":"5d03ba38734809bc","optional":false},{"name":"messages","type":"875338be4eab9491","optional":false},{"name":"reasoningEffort","type":"4cd48f3e5108bd6e","optional":true},{"name":"route","type":"07e1a58c58b593f5","optional":false},{"name":"system","type":"4cd48f3e5108bd6e","optional":false},{"name":"titleProvider","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "4cd48f3e5108bd6e": {"kind":"primitive","type":"string"}, "4d60dddaa65d3da8": {"kind":"object","properties":[{"name":"actor","type":"0a92c5bdfa06c2e2","optional":false},{"name":"kind","type":"6ba7edb6447b6a3e","optional":false},{"name":"shareId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "4e44c9118152f682": {"kind":"literal","value":"text"}, @@ -84,6 +84,7 @@ "52c6113cb0e53f34": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, "53cf1704ae0709c7": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, "5654685d7557ec74": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "566ff6353402bf04": {"kind":"literal","value":"cua-activity"}, "58015da1c1950a66": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false}],"indices":[]}, "587bb11da730e06a": {"kind":"literal","value":"session/title-llm-request"}, "589d0d91239681f8": {"kind":"literal","value":"developer"}, @@ -91,6 +92,7 @@ "5b7abd24d8a133e7": {"kind":"union","types":["792eb6cb1f6bed83","a408aa610f991ff3"]}, "5bb69b88517f6214": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "5bc66269cfaf614c": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false}],"indices":[]}, + "5bcaeed5facdbccc": {"kind":"array","element":"dff922ce762afdc7"}, "5cdbf342b7748d15": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false}],"indices":[]}, "5d03ba38734809bc": {"kind":"array","element":"0657d3ca5ac4e7bf"}, "5d7a64ed6aac5551": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false}],"indices":[]}, @@ -98,13 +100,13 @@ "6292bcbedaa97fea": {"kind":"object","properties":[{"name":"kind","type":"f68c335306535a00","optional":false}],"indices":[]}, "62ecb62dc0fe1b5e": {"kind":"literal","value":"next-turn"}, "63ba8895cc09e469": {"kind":"literal","value":"retry"}, + "64b6ec45d21f5aed": {"kind":"object","properties":[{"name":"data","type":"86a9b7da960c2a98","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"587bb11da730e06a","optional":false}],"indices":[]}, "65d583e66518c523": {"kind":"object","properties":[{"name":"entries","type":"aba175fb20ffc711","optional":false},{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"incomplete","type":"dacf3d5f3e4ff619","optional":true},{"name":"kind","type":"6ebcc2dbec9f2dab","optional":false},{"name":"update","type":"dacf3d5f3e4ff619","optional":true}],"indices":[]}, "672c4aa2a9b736e3": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"1922cd79a70806c1","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "68141cbe3994a5ff": {"kind":"literal","value":"max-tokens"}, "68f44f59e91c4139": {"kind":"literal","value":"user"}, "6b23ed9ce1b397e6": {"kind":"literal","value":"compact-checkpoint"}, "6ba7edb6447b6a3e": {"kind":"literal","value":"share-viewer"}, - "6c2bcfd03238f232": {"kind":"object","properties":[{"name":"data","type":"dd85d6ce8245be2b","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sourceEventSeqs","type":"5d03ba38734809bc","optional":true},{"name":"surfaceOp","type":"335e242de1fcc17b","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"de25352d2dc41963","optional":false}],"indices":[]}, "6ccb6bc423fb3952": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "6ea608bdc8a7a63d": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false}],"indices":[]}, "6ebcc2dbec9f2dab": {"kind":"literal","value":"skill-catalog"}, @@ -112,16 +114,18 @@ "6f44f32be9bcd9a8": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false}],"indices":[]}, "6f9e00383836275e": {"kind":"literal","value":"snapshot"}, "719c51f67074f970": {"kind":"object","properties":[{"name":"kind","type":"2765e9119edf5816","optional":false},{"name":"model","type":"4cd48f3e5108bd6e","optional":false},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false},{"name":"replayState","type":"bbc5696e3f13c758","optional":true}],"indices":[]}, + "72258a6fae4af8fd": {"kind":"object","properties":[{"name":"inserted","type":"26d2d4da493daea9","optional":false},{"name":"outcome","type":"d4e4d575abeb4b72","optional":true},{"name":"removedCount","type":"0657d3ca5ac4e7bf","optional":true},{"name":"start","type":"0657d3ca5ac4e7bf","optional":false},{"name":"target","type":"96f4a9c81fc0f940","optional":false}],"indices":[]}, "7382c4fc95fe8c5d": {"kind":"literal","value":"remove"}, "7554565be416b034": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false}],"indices":[]}, "756b5e23a5cb2c7f": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false}],"indices":[]}, - "785bf331000a35e6": {"kind":"union","types":["0203243b72fc867a","022623b9ef98ec47","02b2c23f2d94b028","0ed8d1108fe7a5e1","0eeb17e1df89b1eb","11638dc58a31496f","1938c8c20f1cba7c","1e709346005826eb","1fdad624334d3548","2152caf1a71e588e","2235d957bf4b7c6c","224aa11d4d5f88c4","24ce31aa528272e5","260523b412c19ad8","28936c614bd4e7e2","290f32bfd81ff85a","297fbd8067d7815a","2aad1179f9576314","312aee2f0c42aabb","31907de956375182","3247e566f4340029","3b04790e08b35241","3b4f2c9ef2c1217e","3bdb8dc6989655b0","3d1339bcc98cb537","408927267422a7b2","45f005e6bbb76452","4991dfc415c9efeb","49dab019d00e8c26","4a9bef9f27a94252","52c6113cb0e53f34","53cf1704ae0709c7","5654685d7557ec74","58015da1c1950a66","5bb69b88517f6214","5bc66269cfaf614c","5cdbf342b7748d15","5d7a64ed6aac5551","6085488d223aeffd","6292bcbedaa97fea","65d583e66518c523","672c4aa2a9b736e3","6ccb6bc423fb3952","6ea608bdc8a7a63d","6f22a9d02b9a1f11","6f44f32be9bcd9a8","719c51f67074f970","7554565be416b034","756b5e23a5cb2c7f","7df62978a2b7de85","7eaef7a763ba5b94","7f959241c24128b4","80677c8c8b804189","825ca23416b1ea9d","8338ee303e2bd448","848639f8787f035b","854db3efdfb0cd39","85fe96bf15d5c755","8620189c8e335827","87b1a33564b9a4d6","88841202942c7683","8a046b52331959aa","8a2e3e7a523e622b","8c1c4f72755a78ea","8c627d7a45fa406c","8f1062573ea91841","8f324cea3916c051","8fcb0b44a575e998","96bfb916a727cd44","99135d8a39379779","99f0e98184709ad1","9edc162949abf93b","9f65c43e340bba31","a15a19ef63cf5d1b","a16e567c8cd2c55c","a2066bd52f61218b","a3c6f1ea38e9a61d","a4afec59b75aad5d","aa2bf9e82b9fdeb9","aae343bc3d663c83","ada310bf0bdb8fed","ade057f4fdc387ae","b062078e899958f9","b2a5c8c008a31e3d","b3681c026a0b98e9","b4ec0af39fd52ed9","b613f83572fe2fbf","b6f94c17dd9bbd7c","b70f3e81fe11b7a5","b79641a9d25e7566","b8ed92a5ca59733f","ba2a1a8f194b1bb2","ba4c40b4381e0dcd","baccc97ec34be6c4","c5228b7a55498d84","c55827fba7018198","cb1c8959e1726f82","cda2345a9be9d139","ce6e647c9e653b5d","d215701afb7aafbf","d85590a5675c6e2f","d9c462b9f62fdd3e","db06ef35b27a3842","dba54c09c6e7aafc","dd00cdccd0ba487b","dd5ee8762bd8a14b","dd6cc2bb2a8f2824","dde0cdf9d426768b","deaae5cd30987d4f","e7f4cbb3a57f4cbd","edbbfff1128099fd","ee577a0cc18664c9","f230c0b583e23b25","f29d63336e8266d8","f4a66f654996c093","f56c5b59ca016131","f6329fb30c7ea801","f6605d6c57933aea","f6afe41e3926f422","f7283223aacdc39b","f97f47b0eb87905e","fcf81d3c58c13593","fe1a7acdeed4d0f5"]}, "78a9be340090b735": {"kind":"literal","value":"tmux-context"}, "792eb6cb1f6bed83": {"kind":"object","properties":[{"name":"contentIndex","type":"0657d3ca5ac4e7bf","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":false},{"name":"noticeIndex","type":"5d03ba38734809bc","optional":true},{"name":"order","type":"0657d3ca5ac4e7bf","optional":false},{"name":"state","type":"c8e6f48878cc2a2f","optional":false}],"indices":[]}, "7b1ce60193fa8b69": {"kind":"literal","value":"working-directory"}, + "7dd505cd3b36da21": {"kind":"object","properties":[{"name":"headerSeq","type":"0657d3ca5ac4e7bf","optional":true},{"name":"message","type":"14e81f18050da9ee","optional":false},{"name":"step","type":"0657d3ca5ac4e7bf","optional":false},{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "7df62978a2b7de85": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false}],"indices":[]}, "7eaef7a763ba5b94": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false}],"indices":[]}, "7f13860ee89a2d35": {"kind":"literal","value":"session-reference"}, + "7f7cc4903d822e9a": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"566ff6353402bf04","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "7f959241c24128b4": {"kind":"object","properties":[{"name":"goalId","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"b815d7b91cdd9fc6","optional":false},{"name":"revision","type":"0657d3ca5ac4e7bf","optional":false},{"name":"round","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "8064c03c87c357fd": {"kind":"union","types":["12d5808fac1996b9","43e311235aa537df","4e88776858652856","814d9434e1ddf907","8e611bf46821e500","c1f0f17b6493b85d","f2da0f27c1e6add5"]}, "80677c8c8b804189": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false}],"indices":[]}, @@ -135,7 +139,6 @@ "8338ee303e2bd448": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "83d6916021eede8f": {"kind":"literal","value":"tool-removal"}, "83da72c6857601c7": {"kind":"object","properties":[{"name":"action","type":"904bf499d98be4a3","optional":false},{"name":"digest","type":"4cd48f3e5108bd6e","optional":true},{"name":"path","type":"4cd48f3e5108bd6e","optional":false},{"name":"scope","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, - "842c4a0ea26c7302": {"kind":"array","element":"dd85d6ce8245be2b"}, "848639f8787f035b": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"bf16d2e98a7f1389","optional":false},{"name":"senderSessionId","type":"4cd48f3e5108bd6e","optional":false},{"name":"stopReason","type":"866f7b2dbdc5b421","optional":true},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "854db3efdfb0cd39": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "85d6d96ff8842974": {"kind":"literal","value":"answered"}, @@ -143,8 +146,8 @@ "85fe96bf15d5c755": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false}],"indices":[]}, "8620189c8e335827": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false}],"indices":[]}, "866f7b2dbdc5b421": {"kind":"union","types":["1e0b0b66b6f0c53f","1ebc6f9ff3aa9e3a","4a561c111a78d452","68141cbe3994a5ff","a2be0f0cb59f0d4a"]}, + "86a9b7da960c2a98": {"kind":"object","properties":[{"name":"maxTokens","type":"0657d3ca5ac4e7bf","optional":false},{"name":"messageSeqs","type":"5d03ba38734809bc","optional":false},{"name":"messages","type":"5bcaeed5facdbccc","optional":false},{"name":"reasoningEffort","type":"4cd48f3e5108bd6e","optional":true},{"name":"route","type":"07e1a58c58b593f5","optional":false},{"name":"system","type":"4cd48f3e5108bd6e","optional":false},{"name":"titleProvider","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "86e1e384495ee09a": {"kind":"object","properties":[{"name":"name","type":"4cd48f3e5108bd6e","optional":false},{"name":"text","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, - "875338be4eab9491": {"kind":"array","element":"2a8e707a5f5c273d"}, "87b1a33564b9a4d6": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false}],"indices":[]}, "88841202942c7683": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, "8a046b52331959aa": {"kind":"object","properties":[{"name":"kind","type":"78a9be340090b735","optional":false}],"indices":[]}, @@ -154,6 +157,7 @@ "8c627d7a45fa406c": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "8decd4949d9ee4ad": {"kind":"array","element":"5b7abd24d8a133e7"}, "8e611bf46821e500": {"kind":"object","properties":[{"name":"tool","type":"fcf427290c6213c2","optional":true},{"name":"toolName","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"85f9b505b7bdff1f","optional":false}],"indices":[]}, + "8ecc75abd481f9ea": {"kind":"object","properties":[{"name":"data","type":"7dd505cd3b36da21","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sourceEventSeqs","type":"5d03ba38734809bc","optional":true},{"name":"surfaceOp","type":"335e242de1fcc17b","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"1379f0b72275994d","optional":false}],"indices":[]}, "8f1062573ea91841": {"kind":"object","properties":[{"name":"clientTimeZone","type":"4cd48f3e5108bd6e","optional":true},{"name":"kind","type":"63ba8895cc09e469","optional":false},{"name":"principal","type":"824a4aad44a54e24","optional":true},{"name":"rpcId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "8f324cea3916c051": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false}],"indices":[]}, "8fcb0b44a575e998": {"kind":"object","properties":[{"name":"kind","type":"a720757f704a2512","optional":false}],"indices":[]}, @@ -171,7 +175,6 @@ "9d42da116fccdc39": {"kind":"literal","value":"cua-held-inputs"}, "9edc162949abf93b": {"kind":"object","properties":[{"name":"deliveryId","type":"4cd48f3e5108bd6e","optional":false},{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"db6c5246911d47a7","optional":false},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false},{"name":"ruleId","type":"4cd48f3e5108bd6e","optional":false},{"name":"source","type":"4cd48f3e5108bd6e","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "9f65c43e340bba31": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false}],"indices":[]}, - "a11e08189f96d25e": {"kind":"object","properties":[{"name":"data","type":"3a012c110d7a2acb","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"829a2fb3be6efd4b","optional":false}],"indices":[]}, "a13d8f379222ece8": {"kind":"literal","value":"tool"}, "a15a19ef63cf5d1b": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false}],"indices":[]}, "a16e567c8cd2c55c": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false}],"indices":[]}, @@ -180,10 +183,8 @@ "a3c6f1ea38e9a61d": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "a408aa610f991ff3": {"kind":"object","properties":[{"name":"name","type":"4cd48f3e5108bd6e","optional":false},{"name":"noticeIndex","type":"5d03ba38734809bc","optional":true},{"name":"state","type":"4902846b72aabae5","optional":false}],"indices":[]}, "a4afec59b75aad5d": {"kind":"object","properties":[{"name":"clientTimeZone","type":"4cd48f3e5108bd6e","optional":true},{"name":"kind","type":"68f44f59e91c4139","optional":false},{"name":"principal","type":"824a4aad44a54e24","optional":true},{"name":"rpcId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, - "a56439237396867a": {"kind":"object","properties":[{"name":"data","type":"4c9da244fc4ca830","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"587bb11da730e06a","optional":false}],"indices":[]}, "a6816f39283ae26f": {"kind":"literal","value":"cua-inputs-released"}, "a720757f704a2512": {"kind":"literal","value":"tool-registry"}, - "a73ee1696868d73a": {"kind":"object","properties":[{"name":"data","type":"b1130980abc639f4","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sourceEventSeqs","type":"5d03ba38734809bc","optional":true},{"name":"surfaceOp","type":"335e242de1fcc17b","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"1379f0b72275994d","optional":false}],"indices":[]}, "a9059a81430b3207": {"kind":"literal","value":"hooks-claude-code"}, "aa2bf9e82b9fdeb9": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false}],"indices":[]}, "aa93010d0e521ad7": {"kind":"primitive","type":"boolean"}, @@ -194,7 +195,6 @@ "aec150797b655c5f": {"kind":"literal","value":"catalog"}, "b062078e899958f9": {"kind":"object","properties":[{"name":"kind","type":"1f1385dbc3e875c0","optional":false}],"indices":[]}, "b0b0eb1b16490f6b": {"kind":"object","properties":[{"name":"attachmentId","type":"4cd48f3e5108bd6e","optional":false},{"name":"bytes","type":"0657d3ca5ac4e7bf","optional":false},{"name":"height","type":"0657d3ca5ac4e7bf","optional":false},{"name":"mediaType","type":"2f1e6a7ebace43d7","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":true},{"name":"originalDimensions","type":"0f46153645c29784","optional":true},{"name":"width","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, - "b1130980abc639f4": {"kind":"object","properties":[{"name":"headerSeq","type":"0657d3ca5ac4e7bf","optional":true},{"name":"message","type":"ed9c093c07b11934","optional":false},{"name":"step","type":"0657d3ca5ac4e7bf","optional":false},{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "b2a5c8c008a31e3d": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false}],"indices":[]}, "b3681c026a0b98e9": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "b4ec0af39fd52ed9": {"kind":"object","properties":[{"name":"kind","type":"bb94f3217aa56c88","optional":false}],"indices":[]}, @@ -202,10 +202,12 @@ "b613f83572fe2fbf": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "b6f94c17dd9bbd7c": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false}],"indices":[]}, "b70f3e81fe11b7a5": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false}],"indices":[]}, + "b72ba9c86f4510fc": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"68f44f59e91c4139","optional":false},{"name":"source","type":"c519fc9b5b12fa24","optional":false,"compatibility":{"version":1,"policy":"session-source-attribution","binding":"session.user-message.source","discriminator":"kind","unknownKinds":"preserve","attributionKinds":["action-cards","tmux-context","user-question-reply","working-directory"]}}],"indices":[]}, "b765ee31033cea46": {"kind":"literal","value":"set"}, "b79641a9d25e7566": {"kind":"object","properties":[{"name":"kind","type":"8067b0d232c350f1","optional":false}],"indices":[]}, "b815d7b91cdd9fc6": {"kind":"literal","value":"goal"}, "b8ed92a5ca59733f": {"kind":"object","properties":[{"name":"clientTimeZone","type":"4cd48f3e5108bd6e","optional":true},{"name":"kind","type":"68f44f59e91c4139","optional":false}],"indices":[]}, + "b9bcecf9562bc661": {"kind":"object","properties":[{"name":"data","type":"b72ba9c86f4510fc","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sourceEventSeqs","type":"5d03ba38734809bc","optional":true},{"name":"surfaceOp","type":"335e242de1fcc17b","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"de25352d2dc41963","optional":false}],"indices":[]}, "ba2a1a8f194b1bb2": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "ba4c40b4381e0dcd": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, "baccc97ec34be6c4": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, @@ -214,6 +216,7 @@ "bcf0caf62d964b2f": {"kind":"object","properties":[{"name":"endSeq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"op","type":"f6cb462f808309e3","optional":false},{"name":"startSeq","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "bf16d2e98a7f1389": {"kind":"literal","value":"subagent-settled"}, "c1f0f17b6493b85d": {"kind":"object","properties":[{"name":"arguments","type":"4cd48f3e5108bd6e","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"1f0133217eeeffd8","optional":false}],"indices":[]}, + "c519fc9b5b12fa24": {"kind":"union","types":["0203243b72fc867a","022623b9ef98ec47","02b2c23f2d94b028","0ed8d1108fe7a5e1","0eeb17e1df89b1eb","11638dc58a31496f","1938c8c20f1cba7c","1e709346005826eb","1fdad624334d3548","2152caf1a71e588e","2235d957bf4b7c6c","224aa11d4d5f88c4","24ce31aa528272e5","260523b412c19ad8","28936c614bd4e7e2","290f32bfd81ff85a","297fbd8067d7815a","2aad1179f9576314","312aee2f0c42aabb","31907de956375182","3247e566f4340029","3b04790e08b35241","3b4f2c9ef2c1217e","3bdb8dc6989655b0","3d1339bcc98cb537","408927267422a7b2","45f005e6bbb76452","4991dfc415c9efeb","49dab019d00e8c26","4a9bef9f27a94252","52c6113cb0e53f34","53cf1704ae0709c7","5654685d7557ec74","58015da1c1950a66","5bb69b88517f6214","5bc66269cfaf614c","5cdbf342b7748d15","5d7a64ed6aac5551","6085488d223aeffd","6292bcbedaa97fea","65d583e66518c523","672c4aa2a9b736e3","6ccb6bc423fb3952","6ea608bdc8a7a63d","6f22a9d02b9a1f11","6f44f32be9bcd9a8","719c51f67074f970","7554565be416b034","756b5e23a5cb2c7f","7df62978a2b7de85","7eaef7a763ba5b94","7f7cc4903d822e9a","7f959241c24128b4","80677c8c8b804189","825ca23416b1ea9d","8338ee303e2bd448","848639f8787f035b","854db3efdfb0cd39","85fe96bf15d5c755","8620189c8e335827","87b1a33564b9a4d6","88841202942c7683","8a046b52331959aa","8a2e3e7a523e622b","8c1c4f72755a78ea","8c627d7a45fa406c","8f1062573ea91841","8f324cea3916c051","8fcb0b44a575e998","96bfb916a727cd44","99135d8a39379779","99f0e98184709ad1","9edc162949abf93b","9f65c43e340bba31","a15a19ef63cf5d1b","a16e567c8cd2c55c","a2066bd52f61218b","a3c6f1ea38e9a61d","a4afec59b75aad5d","aa2bf9e82b9fdeb9","aae343bc3d663c83","ada310bf0bdb8fed","ade057f4fdc387ae","b062078e899958f9","b2a5c8c008a31e3d","b3681c026a0b98e9","b4ec0af39fd52ed9","b613f83572fe2fbf","b6f94c17dd9bbd7c","b70f3e81fe11b7a5","b79641a9d25e7566","b8ed92a5ca59733f","ba2a1a8f194b1bb2","ba4c40b4381e0dcd","baccc97ec34be6c4","c5228b7a55498d84","c55827fba7018198","cb1c8959e1726f82","cda2345a9be9d139","ce6e647c9e653b5d","d215701afb7aafbf","d85590a5675c6e2f","d9c462b9f62fdd3e","db06ef35b27a3842","dba54c09c6e7aafc","dd00cdccd0ba487b","dd5ee8762bd8a14b","dd6cc2bb2a8f2824","dde0cdf9d426768b","deaae5cd30987d4f","e7f4cbb3a57f4cbd","edbbfff1128099fd","ee577a0cc18664c9","f230c0b583e23b25","f29d63336e8266d8","f4a66f654996c093","f56c5b59ca016131","f6329fb30c7ea801","f6605d6c57933aea","f6afe41e3926f422","f7283223aacdc39b","f97f47b0eb87905e","fcf81d3c58c13593","fe1a7acdeed4d0f5"]}, "c5228b7a55498d84": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, "c55827fba7018198": {"kind":"object","properties":[{"name":"callId","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"9645cf93769a6dfb","optional":false},{"name":"outcome","type":"85d6d96ff8842974","optional":false}],"indices":[]}, "c5687b1313206a6f": {"kind":"literal","value":"cordis-host-runner"}, @@ -235,18 +238,17 @@ "dd00cdccd0ba487b": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "dd5ee8762bd8a14b": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, "dd6cc2bb2a8f2824": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, - "dd85d6ce8245be2b": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"68f44f59e91c4139","optional":false},{"name":"source","type":"785bf331000a35e6","optional":false,"compatibility":{"version":1,"policy":"session-source-attribution","binding":"session.user-message.source","discriminator":"kind","unknownKinds":"preserve","attributionKinds":["action-cards","tmux-context","user-question-reply","working-directory"]}}],"indices":[]}, "dde0cdf9d426768b": {"kind":"object","properties":[{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "de25352d2dc41963": {"kind":"literal","value":"user/message"}, "de30b1fa12c75f81": {"kind":"literal","value":"image/gif"}, "deaae5cd30987d4f": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, "deebfc7c62177ea8": {"kind":"object","properties":[{"name":"kind","type":"95a3ffccbf3c8afc","optional":false}],"indices":[]}, "df843efd87c78cf8": {"kind":"array","element":"4f91f187baeabef5"}, + "dff922ce762afdc7": {"kind":"union","types":["04c12e59a9ed4d7a","14e81f18050da9ee","4b259f7f8f0a44ad","b72ba9c86f4510fc","fa87537f4a9c1e25"]}, "e438a9d4fb883b3e": {"kind":"literal","value":"append"}, "e7f4cbb3a57f4cbd": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "e8de0f457fed5b9f": {"kind":"literal","value":"notice"}, "ebb768d85ec87fb6": {"kind":"literal","value":"image/webp"}, - "ed9c093c07b11934": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"589d0d91239681f8","optional":false},{"name":"source","type":"785bf331000a35e6","optional":false,"compatibility":{"version":1,"policy":"session-source-attribution","binding":"session.developer-message.source","discriminator":"kind","unknownKinds":"preserve","attributionKinds":["action-cards","tmux-context","user-question-reply","working-directory"]}}],"indices":[]}, "edbbfff1128099fd": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "ee577a0cc18664c9": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "f19bee84bf3d2090": {"kind":"object","properties":[{"name":"attachmentId","type":"4cd48f3e5108bd6e","optional":false},{"name":"bytes","type":"0657d3ca5ac4e7bf","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, diff --git a/docs/persistence-changes/2026-11-19-cua-input-notices.zh.md b/docs/persistence-changes/2026-11-19-cua-input-notices.zh.md index fea86ebeff..4e837f64e5 100644 --- a/docs/persistence-changes/2026-11-19-cua-input-notices.zh.md +++ b/docs/persistence-changes/2026-11-19-cua-input-notices.zh.md @@ -27,20 +27,20 @@ id: 2026-11-19-cua-input-notices baseline: false changes: - root: "event:agent/inbox/spliced" - previous: "2026-10-21-system-section-admissions" - after: "a11e08189f96d25e03ccd0653567670f61acf64906c1c63c90ee9b893738bab7" + previous: "2026-11-18-cua-activity-context" + after: "41b562e6d6c59ac22c023d14fa1ae878bfb4573fe1b1dcb021e58ac2ee6bf049" decision: same-version - root: "event:developer/message" - previous: "2026-10-21-system-section-admissions" - after: "a73ee1696868d73a95bc7b611037794a4e0b5abe2151ddd18164303fe72fb9f4" + previous: "2026-11-18-cua-activity-context" + after: "8ecc75abd481f9eadd4bbe834120662d870e07d0ecc889e8631b03be5089e710" decision: same-version - root: "event:session/title-llm-request" - previous: "2026-10-21-system-section-admissions" - after: "a56439237396867aceecf24eea7328260ea78aa97487dda14cb40db6b0126ec4" + previous: "2026-11-18-cua-activity-context" + after: "64b6ec45d21f5aed32624819c44ba5c918bbe11ca9c464496d9dbe0606dcb829" decision: same-version - root: "event:user/message" - previous: "2026-10-21-system-section-admissions" - after: "6c2bcfd03238f2325c071320efaf8e78a25d430dfaeeba309d0a362f4e92b3a1" + previous: "2026-11-18-cua-activity-context" + after: "b9bcecf9562bc66102dad311fff56c8c0e694d39afa17b39f87a7b88992011c8" decision: same-version ```