Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions docs/specs/dor-browser.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.

Expand Down Expand Up @@ -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

Expand Down
2 changes: 2 additions & 0 deletions docs/specs/dor-browser.rationale.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 21 additions & 0 deletions dor/src/commands/agent-browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: [
Expand Down Expand Up @@ -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',
Expand Down
11 changes: 10 additions & 1 deletion dor/src/commands/browser-cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -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);
Expand Down
39 changes: 39 additions & 0 deletions dor/test/agent-browser-version.test.mjs
Original file line number Diff line number Diff line change
@@ -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')));
});
7 changes: 4 additions & 3 deletions dor/test/browser-viewport.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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: '' };
},
});
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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;
Expand Down
8 changes: 8 additions & 0 deletions lib/src/components/wall/AgentBrowserPanel.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down
24 changes: 23 additions & 1 deletion lib/src/components/wall/agent-browser-input.test.ts
Original file line number Diff line number Diff line change
@@ -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', () => {
Expand Down Expand Up @@ -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<Record<'altKey' | 'ctrlKey' | 'metaKey' | 'shiftKey', boolean>> = {}) =>
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();
});
});
20 changes: 20 additions & 0 deletions lib/src/components/wall/agent-browser-input.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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<string, [ViewerKeyCommand, ViewerKeyCommand?]> = {
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<number, string> = { 0: 'left', 1: 'middle', 2: 'right' };
export const MOUSE_BUTTON_MASKS: Record<number, number> = { 0: 1, 1: 4, 2: 2 };

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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' });
Expand Down
3 changes: 3 additions & 0 deletions lib/src/components/wall/agent-browser-surface-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ import { agentBrowserSessionFromParams, isToolParams, resolveRenderMode, viewpor
import {
EDIT_OPS,
SPECIAL_KEYS,
macEditingCommand,
modifiers,
virtualKeyCode,
} from './agent-browser-input';
Expand Down Expand Up @@ -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,
Expand All @@ -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] } : {}),
});
}

Expand Down
7 changes: 7 additions & 0 deletions lib/src/host/browser-viewer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 [
Expand Down
Loading
Loading