forked from cflmy/deepseek-harness
fix(cua): detect input during reads and avoid waiting on desktop work
This commit is contained in:
1 parent
d571a18edc
commit
69863f91fd
17 files changed
+161
-59
No files matched your search
@@ -15,8 +15,8 @@
|
||||
en: 1777e7bf6785f986
|
||||
zh: e3daac1074ebb74d
|
||||
/deepseek-ai-dsh-cua-macos/use-this-package:
|
||||
en: 02671262241ca34f
|
||||
zh: a545a9e5c657326e
|
||||
en: 9ddf794c9bd4d350
|
||||
zh: f235de9e6b68481a
|
||||
/deepseek-ai-dsh-cua-macos/use-this-package/connect-an-external-execution-environment:
|
||||
en: 6097d7d03bc8dfad
|
||||
zh: 0978077447118d64
|
||||
|
||||
@@ -80,7 +80,7 @@ Source builds default to `sourceSigning: ad-hoc`, without creating certificates
|
||||
| `dragDurationMs` / `dragSteps` | `400` / `20` | Duration and movement segments for a drag. |
|
||||
| `textEventIntervalMs` | `0.25` | Delay after each Unicode down/up event, from 0 to 999 ms. Keystroke timing is independent. |
|
||||
|
||||
After a window accessibility read or screenshot, the next scheduled model step checks for input on that window since the observation and within the configured lookback. The notice gives the window ID and time of the latest activity from each source: another Agent or external input. Each window can produce one notice until the Agent uses it again. Watches end with the turn or connection. The notice is recorded in the Session.
|
||||
After a window accessibility read or screenshot, the next scheduled model step checks for input on that window since the start of the last successfully delivered read and within the configured lookback, including input during capture. The notice gives the window ID and time of the latest activity from each source: another Agent or external input. Each window can produce one notice until the Agent uses it again. Watches end with the turn or connection. The notice is recorded in the Session.
|
||||
|
||||
The [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-cua-macos) lists all fields. Native tool calls use `{method, params}`; the complete method-specific schema is exposed to the model. `getApp` returns the `appHandle` used by every app-targeted operation, and `app.getWindow(windowId)` returns the object that owns screenshots and pointer input.
|
||||
|
||||
|
||||
@@ -80,7 +80,7 @@ pnpm dsh headless --patch packages/experimental/cua-macos/examples/macos.cordis.
|
||||
| `dragDurationMs` / `dragSteps` | `400` / `20` | 拖动时长和移动分段数。 |
|
||||
| `textEventIntervalMs` | `0.25` | 每个 Unicode 按下或抬起事件后的间隔,范围为 0 至 1000 毫秒。击键节奏独立。 |
|
||||
|
||||
模型读取窗口辅助功能树或截图后,插件在下一次模型请求前检查该窗口。只有上次观察之后且在回看时限内发生的活动才会触发提醒。提醒给出窗口 ID,并分别说明其他 Agent 和外部输入最近出现的时间。每个窗口最多提醒一次,直到 Agent 再次使用该窗口。本轮结束或连接断开时停止关注,已发送的提醒保存在 Session 中。
|
||||
模型读取窗口辅助功能树或截图后,插件在下一次模型请求前检查该窗口。回看从最近一次成功读取开始采样时算起,因此也能提示读取期间发生的输入。超过回看时限的活动会被排除。提醒给出窗口 ID,并分别说明其他 Agent 和外部输入最近出现的时间。每个窗口最多提醒一次,直到 Agent 再次使用该窗口。本轮结束或连接断开时停止关注,已发送的提醒保存在 Session 中。
|
||||
|
||||
[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-cua-macos)列出全部字段。原生工具调用使用 `{method, params}`,模型可以看到每个方法的完整参数定义。`getApp` 返回每个面向应用的操作所需的 `appHandle`,`app.getWindow(windowId)` 返回负责截图和指针输入的对象。
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@ struct ActivityTarget: Hashable, Sendable {
|
||||
var hasInterests: Bool { clients.values.contains { $0.windows.values.contains(where: \.armed) } }
|
||||
func disconnect(_ owner: UUID) { clients.removeValue(forKey: owner) }
|
||||
func clear(_ owner: UUID) { clients[owner]?.windows.removeAll() }
|
||||
/// Return the capture time. The Host sends it back only for an observation it delivered successfully.
|
||||
/// Arm before sampling the window so input during a slow read can invalidate its result.
|
||||
@discardableResult func observe(_ target: ActivityTarget, handle: String, owner: UUID) -> UInt64 {
|
||||
let time = now()
|
||||
if var window = clients[owner]?.windows[target] {
|
||||
@@ -51,6 +51,22 @@ struct ActivityTarget: Hashable, Sendable {
|
||||
}
|
||||
return time
|
||||
}
|
||||
/// Keep the previous delivered observation eligible when a refresh fails.
|
||||
func withObservation(_ target: ActivityTarget, handle: String, owner: UUID,
|
||||
read: @MainActor () async throws -> JSONValue) async throws -> JSONValue {
|
||||
let previous = clients[owner]?.windows[target]
|
||||
let start = observe(target, handle: handle, owner: owner)
|
||||
do {
|
||||
guard var fields = try await read().object else {
|
||||
throw NativeFailure(code: "NATIVE_PROTOCOL", message: "Expected a window observation")
|
||||
}
|
||||
fields["activityObservedAt"] = .string(String(start))
|
||||
return .object(fields)
|
||||
} catch {
|
||||
if previous?.armed != true { clients[owner]?.windows[target] = previous }
|
||||
throw error
|
||||
}
|
||||
}
|
||||
func isTracked(_ process: ProcessIdentity) -> Bool {
|
||||
clients.values.contains { $0.windows.contains { $0.key.process == process && $0.value.armed } }
|
||||
}
|
||||
|
||||
@@ -197,6 +197,21 @@ import Darwin
|
||||
// A dispatched action can invalidate the snapshot that identifies its window.
|
||||
let target = configuration.recentActivityWindowMs != nil && params.contains("appHandle")
|
||||
? await worker.activityTarget(params) : nil
|
||||
if let target, request.method == "getState" || request.method == "screenshot" {
|
||||
inputMonitor.start()
|
||||
defer { if !activity.hasInterests { inputMonitor.stop() } }
|
||||
return try await activity.withObservation(target, handle: params.string("appHandle"), owner: connectionID) {
|
||||
try await self.dispatch(request, params: params, trace: trace)
|
||||
}
|
||||
}
|
||||
let result = try await dispatch(request, params: params, trace: trace)
|
||||
if let target, result["dispatched"] == .bool(true) {
|
||||
activity.record(target, owner: connectionID)
|
||||
if activity.hasInterests { inputMonitor.start() }
|
||||
}
|
||||
return result
|
||||
}
|
||||
private func dispatch(_ request: NativeRequest, params: RequestParameters, trace: ScreenshotTrace?) async throws -> JSONValue {
|
||||
let requiresCatalog = ["getApp", "launchApp", "listApps", "findApps", "typeText", "pressKey", "sendKeyEvent", "click"].contains(request.method)
|
||||
let catalog = requiresCatalog ? ApplicationCatalog.snapshot() : ApplicationCatalogSnapshot(applications: [], frontPID: nil)
|
||||
let result: JSONValue
|
||||
@@ -267,17 +282,6 @@ import Darwin
|
||||
result = try await worker.finishLaunch(plan, pid: pid, catalog: ApplicationCatalog.snapshot())
|
||||
}
|
||||
}
|
||||
if let target {
|
||||
if (request.method == "getState" || request.method == "screenshot"), var fields = result.object {
|
||||
let time = activity.observe(target, handle: try params.string("appHandle"), owner: connectionID)
|
||||
fields["activityObservedAt"] = .string(String(time))
|
||||
inputMonitor.start()
|
||||
return .object(fields)
|
||||
} else if result["dispatched"] == .bool(true) {
|
||||
activity.record(target, owner: connectionID)
|
||||
}
|
||||
if activity.hasInterests { inputMonitor.start() }
|
||||
}
|
||||
return result
|
||||
}
|
||||
private func performForeground(_ plan: ForegroundPlan, requestID: String) async throws -> JSONValue {
|
||||
|
||||
@@ -76,8 +76,6 @@ final class Fixture: NSObject, NSApplicationDelegate, NSTextFieldDelegate {
|
||||
var count = 0
|
||||
var secondaryCount = 0
|
||||
var selectedFile = ""
|
||||
var keyEventCount = 0
|
||||
var keyMonitor: Any?
|
||||
|
||||
init(statePath: String, rowCount: Int = 35, alternateHover: Bool = false) {
|
||||
self.statePath = statePath; self.rowCount = rowCount; self.alternateHover = alternateHover
|
||||
@@ -160,18 +158,10 @@ final class Fixture: NSObject, NSApplicationDelegate, NSTextFieldDelegate {
|
||||
if position != self.lastCursor { self.cursorChanges += 1; self.lastCursor = position }
|
||||
self.persist()
|
||||
}
|
||||
keyMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in
|
||||
self?.keyEventCount += 1
|
||||
self?.persist()
|
||||
return event
|
||||
}
|
||||
persist()
|
||||
print("READY")
|
||||
fflush(stdout)
|
||||
}
|
||||
func applicationWillTerminate(_ notification: Notification) {
|
||||
if let keyMonitor { NSEvent.removeMonitor(keyMonitor) }
|
||||
}
|
||||
@objc func increment() { count += 1; countLabel.stringValue = "Count: \(count)"; persist() }
|
||||
@objc func cycleOverlay() {
|
||||
overlayMode = (overlayMode + 1) % 3
|
||||
@@ -221,7 +211,7 @@ final class Fixture: NSObject, NSApplicationDelegate, NSTextFieldDelegate {
|
||||
? CGWindowListCopyWindowInfo(.optionIncludingWindow, CGWindowID(overlayID)) as? [[String: Any]] : nil
|
||||
let overlayOnScreen = overlayRows?.contains { ($0[kCGWindowIsOnscreen as String] as? Bool) == true } ?? false
|
||||
let state: [String: Any] = ["count": count, "secondaryCount": secondaryCount, "text": field.stringValue, "selectedFile": selectedFile,
|
||||
"keyEventCount": keyEventCount, "rowCount": rowCount, "primaryWindowId": window.windowNumber > 0 ? String(window.windowNumber) as Any : NSNull(),
|
||||
"rowCount": rowCount, "primaryWindowId": window.windowNumber > 0 ? String(window.windowNumber) as Any : NSNull(),
|
||||
"dragDownCount": dragPad.dragDownCount, "dragCount": dragPad.dragCount, "dragPoint": [dragPad.lastPoint.x, dragPad.lastPoint.y],
|
||||
"hoverVisible": !dragPad.hoverButton.isHidden, "hoverClicks": dragPad.hoverClicks,
|
||||
"defaultUIRequests": (dragPad as? AlternateHoverPad)?.defaultUIRequests ?? 0,
|
||||
|
||||
@@ -197,8 +197,8 @@ def main():
|
||||
clients.append(off)
|
||||
off_app = off.call("getApp", {"selector": str(fixture.pid)})["appHandle"]
|
||||
off_read = {"appHandle": off_app, "maxElements": 300, "maxDepth": 20}
|
||||
off_state = off.call("getState", off_read)
|
||||
assert "recentActivity" not in off_state and not has_listener()
|
||||
off.call("getState", off_read)
|
||||
assert not has_listener()
|
||||
app_a = a.call("getApp", {"selector": str(fixture.pid)})["appHandle"]
|
||||
app_b = b.call("getApp", {"selector": str(fixture.pid)})["appHandle"]
|
||||
assert app_a != app_b
|
||||
@@ -224,26 +224,32 @@ def main():
|
||||
while json.loads(state.read_text())["count"] != before + 1:
|
||||
assert time.monotonic() < changed_until, "B input did not update the fixture exactly once"
|
||||
time.sleep(0.025)
|
||||
def take(client, handle, receipt=None):
|
||||
return client.call("takeWindowActivity", {"appHandle": handle, "observations": {window: (receipt or observed)["activityObservedAt"]}})
|
||||
def take(client, handle, receipt):
|
||||
return client.call("takeWindowActivity", {"appHandle": handle, "observations": {window: receipt}})
|
||||
|
||||
events = take(a, app_a)
|
||||
events = take(a, app_a, observed["activityObservedAt"])
|
||||
assert len(events) == 1 and events[0]["source"] == "agent" and events[0]["windowId"] == window, events
|
||||
assert 0 <= events[0]["ageSeconds"] <= 60 and take(a, app_a) == []
|
||||
assert 0 <= events[0]["ageSeconds"] <= 60 and take(a, app_a, observed["activityObservedAt"]) == []
|
||||
after = a.call("getState", {"appHandle": app_a, "windowId": window, "maxElements": 300, "maxDepth": 20})
|
||||
assert f"Count: {before + 1}" in after["tree"], "A retained handle did not observe B's input"
|
||||
off_read["windowId"] = window
|
||||
off_state = off.call("getState", off_read)
|
||||
assert "recentActivity" not in off_state
|
||||
assert "activityObservedAt" not in off_state
|
||||
off_button = next(element for element in off_state["elements"]
|
||||
if element["role"] == "AXButton" and element["title"] == "Increment primary")
|
||||
off_action = off.call("invoke", {"appHandle": off_app, "snapshotId": off_state["snapshotId"], "elementId": off_button["elementId"]})
|
||||
assert "recentActivity" not in off_action
|
||||
off.call("invoke", {"appHandle": off_app, "snapshotId": off_state["snapshotId"], "elementId": off_button["elementId"]})
|
||||
deadline = time.monotonic() + 5
|
||||
while json.loads(state.read_text())["count"] != before + 2:
|
||||
assert time.monotonic() < deadline, "Disabled activity tracking blocked ordinary input"
|
||||
time.sleep(0.025)
|
||||
assert not take(a, app_a) and not take(b, app_b) and not take(off, off_app)
|
||||
assert not take(a, app_a, after["activityObservedAt"])
|
||||
assert not take(b, app_b, own_observation["activityObservedAt"])
|
||||
assert not take(off, off_app, "0")
|
||||
|
||||
# Exercise rearming even when the system does not allow external event injection.
|
||||
b.call("invoke", {"appHandle": app_b, "snapshotId": own_observation["snapshotId"], "elementId": button["elementId"]})
|
||||
events = take(a, app_a, after["activityObservedAt"])
|
||||
assert any(event["source"] == "agent" and event["windowId"] == window for event in events), events
|
||||
|
||||
if has_listener():
|
||||
can_post = subprocess.check_output([str(sender), "--can-post"], text=True, timeout=5).strip() == "yes"
|
||||
@@ -255,13 +261,18 @@ def main():
|
||||
button = next(element for element in focused["elements"]
|
||||
if element["role"] == "AXButton" and element["title"] == "Increment primary")
|
||||
x, y, width, height = button["bounds"]
|
||||
before_count = json.loads(state.read_text())["count"]
|
||||
after = a.call("getState", {"appHandle": app_a, "windowId": window, "maxElements": 300, "maxDepth": 20})
|
||||
deadline = time.monotonic() + 5
|
||||
while json.loads(state.read_text())["count"] != before + 3:
|
||||
assert time.monotonic() < deadline, "Fixture did not receive the second enabled input"
|
||||
time.sleep(0.025)
|
||||
before_count = before + 3
|
||||
with external_input(sender, fixture.pid, x + width / 2, y + height / 2, window):
|
||||
deadline = time.monotonic() + 5
|
||||
reported = False
|
||||
while True:
|
||||
reported |= any(event["source"] == "external-input" and event["windowId"] == window
|
||||
for event in take(a, app_a))
|
||||
for event in take(a, app_a, after["activityObservedAt"]))
|
||||
if reported and json.loads(state.read_text())["count"] == before_count + 1:
|
||||
break
|
||||
assert time.monotonic() < deadline, ("External click was not received and reported", reported)
|
||||
@@ -298,7 +309,7 @@ def main():
|
||||
b.close()
|
||||
clients.remove(b)
|
||||
if not args.without_desktop:
|
||||
assert "recentActivity" not in off.call("getState", off_read)
|
||||
assert "activityObservedAt" not in off.call("getState", off_read)
|
||||
assert not has_listener(), "Off-only helper retained the external input listener"
|
||||
off.close()
|
||||
clients.remove(off)
|
||||
|
||||
@@ -125,3 +125,40 @@ private let second: UInt64 = 1_000_000_000
|
||||
continuous += 3_600 * second
|
||||
#expect(history.take(owner: owner, handle: "app", observations: ["10": observed]).isEmpty)
|
||||
}
|
||||
|
||||
@Test @MainActor func capturesInputDuringWindowReadsAndRollsBackFailedInterests() async throws {
|
||||
var time = second
|
||||
let history = RecentActivity(now: { time })
|
||||
let owner = UUID()
|
||||
history.connect(owner, lookbackMs: 60_000)
|
||||
func read() async throws -> UInt64 {
|
||||
let result = try await history.withObservation(target, handle: "app", owner: owner) {
|
||||
time += second
|
||||
history.record(target, owner: nil)
|
||||
time += second
|
||||
return .object([:])
|
||||
}
|
||||
let stamp = try #require(result["activityObservedAt"].string)
|
||||
return try #require(UInt64(stamp))
|
||||
}
|
||||
func fail() async throws {
|
||||
_ = try await history.withObservation(target, handle: "app", owner: owner) {
|
||||
time += second
|
||||
history.record(target, owner: nil)
|
||||
throw CancellationError()
|
||||
}
|
||||
}
|
||||
func take(_ receipt: UInt64) -> [JSONValue] {
|
||||
history.take(owner: owner, handle: "app", observations: ["10": receipt])
|
||||
}
|
||||
await #expect(throws: CancellationError.self) { try await fail() }
|
||||
#expect(!history.hasInterests)
|
||||
let first = try await read()
|
||||
#expect(take(first) == [.object(["windowId": .string("10"), "source": .string("external-input"), "ageSeconds": .number(1)])])
|
||||
await #expect(throws: CancellationError.self) { try await fail() }
|
||||
#expect(!history.hasInterests)
|
||||
time += second
|
||||
let next = try await read()
|
||||
await #expect(throws: CancellationError.self) { try await fail() }
|
||||
#expect(take(next) == [.object(["windowId": .string("10"), "source": .string("external-input"), "ageSeconds": .number(0)])])
|
||||
}
|
||||
@@ -49,7 +49,7 @@ export function watchWindowActivity(ctx: Context): NonNullable<CuaBackend['windo
|
||||
for (const [handle, windows] of watch.apps) {
|
||||
const observations = Object.fromEntries(windows)
|
||||
try {
|
||||
const result = await watch.access.run(watch.client, handle, signal, authorized =>
|
||||
const result = await watch.access.readCached(watch.client, handle, signal, authorized =>
|
||||
watch.client.request('takeWindowActivity', { appHandle: handle, observations }, authorized))
|
||||
const rows = Rows.parse(result)
|
||||
if (rows.some(row => !windows.has(row.windowId))) throw new NativeError('NATIVE_PROTOCOL', 'Unrequested window activity')
|
||||
@@ -60,7 +60,6 @@ export function watchWindowActivity(ctx: Context): NonNullable<CuaBackend['windo
|
||||
}
|
||||
} catch (error) {
|
||||
if (signal.aborted) return decision
|
||||
watch.apps.delete(handle)
|
||||
ctx.logger.warn('Could not check recent window activity: %s', error)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -236,6 +236,8 @@ it('delivers window activity at the next accepted step and clears it at turn end
|
||||
}] }] })
|
||||
expect(native.request).toHaveBeenLastCalledWith('takeWindowActivity', { appHandle: 'app-one', observations: { '7': '101' } }, expect.any(AbortSignal))
|
||||
expect(await step()).toMatchObject({ messages: [] })
|
||||
native.request.mockRejectedValueOnce(new NativeError('NATIVE_BUSY', 'Another request is in flight'))
|
||||
expect(await step()).toMatchObject({ messages: [] })
|
||||
native.request.mockResolvedValueOnce([{ windowId: '7', source: 'agent', ageSeconds: 5 }])
|
||||
expect(JSON.stringify(await step())).toContain('5 seconds ago')
|
||||
const controller = new AbortController()
|
||||
|
||||
@@ -21,8 +21,8 @@
|
||||
en: 3f638a4a76023fc5
|
||||
zh: 515aeb5de6ae5b33
|
||||
/deepseek-ai-dsh-cua/understand-the-implementation:
|
||||
en: fa68a353d7a94703
|
||||
zh: 432b2e6823e5eb7d
|
||||
en: e063496a8a67584f
|
||||
zh: ba25b0fc57affe94
|
||||
/deepseek-ai-dsh-cua/further-exploration:
|
||||
en: c174fb5a00ea3681
|
||||
zh: 039340042676881d
|
||||
|
||||
@@ -99,7 +99,7 @@ Grant executable paths are optional display metadata. Missing paths omit the too
|
||||
|
||||
The permission Remote also exposes `ptcConfiguration()` and `enablePersistentPtc()` for the detail-page runtime setting. Reads inspect the existing runtime and editable profile entry. Explicit writes obtain execution settings from the Node provider's `resolvePersistentExecution` helper and use `configEditor.edit()` to preserve other fields and apply normal Loader reload; an already-persistent runtime is left intact. CUA declares the Node provider as a peer so these settings follow the installed provider version. This setting is separate from system and application authorization.
|
||||
|
||||
The provider calls [installCua](src/index.ts) with its prepared helper, connection factory, guidance callback, and startup capabilities. [NativeClient](src/native-client.ts) owns request correlation, byte limits, cancellation acknowledgement, and failure settlement. The platform connector owns startup and connection cleanup. Its typed startup failures preserve their code and diagnostic through request writes and connection shutdown. The shared executor retains one connection per Agent and joins in-flight image writes during disposal. Providers can use `windowRead` to register the authorized connection for a window read and receive its native reply after successful decoding.
|
||||
The provider calls [installCua](src/index.ts) with its prepared helper, connection factory, guidance callback, and startup capabilities. [NativeClient](src/native-client.ts) owns request correlation, byte limits, cancellation acknowledgement, and failure settlement. The platform connector owns startup and connection cleanup. Its typed startup failures preserve their code and diagnostic through request writes and connection shutdown. The shared executor retains one connection per Agent and joins in-flight image writes during disposal. Providers can use `windowRead` to register the authorized connection for a window read and receive its native reply after successful decoding. Reads of helper-cached activity recheck consent before and after the query without taking the desktop operation lock.
|
||||
|
||||
Providers implement `CuaBackend.getGuidance(kind)` with `kind: 'raw' | 'standalone'`. Return the operation instructions for raw `cua` calls or `cua_run_code` programs respectively; both kinds may return the same text. Shared CUA applies the same capability-specific permission guidance, configured AX read defaults, and maximum click hold to both results.
|
||||
|
||||
|
||||
@@ -99,7 +99,7 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边
|
||||
|
||||
权限 Remote 还通过 `ptcConfiguration()` 和 `enablePersistentPtc()` 支持详情页的执行方式设置。查询读取现有执行器和可编辑的 profile 条目。显式写入从 Node 提供方的 `resolvePersistentExecution` 辅助函数获取执行设置,再用 `configEditor.edit()` 保留其他字段并按正常 Loader 规则重载;已是持久化模式的执行器保持不变。CUA 将 Node 提供方声明为 peer 依赖,使这些设置与已安装的提供方版本一致。此设置独立于系统权限和应用授权。
|
||||
|
||||
提供方将准备好的 helper、连接工厂、指引回调和启动能力传给 [installCua](src/index.ts)。[NativeClient](src/native-client.ts) 负责请求关联、字节上限、取消确认和失败处理。平台连接器负责启动和连接清理。其带类型的启动失败在请求写入和连接关闭时保留错误码及诊断。共享执行器为每个 Agent 保留一个连接,并在销毁时等待进行中的图像写入。提供方可通过 `windowRead` 获取窗口读取所用的授权连接,并在读取成功后接收原生回复。
|
||||
提供方将准备好的 helper、连接工厂、指引回调和启动能力传给 [installCua](src/index.ts)。[NativeClient](src/native-client.ts) 负责请求关联、字节上限、取消确认和失败处理。平台连接器负责启动和连接清理。其带类型的启动失败在请求写入和连接关闭时保留错误码及诊断。共享执行器为每个 Agent 保留一个连接,并在销毁时等待进行中的图像写入。提供方可通过 `windowRead` 获取窗口读取所用的授权连接,并在读取成功后接收原生回复。平台读取 helper 缓存的窗口活动时,会在查询前后核对应用授权,无须等待正在执行的桌面操作。
|
||||
|
||||
提供方实现 `CuaBackend.getGuidance(kind)`,其中 `kind: 'raw' | 'standalone'`,分别返回原始 `cua` 调用和 `cua_run_code` 程序的操作指引;两种形态可以返回相同文本。共享 CUA 为两份结果统一补充对应能力的权限指引、配置的 AX 读取默认值和最大点击按住时长。
|
||||
|
||||
|
||||
@@ -149,7 +149,7 @@ export class CuaAccess extends TypertRemoteService {
|
||||
* @param options Native transport and profile persistence.
|
||||
* @returns Consent selection, guarded dispatch, and task cleanup capabilities.
|
||||
*/
|
||||
export function installCuaAccess(ctx: Context, options: ControlOptions): Pick<ApplicationAccess, 'select' | 'run' | 'forget' | 'dispose'> {
|
||||
export function installCuaAccess(ctx: Context, options: ControlOptions): Pick<ApplicationAccess, 'select' | 'run' | 'readCached' | 'forget' | 'dispose'> {
|
||||
const policy = new ApplicationAccess(ctx, options)
|
||||
const lifetime = new AbortController()
|
||||
let client: NativeClient | undefined
|
||||
@@ -176,5 +176,6 @@ export function installCuaAccess(ctx: Context, options: ControlOptions): Pick<Ap
|
||||
await client?.dispose()
|
||||
}, 'cua-access.dispose')
|
||||
new CuaAccess(ctx, policy, control, options.permissionParameters)
|
||||
return { select: policy.select.bind(policy), run: policy.run.bind(policy), forget: policy.forget.bind(policy), dispose }
|
||||
return { select: policy.select.bind(policy), run: policy.run.bind(policy), readCached: policy.readCached.bind(policy),
|
||||
forget: policy.forget.bind(policy), dispose }
|
||||
}
|
||||
@@ -236,6 +236,38 @@ export class ApplicationAccess {
|
||||
*/
|
||||
async run<T>(client: NativeClient, handle: CuaAppHandle, signal: AbortSignal,
|
||||
dispatch: (signal: AbortSignal) => Promise<T>, prepare?: (signal: AbortSignal) => Promise<void>): Promise<T> {
|
||||
const { agent, selected, lifetime, requireAccess } = this.authorizedHandle(client, handle, signal)
|
||||
if (prepare) {
|
||||
await requireAccess()
|
||||
await prepare(lifetime)
|
||||
lifetime.throwIfAborted()
|
||||
}
|
||||
return this.options.store.withApplication(selected.identity.id, lifetime, async () => {
|
||||
await requireAccess()
|
||||
return this.withOperation(agent, client, selected.identity, lifetime, dispatch)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Read helper-owned metadata without queuing behind desktop input. Consent is checked again before delivery.
|
||||
* @param client Helper that holds the cached data.
|
||||
* @param handle Selected application.
|
||||
* @param signal Calling step lifetime.
|
||||
* @param read Read-only cache query, cancelled on local revocation.
|
||||
* @returns The result while the original grant remains valid.
|
||||
*/
|
||||
async readCached<T>(client: NativeClient, handle: CuaAppHandle, signal: AbortSignal,
|
||||
read: (signal: AbortSignal) => Promise<T>): Promise<T> {
|
||||
const { agent, selected, lifetime, requireAccess } = this.authorizedHandle(client, handle, signal)
|
||||
return this.withOperation(agent, client, selected.identity, lifetime, async (authorized) => {
|
||||
await requireAccess()
|
||||
const result = await read(authorized)
|
||||
await requireAccess()
|
||||
return result
|
||||
})
|
||||
}
|
||||
|
||||
private authorizedHandle(client: NativeClient, handle: CuaAppHandle, signal: AbortSignal) {
|
||||
const state = this.clients.get(client)
|
||||
const selected = state?.handles.get(handle)
|
||||
if (!state || !selected) throw new NativeError('APP_ACCESS_REQUIRED', 'Select the application with getApp and obtain user consent before reading or controlling it')
|
||||
@@ -250,15 +282,7 @@ export class ApplicationAccess {
|
||||
}
|
||||
if (client.disposed) throw new NativeError('NATIVE_CLOSED', 'Helper is closed; acquire fresh application handles')
|
||||
}
|
||||
if (prepare) {
|
||||
await requireAccess()
|
||||
await prepare(lifetime)
|
||||
lifetime.throwIfAborted()
|
||||
}
|
||||
return this.options.store.withApplication(selected.identity.id, lifetime, async () => {
|
||||
await requireAccess()
|
||||
return this.withOperation(state.agent, client, selected.identity, lifetime, dispatch)
|
||||
})
|
||||
return { agent: state.agent, selected, lifetime, requireAccess }
|
||||
}
|
||||
|
||||
private async selectInOrder(agent: Agent, id: CuaApplicationId, select: () => Promise<void>): Promise<void> {
|
||||
|
||||
@@ -176,7 +176,7 @@ async function screenshotStore(ctx: Context, execution: Readonly<CuaExecution>,
|
||||
export interface CuaWindowRead {
|
||||
agent: Agent
|
||||
client: NativeClient
|
||||
access: Pick<ReturnType<typeof installCuaAccess>, 'run'>
|
||||
access: Pick<ReturnType<typeof installCuaAccess>, 'readCached'>
|
||||
appHandle: CuaAppHandle
|
||||
windowId: string
|
||||
}
|
||||
@@ -429,7 +429,9 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend)
|
||||
if (route?.prepare) owner.coordinates.parameters(request)
|
||||
const dispatch = async (signal: AbortSignal) => {
|
||||
const scoped = { ...execution, agent, signal, nativeClient, coordinates: owner.coordinates }
|
||||
return callNative(request, scoped, route?.useSystemInput)
|
||||
const result = await callNative(request, scoped, route?.useSystemInput)
|
||||
signal.throwIfAborted()
|
||||
return result
|
||||
}
|
||||
return 'appHandle' in request.params
|
||||
? access.run(nativeClient, request.params.appHandle as CuaAppHandle, signal, dispatch, route?.prepare)
|
||||
|
||||
@@ -67,6 +67,22 @@ it('refuses raw handle dispatch until getApp obtains consent', async () => {
|
||||
expect(dispatch).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reads cached activity outside the desktop lock and discards it if another writer revokes consent', async () => {
|
||||
const f = await setup('Always allow')
|
||||
const query = vi.fn(async () => 'window activity')
|
||||
await expect(f.access.readCached(f.client, handle, signal, query)).rejects.toThrow('APP_ACCESS_REQUIRED')
|
||||
expect(query).not.toHaveBeenCalled()
|
||||
await f.access.select(f.agent, f.client, handle, identity, signal)
|
||||
const lease = vi.spyOn(f.store, 'withApplication').mockImplementation(() => { throw new Error('Desktop operation holds the lock') })
|
||||
await expect(f.access.readCached(f.client, handle, signal, query)).resolves.toBe('window activity')
|
||||
await expect(f.access.readCached(f.client, handle, signal, async () => {
|
||||
await f.save([])
|
||||
return 'withheld'
|
||||
})).rejects.toThrow('APP_ACCESS_DENIED')
|
||||
expect(f.client.disposed).toBe(true)
|
||||
expect(lease).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('saves, reuses, and revokes a native identity without executable path metadata', async () => {
|
||||
const f = await setup('Always allow')
|
||||
const withoutPath = ApplicationAuthorizationResult.parse({ id: identity.id, name: identity.name, persistable: true })
|
||||
|
||||
Reference in new issue
Block a user