From 7cab61dba53fdc09e87f3f04ffc8174f2b3ec7dc Mon Sep 17 00:00:00 2001 From: Ned Twigg Date: Sat, 28 Nov 2026 10:39:14 -0800 Subject: [PATCH] agent-browser: warn below a version floor, forward macOS editing chords Dormouse runs whatever agent-browser is installed and never checked its version, so no fallback for an old release could ever be deleted. `dor agent-browser` now asks `--version` once per new browser and warns, without refusing, below a floor of 0.27.0. The spec rule raises the floor only to a release at least six months old, and uses a new release's features as soon as it ships, keeping the old path until the floor passes it. agent-browser 0.45.0 forwards CDP `commands` on stream key events (vercel-labs/agent-browser#1453). On macOS the pane now sends Cmd+Z, Cmd+Shift+Z, Cmd+arrows (and their Shift forms), Cmd+Backspace and Cmd+Delete with their editor command; the viewer socket keeps only listed commands on a keyDown, and the Playwright host passes them to CDP. Older daemons ignore the field. Select-all keeps its host path until the floor reaches 0.45.0. Co-Authored-By: Claude Opus 5.5 --- docs/specs/dor-browser.md | 5 ++- docs/specs/dor-browser.rationale.md | 2 + dor/src/commands/agent-browser.ts | 21 ++++++++++ dor/src/commands/browser-cli.ts | 11 +++++- dor/test/agent-browser-version.test.mjs | 39 +++++++++++++++++++ dor/test/browser-viewport.test.mjs | 7 ++-- .../wall/AgentBrowserPanel.test.tsx | 8 ++++ .../wall/agent-browser-input.test.ts | 24 +++++++++++- .../components/wall/agent-browser-input.ts | 20 ++++++++++ .../agent-browser-surface-controller.test.ts | 6 +++ .../wall/agent-browser-surface-controller.ts | 3 ++ lib/src/host/browser-viewer.test.ts | 7 ++++ lib/src/host/browser-viewer.ts | 10 +++++ lib/src/host/playwright-host.ts | 4 +- lib/src/lib/platform/browser-automation.ts | 25 +++++++++++- scripts/spec-word-budgets.json | 2 +- 16 files changed, 183 insertions(+), 11 deletions(-) create mode 100644 dor/test/agent-browser-version.test.mjs diff --git a/docs/specs/dor-browser.md b/docs/specs/dor-browser.md index d23489189..331d07614 100644 --- a/docs/specs/dor-browser.md +++ b/docs/specs/dor-browser.md @@ -171,7 +171,7 @@ A pane out of sight ([Resource Policy](#resource-policy)) or unmounted parks aft **Must forward hover and wheel to the page over any screencast pane on screen, selected or not, in either mode, never selecting it or taking focus** (rationale). **Must end the page's hover when the pointer leaves the canvas**, except mid-drag of the canvas's own press (rationale). -**Must send a local paste as bounded `input_text` messages** (`viewerTextInputs`), never a key pair per character (rationale). Select-all, copy, cut, and tab select or close go through host operations (`edit`, `tab`), since editing chords do not survive CDP input; undo/redo is not emulated. +**Must send a local paste as bounded `input_text` messages** (`viewerTextInputs`), never a key pair per character (rationale). Select-all, copy, cut, and tab select or close go through host operations (`edit`, `tab`): copy and cut write the OS clipboard, and select-all stands in for agent-browser below 0.45.0. The other macOS Cmd editing chords carry their editor command as a keyDown's `commands`, only from `VIEWER_KEY_COMMANDS`; agent-browser below 0.45.0 ignores it. Source of truth: `lib/src/components/wall/agent-browser-surface-controller.ts` (`Phase`, `driver`), `lib/src/components/wall/AgentBrowserPanel.tsx`, `lib/src/components/wall/agent-browser-input.ts`, `viewerTextInputs` in `lib/src/lib/platform/browser-automation.ts`, `onBrowserLaunchFailed` in `lib/src/components/Wall.tsx`. @@ -235,8 +235,9 @@ agent-browser alone has a per-session daemon, state files beside its socket, and - **Never signal a pid without that proof** (rationale). - **Must run a launch's `open` in the binding's project directory while it exists**, so a relaunch reads the same `./agent-browser.json` the `dor agent-browser` there did, **and every other verb in the neutral directory** ([Browser Host](#browser-host)). - **Must read the stream port in `dor agent-browser` after a command that may bind** (`stream status --json`) and hand it over (rationale). **Never carry a socket directory to the host**, which kills the pid it reads there; host-side operations and captures for a session in a socket directory the host does not share are refused, while its viewer socket still streams and a close still runs. +- **Must warn, never refuse, below the version floor**, the oldest release Dormouse is verified against: `dor agent-browser` checks once per new browser, a GUI launch never. **Never warn above it.** **Must raise the floor only to a release at least six months old, verified against a real daemon, deleting fallbacks for older releases in the same change.** **Must use a release's new features as soon as it ships**, by feature test or by version, keeping the path for older releases until the floor passes them (rationale). -Source of truth: `createAgentBrowserProvider` in `lib/src/host/agent-browser-host.ts`, `streamStatus` in `dor/src/commands/agent-browser.ts`. +Source of truth: `createAgentBrowserProvider` in `lib/src/host/agent-browser-host.ts`; `streamStatus` and `AGENT_BROWSER_MIN_VERSION` in `dor/src/commands/agent-browser.ts`. ### Playwright diff --git a/docs/specs/dor-browser.rationale.md b/docs/specs/dor-browser.rationale.md index fc9af3a79..a96bff386 100644 --- a/docs/specs/dor-browser.rationale.md +++ b/docs/specs/dor-browser.rationale.md @@ -158,6 +158,8 @@ Windows daemon endpoints (2026-10-21): agent-browser 0.27.0 and 0.31.1 write the **Why the sweep closes pages over CDP, not through `tab list`.** `tab list` names only the tabs agent-browser tracks, never the `chrome://newtab/` page a launch leaves, and no verb closes one it does not name. A tracked tab closed over CDP leaves `tab list` too, and later commands still run (0.31.1, 2026-09-24), so one path closes both. +**Why the version floor warns.** Dormouse runs the user's own agent-browser (`docs/specs/security-supply-chain.md`), which shipped a minor release about weekly from 0.27.0 (2026-05) to 0.45.0 (2026-11-25), and nothing upgrades it unasked: a machine with Homebrew on 0.45.0 still ran 0.31.1 (2026-11-27). Without a floor no fallback can ever be deleted; a refusal would stop an agent mid-task over a version that mostly still works, while a warning reaches the agent, which can run `agent-browser upgrade` (present since 0.27.0) itself. The floor started at 0.27.0 (2026-05-07), the newest release six months old on 2026-11-28, whose Windows endpoints and headed handling are measured below. A ceiling would warn nearly every week. Changes that could break the host arrive unannounced: 0.44.0 began refusing stream upgrades whose `Origin` does not match their `Host`, harmless only because the host connects from Node and sends none. Six months is the maintainer's call (2026-11-28): long enough that a user who upgrades only now and then is rarely nagged, so new features ship at once and the old paths wait for the floor. + **Why `dor agent-browser` reads the stream port itself.** The host's `attach` reads only the state files, which an older agent-browser does not write and a caller's own `AGENT_BROWSER_SOCKET_DIR` keeps where the host does not look; with either, `dor agent-browser open` opened no pane (review of #777, 2026-09). The command has just made the daemon, so asking it starts none. ## Playwright diff --git a/dor/src/commands/agent-browser.ts b/dor/src/commands/agent-browser.ts index 82b25da67..4eea4c23d 100644 --- a/dor/src/commands/agent-browser.ts +++ b/dor/src/commands/agent-browser.ts @@ -38,6 +38,26 @@ function missingBinaryMessage(binary: string): string { ].join('\n'); } +/** The oldest agent-browser release Dormouse is verified against + * (docs/specs/dor-browser.md -> "agent-browser"). */ +export const AGENT_BROWSER_MIN_VERSION = '0.27.0'; + +function versionParts(text: string): number[] | undefined { + const match = /\b(\d+)\.(\d+)\.(\d+)\b/.exec(text); + return match ? match.slice(1).map(Number) : undefined; +} + +/** A warning when `agent-browser --version` names a release below the floor; + * '' at or above it, or when the output names no version. */ +export function agentBrowserVersionWarning(versionOutput: string): string { + const found = versionParts(versionOutput); + const floor = versionParts(AGENT_BROWSER_MIN_VERSION)!; + if (!found) return ''; + const index = found.findIndex((part, i) => part !== floor[i]); + if (index < 0 || found[index] > floor[index]) return ''; + return `Warning: agent-browser ${found.join('.')} is older than ${AGENT_BROWSER_MIN_VERSION}, the oldest version Dormouse supports; parts of its browser pane may not work. Update it with: agent-browser upgrade\n`; +} + export const agentBrowserCommand: Command = { name: 'agent-browser' satisfies BrowserAutomationProvider, helpPatches: [ @@ -155,6 +175,7 @@ export const AGENT_BROWSER: BrowserCliDescriptor = { // caller is, with the caller's executable. projectScoped: false, missingBinaryMessage, + versionWarning: agentBrowserVersionWarning, paths: { verbs: new Set(['screenshot', 'pdf', 'upload', 'download', 'har', 'trace', 'profiler', 'record', 'state', 'diff']), flags: new Set(['--profile', '--state', '--executable-path', '--extension', '--init-script', '--screenshot-dir', diff --git a/dor/src/commands/browser-cli.ts b/dor/src/commands/browser-cli.ts index 64c6c0393..61b261b2d 100644 --- a/dor/src/commands/browser-cli.ts +++ b/dor/src/commands/browser-cli.ts @@ -235,6 +235,9 @@ export interface BrowserCliDescriptor { projectScoped: boolean; /** The guidance printed when the binary is not installed. */ missingBinaryMessage(binary: string): string; + /** The warning a fresh browser's command prints for this `--version` + * output, or '' when the CLI meets the provider's floor. */ + versionWarning?(versionOutput: string): string; /** Where a WSL caller's Linux paths are translated for the Windows CLI. */ paths: PathArgs; /** A test's stand-in for the spawn. */ @@ -595,7 +598,13 @@ export async function runBrowserCli(d: BrowserCliDescriptor, args: string[], opt } catch (error) { return isMissingBinaryError(error) ? missing() : fail(errorMessage(error)); } - result.stderr = replacedPin + result.stderr; + // Once per new browser, so no later command pays for the extra spawn. + let outdated = ''; + if (fresh === true && d.versionWarning) { + const version = await run(['--version']).catch(() => undefined); + if (version?.exitCode === 0) outdated = d.versionWarning(version.stdout); + } + result.stderr = replacedPin + outdated + result.stderr; if (distro !== undefined && command !== undefined && d.paths.verbs.has(command)) { result.stdout = linuxPathText(result.stdout, distro); result.stderr = linuxPathText(result.stderr, distro); diff --git a/dor/test/agent-browser-version.test.mjs b/dor/test/agent-browser-version.test.mjs new file mode 100644 index 000000000..428cf4ba5 --- /dev/null +++ b/dor/test/agent-browser-version.test.mjs @@ -0,0 +1,39 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { runCli } from '../dist/cli.js'; + +function launch({ fresh, version }) { + const calls = []; + const options = { + env: { PWD: process.cwd() }, + client: { + resolveBrowser: async () => ({ binding: { session: 'dormouse.1.default' }, fresh }), + browserSurface: async () => ({}), + }, + execAgentBrowser: async (_binary, args) => { + calls.push(args); + return { exitCode: 0, stdout: args[0] === '--version' ? `agent-browser ${version}\n` : '', stderr: '' }; + }, + }; + return { calls, result: runCli(['agent-browser', 'snapshot'], options) }; +} + +test('a fresh browser on an agent-browser below the floor warns and still runs', async () => { + const { result } = launch({ fresh: true, version: '0.26.0' }); + const { exitCode, stderr } = await result; + assert.equal(exitCode, 0); + assert.match(stderr, /^Warning: agent-browser 0\.26\.0 is older than 0\.27\.0, .*agent-browser upgrade\n/); +}); + +test('an agent-browser at or above the floor prints no warning', async () => { + for (const version of ['0.27.0', '0.27.3', '0.45.0', '1.0.0']) { + const { stderr } = await launch({ fresh: true, version }).result; + assert.equal(stderr, '', version); + } +}); + +test('a reused browser never asks the version', async () => { + const { calls, result } = launch({ fresh: false, version: '0.26.0' }); + assert.equal((await result).stderr, ''); + assert.ok(!calls.some((args) => args.includes('--version'))); +}); diff --git a/dor/test/browser-viewport.test.mjs b/dor/test/browser-viewport.test.mjs index 3144383fe..44edfd46b 100644 --- a/dor/test/browser-viewport.test.mjs +++ b/dor/test/browser-viewport.test.mjs @@ -140,7 +140,7 @@ for (const flags of [ browserSurface: async () => ({}), }, execAgentBrowser: async (_binary, args) => { - calls.push(args); + if (args[0] !== '--version') calls.push(args); // The version probe states no session. return { exitCode: 0, stdout: args.includes('eval') ? '2\n' : '', stderr: '' }; }, }); @@ -251,7 +251,7 @@ test('native agent-browser device and headed launches bypass the default viewpor client: { resolveBrowser: async () => ({ binding: { session: 'dormouse.1.default' }, fresh: true, initialViewport: { mode: 'fixed', width: 1440, height: 900 }, launchViewport: { width: 1440, height: 900 } }), browserSurface: async request => { surfaces.push(request); return {}; } }, - execAgentBrowser: async (_binary, args) => { argsSeen.push(args); return { exitCode: 0, stdout: '', stderr: '' }; }, + execAgentBrowser: async (_binary, args) => { if (args[0] !== '--version') argsSeen.push(args); return { exitCode: 0, stdout: '', stderr: '' }; }, }; await runCli(['agent-browser', 'open', 'http://localhost:5173', ...tail], options); assert.equal(argsSeen.length, 2); // Native open and stream status; no blank preparation. @@ -385,7 +385,8 @@ test('every agent-browser call states the pane\'s mode, unless the command gives ...(fresh ? { initialViewport: { mode: 'fixed', width: 1440, height: 900 }, launchViewport: { width: 1440, height: 900 } } : {}) }), browserSurface: async () => ({}), }, - execAgentBrowser: async (_binary, argv) => { calls.push(argv); return { exitCode: 0, stdout: argv.includes('eval') ? '2\n' : '', stderr: '' }; }, + // The version probe states no session. + execAgentBrowser: async (_binary, argv) => { if (argv[0] !== '--version') calls.push(argv); return { exitCode: 0, stdout: argv.includes('eval') ? '2\n' : '', stderr: '' }; }, }); assert.equal(result.exitCode, 0, result.stderr); return calls; diff --git a/lib/src/components/wall/AgentBrowserPanel.test.tsx b/lib/src/components/wall/AgentBrowserPanel.test.tsx index 16b83ec38..bf7df257b 100644 --- a/lib/src/components/wall/AgentBrowserPanel.test.tsx +++ b/lib/src/components/wall/AgentBrowserPanel.test.tsx @@ -1092,6 +1092,14 @@ describe('AgentBrowserPanel canvas input forwarding', () => { await act(async () => { window.dispatchEvent(selectAll); }); expect(host.requests('edit')).toEqual([expect.objectContaining({ edit: 'selectAll' })]); }); + + it('sends a Mac Cmd chord with its editor command', async () => { + await renderWithMode('passthrough', 'ab-panel'); + await act(async () => { + window.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowLeft', code: 'ArrowLeft', metaKey: true, shiftKey: true, bubbles: true, cancelable: true })); + }); + expect(JSON.parse(sentKeyEvents().at(-1)!)).toMatchObject({ eventType: 'keyDown', key: 'ArrowLeft', commands: ['moveToBeginningOfLineAndModifySelection'] }); + }); }); describe('AgentBrowserPanel tab strip actions', () => { diff --git a/lib/src/components/wall/agent-browser-input.test.ts b/lib/src/components/wall/agent-browser-input.test.ts index 7c123dc37..2b5436296 100644 --- a/lib/src/components/wall/agent-browser-input.test.ts +++ b/lib/src/components/wall/agent-browser-input.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { modifiers, virtualKeyCode } from './agent-browser-input'; +import { macEditingCommand, modifiers, virtualKeyCode } from './agent-browser-input'; describe('virtualKeyCode', () => { it('maps printable OEM keys to their real VK, not the char code', () => { @@ -46,3 +46,25 @@ describe('modifiers', () => { expect(modifiers({ altKey: true, ctrlKey: true, metaKey: true, shiftKey: true })).toBe(15); }); }); + +describe('macEditingCommand', () => { + const chord = (key: string, mods: Partial> = {}) => + macEditingCommand({ key, altKey: false, ctrlKey: false, metaKey: true, shiftKey: false, ...mods }); + + it('maps Cmd chords to their editor commands, Shift to the selecting form', () => { + expect(chord('z')).toBe('undo'); + expect(chord('Z', { shiftKey: true })).toBe('redo'); + expect(chord('ArrowLeft')).toBe('moveToBeginningOfLine'); + expect(chord('ArrowDown', { shiftKey: true })).toBe('moveToEndOfDocumentAndModifySelection'); + expect(chord('Backspace')).toBe('deleteToBeginningOfLine'); + expect(chord('Delete')).toBe('deleteToEndOfLine'); + }); + + it('leaves every other chord to the key event', () => { + expect(chord('ArrowLeft', { metaKey: false })).toBeUndefined(); + expect(chord('z', { ctrlKey: true })).toBeUndefined(); + expect(chord('ArrowLeft', { altKey: true })).toBeUndefined(); + expect(chord('Backspace', { shiftKey: true })).toBeUndefined(); + expect(chord('a')).toBeUndefined(); + }); +}); diff --git a/lib/src/components/wall/agent-browser-input.ts b/lib/src/components/wall/agent-browser-input.ts index 4a7b5a63e..34642b411 100644 --- a/lib/src/components/wall/agent-browser-input.ts +++ b/lib/src/components/wall/agent-browser-input.ts @@ -3,6 +3,7 @@ * panel so the mapping (especially the windows-virtual-key table, which has a * nasty `.`=VK_DELETE footgun) is independently testable. */ +import type { ViewerKeyCommand } from '../../lib/platform/browser-automation'; // `text` is what makes typing land; windowsVirtualKeyCode is what makes // non-text keys and modifier chords act. Keyed by KeyboardEvent.key. @@ -69,6 +70,25 @@ export function virtualKeyCode(key: string, code: string): number { // Cmd/Ctrl + these map to native editing ops the stream input path can't do. export const EDIT_OPS = { a: 'selectAll', c: 'copy', x: 'cut' } as const; +// Cmd chords macOS Chromium runs only as editor commands; plain, then with Shift. +// Option chords and Shift-extended arrows act from the key event itself. +const MAC_CMD_COMMANDS: Record = { + z: ['undo', 'redo'], + ArrowLeft: ['moveToBeginningOfLine', 'moveToBeginningOfLineAndModifySelection'], + ArrowRight: ['moveToEndOfLine', 'moveToEndOfLineAndModifySelection'], + ArrowUp: ['moveToBeginningOfDocument', 'moveToBeginningOfDocumentAndModifySelection'], + ArrowDown: ['moveToEndOfDocument', 'moveToEndOfDocumentAndModifySelection'], + Backspace: ['deleteToBeginningOfLine'], + Delete: ['deleteToEndOfLine'], +}; + +/** The editor command a macOS Cmd chord stands for, if any. */ +export function macEditingCommand(e: { key: string; altKey: boolean; ctrlKey: boolean; metaKey: boolean; shiftKey: boolean }): ViewerKeyCommand | undefined { + if (!e.metaKey || e.ctrlKey || e.altKey) return undefined; + const pair = MAC_CMD_COMMANDS[e.key.length === 1 ? e.key.toLowerCase() : e.key]; + return pair?.[e.shiftKey ? 1 : 0]; +} + export const MOUSE_BUTTONS: Record = { 0: 'left', 1: 'middle', 2: 'right' }; export const MOUSE_BUTTON_MASKS: Record = { 0: 1, 1: 4, 2: 2 }; diff --git a/lib/src/components/wall/agent-browser-surface-controller.test.ts b/lib/src/components/wall/agent-browser-surface-controller.test.ts index 55d970f08..6b50fac43 100644 --- a/lib/src/components/wall/agent-browser-surface-controller.test.ts +++ b/lib/src/components/wall/agent-browser-surface-controller.test.ts @@ -343,6 +343,12 @@ describe('painting', () => { controller.handleKeyDownLike({ key: 'v', code: 'KeyV', ctrlKey: IS_MAC, metaKey: !IS_MAC, altKey: false, shiftKey: false }); await flushMicrotasks(); expect(sent().at(-1)).toMatchObject({ type: 'input_keyboard', eventType: 'keyDown', key: 'v' }); + // A macOS Cmd chord carries its editor command, which only the Mac needs. + controller.handleKeyDownLike({ key: 'z', code: 'KeyZ', ctrlKey: false, metaKey: true, altKey: false, shiftKey: true }); + expect(sent().at(-1)).toMatchObject({ type: 'input_keyboard', eventType: 'keyDown', key: 'z', text: '' }); + expect(sent().at(-1).commands).toEqual(IS_MAC ? ['redo'] : undefined); + controller.sendKeyUp({ key: 'z', code: 'KeyZ', ctrlKey: false, metaKey: true, altKey: false, shiftKey: true }); + expect(sent().at(-1).commands).toBeUndefined(); // A view remounted over the open socket asks the host for the last frame. controller.attachView(makeSink()); expect(sent().at(-1)).toEqual({ type: 'repaint' }); diff --git a/lib/src/components/wall/agent-browser-surface-controller.ts b/lib/src/components/wall/agent-browser-surface-controller.ts index a2a00941c..aa48dd2a1 100644 --- a/lib/src/components/wall/agent-browser-surface-controller.ts +++ b/lib/src/components/wall/agent-browser-surface-controller.ts @@ -49,6 +49,7 @@ import { agentBrowserSessionFromParams, isToolParams, resolveRenderMode, viewpor import { EDIT_OPS, SPECIAL_KEYS, + macEditingCommand, modifiers, virtualKeyCode, } from './agent-browser-input'; @@ -1665,6 +1666,7 @@ export class AgentBrowserSurfaceController { // Under ctrl/cmd the key is a shortcut, not text — sending text would make // e.g. cmd-A insert an "a" instead of acting as a chord. const wantsText = eventType === 'keyDown' && !e.ctrlKey && !e.metaKey; + const command = eventType === 'keyDown' && IS_MAC ? macEditingCommand(e) : undefined; this.send({ type: 'input_keyboard', eventType, @@ -1676,6 +1678,7 @@ export class AgentBrowserSurfaceController { text: wantsText ? info?.text ?? (e.key.length === 1 ? e.key : '') : '', windowsVirtualKeyCode: virtualKeyCode(e.key, e.code), modifiers: modifiers(e), + ...(command ? { commands: [command] } : {}), }); } diff --git a/lib/src/host/browser-viewer.test.ts b/lib/src/host/browser-viewer.test.ts index 48ac659f2..152d1f4f2 100644 --- a/lib/src/host/browser-viewer.test.ts +++ b/lib/src/host/browser-viewer.test.ts @@ -402,6 +402,13 @@ describe('parseViewerInput', () => { .toEqual({ type: 'input_mouse', eventType: 'mouseWheel', x: 1, y: 2, button: 'none', buttons: 31, clickCount: 3, modifiers: 15, deltaX: 0, deltaY: 5 }); expect(parseViewerInput(JSON.stringify({ type: 'input_keyboard', eventType: 'keyDown', key: 'a', code: 'c'.repeat(200), text: 't'.repeat(2000), windowsVirtualKeyCode: 65.5, modifiers: 16 }))) .toEqual({ type: 'input_keyboard', eventType: 'keyDown', key: 'a', code: 'c'.repeat(100), text: 't'.repeat(1000), windowsVirtualKeyCode: 0, modifiers: 0 }); + const key = { type: 'input_keyboard', eventType: 'keyDown', key: 'z', code: 'KeyZ', text: '', windowsVirtualKeyCode: 90, modifiers: 4 }; + expect(parseViewerInput(JSON.stringify({ ...key, commands: ['undo'] }))).toEqual({ ...key, commands: ['undo'] }); + // Only a keyDown's listed commands, and at most four, reach a browser. + for (const commands of [['insertText'], ['undo', 'paste'], Array(5).fill('undo'), [], 'undo']) { + expect(parseViewerInput(JSON.stringify({ ...key, commands })), JSON.stringify(commands)).toEqual(key); + } + expect(parseViewerInput(JSON.stringify({ ...key, eventType: 'keyUp', commands: ['undo'] }))).toEqual({ ...key, eventType: 'keyUp' }); const sync = { type: 'sync', width: 800, height: 600, dpr: 2, engagement: '0f5c-e1' }; expect(parseViewerInput(JSON.stringify({ ...sync, extra: 'x' }))).toEqual(sync); for (const refused of [ diff --git a/lib/src/host/browser-viewer.ts b/lib/src/host/browser-viewer.ts index 7477ee818..67be8c3a8 100644 --- a/lib/src/host/browser-viewer.ts +++ b/lib/src/host/browser-viewer.ts @@ -17,10 +17,12 @@ import { VIEWER_TEXT_INPUT_MAX, VIEWPORT_MAX_DPR, VIEWPORT_MAX_SIDE, + VIEWER_KEY_COMMANDS, encodeViewerFrame, type ViewerBrowserInput, type ViewerFrameKind, type ViewerInput, + type ViewerKeyCommand, type ViewerState, type ViewerSyncIntent, } from '../lib/platform/browser-automation'; @@ -562,6 +564,13 @@ export const WEBVIEW_ID = /^[A-Za-z0-9-]{1,64}$/; const finiteCoordinate = (n: unknown): n is number => typeof n === 'number' && Number.isFinite(n) && Math.abs(n) <= 1e6; const integer = (n: unknown): number => (Number.isInteger(n) ? n as number : 0); +/** A keyDown's commands, when each is one the viewer may send. */ +function keyCommands(data: Record): { commands?: ViewerKeyCommand[] } { + const commands = data.commands; + if (data.eventType !== 'keyDown' || !Array.isArray(commands) || commands.length === 0 || commands.length > 4) return {}; + return commands.every((c) => (VIEWER_KEY_COMMANDS as readonly unknown[]).includes(c)) ? { commands: commands as ViewerKeyCommand[] } : {}; +} + /** * One message from the webview, rebuilt field by field from what it sent: * each provider forwards only these shapes, bounded, to its browser. Null for @@ -603,6 +612,7 @@ export function parseViewerInput(raw: string): ViewerInput | null { text: typeof data.text === 'string' ? data.text.slice(0, 1000) : '', windowsVirtualKeyCode: integer(data.windowsVirtualKeyCode), modifiers: integer(data.modifiers) & 15, + ...keyCommands(data), }; case 'input_text': return typeof data.text === 'string' && data.text.length <= VIEWER_TEXT_INPUT_MAX ? { type: 'input_text', text: data.text } : null; diff --git a/lib/src/host/playwright-host.ts b/lib/src/host/playwright-host.ts index 06b8cee04..84829673a 100644 --- a/lib/src/host/playwright-host.ts +++ b/lib/src/host/playwright-host.ts @@ -306,8 +306,8 @@ export function createPlaywrightProvider(deps: { log?(text: string): void } = {} const { eventType: type, x, y, button, buttons, modifiers, clickCount, deltaX, deltaY } = data; await cdp.send('Input.dispatchMouseEvent', { type, x, y, button, buttons, modifiers, clickCount, ...(type === 'mouseWheel' ? { deltaX, deltaY } : {}) }); } else if (data.type === 'input_keyboard') { - const { eventType: type, key, code, text, windowsVirtualKeyCode, modifiers } = data; - await cdp.send('Input.dispatchKeyEvent', { type, key, code, text, windowsVirtualKeyCode, modifiers }); + const { eventType: type, key, code, text, windowsVirtualKeyCode, modifiers, commands } = data; + await cdp.send('Input.dispatchKeyEvent', { type, key, code, text, windowsVirtualKeyCode, modifiers, ...(commands ? { commands } : {}) }); } else { // A paste arrives as text, not a key pair per character (`viewerTextInputs`). await cdp.send('Input.insertText', { text: data.text }); diff --git a/lib/src/lib/platform/browser-automation.ts b/lib/src/lib/platform/browser-automation.ts index 7fd02f551..cb6a6a995 100644 --- a/lib/src/lib/platform/browser-automation.ts +++ b/lib/src/lib/platform/browser-automation.ts @@ -139,12 +139,35 @@ export type ViewerInput = deltaX?: number; deltaY?: number; } - | { type: 'input_keyboard'; eventType: 'keyDown' | 'keyUp'; key: string; code: string; text: string; windowsVirtualKeyCode: number; modifiers: number } + | { + type: 'input_keyboard'; + eventType: 'keyDown' | 'keyUp'; + key: string; + code: string; + text: string; + windowsVirtualKeyCode: number; + modifiers: number; + /** A keyDown's macOS editor command, carried as CDP's `commands`. */ + commands?: ViewerKeyCommand[]; + } /** A paste, inserted whole. */ | { type: 'input_text'; text: string } | ViewerSyncIntent | { type: 'repaint' }; +/** The editor commands a viewer key may carry: the macOS chords Chromium runs + * only as named commands. agent-browser forwards them from 0.45.0 and an + * older daemon ignores them. */ +export const VIEWER_KEY_COMMANDS = [ + 'undo', 'redo', + 'moveToBeginningOfLine', 'moveToBeginningOfLineAndModifySelection', + 'moveToEndOfLine', 'moveToEndOfLineAndModifySelection', + 'moveToBeginningOfDocument', 'moveToBeginningOfDocumentAndModifySelection', + 'moveToEndOfDocument', 'moveToEndOfDocumentAndModifySelection', + 'deleteToBeginningOfLine', 'deleteToEndOfLine', +] as const; +export type ViewerKeyCommand = typeof VIEWER_KEY_COMMANDS[number]; + /** The input a provider forwards to its browser. */ export type ViewerBrowserInput = Exclude; diff --git a/scripts/spec-word-budgets.json b/scripts/spec-word-budgets.json index ed639be2c..5d1811d24 100644 --- a/scripts/spec-word-budgets.json +++ b/scripts/spec-word-budgets.json @@ -6,7 +6,7 @@ "docs/specs/alert.md": 7650, "docs/specs/auto-update.md": 1050, "docs/specs/deploy.md": 2350, - "docs/specs/dor-browser.md": 6750, + "docs/specs/dor-browser.md": 6850, "docs/specs/dor-cli.md": 6200, "docs/specs/dor-tool.md": 7250, "docs/specs/dor-tools-builtin.md": 1800,