Record confirmed pause releases and discard stale held-state notices

This commit is contained in:
creatixchu committed 2026-11-19 11:16:10 +08:00
1 parent 6a143953f0
commit b7b5a0114e
8 files changed
+129 -16

No files matched your search

+2 -2
View File
@@ -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
+2
View File
@@ -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_<sha256>.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.
+2
View File
@@ -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_<sha256>.json`,摘要对应 profile 的真实目录。每次授权检查在 profile 文件锁内打开并读取最新状态,随后关闭存储域;原生操作使用单独的应用锁。撤销会等待其他进程已获准执行的操作结束;撤销完成后,各进程都拒绝旧句柄。不同电脑或 PID 命名空间不能共享这把锁。
旧 `allowedApps` 只在首次访问存储时导入,迁移后不再应用。确认权限页显示正确后,可以删除旧配置。授权、拒绝和允许再次询问均持久化,页面仍不显示仅对某个会话生效的许可。没有 profile 的独立组合只保留进程内决定;有 profile 但缺少域存储的组合会拒绝授权操作。
+39 -10
View File
@@ -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<typeof heldInputs>, state: 'held' | 'released'): string {
function renderInputs(inputs: z.infer<typeof heldInputs>, 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 ['<system-reminder>', 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 ['<system-reminder>', 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.',
'</system-reminder>'].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<z.infer<typeof heldInputs>> | 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<typeof heldInputs>) => 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<string | undefined> {
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<z.infer<typeof heldInputs>> {
@@ -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)
+3 -1
View File
@@ -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'
+1
View File
@@ -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
}
}
@@ -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<void> = Promise.withResolvers()
f.model.beforeStream = async (index, options) => {
if (index !== 1) return
thinking.resolve()
await new Promise<void>((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<void> = Promise.withResolvers()
const finish: PromiseWithResolvers<void> = Promise.withResolvers()
const released: PromiseWithResolvers<void> = 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'])
})
@@ -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) {