From 077a9cde0bc0955f5e27cf48431ca8fec609b324 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Mon, 16 Nov 2026 18:10:15 +0800 Subject: [PATCH] feat(cua): add toggleMouse with initial Windows support (#8425) * feat(cua-windows): implement window-level mouse button toggles * Update guidance * Fix prompt test --- .../profiles/cua-mcp/expected/reference.md | 10 +- .../CuaNative/NativeProtocol.generated.swift | 2 + .../cua-macos/native/protocol.schema.json | 53 +++++++ .../experimental/cua-macos/src/guidance.ts | 1 + .../cua-macos/tests/guidance.spec.ts | 54 +++++-- .../native/desktop-tests/Program.cs | 70 +++++++++ .../native/entry/DesktopExecutor.cs | 6 + .../cua-windows/native/entry/Input.cs | 12 ++ .../cua-windows/native/protocol.schema.json | 53 +++++++ .../cua-windows/native/tests/Program.cs | 22 +++ .../experimental/cua-windows/src/index.ts | 2 +- .../tests/desktop-toggle-mouse.spec.ts | 145 ++++++++++++++++++ .../tests/loader-composition.spec.ts | 6 + .../tests/provider-lifecycle.spec.ts | 1 + packages/experimental/cua/src/api.ts | 3 + packages/experimental/cua/src/guidance.ts | 10 +- packages/experimental/cua/src/protocol.ts | 1 + packages/experimental/cua/src/types.ts | 10 +- packages/experimental/cua/tests/api.spec.ts | 32 ++++ .../cua/tests/native-schema.spec.ts | 7 + .../experimental/cua/tests/protocol.spec.ts | 22 +++ .../cua-run-code/system-prompt.expected.md | 10 +- .../cua-native/system-prompt.expected.md | 10 +- .../cua-native/tool-schemas.expected.json | 49 ++++++ .../session/cua-ptc/system-prompt.expected.md | 10 +- .../system-prompt.expected.md | 10 +- .../cua-run-code/system-prompt.expected.md | 10 +- .../system-prompt.expected.md | 10 +- 28 files changed, 600 insertions(+), 31 deletions(-) create mode 100644 packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts diff --git a/apps/cli/tests/profiles/cua-mcp/expected/reference.md b/apps/cli/tests/profiles/cua-mcp/expected/reference.md index c7ef7c99e1..ea7301ee1b 100644 --- a/apps/cli/tests/profiles/cua-mcp/expected/reference.md +++ b/apps/cli/tests/profiles/cua-mcp/expected/reference.md @@ -31,10 +31,14 @@ Read getAccessibilityTree explicitly before using element ids. Selection and scr - setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value. - selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate. -## Simulated mouse -Use an explicit window for screenshots and pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. +## Screenshots +Use an explicit window for screenshots. - getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. + +## Simulated mouse +Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. @@ -48,6 +52,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. +click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. + Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. AX read defaults: maxElements=2000, maxDepth=25. diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift index 39e9f04e49..a7317d8e38 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift @@ -30,6 +30,7 @@ enum NativeProtocol { "sendKeyEvent": ["appHandle", "direction", "key", "runId", "windowId"], "setValue": ["appHandle", "elementId", "snapshotId", "value", "windowId"], "show": ["appHandle", "windowId"], + "toggleMouse": ["appHandle", "direction", "mouseButton", "windowId"], "typeText": ["appHandle", "text", "windowId"], ] static let stringEnums: [String: [String: Set]] = [ @@ -40,5 +41,6 @@ enum NativeProtocol { "requestPermission": ["permission": ["accessibility", "screenRecording"]], "selectText": ["selectionType": ["cursor_after", "cursor_before", "text"]], "sendKeyEvent": ["direction": ["down", "up"]], + "toggleMouse": ["direction": ["down", "up"], "mouseButton": ["left", "middle", "right"]], ] } diff --git a/packages/experimental/cua-macos/native/protocol.schema.json b/packages/experimental/cua-macos/native/protocol.schema.json index 801414e010..472c3f3b80 100644 --- a/packages/experimental/cua-macos/native/protocol.schema.json +++ b/packages/experimental/cua-macos/native/protocol.schema.json @@ -451,6 +451,59 @@ ], "additionalProperties": false }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "toggleMouse" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "string", + "minLength": 1 + }, + "mouseButton": { + "type": "string", + "enum": [ + "left", + "right", + "middle" + ] + }, + "direction": { + "type": "string", + "enum": [ + "down", + "up" + ] + } + }, + "required": [ + "appHandle", + "windowId", + "mouseButton", + "direction" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, { "type": "object", "properties": { diff --git a/packages/experimental/cua-macos/src/guidance.ts b/packages/experimental/cua-macos/src/guidance.ts index 332d36f163..20f5257334 100644 --- a/packages/experimental/cua-macos/src/guidance.ts +++ b/packages/experimental/cua-macos/src/guidance.ts @@ -13,6 +13,7 @@ function operationGuidance(treeAdvice: string): string { ['sendKeyEvent', "Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients."], ['getAccessibilityTree', `macOS accepts maxElements up to 100000 and maxDepth up to 512. If the tree is truncated, select a narrower window or raise the reported limit on the next read. ${treeAdvice} Use element ids from the file only while that observation is current.`], ['mouseMove', 'With useSystemPointer omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again.'], + ['toggleMouse', 'Not implemented on macOS.'], ['drag', 'Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control. An explicit system drag shares the session decision with mouseMove and holds the chosen button along the path in the unobscured foreground window.'], ['click', 'click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying.'], ]) diff --git a/packages/experimental/cua-macos/tests/guidance.spec.ts b/packages/experimental/cua-macos/tests/guidance.spec.ts index f31ca9e6b7..3fb53d70e3 100644 --- a/packages/experimental/cua-macos/tests/guidance.spec.ts +++ b/packages/experimental/cua-macos/tests/guidance.spec.ts @@ -1,4 +1,4 @@ -/** Model-facing guidance enumerates the full available object API without unavailable operations. */ +/** Model-facing guidance lists the object API with platform availability and input constraints. */ import { expect, it } from 'vitest' import type { CuaApi, CuaApp, CuaSurface, CuaWindow } from '@deepseek-ai/dsh-cua/api' import { COMMON_GUIDANCE, withSystemPointerGuidance } from '@deepseek-ai/dsh-cua/guidance' @@ -9,7 +9,7 @@ const accessibilityNames: Array> = [ 'getAccessibilityTree', 'listActions', 'invoke', 'performAction', 'setValue', 'selectText', ] const appNames: Array = ['appHandle', 'activate', 'getWindows', 'getWindow'] -const windowNames: Array = ['windowId', 'getScreenshot', 'mouseMove', 'click', 'scroll', 'drag'] +const windowNames: Array = ['windowId', 'getScreenshot', 'mouseMove', 'toggleMouse', 'click', 'scroll', 'drag'] it('keeps file-tool instructions in PTC and limits the program guidance to available bindings', () => { for (const name of ['tools.write', 'tools.grep', 'tools.read']) { @@ -20,11 +20,13 @@ it('keeps file-tool instructions in PTC and limits the program guidance to avail expect(PROGRAM_GUIDANCE).toContain('session’s file tools') }) -it('keeps exactly three ordered operation headings', () => { - const heads = COMMON_GUIDANCE.match(/^## .+$/gm) - expect(heads).toEqual(['## Accessibility tree', '## Simulated mouse', '## Simulated keyboard']) - expect(COMMON_GUIDANCE.indexOf('## Accessibility tree')).toBeLessThan(COMMON_GUIDANCE.indexOf('## Simulated mouse')) - expect(COMMON_GUIDANCE.indexOf('## Simulated mouse')).toBeLessThan(COMMON_GUIDANCE.indexOf('## Simulated keyboard')) +it('places observation chapters before simulated input with screenshots in their own chapter', () => { + for (const catalog of [COMMON_GUIDANCE, GUIDANCE, PROGRAM_GUIDANCE]) { + expect(catalog.match(/^## .+$/gm)).toEqual(['## Accessibility tree', '## Screenshots', '## Simulated mouse', '## Simulated keyboard']) + const screenshots = catalog.slice(catalog.indexOf('## Screenshots'), catalog.indexOf('## Simulated mouse')) + expect(screenshots).toContain('- getScreenshot() -> Image') + expect(catalog.slice(catalog.indexOf('## Simulated mouse'))).not.toContain('- getScreenshot(') + } }) it('prefixes concise platform guidance before the shared catalog', () => { @@ -67,7 +69,23 @@ it('states the macOS accessibility, keyboard, and mouse levels', () => { } }) -it('enumerates every available method once in its catalog entry', () => { +it('documents explicit mouse-button events immediately after mouseMove', () => { + const lines = COMMON_GUIDANCE.split('\n') + const index = lines.findIndex(line => line.startsWith('- toggleMouse(')) + expect(lines[index - 1]).toMatch(/^- mouseMove\(/) + expect(lines[index]).toBe("- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically.") + expect(index).toBeGreaterThan(lines.indexOf('## Simulated mouse')) + expect(index).toBeLessThan(lines.indexOf('## Simulated keyboard')) +}) + +it.each([GUIDANCE, PROGRAM_GUIDANCE])('marks toggleMouse as unavailable in the macOS method entry', (catalog) => { + const shared = COMMON_GUIDANCE.split('\n').find(line => line.startsWith('- toggleMouse(')) + const entry = catalog.split('\n').find(line => line.startsWith('- toggleMouse(')) + expect(entry).toBe(`${shared} Not implemented on macOS.`) + expect(PLATFORM_GUIDANCE).not.toContain('toggleMouse') +}) + +it('enumerates every public method once in its catalog entry', () => { const signatures = [ ...apiNames.map(name => `cua.${name}(`), ...appNames.filter(name => name !== 'appHandle').map(name => `app.${name}(`), @@ -79,8 +97,8 @@ it('enumerates every available method once in its catalog entry', () => { for (const catalog of [COMMON_GUIDANCE, GUIDANCE, PROGRAM_GUIDANCE]) { for (const signature of signatures) expect(catalog.split('\n').filter(line => line.startsWith(`- ${signature}`))).toHaveLength(1) } - expect(signatures).toHaveLength(25) - expect(new Set(signatures.map(signature => signature.slice(signature.indexOf('.') + 1, -1))).size).toBe(24) + expect(signatures).toHaveLength(26) + expect(new Set(signatures.map(signature => signature.slice(signature.indexOf('.') + 1, -1))).size).toBe(25) expect(COMMON_GUIDANCE).toContain('app.appHandle') expect(COMMON_GUIDANCE).toContain('window.windowId') }) @@ -128,7 +146,8 @@ it('references Modifier without defining its members in shared guidance', () => }) it('states platform-dependent levels without qualifying grouped method names', () => { - expect(COMMON_GUIDANCE).toContain('## Simulated mouse\nUse an explicit window for screenshots and pointer input.') + expect(COMMON_GUIDANCE).toContain('## Screenshots\nUse an explicit window for screenshots.') + expect(COMMON_GUIDANCE).toContain('## Simulated mouse\nUse an explicit window for pointer input.') for (const heading of ['Accessibility tree', 'Simulated keyboard']) { expect(COMMON_GUIDANCE).toContain(`## ${heading}\nAvailable at app or window level depending on the platform.`) } @@ -139,6 +158,15 @@ it('states platform-dependent levels without qualifying grouped method names', ( expect(COMMON_GUIDANCE).toContain('from: [number, number]') }) +it('guides complex input combinations through platform-supported primitive operations', () => { + const advice = 'click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform.' + for (const catalog of [COMMON_GUIDANCE, GUIDANCE, PROGRAM_GUIDANCE]) { + expect(catalog).toContain(advice) + expect(catalog.indexOf(advice)).toBeGreaterThan(catalog.indexOf('- sendKeyEvent(')) + expect(catalog.indexOf(advice)).toBeLessThan(catalog.indexOf('Raw tools use { method, params }')) + } +}) + it('keeps consent, lock, observation, and no-replay rules', () => { expect(COMMON_GUIDANCE).toContain('consent') expect(COMMON_GUIDANCE).toContain('SESSION_LOCKED') @@ -159,6 +187,6 @@ it('documents explicit inspection and separate key arguments', () => { expect(COMMON_GUIDANCE).toContain('perform a left-button double-click') }) -it('omits stale names and unavailable platform operations', () => { - for (const stale of ['getAXState', 'emit', 'disableDiffing', 'performSecondaryAction', 'hover(', 'keyChord', 'window.typeText', 'window.pressKey', 'elementIndex', 'verified: false', 'browser tabs', 'not implemented']) expect(GUIDANCE).not.toContain(stale) +it('omits stale names and unrelated operations', () => { + for (const stale of ['getAXState', 'emit', 'disableDiffing', 'performSecondaryAction', 'hover(', 'keyChord', 'window.typeText', 'window.pressKey', 'elementIndex', 'verified: false', 'browser tabs']) expect(GUIDANCE).not.toContain(stale) }) diff --git a/packages/experimental/cua-windows/native/desktop-tests/Program.cs b/packages/experimental/cua-windows/native/desktop-tests/Program.cs index 58421dec24..3371433909 100644 --- a/packages/experimental/cua-windows/native/desktop-tests/Program.cs +++ b/packages/experimental/cua-windows/native/desktop-tests/Program.cs @@ -11,6 +11,7 @@ internal sealed class FixtureForm : Form internal readonly TextBox Editor = new() { Name = "editor", AccessibleName = "CUA test text", Multiline = true, Bounds = new(20, 20, 440, 100) }; private readonly Button button = new() { Name = "submit", Text = "Record click", Bounds = new(20, 140, 180, 40) }; private int clicks; + private int leftDowns, leftUps, rightDowns, rightUps, middleDowns, middleUps; private readonly ToolTip tooltip = new(); internal FixtureForm(string title) @@ -22,13 +23,55 @@ internal sealed class FixtureForm : Form Controls.Add(Editor); Controls.Add(button); button.Click += (_, _) => clicks++; + button.MouseDown += (_, e) => Count(e.Button, down: true); + button.MouseUp += (_, e) => Count(e.Button, down: false); + Editor.MouseDown += (_, e) => Count(e.Button, down: true); + Editor.MouseUp += (_, e) => Count(e.Button, down: false); tooltip.SetToolTip(button, "CUA hover is retained"); } + private void Count(MouseButtons pressed, bool down) + { + switch (pressed) + { + case MouseButtons.Left: if (down) leftDowns++; else leftUps++; break; + case MouseButtons.Right: if (down) rightDowns++; else rightUps++; break; + case MouseButtons.Middle: if (down) middleDowns++; else middleUps++; break; + } + } + + internal void PointAtButton() => Cursor.Position = button.PointToScreen(new Point(button.Width / 2, button.Height / 2)); + + internal void PointOutside() + { + var bounds = RectangleToScreen(ClientRectangle); + Cursor.Position = new Point(bounds.Right + 40, bounds.Top + 20); + } + + internal void Cover(FixtureForm cover) + { + cover.Bounds = Bounds; + cover.TopMost = true; + cover.Show(); + Activate(); + PointAtButton(); + } + + internal void Uncover(FixtureForm cover) + { + if (cover.Visible) cover.Hide(); + cover.TopMost = false; + Activate(); + PointAtButton(); + } + internal object Inspect() => new { text = Editor.Text, clicks, window = Handle.ToString(CultureInfo.InvariantCulture), foreground = GetForegroundWindow().ToString(CultureInfo.InvariantCulture), cursor = new { x = Cursor.Position.X, y = Cursor.Position.Y }, + under = GetAncestor(WindowFromPoint(Cursor.Position), 2).ToString(CultureInfo.InvariantCulture), + downs = new { left = leftDowns, right = rightDowns, middle = middleDowns }, + ups = new { left = leftUps, right = rightUps, middle = middleUps }, button = new { x = button.Left + button.Width / 2, y = button.Top + button.Height / 2 }, selection = new { start = Editor.SelectionStart, length = Editor.SelectionLength }, buttons = MouseButtons.ToString(), minimized = WindowState == FormWindowState.Minimized, visible = Visible, @@ -41,12 +84,31 @@ internal sealed class FixtureForm : Form } [DllImport("user32.dll")] private static extern nint GetForegroundWindow(); + [DllImport("user32.dll")] private static extern nint WindowFromPoint(Point point); + [DllImport("user32.dll")] private static extern nint GetAncestor(nint window, uint flags); } internal static class Program { private static void Write(object value) { Console.WriteLine(JsonSerializer.Serialize(value)); Console.Out.Flush(); } + private static void ReleaseButtons() + { + var inputs = new[] { 0x0004u, 0x0010u, 0x0040u } + .Select(flags => new Input { Type = 0, Data = new MouseInput { Flags = flags } }).ToArray(); + if (SendInput((uint)inputs.Length, inputs, Marshal.SizeOf()) != inputs.Length) + { + Console.Error.WriteLine("Fixture could not release every mouse button"); + Environment.ExitCode = 1; + } + } + + [StructLayout(LayoutKind.Sequential)] + private struct MouseInput { public int X, Y; public uint Data, Flags, Time; public nuint ExtraInfo; } + + [StructLayout(LayoutKind.Sequential)] + private struct Input { public uint Type; public MouseInput Data; } + [STAThread] private static void Main() { @@ -68,6 +130,11 @@ internal static class Program case "sibling": sibling.Show(); sibling.Activate(); sibling.Editor.Focus(); Write(sibling.Inspect()); break; case "inspect": Write(form.Inspect()); break; case "focus": form.Activate(); form.Editor.Focus(); Write(form.Inspect()); break; + case "pointer": form.PointAtButton(); Write(form.Inspect()); break; + case "pointer-outside": form.PointOutside(); Write(form.Inspect()); break; + case "cover": form.Cover(sibling); Write(new { form = form.Inspect(), sibling = sibling.Inspect() }); break; + case "uncover": form.Uncover(sibling); Write(form.Inspect()); break; + case "release-input": ReleaseButtons(); Write(form.Inspect()); break; case "minimize": form.WindowState = FormWindowState.Minimized; Write(form.Inspect()); break; case "hide": form.Hide(); Write(form.Inspect()); break; case "resize": form.Width += 50; Write(form.Inspect()); break; @@ -93,4 +160,7 @@ internal static class Program [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool AllowSetForegroundWindow(uint processId); + + [DllImport("user32.dll", SetLastError = true)] + private static extern uint SendInput(uint count, [In] Input[] inputs, int size); } diff --git a/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs b/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs index 666bd9c48a..6af36d042f 100644 --- a/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs +++ b/packages/experimental/cua-windows/native/entry/DesktopExecutor.cs @@ -169,6 +169,12 @@ internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta) : IA var pointed = Coordinate(app, parameters, context); return Input.MouseMove(app, pointed.Window, pointed.X, pointed.Y, context); } + case "toggleMouse": + { + var target = Selected(app, parameters, context); + Input.ToggleMouse(app, target, String(parameters, "mouseButton"), String(parameters, "direction"), context); + return ActionResult(foreground); + } case "scroll": { var target = Coordinate(app, parameters, context); diff --git a/packages/experimental/cua-windows/native/entry/Input.cs b/packages/experimental/cua-windows/native/entry/Input.cs index 7493acc990..9d186055d5 100644 --- a/packages/experimental/cua-windows/native/entry/Input.cs +++ b/packages/experimental/cua-windows/native/entry/Input.cs @@ -162,6 +162,18 @@ internal static class Input return new { dispatched = true, hoverRoute = "system-pointer", systemPointerMoved = before.X != point.X || before.Y != point.Y }; } + internal static void ToggleMouse(AppState app, WindowState window, string button, string direction, RequestContext context) + { + var flags = Button(button); + if (direction == "down") + { + if (!Win32.GetCursorPos(out var point)) throw new NativeFailure("INPUT_UNAVAILABLE", "The current pointer position is unavailable"); + Hit(app, window, point, context); + } + else Windows.RequireForeground(app, window, context); + Send(Mouse(direction == "down" ? flags.Down : flags.Up)); + } + internal static void Click(AppState app, WindowState window, double x, double y, string button, int count, string[] modifiers, RequestContext context) { if (button != "left" && count != 1) throw new NativeFailure("UNSUPPORTED", "Only left clicks support double-click"); diff --git a/packages/experimental/cua-windows/native/protocol.schema.json b/packages/experimental/cua-windows/native/protocol.schema.json index bb03a5a331..22763d1b61 100644 --- a/packages/experimental/cua-windows/native/protocol.schema.json +++ b/packages/experimental/cua-windows/native/protocol.schema.json @@ -451,6 +451,59 @@ ], "additionalProperties": false }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "toggleMouse" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "string", + "minLength": 1 + }, + "mouseButton": { + "type": "string", + "enum": [ + "left", + "right", + "middle" + ] + }, + "direction": { + "type": "string", + "enum": [ + "down", + "up" + ] + } + }, + "required": [ + "appHandle", + "windowId", + "mouseButton", + "direction" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, { "type": "object", "properties": { diff --git a/packages/experimental/cua-windows/native/tests/Program.cs b/packages/experimental/cua-windows/native/tests/Program.cs index 1a76604edb..520a805ab6 100644 --- a/packages/experimental/cua-windows/native/tests/Program.cs +++ b/packages/experimental/cua-windows/native/tests/Program.cs @@ -56,6 +56,28 @@ foreach (var method in new[] { "listActions", "performAction", "invoke", "mouseM }))); Check(operation.Params.GetProperty("elementId").GetString() == "42/-7/9", "Element operations preserve slash-separated RuntimeIds: " + method); } +foreach (var mouseButton in new[] { "left", "right", "middle" }) +foreach (var direction in new[] { "down", "up" }) +{ + var toggle = NativeRequest.Parse(WireJson.Parse(System.Text.Json.JsonSerializer.Serialize(new + { + id = "mouse", method = "toggleMouse", @params = new { appHandle = "app", windowId = "1", mouseButton, direction }, + }))); + Check(toggle.Params.GetProperty("mouseButton").GetString() == mouseButton + && toggle.Params.GetProperty("direction").GetString() == direction, + "Mouse-button events retain the explicit button and direction"); +} +foreach (var invalid in new[] +{ + """{"appHandle":"app","windowId":"1","mouseButton":"left"}""", + """{"appHandle":"app","windowId":"1","direction":"down"}""", + """{"appHandle":"app","mouseButton":"left","direction":"down"}""", + """{"appHandle":"app","windowId":"1","mouseButton":"back","direction":"down"}""", + """{"appHandle":"app","windowId":"1","mouseButton":"left","direction":"press"}""", + """{"appHandle":"app","windowId":"1","mouseButton":"left","direction":"down","x":1,"y":2}""", +}) + Refuses(() => NativeRequest.Parse(WireJson.Parse("{\"id\":\"mouse\",\"method\":\"toggleMouse\",\"params\":" + invalid + "}")), "INVALID_ARGUMENT"); + var launch = NativeRequest.Parse(WireJson.Parse("""{"id":"launch","method":"launchApp","params":{"appHandle":"pending"}}""")); Check(launch.Method == "launchApp" && launch.Params.GetProperty("appHandle").GetString() == "pending", "Host launch continuation retains the selected application handle"); diff --git a/packages/experimental/cua-windows/src/index.ts b/packages/experimental/cua-windows/src/index.ts index 8e63904c91..3be20956f5 100644 --- a/packages/experimental/cua-windows/src/index.ts +++ b/packages/experimental/cua-windows/src/index.ts @@ -14,7 +14,7 @@ const CAPABILITIES: CuaStartupCapabilities = { platform: 'windows', methods: [ 'getCapabilities', 'listApps', 'getApp', 'activate', 'show', 'listWindows', 'getState', - 'listActions', 'performAction', 'invoke', 'mouseMove', 'click', 'setValue', 'selectText', + 'listActions', 'performAction', 'invoke', 'mouseMove', 'toggleMouse', 'click', 'setValue', 'selectText', 'typeText', 'paste', 'pressKey', 'sendKeyEvent', 'scroll', 'drag', 'screenshot', ], appLevelAccessibility: false, diff --git a/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts b/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts new file mode 100644 index 0000000000..25a37bb8e2 --- /dev/null +++ b/packages/experimental/cua-windows/tests/desktop-toggle-mouse.spec.ts @@ -0,0 +1,145 @@ +/** Opt-in real Windows mouse-button toggles through the native helper. */ +import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process' +import { createInterface } from 'node:readline' +import { Context } from '@deepseek-ai/cordis' +import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local' +import { NativeClient } from '@deepseek-ai/dsh-cua/native-client' +import { expect, it } from 'vitest' +import { z } from 'zod' +import { Config } from '../src/index.ts' +import { WindowsNativeRuntime } from '../src/native-runtime.ts' + +const helperPath = process.env.DSH_CUA_DESKTOP_TEST_HELPER +const fixturePath = process.env.DSH_CUA_DESKTOP_TEST_FIXTURE +const Counts = z.object({ left: z.number().int(), right: z.number().int(), middle: z.number().int() }) +const FixtureState = z.object({ + window: z.string(), foreground: z.string(), + cursor: z.object({ x: z.number().int(), y: z.number().int() }), + under: z.string(), buttons: z.string(), clicks: z.number().int(), downs: Counts, ups: Counts, +}) +const Initial = z.object({ pid: z.number().int(), state: FixtureState }) +const Cover = z.object({ form: FixtureState, sibling: FixtureState }) +const App = z.object({ appHandle: z.string(), running: z.boolean() }) +const Windows = z.array(z.object({ windowId: z.string(), title: z.string() })) +const ToggleResult = z.object({ dispatched: z.boolean() }) + +interface Fixture { + readonly child: ChildProcessWithoutNullStreams + readonly exit: Promise + read(schema: z.ZodType): Promise + command(text: string, schema: z.ZodType): Promise +} + +function fixtureProcess(path: string): Fixture { + const child = spawn(path, [], { windowsHide: true }) + child.stderr.pipe(process.stderr) + const reader = createInterface({ input: child.stdout }) + const iterator = reader[Symbol.asyncIterator]() + const exit = new Promise((resolve) => { + child.once('error', (error) => { reader.close(); resolve(error) }) + child.once('exit', (code, signal) => { + reader.close() + resolve(code === 0 ? undefined : new Error(`Fixture exited with code ${code}, signal ${signal}`)) + }) + }) + const read = async (schema: z.ZodType): Promise => { + const next = await iterator.next() + if (next.done) throw new Error('The fixture exited before replying') + return schema.parse(JSON.parse(next.value)) + } + return { child, exit, read, command: async (text, schema) => { child.stdin.write(text + '\n'); return read(schema) } } +} + +async function releaseAndClose(fixture: Fixture): Promise { + let forced = false + const timer = setTimeout(() => { forced = true; fixture.child.kill() }, 5000) + try { + if (fixture.child.exitCode === null && fixture.child.signalCode === null && fixture.child.pid !== undefined) { + // The fixture processes release before close even if an earlier inspection is still awaiting its reply. + fixture.child.stdin.end('release-input\nclose\n') + } + const error = await fixture.exit + if (forced) throw new Error('Fixture shutdown timed out; mouse-button release could not be confirmed', { cause: error }) + if (error) throw error + } finally { clearTimeout(timer) } +} + +it.skipIf(process.platform !== 'win32' || !helperPath || !fixturePath)( + 'toggles mouse buttons without movement, observation, or implicit release', + async ({ onTestFinished, signal }) => { + const fixture = fixtureProcess(fixturePath!) + const ctx = new Context() + const cleanups: Array<() => Promise> = [] + onTestFinished(async () => { + const errors: unknown[] = [] + for (const cleanup of [ + () => releaseAndClose(fixture), ...cleanups.toReversed(), () => ctx.fiber.dispose(), + ]) { + try { await cleanup() } catch (error) { errors.push(error) } + } + if (errors.length > 0) throw new AggregateError(errors, 'Desktop mouse test cleanup failed') + }) + const inspect = () => fixture.command('inspect', FixtureState) + const observed = async (expected: object) => { + let state = await inspect() + await expect.poll(async () => { state = await inspect(); return state }, { timeout: 5000, interval: 25 }).toMatchObject(expected) + return state + } + const initial = await fixture.read(Initial) + const focused = await fixture.command('focus', FixtureState) + expect(focused.window).toBe(initial.state.window) + expect(focused.foreground, 'Windows denied foreground to the private fixture').toBe(focused.window) + expect(focused.buttons).toBe('None') + + await ctx.plugin(LocalSubprocessRuntime) + const nativeRuntime = new WindowsNativeRuntime(ctx, 25, 1000, 'pipe') + cleanups.push(() => nativeRuntime.dispose()) + const native = new NativeClient(ctx, { ...Config({}), helperPath: helperPath!, cwd: process.cwd() }, + (_owner, config) => nativeRuntime.connect(config)) + cleanups.push(() => native.dispose()) + const app = App.parse(await native.request('getApp', { selector: fixturePath! }, signal)) + expect(app.running).toBe(true) + const windows = Windows.parse(await native.request('listWindows', { appHandle: app.appHandle }, signal)) + const windowId = initial.state.window + expect(windows.some(window => window.windowId === windowId)).toBe(true) + const toggle = async (mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') => + ToggleResult.parse(await native.request('toggleMouse', { appHandle: app.appHandle, windowId, mouseButton, direction }, signal)) + + const { cursor } = await fixture.command('pointer', FixtureState) + for (const mouseButton of ['left', 'right', 'middle'] as const) { + const before = await inspect() + expect((await toggle(mouseButton, 'down')).dispatched).toBe(true) + const down = await observed({ cursor, buttons: { left: 'Left', right: 'Right', middle: 'Middle' }[mouseButton], + downs: { [mouseButton]: before.downs[mouseButton] + 1 }, ups: before.ups }) + await native.request('getCapabilities', {}, signal) + expect(await inspect()).toMatchObject({ cursor, buttons: down.buttons, ups: down.ups }) + expect((await toggle(mouseButton, 'up')).dispatched).toBe(true) + await observed({ cursor, buttons: 'None', ups: { [mouseButton]: down.ups[mouseButton] + 1 }, + clicks: down.clicks + (mouseButton === 'left' ? 1 : 0) }) + } + + const sibling = await fixture.command('sibling', FixtureState) + expect(sibling.foreground).toBe(sibling.window) + const background = await inspect() + await expect(toggle('left', 'down')).rejects.toMatchObject({ code: 'FOREGROUND_REQUIRED' }) + expect(await inspect()).toMatchObject({ buttons: 'None', downs: background.downs }) + const restored = await fixture.command('focus', FixtureState) + expect(restored.foreground).toBe(restored.window) + + const cover = await fixture.command('cover', Cover) + expect(cover.form.foreground).toBe(cover.form.window) + expect(cover.form.under).toBe(cover.sibling.window) + await expect(toggle('left', 'down')).rejects.toMatchObject({ code: 'WINDOW_OBSCURED' }) + expect(await inspect()).toMatchObject({ buttons: 'None', downs: cover.form.downs }) + const uncovered = await fixture.command('uncover', FixtureState) + expect(uncovered.foreground).toBe(uncovered.window) + + expect((await toggle('left', 'down')).dispatched).toBe(true) + const pressed = await observed({ buttons: 'Left', downs: { left: uncovered.downs.left + 1 } }) + const outside = await fixture.command('pointer-outside', FixtureState) + expect(outside.cursor).not.toEqual(pressed.cursor) + expect(outside.foreground).toBe(outside.window) + expect(outside.under).not.toBe(outside.window) + expect((await toggle('left', 'up')).dispatched).toBe(true) + await observed({ buttons: 'None', cursor: outside.cursor, ups: { left: pressed.ups.left + 1 }, clicks: pressed.clicks }) + }, 120_000) diff --git a/packages/experimental/cua-windows/tests/loader-composition.spec.ts b/packages/experimental/cua-windows/tests/loader-composition.spec.ts index 3f2dc48b47..e90acbbf49 100644 --- a/packages/experimental/cua-windows/tests/loader-composition.spec.ts +++ b/packages/experimental/cua-windows/tests/loader-composition.spec.ts @@ -31,6 +31,12 @@ it.skipIf(process.platform !== 'win32')('loads the Windows provider and rejects const prompt = await ctx.systemPrompt.assemble({ scope: agent }) expect(prompt.sections.find(section => section.name === 'computer-use:dsh-cua')?.text).toContain('Windows:') expect(prompt.sections.find(section => section.name === 'computer-use:dsh-cua')?.text).not.toContain('useSystemPointer') + const toggleMouse = prompt.sections.find(section => section.name === 'computer-use:dsh-cua')?.text + .split('\n').find(line => line.startsWith('- toggleMouse(')) + expect(toggleMouse).toContain("toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult") + expect(toggleMouse).toContain("Release held buttons explicitly with 'up'; the opposite event is not sent automatically.") + expect(toggleMouse).toContain('press or release the specified mouse button at the current pointer position without moving it.') + expect(toggleMouse).not.toContain('Not implemented') expect(JSON.stringify(ctx.tools.get('cua', agent)!.parameters)).not.toContain('useSystemPointer') const batch = await ctx.tools.execute({ agent, signal: new AbortController().signal, calls: [{ type: 'tool-call', id: brandString('invalid-window'), name: 'cua', diff --git a/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts index 9e8c2601bf..dcee6fa104 100644 --- a/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts @@ -49,6 +49,7 @@ it('uses an absolute fixture without compiling and disposes the Host runtime', a expect(backend.permissionParameters('requestPermission', 'accessibility', 'en')).toEqual({ permission: 'accessibility' }) expect(backend.capabilities).toMatchObject({ platform: 'windows', appLevelAccessibility: false, keyboard: ['window'] }) expect(backend.capabilities.methods).toContain('sendKeyEvent') + expect(backend.capabilities.methods).toContain('toggleMouse') expect(backend.sendKeyEvent).toBeUndefined() const channel = { marker: 'native stream' } native.connect.mockReturnValue(channel) diff --git a/packages/experimental/cua/src/api.ts b/packages/experimental/cua/src/api.ts index 319b2888f6..7e98c2a041 100644 --- a/packages/experimental/cua/src/api.ts +++ b/packages/experimental/cua/src/api.ts @@ -191,6 +191,9 @@ function createCuaObjects(call: ReturnType): { const [x, y] = targetPoint return HoverResult.parse(await base.call('mouseMove', { ...coordinateParams(appHandle, windowId), x, y, ...relative }, options)) }, + async toggleMouse(mouseButton, direction) { + return base.action('toggleMouse', { mouseButton, direction }) + }, async click(targetPoint, options) { const mouseButton = options?.mouseButton ?? 'left' const clickCount = options?.clickCount ?? 1 diff --git a/packages/experimental/cua/src/guidance.ts b/packages/experimental/cua/src/guidance.ts index 35524cf70d..de995fa93e 100644 --- a/packages/experimental/cua/src/guidance.ts +++ b/packages/experimental/cua/src/guidance.ts @@ -36,10 +36,14 @@ Read getAccessibilityTree explicitly before using element ids. Selection and scr - setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value. - selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate. -## Simulated mouse -Use an explicit window for screenshots and pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. +## Screenshots +Use an explicit window for screenshots. - getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. + +## Simulated mouse +Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - ${hoverSignature} -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. @@ -53,6 +57,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. +click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. + Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name.` /** diff --git a/packages/experimental/cua/src/protocol.ts b/packages/experimental/cua/src/protocol.ts index 081ff2adc4..7ee5d6f017 100644 --- a/packages/experimental/cua/src/protocol.ts +++ b/packages/experimental/cua/src/protocol.ts @@ -72,6 +72,7 @@ function requestSchema(hover: H, drag: operation('listActions', snapshot), operation('performAction', { ...snapshot, action: z.string().min(1), argument: jsonValue.optional() }), operation('invoke', snapshot), + operation('toggleMouse', { ...window, mouseButton: pointer.mouseButton.unwrap(), direction: z.enum(['down', 'up']) }), z.object({ method: z.literal('mouseMove'), params: hover }).strict(), z.object({ method: z.literal('click'), params: z.union([ z.object({ ...snapshot, ...click }).strict(), diff --git a/packages/experimental/cua/src/types.ts b/packages/experimental/cua/src/types.ts index 4c6d173c24..b38229c220 100644 --- a/packages/experimental/cua/src/types.ts +++ b/packages/experimental/cua/src/types.ts @@ -62,7 +62,7 @@ export interface CuaCoordinateOptions { export type CuaShowResult = z.output /** Modifiers attached to a window-directed pointer gesture. */ export type CuaPointerModifier = NonNullable['modifiers']>[number] -/** Buttons supported by window-directed clicks and drags. */ +/** Buttons supported by window-directed mouse input. */ export type CuaMouseButton = NonNullable['mouseButton']> /** * Left clicks support one or two presses; right and middle clicks support one. @@ -191,6 +191,14 @@ export interface CuaWindow extends CuaSurface { */ mouseMove(target: CuaElementId | readonly [number, number], options?: CuaCoordinateOptions & { useSystemPointer?: boolean }): Promise + /** + * Send one mouse-button down or up event without moving the pointer. + * Does not send the opposite event; callers explicitly release a pressed button. + * @param mouseButton - Mouse button to press or release. + * @param direction - Explicit event direction. + * @returns Whether the provider successfully executed the requested operation. + */ + toggleMouse(mouseButton: CuaMouseButton, direction: 'down' | 'up'): Promise /** * Click a current element id or screenshot-local point. * Cancellation or timeout releases the held button; received input cannot be undone. The operation deadline includes holdMs. diff --git a/packages/experimental/cua/tests/api.spec.ts b/packages/experimental/cua/tests/api.spec.ts index c17a0ea7b7..de8325bfb2 100644 --- a/packages/experimental/cua/tests/api.spec.ts +++ b/packages/experimental/cua/tests/api.spec.ts @@ -953,6 +953,38 @@ describe('input actions', () => { expect(windowFixture.dispatch).not.toHaveBeenCalled() }) + it.each(['left', 'right', 'middle'] as const)('dispatches one %s mouse-button event without an observation', async (mouseButton) => { + const f = fixture() + const app = await f.api.getApp('Editor') + const window = await app.getWindow('23') + expect(app).not.toHaveProperty('toggleMouse') + expectTypeOf().not.toHaveProperty('toggleMouse') + expectTypeOf().parameters.toEqualTypeOf<[ + mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up', + ]>() + for (const direction of ['down', 'up'] as const) { + f.dispatch.mockClear() + await expect(window.toggleMouse(mouseButton, direction)).resolves.toEqual(delivered) + expect(f.dispatch).toHaveBeenCalledExactlyOnceWith({ method: 'toggleMouse', params: { + appHandle: 'app-17', windowId: '23', mouseButton, direction, + } }) + } + }) + + it('preserves mouse-button dispatch failures without retries or an opposite event', async () => { + const f = fixture() + const window = await (await f.api.getApp('Editor')).getWindow('23') + f.dispatch.mockClear() + f.dispatch.mockResolvedValueOnce({ dispatched: false }) + await expect(window.toggleMouse('left', 'down')).resolves.toEqual({ dispatched: false }) + const failure = new Error('Mouse-button input is not supported') + f.dispatch.mockRejectedValueOnce(failure) + await expect(window.toggleMouse('left', 'up')).rejects.toBe(failure) + f.dispatch.mockResolvedValueOnce({ dispatched: 'yes' }) + await expect(window.toggleMouse('right', 'up')).rejects.toThrow() + expect(f.dispatch).toHaveBeenCalledTimes(3) + }) + it('retains the snapshot identity for element right and double clicks', async () => { const f = fixture() const app = await f.api.getApp('Editor') diff --git a/packages/experimental/cua/tests/native-schema.spec.ts b/packages/experimental/cua/tests/native-schema.spec.ts index eca0803ce5..68689e2a16 100644 --- a/packages/experimental/cua/tests/native-schema.spec.ts +++ b/packages/experimental/cua/tests/native-schema.spec.ts @@ -57,6 +57,13 @@ it('admits key events with only an explicit direction enum', () => { expect(native.enums.get('sendKeyEvent')?.has('key') ?? false).toBe(false) }) +it('admits mouse-button events with explicit button and direction enums and no coordinates', () => { + const native = nativeProtocol() + expect(native.fields.get('toggleMouse')).toEqual(new Set(['appHandle', 'windowId', 'mouseButton', 'direction'])) + expect(native.enums.get('toggleMouse')?.get('mouseButton')).toEqual(new Set(['left', 'right', 'middle'])) + expect(native.enums.get('toggleMouse')?.get('direction')).toEqual(new Set(['down', 'up'])) +}) + it('accepts a parameter-free object schema without a properties dictionary', () => { replacements.values.set(0, { properties: { method: { const: 'getCapabilities' }, params: { type: 'object' } } }) expect(nativeProtocol().fields.get('getCapabilities')).toEqual(new Set()) diff --git a/packages/experimental/cua/tests/protocol.spec.ts b/packages/experimental/cua/tests/protocol.spec.ts index 8067bb10c4..9716a5ff5e 100644 --- a/packages/experimental/cua/tests/protocol.spec.ts +++ b/packages/experimental/cua/tests/protocol.spec.ts @@ -71,6 +71,28 @@ it('admits arbitrary key names with an explicit key-event direction', () => { expect(Request.parse(request)).toEqual(request) }) +it.each(['left', 'right', 'middle'])('admits explicit %s mouse-button events without coordinates', (mouseButton) => { + for (const schema of [Request, SystemPointerRequest]) { + for (const direction of ['down', 'up']) { + const request = { method: 'toggleMouse', params: { appHandle: 'app', windowId: '23', mouseButton, direction } } + expect(schema.parse(request)).toEqual(request) + } + } +}) + +it.each([ + { mouseButton: undefined }, { mouseButton: 'back' }, + { direction: undefined }, { direction: 'press' }, + { appHandle: undefined }, { windowId: undefined }, + { x: 1 }, { y: 2 }, { relative: true }, { elementId: '0' }, { snapshotId: 'snapshot' }, + { modifiers: [] }, { useSystemPointer: true }, +])('rejects invalid mouse-button event parameters %j', (invalid) => { + const params = { appHandle: 'app', windowId: '23', mouseButton: 'left', direction: 'down', ...invalid } + for (const schema of [Request, SystemPointerRequest]) { + expect(schema.safeParse({ method: 'toggleMouse', params }).success).toBe(false) + } +}) + it.each([ { appHandle: 'app', snapshotId: 'snapshot', elementId: '0' }, { appHandle: 'app', windowId: '23', x: 1, y: 2 }, diff --git a/snapshots/sdk/cua-run-code/system-prompt.expected.md b/snapshots/sdk/cua-run-code/system-prompt.expected.md index 92190be4ef..db7bd43972 100644 --- a/snapshots/sdk/cua-run-code/system-prompt.expected.md +++ b/snapshots/sdk/cua-run-code/system-prompt.expected.md @@ -65,10 +65,14 @@ Read getAccessibilityTree explicitly before using element ids. Selection and scr - setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value. - selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate. -## Simulated mouse -Use an explicit window for screenshots and pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. +## Screenshots +Use an explicit window for screenshots. - getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. + +## Simulated mouse +Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. @@ -82,6 +86,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. +click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. + Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. AX read defaults: maxElements=2000, maxDepth=25. diff --git a/snapshots/session/cua-native/system-prompt.expected.md b/snapshots/session/cua-native/system-prompt.expected.md index 572b8f2eb0..3cc3ebd954 100644 --- a/snapshots/session/cua-native/system-prompt.expected.md +++ b/snapshots/session/cua-native/system-prompt.expected.md @@ -66,12 +66,16 @@ Read getAccessibilityTree explicitly before using element ids. Selection and scr - setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value. - selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate. +## Screenshots +Use an explicit window for screenshots. +- getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. + ## Simulated mouse Leave useSystemPointer unset for ordinary mouseMove and drag calls, even after approval. Prefer selectText for a supported text range and ordinary window-directed drag for a draggable control. If the effect is unclear, inspect the window before choosing another action. Request the system pointer only when the user explicitly asks for it or the intended effect requires it. -Use an explicit window for screenshots and pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. -- getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. +Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemPointer?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemPointer omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. Not implemented on macOS. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemPointer?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control. An explicit system drag shares the session decision with mouseMove and holds the chosen button along the path in the unobscured foreground window. @@ -85,6 +89,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. + Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. Only if the task cannot be completed without moving the user’s pointer, call await win.mouseMove(target, { useSystemPointer: true }). Prefer an advertised accessibility action, a click on a visible control, or browser tools when possible. The question interrupts the user. When approval is disabled an explicit move can act immediately. Pass true on every physical move, even after approval. Omitting the option or passing false uses the default hover route without prompting. Approval or refusal lasts until this session closes or DSH restarts. A refusal sends no input. If the user dismisses the request, ask again only if they request it. Wait for an outstanding request to finish. Subagents cannot request physical movement. diff --git a/snapshots/session/cua-native/tool-schemas.expected.json b/snapshots/session/cua-native/tool-schemas.expected.json index 1afadeca68..ec3478d7c2 100644 --- a/snapshots/session/cua-native/tool-schemas.expected.json +++ b/snapshots/session/cua-native/tool-schemas.expected.json @@ -462,6 +462,55 @@ ], "additionalProperties": false }, + { + "type": "object", + "properties": { + "method": { + "type": "string", + "const": "toggleMouse" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "string", + "minLength": 1 + }, + "mouseButton": { + "type": "string", + "enum": [ + "left", + "right", + "middle" + ] + }, + "direction": { + "type": "string", + "enum": [ + "down", + "up" + ] + } + }, + "required": [ + "appHandle", + "windowId", + "mouseButton", + "direction" + ], + "additionalProperties": false + } + }, + "required": [ + "method", + "params" + ], + "additionalProperties": false + }, { "type": "object", "properties": { diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index ff53e75417..e081a0a66c 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -68,12 +68,16 @@ Read getAccessibilityTree explicitly before using element ids. Selection and scr - setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value. - selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate. +## Screenshots +Use an explicit window for screenshots. +- getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. + ## Simulated mouse Leave useSystemPointer unset for ordinary mouseMove and drag calls, even after approval. Prefer selectText for a supported text range and ordinary window-directed drag for a draggable control. If the effect is unclear, inspect the window before choosing another action. Request the system pointer only when the user explicitly asks for it or the intended effect requires it. -Use an explicit window for screenshots and pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. -- getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. +Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemPointer?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemPointer omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. Not implemented on macOS. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemPointer?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control. An explicit system drag shares the session decision with mouseMove and holds the chosen button along the path in the unobscured foreground window. @@ -87,6 +91,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. + Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. Only if the task cannot be completed without moving the user’s pointer, call await win.mouseMove(target, { useSystemPointer: true }). Prefer an advertised accessibility action, a click on a visible control, or browser tools when possible. The question interrupts the user. When approval is disabled an explicit move can act immediately. Pass true on every physical move, even after approval. Omitting the option or passing false uses the default hover route without prompting. Approval or refusal lasts until this session closes or DSH restarts. A refusal sends no input. If the user dismisses the request, ask again only if they request it. Wait for an outstanding request to finish. Subagents cannot request physical movement. diff --git a/snapshots/session/cua-run-code-ptc/system-prompt.expected.md b/snapshots/session/cua-run-code-ptc/system-prompt.expected.md index 893532843c..bb4eb419d5 100644 --- a/snapshots/session/cua-run-code-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-run-code-ptc/system-prompt.expected.md @@ -66,10 +66,14 @@ Read getAccessibilityTree explicitly before using element ids. Selection and scr - setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value. - selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate. -## Simulated mouse -Use an explicit window for screenshots and pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. +## Screenshots +Use an explicit window for screenshots. - getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. + +## Simulated mouse +Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. @@ -83,6 +87,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. +click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. + Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. AX read defaults: maxElements=2000, maxDepth=25. diff --git a/snapshots/session/cua-run-code/system-prompt.expected.md b/snapshots/session/cua-run-code/system-prompt.expected.md index 1545776e2c..a194b2db34 100644 --- a/snapshots/session/cua-run-code/system-prompt.expected.md +++ b/snapshots/session/cua-run-code/system-prompt.expected.md @@ -64,10 +64,14 @@ Read getAccessibilityTree explicitly before using element ids. Selection and scr - setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value. - selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate. -## Simulated mouse -Use an explicit window for screenshots and pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. +## Screenshots +Use an explicit window for screenshots. - getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. + +## Simulated mouse +Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. @@ -81,6 +85,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. +click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. + Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. AX read defaults: maxElements=2000, maxDepth=25. diff --git a/snapshots/session/ptc-script-retained/system-prompt.expected.md b/snapshots/session/ptc-script-retained/system-prompt.expected.md index 0b31f65856..c2333aa706 100644 --- a/snapshots/session/ptc-script-retained/system-prompt.expected.md +++ b/snapshots/session/ptc-script-retained/system-prompt.expected.md @@ -68,12 +68,16 @@ Read getAccessibilityTree explicitly before using element ids. Selection and scr - setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value. - selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate. +## Screenshots +Use an explicit window for screenshots. +- getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. + ## Simulated mouse Leave useSystemPointer unset for ordinary mouseMove and drag calls, even after approval. Prefer selectText for a supported text range and ordinary window-directed drag for a draggable control. If the effect is unclear, inspect the window before choosing another action. Request the system pointer only when the user explicitly asks for it or the intended effect requires it. -Use an explicit window for screenshots and pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. -- getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId. +Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemPointer?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. With useSystemPointer omitted or false, macOS uses accessibility hover without asking for mouse control. This requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again. +- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically. Not implemented on macOS. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemPointer?: boolean }) -> ActionResult — drag between two points of one window. Omitting useSystemPointer or passing false directs the drag to the window without asking for mouse control. An explicit system drag shares the session decision with mouseMove and holds the chosen button along the path in the unobscured foreground window. @@ -87,6 +91,8 @@ Available at app or window level depending on the platform. - pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. - sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier. Send 'down' to hold a key across tool calls in one program, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this program returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. + Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. Only if the task cannot be completed without moving the user’s pointer, call await win.mouseMove(target, { useSystemPointer: true }). Prefer an advertised accessibility action, a click on a visible control, or browser tools when possible. The question interrupts the user. When approval is disabled an explicit move can act immediately. Pass true on every physical move, even after approval. Omitting the option or passing false uses the default hover route without prompting. Approval or refusal lasts until this session closes or DSH restarts. A refusal sends no input. If the user dismisses the request, ask again only if they request it. Wait for an outstanding request to finish. Subagents cannot request physical movement.