fix(cua): preserve drag release settling and verify pointer state and deltas

This commit is contained in:
creatixchu committed 2026-11-12 15:31:16 +08:00
1 parent 195c6fca26
commit ea9e78dc83
17 files changed
+121 -42

No files matched your search

@@ -45,8 +45,8 @@
en: a2c9acb5a4320dda
zh: e8d1586af60215c4
/deepseek-ai-dsh-cua-macos/known-limitations-and-deferred-work:
en: 58f87b2ee23def70
zh: f7e03371bc06cbfa
en: 7e82191d689581ea
zh: eb1175fd67dd316a
/deepseek-ai-dsh-cua-macos/known-limitations-and-deferred-work/dev-note:
en: b836f01bd0bceb4a
zh: 8122fa08b2aa95fa
@@ -263,6 +263,7 @@ The queue orders individual native requests. Holding an app object does not rese
- Element IDs belong to the application's current accessibility snapshot; a later read replaces them. Screenshots and pointer input require an explicit window object.
- Coordinates use the returned screenshot pixels, including the title bar; `relative: true` selects integers from 0 to 999. Native point conversion is Host-owned. Window movement, application changes and other desktop users can race observations and input.
- macOS Stage Manager can reduce background window bounds and screenshots to thumbnails. Full-window observation and coordinate input in this state are not guaranteed; model guidance requires explaining foreground needs and avoiding repeated focus reclamation.
- System drag checks the selected window at every movement. An input-receiving popup can interrupt the gesture even in the same application. Window checks and event delivery add to the requested movement duration. Modifiers are carried on mouse events. Applications that poll system keyboard state may ignore them.
- Background input depends on private SkyLight symbols; macOS updates can make them unavailable. Validate each target OS version.
- Observed failures include dispatched Unicode text not appearing in Blender and background Command+A not selecting all text in AppKit. Inspect application state after input; a successful tool result confirms dispatch only.
- Source builds default to `ad-hoc` and can require new grants after binary changes. The [developer’s fixed identity](../../../.agents/skills/dsh-cua-macos-signing/SKILL.md) lives outside DSH home; deleting DSH home removes its selection, not the certificate or private key. Release distribution needs a stable Developer ID signature and notarization; the build command accepts `--identity`, and installed packages preserve the distributed signature. The [permission page](../cua/README.md) offers helper authorization and target-application revocation.
@@ -263,6 +263,7 @@ Only if the task cannot be completed without moving the user’s pointer, call a
- 元素 ID 只对应用当前的辅助功能快照有效;之后的读取会替换它们。截图和指针输入都要求显式的窗口对象。
- 坐标使用包含标题栏的返回截图像素;`relative: true` 使用 0~999 的整数,由 Host 换算原生 point。窗口移动、应用变化及其他桌面使用者的操作可能与观察和输入交错。
- macOS 台前调度可能将后台窗口的尺寸与截图变为缩略图,当前无法保证这种状态下的完整画面与坐标输入;模型指引要求说明前台需求并避免反复抢回焦点。
- 系统鼠标拖动的每一步都必须命中所选窗口。同一应用中拦截鼠标的弹窗也会中断手势。检查窗口和投递事件的耗时会计入实际拖动时间。修饰键记录在鼠标事件上。读取系统键盘状态的应用可能无法识别这些修饰键。
- 后台输入依赖私有 SkyLight 符号,macOS 升级可能使其不可用,需在目标系统版本验证。
- 实测 Blender Unicode 输入曾出现分派成功但界面未显示文本,后台 AppKit 的 Command+A 曾未选中全文。输入后必须检查应用状态;工具返回成功只表示已分派。
- 源码构建默认使用 `ad-hoc`,二进制变化后可能需要重新授权。[开发者固定身份](../../../.agents/skills/dsh-cua-macos-signing/SKILL.md)保存在 DSH home 之外;删除 DSH home 只删除选择它的配置,不删除证书和私钥。正式分发应以固定 Developer ID 签名并完成公证;构建命令支持 `--identity` 指定签名身份,安装版保留分发时的签名。[权限页面](../cua/README.zh.md)提供 helper 授权入口和目标应用许可撤销。
@@ -18,14 +18,14 @@
en: f29d74be684f5840
zh: 67233850329d1db1
/dsh-cua-native-helper/request-protocol:
en: a993e9eacf63cceb
zh: 12292c9ba53df2ad
en: cc426543c91bf3f4
zh: 1671aac76cd0bfcc
/dsh-cua-native-helper/observation-and-input:
en: e5c69b1bf5365c98
zh: 0a07a4f246f6fee5
/dsh-cua-native-helper/verification:
en: 908b13b2732c1bec
zh: ac3bbd77ed9a69b8
en: 1f82a29e32eeec25
zh: 0964d7a4a2259ee3
/dsh-cua-native-helper/further-exploration:
en: 265e1927952ce6d7
zh: 7c35d9fd98b6e6c8
@@ -83,7 +83,7 @@ Successful `activate` returns `dispatched` and `foregroundChanged`. A known chan
Every app-targeted operation requires `appHandle` from `getApp` in the same helper. The helper pins the PID and kernel process start time, and invalidates the handle and all of its snapshots after process exit or PID reuse. Calling `getApp` can acquire the replacement process without reactivating old handles. A random per-helper namespace prevents handles from a terminated helper matching those of its replacement. Repeated acquisition of the same live process shares its handle. If this connection already holds a handle for a process started during consent, `launchApp` returns `STALE_APP` and expires only the pending handle. A post-launch inspection failure invalidates the pending handle and preserves the original error. It does not terminate a process already started; launchApp cannot reuse the failed handle.
Stable error codes are `INVALID_REQUEST` (malformed envelope), `INVALID_ARGUMENT` (invalid parameters), `UNSUPPORTED` (unknown operation), `APP_UNAVAILABLE`, `APP_PATH_UNAVAILABLE`, `PROCESS_INSPECTION_FAILED`, `AMBIGUOUS_APP`, `STALE_APP`, `STALE_SNAPSHOT`, `WINDOW_UNAVAILABLE`, `WINDOW_CHANGED`, `PERMISSION_DENIED`, `HOVER_UNAVAILABLE`, `FOREGROUND_REQUIRED` (hover target is not the unobscured foreground window), `PANEL_NOT_READY` (system panel recipient unavailable before input), and `NATIVE_ERROR` (remaining operating-system failures). An error never promises that a partially dispatched input was rolled back. The host must not retry input automatically.
Stable error codes are `INVALID_REQUEST` (malformed envelope), `INVALID_ARGUMENT` (invalid parameters), `UNSUPPORTED` (unknown operation), `APP_UNAVAILABLE`, `APP_PATH_UNAVAILABLE`, `PROCESS_INSPECTION_FAILED`, `AMBIGUOUS_APP`, `STALE_APP`, `STALE_SNAPSHOT`, `WINDOW_UNAVAILABLE`, `WINDOW_CHANGED`, `PERMISSION_DENIED`, `HOVER_UNAVAILABLE`, `FOREGROUND_REQUIRED` (system-pointer input requires a hit on the foreground target window), `INPUT_BUSY` (wait for a held mouse button to be released before requesting a system drag), `PANEL_NOT_READY` (system panel recipient unavailable before input), and `NATIVE_ERROR` (remaining operating-system failures). An error never promises that a partially dispatched input was rolled back. The host must not retry input automatically.
Application selection returns an authorization record to the Host: a SHA-256 digest of the case-sensitive bundle identifier prefixed with `macos:bundle-id:`, display name, optional executable path, and persistable flag. All installations with that identifier share consent, including unsigned and ad-hoc-signed applications. Without a nonempty bundle identifier, both running and stopped applications use SHA-256 of `macos:executable-path:` followed by the symlink-resolved executable path and remain eligible for saved consent. A running bundle identifier remains usable when the process path query fails; the record omits executablePath. Available paths must still match the selection. Without either identity, APP_PATH_UNAVAILABLE reports the path query cause, including its errno, before any target operation. PROCESS_INSPECTION_FAILED means the process instance could not be verified; only ESRCH from process inspection is reported as a missing process. Neither failure triggers an automatic retry. Process IDs and start times validate live handles but do not enter the saved identity. The Host strips this record from model results and obtains human consent before launch, observation or input. This pipe protocol is trusted Host transport, not a sandbox against a separately authorized shell process.
@@ -165,7 +165,7 @@ For text pacing comparisons, use `native/tests/text_input_benchmark.py` with `--
For an independently isolated Electron/Chromium check, run `python3 packages/experimental/cua-macos/native/tests/electron_e2e.py --electron /absolute/path/to/Electron.app/Contents/MacOS/Electron`. Omitting `--electron` uses an already installed desktop workspace runtime. The check never downloads Electron. Its renderer runs with Node integration disabled, context isolation and Chromium sandboxing enabled, private userData/sessionData/log directories, and a local fixture page. Renderer click/input events write independent observations through the main process; all test actions still use the native helper. AX polling waits for actual controls after Chromium accessibility activation. Native and Electron subprocess groups are owned and stopped before temporary files are removed. Optional artifacts include a fixture-only screenshot and private request transcript.
Run `python3 packages/experimental/cua-macos/native/tests/capabilities_e2e.py --helper /absolute/helper --artifacts /private/evidence` to verify a stopped application's discovery and launch, Unicode selection, multiline plain/HTML paste, middle/modifier gestures, overlapping W and D key events, and keypad identities through an isolated AppKit receiver. Add `--keyboard-only` for a background receiver that checks a two-second W+D hold, independent D release, and W cleanup. Add `--click-only` to check click holds, AX routing and cancellation/timeout release in a background fixture without keyboard or clipboard input. It requires existing Accessibility/Screen Recording grants and records the receiver's actual state separately from dispatch results.
Run `python3 packages/experimental/cua-macos/native/tests/capabilities_e2e.py --helper /absolute/helper --artifacts /private/evidence` to verify a stopped application's discovery and launch, Unicode selection, multiline plain/HTML paste, middle/modifier gestures, overlapping W and D key events, and keypad identities through an isolated AppKit receiver. Add `--keyboard-only` for a background receiver that checks a two-second W+D hold, independent D release, and W cleanup. Add `--click-only` to check click holds, AX routing and cancellation/timeout release in a background fixture without keyboard or clipboard input. It requires existing Accessibility/Screen Recording grants and records the receiver's actual state separately from dispatch results. Use `--drag-only` to verify rejection before pressing on a background target, then check event order, held-button state and two-axis deltas in the foreground receiver. Cancellation after the first movement must release exactly once at the last posted point.
Run `python3 packages/experimental/cua-macos/native/tests/paste_e2e.py --artifacts /private/evidence` to verify that an owned AppKit app accepts a background Paste action without reading its data, reports `PASTE_NOT_CONSUMED`, then consumes the same paste in the foreground. The test requires an unlocked Mac and Accessibility permission, activates only its own two applications, and records received actions and text independently of helper replies.
@@ -83,7 +83,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后
每个面向应用的操作都要求使用同一 helper 的 `getApp` 返回的 `appHandle`。helper 固定 PID 和内核进程启动时间,进程退出或 PID 被复用后使句柄及其全部快照失效。再次调用 `getApp` 可取得替代进程,不会重新激活旧句柄。随机的 helper 命名空间防止已终止 helper 的句柄与替代实例重合。重复获取同一存活进程会共享句柄。如果进程在授权期间启动,而当前连接已取得其句柄,`launchApp` 返回 `STALE_APP`,只有待启动句柄失效。启动后检查失败会使待启动句柄失效,并保留原错误;已经启动的进程不会被终止,launchApp 也不能复用失败的句柄。
稳定错误码包括 `INVALID_REQUEST`(信封无效)、`INVALID_ARGUMENT`(参数无效)、`UNSUPPORTED`(操作未知)、`APP_UNAVAILABLE`、`APP_PATH_UNAVAILABLE`、`PROCESS_INSPECTION_FAILED`、`AMBIGUOUS_APP`、`STALE_APP`、`STALE_SNAPSHOT`、`WINDOW_UNAVAILABLE`、`WINDOW_CHANGED`、`PERMISSION_DENIED`、`HOVER_UNAVAILABLE`、`FOREGROUND_REQUIRED`(悬停目标不是未被遮挡的前台窗口)、`PANEL_NOT_READY`(输入前系统面板接收方尚不可用)及 `NATIVE_ERROR`(其余操作系统失败)。错误不保证已分派的部分输入被回滚,Host 不得自动重试输入。
稳定错误码包括 `INVALID_REQUEST`(信封无效)、`INVALID_ARGUMENT`(参数无效)、`UNSUPPORTED`(操作未知)、`APP_UNAVAILABLE`、`APP_PATH_UNAVAILABLE`、`PROCESS_INSPECTION_FAILED`、`AMBIGUOUS_APP`、`STALE_APP`、`STALE_SNAPSHOT`、`WINDOW_UNAVAILABLE`、`WINDOW_CHANGED`、`PERMISSION_DENIED`、`HOVER_UNAVAILABLE`、`FOREGROUND_REQUIRED`(系统鼠标操作要求命中前台目标窗口)、`INPUT_BUSY`(有鼠标键按下,等松开后再请求系统拖动)、`PANEL_NOT_READY`(输入前系统面板接收方尚不可用)及 `NATIVE_ERROR`(其余操作系统失败)。错误不保证已分派的部分输入被回滚,Host 不得自动重试输入。
应用选择向 Host 返回授权记录:区分大小写的 Bundle ID 加上 `macos:bundle-id:` 前缀后计算的 SHA-256 摘要、显示名称、可选的可执行路径和可持久化标记。相同标识的所有安装副本共用授权,包括未签名和临时签名的应用。缺少非空 Bundle ID 时,运行中和未启动应用都对 `macos:executable-path:` 与解析符号链接后的可执行路径计算 SHA-256,仍可保存长期授权。进程路径查询失败时,运行中的有效 Bundle ID 仍可用于授权,记录省略 executablePath;路径可取得时仍须与所选目标一致。两种身份均不可用时,在执行目标操作前返回 APP_PATH_UNAVAILABLE,保留路径查询原因和 errno。PROCESS_INSPECTION_FAILED 表示无法验证进程实例,只有进程检查返回 ESRCH 时才报告进程不存在;两种失败都不触发自动重试。进程号和启动时间只校验存活句柄,不进入已保存身份。Host 从模型结果中移除此记录,并在启动、观察和输入前取得用户许可。此管道协议用于可信 Host 传输,无法隔离另一个已获授权的 shell 进程。
@@ -165,7 +165,7 @@ Blender 键盘检查使用 `python3 packages/experimental/cua-macos/native/tests
隔离的 Electron/Chromium 检查使用 `python3 packages/experimental/cua-macos/native/tests/electron_e2e.py --electron /absolute/path/to/Electron.app/Contents/MacOS/Electron`。省略 `--electron` 时使用桌面工作区已安装的运行时,检查不下载 Electron。渲染器禁用 Node 集成,启用上下文隔离和 Chromium 沙箱,使用独立 userData/sessionData/log 目录及本地 fixture 页面。渲染器的点击/输入事件通过主进程写出独立观察,测试动作仍通过原生 helper 执行。AX 轮询等待 Chromium 辅助功能启用后的真实控件。原生和 Electron 子进程组由测试持有,在删除临时文件前停止。可选产物包含仅有 fixture 的截图和私有请求记录。
运行 `python3 packages/experimental/cua-macos/native/tests/capabilities_e2e.py --helper /absolute/helper --artifacts /private/evidence`,通过隔离的 AppKit 接收方验证未运行应用的发现和启动、Unicode 选区、多行纯文本/HTML 粘贴、带修饰键的中键手势、W 和 D 同时按住时的事件顺序及数字键盘键码。需要已有辅助功能/屏幕录制权限,接收方实际状态与分派结果分开记录。添加 `--keyboard-only` 可用后台窗口验证 W、D 同时按住两秒、单独释放 D 和收尾时释放 W。添加 `--click-only` 可在后台测试窗口中验证按住时长、AX 路由和取消、超时后的松开事件,不发送键盘或剪贴板输入。
运行 `python3 packages/experimental/cua-macos/native/tests/capabilities_e2e.py --helper /absolute/helper --artifacts /private/evidence`,通过隔离的 AppKit 接收方验证未运行应用的发现和启动、Unicode 选区、多行纯文本/HTML 粘贴、带修饰键的中键手势、W 和 D 同时按住时的事件顺序及数字键盘键码。需要已有辅助功能/屏幕录制权限,接收方实际状态与分派结果分开记录。添加 `--keyboard-only` 可用后台窗口验证 W、D 同时按住两秒、单独释放 D 和收尾时释放 W。添加 `--click-only` 可在后台测试窗口中验证按住时长、AX 路由和取消、超时后的松开事件,不发送键盘或剪贴板输入。 使用 `--drag-only` 可验证后台目标在按下前被拒绝,以及前台拖动的事件顺序、按键状态和两轴位移。测试在第一次移动后取消,核对只在最后投递的位置释放一次。
运行 `python3 packages/experimental/cua-macos/native/tests/paste_e2e.py --artifacts /private/evidence`,验证自有 AppKit 应用在后台接收 Paste 动作但不读取数据时返回 `PASTE_NOT_CONSUMED`,以及前台读取同一次粘贴后成功。测试要求 Mac 已解锁并已授予辅助功能权限,只激活自有的两个应用,并独立记录收到的动作和文本以核对 helper 回复。
@@ -10,7 +10,7 @@ final class WindowPointerInput {
let up: CGEvent
}
private struct DragStep {
struct DragStep {
let movement: CGEvent
let release: CGEvent
}
@@ -186,7 +186,7 @@ final class WindowPointerInput {
}
}
let down = try event(Self.down(selected), at: start)
var release = try event(Self.up(selected), at: start)
let initialRelease = try event(Self.up(selected), at: start)
var previous = start
var path: [DragStep] = []
for index in 1...steps {
@@ -203,32 +203,53 @@ final class WindowPointerInput {
if useSystemPointer {
try Self.validateSystemWindow(route)
try await Self.checkSystemHit(route, at: down.location)
guard ![CGMouseButton.left, .right, .center].contains(where: { CGEventSource.buttonState(.combinedSessionState, button: $0) }) else {
throw NativeFailure(code: "INPUT_BUSY", message: "A mouse button is already held")
}
try Self.requireReleasedButtons()
try checkCancellation()
post(try event(.mouseMoved, at: start))
try await Self.checkSystemHit(route, at: down.location)
}
let interval = Self.dragStepInterval(durationMs: durationMs, steps: steps)
try await Self.postDrag(down: down, initialRelease: initialRelease, path: path,
interval: Self.dragStepInterval(durationMs: durationMs, steps: steps),
validate: { event in
if useSystemPointer {
try await Self.checkSystemHit(route, at: event.location)
if event.type == Self.down(selected) { try Self.requireReleasedButtons() }
}
try self.checkCancellation()
}, post: post)
try checkCancellation()
}
static func requireReleasedButtons(isPressed: (CGMouseButton) -> Bool = {
CGEventSource.buttonState(.combinedSessionState, button: $0)
}) throws {
if [CGMouseButton.left, .right, .center].contains(where: isPressed) {
throw NativeFailure(code: "INPUT_BUSY", message: "Wait for the held mouse button to be released before requesting a system drag")
}
}
/// After a press, always post one release at the last posted point, even when validation or a wait fails.
static func postDrag(down: CGEvent, initialRelease: CGEvent, path: [DragStep], interval: TimeInterval,
validate: (CGEvent) async throws -> Void, post: (CGEvent) -> Void,
isolation: isolated (any Actor)? = #isolation) async throws {
try await validate(down)
post(down)
var release = initialRelease
var failure: (any Error)?
do {
defer { post(release) }
try await Task.sleep(for: .milliseconds(16))
for step in path {
if useSystemPointer { try await Self.checkSystemHit(route, at: step.movement.location) }
try checkCancellation()
try await validate(step.movement)
post(step.movement)
release = step.release
try await Task.sleep(for: .seconds(interval))
}
try await Task.sleep(for: .milliseconds(50))
if useSystemPointer { try await Self.checkSystemHit(route, at: release.location) }
try checkCancellation()
}
try await Task.sleep(for: .milliseconds(100))
try checkCancellation()
try await validate(release)
} catch { failure = error }
post(release)
// The next input request must allow time for release processing even when this request was cancelled.
try await Task { try await Task.sleep(for: .milliseconds(100)) }.value
if let failure { throw failure }
}
/// Every posted down is paired with exactly one up, including cancellation during the wait.
@@ -93,6 +93,8 @@ final class CapabilitiesFixture: NSObject, NSApplicationDelegate, NSWindowDelega
value["button"] = event.buttonNumber
value["pressedButtons"] = NSEvent.pressedMouseButtons
value["deltaX"] = event.deltaX
value["deltaY"] = event.deltaY
value["eventNumber"] = event.eventNumber
value["point"] = [event.locationInWindow.x, event.locationInWindow.y]
}
self.events.append(value)
@@ -51,7 +51,7 @@ def check_system_drag(helper, owner, window, point, state_file):
call("getState", {**window, "maxElements": 300, "maxDepth": 20})
count = len(json.loads(state_file.read_text())["events"])
params = {**window, "fromX": point["x"], "fromY": point["y"], "toX": point["x"] + 80,
"toY": point["y"] + 20, "durationMs": 400, "steps": 20, "useSystemPointer": True}
"toY": point["y"] + 20, "durationMs": 400, "steps": 1, "modifiers": ["shift"], "useSystemPointer": True}
call("drag", params, "FOREGROUND_REQUIRED")
assert len(json.loads(state_file.read_text())["events"]) == count
call("activate", owner)
@@ -60,9 +60,13 @@ def check_system_drag(helper, owner, window, point, state_file):
call("drag", params)
state = wait_for_state(state_file, lambda v: any(e["type"] == 2 for e in v["events"][count:]))
events = state["events"][count:]
assert events[0]["type"] == 1 and events[-1]["type"] == 2, events
assert any(e["type"] == 6 and e["pressedButtons"] & 1 and e["deltaX"] > 0 for e in events), events
assert events[-1]["point"][0] - events[0]["point"][0] == 80, events
assert [e["type"] for e in events] == [1, 6, 2], events
down, move, up = events
assert all(e["shift"] and e["eventNumber"] == down["eventNumber"] for e in events), events
assert move["pressedButtons"] & 1 and (move["deltaX"], move["deltaY"]) == (80, 20), events
# AppKit window coordinates count upward; Quartz movement deltas count downward.
assert (move["point"][0] - down["point"][0], down["point"][1] - move["point"][1]) == (80, 20), events
assert up["point"] == move["point"] and not up["pressedButtons"] & 1, events
key = hashlib.sha256(Path(helper.process.args[0]).read_bytes()).hexdigest()
connection = Connection(Path(f"/tmp/dsh-cua-{os.getuid()}/{key}.sock"), key)
try:
@@ -0,0 +1,42 @@
// Exercise release ownership without permission to move the desktop pointer.
import CoreGraphics
import Testing
@testable import CuaNative
@Test func systemDragRequiresAllSupportedButtonsToBeReleased() throws {
try WindowPointerInput.requireReleasedButtons(isPressed: { _ in false })
for held in [CGMouseButton.left, .right, .center] {
do {
try WindowPointerInput.requireReleasedButtons(isPressed: { $0 == held })
Issue.record("Admitted drag while button was held")
} catch let error as NativeFailure {
#expect(error.code == "INPUT_BUSY")
}
}
}
@Test @MainActor func interruptedDragReleasesOnlyAtTheLastPostedPoint() async throws {
func event(_ type: CGEventType, x: Int) throws -> CGEvent {
try #require(CGEvent(mouseEventSource: nil, mouseType: type,
mouseCursorPosition: CGPoint(x: x, y: 10), mouseButton: .left))
}
let down = try event(.leftMouseDown, x: 10)
let release = try event(.leftMouseUp, x: 10)
let path = try [20, 30].map { x in
WindowPointerInput.DragStep(movement: try event(.leftMouseDragged, x: x), release: try event(.leftMouseUp, x: x))
}
let interruptions: [(CGEvent, [CGEvent])] = [
(down, []),
(path[0].movement, [down, release]),
(path[1].movement, [down, path[0].movement, path[0].release]),
]
for (blocked, expected) in interruptions {
var posted: [CGEvent] = []
do {
try await WindowPointerInput.postDrag(down: down, initialRelease: release, path: path, interval: 0,
validate: { if $0 === blocked { throw CancellationError() } }, post: { posted.append($0) })
Issue.record("Interrupted drag completed")
} catch { #expect(error is CancellationError) }
#expect(posted.elementsEqual(expected, by: { $0 === $1 }))
}
}
@@ -1400,6 +1400,13 @@ it.each([true, false])('uses the declared systemPointer capability for a non-mac
const answer = vi.spyOn(f.ctx.userQuestions, 'ask').mockResolvedValue({
answers: [{ id: 'cua-mouse-control', selected: ['Allow for this session'] }],
})
if (!systemPointer) {
const denied = await f.execute('drag', { appHandle: 'app-one', windowId: '7', fromX: 1, fromY: 1, toX: 2, toY: 2, useSystemPointer: true })
expect(denied.isError).toBe(true)
expect(JSON.stringify(denied.content)).toContain('useSystemPointer')
expect(native.request).not.toHaveBeenCalled()
expect(answer).not.toHaveBeenCalled()
}
const physical = await f.execute('mouseMove', physicalHover)
expect(physical.isError).toBe(!systemPointer)
expect(answer).toHaveBeenCalledTimes(systemPointer ? 1 : 0)
+2 -2
View File
@@ -21,8 +21,8 @@
en: 754ca69ec462325a
zh: 440d76acf2666689
/deepseek-ai-dsh-cua/understand-the-implementation:
en: 9e755327bfdb71fa
zh: 38e80a91e290800e
en: 1466856a9cf848fe
zh: 4ef0d79f573c70a6
/deepseek-ai-dsh-cua/further-exploration:
en: c174fb5a00ea3681
zh: 039340042676881d
+1 -1
View File
@@ -78,7 +78,7 @@ The Host marker has no configurable fields; platform providers own native config
<a id="understand-the-implementation"></a>
## Understand the implementation
Providers declare `systemPointer: true` to support explicit physical pointer movement. CUA exposes the option in the tool schema and model instructions only for those providers. CUA owns the approval card, live-session decision and delegated-task restriction. A provider receives the per-call pointer mode after CUA checks application access and any required consent.
Providers declaring `systemPointer: true` must support explicit `useSystemPointer: true` on both `mouseMove` and `drag`. The operations share one session decision. CUA validates the tool arguments, asks for consent, and enforces the delegated-task restriction before calling the provider. The provider documents its default input routes.
Permission responses identify their platform and report only the state that platform can observe. The shared page renders the controls those observations support. Before platform identification, it shows neutral observation and input rows without system actions. Native providers use the shared build lock and compiler cleanup. The macOS provider reads its signed application receipt after compilation completes under the same lock.
+1 -1
View File
@@ -78,7 +78,7 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边
<a id="understand-the-implementation"></a>
## 理解实现
提供方通过 `systemPointer: true` 声明支持真实鼠标移动。CUA 据此在工具 schema 和模型提示词中加入该选项,负责显示授权卡、记录当前会话的决定并限制子代理。CUA 检查应用访问权限和本次移动所需的授权后,将悬停方式传给提供方。
提供方声明 `systemPointer: true` 后,`mouseMove` 和 `drag` 都必须支持显式传入 `useSystemPointer: true`。两种操作共用一次会话授权。CUA 负责工具参数校验、授权提示和子代理限制,在检查应用访问权限及本次操作的授权后调用提供方。提供方负责说明各自的默认输入方式。
权限响应标识所属平台,并且只报告该平台能够观察到的状态。共享页面显示这些观察结果支持的控件。平台尚未确认时显示通用观察和输入项,不提供系统操作。原生提供方共用编译锁和编译进程清理逻辑。macOS 提供方在锁内等待编译完成,再读取签名应用的构建回执。
+1
View File
@@ -279,6 +279,7 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend)
const signal = execution.signal
signal.throwIfAborted()
const client = execution.nativeClient
// Released macOS helpers accept an explicit false for mouseMove but reject the new drag field.
if (method === 'drag' && !useSystemPointer) delete params.useSystemPointer
else if (useSystemPointer !== undefined) params.useSystemPointer = useSystemPointer
if (method === 'sendKeyEvent' && backend.sendKeyEvent) return backend.sendKeyEvent(client, params, execution)
@@ -1,14 +1,14 @@
/** Scope and interruption shown before the user grants mouse control. */
export const mouseControlPrompt = {
question: {
en: 'Allow the agent to move your mouse pointer?',
zh: '允许智能体移动你的鼠标指针吗?',
ja: 'エージェントがマウスポインタを動かすことを許可しますか?',
es: '¿Permitir que el agente mueva el puntero del ratón?',
fr: 'Autoriser l’agent à déplacer le pointeur de la souris ?',
de: 'Darf der Agent den Mauszeiger bewegen?',
ru: 'Разрешить агенту перемещать указатель мыши?',
pt: 'Permitir que o agente mova o ponteiro do mouse?',
en: 'Allow the agent to move and drag with your mouse?',
zh: '允许智能体使用你的鼠标移动指针和拖动吗?',
ja: 'エージェントにマウスポインタの移動とドラッグを許可しますか?',
es: '¿Permitir que el agente mueva el puntero y arrastre con tu ratón?',
fr: 'Autoriser l’agent à déplacer le pointeur et à faire glisser des éléments avec votre souris ?',
de: 'Darf der Agent den Mauszeiger bewegen und mit gedrückter Maustaste ziehen?',
ru: 'Разрешить агенту перемещать указатель и перетаскивать объекты с помощью мыши?',
pt: 'Permitir que o agente mova o ponteiro e arraste com o seu mouse?',
},
detail: {
en: 'The agent can move your pointer and drag with a mouse button held when it explicitly requests control. Your choice lasts until you close this session or restart DSH.',
@@ -58,6 +58,6 @@ export class MouseControl {
throw error
}
}
if (!granted) throw new NativeError('MOUSE_CONTROL_DENIED', 'The user declined system-pointer movement for this session. No input was sent. Use pointer-free actions.')
if (!granted) throw new NativeError('MOUSE_CONTROL_DENIED', 'The user declined system-pointer moves and drags for this session. No input was sent. Use pointer-free actions.')
}
}