diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index d4d854da74..6f0fed926a 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: 02671262241ca34f - zh: a545a9e5c657326e + en: 9ddf794c9bd4d350 + zh: f235de9e6b68481a /deepseek-ai-dsh-cua-macos/use-this-package/connect-an-external-execution-environment: en: 6097d7d03bc8dfad zh: 0978077447118d64 diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index 5bff359df0..91b1cba159 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -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. diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 017c275493..d3b1184c2d 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -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)` 返回负责截图和指针输入的对象。 diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/RecentActivity.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/RecentActivity.swift index 0d5d40ac3e..fd71114589 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/RecentActivity.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/RecentActivity.swift @@ -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 } } } diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift index 09dc856b77..8facd85eae 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift @@ -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 { diff --git a/packages/experimental/cua-macos/native/tests/Fixture.swift b/packages/experimental/cua-macos/native/tests/Fixture.swift index 63f74cd7f7..3057ad01b1 100644 --- a/packages/experimental/cua-macos/native/tests/Fixture.swift +++ b/packages/experimental/cua-macos/native/tests/Fixture.swift @@ -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, 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 bf3682ed80..3196677143 100644 --- a/packages/experimental/cua-macos/native/tests/shared_helper_e2e.py +++ b/packages/experimental/cua-macos/native/tests/shared_helper_e2e.py @@ -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) diff --git a/packages/experimental/cua-macos/native/tests/swift/RecentActivityTests.swift b/packages/experimental/cua-macos/native/tests/swift/RecentActivityTests.swift index 0e97cb8902..6476fa1926 100644 --- a/packages/experimental/cua-macos/native/tests/swift/RecentActivityTests.swift +++ b/packages/experimental/cua-macos/native/tests/swift/RecentActivityTests.swift @@ -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)])]) +} diff --git a/packages/experimental/cua-macos/src/recent-activity.ts b/packages/experimental/cua-macos/src/recent-activity.ts index 9b8b9b9c27..d80a9fb0f7 100644 --- a/packages/experimental/cua-macos/src/recent-activity.ts +++ b/packages/experimental/cua-macos/src/recent-activity.ts @@ -49,7 +49,7 @@ export function watchWindowActivity(ctx: Context): NonNullable + 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 { +export function installCuaAccess(ctx: Context, options: ControlOptions): Pick { 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(client: NativeClient, handle: CuaAppHandle, signal: AbortSignal, dispatch: (signal: AbortSignal) => Promise, prepare?: (signal: AbortSignal) => Promise): Promise { + 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(client: NativeClient, handle: CuaAppHandle, signal: AbortSignal, + read: (signal: AbortSignal) => Promise): Promise { + 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): Promise { diff --git a/packages/experimental/cua/src/index.ts b/packages/experimental/cua/src/index.ts index 64c01d9915..b5ff76231d 100644 --- a/packages/experimental/cua/src/index.ts +++ b/packages/experimental/cua/src/index.ts @@ -176,7 +176,7 @@ async function screenshotStore(ctx: Context, execution: Readonly, export interface CuaWindowRead { agent: Agent client: NativeClient - access: Pick, 'run'> + access: Pick, '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) diff --git a/packages/experimental/cua/tests/application-access.spec.ts b/packages/experimental/cua/tests/application-access.spec.ts index ca15890ab3..4ea6701b68 100644 --- a/packages/experimental/cua/tests/application-access.spec.ts +++ b/packages/experimental/cua/tests/application-access.spec.ts @@ -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 })