From 2b5df3e52ae90cc2629a761a78a366a462323c90 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 22:43:53 +0000 Subject: [PATCH 01/30] feat(browser): daemon-run headless browser with agent ops and viewer stream Each project gets a headless Chromium on its daemon's machine, driven over a private DevTools pipe. Agents use `pu browser` (open, snapshot with [ref=eN] outlines, click, type, press, scroll, screenshot, console, eval, wait). Viewers hold a browser_attach stream for screencast frames with ack-based flow control, tab state, and input; a person can take control, which refuses agent actions until they hand it back. Because everything goes through the daemon socket, it works for remote machines unchanged. Protocol version 15. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ2eMMzt56iHuDqpo7z --- .../protocol/generated/BrowserConsoleEntry.ts | 13 + .../src/protocol/generated/BrowserDriver.ts | 8 + .../src/protocol/generated/BrowserHistory.ts | 3 + .../protocol/generated/BrowserInputEvent.ts | 28 + .../protocol/generated/BrowserKeyAction.ts | 3 + .../protocol/generated/BrowserMouseAction.ts | 3 + .../protocol/generated/BrowserMouseButton.ts | 3 + .../ui/src/protocol/generated/BrowserOp.ts | 28 + .../src/protocol/generated/BrowserTabInfo.ts | 20 + .../ui/src/protocol/generated/GridCommand.ts | 6 + .../ui/src/protocol/generated/Request.ts | 3 + .../ui/src/protocol/generated/Response.ts | 39 + .../ui/src/protocol/generated/index.ts | 9 + .../src/protocol/generated/protocolVersion.ts | 2 +- .../ui/src/protocol/generated/samples.ts | 106 +- crates/pu-cli/src/commands/browser.rs | 281 ++++ crates/pu-cli/src/commands/mod.rs | 1 + crates/pu-cli/src/main.rs | 14 + crates/pu-cli/src/output/mod.rs | 42 + crates/pu-core/src/protocol/browser.rs | 354 +++++ crates/pu-core/src/protocol/grid.rs | 9 + crates/pu-core/src/protocol/mod.rs | 63 +- crates/pu-core/src/protocol/tests.rs | 78 +- crates/pu-core/src/ts_export.rs | 16 +- crates/pu-engine/src/browser/cdp.rs | 334 ++++ crates/pu-engine/src/browser/keys.rs | 141 ++ crates/pu-engine/src/browser/launch.rs | 276 ++++ crates/pu-engine/src/browser/mod.rs | 1354 +++++++++++++++++ crates/pu-engine/src/browser/snapshot.rs | 318 ++++ crates/pu-engine/src/browser/tab.rs | 529 +++++++ crates/pu-engine/src/engine/mod.rs | 28 + crates/pu-engine/src/ipc_server/mod.rs | 15 + crates/pu-engine/src/ipc_server/streams.rs | 144 ++ crates/pu-engine/src/lib.rs | 1 + crates/pu-engine/tests/browser.rs | 462 ++++++ 35 files changed, 4729 insertions(+), 5 deletions(-) create mode 100644 apps/purepoint-windows/ui/src/protocol/generated/BrowserConsoleEntry.ts create mode 100644 apps/purepoint-windows/ui/src/protocol/generated/BrowserDriver.ts create mode 100644 apps/purepoint-windows/ui/src/protocol/generated/BrowserHistory.ts create mode 100644 apps/purepoint-windows/ui/src/protocol/generated/BrowserInputEvent.ts create mode 100644 apps/purepoint-windows/ui/src/protocol/generated/BrowserKeyAction.ts create mode 100644 apps/purepoint-windows/ui/src/protocol/generated/BrowserMouseAction.ts create mode 100644 apps/purepoint-windows/ui/src/protocol/generated/BrowserMouseButton.ts create mode 100644 apps/purepoint-windows/ui/src/protocol/generated/BrowserOp.ts create mode 100644 apps/purepoint-windows/ui/src/protocol/generated/BrowserTabInfo.ts create mode 100644 crates/pu-cli/src/commands/browser.rs create mode 100644 crates/pu-core/src/protocol/browser.rs create mode 100644 crates/pu-engine/src/browser/cdp.rs create mode 100644 crates/pu-engine/src/browser/keys.rs create mode 100644 crates/pu-engine/src/browser/launch.rs create mode 100644 crates/pu-engine/src/browser/mod.rs create mode 100644 crates/pu-engine/src/browser/snapshot.rs create mode 100644 crates/pu-engine/src/browser/tab.rs create mode 100644 crates/pu-engine/tests/browser.rs diff --git a/apps/purepoint-windows/ui/src/protocol/generated/BrowserConsoleEntry.ts b/apps/purepoint-windows/ui/src/protocol/generated/BrowserConsoleEntry.ts new file mode 100644 index 00000000..f78f98f1 --- /dev/null +++ b/apps/purepoint-windows/ui/src/protocol/generated/BrowserConsoleEntry.ts @@ -0,0 +1,13 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type BrowserConsoleEntry = { + /** + * `log`, `info`, `warning`, `error`, `debug`, `exception` or `dialog`. + */ + level: string; + text: string; + /** + * Milliseconds since the Unix epoch. + */ + timestamp_ms: number; +}; diff --git a/apps/purepoint-windows/ui/src/protocol/generated/BrowserDriver.ts b/apps/purepoint-windows/ui/src/protocol/generated/BrowserDriver.ts new file mode 100644 index 00000000..dab9b05c --- /dev/null +++ b/apps/purepoint-windows/ui/src/protocol/generated/BrowserDriver.ts @@ -0,0 +1,8 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * Who is in control of a tab. Agent ops (click, type, navigate, eval…) are + * refused with `BROWSER_HUMAN_DRIVING` while a person drives; reading the page + * (snapshot, screenshot, console) always works. + */ +export type BrowserDriver = 'agent' | 'human'; diff --git a/apps/purepoint-windows/ui/src/protocol/generated/BrowserHistory.ts b/apps/purepoint-windows/ui/src/protocol/generated/BrowserHistory.ts new file mode 100644 index 00000000..d6b6a40a --- /dev/null +++ b/apps/purepoint-windows/ui/src/protocol/generated/BrowserHistory.ts @@ -0,0 +1,3 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type BrowserHistory = 'back' | 'forward' | 'reload'; diff --git a/apps/purepoint-windows/ui/src/protocol/generated/BrowserInputEvent.ts b/apps/purepoint-windows/ui/src/protocol/generated/BrowserInputEvent.ts new file mode 100644 index 00000000..8efcc26e --- /dev/null +++ b/apps/purepoint-windows/ui/src/protocol/generated/BrowserInputEvent.ts @@ -0,0 +1,28 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { BrowserKeyAction } from './BrowserKeyAction'; +import type { BrowserMouseAction } from './BrowserMouseAction'; +import type { BrowserMouseButton } from './BrowserMouseButton'; + +/** + * Input from a viewer. Coordinates are CSS pixels in the page viewport. + */ +export type BrowserInputEvent = + | { + kind: 'mouse'; + action: BrowserMouseAction; + x: number; + y: number; + button?: BrowserMouseButton; + click_count?: number; + modifiers?: number; + } + | { kind: 'wheel'; x: number; y: number; dx: number; dy: number; modifiers?: number } + | { + kind: 'key'; + action: BrowserKeyAction; + key: string; + code?: string | null; + text?: string | null; + modifiers?: number; + } + | { kind: 'text'; text: string }; diff --git a/apps/purepoint-windows/ui/src/protocol/generated/BrowserKeyAction.ts b/apps/purepoint-windows/ui/src/protocol/generated/BrowserKeyAction.ts new file mode 100644 index 00000000..bb3ce6a9 --- /dev/null +++ b/apps/purepoint-windows/ui/src/protocol/generated/BrowserKeyAction.ts @@ -0,0 +1,3 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type BrowserKeyAction = 'down' | 'up'; diff --git a/apps/purepoint-windows/ui/src/protocol/generated/BrowserMouseAction.ts b/apps/purepoint-windows/ui/src/protocol/generated/BrowserMouseAction.ts new file mode 100644 index 00000000..bfbbdb6b --- /dev/null +++ b/apps/purepoint-windows/ui/src/protocol/generated/BrowserMouseAction.ts @@ -0,0 +1,3 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type BrowserMouseAction = 'down' | 'up' | 'move'; diff --git a/apps/purepoint-windows/ui/src/protocol/generated/BrowserMouseButton.ts b/apps/purepoint-windows/ui/src/protocol/generated/BrowserMouseButton.ts new file mode 100644 index 00000000..7bee7931 --- /dev/null +++ b/apps/purepoint-windows/ui/src/protocol/generated/BrowserMouseButton.ts @@ -0,0 +1,3 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type BrowserMouseButton = 'none' | 'left' | 'middle' | 'right'; diff --git a/apps/purepoint-windows/ui/src/protocol/generated/BrowserOp.ts b/apps/purepoint-windows/ui/src/protocol/generated/BrowserOp.ts new file mode 100644 index 00000000..039fd665 --- /dev/null +++ b/apps/purepoint-windows/ui/src/protocol/generated/BrowserOp.ts @@ -0,0 +1,28 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { BrowserDriver } from './BrowserDriver'; +import type { BrowserHistory } from './BrowserHistory'; +import type { BrowserInputEvent } from './BrowserInputEvent'; + +/** + * One browser operation. A `None` tab id means the project's most recently + * opened or used tab. + */ +export type BrowserOp = + | { action: 'open'; url?: string | null } + | { action: 'list' } + | { action: 'close'; tab_id?: string | null } + | { action: 'navigate'; tab_id?: string | null; url: string } + | { action: 'history'; tab_id?: string | null; direction: BrowserHistory } + | { action: 'snapshot'; tab_id?: string | null } + | { action: 'click'; tab_id?: string | null; ref: string } + | { action: 'type'; tab_id?: string | null; ref?: string | null; text: string; submit?: boolean } + | { action: 'press'; tab_id?: string | null; key: string } + | { action: 'scroll'; tab_id?: string | null; dx?: number; dy: number } + | { action: 'screenshot'; tab_id?: string | null; path?: string | null; full_page?: boolean } + | { action: 'console'; tab_id?: string | null; clear?: boolean } + | { action: 'eval'; tab_id?: string | null; expression: string } + | { action: 'wait'; tab_id?: string | null; text?: string | null; timeout_ms?: number | null } + | { action: 'control'; tab_id?: string | null; driver: BrowserDriver } + | { action: 'input'; tab_id?: string | null; event: BrowserInputEvent } + | { action: 'resize'; tab_id?: string | null; width: number; height: number; scale?: number } + | { action: 'frame_ack'; tab_id?: string | null; seq: number }; diff --git a/apps/purepoint-windows/ui/src/protocol/generated/BrowserTabInfo.ts b/apps/purepoint-windows/ui/src/protocol/generated/BrowserTabInfo.ts new file mode 100644 index 00000000..cbbfd921 --- /dev/null +++ b/apps/purepoint-windows/ui/src/protocol/generated/BrowserTabInfo.ts @@ -0,0 +1,20 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { BrowserDriver } from './BrowserDriver'; + +/** + * One open tab, as every client sees it. + */ +export type BrowserTabInfo = { + tab_id: string; + url: string; + title: string; + loading: boolean; + driver: BrowserDriver; + can_go_back: boolean; + can_go_forward: boolean; + /** + * The page viewport in CSS pixels (what clicks are measured against). + */ + width: number; + height: number; +}; diff --git a/apps/purepoint-windows/ui/src/protocol/generated/GridCommand.ts b/apps/purepoint-windows/ui/src/protocol/generated/GridCommand.ts index 69b1b4c7..f4ad61e0 100644 --- a/apps/purepoint-windows/ui/src/protocol/generated/GridCommand.ts +++ b/apps/purepoint-windows/ui/src/protocol/generated/GridCommand.ts @@ -26,6 +26,12 @@ export type GridCommand = leaf_id?: number | null; agent_id?: string | null; } + | { + action: 'open_browser'; + workspace_id?: string | null; + leaf_id?: number | null; + browser_tab: string; + } | { action: 'select_tab'; workspace_id?: string | null; diff --git a/apps/purepoint-windows/ui/src/protocol/generated/Request.ts b/apps/purepoint-windows/ui/src/protocol/generated/Request.ts index d9b307ab..16488ffd 100644 --- a/apps/purepoint-windows/ui/src/protocol/generated/Request.ts +++ b/apps/purepoint-windows/ui/src/protocol/generated/Request.ts @@ -1,5 +1,6 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { AgentQueryState } from './AgentQueryState'; +import type { BrowserOp } from './BrowserOp'; import type { ChannelReference } from './ChannelReference'; import type { GridCommand } from './GridCommand'; import type { InventoryKind } from './InventoryKind'; @@ -124,6 +125,8 @@ export type Request = | { type: 'subscribe_grid'; project_root: string } | { type: 'subscribe_status'; project_root: string } | { type: 'grid_command'; project_root: string; command: GridCommand } + | { type: 'browser'; project_root: string; op: BrowserOp } + | { type: 'browser_attach'; project_root: string; tab_id?: string | null } | { type: 'rename'; project_root: string; agent_id: string; name: string } | { type: 'assign_trigger'; project_root: string; agent_id: string; trigger_name: string } | { type: 'create_worktree'; project_root: string; name?: string | null; base?: string | null } diff --git a/apps/purepoint-windows/ui/src/protocol/generated/Response.ts b/apps/purepoint-windows/ui/src/protocol/generated/Response.ts index aaa69486..ae9f4d6b 100644 --- a/apps/purepoint-windows/ui/src/protocol/generated/Response.ts +++ b/apps/purepoint-windows/ui/src/protocol/generated/Response.ts @@ -4,6 +4,8 @@ import type { AgentDefInfo } from './AgentDefInfo'; import type { AgentPulseEntry } from './AgentPulseEntry'; import type { AgentStatus } from './AgentStatus'; import type { AgentStatusReport } from './AgentStatusReport'; +import type { BrowserConsoleEntry } from './BrowserConsoleEntry'; +import type { BrowserTabInfo } from './BrowserTabInfo'; import type { ChannelMessage } from './ChannelMessage'; import type { FsEntry } from './FsEntry'; import type { GridCommand } from './GridCommand'; @@ -85,6 +87,43 @@ export type Response = | { type: 'resync' } | { type: 'pty_size'; cols: number; rows: number; owner_client_id: string | null } | { type: 'output'; agent_id: string; data: string } + | { type: 'browser_tab'; tab: BrowserTabInfo } + | { type: 'browser_tabs'; tabs: Array } + | { + type: 'browser_snapshot'; + tab: BrowserTabInfo; + /** + * Indented accessibility outline; interactive elements carry `[ref=eN]`. + */ + tree: string; + } + | { + type: 'browser_screenshot'; + tab_id: string; + /** + * A PNG on the daemon's machine. + */ + path: string; + } + | { type: 'browser_console'; tab_id: string; entries: Array } + | { type: 'browser_eval_result'; tab_id: string; value: JsonValue } + | { type: 'browser_attached'; tab: BrowserTabInfo } + | { + type: 'browser_frame'; + tab_id: string; + seq: number; + /** + * Base64 JPEG. + */ + data: string; + /** + * The CSS viewport the frame shows, for mapping input coordinates. + */ + width: number; + height: number; + } + | { type: 'browser_tab_state'; tab: BrowserTabInfo } + | { type: 'browser_tab_closed'; tab_id: string } | { type: 'grid_subscribed' } | { type: 'grid_layout'; layout: JsonValue } | { type: 'grid_event'; project_root: string; command: GridCommand } diff --git a/apps/purepoint-windows/ui/src/protocol/generated/index.ts b/apps/purepoint-windows/ui/src/protocol/generated/index.ts index eaf5acd7..e485189c 100644 --- a/apps/purepoint-windows/ui/src/protocol/generated/index.ts +++ b/apps/purepoint-windows/ui/src/protocol/generated/index.ts @@ -12,6 +12,15 @@ export type * from './AgentStatus'; export type * from './AgentStatusReport'; export type * from './AttentionActionability'; export type * from './AttentionKind'; +export type * from './BrowserConsoleEntry'; +export type * from './BrowserDriver'; +export type * from './BrowserHistory'; +export type * from './BrowserInputEvent'; +export type * from './BrowserKeyAction'; +export type * from './BrowserMouseAction'; +export type * from './BrowserMouseButton'; +export type * from './BrowserOp'; +export type * from './BrowserTabInfo'; export type * from './ChannelAuthor'; export type * from './ChannelMessage'; export type * from './ChannelReaction'; diff --git a/apps/purepoint-windows/ui/src/protocol/generated/protocolVersion.ts b/apps/purepoint-windows/ui/src/protocol/generated/protocolVersion.ts index 44281fb6..98bdc675 100644 --- a/apps/purepoint-windows/ui/src/protocol/generated/protocolVersion.ts +++ b/apps/purepoint-windows/ui/src/protocol/generated/protocolVersion.ts @@ -1,4 +1,4 @@ // This file was generated by crates/pu-core/src/ts_export.rs. Do not edit this file manually. /** Wire protocol version (`pu_core::protocol::PROTOCOL_VERSION`). */ -export const PROTOCOL_VERSION = 14; +export const PROTOCOL_VERSION = 15; diff --git a/apps/purepoint-windows/ui/src/protocol/generated/samples.ts b/apps/purepoint-windows/ui/src/protocol/generated/samples.ts index dacab54c..af5e6e37 100644 --- a/apps/purepoint-windows/ui/src/protocol/generated/samples.ts +++ b/apps/purepoint-windows/ui/src/protocol/generated/samples.ts @@ -99,6 +99,39 @@ export const requestInputs: Request[] = [ { type: 'fs_write', path: '/p/a', data_base64: 'aGk=' }, { type: 'attach_file', upload_id: 'u1', name: 'a.png', data_base64: 'aGk=' }, { type: 'git_exec', cwd: '/p', program: 'git', args: ['status'] }, + { type: 'browser', project_root: '/test', op: { action: 'open', url: 'localhost:3000' } }, + { type: 'browser', project_root: '/test', op: { action: 'click', ref: 'e3' } }, + { + type: 'browser', + project_root: '/test', + op: { action: 'type', tab_id: 'T1', ref: 'e5', text: 'hi', submit: true }, + }, + { + type: 'browser', + project_root: '/test', + op: { + action: 'input', + event: { kind: 'mouse', action: 'down', x: 10, y: 20, button: 'left', click_count: 1 }, + }, + }, + { + type: 'browser', + project_root: '/test', + op: { action: 'input', event: { kind: 'key', action: 'down', key: 'Enter' } }, + }, + { + type: 'browser', + project_root: '/test', + op: { action: 'resize', width: 800, height: 600, scale: 2 }, + }, + { type: 'browser', project_root: '/test', op: { action: 'frame_ack', seq: 4 } }, + { type: 'browser', project_root: '/test', op: { action: 'control', driver: 'human' } }, + { type: 'browser_attach', project_root: '/test', tab_id: 'T1' }, + { + type: 'grid_command', + project_root: '/test', + command: { action: 'open_browser', browser_tab: 'T1' }, + }, ]; export const requestOutputs: Request[] = [ @@ -294,6 +327,56 @@ export const requestOutputs: Request[] = [ stdin_base64: null, timeout_ms: 30000, }, + { type: 'browser', project_root: '/test', op: { action: 'open', url: 'localhost:3000' } }, + { type: 'browser', project_root: '/test', op: { action: 'click', tab_id: null, ref: 'e3' } }, + { + type: 'browser', + project_root: '/test', + op: { action: 'type', tab_id: 'T1', ref: 'e5', text: 'hi', submit: true }, + }, + { + type: 'browser', + project_root: '/test', + op: { + action: 'input', + tab_id: null, + event: { + kind: 'mouse', + action: 'down', + x: 10.0, + y: 20.0, + button: 'left', + click_count: 1, + modifiers: 0, + }, + }, + }, + { + type: 'browser', + project_root: '/test', + op: { + action: 'input', + tab_id: null, + event: { kind: 'key', action: 'down', key: 'Enter', code: null, text: null, modifiers: 0 }, + }, + }, + { + type: 'browser', + project_root: '/test', + op: { action: 'resize', tab_id: null, width: 800, height: 600, scale: 2.0 }, + }, + { type: 'browser', project_root: '/test', op: { action: 'frame_ack', tab_id: null, seq: 4 } }, + { + type: 'browser', + project_root: '/test', + op: { action: 'control', tab_id: null, driver: 'human' }, + }, + { type: 'browser_attach', project_root: '/test', tab_id: 'T1' }, + { + type: 'grid_command', + project_root: '/test', + command: { action: 'open_browser', browser_tab: 'T1' }, + }, ]; export const responseOutputs: Response[] = [ @@ -303,7 +386,7 @@ export const responseOutputs: Response[] = [ type: 'health_report', pid: 1, uptime_seconds: 10, - protocol_version: 14, + protocol_version: 15, projects: ['/a'], agent_count: 2, }, @@ -685,4 +768,25 @@ export const responseOutputs: Response[] = [ truncated: false, }, { type: 'attach_file_result', received: 2, path: null }, + { + type: 'browser_tab', + tab: { + tab_id: 'T1', + url: 'http://localhost:3000/', + title: 'App', + loading: false, + driver: 'agent', + can_go_back: false, + can_go_forward: false, + width: 1280, + height: 800, + }, + }, + { type: 'browser_frame', tab_id: 'T1', seq: 3, data: '/9j/', width: 1280.0, height: 800.0 }, + { type: 'browser_tab_closed', tab_id: 'T1' }, + { + type: 'browser_console', + tab_id: 'T1', + entries: [{ level: 'error', text: 'boom', timestamp_ms: 1 }], + }, ]; diff --git a/crates/pu-cli/src/commands/browser.rs b/crates/pu-cli/src/commands/browser.rs new file mode 100644 index 00000000..3026d247 --- /dev/null +++ b/crates/pu-cli/src/commands/browser.rs @@ -0,0 +1,281 @@ +//! `pu browser`: drive the project's headless browser on the daemon's machine. + +use std::path::Path; + +use clap::{Subcommand, ValueEnum}; +use pu_core::protocol::{BrowserDriver, BrowserHistory, BrowserOp, GridCommand, Request, Response}; + +use crate::client; +use crate::daemon_ctrl; +use crate::error::CliError; +use crate::output; + +#[derive(Subcommand, Debug, Clone, PartialEq)] +pub enum BrowserAction { + /// Open a tab (starting the project's browser if needed) + Open { + /// Address to load, e.g. localhost:3000 or https://example.com + url: Option, + /// Also show the tab in a browser pane in the PurePoint app + #[arg(long)] + show: bool, + }, + /// List open tabs (the last is the default tab) + Tabs, + /// Close a tab; closing the last stops the project's browser + Close, + /// Load an address in the tab and wait for it + #[command(alias = "navigate")] + Goto { url: String }, + /// Go back in the tab's history + Back, + /// Go forward in the tab's history + Forward, + /// Reload the page + Reload, + /// Print the page as an outline; interactive elements carry [ref=eN] + Snapshot, + /// Click an element by its ref from the latest snapshot + Click { + /// e.g. e3 + #[arg(value_name = "REF")] + element: String, + }, + /// Replace an element's text (ref from the latest snapshot, or "focused") + Type { + /// e.g. e5, or "focused" for the element that has focus + #[arg(value_name = "REF")] + element: String, + text: String, + /// Press Enter afterwards + #[arg(long)] + submit: bool, + }, + /// Press a key or chord: Enter, Tab, Escape, ArrowDown, Control+a + Press { key: String }, + /// Scroll the page + Scroll { + direction: ScrollDirection, + /// CSS pixels + #[arg(default_value_t = 600)] + amount: u32, + }, + /// Save a PNG on the daemon's machine and print its path + Screenshot { + /// Where to save it (default: ~/.pu/browser/screenshots/) + path: Option, + /// Capture the whole page, not just the viewport + #[arg(long)] + full_page: bool, + }, + /// Print console messages, uncaught exceptions and dialogs + Console { + /// Clear them after printing + #[arg(long)] + clear: bool, + }, + /// Evaluate a JavaScript expression and print its value + Eval { expression: String }, + /// Wait for text to appear, or for loading to finish + Wait { + /// Text to wait for + #[arg(long)] + text: Option, + /// Give up after this many milliseconds (default 10000, max 120000) + #[arg(long)] + timeout: Option, + }, + /// Hand the tab to a person ("human") or back to agents ("agent") + Control { driver: Driver }, +} + +#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)] +pub enum ScrollDirection { + Up, + Down, + Left, + Right, +} + +#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)] +pub enum Driver { + Human, + Agent, +} + +/// The daemon op for a subcommand. `cwd` makes a relative screenshot path +/// absolute; with `--machine` it is `None` and paths are sent as given. +pub fn op_for(action: BrowserAction, tab: Option, cwd: Option<&Path>) -> BrowserOp { + let tab_id = tab; + match action { + BrowserAction::Open { url, .. } => BrowserOp::Open { url }, + BrowserAction::Tabs => BrowserOp::List, + BrowserAction::Close => BrowserOp::Close { tab_id }, + BrowserAction::Goto { url } => BrowserOp::Navigate { tab_id, url }, + BrowserAction::Back => BrowserOp::History { + tab_id, + direction: BrowserHistory::Back, + }, + BrowserAction::Forward => BrowserOp::History { + tab_id, + direction: BrowserHistory::Forward, + }, + BrowserAction::Reload => BrowserOp::History { + tab_id, + direction: BrowserHistory::Reload, + }, + BrowserAction::Snapshot => BrowserOp::Snapshot { tab_id }, + BrowserAction::Click { element } => BrowserOp::Click { tab_id, element }, + BrowserAction::Type { + element, + text, + submit, + } => BrowserOp::Type { + tab_id, + element: (!matches!(element.as_str(), "focused" | "-")).then_some(element), + text, + submit, + }, + BrowserAction::Press { key } => BrowserOp::Press { tab_id, key }, + BrowserAction::Scroll { direction, amount } => { + let amount = f64::from(amount); + let (dx, dy) = match direction { + ScrollDirection::Up => (0.0, -amount), + ScrollDirection::Down => (0.0, amount), + ScrollDirection::Left => (-amount, 0.0), + ScrollDirection::Right => (amount, 0.0), + }; + BrowserOp::Scroll { tab_id, dx, dy } + } + BrowserAction::Screenshot { path, full_page } => BrowserOp::Screenshot { + tab_id, + path: path.map(|p| match cwd { + Some(cwd) if !Path::new(&p).is_absolute() => { + cwd.join(p).to_string_lossy().into_owned() + } + _ => p, + }), + full_page, + }, + BrowserAction::Console { clear } => BrowserOp::Console { tab_id, clear }, + BrowserAction::Eval { expression } => BrowserOp::Eval { tab_id, expression }, + BrowserAction::Wait { text, timeout } => BrowserOp::Wait { + tab_id, + text, + timeout_ms: timeout, + }, + BrowserAction::Control { driver } => BrowserOp::Control { + tab_id, + driver: match driver { + Driver::Human => BrowserDriver::Human, + Driver::Agent => BrowserDriver::Agent, + }, + }, + } +} + +pub async fn run( + socket: &Path, + action: BrowserAction, + tab: Option, + json: bool, +) -> Result<(), CliError> { + daemon_ctrl::ensure_daemon(socket).await?; + let project_root = crate::commands::project_root_string()?; + let show = matches!(action, BrowserAction::Open { show: true, .. }); + let cwd = if crate::machine_target::remote_machine().is_some() { + None + } else { + std::env::current_dir().ok() + }; + let op = op_for(action, tab, cwd.as_deref()); + let resp = client::send_request( + socket, + &Request::Browser { + project_root: project_root.clone(), + op, + }, + ) + .await?; + let resp = output::check_response(resp, json)?; + if show && let Response::BrowserTab { tab } = &resp { + // Best effort: with no app subscribed nobody shows it, which is fine. + let _ = client::send_request( + socket, + &Request::GridCommand { + project_root, + command: GridCommand::OpenBrowser { + workspace_id: None, + leaf_id: None, + browser_tab: tab.tab_id.clone(), + }, + }, + ) + .await; + } + if !json && matches!(resp, Response::Ok) { + return Ok(()); + } + output::print_response(&resp, json) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn given_type_with_focused_should_type_into_the_focused_element() { + let op = op_for( + BrowserAction::Type { + element: "focused".into(), + text: "hi".into(), + submit: true, + }, + None, + None, + ); + assert_eq!( + op, + BrowserOp::Type { + tab_id: None, + element: None, + text: "hi".into(), + submit: true + } + ); + } + + #[test] + fn given_a_relative_screenshot_path_should_resolve_it_locally_only() { + let action = || BrowserAction::Screenshot { + path: Some("shot.png".into()), + full_page: false, + }; + let local = op_for(action(), None, Some(Path::new("/work"))); + assert!( + matches!(local, BrowserOp::Screenshot { path: Some(p), .. } if p == "/work/shot.png") + ); + let remote = op_for(action(), None, None); + assert!(matches!(remote, BrowserOp::Screenshot { path: Some(p), .. } if p == "shot.png")); + } + + #[test] + fn given_scroll_directions_should_sign_the_deltas() { + let up = op_for( + BrowserAction::Scroll { + direction: ScrollDirection::Up, + amount: 300, + }, + Some("T".into()), + None, + ); + assert_eq!( + up, + BrowserOp::Scroll { + tab_id: Some("T".into()), + dx: 0.0, + dy: -300.0 + } + ); + } +} diff --git a/crates/pu-cli/src/commands/mod.rs b/crates/pu-cli/src/commands/mod.rs index 733c3c75..b8ea0241 100644 --- a/crates/pu-cli/src/commands/mod.rs +++ b/crates/pu-cli/src/commands/mod.rs @@ -1,6 +1,7 @@ pub mod agent_def; pub mod attach; pub mod bench; +pub mod browser; pub mod channel; pub mod clean; pub mod daemon; diff --git a/crates/pu-cli/src/main.rs b/crates/pu-cli/src/main.rs index 10796eb9..31ab8e46 100644 --- a/crates/pu-cli/src/main.rs +++ b/crates/pu-cli/src/main.rs @@ -291,6 +291,17 @@ enum Commands { #[arg(long)] interval: Option, }, + /// Drive the project's headless browser (shared with browser panes in the app) + Browser { + /// Tab to act on (an id from `pu browser tabs`; default: the last used) + #[arg(long, global = true)] + tab: Option, + /// Output as JSON + #[arg(long, global = true)] + json: bool, + #[command(subcommand)] + action: commands::browser::BrowserAction, + }, /// Manage machines reachable over SSH (use with --machine) Machine { #[command(subcommand)] @@ -1107,6 +1118,9 @@ async fn async_main() { } => commands::diff::run(&socket, worktree, stat, json).await, Commands::Watch { interval } => commands::watch::run(&socket, interval).await, Commands::Machine { action } => commands::machine::run(action).await, + Commands::Browser { tab, json, action } => { + commands::browser::run(&socket, action, tab, json).await + } Commands::Clean { worktree, all, diff --git a/crates/pu-cli/src/output/mod.rs b/crates/pu-cli/src/output/mod.rs index e200c05f..cd199e3a 100644 --- a/crates/pu-cli/src/output/mod.rs +++ b/crates/pu-cli/src/output/mod.rs @@ -44,6 +44,33 @@ pub fn print_response(response: &Response, json_mode: bool) -> Result<(), CliErr } match response { Response::Resync | Response::PtySize { .. } => {} + Response::BrowserTab { tab } + | Response::BrowserAttached { tab } + | Response::BrowserTabState { tab } => println!("{}", browser_tab_line(tab)), + Response::BrowserTabs { tabs } => { + if tabs.is_empty() { + println!("No open tabs"); + } + for tab in tabs { + println!("{}", browser_tab_line(tab)); + } + } + Response::BrowserSnapshot { tab, tree } => { + println!("{}", browser_tab_line(tab)); + print!("{tree}"); + } + Response::BrowserScreenshot { path, .. } => println!("{path}"), + Response::BrowserConsole { entries, .. } => { + for entry in entries { + println!("[{}] {}", entry.level, entry.text); + } + } + Response::BrowserEvalResult { value, .. } => match value { + serde_json::Value::String(s) => println!("{s}"), + other => println!("{}", serde_json::to_string_pretty(other)?), + }, + Response::BrowserFrame { seq, .. } => println!("frame {seq}"), + Response::BrowserTabClosed { tab_id } => println!("Tab {tab_id} closed"), Response::Inventory(report) => { let c = &report.summary; println!( @@ -376,3 +403,18 @@ pub fn print_response(response: &Response, json_mode: bool) -> Result<(), CliErr } Ok(()) } + +/// ` ""`, with loading and driver noted. +pub fn browser_tab_line(tab: &pu_core::protocol::BrowserTabInfo) -> String { + let mut line = format!("{} {}", tab.tab_id, tab.url); + if !tab.title.is_empty() { + line.push_str(&format!(" \"{}\"", tab.title)); + } + if tab.loading { + line.push_str(" (loading)"); + } + if tab.driver == pu_core::protocol::BrowserDriver::Human { + line.push_str(" (a person is driving)"); + } + line +} diff --git a/crates/pu-core/src/protocol/browser.rs b/crates/pu-core/src/protocol/browser.rs new file mode 100644 index 00000000..e98d93f2 --- /dev/null +++ b/crates/pu-core/src/protocol/browser.rs @@ -0,0 +1,354 @@ +//! Browser wire types (BROWSER-*, `docs/product/browser.md`). +//! +//! The daemon on each machine runs one headless Chromium per project. Every +//! operation is a `Request::Browser { project_root, op }`; a viewer (a browser +//! pane in an app) holds a `Request::BrowserAttach` stream, receives frames +//! and tab state, and sends its own `Request::Browser` ops on that stream. +//! Ops sent on an attach stream act as the person at the pane; ops sent +//! anywhere else act as an agent and are refused while a person drives. + +use serde::{Deserialize, Serialize}; + +/// Who is in control of a tab. Agent ops (click, type, navigate, eval…) are +/// refused with `BROWSER_HUMAN_DRIVING` while a person drives; reading the page +/// (snapshot, screenshot, console) always works. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +#[serde(rename_all = "snake_case")] +pub enum BrowserDriver { + #[default] + Agent, + Human, +} + +/// One open tab, as every client sees it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct BrowserTabInfo { + pub tab_id: String, + pub url: String, + pub title: String, + pub loading: bool, + pub driver: BrowserDriver, + pub can_go_back: bool, + pub can_go_forward: bool, + /// The page viewport in CSS pixels (what clicks are measured against). + pub width: u32, + pub height: u32, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct BrowserConsoleEntry { + /// `log`, `info`, `warning`, `error`, `debug`, `exception` or `dialog`. + pub level: String, + pub text: String, + /// Milliseconds since the Unix epoch. + pub timestamp_ms: u64, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +#[serde(rename_all = "snake_case")] +pub enum BrowserMouseAction { + Down, + Up, + Move, +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +#[serde(rename_all = "snake_case")] +pub enum BrowserMouseButton { + #[default] + None, + Left, + Middle, + Right, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +#[serde(rename_all = "snake_case")] +pub enum BrowserKeyAction { + Down, + Up, +} + +/// Modifier bits, as Chromium numbers them: Alt=1, Ctrl=2, Meta=4, Shift=8. +pub mod modifiers { + pub const ALT: u32 = 1; + pub const CTRL: u32 = 2; + pub const META: u32 = 4; + pub const SHIFT: u32 = 8; +} + +/// Input from a viewer. Coordinates are CSS pixels in the page viewport. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +#[serde(tag = "kind", rename_all = "snake_case")] +#[cfg_attr(feature = "ts", ts(optional_fields = nullable))] +pub enum BrowserInputEvent { + Mouse { + action: BrowserMouseAction, + x: f64, + y: f64, + #[serde(default)] + #[cfg_attr(feature = "ts", ts(optional = nullable))] + button: BrowserMouseButton, + #[serde(default)] + #[cfg_attr(feature = "ts", ts(optional = nullable))] + click_count: u32, + #[serde(default)] + #[cfg_attr(feature = "ts", ts(optional = nullable))] + modifiers: u32, + }, + Wheel { + x: f64, + y: f64, + dx: f64, + dy: f64, + #[serde(default)] + #[cfg_attr(feature = "ts", ts(optional = nullable))] + modifiers: u32, + }, + /// A key press or release. `key` is a DOM `KeyboardEvent.key` value + /// (`"a"`, `"Enter"`, `"ArrowLeft"`); `text` is what it types, if anything. + Key { + action: BrowserKeyAction, + key: String, + #[serde(default)] + code: Option<String>, + #[serde(default)] + text: Option<String>, + #[serde(default)] + #[cfg_attr(feature = "ts", ts(optional = nullable))] + modifiers: u32, + }, + /// Committed text (typing, paste, IME composition result). + Text { text: String }, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +#[serde(rename_all = "snake_case")] +pub enum BrowserHistory { + Back, + Forward, + Reload, +} + +/// One browser operation. A `None` tab id means the project's most recently +/// opened or used tab. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +#[serde(tag = "action", rename_all = "snake_case")] +#[cfg_attr(feature = "ts", ts(optional_fields = nullable))] +pub enum BrowserOp { + /// Open a tab (starting the project's browser if needed). → `BrowserTab` + Open { + #[serde(default)] + url: Option<String>, + }, + /// → `BrowserTabs`. Never starts the browser. + List, + /// → `Ok`. Closing the last tab stops the project's browser. + Close { + #[serde(default)] + tab_id: Option<String>, + }, + /// Load `url` and wait (up to 15 s) for it. → `BrowserTab` + Navigate { + #[serde(default)] + tab_id: Option<String>, + url: String, + }, + /// → `BrowserTab` + History { + #[serde(default)] + tab_id: Option<String>, + direction: BrowserHistory, + }, + /// The page as an accessibility outline with `[ref=eN]` on interactive + /// elements, for `click` and `type`. → `BrowserSnapshot` + Snapshot { + #[serde(default)] + tab_id: Option<String>, + }, + /// Click an element from the latest snapshot. → `Ok` + Click { + #[serde(default)] + tab_id: Option<String>, + #[serde(rename = "ref")] + element: String, + }, + /// Type into an element from the latest snapshot (or the focused element + /// when `ref` is left out), pressing Enter after when `submit`. → `Ok` + Type { + #[serde(default)] + tab_id: Option<String>, + #[serde(default, rename = "ref")] + element: Option<String>, + text: String, + #[serde(default)] + #[cfg_attr(feature = "ts", ts(optional = nullable))] + submit: bool, + }, + /// Press a key by DOM name (`Enter`, `Tab`, `Escape`, `ArrowDown`, `a`). → `Ok` + Press { + #[serde(default)] + tab_id: Option<String>, + key: String, + }, + /// Scroll the page by CSS pixels. → `Ok` + Scroll { + #[serde(default)] + tab_id: Option<String>, + #[serde(default)] + #[cfg_attr(feature = "ts", ts(optional = nullable))] + dx: f64, + dy: f64, + }, + /// Save a PNG on the daemon's machine (default `~/.pu/browser/screenshots/`). → `BrowserScreenshot` + Screenshot { + #[serde(default)] + tab_id: Option<String>, + #[serde(default)] + path: Option<String>, + #[serde(default)] + #[cfg_attr(feature = "ts", ts(optional = nullable))] + full_page: bool, + }, + /// Console messages, uncaught exceptions and dialogs since the tab opened + /// (or the last `clear`), oldest first. → `BrowserConsole` + Console { + #[serde(default)] + tab_id: Option<String>, + #[serde(default)] + #[cfg_attr(feature = "ts", ts(optional = nullable))] + clear: bool, + }, + /// Evaluate a JavaScript expression (promises are awaited). → `BrowserEvalResult` + Eval { + #[serde(default)] + tab_id: Option<String>, + expression: String, + }, + /// Wait until `text` appears on the page, or (without `text`) until it + /// stops loading. → `BrowserTab`, or `BROWSER_TIMEOUT`. + Wait { + #[serde(default)] + tab_id: Option<String>, + #[serde(default)] + text: Option<String>, + #[serde(default)] + timeout_ms: Option<u64>, + }, + /// Hand the tab to a person or back to agents. → `BrowserTab` + Control { + #[serde(default)] + tab_id: Option<String>, + driver: BrowserDriver, + }, + /// Viewer input. On an attach stream it is answered only on error. + Input { + #[serde(default)] + tab_id: Option<String>, + event: BrowserInputEvent, + }, + /// Set the viewport in CSS pixels and the viewer's pixel density. + /// On an attach stream it is answered only on error. + Resize { + #[serde(default)] + tab_id: Option<String>, + width: u32, + height: u32, + #[serde(default = "default_scale")] + #[cfg_attr(feature = "ts", ts(optional = nullable))] + scale: f64, + }, + /// Attach streams only: the viewer has drawn frame `seq`. Never answered. + FrameAck { + #[serde(default)] + tab_id: Option<String>, + seq: u64, + }, +} + +fn default_scale() -> f64 { + 1.0 +} + +impl BrowserOp { + pub fn tab_id(&self) -> Option<&str> { + match self { + Self::Open { .. } | Self::List => None, + Self::Close { tab_id } + | Self::Navigate { tab_id, .. } + | Self::History { tab_id, .. } + | Self::Snapshot { tab_id } + | Self::Click { tab_id, .. } + | Self::Type { tab_id, .. } + | Self::Press { tab_id, .. } + | Self::Scroll { tab_id, .. } + | Self::Screenshot { tab_id, .. } + | Self::Console { tab_id, .. } + | Self::Eval { tab_id, .. } + | Self::Wait { tab_id, .. } + | Self::Control { tab_id, .. } + | Self::Input { tab_id, .. } + | Self::Resize { tab_id, .. } + | Self::FrameAck { tab_id, .. } => tab_id.as_deref(), + } + } + + /// Points an op that names no tab at `tab_id` (an attach stream's tab). + pub fn default_tab(&mut self, id: &str) { + let slot = match self { + Self::Open { .. } | Self::List => return, + Self::Close { tab_id } + | Self::Navigate { tab_id, .. } + | Self::History { tab_id, .. } + | Self::Snapshot { tab_id } + | Self::Click { tab_id, .. } + | Self::Type { tab_id, .. } + | Self::Press { tab_id, .. } + | Self::Scroll { tab_id, .. } + | Self::Screenshot { tab_id, .. } + | Self::Console { tab_id, .. } + | Self::Eval { tab_id, .. } + | Self::Wait { tab_id, .. } + | Self::Control { tab_id, .. } + | Self::Input { tab_id, .. } + | Self::Resize { tab_id, .. } + | Self::FrameAck { tab_id, .. } => tab_id, + }; + if slot.is_none() { + *slot = Some(id.to_string()); + } + } + + /// Ops that act on the page and so are refused while a person drives, + /// unless they come from that person's viewer. + pub fn acts_on_page(&self) -> bool { + matches!( + self, + Self::Navigate { .. } + | Self::History { .. } + | Self::Click { .. } + | Self::Type { .. } + | Self::Press { .. } + | Self::Scroll { .. } + | Self::Eval { .. } + | Self::Input { .. } + ) + } + + /// Ops a viewer sends many times a second; an attach stream answers them only on error. + pub fn is_quiet_on_stream(&self) -> bool { + matches!( + self, + Self::Input { .. } | Self::Resize { .. } | Self::FrameAck { .. } + ) + } +} diff --git a/crates/pu-core/src/protocol/grid.rs b/crates/pu-core/src/protocol/grid.rs index 2a8b8700..050aaa89 100644 --- a/crates/pu-core/src/protocol/grid.rs +++ b/crates/pu-core/src/protocol/grid.rs @@ -53,6 +53,15 @@ pub enum GridCommand { #[serde(default, skip_serializing_if = "Option::is_none")] agent_id: Option<String>, }, + /// Open a tab after the pane's active tab showing browser tab `browser_tab` + /// (an id from `Request::Browser`), so a person can watch and take over. + OpenBrowser { + #[serde(default, skip_serializing_if = "Option::is_none")] + workspace_id: Option<String>, + #[serde(default, skip_serializing_if = "Option::is_none")] + leaf_id: Option<u32>, + browser_tab: String, + }, /// Select a tab by 1-based `index` or by `direction` ("next" | "prev"). SelectTab { #[serde(default, skip_serializing_if = "Option::is_none")] diff --git a/crates/pu-core/src/protocol/mod.rs b/crates/pu-core/src/protocol/mod.rs index e0f1b0d4..780d79dd 100644 --- a/crates/pu-core/src/protocol/mod.rs +++ b/crates/pu-core/src/protocol/mod.rs @@ -1,3 +1,4 @@ +mod browser; mod encoding; mod grid; mod inventory; @@ -8,6 +9,7 @@ mod targets; mod tests; pub use crate::channel::{ChannelAuthor, ChannelMessage, ChannelReaction, ChannelReference}; +pub use browser::*; pub use grid::*; pub use inventory::*; pub use payloads::*; @@ -19,7 +21,7 @@ use serde::{Deserialize, Serialize}; use crate::types::{AgentStatus, WorktreeEntry}; use indexmap::IndexMap; -pub const PROTOCOL_VERSION: u32 = 14; +pub const PROTOCOL_VERSION: u32 = 15; #[derive(Debug, Clone, Serialize, Deserialize)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] @@ -225,6 +227,19 @@ pub enum Request { project_root: String, command: GridCommand, }, + /// A browser operation on the project's headless browser (`docs/product/browser.md`). + Browser { + project_root: String, + op: BrowserOp, + }, + /// Watch and drive a tab: `BrowserAttached`, then `BrowserFrame` and + /// `BrowserTabState` until the tab closes (`BrowserTabClosed`) or the + /// client sends a line that is not a `browser` request. + BrowserAttach { + project_root: String, + #[serde(default)] + tab_id: Option<String>, + }, Rename { project_root: String, agent_id: String, @@ -645,6 +660,50 @@ pub enum Response { #[cfg_attr(feature = "ts", ts(type = "string"))] data: Vec<u8>, }, + BrowserTab { + tab: BrowserTabInfo, + }, + BrowserTabs { + tabs: Vec<BrowserTabInfo>, + }, + BrowserSnapshot { + tab: BrowserTabInfo, + /// Indented accessibility outline; interactive elements carry `[ref=eN]`. + tree: String, + }, + BrowserScreenshot { + tab_id: String, + /// A PNG on the daemon's machine. + path: String, + }, + BrowserConsole { + tab_id: String, + entries: Vec<BrowserConsoleEntry>, + }, + BrowserEvalResult { + tab_id: String, + value: serde_json::Value, + }, + BrowserAttached { + tab: BrowserTabInfo, + }, + /// One screencast frame. The viewer acks it with a `frame_ack` op; at most + /// two frames are unacknowledged, and older undrawn frames are skipped. + BrowserFrame { + tab_id: String, + seq: u64, + /// Base64 JPEG. + data: String, + /// The CSS viewport the frame shows, for mapping input coordinates. + width: f64, + height: f64, + }, + BrowserTabState { + tab: BrowserTabInfo, + }, + BrowserTabClosed { + tab_id: String, + }, GridSubscribed, GridLayout { layout: serde_json::Value, @@ -849,6 +908,8 @@ impl Request { | Self::SubscribeGrid { project_root, .. } | Self::SubscribeStatus { project_root, .. } | Self::GridCommand { project_root, .. } + | Self::Browser { project_root, .. } + | Self::BrowserAttach { project_root, .. } | Self::Rename { project_root, .. } | Self::AssignTrigger { project_root, .. } | Self::CreateWorktree { project_root, .. } diff --git a/crates/pu-core/src/protocol/tests.rs b/crates/pu-core/src/protocol/tests.rs index cc89bb37..7e34bc99 100644 --- a/crates/pu-core/src/protocol/tests.rs +++ b/crates/pu-core/src/protocol/tests.rs @@ -584,7 +584,7 @@ fn given_kill_request_without_exclude_should_default_empty() { #[test] fn given_protocol_version_should_be_current() { // Intentional hardcoded check — update when the protocol version is bumped. - assert_eq!(PROTOCOL_VERSION, 14); + assert_eq!(PROTOCOL_VERSION, 15); } // --- GridCommand round-trips --- @@ -2658,3 +2658,79 @@ fn given_fs_and_git_responses_should_round_trip_with_spec_shapes() { assert!(entry.get(key).is_some(), "missing {key}"); } } + +#[test] +fn given_browser_ops_should_parse_from_the_wire_and_round_trip() { + let cases = [ + r#"{"type":"browser","project_root":"/p","op":{"action":"open"}}"#, + r#"{"type":"browser","project_root":"/p","op":{"action":"list"}}"#, + r#"{"type":"browser","project_root":"/p","op":{"action":"click","ref":"e3"}}"#, + r#"{"type":"browser","project_root":"/p","op":{"action":"type","text":"hi"}}"#, + r#"{"type":"browser","project_root":"/p","op":{"action":"history","direction":"back"}}"#, + r#"{"type":"browser","project_root":"/p","op":{"action":"input","tab_id":"T","event":{"kind":"wheel","x":1,"y":2,"dx":0,"dy":-120}}}"#, + r#"{"type":"browser","project_root":"/p","op":{"action":"input","event":{"kind":"text","text":"é"}}}"#, + r#"{"type":"browser","project_root":"/p","op":{"action":"resize","width":10,"height":20}}"#, + r#"{"type":"browser_attach","project_root":"/p"}"#, + ]; + for json in cases { + let request: Request = serde_json::from_str(json).unwrap_or_else(|e| panic!("{json}: {e}")); + let again: Request = + serde_json::from_value(serde_json::to_value(&request).unwrap()).unwrap(); + assert_eq!( + serde_json::to_value(&again).unwrap(), + serde_json::to_value(&request).unwrap() + ); + } + let mut request: Request = serde_json::from_str(cases[2]).unwrap(); + assert_eq!(request.project_root_mut().map(|r| r.as_str()), Some("/p")); + match serde_json::from_str::<Request>(cases[7]).unwrap() { + Request::Browser { + op: BrowserOp::Resize { scale, .. }, + .. + } => assert_eq!(scale, 1.0), + other => panic!("{other:?}"), + } +} + +#[test] +fn given_browser_ops_should_say_which_act_on_the_page_and_default_their_tab() { + let click = BrowserOp::Click { + tab_id: None, + element: "e1".into(), + }; + assert!(click.acts_on_page()); + assert!(!BrowserOp::Snapshot { tab_id: None }.acts_on_page()); + assert!( + !BrowserOp::Control { + tab_id: None, + driver: BrowserDriver::Human + } + .acts_on_page() + ); + let mut op = BrowserOp::Navigate { + tab_id: None, + url: "x".into(), + }; + op.default_tab("T1"); + assert_eq!(op.tab_id(), Some("T1")); + let mut named = BrowserOp::Navigate { + tab_id: Some("T2".into()), + url: "x".into(), + }; + named.default_tab("T1"); + assert_eq!(named.tab_id(), Some("T2")); + assert!( + BrowserOp::FrameAck { + tab_id: None, + seq: 1 + } + .is_quiet_on_stream() + ); + assert!( + !BrowserOp::Navigate { + tab_id: None, + url: "x".into() + } + .is_quiet_on_stream() + ); +} diff --git a/crates/pu-core/src/ts_export.rs b/crates/pu-core/src/ts_export.rs index 4504420e..7ae70a89 100644 --- a/crates/pu-core/src/ts_export.rs +++ b/crates/pu-core/src/ts_export.rs @@ -57,6 +57,16 @@ const REQUEST_INPUTS: &[&str] = &[ r#"{"type":"fs_write","path":"/p/a","data_base64":"aGk="}"#, r#"{"type":"attach_file","upload_id":"u1","name":"a.png","data_base64":"aGk="}"#, r#"{"type":"git_exec","cwd":"/p","program":"git","args":["status"]}"#, + r#"{"type":"browser","project_root":"/test","op":{"action":"open","url":"localhost:3000"}}"#, + r#"{"type":"browser","project_root":"/test","op":{"action":"click","ref":"e3"}}"#, + r#"{"type":"browser","project_root":"/test","op":{"action":"type","tab_id":"T1","ref":"e5","text":"hi","submit":true}}"#, + r#"{"type":"browser","project_root":"/test","op":{"action":"input","event":{"kind":"mouse","action":"down","x":10,"y":20,"button":"left","click_count":1}}}"#, + r#"{"type":"browser","project_root":"/test","op":{"action":"input","event":{"kind":"key","action":"down","key":"Enter"}}}"#, + r#"{"type":"browser","project_root":"/test","op":{"action":"resize","width":800,"height":600,"scale":2}}"#, + r#"{"type":"browser","project_root":"/test","op":{"action":"frame_ack","seq":4}}"#, + r#"{"type":"browser","project_root":"/test","op":{"action":"control","driver":"human"}}"#, + r#"{"type":"browser_attach","project_root":"/test","tab_id":"T1"}"#, + r#"{"type":"grid_command","project_root":"/test","command":{"action":"open_browser","browser_tab":"T1"}}"#, ]; const SIGNAL: &str = r#"{"schema_version":1,"identity":{"agent_id":"ag-1","worktree_id":null,"launch_id":"l1","generation":3,"native_session_id":"s1"},"activity":"idle","pending_attention":[{"request_id":"r1","kind":"permission","event_id":"e1","turn_id":null,"confidence":"authoritative"}],"outcome":{"kind":"completed","event_id":"e2","turn_id":"t1","confidence":"heuristic"},"observation":{"state":"current","last_received_at_ms":1000,"expires_at_ms":2000},"evidence":null}"#; @@ -70,7 +80,7 @@ fn response_inputs() -> Vec<String> { vec![ r#"{"type":"ok"}"#.into(), r#"{"type":"error","code":"NOT_FOUND","message":"no such agent"}"#.into(), - r#"{"type":"health_report","pid":1,"uptime_seconds":10,"protocol_version":14,"projects":["/a"],"agent_count":2}"#.into(), + r#"{"type":"health_report","pid":1,"uptime_seconds":10,"protocol_version":15,"projects":["/a"],"agent_count":2}"#.into(), r#"{"type":"project_order","project_roots":["/b","/a"]}"#.into(), r#"{"type":"spawn_result","worktree_id":null,"agent_id":"ag-1","status":"running"}"#.into(), format!( @@ -97,6 +107,10 @@ fn response_inputs() -> Vec<String> { r#"{"type":"pulse_report","worktrees":[{"worktree_id":"wt-1","worktree_name":"fix","branch":"pu/fix","elapsed_seconds":9,"agents":[],"files_changed":1,"insertions":2,"deletions":3}],"root_agents":[{"id":"ag-1","name":"c","agent_type":"claude","status":"broken","exit_code":1,"runtime_seconds":4,"idle_seconds":null,"prompt_snippet":null}]}"#.into(), r#"{"type":"fs_list_result","path":"/a","entries":[{"name":"b","path":"/a/b","is_dir":false,"is_symlink":false,"size":3,"modified_ms":-1,"ignored":false}],"truncated":false}"#.into(), r#"{"type":"attach_file_result","received":2}"#.into(), + r#"{"type":"browser_tab","tab":{"tab_id":"T1","url":"http://localhost:3000/","title":"App","loading":false,"driver":"agent","can_go_back":false,"can_go_forward":false,"width":1280,"height":800}}"#.into(), + r#"{"type":"browser_frame","tab_id":"T1","seq":3,"data":"/9j/","width":1280.0,"height":800.0}"#.into(), + r#"{"type":"browser_tab_closed","tab_id":"T1"}"#.into(), + r#"{"type":"browser_console","tab_id":"T1","entries":[{"level":"error","text":"boom","timestamp_ms":1}]}"#.into(), ] } diff --git a/crates/pu-engine/src/browser/cdp.rs b/crates/pu-engine/src/browser/cdp.rs new file mode 100644 index 00000000..f5a5e0a7 --- /dev/null +++ b/crates/pu-engine/src/browser/cdp.rs @@ -0,0 +1,334 @@ +//! A minimal Chrome DevTools Protocol client over a byte stream. +//! +//! Chromium started with `--remote-debugging-pipe` reads commands on fd 3 and +//! writes replies and events on fd 4, each message a JSON object followed by +//! a NUL byte. Commands are matched to replies by `id`; everything else is an +//! event, fanned out to subscribers. Sessions use flat mode: a command for a +//! tab carries that tab's `sessionId`, and so do its events. + +use std::collections::HashMap; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::time::Duration; + +use serde_json::{Value, json}; +use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader}; +use tokio::sync::{Mutex, broadcast, mpsc, oneshot}; + +/// No single command should take this long; a hung browser must not hang a client. +const CALL_TIMEOUT: Duration = Duration::from_secs(30); +/// Chromium can emit large bursts (screencast frames, console floods). A +/// subscriber that falls this far behind loses events rather than stalling the reader. +const EVENT_CAPACITY: usize = 4096; +/// Messages beyond this are dropped (a full-page screenshot of a huge page can +/// still be tens of MB, so the limit is generous). +const MAX_MESSAGE: usize = 256 * 1024 * 1024; + +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum CdpError { + #[error("browser closed")] + Closed, + #[error("browser did not answer {0} in time")] + Timeout(String), + #[error("{method}: {message}")] + Protocol { method: String, message: String }, +} + +/// One event from the browser. +#[derive(Debug, Clone)] +pub struct CdpEvent { + pub method: String, + pub params: Value, + pub session_id: Option<String>, +} + +type Pending = Arc<Mutex<HashMap<u64, (String, oneshot::Sender<Result<Value, CdpError>>)>>>; + +pub struct Cdp { + outbox: mpsc::UnboundedSender<Vec<u8>>, + pending: Pending, + next_id: AtomicU64, + events: broadcast::Sender<Arc<CdpEvent>>, + alive: Arc<AtomicBool>, + closed: Arc<tokio::sync::Notify>, +} + +impl Cdp { + /// Starts the reader and writer tasks. `reader` is the browser's output + /// (fd 4), `writer` its input (fd 3). + pub fn start<R, W>(reader: R, writer: W) -> Arc<Self> + where + R: AsyncRead + Unpin + Send + 'static, + W: AsyncWrite + Unpin + Send + 'static, + { + let (outbox, mut outbox_rx) = mpsc::unbounded_channel::<Vec<u8>>(); + let pending: Pending = Arc::default(); + let (events, _) = broadcast::channel(EVENT_CAPACITY); + let alive = Arc::new(AtomicBool::new(true)); + let closed = Arc::new(tokio::sync::Notify::new()); + + let mut writer = writer; + tokio::spawn(async move { + while let Some(message) = outbox_rx.recv().await { + if writer.write_all(&message).await.is_err() || writer.flush().await.is_err() { + break; + } + } + }); + + let reader_pending = pending.clone(); + let reader_events = events.clone(); + let reader_alive = alive.clone(); + let reader_closed = closed.clone(); + tokio::spawn(async move { + let mut reader = BufReader::new(reader); + let mut buf = Vec::new(); + loop { + buf.clear(); + match reader.read_until(0, &mut buf).await { + Ok(0) | Err(_) => break, + Ok(_) => {} + } + if buf.last() == Some(&0) { + buf.pop(); + } + if buf.is_empty() || buf.len() > MAX_MESSAGE { + continue; + } + let Ok(message) = serde_json::from_slice::<Value>(&buf) else { + tracing::debug!("unparseable devtools message"); + continue; + }; + dispatch(message, &reader_pending, &reader_events).await; + } + reader_alive.store(false, Ordering::SeqCst); + // Fail every waiting call: nothing will answer them now. + for (_, (_, tx)) in reader_pending.lock().await.drain() { + let _ = tx.send(Err(CdpError::Closed)); + } + reader_closed.notify_waiters(); + }); + + Arc::new(Self { + outbox, + pending, + next_id: AtomicU64::new(1), + events, + alive, + closed, + }) + } + + pub fn is_alive(&self) -> bool { + self.alive.load(Ordering::SeqCst) + } + + /// Resolves once the browser's output has closed. + pub async fn closed(&self) { + let notified = self.closed.notified(); + if !self.is_alive() { + return; + } + notified.await; + } + + pub fn subscribe(&self) -> broadcast::Receiver<Arc<CdpEvent>> { + self.events.subscribe() + } + + /// Sends a command and waits for its result. + pub async fn call( + &self, + session_id: Option<&str>, + method: &str, + params: Value, + ) -> Result<Value, CdpError> { + if !self.is_alive() { + return Err(CdpError::Closed); + } + let id = self.next_id.fetch_add(1, Ordering::Relaxed); + let mut message = json!({ "id": id, "method": method, "params": params }); + if let Some(session_id) = session_id { + message["sessionId"] = Value::String(session_id.to_string()); + } + let mut bytes = serde_json::to_vec(&message).expect("a JSON value always serializes"); + bytes.push(0); + + let (tx, rx) = oneshot::channel(); + self.pending + .lock() + .await + .insert(id, (method.to_string(), tx)); + if self.outbox.send(bytes).is_err() { + self.pending.lock().await.remove(&id); + return Err(CdpError::Closed); + } + match tokio::time::timeout(CALL_TIMEOUT, rx).await { + Ok(Ok(result)) => result, + Ok(Err(_)) => Err(CdpError::Closed), + Err(_) => { + self.pending.lock().await.remove(&id); + Err(CdpError::Timeout(method.to_string())) + } + } + } + + /// Sends a command without waiting for its result (acks, input bursts). + pub fn send(&self, session_id: Option<&str>, method: &str, params: Value) { + let id = self.next_id.fetch_add(1, Ordering::Relaxed); + let mut message = json!({ "id": id, "method": method, "params": params }); + if let Some(session_id) = session_id { + message["sessionId"] = Value::String(session_id.to_string()); + } + let mut bytes = serde_json::to_vec(&message).expect("a JSON value always serializes"); + bytes.push(0); + let _ = self.outbox.send(bytes); + } +} + +async fn dispatch(message: Value, pending: &Pending, events: &broadcast::Sender<Arc<CdpEvent>>) { + if let Some(id) = message.get("id").and_then(Value::as_u64) { + let Some((method, tx)) = pending.lock().await.remove(&id) else { + return; // a `send` or a timed-out call + }; + let result = match message.get("error") { + Some(error) => Err(CdpError::Protocol { + method, + message: error + .get("message") + .and_then(Value::as_str) + .unwrap_or("unknown error") + .to_string(), + }), + None => Ok(message.get("result").cloned().unwrap_or(Value::Null)), + }; + let _ = tx.send(result); + return; + } + let Some(method) = message.get("method").and_then(Value::as_str) else { + return; + }; + let event = CdpEvent { + method: method.to_string(), + params: message.get("params").cloned().unwrap_or(Value::Null), + session_id: message + .get("sessionId") + .and_then(Value::as_str) + .map(str::to_string), + }; + let _ = events.send(Arc::new(event)); +} + +#[cfg(test)] +mod tests { + use super::*; + use tokio::io::{AsyncReadExt, duplex}; + + /// Reads one NUL-terminated message the client wrote. + async fn read_message(stream: &mut (impl AsyncRead + Unpin)) -> Value { + let mut bytes = Vec::new(); + loop { + let byte = stream.read_u8().await.unwrap(); + if byte == 0 { + break; + } + bytes.push(byte); + } + serde_json::from_slice(&bytes).unwrap() + } + + async fn write_message(stream: &mut (impl AsyncWrite + Unpin), value: Value) { + let mut bytes = serde_json::to_vec(&value).unwrap(); + bytes.push(0); + stream.write_all(&bytes).await.unwrap(); + } + + #[tokio::test] + async fn given_a_call_should_send_a_nul_terminated_command_and_return_its_result() { + let (client_out, mut browser_in) = duplex(4096); + let (mut browser_out, client_in) = duplex(4096); + let cdp = Cdp::start(client_in, client_out); + + let call = tokio::spawn({ + let cdp = cdp.clone(); + async move { + cdp.call(Some("S1"), "Page.navigate", json!({"url": "http://x"})) + .await + } + }); + let command = read_message(&mut browser_in).await; + assert_eq!(command["method"], "Page.navigate"); + assert_eq!(command["sessionId"], "S1"); + assert_eq!(command["params"]["url"], "http://x"); + write_message( + &mut browser_out, + json!({"id": command["id"], "result": {"frameId": "F"}}), + ) + .await; + assert_eq!(call.await.unwrap().unwrap(), json!({"frameId": "F"})); + } + + #[tokio::test] + async fn given_an_error_reply_should_return_a_protocol_error_naming_the_method() { + let (client_out, mut browser_in) = duplex(4096); + let (mut browser_out, client_in) = duplex(4096); + let cdp = Cdp::start(client_in, client_out); + + let call = tokio::spawn({ + let cdp = cdp.clone(); + async move { cdp.call(None, "DOM.focus", json!({})).await } + }); + let command = read_message(&mut browser_in).await; + write_message( + &mut browser_out, + json!({"id": command["id"], "error": {"code": -32000, "message": "not focusable"}}), + ) + .await; + assert_eq!( + call.await.unwrap(), + Err(CdpError::Protocol { + method: "DOM.focus".into(), + message: "not focusable".into() + }) + ); + } + + #[tokio::test] + async fn given_an_event_should_deliver_it_with_its_session() { + let (client_out, _browser_in) = duplex(4096); + let (mut browser_out, client_in) = duplex(4096); + let cdp = Cdp::start(client_in, client_out); + let mut events = cdp.subscribe(); + + write_message( + &mut browser_out, + json!({"method": "Page.loadEventFired", "params": {"timestamp": 1}, "sessionId": "S2"}), + ) + .await; + let event = events.recv().await.unwrap(); + assert_eq!(event.method, "Page.loadEventFired"); + assert_eq!(event.session_id.as_deref(), Some("S2")); + assert_eq!(event.params["timestamp"], 1); + } + + #[tokio::test] + async fn given_the_browser_closes_should_fail_waiting_calls_and_report_closed() { + let (client_out, mut browser_in) = duplex(4096); + let (browser_out, client_in) = duplex(4096); + let cdp = Cdp::start(client_in, client_out); + + let call = tokio::spawn({ + let cdp = cdp.clone(); + async move { cdp.call(None, "Browser.getVersion", json!({})).await } + }); + let _ = read_message(&mut browser_in).await; + drop(browser_out); + assert_eq!(call.await.unwrap(), Err(CdpError::Closed)); + cdp.closed().await; + assert!(!cdp.is_alive()); + assert_eq!( + cdp.call(None, "Browser.getVersion", json!({})).await, + Err(CdpError::Closed) + ); + } +} diff --git a/crates/pu-engine/src/browser/keys.rs b/crates/pu-engine/src/browser/keys.rs new file mode 100644 index 00000000..9abb9cf4 --- /dev/null +++ b/crates/pu-engine/src/browser/keys.rs @@ -0,0 +1,141 @@ +//! DOM key names to the fields Chromium's `Input.dispatchKeyEvent` needs. + +use serde_json::{Value, json}; + +/// The `key`, `code`, Windows virtual key code and typed text for a DOM key name. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct KeyInfo { + pub key: String, + pub code: String, + pub key_code: u32, + pub text: Option<String>, +} + +pub fn lookup(name: &str) -> KeyInfo { + let named = |key: &str, code: &str, key_code: u32, text: Option<&str>| KeyInfo { + key: key.to_string(), + code: code.to_string(), + key_code, + text: text.map(str::to_string), + }; + match name { + "Enter" | "Return" => named("Enter", "Enter", 13, Some("\r")), + "Tab" => named("Tab", "Tab", 9, None), + "Escape" | "Esc" => named("Escape", "Escape", 27, None), + "Backspace" => named("Backspace", "Backspace", 8, None), + "Delete" => named("Delete", "Delete", 46, None), + "Space" | " " => named(" ", "Space", 32, Some(" ")), + "ArrowUp" | "Up" => named("ArrowUp", "ArrowUp", 38, None), + "ArrowDown" | "Down" => named("ArrowDown", "ArrowDown", 40, None), + "ArrowLeft" | "Left" => named("ArrowLeft", "ArrowLeft", 37, None), + "ArrowRight" | "Right" => named("ArrowRight", "ArrowRight", 39, None), + "Home" => named("Home", "Home", 36, None), + "End" => named("End", "End", 35, None), + "PageUp" => named("PageUp", "PageUp", 33, None), + "PageDown" => named("PageDown", "PageDown", 34, None), + "Shift" => named("Shift", "ShiftLeft", 16, None), + "Control" => named("Control", "ControlLeft", 17, None), + "Alt" => named("Alt", "AltLeft", 18, None), + "Meta" => named("Meta", "MetaLeft", 91, None), + other => { + if let Some(n) = other + .strip_prefix('F') + .and_then(|n| n.parse::<u32>().ok()) + .filter(|n| (1..=12).contains(n)) + { + return named(other, other, 111 + n, None); + } + let mut chars = other.chars(); + match (chars.next(), chars.next()) { + (Some(c), None) => { + let upper = c.to_ascii_uppercase(); + let (code, key_code) = if c.is_ascii_alphabetic() { + (format!("Key{upper}"), upper as u32) + } else if c.is_ascii_digit() { + (format!("Digit{c}"), c as u32) + } else { + (String::new(), 0) + }; + KeyInfo { + key: c.to_string(), + code, + key_code, + text: Some(c.to_string()), + } + } + _ => named(other, "", 0, None), + } + } + } +} + +/// The `Input.dispatchKeyEvent` params for one press or release. +pub fn key_event(down: bool, info: &KeyInfo, modifiers: u32) -> Value { + // A key that types something is a `keyDown` with text; Chromium inserts it. + // Ctrl/Meta chords must not type (they are shortcuts). + let types = down && modifiers & (super::modifiers::CTRL | super::modifiers::META) == 0; + let kind = match (down, types && info.text.is_some()) { + (true, true) => "keyDown", + (true, false) => "rawKeyDown", + (false, _) => "keyUp", + }; + let mut params = json!({ + "type": kind, + "key": info.key, + "code": info.code, + "windowsVirtualKeyCode": info.key_code, + "nativeVirtualKeyCode": info.key_code, + "modifiers": modifiers, + }); + if kind == "keyDown" + && let Some(text) = &info.text + { + params["text"] = json!(text); + params["unmodifiedText"] = json!(text); + } + params +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn given_named_keys_should_map_to_dom_codes() { + assert_eq!(lookup("Enter").key_code, 13); + assert_eq!(lookup("Enter").text.as_deref(), Some("\r")); + assert_eq!(lookup("ArrowDown").code, "ArrowDown"); + assert_eq!(lookup("Esc").key, "Escape"); + assert_eq!(lookup("F5").key_code, 116); + } + + #[test] + fn given_a_character_should_map_to_its_key_and_text() { + let a = lookup("a"); + assert_eq!( + (a.key.as_str(), a.code.as_str(), a.key_code), + ("a", "KeyA", 65) + ); + assert_eq!(a.text.as_deref(), Some("a")); + assert_eq!(lookup("7").code, "Digit7"); + assert_eq!(lookup("/").text.as_deref(), Some("/")); + } + + #[test] + fn given_a_typing_key_down_should_carry_text() { + let params = key_event(true, &lookup("a"), 0); + assert_eq!(params["type"], "keyDown"); + assert_eq!(params["text"], "a"); + } + + #[test] + fn given_a_shortcut_or_release_should_not_type() { + let chord = key_event(true, &lookup("a"), super::super::modifiers::META); + assert_eq!(chord["type"], "rawKeyDown"); + assert!(chord.get("text").is_none()); + let up = key_event(false, &lookup("a"), 0); + assert_eq!(up["type"], "keyUp"); + assert!(up.get("text").is_none()); + assert_eq!(key_event(true, &lookup("Tab"), 0)["type"], "rawKeyDown"); + } +} diff --git a/crates/pu-engine/src/browser/launch.rs b/crates/pu-engine/src/browser/launch.rs new file mode 100644 index 00000000..6daff606 --- /dev/null +++ b/crates/pu-engine/src/browser/launch.rs @@ -0,0 +1,276 @@ +//! Finding and starting the machine's Chromium. +//! +//! The browser is started headless with `--remote-debugging-pipe`: it reads +//! DevTools commands on fd 3 and writes on fd 4, so it opens no debugging +//! port and only the daemon (which holds the other pipe ends) can drive it. + +use std::path::{Path, PathBuf}; + +/// `PU_BROWSER` names the browser executable, overriding the search. +pub const BROWSER_ENV: &str = "PU_BROWSER"; + +const DEFAULT_WIDTH: u32 = 1280; +const DEFAULT_HEIGHT: u32 = 800; + +/// Candidate executables, most preferred first. +pub fn candidates(path_var: Option<&str>) -> Vec<PathBuf> { + let mut out = Vec::new(); + if cfg!(target_os = "macos") { + for app in [ + "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", + "/Applications/Chromium.app/Contents/MacOS/Chromium", + "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge", + "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser", + ] { + out.push(PathBuf::from(app)); + } + if let Ok(home) = pu_core::paths::home_dir() { + out.push(home.join("Applications/Google Chrome.app/Contents/MacOS/Google Chrome")); + } + } + let names = [ + "google-chrome", + "google-chrome-stable", + "chromium", + "chromium-browser", + "microsoft-edge", + "microsoft-edge-stable", + "brave-browser", + "chrome-headless-shell", + ]; + let mut dirs: Vec<PathBuf> = path_var + .map(|p| std::env::split_paths(p).collect()) + .unwrap_or_default(); + for extra in [ + "/usr/bin", + "/usr/local/bin", + "/opt/homebrew/bin", + "/snap/bin", + ] { + let extra = PathBuf::from(extra); + if !dirs.contains(&extra) { + dirs.push(extra); + } + } + for name in names { + for dir in &dirs { + out.push(dir.join(name)); + } + } + if let Ok(home) = pu_core::paths::home_dir() { + // `pu browser install` (or a manual unpack) puts one here. + out.push(home.join(".pu/browser/chrome/chrome")); + } + out +} + +/// The browser to run: `PU_BROWSER` if set, else the first candidate that exists. +pub fn find_browser(env_override: Option<&str>, path_var: Option<&str>) -> Option<PathBuf> { + if let Some(explicit) = env_override.filter(|s| !s.is_empty()) { + return Some(PathBuf::from(explicit)); + } + candidates(path_var).into_iter().find(|p| is_executable(p)) +} + +fn is_executable(path: &Path) -> bool { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::metadata(path) + .map(|m| m.is_file() && m.permissions().mode() & 0o111 != 0) + .unwrap_or(false) + } + #[cfg(not(unix))] + { + path.is_file() + } +} + +/// The command-line flags for a headless, pipe-driven browser on `profile`. +pub fn args(profile: &Path, as_root: bool) -> Vec<String> { + let mut args = vec![ + "--headless=new".to_string(), + "--remote-debugging-pipe".to_string(), + format!("--user-data-dir={}", profile.display()), + "--no-first-run".to_string(), + "--no-default-browser-check".to_string(), + "--disable-background-networking".to_string(), + "--disable-features=Translate,MediaRouter,OptimizationHints".to_string(), + "--mute-audio".to_string(), + format!("--window-size={DEFAULT_WIDTH},{DEFAULT_HEIGHT}"), + ]; + if as_root { + // Chromium refuses to run its sandbox as root (containers, some servers). + args.push("--no-sandbox".to_string()); + } + args.push("about:blank".to_string()); + args +} + +/// A stable directory name for a project's browser profile, so logins +/// survive daemon restarts. FNV-1a: `DefaultHasher` may change between releases. +pub fn profile_key(project_root: &str) -> String { + let mut hash: u64 = 0xcbf2_9ce4_8422_2325; + for byte in project_root.as_bytes() { + hash ^= u64::from(*byte); + hash = hash.wrapping_mul(0x0000_0100_0000_01b3); + } + let name = Path::new(project_root) + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + let safe: String = name + .chars() + .filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_') + .take(32) + .collect(); + format!("{safe}-{hash:016x}") +} + +pub fn default_size() -> (u32, u32) { + (DEFAULT_WIDTH, DEFAULT_HEIGHT) +} + +#[cfg(unix)] +pub mod unix { + use std::os::fd::{AsRawFd, OwnedFd}; + use std::path::Path; + + use tokio::net::unix::pipe; + + /// A running browser and the daemon's ends of its DevTools pipe. + pub struct Launched { + pub child: tokio::process::Child, + /// Browser output (its fd 4). + pub reader: pipe::Receiver, + /// Browser input (its fd 3). + pub writer: pipe::Sender, + } + + fn cloexec_pipe() -> std::io::Result<(OwnedFd, OwnedFd)> { + nix::unistd::pipe2(nix::fcntl::OFlag::O_CLOEXEC).map_err(std::io::Error::from) + } + + fn set_nonblocking(fd: &OwnedFd) -> std::io::Result<()> { + use nix::fcntl::{FcntlArg, OFlag, fcntl}; + let flags = fcntl(fd, FcntlArg::F_GETFL).map_err(std::io::Error::from)?; + let flags = OFlag::from_bits_truncate(flags) | OFlag::O_NONBLOCK; + fcntl(fd, FcntlArg::F_SETFL(flags)).map_err(std::io::Error::from)?; + Ok(()) + } + + pub fn spawn( + executable: &Path, + args: &[String], + log: Option<&Path>, + ) -> std::io::Result<Launched> { + // Browser reads `to_browser_read` (fd 3), writes `from_browser_write` (fd 4). + let (to_browser_read, to_browser_write) = cloexec_pipe()?; + let (from_browser_read, from_browser_write) = cloexec_pipe()?; + let child_in = to_browser_read.as_raw_fd(); + let child_out = from_browser_write.as_raw_fd(); + + let mut command = tokio::process::Command::new(executable); + command + .args(args) + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::null()) + .kill_on_drop(true) + // Its own group, so stopping it also stops its renderer processes. + .process_group(0); + match log.and_then(|p| { + std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(p) + .ok() + }) { + Some(file) => command.stderr(file), + None => command.stderr(std::process::Stdio::null()), + }; + // SAFETY: only async-signal-safe calls (fcntl, dup2) between fork and exec. + unsafe { + command.pre_exec(move || { + // Move both ends above 3/4 first so the dup2s cannot clobber each other. + let high_in = libc::fcntl(child_in, libc::F_DUPFD_CLOEXEC, 10); + let high_out = libc::fcntl(child_out, libc::F_DUPFD_CLOEXEC, 10); + if high_in < 0 || high_out < 0 { + return Err(std::io::Error::last_os_error()); + } + // dup2 clears close-on-exec on the new descriptor. + if libc::dup2(high_in, 3) < 0 || libc::dup2(high_out, 4) < 0 { + return Err(std::io::Error::last_os_error()); + } + Ok(()) + }); + } + let child = command.spawn()?; + // The browser holds its ends now; closing ours lets EOF reach each side. + drop(to_browser_read); + drop(from_browser_write); + + set_nonblocking(&from_browser_read)?; + set_nonblocking(&to_browser_write)?; + let reader = pipe::Receiver::from_owned_fd(from_browser_read)?; + let writer = pipe::Sender::from_owned_fd(to_browser_write)?; + Ok(Launched { + child, + reader, + writer, + }) + } + + /// Stops the browser's whole process group. + pub fn stop_group(pid: u32) { + if let Ok(pid) = i32::try_from(pid) { + // SAFETY: plain signal delivery to a group this daemon created. + unsafe { + libc::killpg(pid, libc::SIGTERM); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn given_an_override_should_use_it_without_searching() { + assert_eq!( + find_browser(Some("/custom/chrome"), None), + Some(PathBuf::from("/custom/chrome")) + ); + } + + #[test] + fn given_a_path_should_search_it_for_chromium_names() { + let list = candidates(Some("/a/bin")); + assert!(list.contains(&PathBuf::from("/a/bin/google-chrome"))); + assert!(list.contains(&PathBuf::from("/a/bin/chromium"))); + } + + #[test] + fn given_root_should_disable_the_sandbox_and_always_use_the_pipe() { + let profile = Path::new("/p"); + let as_user = args(profile, false); + assert!(as_user.contains(&"--remote-debugging-pipe".to_string())); + assert!(as_user.contains(&"--user-data-dir=/p".to_string())); + assert!( + !as_user + .iter() + .any(|a| a.starts_with("--remote-debugging-port")) + ); + assert!(!as_user.contains(&"--no-sandbox".to_string())); + assert!(args(profile, true).contains(&"--no-sandbox".to_string())); + } + + #[test] + fn given_a_project_root_should_name_a_stable_distinct_profile() { + let a = profile_key("/home/me/app"); + assert_eq!(a, profile_key("/home/me/app")); + assert!(a.starts_with("app-")); + assert_ne!(a, profile_key("/home/other/app")); + assert!(profile_key("/").starts_with('-')); + } +} diff --git a/crates/pu-engine/src/browser/mod.rs b/crates/pu-engine/src/browser/mod.rs new file mode 100644 index 00000000..a36525b1 --- /dev/null +++ b/crates/pu-engine/src/browser/mod.rs @@ -0,0 +1,1354 @@ +//! The daemon's browser (`docs/product/browser.md`). +//! +//! Each project gets its own headless Chromium, started on first use with a +//! persistent profile under `~/.pu/browser/profiles/`, so logins survive +//! restarts. Agents drive it with `Request::Browser`; browser panes watch and +//! drive it over `Request::BrowserAttach`. Both go through the machine's +//! daemon connection, so a pane works the same for a local or a remote project. + +pub mod cdp; +pub mod keys; +pub mod launch; +pub mod snapshot; +pub mod tab; + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Weak}; +use std::time::Duration; + +use base64::Engine as _; +use indexmap::IndexMap; +pub use pu_core::protocol::modifiers; +use pu_core::protocol::{ + BrowserDriver, BrowserHistory, BrowserInputEvent, BrowserKeyAction, BrowserMouseAction, + BrowserMouseButton, BrowserOp, Response, +}; +use serde_json::{Value, json}; +use tokio::sync::Mutex; + +use cdp::{Cdp, CdpError, CdpEvent}; +use tab::{Tab, Viewport}; + +/// How long `open`, `navigate` and history moves wait for the page to load. +const LOAD_TIMEOUT: Duration = Duration::from_secs(15); +const DEFAULT_WAIT: Duration = Duration::from_secs(10); +const MAX_WAIT: Duration = Duration::from_secs(120); + +/// Who sent an op. Ops from a viewer's attach stream are the person at the pane. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Caller { + Agent, + Viewer, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BrowserError { + pub code: &'static str, + pub message: String, +} + +impl BrowserError { + fn new(code: &'static str, message: impl Into<String>) -> Self { + Self { + code, + message: message.into(), + } + } + + pub fn into_response(self) -> Response { + Response::Error { + code: self.code.into(), + message: self.message, + } + } +} + +impl From<CdpError> for BrowserError { + fn from(error: CdpError) -> Self { + match error { + CdpError::Closed => Self::new( + "BROWSER_CLOSED", + "the browser exited; open a tab to restart it", + ), + CdpError::Timeout(method) => Self::new( + "BROWSER_TIMEOUT", + format!("the browser did not answer {method} in time"), + ), + CdpError::Protocol { method, message } => { + Self::new("BROWSER_ERROR", format!("{method}: {message}")) + } + } + } +} + +type Result<T> = std::result::Result<T, BrowserError>; + +/// One project's running browser. +pub struct Instance { + cdp: Arc<Cdp>, + pid: Option<u32>, + _child: std::sync::Mutex<Option<tokio::process::Child>>, + /// Open tabs, least recently used first: the last is the default tab. + tabs: std::sync::Mutex<IndexMap<String, Arc<Tab>>>, + /// The `about:blank` tab Chromium starts with, closed once a real tab exists. + initial_targets: std::sync::Mutex<Vec<String>>, + screenshots: PathBuf, +} + +impl Drop for Instance { + fn drop(&mut self) { + for tab in self.tabs.lock().unwrap_or_else(|e| e.into_inner()).values() { + tab.mark_closed(); + } + #[cfg(unix)] + if let Some(pid) = self.pid { + launch::unix::stop_group(pid); + } + } +} + +impl Instance { + fn tab_list(&self) -> Vec<Arc<Tab>> { + self.tabs + .lock() + .unwrap_or_else(|e| e.into_inner()) + .values() + .cloned() + .collect() + } + + fn tab_for_session(&self, session_id: &str) -> Option<Arc<Tab>> { + self.tabs + .lock() + .unwrap_or_else(|e| e.into_inner()) + .values() + .find(|t| t.session_id == session_id) + .cloned() + } + + /// The named tab, or the most recently used one; either becomes the most recent. + fn resolve(&self, tab_id: Option<&str>) -> Result<Arc<Tab>> { + let mut tabs = self.tabs.lock().unwrap_or_else(|e| e.into_inner()); + let id = match tab_id { + Some(id) => id.to_string(), + None => tabs.keys().last().cloned().ok_or_else(|| { + BrowserError::new( + "BROWSER_NO_TAB", + "no open tab; open one with `pu browser open <url>`", + ) + })?, + }; + let tab = tabs + .shift_remove(&id) + .ok_or_else(|| BrowserError::new("BROWSER_TAB_NOT_FOUND", format!("no tab {id}")))?; + tabs.insert(id, tab.clone()); + Ok(tab) + } + + fn remove_tab(&self, target_id: &str) -> Option<Arc<Tab>> { + let tab = self + .tabs + .lock() + .unwrap_or_else(|e| e.into_inner()) + .shift_remove(target_id); + if let Some(tab) = &tab { + tab.mark_closed(); + } + tab + } + + fn is_empty(&self) -> bool { + self.tabs + .lock() + .unwrap_or_else(|e| e.into_inner()) + .is_empty() + } + + async fn create_tab(self: &Arc<Self>) -> Result<Arc<Tab>> { + let created = self + .cdp + .call(None, "Target.createTarget", json!({ "url": "about:blank" })) + .await?; + let target_id = created + .get("targetId") + .and_then(Value::as_str) + .ok_or_else(|| { + BrowserError::new("BROWSER_ERROR", "Target.createTarget returned no target") + })? + .to_string(); + let tab = self.adopt(&target_id).await?; + // Chromium's own startup tab is not one of ours. + let initial: Vec<String> = std::mem::take( + &mut *self + .initial_targets + .lock() + .unwrap_or_else(|e| e.into_inner()), + ); + for target in initial { + self.cdp + .send(None, "Target.closeTarget", json!({ "targetId": target })); + } + Ok(tab) + } + + /// Attaches to a page target and registers it as a tab. + async fn adopt(self: &Arc<Self>, target_id: &str) -> Result<Arc<Tab>> { + let attached = self + .cdp + .call( + None, + "Target.attachToTarget", + json!({ "targetId": target_id, "flatten": true }), + ) + .await?; + let session_id = attached + .get("sessionId") + .and_then(Value::as_str) + .ok_or_else(|| { + BrowserError::new("BROWSER_ERROR", "Target.attachToTarget returned no session") + })? + .to_string(); + let (width, height) = launch::default_size(); + let tab = Arc::new(Tab::new( + target_id.to_string(), + session_id.clone(), + Viewport { + width, + height, + scale: 1.0, + }, + )); + // Registered before enabling domains, so their first events are routed. + self.tabs + .lock() + .unwrap_or_else(|e| e.into_inner()) + .insert(target_id.to_string(), tab.clone()); + let session = Some(session_id.as_str()); + for domain in [ + "Page.enable", + "Runtime.enable", + "DOM.enable", + "Accessibility.enable", + ] { + self.cdp.call(session, domain, json!({})).await?; + } + apply_viewport(&self.cdp, &tab).await?; + Ok(tab) + } + + fn on_event(self: &Arc<Self>, event: &CdpEvent) { + if let Some(session_id) = &event.session_id { + if let Some(tab) = self.tab_for_session(session_id) + && tab.on_event(event, &self.cdp) + { + let cdp = self.cdp.clone(); + tokio::spawn(async move { refresh_history(&cdp, &tab).await }); + } + return; + } + let info = event.params.get("targetInfo"); + match event.method.as_str() { + "Target.targetInfoChanged" => { + let Some(info) = info else { return }; + let Some(id) = info.get("targetId").and_then(Value::as_str) else { + return; + }; + let tab = self + .tabs + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get(id) + .cloned(); + if let Some(tab) = tab { + tab.set_page( + info.get("url").and_then(Value::as_str), + info.get("title").and_then(Value::as_str), + ); + } + } + "Target.targetCreated" => { + // A page opened by another (window.open, target=_blank) is a new tab. + let Some(info) = info else { return }; + let is_popup = info.get("type").and_then(Value::as_str) == Some("page") + && info.get("openerId").and_then(Value::as_str).is_some(); + let Some(id) = info.get("targetId").and_then(Value::as_str) else { + return; + }; + if is_popup { + let instance = self.clone(); + let id = id.to_string(); + tokio::spawn(async move { + if let Err(e) = instance.adopt(&id).await { + tracing::debug!(target = id, "could not adopt popup: {}", e.message); + } + }); + } + } + "Target.targetDestroyed" | "Target.detachedFromTarget" => { + let id = event + .params + .get("targetId") + .and_then(Value::as_str) + .map(str::to_string) + .or_else(|| { + let session = event.params.get("sessionId").and_then(Value::as_str)?; + self.tab_for_session(session).map(|t| t.target_id.clone()) + }); + if let Some(id) = id { + self.remove_tab(&id); + } + } + _ => {} + } + } +} + +async fn apply_viewport(cdp: &Cdp, tab: &Tab) -> Result<()> { + let viewport = tab.viewport(); + cdp.call( + Some(&tab.session_id), + "Emulation.setDeviceMetricsOverride", + json!({ + "width": viewport.width, + "height": viewport.height, + "deviceScaleFactor": viewport.scale, + "mobile": false, + }), + ) + .await?; + Ok(()) +} + +async fn refresh_history(cdp: &Cdp, tab: &Tab) { + let Ok(history) = cdp + .call( + Some(&tab.session_id), + "Page.getNavigationHistory", + json!({}), + ) + .await + else { + return; + }; + let index = history + .get("currentIndex") + .and_then(Value::as_i64) + .unwrap_or(0); + let count = history + .get("entries") + .and_then(Value::as_array) + .map_or(0, |e| e.len() as i64); + tab.set_history(index > 0, index + 1 < count); +} + +/// The browsers of every project on this daemon. +pub struct BrowserManager { + instances: Mutex<HashMap<String, Arc<Instance>>>, + base_dir: Option<PathBuf>, +} + +impl Default for BrowserManager { + fn default() -> Self { + Self::new( + pu_core::paths::global_pu_dir() + .ok() + .map(|d| d.join("browser")), + ) + } +} + +impl BrowserManager { + /// `base_dir` holds profiles, screenshots and the browser log (`~/.pu/browser`). + pub fn new(base_dir: Option<PathBuf>) -> Self { + Self { + instances: Mutex::new(HashMap::new()), + base_dir, + } + } + + /// Stops every project's browser. + pub async fn shutdown(&self) { + self.instances.lock().await.clear(); + } + + async fn existing(&self, root: &str) -> Option<Arc<Instance>> { + let mut instances = self.instances.lock().await; + match instances.get(root) { + Some(instance) if instance.cdp.is_alive() => Some(instance.clone()), + Some(_) => { + instances.remove(root); + None + } + None => None, + } + } + + async fn running(&self, root: &str) -> Result<Arc<Instance>> { + self.existing(root).await.ok_or_else(|| { + BrowserError::new( + "BROWSER_NO_TAB", + "no open tab; open one with `pu browser open <url>`", + ) + }) + } + + async fn get_or_launch(&self, root: &str) -> Result<Arc<Instance>> { + let mut instances = self.instances.lock().await; + if let Some(instance) = instances.get(root).filter(|i| i.cdp.is_alive()) { + return Ok(instance.clone()); + } + let instance = self.launch(root).await?; + instances.insert(root.to_string(), instance.clone()); + Ok(instance) + } + + #[cfg(not(unix))] + async fn launch(&self, _root: &str) -> Result<Arc<Instance>> { + Err(BrowserError::new( + "BROWSER_UNSUPPORTED", + "the browser runs on macOS and Linux daemons; open the project from a Mac or Linux machine", + )) + } + + #[cfg(unix)] + async fn launch(&self, root: &str) -> Result<Arc<Instance>> { + let path_var = std::env::var("PATH").ok(); + let override_path = std::env::var(launch::BROWSER_ENV).ok(); + let executable = launch::find_browser(override_path.as_deref(), path_var.as_deref()) + .ok_or_else(|| { + BrowserError::new( + "BROWSER_NOT_FOUND", + format!( + "no Chrome, Chromium or Edge found on this machine; install one or set {} to its executable", + launch::BROWSER_ENV + ), + ) + })?; + let base = self.base_dir.clone().ok_or_else(|| { + BrowserError::new("BROWSER_ERROR", "no home directory for browser profiles") + })?; + let profile = base.join("profiles").join(launch::profile_key(root)); + let screenshots = base.join("screenshots"); + for dir in [&profile, &screenshots] { + create_private_dir(dir).map_err(|e| { + BrowserError::new("BROWSER_ERROR", format!("{}: {e}", dir.display())) + })?; + } + // A daemon that was killed can leave the profile's singleton lock behind; + // with it Chromium hands off to a browser that no longer exists and exits. + for lock in ["SingletonLock", "SingletonSocket", "SingletonCookie"] { + let _ = std::fs::remove_file(profile.join(lock)); + } + let as_root = nix::unistd::geteuid().is_root(); + let args = launch::args(&profile, as_root); + let log = base.join("chromium.log"); + let launched = launch::unix::spawn(&executable, &args, Some(&log)).map_err(|e| { + BrowserError::new( + "BROWSER_LAUNCH_FAILED", + format!("could not start {}: {e}", executable.display()), + ) + })?; + let pid = launched.child.id(); + let cdp = Cdp::start(launched.reader, launched.writer); + let events = cdp.subscribe(); + cdp.call( + None, + "Target.setDiscoverTargets", + json!({ "discover": true }), + ) + .await + .map_err(|e| { + BrowserError::new( + "BROWSER_LAUNCH_FAILED", + format!( + "{} started but did not answer ({e}); see {}", + executable.display(), + log.display() + ), + ) + })?; + let targets = cdp.call(None, "Target.getTargets", json!({})).await?; + let initial = targets + .get("targetInfos") + .and_then(Value::as_array) + .map(|infos| { + infos + .iter() + .filter(|i| i.get("type").and_then(Value::as_str) == Some("page")) + .filter_map(|i| { + i.get("targetId") + .and_then(Value::as_str) + .map(str::to_string) + }) + .collect() + }) + .unwrap_or_default(); + tracing::info!(project_root = root, pid, browser = %executable.display(), "browser started"); + let instance = Arc::new(Instance { + cdp: cdp.clone(), + pid, + _child: std::sync::Mutex::new(Some(launched.child)), + tabs: std::sync::Mutex::new(IndexMap::new()), + initial_targets: std::sync::Mutex::new(initial), + screenshots, + }); + tokio::spawn(pump(Arc::downgrade(&instance), cdp, events)); + Ok(instance) + } + + /// The tab a new attach stream will show. Never starts the browser. + pub async fn attach(&self, root: &str, tab_id: Option<&str>) -> Result<(Arc<Cdp>, Arc<Tab>)> { + let instance = self.running(root).await?; + let tab = instance.resolve(tab_id)?; + Ok((instance.cdp.clone(), tab)) + } + + pub async fn handle(&self, root: &str, op: BrowserOp, caller: Caller) -> Response { + match self.run(root, op, caller).await { + Ok(response) => response, + Err(error) => error.into_response(), + } + } + + async fn run(&self, root: &str, op: BrowserOp, caller: Caller) -> Result<Response> { + match op { + BrowserOp::List => { + let tabs = match self.existing(root).await { + Some(instance) => instance.tab_list().iter().map(|t| t.info()).collect(), + None => Vec::new(), + }; + return Ok(Response::BrowserTabs { tabs }); + } + BrowserOp::Open { url } => { + let instance = self.get_or_launch(root).await?; + let tab = instance.create_tab().await?; + if let Some(url) = url.filter(|u| !u.trim().is_empty()) { + navigate(&instance.cdp, &tab, &url).await?; + } + return Ok(Response::BrowserTab { tab: tab.info() }); + } + BrowserOp::Close { tab_id } => { + let instance = self.running(root).await?; + let tab = instance.resolve(tab_id.as_deref())?; + let _ = instance + .cdp + .call( + None, + "Target.closeTarget", + json!({ "targetId": tab.target_id }), + ) + .await; + instance.remove_tab(&tab.target_id); + if instance.is_empty() { + self.instances.lock().await.remove(root); + } + return Ok(Response::Ok); + } + _ => {} + } + + let instance = self.running(root).await?; + let tab = instance.resolve(op.tab_id())?; + if op.acts_on_page() && caller == Caller::Agent && tab.driver() == BrowserDriver::Human { + return Err(BrowserError::new( + "BROWSER_HUMAN_DRIVING", + "a person is driving this tab; wait for them to hand it back", + )); + } + let cdp = &instance.cdp; + let session = Some(tab.session_id.as_str()); + match op { + BrowserOp::Open { .. } | BrowserOp::List | BrowserOp::Close { .. } => unreachable!(), + BrowserOp::Navigate { url, .. } => { + navigate(cdp, &tab, &url).await?; + Ok(Response::BrowserTab { tab: tab.info() }) + } + BrowserOp::History { direction, .. } => { + history(cdp, &tab, direction).await?; + Ok(Response::BrowserTab { tab: tab.info() }) + } + BrowserOp::Snapshot { .. } => { + let tree = cdp + .call(session, "Accessibility.getFullAXTree", json!({})) + .await?; + let nodes = tree + .get("nodes") + .and_then(Value::as_array) + .cloned() + .unwrap_or_default(); + let snapshot = snapshot::format(&nodes); + tab.store_refs(snapshot.refs); + Ok(Response::BrowserSnapshot { + tab: tab.info(), + tree: snapshot.tree, + }) + } + BrowserOp::Click { element, .. } => { + let backend = element_ref(&tab, &element)?; + let (x, y) = element_center(cdp, &tab, backend).await?; + click(cdp, &tab, x, y).await?; + Ok(Response::Ok) + } + BrowserOp::Type { + element, + text, + submit, + .. + } => { + if let Some(element) = element { + let backend = element_ref(&tab, &element)?; + focus_and_select(cdp, &tab, backend).await?; + } + cdp.call(session, "Input.insertText", json!({ "text": text })) + .await?; + if submit { + press(cdp, &tab, "Enter").await?; + } + Ok(Response::Ok) + } + BrowserOp::Press { key, .. } => { + press(cdp, &tab, &key).await?; + Ok(Response::Ok) + } + BrowserOp::Scroll { dx, dy, .. } => { + let viewport = tab.viewport(); + cdp.call( + session, + "Input.dispatchMouseEvent", + json!({ + "type": "mouseWheel", + "x": f64::from(viewport.width) / 2.0, + "y": f64::from(viewport.height) / 2.0, + "deltaX": dx, + "deltaY": dy, + }), + ) + .await?; + Ok(Response::Ok) + } + BrowserOp::Screenshot { + path, full_page, .. + } => { + let path = screenshot(cdp, &tab, &instance.screenshots, path, full_page).await?; + Ok(Response::BrowserScreenshot { + tab_id: tab.target_id.clone(), + path, + }) + } + BrowserOp::Console { clear, .. } => Ok(Response::BrowserConsole { + tab_id: tab.target_id.clone(), + entries: tab.console(clear), + }), + BrowserOp::Eval { expression, .. } => { + let value = evaluate(cdp, &tab, &expression).await?; + Ok(Response::BrowserEvalResult { + tab_id: tab.target_id.clone(), + value, + }) + } + BrowserOp::Wait { + text, timeout_ms, .. + } => { + let timeout = timeout_ms + .map(Duration::from_millis) + .unwrap_or(DEFAULT_WAIT) + .min(MAX_WAIT); + wait(cdp, &tab, text.as_deref(), timeout).await?; + Ok(Response::BrowserTab { tab: tab.info() }) + } + BrowserOp::Control { driver, .. } => { + tab.set_driver(driver); + Ok(Response::BrowserTab { tab: tab.info() }) + } + BrowserOp::Input { event, .. } => { + dispatch_input(cdp, &tab, event); + Ok(Response::Ok) + } + BrowserOp::Resize { + width, + height, + scale, + .. + } => { + let viewport = Viewport { + width: width.clamp(200, 4000), + height: height.clamp(150, 4000), + scale: if scale.is_finite() { + scale.clamp(1.0, 3.0) + } else { + 1.0 + }, + }; + if viewport != tab.viewport() { + tab.set_viewport(viewport); + apply_viewport(cdp, &tab).await?; + if tab.has_viewers() { + // New frame bounds take effect on a fresh screencast. + cdp.send(session, "Page.stopScreencast", json!({})); + tab.start_screencast(cdp); + } + } + Ok(Response::Ok) + } + BrowserOp::FrameAck { .. } => Err(BrowserError::new( + "ATTACH_REQUIRED", + "frame_ack is only meaningful on a browser_attach stream", + )), + } + } +} + +async fn pump( + instance: Weak<Instance>, + cdp: Arc<Cdp>, + mut events: tokio::sync::broadcast::Receiver<Arc<CdpEvent>>, +) { + loop { + tokio::select! { + event = events.recv() => match event { + Ok(event) => { + let Some(instance) = instance.upgrade() else { return }; + instance.on_event(&event); + } + Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => { + tracing::debug!("browser event pump lagged {n} events"); + } + Err(tokio::sync::broadcast::error::RecvError::Closed) => break, + }, + _ = cdp.closed() => break, + } + } + // The browser is gone: every viewer of its tabs must learn it. + if let Some(instance) = instance.upgrade() { + tracing::info!(pid = instance.pid, "browser exited"); + for tab in instance.tab_list() { + tab.mark_closed(); + } + } +} + +fn create_private_dir(dir: &Path) -> std::io::Result<()> { + std::fs::create_dir_all(dir)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?; + } + Ok(()) +} + +/// Adds a scheme to a bare address: local hosts get `http://`, others `https://`. +pub fn normalize_url(url: &str) -> String { + let url = url.trim(); + if url.contains("://") + || [ + "about:", + "data:", + "file:", + "javascript:", + "chrome:", + "blob:", + ] + .iter() + .any(|scheme| url.starts_with(scheme)) + { + return url.to_string(); + } + let host = url.split(['/', '?', '#']).next().unwrap_or(""); + let bare_host = host.rsplit_once(':').map_or(host, |(h, _)| h); + let local = bare_host == "localhost" + || bare_host.ends_with(".localhost") + || bare_host.ends_with(".local") + || bare_host == "[::1]" + || bare_host.parse::<std::net::Ipv4Addr>().is_ok() + || (host.contains(':') && !bare_host.contains('.')); + if local { + format!("http://{url}") + } else { + format!("https://{url}") + } +} + +/// Waits for the tab's main frame to finish loading, given a subscription +/// taken before the navigation started. +async fn wait_for_load( + events: &mut tokio::sync::broadcast::Receiver<Arc<CdpEvent>>, + tab: &Tab, + timeout: Duration, +) { + let deadline = tokio::time::Instant::now() + timeout; + loop { + match tokio::time::timeout_at(deadline, events.recv()).await { + Err(_) => return, // a slow page is still usable; report what it shows now + Ok(Err(tokio::sync::broadcast::error::RecvError::Lagged(_))) => continue, + Ok(Err(_)) => return, + Ok(Ok(event)) => { + if event.session_id.as_deref() != Some(tab.session_id.as_str()) { + continue; + } + let main = event.params.get("frameId").and_then(Value::as_str) + == Some(tab.target_id.as_str()); + if event.method == "Page.loadEventFired" + || (event.method == "Page.frameStoppedLoading" && main) + { + return; + } + } + } + } +} + +async fn navigate(cdp: &Cdp, tab: &Tab, url: &str) -> Result<()> { + let url = normalize_url(url); + let mut events = cdp.subscribe(); + let result = cdp + .call( + Some(&tab.session_id), + "Page.navigate", + json!({ "url": url }), + ) + .await?; + if let Some(error) = result.get("errorText").and_then(Value::as_str) { + return Err(BrowserError::new( + "BROWSER_NAVIGATION_FAILED", + format!("could not load {url}: {error}"), + )); + } + // A same-document navigation (a #fragment) has no loader and no load event. + if result.get("loaderId").is_some() { + wait_for_load(&mut events, tab, LOAD_TIMEOUT).await; + } + tab.set_page(Some(&url), None); + refresh_history(cdp, tab).await; + // `set_page` above may race the browser's own URL report; the browser wins. + if let Ok(info) = cdp + .call( + None, + "Target.getTargetInfo", + json!({ "targetId": tab.target_id }), + ) + .await + && let Some(info) = info.get("targetInfo") + { + tab.set_page( + info.get("url").and_then(Value::as_str), + info.get("title").and_then(Value::as_str), + ); + } + Ok(()) +} + +async fn history(cdp: &Cdp, tab: &Tab, direction: BrowserHistory) -> Result<()> { + let session = Some(tab.session_id.as_str()); + let mut events = cdp.subscribe(); + match direction { + BrowserHistory::Reload => { + cdp.call(session, "Page.reload", json!({})).await?; + } + BrowserHistory::Back | BrowserHistory::Forward => { + let history = cdp + .call(session, "Page.getNavigationHistory", json!({})) + .await?; + let index = history + .get("currentIndex") + .and_then(Value::as_i64) + .unwrap_or(0); + let target = if direction == BrowserHistory::Back { + index - 1 + } else { + index + 1 + }; + let entry = history + .get("entries") + .and_then(Value::as_array) + .and_then(|entries| usize::try_from(target).ok().and_then(|i| entries.get(i))) + .and_then(|e| e.get("id")) + .cloned(); + let Some(entry_id) = entry else { + return Ok(()); // nothing to go back or forward to + }; + cdp.call( + session, + "Page.navigateToHistoryEntry", + json!({ "entryId": entry_id }), + ) + .await?; + } + } + wait_for_load(&mut events, tab, LOAD_TIMEOUT).await; + refresh_history(cdp, tab).await; + Ok(()) +} + +fn element_ref(tab: &Tab, element: &str) -> Result<i64> { + tab.resolve_ref(element).ok_or_else(|| { + BrowserError::new( + "BROWSER_REF_NOT_FOUND", + format!("no element {element} in the latest snapshot; take a new snapshot"), + ) + }) +} + +async fn element_center(cdp: &Cdp, tab: &Tab, backend: i64) -> Result<(f64, f64)> { + let session = Some(tab.session_id.as_str()); + // Best effort: an element in a fixed header cannot scroll and needs not. + let _ = cdp + .call( + session, + "DOM.scrollIntoViewIfNeeded", + json!({ "backendNodeId": backend }), + ) + .await; + let quads = cdp + .call( + session, + "DOM.getContentQuads", + json!({ "backendNodeId": backend }), + ) + .await?; + let quad = quads + .get("quads") + .and_then(Value::as_array) + .and_then(|q| q.first()) + .and_then(Value::as_array) + .filter(|q| q.len() == 8) + .ok_or_else(|| { + BrowserError::new( + "BROWSER_NOT_VISIBLE", + "the element has no visible box (hidden, or not rendered)", + ) + })?; + let coords: Vec<f64> = quad.iter().filter_map(Value::as_f64).collect(); + let x = (coords[0] + coords[2] + coords[4] + coords[6]) / 4.0; + let y = (coords[1] + coords[3] + coords[5] + coords[7]) / 4.0; + Ok((x, y)) +} + +async fn click(cdp: &Cdp, tab: &Tab, x: f64, y: f64) -> Result<()> { + let session = Some(tab.session_id.as_str()); + for (kind, buttons) in [("mouseMoved", 0), ("mousePressed", 1), ("mouseReleased", 0)] { + let button = if kind == "mouseMoved" { "none" } else { "left" }; + cdp.call( + session, + "Input.dispatchMouseEvent", + json!({ "type": kind, "x": x, "y": y, "button": button, "buttons": buttons, "clickCount": 1 }), + ) + .await?; + } + Ok(()) +} + +/// Focuses an element and selects its contents, so typed text replaces them. +async fn focus_and_select(cdp: &Cdp, tab: &Tab, backend: i64) -> Result<()> { + let session = Some(tab.session_id.as_str()); + let resolved = cdp + .call( + session, + "DOM.resolveNode", + json!({ "backendNodeId": backend }), + ) + .await?; + let object_id = resolved + .get("object") + .and_then(|o| o.get("objectId")) + .and_then(Value::as_str) + .ok_or_else(|| { + BrowserError::new( + "BROWSER_REF_NOT_FOUND", + "the element is gone; take a new snapshot", + ) + })?; + cdp.call( + session, + "Runtime.callFunctionOn", + json!({ + "objectId": object_id, + "functionDeclaration": "function() { this.scrollIntoView({block: 'center', inline: 'center'}); this.focus(); if (typeof this.select === 'function') { this.select(); } else if (this.isContentEditable) { const r = document.createRange(); r.selectNodeContents(this); const s = getSelection(); s.removeAllRanges(); s.addRange(r); } }", + }), + ) + .await?; + Ok(()) +} + +/// Presses a key or chord such as `Enter`, `Shift+Tab` or `Control+a`. +async fn press(cdp: &Cdp, tab: &Tab, chord: &str) -> Result<()> { + let session = Some(tab.session_id.as_str()); + let (mods, key) = parse_chord(chord); + let info = keys::lookup(&key); + cdp.call( + session, + "Input.dispatchKeyEvent", + keys::key_event(true, &info, mods), + ) + .await?; + cdp.call( + session, + "Input.dispatchKeyEvent", + keys::key_event(false, &info, mods), + ) + .await?; + Ok(()) +} + +/// Splits `Control+Shift+a` into modifier bits and the key. +pub fn parse_chord(chord: &str) -> (u32, String) { + let chord = chord.trim(); + // `+` alone (or a trailing `++`) is the plus key itself. + let (prefix, key) = match chord.strip_suffix("++") { + Some(prefix) => (prefix, "+"), + None => match chord.rsplit_once('+') { + Some((prefix, key)) if !key.is_empty() => (prefix, key), + _ => ("", chord), + }, + }; + let mut mods = 0; + for part in prefix.split('+').filter(|p| !p.is_empty()) { + mods |= match part.to_ascii_lowercase().as_str() { + "alt" | "option" => modifiers::ALT, + "ctrl" | "control" => modifiers::CTRL, + "meta" | "cmd" | "command" | "super" => modifiers::META, + "shift" => modifiers::SHIFT, + _ => 0, + }; + } + (mods, key.to_string()) +} + +async fn screenshot( + cdp: &Cdp, + tab: &Tab, + dir: &Path, + path: Option<String>, + full_page: bool, +) -> Result<String> { + let path = match path { + Some(path) => { + let path = PathBuf::from(path); + if !path.is_absolute() { + return Err(BrowserError::new( + "BROWSER_INVALID_PATH", + "a screenshot path must be absolute on the daemon's machine", + )); + } + path + } + None => { + let stamp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis()) + .unwrap_or(0); + let short: String = tab.target_id.chars().take(8).collect(); + dir.join(format!("{short}-{stamp}.png")) + } + }; + let result = cdp + .call( + Some(&tab.session_id), + "Page.captureScreenshot", + json!({ "format": "png", "captureBeyondViewport": full_page }), + ) + .await?; + let data = result.get("data").and_then(Value::as_str).ok_or_else(|| { + BrowserError::new("BROWSER_ERROR", "Page.captureScreenshot returned no image") + })?; + let bytes = base64::engine::general_purpose::STANDARD + .decode(data) + .map_err(|e| BrowserError::new("BROWSER_ERROR", format!("bad screenshot data: {e}")))?; + let write_path = path.clone(); + tokio::task::spawn_blocking(move || { + if let Some(parent) = write_path.parent() { + std::fs::create_dir_all(parent)?; + } + std::fs::write(&write_path, bytes) + }) + .await + .map_err(|e| BrowserError::new("BROWSER_ERROR", e.to_string()))? + .map_err(|e| BrowserError::new("BROWSER_INVALID_PATH", format!("{}: {e}", path.display())))?; + Ok(path.to_string_lossy().into_owned()) +} + +async fn evaluate(cdp: &Cdp, tab: &Tab, expression: &str) -> Result<Value> { + let result = cdp + .call( + Some(&tab.session_id), + "Runtime.evaluate", + json!({ + "expression": expression, + "returnByValue": true, + "awaitPromise": true, + "userGesture": true, + }), + ) + .await?; + if let Some(details) = result.get("exceptionDetails") { + let text = details + .get("exception") + .and_then(|e| e.get("description")) + .and_then(Value::as_str) + .or_else(|| details.get("text").and_then(Value::as_str)) + .unwrap_or("evaluation failed"); + return Err(BrowserError::new("BROWSER_EVAL_FAILED", text)); + } + let object = result.get("result").cloned().unwrap_or(Value::Null); + Ok(match object.get("value") { + Some(value) => value.clone(), + None => object + .get("description") + .or_else(|| object.get("type")) + .cloned() + .unwrap_or(Value::Null), + }) +} + +async fn wait(cdp: &Cdp, tab: &Tab, text: Option<&str>, timeout: Duration) -> Result<()> { + let deadline = tokio::time::Instant::now() + timeout; + match text { + Some(text) => { + let expression = format!( + "!!(document.body && document.body.innerText.includes({}))", + serde_json::to_string(text).unwrap_or_default() + ); + loop { + if evaluate(cdp, tab, &expression).await? == Value::Bool(true) { + return Ok(()); + } + if tokio::time::Instant::now() >= deadline { + return Err(BrowserError::new( + "BROWSER_TIMEOUT", + format!( + "\"{text}\" did not appear within {} ms", + timeout.as_millis() + ), + )); + } + tokio::time::sleep(Duration::from_millis(250)).await; + } + } + None => { + let mut info = tab.subscribe_info(); + let loaded = tokio::time::timeout_at(deadline, info.wait_for(|i| !i.loading)).await; + match loaded { + Ok(_) => Ok(()), + Err(_) => Err(BrowserError::new( + "BROWSER_TIMEOUT", + format!( + "the page was still loading after {} ms", + timeout.as_millis() + ), + )), + } + } + } +} + +fn mouse_button(button: BrowserMouseButton) -> &'static str { + match button { + BrowserMouseButton::None => "none", + BrowserMouseButton::Left => "left", + BrowserMouseButton::Middle => "middle", + BrowserMouseButton::Right => "right", + } +} + +/// Chromium's `buttons` bitmask for a button held during a move. +fn buttons_mask(button: BrowserMouseButton) -> u32 { + match button { + BrowserMouseButton::None => 0, + BrowserMouseButton::Left => 1, + BrowserMouseButton::Right => 2, + BrowserMouseButton::Middle => 4, + } +} + +/// The DevTools command for one viewer input event. +pub fn input_command(event: &BrowserInputEvent) -> (&'static str, Value) { + match event { + BrowserInputEvent::Mouse { + action, + x, + y, + button, + click_count, + modifiers, + } => { + let kind = match action { + BrowserMouseAction::Down => "mousePressed", + BrowserMouseAction::Up => "mouseReleased", + BrowserMouseAction::Move => "mouseMoved", + }; + let buttons = match action { + BrowserMouseAction::Up => 0, + _ => buttons_mask(*button), + }; + ( + "Input.dispatchMouseEvent", + json!({ + "type": kind, + "x": x, + "y": y, + "button": mouse_button(*button), + "buttons": buttons, + "clickCount": if *action == BrowserMouseAction::Move { 0 } else { (*click_count).max(1) }, + "modifiers": modifiers, + }), + ) + } + BrowserInputEvent::Wheel { + x, + y, + dx, + dy, + modifiers, + } => ( + "Input.dispatchMouseEvent", + json!({ "type": "mouseWheel", "x": x, "y": y, "deltaX": dx, "deltaY": dy, "modifiers": modifiers }), + ), + BrowserInputEvent::Key { + action, + key, + code, + text, + modifiers, + } => { + let mut info = keys::lookup(key); + if let Some(code) = code.as_ref().filter(|c| !c.is_empty()) { + info.code = code.clone(); + } + if text.is_some() { + info.text = text.clone().filter(|t| !t.is_empty()); + } + ( + "Input.dispatchKeyEvent", + keys::key_event(*action == BrowserKeyAction::Down, &info, *modifiers), + ) + } + BrowserInputEvent::Text { text } => ("Input.insertText", json!({ "text": text })), + } +} + +fn dispatch_input(cdp: &Cdp, tab: &Tab, event: BrowserInputEvent) { + let (method, params) = input_command(&event); + cdp.send(Some(&tab.session_id), method, params); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn given_bare_addresses_should_pick_a_scheme() { + assert_eq!(normalize_url("localhost:3000"), "http://localhost:3000"); + assert_eq!(normalize_url("127.0.0.1:8080/x"), "http://127.0.0.1:8080/x"); + assert_eq!(normalize_url("devbox:5173"), "http://devbox:5173"); + assert_eq!(normalize_url("app.localhost"), "http://app.localhost"); + assert_eq!( + normalize_url("example.com/docs"), + "https://example.com/docs" + ); + assert_eq!(normalize_url(" https://a.b "), "https://a.b"); + assert_eq!(normalize_url("about:blank"), "about:blank"); + assert_eq!(normalize_url("file:///tmp/a.html"), "file:///tmp/a.html"); + } + + #[test] + fn given_chords_should_split_modifiers_from_the_key() { + assert_eq!(parse_chord("Enter"), (0, "Enter".into())); + assert_eq!( + parse_chord("Control+Shift+a"), + (modifiers::CTRL | modifiers::SHIFT, "a".into()) + ); + assert_eq!(parse_chord("Cmd+L"), (modifiers::META, "L".into())); + assert_eq!(parse_chord("+"), (0, "+".into())); + assert_eq!(parse_chord("Shift++"), (modifiers::SHIFT, "+".into())); + } + + #[test] + fn given_viewer_mouse_events_should_map_to_devtools_mouse_events() { + let (method, params) = input_command(&BrowserInputEvent::Mouse { + action: BrowserMouseAction::Down, + x: 10.0, + y: 20.0, + button: BrowserMouseButton::Left, + click_count: 2, + modifiers: modifiers::SHIFT, + }); + assert_eq!(method, "Input.dispatchMouseEvent"); + assert_eq!(params["type"], "mousePressed"); + assert_eq!(params["button"], "left"); + assert_eq!(params["buttons"], 1); + assert_eq!(params["clickCount"], 2); + assert_eq!(params["modifiers"], modifiers::SHIFT); + + let (_, drag) = input_command(&BrowserInputEvent::Mouse { + action: BrowserMouseAction::Move, + x: 11.0, + y: 21.0, + button: BrowserMouseButton::Left, + click_count: 0, + modifiers: 0, + }); + assert_eq!( + (drag["type"].as_str(), drag["buttons"].as_u64()), + (Some("mouseMoved"), Some(1)) + ); + + let (_, up) = input_command(&BrowserInputEvent::Mouse { + action: BrowserMouseAction::Up, + x: 11.0, + y: 21.0, + button: BrowserMouseButton::Left, + click_count: 1, + modifiers: 0, + }); + assert_eq!(up["buttons"], 0); + } + + #[test] + fn given_viewer_keys_and_text_should_map_to_key_events_and_inserted_text() { + let (method, params) = input_command(&BrowserInputEvent::Key { + action: BrowserKeyAction::Down, + key: "Enter".into(), + code: None, + text: None, + modifiers: 0, + }); + assert_eq!(method, "Input.dispatchKeyEvent"); + assert_eq!(params["windowsVirtualKeyCode"], 13); + let (method, params) = input_command(&BrowserInputEvent::Text { + text: "héllo".into(), + }); + assert_eq!( + (method, params["text"].as_str()), + ("Input.insertText", Some("héllo")) + ); + let (_, wheel) = input_command(&BrowserInputEvent::Wheel { + x: 1.0, + y: 2.0, + dx: 0.0, + dy: 120.0, + modifiers: 0, + }); + assert_eq!( + (wheel["type"].as_str(), wheel["deltaY"].as_f64()), + (Some("mouseWheel"), Some(120.0)) + ); + } + + #[tokio::test] + async fn given_no_browser_should_list_no_tabs_and_refuse_tab_ops_without_launching() { + let manager = BrowserManager::new(None); + assert!(matches!( + manager.handle("/p", BrowserOp::List, Caller::Agent).await, + Response::BrowserTabs { tabs } if tabs.is_empty() + )); + match manager + .handle("/p", BrowserOp::Snapshot { tab_id: None }, Caller::Agent) + .await + { + Response::Error { code, .. } => assert_eq!(code, "BROWSER_NO_TAB"), + other => panic!("unexpected {other:?}"), + } + assert!(manager.attach("/p", None).await.is_err()); + } +} diff --git a/crates/pu-engine/src/browser/snapshot.rs b/crates/pu-engine/src/browser/snapshot.rs new file mode 100644 index 00000000..6f6bb4df --- /dev/null +++ b/crates/pu-engine/src/browser/snapshot.rs @@ -0,0 +1,318 @@ +//! Turns Chromium's accessibility tree into the outline agents read. +//! +//! Each meaningful node becomes one indented line, `- role "name" [state]`. +//! Interactive elements get a `[ref=eN]` that maps to the node's backend DOM +//! id, so `click e3` and `type e5 …` can find them again. Ignored and purely +//! structural nodes (`generic`, `none`) are flattened into their parent. + +use std::collections::HashMap; + +use serde_json::Value; + +/// Agents read the outline as text; past this the page is cut off with a note. +const MAX_LINES: usize = 3000; +const MAX_NAME: usize = 200; + +const INTERACTIVE: &[&str] = &[ + "button", + "checkbox", + "combobox", + "link", + "listbox", + "menuitem", + "menuitemcheckbox", + "menuitemradio", + "option", + "radio", + "searchbox", + "slider", + "spinbutton", + "switch", + "tab", + "textbox", + "treeitem", +]; + +const FLATTENED: &[&str] = &[ + "none", + "generic", + "presentation", + "InlineTextBox", + "LineBreak", + "LayoutTableCell", + "LayoutTableRow", + "LayoutTable", +]; + +#[derive(Debug, Default)] +pub struct Snapshot { + pub tree: String, + /// `eN` → backend DOM node id. + pub refs: HashMap<String, i64>, +} + +pub fn format(nodes: &[Value]) -> Snapshot { + let by_id: HashMap<&str, &Value> = nodes + .iter() + .filter_map(|n| Some((n.get("nodeId")?.as_str()?, n))) + .collect(); + let root = nodes + .iter() + .find(|n| n.get("parentId").is_none()) + .or_else(|| nodes.first()); + let mut out = Writer { + by_id, + snapshot: Snapshot::default(), + lines: 0, + truncated: false, + }; + if let Some(root) = root { + out.visit(root, 0, None); + } + if out.truncated { + out.snapshot + .tree + .push_str("- … (outline truncated; scroll or use eval to read more)\n"); + } + out.snapshot +} + +struct Writer<'a> { + by_id: HashMap<&'a str, &'a Value>, + snapshot: Snapshot, + lines: usize, + truncated: bool, +} + +impl<'a> Writer<'a> { + fn visit(&mut self, node: &'a Value, depth: usize, parent_name: Option<&str>) { + if self.truncated { + return; + } + let role = ax_str(node, "role"); + let name = ax_str(node, "name"); + let ignored = node.get("ignored").and_then(Value::as_bool) == Some(true); + + let printed = !ignored && self.line(node, role, name, depth, parent_name); + let child_depth = if printed { depth + 1 } else { depth }; + let name_for_children = if printed { Some(name) } else { parent_name }; + + let Some(children) = node.get("childIds").and_then(Value::as_array) else { + return; + }; + for child in children { + let Some(child) = child.as_str().and_then(|id| self.by_id.get(id)).copied() else { + continue; + }; + self.visit(child, child_depth, name_for_children); + } + } + + /// Writes the node's line, returning whether it printed one. + fn line( + &mut self, + node: &Value, + role: &str, + name: &str, + depth: usize, + parent_name: Option<&str>, + ) -> bool { + let name = name.trim(); + if role.is_empty() || (FLATTENED.contains(&role) && name.is_empty()) { + return false; + } + if role == "InlineTextBox" { + return false; + } + let (role, name) = match role { + "StaticText" => { + // Text repeating its parent's accessible name adds nothing. + if name.is_empty() || parent_name.is_some_and(|p| p.trim() == name) { + return false; + } + ("text", name) + } + "RootWebArea" | "WebArea" => ("document", name), + other => (other, name), + }; + if self.lines >= MAX_LINES { + self.truncated = true; + return false; + } + self.lines += 1; + + let mut line = format!("{}- {role}", " ".repeat(depth)); + if !name.is_empty() { + line.push_str(&format!(" \"{}\"", clip(name))); + } + let value = ax_str(node, "value").trim(); + if !value.is_empty() { + line.push_str(&format!(" value=\"{}\"", clip(value))); + } + for state in states(node) { + line.push_str(&format!(" [{state}]")); + } + if INTERACTIVE.contains(&role) + && let Some(backend) = node.get("backendDOMNodeId").and_then(Value::as_i64) + { + let reference = format!("e{}", self.snapshot.refs.len() + 1); + line.push_str(&format!(" [ref={reference}]")); + self.snapshot.refs.insert(reference, backend); + } + line.push('\n'); + self.snapshot.tree.push_str(&line); + true + } +} + +fn ax_str<'v>(node: &'v Value, key: &str) -> &'v str { + node.get(key) + .and_then(|v| v.get("value")) + .and_then(Value::as_str) + .unwrap_or("") +} + +fn states(node: &Value) -> Vec<String> { + let Some(properties) = node.get("properties").and_then(Value::as_array) else { + return Vec::new(); + }; + let mut out = Vec::new(); + for property in properties { + let name = property.get("name").and_then(Value::as_str).unwrap_or(""); + let value = property.get("value").and_then(|v| v.get("value")); + match (name, value) { + ("focused" | "disabled" | "required" | "selected", Some(Value::Bool(true))) => { + out.push(name.to_string()) + } + ("checked" | "pressed", Some(Value::String(v))) if v == "true" || v == "mixed" => out + .push(if v == "mixed" { + format!("{name}=mixed") + } else { + name.to_string() + }), + ("checked" | "pressed", Some(Value::Bool(true))) => out.push(name.to_string()), + ("expanded", Some(Value::Bool(b))) => out.push(format!("expanded={b}")), + ("level", Some(Value::Number(n))) => out.push(format!("level={n}")), + _ => {} + } + } + out +} + +fn clip(text: &str) -> String { + let single: String = text + .chars() + .map(|c| if c.is_control() { ' ' } else { c }) + .collect(); + let escaped = single.replace('"', "\\\""); + if escaped.chars().count() <= MAX_NAME { + escaped + } else { + let cut: String = escaped.chars().take(MAX_NAME).collect(); + format!("{cut}…") + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn node(id: &str, parent: Option<&str>, role: &str, name: &str, children: &[&str]) -> Value { + let mut n = json!({ + "nodeId": id, + "ignored": false, + "role": {"type": "role", "value": role}, + "name": {"type": "computedString", "value": name}, + "childIds": children, + "backendDOMNodeId": id.parse::<i64>().unwrap() + 100, + }); + if let Some(parent) = parent { + n["parentId"] = json!(parent); + } + n + } + + #[test] + fn given_a_page_should_outline_it_with_refs_on_interactive_elements() { + let nodes = vec![ + node("1", None, "RootWebArea", "Login", &["2"]), + node("2", Some("1"), "generic", "", &["3", "4", "6"]), + node("3", Some("2"), "heading", "Sign in", &[]), + node("4", Some("2"), "textbox", "Email", &["5"]), + node("5", Some("4"), "StaticText", "Email", &[]), + node("6", Some("2"), "button", "Continue", &[]), + ]; + let snapshot = format(&nodes); + assert_eq!( + snapshot.tree, + "- document \"Login\"\n - heading \"Sign in\"\n - textbox \"Email\" [ref=e1]\n - button \"Continue\" [ref=e2]\n" + ); + assert_eq!(snapshot.refs.get("e1"), Some(&104)); + assert_eq!(snapshot.refs.get("e2"), Some(&106)); + } + + #[test] + fn given_ignored_nodes_should_keep_their_children_at_the_parent_depth() { + let mut ignored = node("2", Some("1"), "div", "", &["3"]); + ignored["ignored"] = json!(true); + let nodes = vec![ + node("1", None, "RootWebArea", "", &["2"]), + ignored, + node("3", Some("2"), "link", "Docs", &[]), + ]; + assert_eq!( + format(&nodes).tree, + "- document\n - link \"Docs\" [ref=e1]\n" + ); + } + + #[test] + fn given_values_and_states_should_show_them() { + let mut field = node("2", Some("1"), "textbox", "Query", &[]); + field["value"] = json!({"type": "string", "value": "rust"}); + field["properties"] = json!([ + {"name": "focused", "value": {"type": "boolean", "value": true}}, + {"name": "required", "value": {"type": "boolean", "value": false}} + ]); + let mut check = node("3", Some("1"), "checkbox", "Remember", &[]); + check["properties"] = + json!([{"name": "checked", "value": {"type": "tristate", "value": "true"}}]); + let mut heading = node("4", Some("1"), "heading", "Title", &[]); + heading["properties"] = + json!([{"name": "level", "value": {"type": "integer", "value": 2}}]); + let nodes = vec![ + node("1", None, "RootWebArea", "", &["2", "3", "4"]), + field, + check, + heading, + ]; + assert_eq!( + format(&nodes).tree, + "- document\n - textbox \"Query\" value=\"rust\" [focused] [ref=e1]\n - checkbox \"Remember\" [checked] [ref=e2]\n - heading \"Title\" [level=2]\n" + ); + } + + #[test] + fn given_long_or_quoted_names_should_escape_and_clip_them() { + let long = "x".repeat(300); + let nodes = vec![ + node("1", None, "RootWebArea", "", &["2", "3"]), + node("2", Some("1"), "StaticText", "say \"hi\"\nnow", &[]), + node("3", Some("1"), "StaticText", &long, &[]), + ]; + let tree = format(&nodes).tree; + assert!(tree.contains("- text \"say \\\"hi\\\" now\"\n"), "{tree}"); + assert!( + tree.contains(&format!("\"{}…\"", "x".repeat(MAX_NAME))), + "{tree}" + ); + } + + #[test] + fn given_no_nodes_should_return_an_empty_outline() { + let snapshot = format(&[]); + assert!(snapshot.tree.is_empty()); + assert!(snapshot.refs.is_empty()); + } +} diff --git a/crates/pu-engine/src/browser/tab.rs b/crates/pu-engine/src/browser/tab.rs new file mode 100644 index 00000000..9ab77e3a --- /dev/null +++ b/crates/pu-engine/src/browser/tab.rs @@ -0,0 +1,529 @@ +//! One browser tab: its state as clients see it, its latest screencast frame, +//! its console, and the refs from its latest snapshot. + +use std::collections::{HashMap, VecDeque}; +use std::sync::Arc; +use std::sync::Mutex; +use std::sync::atomic::{AtomicU64, Ordering}; + +use pu_core::protocol::{BrowserConsoleEntry, BrowserDriver, BrowserTabInfo}; +use serde_json::{Value, json}; +use tokio::sync::watch; + +use super::cdp::{Cdp, CdpEvent}; + +/// Console entries kept per tab; older ones are dropped. +const CONSOLE_LIMIT: usize = 500; +/// JPEG quality for screencast frames: sharp enough for text, small enough for SSH. +const SCREENCAST_QUALITY: u32 = 70; +/// Frames are capped at this many device pixels on a side. +const MAX_FRAME_EDGE: f64 = 3840.0; + +/// One screencast frame, shared by every viewer of the tab. +#[derive(Debug)] +pub struct Frame { + pub seq: u64, + /// Base64 JPEG, as Chromium sent it. + pub data: String, + /// The CSS viewport the frame shows. + pub width: f64, + pub height: f64, +} + +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Viewport { + pub width: u32, + pub height: u32, + pub scale: f64, +} + +pub struct Tab { + pub target_id: String, + pub session_id: String, + info: watch::Sender<BrowserTabInfo>, + frame: watch::Sender<Option<Arc<Frame>>>, + closed: watch::Sender<bool>, + frame_seq: AtomicU64, + viewers: Mutex<usize>, + viewport: Mutex<Viewport>, + console: Mutex<VecDeque<BrowserConsoleEntry>>, + refs: Mutex<HashMap<String, i64>>, +} + +impl Tab { + pub fn new(target_id: String, session_id: String, viewport: Viewport) -> Self { + let info = BrowserTabInfo { + tab_id: target_id.clone(), + url: "about:blank".into(), + title: String::new(), + loading: false, + driver: BrowserDriver::Agent, + can_go_back: false, + can_go_forward: false, + width: viewport.width, + height: viewport.height, + }; + Self { + target_id, + session_id, + info: watch::Sender::new(info), + frame: watch::Sender::new(None), + closed: watch::Sender::new(false), + frame_seq: AtomicU64::new(0), + viewers: Mutex::new(0), + viewport: Mutex::new(viewport), + console: Mutex::default(), + refs: Mutex::default(), + } + } + + pub fn info(&self) -> BrowserTabInfo { + self.info.borrow().clone() + } + + pub fn subscribe_info(&self) -> watch::Receiver<BrowserTabInfo> { + self.info.subscribe() + } + + pub fn subscribe_frames(&self) -> watch::Receiver<Option<Arc<Frame>>> { + self.frame.subscribe() + } + + pub fn subscribe_closed(&self) -> watch::Receiver<bool> { + self.closed.subscribe() + } + + pub fn is_closed(&self) -> bool { + *self.closed.borrow() + } + + pub fn mark_closed(&self) { + self.closed.send_replace(true); + } + + pub fn driver(&self) -> BrowserDriver { + self.info.borrow().driver + } + + pub fn set_driver(&self, driver: BrowserDriver) { + self.info.send_if_modified(|info| { + let changed = info.driver != driver; + info.driver = driver; + changed + }); + } + + pub fn viewport(&self) -> Viewport { + *self.viewport.lock().unwrap_or_else(|e| e.into_inner()) + } + + pub fn set_viewport(&self, viewport: Viewport) { + *self.viewport.lock().unwrap_or_else(|e| e.into_inner()) = viewport; + self.info.send_if_modified(|info| { + let changed = info.width != viewport.width || info.height != viewport.height; + info.width = viewport.width; + info.height = viewport.height; + changed + }); + } + + pub fn set_history(&self, can_go_back: bool, can_go_forward: bool) { + self.info.send_if_modified(|info| { + let changed = info.can_go_back != can_go_back || info.can_go_forward != can_go_forward; + info.can_go_back = can_go_back; + info.can_go_forward = can_go_forward; + changed + }); + } + + pub fn set_page(&self, url: Option<&str>, title: Option<&str>) { + self.info.send_if_modified(|info| { + let mut changed = false; + if let Some(url) = url.filter(|u| *u != info.url) { + info.url = url.to_string(); + changed = true; + } + if let Some(title) = title.filter(|t| *t != info.title) { + info.title = title.to_string(); + changed = true; + } + changed + }); + } + + fn set_loading(&self, loading: bool) { + self.info.send_if_modified(|info| { + let changed = info.loading != loading; + info.loading = loading; + changed + }); + } + + pub fn store_refs(&self, refs: HashMap<String, i64>) { + *self.refs.lock().unwrap_or_else(|e| e.into_inner()) = refs; + } + + pub fn resolve_ref(&self, reference: &str) -> Option<i64> { + let reference = reference + .trim() + .trim_matches(|c| c == '[' || c == ']') + .trim_start_matches('@'); + let reference = reference.strip_prefix("ref=").unwrap_or(reference); + self.refs + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get(reference) + .copied() + } + + pub fn console(&self, clear: bool) -> Vec<BrowserConsoleEntry> { + let mut console = self.console.lock().unwrap_or_else(|e| e.into_inner()); + let entries = console.iter().cloned().collect(); + if clear { + console.clear(); + } + entries + } + + fn log(&self, level: &str, text: String) { + let mut console = self.console.lock().unwrap_or_else(|e| e.into_inner()); + if console.len() >= CONSOLE_LIMIT { + console.pop_front(); + } + console.push_back(BrowserConsoleEntry { + level: level.to_string(), + text, + timestamp_ms: now_ms(), + }); + } + + // --- Viewers --- + + /// Counts a viewer in, starting the screencast for the first. + pub fn add_viewer(&self, cdp: &Cdp) { + let mut viewers = self.viewers.lock().unwrap_or_else(|e| e.into_inner()); + *viewers += 1; + if *viewers == 1 { + self.start_screencast(cdp); + } + } + + /// Counts a viewer out, stopping the screencast after the last. + pub fn remove_viewer(&self, cdp: &Cdp) { + let mut viewers = self.viewers.lock().unwrap_or_else(|e| e.into_inner()); + *viewers = viewers.saturating_sub(1); + if *viewers == 0 { + cdp.send(Some(&self.session_id), "Page.stopScreencast", json!({})); + } + } + + pub fn has_viewers(&self) -> bool { + *self.viewers.lock().unwrap_or_else(|e| e.into_inner()) > 0 + } + + pub fn start_screencast(&self, cdp: &Cdp) { + let viewport = self.viewport(); + let max_width = (f64::from(viewport.width) * viewport.scale).min(MAX_FRAME_EDGE); + let max_height = (f64::from(viewport.height) * viewport.scale).min(MAX_FRAME_EDGE); + cdp.send( + Some(&self.session_id), + "Page.startScreencast", + json!({ + "format": "jpeg", + "quality": SCREENCAST_QUALITY, + "maxWidth": max_width.round() as u32, + "maxHeight": max_height.round() as u32, + "everyNthFrame": 1, + }), + ); + } + + // --- Events --- + + /// Applies one event for this tab's session. Returns true when the main + /// frame finished loading, so the caller can refresh history. + pub fn on_event(&self, event: &CdpEvent, cdp: &Cdp) -> bool { + let params = &event.params; + match event.method.as_str() { + "Page.screencastFrame" => { + // Ack at once: the newest frame always replaces an undrawn one, + // so a slow viewer only skips frames and never stalls the page. + if let Some(id) = params.get("sessionId") { + cdp.send( + Some(&self.session_id), + "Page.screencastFrameAck", + json!({ "sessionId": id }), + ); + } + let Some(data) = params.get("data").and_then(Value::as_str) else { + return false; + }; + let metadata = params.get("metadata"); + let viewport = self.viewport(); + let dim = |key: &str, fallback: u32| { + metadata + .and_then(|m| m.get(key)) + .and_then(Value::as_f64) + .unwrap_or(f64::from(fallback)) + }; + let seq = self.frame_seq.fetch_add(1, Ordering::Relaxed) + 1; + self.frame.send_replace(Some(Arc::new(Frame { + seq, + data: data.to_string(), + width: dim("deviceWidth", viewport.width), + height: dim("deviceHeight", viewport.height), + }))); + } + "Page.frameStartedLoading" if self.is_main_frame(params) => self.set_loading(true), + "Page.frameStoppedLoading" if self.is_main_frame(params) => { + self.set_loading(false); + return true; + } + "Page.frameNavigated" => { + let frame = params.get("frame"); + let top = frame.is_some_and(|f| f.get("parentId").is_none()); + if top { + let url = frame.and_then(|f| f.get("url")).and_then(Value::as_str); + self.set_page(url, None); + // Old refs point into the previous document. + self.store_refs(HashMap::new()); + } + } + "Page.navigatedWithinDocument" if self.is_main_frame(params) => { + self.set_page(params.get("url").and_then(Value::as_str), None); + return true; + } + "Runtime.consoleAPICalled" => { + let level = params.get("type").and_then(Value::as_str).unwrap_or("log"); + let level = if level == "warn" { "warning" } else { level }; + let text = params + .get("args") + .and_then(Value::as_array) + .map(|args| { + args.iter() + .map(remote_object_text) + .collect::<Vec<_>>() + .join(" ") + }) + .unwrap_or_default(); + self.log(level, text); + } + "Runtime.exceptionThrown" => { + let details = params.get("exceptionDetails"); + let text = details + .and_then(|d| d.get("exception")) + .and_then(|e| e.get("description")) + .and_then(Value::as_str) + .or_else(|| details.and_then(|d| d.get("text")).and_then(Value::as_str)) + .unwrap_or("uncaught exception"); + self.log("exception", text.to_string()); + } + "Page.javascriptDialogOpening" => { + // A dialog blocks the page for everyone; accept it and record it, + // so agents and viewers are never stuck behind one. + let kind = params + .get("type") + .and_then(Value::as_str) + .unwrap_or("alert"); + let message = params.get("message").and_then(Value::as_str).unwrap_or(""); + self.log("dialog", format!("{kind}: {message} (accepted)")); + cdp.send( + Some(&self.session_id), + "Page.handleJavaScriptDialog", + json!({ "accept": true }), + ); + } + _ => {} + } + false + } + + fn is_main_frame(&self, params: &Value) -> bool { + params.get("frameId").and_then(Value::as_str) == Some(self.target_id.as_str()) + } +} + +/// A console argument as text: strings bare, other values as Chromium describes them. +fn remote_object_text(object: &Value) -> String { + match object.get("value") { + Some(Value::String(s)) => s.clone(), + Some(Value::Null) | None => object + .get("description") + .and_then(Value::as_str) + .or_else(|| object.get("type").and_then(Value::as_str)) + .unwrap_or("") + .to_string(), + Some(other) => other.to_string(), + } +} + +fn now_ms() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0) +} + +#[cfg(test)] +mod tests { + use super::*; + use tokio::io::duplex; + + fn tab() -> Tab { + Tab::new( + "T1".into(), + "S1".into(), + Viewport { + width: 800, + height: 600, + scale: 2.0, + }, + ) + } + + fn event(method: &str, params: Value) -> CdpEvent { + CdpEvent { + method: method.into(), + params, + session_id: Some("S1".into()), + } + } + + fn cdp() -> Arc<Cdp> { + let (client_out, _browser_in) = duplex(1 << 16); + let (_browser_out, client_in) = duplex(1 << 16); + Cdp::start(client_in, client_out) + } + + #[tokio::test] + async fn given_screencast_frames_should_keep_only_the_newest_numbered_in_order() { + let tab = tab(); + let cdp = cdp(); + let frames = tab.subscribe_frames(); + for data in ["AAA", "BBB"] { + tab.on_event( + &event( + "Page.screencastFrame", + json!({"data": data, "sessionId": 1, "metadata": {"deviceWidth": 800, "deviceHeight": 600}}), + ), + &cdp, + ); + } + let latest = frames.borrow().clone().unwrap(); + assert_eq!((latest.seq, latest.data.as_str()), (2, "BBB")); + assert_eq!((latest.width, latest.height), (800.0, 600.0)); + } + + #[tokio::test] + async fn given_main_frame_loading_events_should_track_loading_and_report_the_stop() { + let tab = tab(); + let cdp = cdp(); + assert!(!tab.on_event( + &event("Page.frameStartedLoading", json!({"frameId": "T1"})), + &cdp + )); + assert!(tab.info().loading); + // A subframe never changes the tab's loading state. + assert!(!tab.on_event( + &event("Page.frameStoppedLoading", json!({"frameId": "X"})), + &cdp + )); + assert!(tab.info().loading); + assert!(tab.on_event( + &event("Page.frameStoppedLoading", json!({"frameId": "T1"})), + &cdp + )); + assert!(!tab.info().loading); + } + + #[tokio::test] + async fn given_a_top_level_navigation_should_update_the_url_and_drop_old_refs() { + let tab = tab(); + let cdp = cdp(); + tab.store_refs(HashMap::from([("e1".to_string(), 5)])); + tab.on_event( + &event( + "Page.frameNavigated", + json!({"frame": {"id": "F2", "parentId": "T1", "url": "http://ad"}}), + ), + &cdp, + ); + assert_eq!(tab.resolve_ref("e1"), Some(5)); + tab.on_event( + &event( + "Page.frameNavigated", + json!({"frame": {"id": "T1", "url": "http://localhost:3000/"}}), + ), + &cdp, + ); + assert_eq!(tab.info().url, "http://localhost:3000/"); + assert_eq!(tab.resolve_ref("e1"), None); + } + + #[tokio::test] + async fn given_console_messages_exceptions_and_dialogs_should_record_them() { + let tab = tab(); + let cdp = cdp(); + tab.on_event( + &event( + "Runtime.consoleAPICalled", + json!({"type": "warn", "args": [{"type": "string", "value": "low"}, {"type": "number", "value": 3}]}), + ), + &cdp, + ); + tab.on_event( + &event( + "Runtime.exceptionThrown", + json!({"exceptionDetails": {"text": "Uncaught", "exception": {"description": "TypeError: x is undefined"}}}), + ), + &cdp, + ); + tab.on_event( + &event( + "Page.javascriptDialogOpening", + json!({"type": "confirm", "message": "Leave?"}), + ), + &cdp, + ); + let entries = tab.console(true); + let summary: Vec<(&str, &str)> = entries + .iter() + .map(|e| (e.level.as_str(), e.text.as_str())) + .collect(); + assert_eq!( + summary, + vec![ + ("warning", "low 3"), + ("exception", "TypeError: x is undefined"), + ("dialog", "confirm: Leave? (accepted)"), + ] + ); + assert!(tab.console(false).is_empty()); + } + + #[test] + fn given_ref_spellings_should_resolve_the_same_element() { + let tab = tab(); + tab.store_refs(HashMap::from([("e3".to_string(), 42)])); + for spelling in ["e3", "@e3", "ref=e3", "[ref=e3]", " e3 "] { + assert_eq!(tab.resolve_ref(spelling), Some(42), "{spelling}"); + } + assert_eq!(tab.resolve_ref("e4"), None); + } + + #[test] + fn given_a_driver_or_viewport_change_should_publish_it() { + let tab = tab(); + let mut info = tab.subscribe_info(); + info.mark_unchanged(); + tab.set_driver(BrowserDriver::Human); + assert!(info.has_changed().unwrap()); + assert_eq!(info.borrow_and_update().driver, BrowserDriver::Human); + tab.set_viewport(Viewport { + width: 1024, + height: 700, + scale: 1.0, + }); + assert_eq!((tab.info().width, tab.info().height), (1024, 700)); + } +} diff --git a/crates/pu-engine/src/engine/mod.rs b/crates/pu-engine/src/engine/mod.rs index 3aca9c79..62a46ee8 100644 --- a/crates/pu-engine/src/engine/mod.rs +++ b/crates/pu-engine/src/engine/mod.rs @@ -107,6 +107,8 @@ pub struct Engine { /// must stay resumable, so their exits are not recorded as Broken; any /// other exit (including one that happened just before teardown) is. shutdown_killed: Arc<std::sync::Mutex<HashSet<u32>>>, + /// Each project's headless browser (`docs/product/browser.md`). + browsers: Arc<crate::browser::BrowserManager>, } impl Default for Engine { @@ -230,6 +232,17 @@ fn catalog_executable_available( } impl Engine { + /// Keep browser profiles and screenshots in `dir` instead of `~/.pu/browser`. + pub fn with_browser_dir(mut self, dir: std::path::PathBuf) -> Self { + self.browsers = Arc::new(crate::browser::BrowserManager::new(Some(dir))); + self + } + + /// The daemon's browsers, for the attach stream. + pub fn browsers(&self) -> &Arc<crate::browser::BrowserManager> { + &self.browsers + } + pub fn new() -> Self { Self { sizes: Mutex::new(HashMap::new()), @@ -252,6 +265,7 @@ impl Engine { registry_ready: tokio::sync::watch::Sender::new(true), resuming: Arc::new(std::sync::Mutex::new(HashSet::new())), shutdown_killed: Arc::new(std::sync::Mutex::new(HashSet::new())), + browsers: Arc::default(), } } @@ -368,6 +382,7 @@ impl Engine { /// its natural exit. #[cfg(windows)] pub async fn kill_all_sessions(&self, grace: Duration) { + self.browsers.shutdown().await; let handles: Vec<AgentHandle> = { let mut sessions = self.sessions.lock().await; sessions.drain().map(|(_, h)| h).collect() @@ -412,6 +427,7 @@ impl Engine { /// its natural exit. #[cfg(unix)] pub async fn kill_all_sessions(&self, grace: Duration) { + self.browsers.shutdown().await; let handles: Vec<AgentHandle> = { let mut sessions = self.sessions.lock().await; sessions.drain().map(|(_, h)| h).collect() @@ -668,6 +684,18 @@ impl Engine { .await } Request::Attach { agent_id, .. } => self.handle_attach(&agent_id).await, + Request::Browser { project_root, op } => { + self.browsers + .handle(&project_root, op, crate::browser::Caller::Agent) + .await + } + Request::BrowserAttach { + project_root, + tab_id, + } => match self.browsers.attach(&project_root, tab_id.as_deref()).await { + Ok((_, tab)) => Response::BrowserAttached { tab: tab.info() }, + Err(error) => error.into_response(), + }, Request::Input { agent_id, data, diff --git a/crates/pu-engine/src/ipc_server/mod.rs b/crates/pu-engine/src/ipc_server/mod.rs index d3f3b4ce..d622d6f0 100644 --- a/crates/pu-engine/src/ipc_server/mod.rs +++ b/crates/pu-engine/src/ipc_server/mod.rs @@ -42,6 +42,7 @@ enum StreamMode { Status(String), Projects, Fs { root: String, recursive: bool }, + Browser(String), } impl StreamMode { @@ -59,6 +60,7 @@ impl StreamMode { root: root.clone(), recursive: *recursive, }, + Request::BrowserAttach { project_root, .. } => Self::Browser(project_root.clone()), _ => Self::None, } } @@ -368,6 +370,19 @@ impl IpcServer { return false; } } + StreamMode::Browser(project_root) => { + if let Response::BrowserAttached { tab } = &response { + return streams::handle_browser_stream( + reader, + pending, + writer, + engine, + &project_root, + &tab.tab_id, + ) + .await; + } + } StreamMode::None => {} } diff --git a/crates/pu-engine/src/ipc_server/streams.rs b/crates/pu-engine/src/ipc_server/streams.rs index 3d65dbdc..d0989830 100644 --- a/crates/pu-engine/src/ipc_server/streams.rs +++ b/crates/pu-engine/src/ipc_server/streams.rs @@ -562,6 +562,150 @@ pub(super) async fn handle_fs_stream( tracing::debug!(root = root_str, "fs stream ended"); } +/// Viewers may have this many frames sent but not yet drawn; newer frames +/// replace undrawn ones, so a slow link drops frames instead of queueing them. +const BROWSER_FRAMES_IN_FLIGHT: usize = 2; + +/// Browser pane stream: frames and tab state out, viewer ops in. Ops on the +/// stream act as the person at the pane (`Caller::Viewer`) and default to the +/// attached tab. Input, resize and frame acks are answered only on error; +/// other ops run beside the stream, so a slow navigation never stalls frames. +/// Any line that is not a `browser` request ends the stream. +pub(super) async fn handle_browser_stream( + reader: &mut IpcReader, + partial: &mut Vec<u8>, + writer: &mut IpcWriter, + engine: &Engine, + project_root: &str, + tab_id: &str, +) -> bool { + let browsers = engine.browsers().clone(); + let (cdp, tab) = match browsers.attach(project_root, Some(tab_id)).await { + Ok(attached) => attached, + Err(_) => { + let closed = Response::BrowserTabClosed { + tab_id: tab_id.to_string(), + }; + return write_response(writer, &closed).await.is_ok(); + } + }; + tab.add_viewer(&cdp); + tracing::debug!(project_root, tab_id, "browser stream started"); + let result = browser_stream_loop(reader, partial, writer, &browsers, project_root, &tab).await; + tab.remove_viewer(&cdp); + tracing::debug!(project_root, tab_id, "browser stream ended"); + result +} + +async fn browser_stream_loop( + reader: &mut IpcReader, + partial: &mut Vec<u8>, + writer: &mut IpcWriter, + browsers: &std::sync::Arc<crate::browser::BrowserManager>, + project_root: &str, + tab: &crate::browser::tab::Tab, +) -> bool { + use crate::browser::Caller; + use pu_core::protocol::BrowserOp; + use std::collections::VecDeque; + + let mut frames = tab.subscribe_frames(); + let mut info = tab.subscribe_info(); + let mut closed = tab.subscribe_closed(); + // A frame drawn before this viewer arrived is still worth showing now. + frames.mark_changed(); + let mut in_flight: VecDeque<u64> = VecDeque::new(); + let (replies_tx, mut replies_rx) = tokio::sync::mpsc::unbounded_channel::<Response>(); + let tab_id = tab.target_id.clone(); + let closed_response = || Response::BrowserTabClosed { + tab_id: tab_id.clone(), + }; + + if *closed.borrow() { + return write_response(writer, &closed_response()).await.is_ok(); + } + + loop { + tokio::select! { + changed = frames.changed(), if in_flight.len() < BROWSER_FRAMES_IN_FLIGHT => { + if changed.is_err() { + break; + } + let frame = frames.borrow_and_update().clone(); + if let Some(frame) = frame { + let resp = Response::BrowserFrame { + tab_id: tab_id.clone(), + seq: frame.seq, + data: frame.data.clone(), + width: frame.width, + height: frame.height, + }; + if write_response(writer, &resp).await.is_err() { + return false; + } + in_flight.push_back(frame.seq); + } + } + changed = info.changed() => { + if changed.is_err() { + break; + } + let state = info.borrow_and_update().clone(); + if write_response(writer, &Response::BrowserTabState { tab: state }).await.is_err() { + return false; + } + } + changed = closed.changed() => { + if changed.is_err() || *closed.borrow() { + return write_response(writer, &closed_response()).await.is_ok(); + } + } + Some(reply) = replies_rx.recv() => { + if write_response(writer, &reply).await.is_err() { + return false; + } + } + frame = read_frame(reader, partial) => { + let line = match frame { + Ok(Frame::Line(line)) => line, + Ok(Frame::Eof) => return false, + Ok(Frame::TooLarge) => { + reject_frame_too_large(writer).await; + return false; + } + Err(_) => return false, + }; + let Some(Request::Browser { mut op, .. }) = parse_stream_request(&line) else { + break; + }; + op.default_tab(&tab_id); + if let BrowserOp::FrameAck { seq, .. } = op { + while in_flight.front().is_some_and(|sent| *sent <= seq) { + in_flight.pop_front(); + } + continue; + } + if op.is_quiet_on_stream() { + let resp = browsers.handle(project_root, op, Caller::Viewer).await; + if matches!(resp, Response::Error { .. }) + && write_response(writer, &resp).await.is_err() + { + return false; + } + continue; + } + let browsers = browsers.clone(); + let root = project_root.to_string(); + let replies = replies_tx.clone(); + tokio::spawn(async move { + let _ = replies.send(browsers.handle(&root, op, Caller::Viewer).await); + }); + } + } + } + true +} + #[cfg(test)] mod watch_tests { use super::*; diff --git a/crates/pu-engine/src/lib.rs b/crates/pu-engine/src/lib.rs index 6395a3b8..003a43ea 100644 --- a/crates/pu-engine/src/lib.rs +++ b/crates/pu-engine/src/lib.rs @@ -1,4 +1,5 @@ pub mod agent_monitor; +pub mod browser; pub mod build_cache; pub mod daemon_lifecycle; pub mod delivery; diff --git a/crates/pu-engine/tests/browser.rs b/crates/pu-engine/tests/browser.rs new file mode 100644 index 00000000..ba3ba483 --- /dev/null +++ b/crates/pu-engine/tests/browser.rs @@ -0,0 +1,462 @@ +//! Drives a real headless Chromium through the daemon socket, the way the +//! CLI (agents) and a browser pane (viewers) do. Skipped when the machine has +//! no Chrome/Chromium (set `PU_BROWSER` to point at one). +#![cfg(unix)] + +use std::time::Duration; + +use pu_core::protocol::{ + BrowserDriver, BrowserInputEvent, BrowserMouseAction, BrowserMouseButton, BrowserOp, Request, + Response, +}; +use tempfile::TempDir; +use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; +use tokio::net::TcpListener; + +const PAGE: &str = r#"<!doctype html> +<html><head><title>Fixture + +

Sign in

+ + +

+ Next page +"#; + +fn have_browser() -> bool { + let path = std::env::var("PATH").ok(); + let explicit = std::env::var("PU_BROWSER").ok(); + pu_engine::browser::launch::find_browser(explicit.as_deref(), path.as_deref()) + .is_some_and(|p| p.exists()) +} + +/// A tiny HTTP server: `/second` gets a second page, everything else `PAGE`. +async fn serve() -> String { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { + loop { + let Ok((mut socket, _)) = listener.accept().await else { + return; + }; + tokio::spawn(async move { + let mut reader = BufReader::new(&mut socket); + let mut request = String::new(); + if reader.read_line(&mut request).await.is_err() { + return; + } + loop { + let mut header = String::new(); + if reader.read_line(&mut header).await.unwrap_or(0) == 0 || header == "\r\n" { + break; + } + } + let body = if request.contains("/second") { + "Second

Second page

" + } else { + PAGE + }; + let response = format!( + "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + let _ = socket.write_all(response.as_bytes()).await; + }); + } + }); + format!("localhost:{}", addr.port()) +} + +struct Client { + reader: BufReader, + writer: pu_transport::WriteHalf, +} + +impl Client { + async fn connect(sock: &std::path::Path) -> Self { + let endpoint = pu_transport::Endpoint::for_socket(sock).unwrap(); + let stream = pu_transport::connect(&endpoint).await.unwrap(); + let (reader, writer) = stream.into_split(); + Self { + reader: BufReader::new(reader), + writer, + } + } + + async fn write(&mut self, request: &Request) { + let json = serde_json::to_string(request).unwrap(); + self.writer + .write_all(format!("{json}\n").as_bytes()) + .await + .unwrap(); + } + + async fn read(&mut self) -> Response { + let mut line = String::new(); + tokio::time::timeout(Duration::from_secs(30), self.reader.read_line(&mut line)) + .await + .expect("daemon answered in time") + .unwrap(); + serde_json::from_str(line.trim()).unwrap_or_else(|e| panic!("{e}: {line}")) + } + + async fn call(&mut self, request: &Request) -> Response { + self.write(request).await; + self.read().await + } +} + +fn browser(root: &str, op: BrowserOp) -> Request { + Request::Browser { + project_root: root.to_string(), + op, + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn given_an_agent_and_a_viewer_should_share_one_live_tab() { + if !have_browser() { + eprintln!("skipping: no Chrome/Chromium on this machine (set PU_BROWSER)"); + return; + } + let tmp = TempDir::new().unwrap(); + let sock = tmp.path().join("daemon.sock"); + let project = tmp.path().join("app"); + std::fs::create_dir_all(&project).unwrap(); + let engine = pu_engine::engine::Engine::new().with_browser_dir(tmp.path().join("browser")); + let server = pu_engine::ipc_server::IpcServer::bind(&sock, engine).unwrap(); + let engine = server.engine().clone(); + tokio::spawn(async move { server.run().await.ok() }); + let site = serve().await; + let root = pu_core::canon::canonicalize(&project) + .unwrap() + .to_string_lossy() + .into_owned(); + let mut agent = Client::connect(&sock).await; + + // Nothing runs until a tab is opened. + assert!(matches!( + agent.call(&browser(&root, BrowserOp::List)).await, + Response::BrowserTabs { tabs } if tabs.is_empty() + )); + + // An agent opens the dev server, reads it, fills the form and clicks. + let tab = match agent + .call(&browser( + &root, + BrowserOp::Open { + url: Some(site.clone()), + }, + )) + .await + { + Response::BrowserTab { tab } => tab, + other => panic!("open: {other:?}"), + }; + assert_eq!(tab.url, format!("http://{site}/")); + assert_eq!(tab.title, "Fixture"); + + let tree = match agent + .call(&browser(&root, BrowserOp::Snapshot { tab_id: None })) + .await + { + Response::BrowserSnapshot { tree, .. } => tree, + other => panic!("snapshot: {other:?}"), + }; + assert!(tree.contains("heading \"Sign in\""), "{tree}"); + let line_ref = |needle: &str| { + let line = tree + .lines() + .find(|l| l.contains(needle)) + .unwrap_or_else(|| panic!("{needle} in {tree}")); + let start = line.find("[ref=").unwrap() + 5; + line[start..line[start..].find(']').unwrap() + start].to_string() + }; + let email = line_ref("textbox \"Email\""); + let go = line_ref("button \"Continue\""); + + let typed = agent + .call(&browser( + &root, + BrowserOp::Type { + tab_id: None, + element: Some(email.clone()), + text: "ada".into(), + submit: false, + }, + )) + .await; + assert!(matches!(typed, Response::Ok), "{typed:?}"); + let clicked = agent + .call(&browser( + &root, + BrowserOp::Click { + tab_id: None, + element: go.clone(), + }, + )) + .await; + assert!(matches!(clicked, Response::Ok), "{clicked:?}"); + let waited = agent + .call(&browser( + &root, + BrowserOp::Wait { + tab_id: None, + text: Some("Hello ada".into()), + timeout_ms: Some(5000), + }, + )) + .await; + assert!(matches!(waited, Response::BrowserTab { .. }), "{waited:?}"); + + // Typing into the field again replaces its contents. + agent + .call(&browser( + &root, + BrowserOp::Type { + tab_id: None, + element: Some(email), + text: "grace".into(), + submit: false, + }, + )) + .await; + match agent + .call(&browser( + &root, + BrowserOp::Eval { + tab_id: None, + expression: "document.getElementById('email').value".into(), + }, + )) + .await + { + Response::BrowserEvalResult { value, .. } => assert_eq!(value, "grace"), + other => panic!("eval: {other:?}"), + } + + match agent + .call(&browser( + &root, + BrowserOp::Console { + tab_id: None, + clear: false, + }, + )) + .await + { + Response::BrowserConsole { entries, .. } => { + assert!(entries.iter().any(|e| e.text == "clicked 2"), "{entries:?}") + } + other => panic!("console: {other:?}"), + } + + match agent + .call(&browser( + &root, + BrowserOp::Screenshot { + tab_id: None, + path: None, + full_page: false, + }, + )) + .await + { + Response::BrowserScreenshot { path, .. } => { + let bytes = std::fs::read(&path).unwrap(); + assert_eq!(&bytes[..8], b"\x89PNG\r\n\x1a\n"); + } + other => panic!("screenshot: {other:?}"), + } + + // A viewer attaches and gets the tab, then live frames. + let mut viewer = Client::connect(&sock).await; + match viewer + .call(&Request::BrowserAttach { + project_root: root.clone(), + tab_id: Some(tab.tab_id.clone()), + }) + .await + { + Response::BrowserAttached { tab: attached } => assert_eq!(attached.tab_id, tab.tab_id), + other => panic!("attach: {other:?}"), + } + viewer + .write(&browser( + &root, + BrowserOp::Resize { + tab_id: None, + width: 640, + height: 480, + scale: 2.0, + }, + )) + .await; + let frame = loop { + match viewer.read().await { + Response::BrowserFrame { + seq, + data, + width, + height, + .. + } => break (seq, data, width, height), + Response::BrowserTabState { .. } => continue, + other => panic!("expected a frame, got {other:?}"), + } + }; + assert!(!frame.1.is_empty()); + assert!(frame.2 > 0.0 && frame.3 > 0.0); + viewer + .write(&browser( + &root, + BrowserOp::FrameAck { + tab_id: None, + seq: frame.0, + }, + )) + .await; + + // The person takes over: agent actions are refused, viewer input works. + viewer + .write(&browser( + &root, + BrowserOp::Control { + tab_id: None, + driver: BrowserDriver::Human, + }, + )) + .await; + let refused = loop { + let resp = agent + .call(&browser( + &root, + BrowserOp::Press { + tab_id: None, + key: "Tab".into(), + }, + )) + .await; + match resp { + Response::Ok => tokio::time::sleep(Duration::from_millis(50)).await, + other => break other, + } + }; + assert!( + matches!(&refused, Response::Error { code, .. } if code == "BROWSER_HUMAN_DRIVING"), + "{refused:?}" + ); + // The viewer clicks the button by its position: the click lands in the page. + agent + .call(&browser( + &root, + BrowserOp::Eval { + tab_id: None, + expression: "1".into(), + }, + )) + .await; // refused too, but reading still works: + for action in [BrowserMouseAction::Down, BrowserMouseAction::Up] { + viewer + .write(&browser( + &root, + BrowserOp::Input { + tab_id: None, + event: BrowserInputEvent::Mouse { + action, + x: 100.0, + y: 230.0, + button: BrowserMouseButton::Left, + click_count: 1, + modifiers: 0, + }, + }, + )) + .await; + } + let mut agent_reader = Client::connect(&sock).await; + let deadline = tokio::time::Instant::now() + Duration::from_secs(5); + loop { + let console = agent_reader + .call(&browser( + &root, + BrowserOp::Console { + tab_id: None, + clear: false, + }, + )) + .await; + let clicks = match console { + Response::BrowserConsole { entries, .. } => { + entries.iter().filter(|e| e.text == "clicked 2").count() + } + other => panic!("console: {other:?}"), + }; + if clicks == 2 { + break; + } + assert!( + tokio::time::Instant::now() < deadline, + "viewer click never landed" + ); + tokio::time::sleep(Duration::from_millis(100)).await; + } + + // Navigation shows in the viewer's tab state. + viewer + .write(&browser( + &root, + BrowserOp::Navigate { + tab_id: None, + url: format!("{site}/second"), + }, + )) + .await; + let deadline = tokio::time::Instant::now() + Duration::from_secs(15); + loop { + assert!( + tokio::time::Instant::now() < deadline, + "navigation never showed" + ); + match viewer.read().await { + Response::BrowserTabState { tab } if tab.title == "Second" && !tab.loading => { + assert!(tab.can_go_back, "{tab:?}"); + break; + } + Response::BrowserFrame { seq, .. } => { + viewer + .write(&browser(&root, BrowserOp::FrameAck { tab_id: None, seq })) + .await; + } + _ => {} + } + } + + // Closing the tab ends the viewer's stream and stops the browser. + let closed = agent + .call(&browser( + &root, + BrowserOp::Close { + tab_id: Some(tab.tab_id.clone()), + }, + )) + .await; + assert!(matches!(closed, Response::Ok), "{closed:?}"); + let deadline = tokio::time::Instant::now() + Duration::from_secs(5); + loop { + assert!( + tokio::time::Instant::now() < deadline, + "viewer never saw the close" + ); + if let Response::BrowserTabClosed { tab_id } = viewer.read().await { + assert_eq!(tab_id, tab.tab_id); + break; + } + } + assert!(matches!( + agent.call(&browser(&root, BrowserOp::List)).await, + Response::BrowserTabs { tabs } if tabs.is_empty() + )); + engine.kill_all_sessions(Duration::from_millis(10)).await; +} From c97430c61e54428a42f9ee1cba08ae031f3b8359 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 22:55:50 +0000 Subject: [PATCH 02/30] feat(browser): browser pane for the macOS and iPad apps; docs and agent skill A new pane tab kind shows a live tab of the project's browser over the project's daemon connection, so it works the same for remote machines. The pane has back/forward/reload, an address field and Take Control / Hand Back; it draws screencast frames, acks them after drawing, maps mouse, scroll, keys, paste and copy into page input, and keeps the page viewport at the pane's size. Pane tabs persist their browser tab and last URL, reattach after relaunch and reopen a lost tab. Empty tabs offer Open Browser, `pu browser open --show` opens a pane via the new open_browser grid command, closing a pane's last view of a tab closes the tab, and a remote agent's localhost links open in a browser pane. Adds docs/product/browser.md, the protocol reference, CLI reference, changelog, and teaches agents `pu browser` through the bundled skill. `pu browser goto /path` resolves against the current page. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ2eMMzt56iHuDqpo7z --- CHANGELOG.md | 2 + .../purepoint-macos/Models/Workspace.swift | 6 +- .../purepoint-macos/PurePointiPadApp.swift | 12 + .../Services/DaemonProtocol+Browser.swift | 189 ++++++++++ .../Services/DaemonProtocol.swift | 44 ++- .../State/BrowserSession.swift | 328 ++++++++++++++++++ .../State/WorkspaceRegistry.swift | 43 +++ .../Views/Browser/BrowserCanvas+iOS.swift | 182 ++++++++++ .../Views/Browser/BrowserCanvas.swift | 219 ++++++++++++ .../Views/Browser/BrowserPaneView.swift | 170 +++++++++ .../Views/PaneGrid/PaneCellView.swift | 30 +- .../Views/PaneGrid/PaneTabBar.swift | 4 + .../Views/PaneGrid/WorkspacePersistence.swift | 16 +- .../Views/Terminal/TerminalPaneView+iOS.swift | 1 + .../Views/Terminal/TerminalPaneView.swift | 2 + .../purepoint-macos/purepoint_macosApp.swift | 12 + .../BrowserPaneTests.swift | 135 +++++++ .../PaneTabStackTests.swift | 1 + crates/pu-cli/assets/plugin/commands/pu.md | 18 + .../pu-cli/assets/plugin/skills/pu/SKILL.md | 3 + crates/pu-engine/src/browser/mod.rs | 37 +- docs/guide/cli-reference.md | 31 ++ docs/product/browser.md | 113 ++++++ docs/product/cross-reference-matrix.md | 1 + docs/reference/ipc-api.md | 45 ++- docs/spec-system.md | 1 + 26 files changed, 1631 insertions(+), 14 deletions(-) create mode 100644 apps/purepoint-macos/purepoint-macos/Services/DaemonProtocol+Browser.swift create mode 100644 apps/purepoint-macos/purepoint-macos/State/BrowserSession.swift create mode 100644 apps/purepoint-macos/purepoint-macos/Views/Browser/BrowserCanvas+iOS.swift create mode 100644 apps/purepoint-macos/purepoint-macos/Views/Browser/BrowserCanvas.swift create mode 100644 apps/purepoint-macos/purepoint-macos/Views/Browser/BrowserPaneView.swift create mode 100644 apps/purepoint-macos/purepoint-macosTests/BrowserPaneTests.swift create mode 100644 docs/product/browser.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 572e4f75..38b47309 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ All notable changes to PurePoint are documented here. Format follows [Keep a Cha ## [Unreleased] ### Added +- A browser for agents and for you. Each project gets a headless Chrome (or Chromium, Edge or Brave) on the machine where its agents run. Agents drive it with `pu browser` (`open`, `snapshot` with `[ref=eN]` handles, `click`, `type`, `press`, `scroll`, `screenshot`, `console`, `eval`, `wait`), and you watch and use the same tab live in a new browser pane: choose Open Browser in an empty tab, or have an agent run `pu browser open --show`. Take Control stops agents' page actions until you hand the tab back. Because the browser runs on the project's machine, `localhost` means the same thing to agents and to you, and panes work for remote machines. A remote agent's `localhost` links now open in a browser pane instead of your own browser. Logins persist per project in `~/.pu/browser/profiles` on that machine. See [Browser](docs/product/browser.md). - PurePoint runs natively on Windows 11 (x64 and arm64), with no WSL. `pu-engine` and `pu` are native Windows programs: the daemon listens on a private named pipe, agents run in ConPTY terminals and are stopped as a whole process tree, `pu daemon install` starts the daemon at sign-in through your user's Run key, and `pu phone` runs Point Guard for phone pairing over Tailscale. See [PurePoint on Windows](docs/guide/windows.md). - A Windows desktop app (`PurePoint__-setup.exe`, a per-user installer that needs no administrator rights) with the macOS app's features. On first launch it installs `pu` and `pu-engine` to `%USERPROFILE%\.pu\bin`, adds that folder to your user `PATH`, installs the Claude Code plugin and supervises the daemon. The arm64 installer has not been tested on Arm hardware yet. - `scripts/install.ps1` installs the Windows CLI from PowerShell (`irm https://raw.githubusercontent.com/2witstudios/PurePoint/main/scripts/install.ps1 | iex`). Like `install.sh`, it verifies the release's minisign signature or its GitHub attestation before installing, and stops if neither can be checked unless `PU_INSTALL_SKIP_VERIFY=1` is set. @@ -13,6 +14,7 @@ All notable changes to PurePoint are documented here. Format follows [Keep a Cha - Paste an image (Cmd+V) into any agent's terminal, or drop files on a remote agent's terminal, and the macOS app uploads it to the agent's machine and types its path there, so remote agents can see screenshots. Uploads are kept in `~/.pu/attachments` on that machine for 7 days. ### Changed +- The daemon protocol is now version 15, for the new `browser` and `browser_attach` requests. Update PurePoint on every machine and restart its daemon. - The daemon protocol is now version 14, for the new `reorder_projects` request. Update PurePoint on every machine and restart its daemon. - Phones and iPads now pair with full access (agents, terminals, workspace management and Point Guard chat). Point Guard setup shows each device on one line with a single Access menu (Full access, Terminals only, View only, No access) and a Revoke button. Revoked devices are removed instead of lingering as "Revoked", and the redundant "Require re-pair" button is gone. Devices that are already paired keep their current access. - The daemon protocol is now version 12, for the new `attach_file` request. Update PurePoint on every machine and restart its daemon. diff --git a/apps/purepoint-macos/purepoint-macos/Models/Workspace.swift b/apps/purepoint-macos/purepoint-macos/Models/Workspace.swift index eab7c16d..6806d399 100644 --- a/apps/purepoint-macos/purepoint-macos/Models/Workspace.swift +++ b/apps/purepoint-macos/purepoint-macos/Models/Workspace.swift @@ -21,6 +21,10 @@ nonisolated enum SurfaceContent: Equatable, Sendable { case agent(String) /// The file navigator/editor. `path` is the absolute file to show; `nil` opens the navigator alone. case file(path: String?) + /// A tab of the project's browser, which runs on the project's machine. `tabId` is the + /// daemon's tab (`nil` until opened); `url` is the last page shown, so a tab lost to a + /// daemon or browser restart reopens where it was. + case browser(tabId: String?, url: String?) var agentId: String? { if case .agent(let id) = self { return id } @@ -192,7 +196,7 @@ nonisolated struct Workspace: Identifiable, Equatable, Sendable { if isPointGuard { return false } return !surfaces.contains { surface in switch surface.surface.content { - case .agent, .file, .pointGuard: true + case .agent, .file, .pointGuard, .browser: true case .empty: false } } diff --git a/apps/purepoint-macos/purepoint-macos/PurePointiPadApp.swift b/apps/purepoint-macos/purepoint-macos/PurePointiPadApp.swift index 3fef0361..9e5b298f 100644 --- a/apps/purepoint-macos/purepoint-macos/PurePointiPadApp.swift +++ b/apps/purepoint-macos/purepoint-macos/PurePointiPadApp.swift @@ -44,6 +44,18 @@ struct PurePointiPadApp: App { viewCache.remove(agentId: agentId) appState.projectState(forId: projectId)?.removeAndKillAgent(agentId) } + BrowserLinks.open = { [weak registry] agentId, url in + guard let registry, let workspaceId = registry.workspaceId(forAgent: agentId), + let workspace = registry.workspace(id: workspaceId) + else { return false } + let content = SurfaceContent.browser(tabId: nil, url: url.absoluteString) + return registry.newTab(workspaceId: workspaceId, leafId: workspace.focusedLeafId, content: content) != nil + } + registry.onCloseBrowserTab = { projectId, tabId in + guard let project = appState.projectState(forId: projectId) else { return } + let (client, root) = (project.client, project.projectRoot) + Task { _ = try? await client.send(.browser(projectRoot: root, op: .close(tabId: tabId))) } + } hotkeyMonitor.keyBindingState = keyBindingState hotkeyMonitor.start() CommandPalettePanel.registerPresenter() diff --git a/apps/purepoint-macos/purepoint-macos/Services/DaemonProtocol+Browser.swift b/apps/purepoint-macos/purepoint-macos/Services/DaemonProtocol+Browser.swift new file mode 100644 index 00000000..c2b3c0a6 --- /dev/null +++ b/apps/purepoint-macos/purepoint-macos/Services/DaemonProtocol+Browser.swift @@ -0,0 +1,189 @@ +import Foundation + +// Browser wire types (protocol 15): `crates/pu-core/src/protocol/browser.rs`. +// The project's headless browser runs on the daemon's machine; a browser pane +// watches one tab over a `browser_attach` stream and drives it with ops. + +/// One tab as the daemon reports it. +nonisolated struct BrowserTabInfo: Decodable, Equatable, Sendable { + let tabId: String + let url: String + let title: String + let loading: Bool + /// `agent` or `human`. + let driver: String + let canGoBack: Bool + let canGoForward: Bool + /// The page viewport in CSS pixels. + let width: Int + let height: Int + + var isHumanDriving: Bool { driver == "human" } + + enum CodingKeys: String, CodingKey { + case tabId = "tab_id" + case url, title, loading, driver + case canGoBack = "can_go_back" + case canGoForward = "can_go_forward" + case width, height + } +} + +nonisolated struct BrowserTabPayload: Decodable { + let tab: BrowserTabInfo +} + +/// One screencast frame: a base64 JPEG and the CSS viewport it shows. +nonisolated struct BrowserFramePayload: Decodable, Sendable { + let tabId: String + let seq: UInt64 + let data: String + let width: Double + let height: Double + + enum CodingKeys: String, CodingKey { + case tabId = "tab_id" + case seq, data, width, height + } +} + +nonisolated struct BrowserTabIdPayload: Decodable { + let tabId: String + + enum CodingKeys: String, CodingKey { + case tabId = "tab_id" + } +} + +nonisolated struct BrowserEvalPayload: Decodable { + let value: BrowserJSONValue? +} + +/// Just enough of a JSON value to read an eval result as text. +nonisolated enum BrowserJSONValue: Decodable, Sendable { + case string(String) + case other + + init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + if let string = try? container.decode(String.self) { + self = .string(string) + } else { + self = .other + } + } + + var string: String? { + if case .string(let s) = self { return s } + return nil + } +} + +/// Modifier bits, as Chromium numbers them. +nonisolated struct BrowserModifiers: OptionSet, Sendable { + let rawValue: Int + static let alt = BrowserModifiers(rawValue: 1) + static let control = BrowserModifiers(rawValue: 2) + static let meta = BrowserModifiers(rawValue: 4) + static let shift = BrowserModifiers(rawValue: 8) +} + +/// Input from the person at a browser pane. Coordinates are CSS pixels. +nonisolated enum BrowserInputEvent: Encodable, Equatable, Sendable { + enum MouseAction: String, Sendable { case down, up, move } + enum MouseButton: String, Sendable { case none, left, middle, right } + + case mouse(action: MouseAction, x: Double, y: Double, button: MouseButton, clickCount: Int, modifiers: Int) + case wheel(x: Double, y: Double, dx: Double, dy: Double, modifiers: Int) + case key(down: Bool, key: String, code: String?, text: String?, modifiers: Int) + case text(String) + + func encode(to encoder: Encoder) throws { + var c = encoder.container(keyedBy: DynamicCodingKey.self) + switch self { + case .mouse(let action, let x, let y, let button, let clickCount, let modifiers): + try c.encode("mouse", forKey: .key("kind")) + try c.encode(action.rawValue, forKey: .key("action")) + try c.encode(x, forKey: .key("x")) + try c.encode(y, forKey: .key("y")) + try c.encode(button.rawValue, forKey: .key("button")) + try c.encode(clickCount, forKey: .key("click_count")) + try c.encode(modifiers, forKey: .key("modifiers")) + case .wheel(let x, let y, let dx, let dy, let modifiers): + try c.encode("wheel", forKey: .key("kind")) + try c.encode(x, forKey: .key("x")) + try c.encode(y, forKey: .key("y")) + try c.encode(dx, forKey: .key("dx")) + try c.encode(dy, forKey: .key("dy")) + try c.encode(modifiers, forKey: .key("modifiers")) + case .key(let down, let key, let code, let text, let modifiers): + try c.encode("key", forKey: .key("kind")) + try c.encode(down ? "down" : "up", forKey: .key("action")) + try c.encode(key, forKey: .key("key")) + try c.encodeIfPresent(code, forKey: .key("code")) + try c.encodeIfPresent(text, forKey: .key("text")) + try c.encode(modifiers, forKey: .key("modifiers")) + case .text(let text): + try c.encode("text", forKey: .key("kind")) + try c.encode(text, forKey: .key("text")) + } + } +} + +/// The browser ops a pane sends. A `nil` tab id means the stream's tab. +nonisolated enum BrowserOp: Encodable, Equatable, Sendable { + case open(url: String?) + case close(tabId: String?) + case navigate(tabId: String?, url: String) + /// `back`, `forward` or `reload`. + case history(tabId: String?, direction: String) + /// `human` or `agent`. + case control(tabId: String?, driver: String) + case eval(tabId: String?, expression: String) + case input(tabId: String?, event: BrowserInputEvent) + case resize(tabId: String?, width: Int, height: Int, scale: Double) + case frameAck(tabId: String?, seq: UInt64) + + func encode(to encoder: Encoder) throws { + var c = encoder.container(keyedBy: DynamicCodingKey.self) + func tab(_ id: String?) throws { try c.encodeIfPresent(id, forKey: .key("tab_id")) } + switch self { + case .open(let url): + try c.encode("open", forKey: .key("action")) + try c.encodeIfPresent(url, forKey: .key("url")) + case .close(let tabId): + try c.encode("close", forKey: .key("action")) + try tab(tabId) + case .navigate(let tabId, let url): + try c.encode("navigate", forKey: .key("action")) + try tab(tabId) + try c.encode(url, forKey: .key("url")) + case .history(let tabId, let direction): + try c.encode("history", forKey: .key("action")) + try tab(tabId) + try c.encode(direction, forKey: .key("direction")) + case .control(let tabId, let driver): + try c.encode("control", forKey: .key("action")) + try tab(tabId) + try c.encode(driver, forKey: .key("driver")) + case .eval(let tabId, let expression): + try c.encode("eval", forKey: .key("action")) + try tab(tabId) + try c.encode(expression, forKey: .key("expression")) + case .input(let tabId, let event): + try c.encode("input", forKey: .key("action")) + try tab(tabId) + try c.encode(event, forKey: .key("event")) + case .resize(let tabId, let width, let height, let scale): + try c.encode("resize", forKey: .key("action")) + try tab(tabId) + try c.encode(width, forKey: .key("width")) + try c.encode(height, forKey: .key("height")) + try c.encode(scale, forKey: .key("scale")) + case .frameAck(let tabId, let seq): + try c.encode("frame_ack", forKey: .key("action")) + try tab(tabId) + try c.encode(seq, forKey: .key("seq")) + } + } +} diff --git a/apps/purepoint-macos/purepoint-macos/Services/DaemonProtocol.swift b/apps/purepoint-macos/purepoint-macos/Services/DaemonProtocol.swift index b5d77b5e..ca052e60 100644 --- a/apps/purepoint-macos/purepoint-macos/Services/DaemonProtocol.swift +++ b/apps/purepoint-macos/purepoint-macos/Services/DaemonProtocol.swift @@ -81,6 +81,8 @@ nonisolated enum GridAction: Codable, Equatable { case closeTab(leafId: Int?, tabId: Int?) case moveTab(tabId: Int, toLeaf: Int, index: Int?) case breakTab(tabId: Int?, axis: String) + /// Open a tab showing a browser tab (an id from `pu browser`), from `pu browser open --show`. + case openBrowser(leafId: Int?, browserTab: String) case getLayout private enum CodingKeys: String, CodingKey { @@ -92,6 +94,7 @@ nonisolated enum GridAction: Codable, Equatable { case index case tabId = "tab_id" case toLeaf = "to_leaf" + case browserTab = "browser_tab" } init(from decoder: Decoder) throws { @@ -129,6 +132,9 @@ nonisolated enum GridAction: Codable, Equatable { let tabId = try container.decodeIfPresent(Int.self, forKey: .tabId) let axis = try container.decodeIfPresent(String.self, forKey: .axis) ?? "v" self = .breakTab(tabId: tabId, axis: axis) + case "open_browser": + let browserTab = try container.decode(String.self, forKey: .browserTab) + self = .openBrowser(leafId: leafId, browserTab: browserTab) default: self = .getLayout } @@ -174,6 +180,10 @@ nonisolated enum GridAction: Codable, Equatable { try container.encode("break_tab", forKey: .action) try container.encodeIfPresent(tabId, forKey: .tabId) try container.encode(axis, forKey: .axis) + case .openBrowser(let leafId, let browserTab): + try container.encode("open_browser", forKey: .action) + try container.encodeIfPresent(leafId, forKey: .leafId) + try container.encode(browserTab, forKey: .browserTab) case .getLayout: try container.encode("get_layout", forKey: .action) } @@ -322,6 +332,10 @@ nonisolated enum DaemonRequest: Encodable { case subscribeGrid(projectRoot: String) case subscribeStatus(projectRoot: String) case gridCommand(projectRoot: String, command: GridCommandPayload) + /// An op on the project's browser, on the daemon's machine (protocol 15). + case browser(projectRoot: String, op: BrowserOp) + /// Watch and drive a browser tab: frames and tab state until it closes. + case browserAttach(projectRoot: String, tabId: String?) case createWorktree(projectRoot: String, name: String?, base: String? = nil) case deleteWorktree(projectRoot: String, worktreeId: String) case listTemplates(projectRoot: String) @@ -493,6 +507,14 @@ nonisolated enum DaemonRequest: Encodable { try container.encode("grid_command", forKey: .key("type")) try container.encode(projectRoot, forKey: .key("project_root")) try container.encode(command, forKey: .key("command")) + case .browser(let projectRoot, let op): + try container.encode("browser", forKey: .key("type")) + try container.encode(projectRoot, forKey: .key("project_root")) + try container.encode(op, forKey: .key("op")) + case .browserAttach(let projectRoot, let tabId): + try container.encode("browser_attach", forKey: .key("type")) + try container.encode(projectRoot, forKey: .key("project_root")) + try container.encodeIfPresent(tabId, forKey: .key("tab_id")) case .createWorktree(let projectRoot, let name, let base): try container.encode("create_worktree", forKey: .key("type")) try container.encode(projectRoot, forKey: .key("project_root")) @@ -712,6 +734,12 @@ nonisolated enum DaemonResponse: Decodable { case gridSubscribed case gridLayout(layout: Data) case gridEvent(projectRoot: String, command: GridCommandPayload) + case browserTab(BrowserTabInfo) + case browserAttached(BrowserTabInfo) + case browserTabState(BrowserTabInfo) + case browserFrame(BrowserFramePayload) + case browserTabClosed(tabId: String) + case browserEvalResult(value: String?) case statusSubscribed case statusEvent(worktrees: [WorktreeEntry], agents: [AgentStatusReport]) case createWorktreeResult(worktreeId: String) @@ -817,6 +845,18 @@ nonisolated enum DaemonResponse: Decodable { case "grid_event": let p = try GridEventPayload(from: decoder) self = .gridEvent(projectRoot: p.projectRoot, command: p.command) + case "browser_tab": + self = .browserTab(try BrowserTabPayload(from: decoder).tab) + case "browser_attached": + self = .browserAttached(try BrowserTabPayload(from: decoder).tab) + case "browser_tab_state": + self = .browserTabState(try BrowserTabPayload(from: decoder).tab) + case "browser_frame": + self = .browserFrame(try BrowserFramePayload(from: decoder)) + case "browser_tab_closed": + self = .browserTabClosed(tabId: try BrowserTabIdPayload(from: decoder).tabId) + case "browser_eval_result": + self = .browserEvalResult(value: try BrowserEvalPayload(from: decoder).value?.string) case "create_worktree_result": let p = try CreateWorktreeResultPayload(from: decoder) self = .createWorktreeResult(worktreeId: p.worktreeId) @@ -1283,7 +1323,7 @@ private nonisolated struct GridEventPayload: Decodable { // MARK: - Helpers -private nonisolated struct DynamicCodingKey: CodingKey { +nonisolated struct DynamicCodingKey: CodingKey { var stringValue: String var intValue: Int? { nil } @@ -1299,7 +1339,7 @@ private nonisolated struct DynamicCodingKey: CodingKey { nonisolated enum DaemonProtocol { /// The protocol this app speaks. A daemon reporting another version is incompatible. - static let version = 14 + static let version = 15 } nonisolated struct InventoryProjectPayload: Decodable, Sendable, Equatable { diff --git a/apps/purepoint-macos/purepoint-macos/State/BrowserSession.swift b/apps/purepoint-macos/purepoint-macos/State/BrowserSession.swift new file mode 100644 index 00000000..c2b48131 --- /dev/null +++ b/apps/purepoint-macos/purepoint-macos/State/BrowserSession.swift @@ -0,0 +1,328 @@ +import CoreGraphics +import Foundation +import ImageIO +import Observation + +/// Text helpers for browser panes. +nonisolated enum BrowserAddress { + /// A pane tab's title: the page's host (and port), or "Browser" before a page loads. + static func tabTitle(for url: String?) -> String { + guard let url, !url.isEmpty, url != "about:blank" else { return "Browser" } + guard let components = URLComponents(string: url), let host = components.host, !host.isEmpty else { + return url + } + if let port = components.port { return "\(host):\(port)" } + return host + } + + /// What the address field shows: blank for a blank page. + static func fieldText(for url: String?) -> String { + guard let url, url != "about:blank" else { return "" } + return url + } +} + +/// Where a remote terminal's loopback links go. `http://localhost:3000` printed by an agent on +/// another machine means that machine, so it opens in a browser pane of the agent's project +/// (whose browser runs there) instead of this device's browser. +@MainActor +enum BrowserLinks { + /// Opens `url` in a browser pane beside the agent's terminal; false if it could not. + static var open: ((_ agentId: String, _ url: URL) -> Bool)? + + nonisolated static func isLoopback(_ url: URL) -> Bool { + guard let scheme = url.scheme?.lowercased(), scheme == "http" || scheme == "https", + let host = url.host?.lowercased() + else { return false } + return host == "localhost" || host.hasSuffix(".localhost") || host == "127.0.0.1" || host == "0.0.0.0" + || host == "::1" || host == "[::1]" + } + + /// The terminal link handler: loopback links of a remote agent go to a browser pane. + static func handler(agentId: String, isRemote: @escaping () -> Bool, fallback: @escaping (URL) -> Void) + -> (URL) -> Void + { + { url in + if isRemote(), isLoopback(url), open?(agentId, url) == true { return } + fallback(url) + } + } +} + +/// One browser pane's live view of a tab of the project's browser. +/// +/// The browser runs on the project's daemon's machine; this holds a `browser_attach` stream to +/// that daemon (local, or a machine's over SSH), draws its frames, and sends the person's +/// input on the same stream. A pane opened without a tab opens one first. A tab that is gone +/// (the browser or daemon restarted) is reopened on its last page. +@MainActor @Observable +final class BrowserSession { + enum Phase: Equatable { + case connecting + case live + /// The tab closed (from `pu browser close`, or the browser exited). + case closed + case failed(String) + } + + private(set) var phase: Phase = .connecting + private(set) var tab: BrowserTabInfo? + private(set) var frame: CGImage? + /// The CSS viewport the current frame shows, for mapping input coordinates. + private(set) var frameSize = CGSize(width: 1280, height: 800) + /// A transient problem to show over the page (a failed navigation, a refused action). + private(set) var notice: String? + + @ObservationIgnored let projectRoot: String + @ObservationIgnored private let client: DaemonClient + @ObservationIgnored private var tabId: String? + @ObservationIgnored private var lastURL: String? + @ObservationIgnored private let onTabChange: @MainActor (String, String?) -> Void + @ObservationIgnored private var streamTask: Task? + @ObservationIgnored private let writer = BrowserStreamWriter() + @ObservationIgnored private var viewport: (width: Int, height: Int, scale: Double)? + @ObservationIgnored private var pendingCopy = false + @ObservationIgnored private var noticeTask: Task? + + init( + client: DaemonClient, projectRoot: String, tabId: String?, url: String?, + onTabChange: @escaping @MainActor (String, String?) -> Void + ) { + self.client = client + self.projectRoot = projectRoot + self.tabId = tabId + self.lastURL = url + self.onTabChange = onTabChange + } + + var isHumanDriving: Bool { tab?.isHumanDriving ?? false } + + func start() { + guard streamTask == nil else { return } + phase = .connecting + streamTask = Task { [weak self] in await self?.run() } + } + + func stop() { + streamTask?.cancel() + streamTask = nil + Task { [writer] in await writer.close() } + } + + /// Opens a fresh tab on the last page, after the tab closed. + func reopen() { + stop() + tabId = nil + start() + } + + // MARK: - Actions + + func navigate(to address: String) { + let address = address.trimmingCharacters(in: .whitespacesAndNewlines) + guard !address.isEmpty else { return } + send(.navigate(tabId: nil, url: address)) + } + + func goBack() { send(.history(tabId: nil, direction: "back")) } + func goForward() { send(.history(tabId: nil, direction: "forward")) } + func reload() { send(.history(tabId: nil, direction: "reload")) } + + /// Take the tab from agents, or hand it back to them. + func setHumanDriving(_ human: Bool) { + send(.control(tabId: nil, driver: human ? "human" : "agent")) + } + + func input(_ event: BrowserInputEvent) { send(.input(tabId: nil, event: event)) } + + /// Copy the page's selected text to the clipboard (`copy` is called with it). + func copySelection() { + pendingCopy = true + send(.eval(tabId: nil, expression: "String(getSelection ? getSelection() : '')")) + } + + @ObservationIgnored var copy: ((String) -> Void)? + + /// The pane's size in points and its pixel density; the page's viewport follows it. + func resize(width: Int, height: Int, scale: Double) { + guard width > 0, height > 0 else { return } + if let viewport, viewport.width == width, viewport.height == height, viewport.scale == scale { return } + viewport = (width, height, scale) + send(.resize(tabId: nil, width: width, height: height, scale: scale)) + } + + private func send(_ op: BrowserOp) { + Task { [writer, projectRoot] in await writer.send(.browser(projectRoot: projectRoot, op: op)) } + } + + private func show(notice text: String) { + notice = text + noticeTask?.cancel() + noticeTask = Task { [weak self] in + try? await Task.sleep(for: .seconds(4)) + guard !Task.isCancelled else { return } + self?.notice = nil + } + } + + // MARK: - Stream + + private func run() async { + var failures = 0 + while !Task.isCancelled { + do { + try await attachOnce() + return // the tab closed; the pane offers to reopen it + } catch is CancellationError { + return + } catch BrowserSessionError.daemon(let code, let message) { + // Unrecoverable without the person: say why. + phase = .failed(BrowserSession.describe(code: code, message: message)) + return + } catch { + #if os(iOS) + if await AppActivity.shared.isInBackground { + await AppActivity.shared.untilForeground() + failures = 0 + continue + } + #endif + failures += 1 + phase = failures > 3 ? .failed(error.localizedDescription) : .connecting + let delay: Duration = failures <= 3 ? .milliseconds(300) : .seconds(2) + try? await Task.sleep(for: delay) + } + } + } + + private func attachOnce() async throws { + if tabId == nil { + let opened = try await client.send(.browser(projectRoot: projectRoot, op: .open(url: lastURL))) + switch opened { + case .browserTab(let info): + adopt(info) + case .error(let code, let message): + throw BrowserSessionError.daemon(code, message) + default: + throw BrowserSessionError.unexpected + } + } + let (stream, reader) = try await client.connect() + await writer.use(stream) + defer { Task { [writer] in await writer.close(stream) } } + try await DaemonClient.write(.browserAttach(projectRoot: projectRoot, tabId: tabId), to: stream) + + let first = try await reader.readLine() + switch DaemonClient.parse(first) { + case .browserAttached(let info): + adopt(info) + case .error(let code, _) where code == "BROWSER_TAB_NOT_FOUND" || code == "BROWSER_NO_TAB": + // The tab is gone (browser or daemon restarted): open a new one on its last page. + tabId = nil + throw BrowserSessionError.retry + case .error(let code, let message): + throw BrowserSessionError.daemon(code, message) + default: + throw BrowserSessionError.unexpected + } + phase = .live + if let viewport { + await writer.send( + .browser( + projectRoot: projectRoot, + op: .resize(tabId: nil, width: viewport.width, height: viewport.height, scale: viewport.scale))) + } + + while !Task.isCancelled { + let line = try await reader.readLine() + switch DaemonClient.parse(line) { + case .browserFrame(let payload): + let image = await Task.detached(priority: .userInitiated) { BrowserSession.decode(payload.data) }.value + if let image { + frame = image + frameSize = CGSize(width: payload.width, height: payload.height) + } + // Acked once drawn: the daemon sends at most two frames ahead of the screen. + await writer.send(.browser(projectRoot: projectRoot, op: .frameAck(tabId: nil, seq: payload.seq))) + case .browserTabState(let info): + adopt(info) + case .browserTabClosed: + phase = .closed + frame = nil + return + case .browserTab(let info): + adopt(info) + case .browserEvalResult(let value): + if pendingCopy, let value, !value.isEmpty { copy?(value) } + pendingCopy = false + case .error(_, let message): + show(notice: message) + default: + break + } + } + } + + private func adopt(_ info: BrowserTabInfo) { + let changed = tab?.tabId != info.tabId || tab?.url != info.url + tab = info + tabId = info.tabId + if info.url != "about:blank" { lastURL = info.url } + if changed { onTabChange(info.tabId, lastURL) } + } + + nonisolated static func decode(_ base64: String) -> CGImage? { + guard let data = Data(base64Encoded: base64), + let source = CGImageSourceCreateWithData(data as CFData, nil) + else { return nil } + return CGImageSourceCreateImageAtIndex(source, 0, nil) + } + + static func describe(code: String, message: String) -> String { + switch code { + case "BROWSER_NOT_FOUND": + "No Chrome, Chromium or Edge on the project's machine. Install one there, or set PU_BROWSER for its daemon." + case "BROWSER_UNSUPPORTED": + "The browser runs on macOS and Linux machines." + default: + message + } + } +} + +nonisolated enum BrowserSessionError: Error, LocalizedError { + case daemon(String, String) + case unexpected + /// The tab was gone; try again with a new one. + case retry + + var errorDescription: String? { + switch self { + case .daemon(_, let message): message + case .unexpected: "Unexpected reply from the daemon" + case .retry: "Reopening the tab" + } + } +} + +/// Serializes writes to a pane's attach stream so JSON lines never interleave. +actor BrowserStreamWriter { + private var stream: (any DaemonByteStream)? + + func use(_ stream: any DaemonByteStream) { + self.stream = stream + } + + func send(_ request: DaemonRequest) async { + guard let stream else { return } + try? await DaemonClient.write(request, to: stream) + } + + /// Closes `stream` if it is still the current one (or the current one, given none). + func close(_ which: (any DaemonByteStream)? = nil) { + guard let current = stream else { return } + if let which, which !== current { return } + current.close() + stream = nil + } +} diff --git a/apps/purepoint-macos/purepoint-macos/State/WorkspaceRegistry.swift b/apps/purepoint-macos/purepoint-macos/State/WorkspaceRegistry.swift index 74226201..6fe5fe8a 100644 --- a/apps/purepoint-macos/purepoint-macos/State/WorkspaceRegistry.swift +++ b/apps/purepoint-macos/purepoint-macos/State/WorkspaceRegistry.swift @@ -53,6 +53,8 @@ final class WorkspaceRegistry { /// Invoked with (projectRoot, agentId) when a tab holding an agent is closed. @ObservationIgnored var onCloseAgent: ((String, String) -> Void)? + /// Called with (project id, browser tab id) when the last pane tab showing a browser tab closes. + @ObservationIgnored var onCloseBrowserTab: ((String, String) -> Void)? @ObservationIgnored private var reservationsByProject: [String: [SurfaceReservation]] = [:] /// The latest live-agent list each project's manifest produced, kept so a pane binding @@ -467,6 +469,21 @@ final class WorkspaceRegistry { mutate(workspaceId) { $0.breakTab(surfaceId, axis: axis) } } + /// Show a browser tab in a tab: an existing tab of the project's browser, or (with no + /// `tabId`) a new one the pane opens, on `url` if given. + func openBrowser(workspaceId: String, surfaceId: Int, tabId: String? = nil, url: String? = nil) { + mutate(workspaceId) { $0.setContent(.browser(tabId: tabId, url: url), forSurface: surfaceId) } + } + + /// Record which browser tab a pane shows and its page, so it reattaches after a relaunch. + /// Leaves the tab alone if it shows something else by now. + func updateBrowser(workspaceId: String, surfaceId: Int, tabId: String, url: String?) { + guard let surface = workspace(id: workspaceId)?.surfaces.first(where: { $0.surface.id == surfaceId })?.surface, + case .browser = surface.content + else { return } + mutate(workspaceId) { $0.setContent(.browser(tabId: tabId, url: url), forSurface: surfaceId) } + } + /// Show the file navigator in a tab (optionally opened on a file). No daemon involved. func openFile(workspaceId: String, surfaceId: Int, path: String?) { mutate(workspaceId) { $0.setContent(.file(path: path), forSurface: surfaceId) } @@ -524,6 +541,13 @@ final class WorkspaceRegistry { let index = list.firstIndex(where: { $0.id == workspaceId }) else { return } + // Browser tabs closed with their pane tab, unless another pane tab still shows them. + let closing = Set(surfaceIds) + let browserTabs = list[index].surfaces.compactMap { entry -> String? in + guard closing.contains(entry.surface.id), case .browser(let tabId?, _) = entry.surface.content + else { return nil } + return tabId + } let killed = body(&list[index]) for surfaceId in surfaceIds { dropReservation(projectRoot: projectRoot, workspaceId: workspaceId, surfaceId: surfaceId) @@ -544,6 +568,14 @@ final class WorkspaceRegistry { for agentId in killed { onCloseAgent?(projectRoot, agentId) } + let stillShown = Set( + list.flatMap { $0.surfaces }.compactMap { entry -> String? in + if case .browser(let tabId?, _) = entry.surface.content { return tabId } + return nil + }) + for tabId in browserTabs where !stillShown.contains(tabId) { + onCloseBrowserTab?(projectRoot, tabId) + } } private func mutate(_ workspaceId: String, _ body: (inout Workspace) -> Void) { @@ -625,6 +657,17 @@ final class WorkspaceRegistry { case .breakTab(let tabId, let axisStr): guard let surfaceId = tabId ?? current.focusedSurface?.id else { return } breakTab(workspaceId: workspaceId, surfaceId: surfaceId, axis: axis(axisStr)) + case .openBrowser(let leafId, let browserTab): + // Already on screen: just bring it forward. + if let shown = current.surfaces.first(where: { + if case .browser(let tabId, _) = $0.surface.content { return tabId == browserTab } + return false + }) { + selectTab(workspaceId: workspaceId, surfaceId: shown.surface.id) + return + } + guard let target = pane(leafId) else { return } + newTab(workspaceId: workspaceId, leafId: target, content: .browser(tabId: browserTab, url: nil)) case .getLayout: break // daemon answers this from the file directly } diff --git a/apps/purepoint-macos/purepoint-macos/Views/Browser/BrowserCanvas+iOS.swift b/apps/purepoint-macos/purepoint-macos/Views/Browser/BrowserCanvas+iOS.swift new file mode 100644 index 00000000..1d133173 --- /dev/null +++ b/apps/purepoint-macos/purepoint-macos/Views/Browser/BrowserCanvas+iOS.swift @@ -0,0 +1,182 @@ +#if os(iOS) +import SwiftUI +import UIKit + +/// iPad twin of the Mac browser canvas: tap to click, drag to scroll, and the on-screen or +/// hardware keyboard types into the page. +struct BrowserCanvas: UIViewRepresentable { + let image: CGImage? + let cssSize: CGSize + let onInput: (BrowserInputEvent) -> Void + let onResize: (Int, Int, Double) -> Void + let onCopy: () -> Void + let onFocus: () -> Void + + func makeUIView(context: Context) -> BrowserCanvasUIView { + BrowserCanvasUIView() + } + + func updateUIView(_ view: BrowserCanvasUIView, context: Context) { + view.onInput = onInput + view.onResize = onResize + view.onCopy = onCopy + view.onFocus = onFocus + view.cssSize = cssSize + view.image = image + } +} + +final class BrowserCanvasUIView: UIView, UIKeyInput { + var onInput: ((BrowserInputEvent) -> Void)? + var onResize: ((Int, Int, Double) -> Void)? + var onCopy: (() -> Void)? + var onFocus: (() -> Void)? + var cssSize = CGSize(width: 1280, height: 800) + var image: CGImage? { + didSet { + guard image !== oldValue else { return } + layer.contents = image + } + } + private var lastPan = CGPoint.zero + private var lastSize = CGSize.zero + + // UITextInputTraits: page text is not prose to autocorrect. + var autocorrectionType: UITextAutocorrectionType = .no + var autocapitalizationType: UITextAutocapitalizationType = .none + var spellCheckingType: UITextSpellCheckingType = .no + var smartQuotesType: UITextSmartQuotesType = .no + var smartDashesType: UITextSmartDashesType = .no + + override init(frame: CGRect) { + super.init(frame: frame) + layer.contentsGravity = .resize + backgroundColor = .white + isMultipleTouchEnabled = false + addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapped(_:)))) + let pan = UIPanGestureRecognizer(target: self, action: #selector(panned(_:))) + pan.maximumNumberOfTouches = 2 + addGestureRecognizer(pan) + let pointerScroll = UIPanGestureRecognizer(target: self, action: #selector(panned(_:))) + pointerScroll.allowedScrollTypesMask = .continuous + pointerScroll.allowedTouchTypes = [] + addGestureRecognizer(pointerScroll) + } + + required init?(coder: NSCoder) { fatalError("init(coder:) is not used") } + + override var canBecomeFirstResponder: Bool { true } + + override func layoutSubviews() { + super.layoutSubviews() + guard bounds.size != lastSize, bounds.width >= 1, bounds.height >= 1 else { return } + lastSize = bounds.size + onResize?(Int(bounds.width.rounded()), Int(bounds.height.rounded()), Double(traitCollection.displayScale)) + } + + private func pagePoint(_ p: CGPoint) -> CGPoint { + let sx = bounds.width > 0 ? cssSize.width / bounds.width : 1 + let sy = bounds.height > 0 ? cssSize.height / bounds.height : 1 + return CGPoint(x: p.x * sx, y: p.y * sy) + } + + @objc private func tapped(_ gesture: UITapGestureRecognizer) { + becomeFirstResponder() + onFocus?() + let p = pagePoint(gesture.location(in: self)) + onInput?(.mouse(action: .move, x: p.x, y: p.y, button: .none, clickCount: 0, modifiers: 0)) + onInput?(.mouse(action: .down, x: p.x, y: p.y, button: .left, clickCount: 1, modifiers: 0)) + onInput?(.mouse(action: .up, x: p.x, y: p.y, button: .left, clickCount: 1, modifiers: 0)) + } + + @objc private func panned(_ gesture: UIPanGestureRecognizer) { + let translation = gesture.translation(in: self) + if gesture.state == .began { lastPan = .zero } + let dx = translation.x - lastPan.x + let dy = translation.y - lastPan.y + lastPan = translation + guard dx != 0 || dy != 0 else { return } + let p = pagePoint(gesture.location(in: self)) + let s = pagePoint(CGPoint(x: dx, y: dy)) + // Content follows the finger: dragging up scrolls the page down. + onInput?(.wheel(x: p.x, y: p.y, dx: -s.x, dy: -s.y, modifiers: 0)) + } + + // MARK: - UIKeyInput + + var hasText: Bool { true } + + func insertText(_ text: String) { + if text == "\n" { + press("Enter") + } else { + onInput?(.text(text)) + } + } + + func deleteBackward() { press("Backspace") } + + private func press(_ key: String, modifiers: Int = 0) { + let text: String? = key == "Enter" ? "\r" : nil + onInput?(.key(down: true, key: key, code: nil, text: text, modifiers: modifiers)) + onInput?(.key(down: false, key: key, code: nil, text: nil, modifiers: modifiers)) + } + + // MARK: - Hardware keyboard + + override func pressesBegan(_ presses: Set, with event: UIPressesEvent?) { + var unhandled = Set() + for press in presses { + guard let key = press.key else { + unhandled.insert(press) + continue + } + let modifiers = Self.modifiers(key.modifierFlags) + if key.modifierFlags.contains(.command) { + switch key.charactersIgnoringModifiers.lowercased() { + case "v": + if let text = UIPasteboard.general.string, !text.isEmpty { onInput?(.text(text)) } + continue + case "c": + onCopy?() + continue + default: + break + } + } + if let named = Self.namedKey(key.keyCode) { + self.press(named, modifiers: modifiers) + } else { + unhandled.insert(press) // characters arrive through insertText + } + } + if !unhandled.isEmpty { super.pressesBegan(unhandled, with: event) } + } + + static func modifiers(_ flags: UIKeyModifierFlags) -> Int { + var m = BrowserModifiers() + if flags.contains(.alternate) { m.insert(.alt) } + if flags.contains(.control) { m.insert(.control) } + if flags.contains(.command) { m.insert(.meta) } + if flags.contains(.shift) { m.insert(.shift) } + return m.rawValue + } + + static func namedKey(_ code: UIKeyboardHIDUsage) -> String? { + switch code { + case .keyboardTab: "Tab" + case .keyboardEscape: "Escape" + case .keyboardDeleteForward: "Delete" + case .keyboardLeftArrow: "ArrowLeft" + case .keyboardRightArrow: "ArrowRight" + case .keyboardUpArrow: "ArrowUp" + case .keyboardDownArrow: "ArrowDown" + case .keyboardHome: "Home" + case .keyboardEnd: "End" + case .keyboardPageUp: "PageUp" + case .keyboardPageDown: "PageDown" + default: nil + } + } +} +#endif diff --git a/apps/purepoint-macos/purepoint-macos/Views/Browser/BrowserCanvas.swift b/apps/purepoint-macos/purepoint-macos/Views/Browser/BrowserCanvas.swift new file mode 100644 index 00000000..284db079 --- /dev/null +++ b/apps/purepoint-macos/purepoint-macos/Views/Browser/BrowserCanvas.swift @@ -0,0 +1,219 @@ +#if os(macOS) +import AppKit +import SwiftUI + +/// Draws a browser tab's frames and turns mouse, scroll and keyboard input into page input. +struct BrowserCanvas: NSViewRepresentable { + let image: CGImage? + let cssSize: CGSize + let onInput: (BrowserInputEvent) -> Void + let onResize: (Int, Int, Double) -> Void + let onCopy: () -> Void + let onFocus: () -> Void + + func makeNSView(context: Context) -> BrowserCanvasNSView { + BrowserCanvasNSView() + } + + func updateNSView(_ view: BrowserCanvasNSView, context: Context) { + view.onInput = onInput + view.onResize = onResize + view.onCopy = onCopy + view.onFocus = onFocus + view.cssSize = cssSize + view.image = image + } +} + +final class BrowserCanvasNSView: NSView { + var onInput: ((BrowserInputEvent) -> Void)? + var onResize: ((Int, Int, Double) -> Void)? + var onCopy: (() -> Void)? + var onFocus: (() -> Void)? + var cssSize = CGSize(width: 1280, height: 800) + var image: CGImage? { + didSet { + guard image !== oldValue else { return } + layer?.contents = image + } + } + private var lastMove = Date.distantPast + private var trackingArea: NSTrackingArea? + + override init(frame frameRect: NSRect) { + super.init(frame: frameRect) + wantsLayer = true + layer?.contentsGravity = .resize + layer?.backgroundColor = NSColor.white.cgColor + } + + required init?(coder: NSCoder) { fatalError("init(coder:) is not used") } + + override var isFlipped: Bool { true } + override var acceptsFirstResponder: Bool { true } + override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true } + + // MARK: - Size + + override func setFrameSize(_ newSize: NSSize) { + super.setFrameSize(newSize) + reportSize() + } + + override func viewDidChangeBackingProperties() { + super.viewDidChangeBackingProperties() + reportSize() + } + + override func viewDidMoveToWindow() { + super.viewDidMoveToWindow() + reportSize() + } + + private func reportSize() { + guard bounds.width >= 1, bounds.height >= 1 else { return } + let scale = Double(window?.backingScaleFactor ?? 2) + onResize?(Int(bounds.width.rounded()), Int(bounds.height.rounded()), scale) + } + + override func updateTrackingAreas() { + super.updateTrackingAreas() + if let trackingArea { removeTrackingArea(trackingArea) } + let area = NSTrackingArea( + rect: bounds, options: [.mouseMoved, .activeInKeyWindow, .inVisibleRect], owner: self, userInfo: nil) + addTrackingArea(area) + trackingArea = area + } + + // MARK: - Mouse + + /// A point in this view as CSS pixels in the page. + private func pagePoint(_ event: NSEvent) -> CGPoint { + let p = convert(event.locationInWindow, from: nil) + let sx = bounds.width > 0 ? cssSize.width / bounds.width : 1 + let sy = bounds.height > 0 ? cssSize.height / bounds.height : 1 + return CGPoint(x: p.x * sx, y: p.y * sy) + } + + private func mouse(_ action: BrowserInputEvent.MouseAction, _ button: BrowserInputEvent.MouseButton, _ event: NSEvent) { + let p = pagePoint(event) + onInput?( + .mouse( + action: action, x: p.x, y: p.y, button: button, clickCount: event.clickCount, + modifiers: Self.modifiers(event.modifierFlags))) + } + + override func mouseDown(with event: NSEvent) { + window?.makeFirstResponder(self) + onFocus?() + mouse(.down, .left, event) + } + override func mouseUp(with event: NSEvent) { mouse(.up, .left, event) } + override func mouseDragged(with event: NSEvent) { mouse(.move, .left, event) } + override func rightMouseDown(with event: NSEvent) { + window?.makeFirstResponder(self) + mouse(.down, .right, event) + } + override func rightMouseUp(with event: NSEvent) { mouse(.up, .right, event) } + override func otherMouseDown(with event: NSEvent) { mouse(.down, .middle, event) } + override func otherMouseUp(with event: NSEvent) { mouse(.up, .middle, event) } + + override func mouseMoved(with event: NSEvent) { + // Hover only needs to keep up with the eye; over SSH every line costs. + let now = Date() + guard now.timeIntervalSince(lastMove) > 1.0 / 30 else { return } + lastMove = now + mouse(.move, .none, event) + } + + override func scrollWheel(with event: NSEvent) { + let p = pagePoint(event) + let factor: CGFloat = event.hasPreciseScrollingDeltas ? 1 : 40 + onInput?( + .wheel( + x: p.x, y: p.y, dx: -event.scrollingDeltaX * factor, dy: -event.scrollingDeltaY * factor, + modifiers: Self.modifiers(event.modifierFlags))) + } + + // MARK: - Keyboard + + override func performKeyEquivalent(with event: NSEvent) -> Bool { + guard window?.firstResponder === self, event.modifierFlags.contains(.command) else { + return super.performKeyEquivalent(with: event) + } + switch event.charactersIgnoringModifiers?.lowercased() { + case "v": + if let text = NSPasteboard.general.string(forType: .string), !text.isEmpty { onInput?(.text(text)) } + return true + case "c": + onCopy?() + return true + default: + return super.performKeyEquivalent(with: event) + } + } + + override func keyDown(with event: NSEvent) { key(event, down: true) } + override func keyUp(with event: NSEvent) { key(event, down: false) } + + private func key(_ event: NSEvent, down: Bool) { + let modifiers = Self.modifiers(event.modifierFlags) + let named = Self.namedKey(event.keyCode) + let characters = event.characters ?? "" + let key = named ?? (characters.isEmpty ? (event.charactersIgnoringModifiers ?? "") : characters) + guard !key.isEmpty else { return } + // Text is typed only by a plain (or shifted/option) press; chords are shortcuts. + let typing = !event.modifierFlags.contains(.command) && !event.modifierFlags.contains(.control) + let text: String? = + if named == "Enter" { "\r" } else if named == nil, typing, Self.isPrintable(characters) { characters } else { nil } + onInput?(.key(down: down, key: key, code: nil, text: down ? text : nil, modifiers: modifiers)) + } + + static func modifiers(_ flags: NSEvent.ModifierFlags) -> Int { + var m = BrowserModifiers() + if flags.contains(.option) { m.insert(.alt) } + if flags.contains(.control) { m.insert(.control) } + if flags.contains(.command) { m.insert(.meta) } + if flags.contains(.shift) { m.insert(.shift) } + return m.rawValue + } + + static func isPrintable(_ text: String) -> Bool { + guard let scalar = text.unicodeScalars.first else { return false } + // AppKit reports arrows and function keys in the private-use area. + return !text.isEmpty && scalar.value >= 0x20 && scalar.value != 0x7F && !(0xF700...0xF8FF).contains(scalar.value) + } + + /// DOM key names for keys that type nothing, by macOS virtual key code. + static func namedKey(_ keyCode: UInt16) -> String? { + switch keyCode { + case 36, 76: "Enter" + case 48: "Tab" + case 51: "Backspace" + case 53: "Escape" + case 117: "Delete" + case 123: "ArrowLeft" + case 124: "ArrowRight" + case 125: "ArrowDown" + case 126: "ArrowUp" + case 115: "Home" + case 119: "End" + case 116: "PageUp" + case 121: "PageDown" + case 122: "F1" + case 120: "F2" + case 99: "F3" + case 118: "F4" + case 96: "F5" + case 97: "F6" + case 98: "F7" + case 100: "F8" + case 101: "F9" + case 109: "F10" + case 103: "F11" + case 111: "F12" + default: nil + } + } +} +#endif diff --git a/apps/purepoint-macos/purepoint-macos/Views/Browser/BrowserPaneView.swift b/apps/purepoint-macos/purepoint-macos/Views/Browser/BrowserPaneView.swift new file mode 100644 index 00000000..3167018a --- /dev/null +++ b/apps/purepoint-macos/purepoint-macos/Views/Browser/BrowserPaneView.swift @@ -0,0 +1,170 @@ +import SwiftUI + +#if os(macOS) +import AppKit +#else +import UIKit +#endif + +/// A browser pane: a live view of a tab of the project's browser, which runs headless on the +/// project's machine (this Mac, or a remote machine over SSH). Agents drive the same tab with +/// `pu browser`; "Take Control" stops them until the person hands it back. +struct BrowserPaneView: View { + let onFocus: () -> Void + @State private var session: BrowserSession + @State private var address = "" + @FocusState private var addressFocused: Bool + private let startsBlank: Bool + + init( + workspaceId: String, surfaceId: Int, client: DaemonClient, projectRoot: String, tabId: String?, url: String?, + registry: WorkspaceRegistry, onFocus: @escaping () -> Void + ) { + self.onFocus = onFocus + self.startsBlank = tabId == nil && url == nil + _session = State( + initialValue: BrowserSession( + client: client, projectRoot: projectRoot, tabId: tabId, url: url, + onTabChange: { [weak registry] tabId, url in + registry?.updateBrowser(workspaceId: workspaceId, surfaceId: surfaceId, tabId: tabId, url: url) + })) + _address = State(initialValue: BrowserAddress.fieldText(for: url)) + } + + var body: some View { + VStack(spacing: 0) { + toolbar + Divider() + ZStack(alignment: .top) { + BrowserCanvas( + image: session.frame, + cssSize: session.frameSize, + onInput: { session.input($0) }, + onResize: { session.resize(width: $0, height: $1, scale: $2) }, + onCopy: { session.copySelection() }, + onFocus: { + addressFocused = false + onFocus() + } + ) + .background(Color.white) + overlay + if let notice = session.notice { + Text(notice) + .font(.callout) + .padding(.horizontal, 12) + .padding(.vertical, 6) + .background(.regularMaterial, in: Capsule()) + .padding(.top, 8) + .transition(.opacity) + } + } + } + .onAppear { + session.copy = { BrowserPaneView.copyToClipboard($0) } + session.start() + if startsBlank { addressFocused = true } + } + .onDisappear { session.stop() } + .onChange(of: session.tab?.url) { _, url in + if !addressFocused { address = BrowserAddress.fieldText(for: url) } + } + } + + // MARK: - Toolbar + + private var toolbar: some View { + HStack(spacing: 6) { + Button(action: session.goBack) { Image(systemName: "chevron.left") } + .disabled(!(session.tab?.canGoBack ?? false)) + .help("Back") + Button(action: session.goForward) { Image(systemName: "chevron.right") } + .disabled(!(session.tab?.canGoForward ?? false)) + .help("Forward") + Button(action: session.reload) { + if session.tab?.loading == true { + ProgressView().controlSize(.small) + } else { + Image(systemName: "arrow.clockwise") + } + } + .help("Reload") + + TextField("Address, e.g. localhost:3000", text: $address) + .textFieldStyle(.roundedBorder) + .focused($addressFocused) + .autocorrectionDisabled() + #if os(iOS) + .textInputAutocapitalization(.never) + .keyboardType(.URL) + #endif + .onSubmit { + session.navigate(to: address) + addressFocused = false + } + + driverControl + } + .buttonStyle(.borderless) + .padding(.horizontal, 8) + .padding(.vertical, 5) + } + + @ViewBuilder + private var driverControl: some View { + if session.isHumanDriving { + Button { + session.setHumanDriving(false) + } label: { + Label("Hand Back", systemImage: "person.fill") + } + .help("You are driving; agents' browser actions wait. Hand the tab back to them.") + } else { + Button { + session.setHumanDriving(true) + } label: { + Label("Take Control", systemImage: "hand.raised") + } + .help("Stop agents from acting in this tab until you hand it back.") + } + } + + // MARK: - States + + @ViewBuilder + private var overlay: some View { + switch session.phase { + case .connecting where session.frame == nil: + ProgressView("Connecting to the browser…") + .frame(maxWidth: .infinity, maxHeight: .infinity) + case .closed: + message("This browser tab was closed.", action: "Reopen", perform: session.reopen) + case .failed(let reason): + message(reason, action: "Try Again", perform: session.reopen) + default: + EmptyView() + } + } + + private func message(_ text: String, action: String, perform: @escaping () -> Void) -> some View { + VStack(spacing: 12) { + Image(systemName: "globe").font(.system(size: 28)).foregroundStyle(.tertiary) + Text(text) + .multilineTextAlignment(.center) + .foregroundStyle(.secondary) + .frame(maxWidth: 360) + Button(action, action: perform).buttonStyle(.bordered) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .background(.background) + } + + static func copyToClipboard(_ text: String) { + #if os(macOS) + NSPasteboard.general.clearContents() + NSPasteboard.general.setString(text, forType: .string) + #else + UIPasteboard.general.string = text + #endif + } +} diff --git a/apps/purepoint-macos/purepoint-macos/Views/PaneGrid/PaneCellView.swift b/apps/purepoint-macos/purepoint-macos/Views/PaneGrid/PaneCellView.swift index 4f9b4c89..1b819090 100644 --- a/apps/purepoint-macos/purepoint-macos/Views/PaneGrid/PaneCellView.swift +++ b/apps/purepoint-macos/purepoint-macos/Views/PaneGrid/PaneCellView.swift @@ -1,7 +1,7 @@ import SwiftUI /// A single pane cell in the grid: its tab strip above the active tab's content — -/// a terminal, the file navigator, or the empty-tab placeholder. +/// a terminal, the file navigator, a browser, or the empty-tab placeholder. /// /// Only the active tab is rendered. A background agent's terminal view stays alive in /// `TerminalViewCache` (keyed by agent ID), so switching back is instant and keeps scrollback. @@ -73,6 +73,23 @@ struct PaneCellView: View { // One view per tab; its state lives in the tab's FileTabSession, not the view. .id(surface.id) } + case .browser(let tabId, let url): + if let surface = activeTab, + let project = appState.projectState(forWorkspace: workspaceId, registry: registry) + { + // The project's daemon runs the browser, so a remote project's pane shows its + // machine's browser through the same connection as its terminals. + BrowserPaneView( + workspaceId: workspaceId, surfaceId: surface.id, client: project.client, + projectRoot: project.projectRoot, tabId: tabId, url: url, registry: registry, onFocus: focus + ) + .id(surface.id) + } else { + Text("The project is not connected") + .foregroundStyle(.secondary) + .frame(maxWidth: .infinity, maxHeight: .infinity) + .onTapGesture(perform: focus) + } case .empty, nil: if let surface = activeTab { EmptyTabView(workspaceId: workspaceId, surfaceId: surface.id) @@ -103,11 +120,16 @@ private struct EmptyTabView: View { Text("Empty Tab") .font(.title3) .foregroundStyle(.tertiary) - Text("Spawn a new agent, or open files") + Text("Spawn a new agent, open files, or open a browser") .font(.caption) .foregroundStyle(.quaternary) - Button("New Agent\u{2026}") { - openCommandPalette() + HStack(spacing: 8) { + Button("New Agent\u{2026}") { + openCommandPalette() + } + Button("Open Browser") { + registry.openBrowser(workspaceId: workspaceId, surfaceId: surfaceId) + } } .buttonStyle(.bordered) } diff --git a/apps/purepoint-macos/purepoint-macos/Views/PaneGrid/PaneTabBar.swift b/apps/purepoint-macos/purepoint-macos/Views/PaneGrid/PaneTabBar.swift index ecc04a38..eb41e9a1 100644 --- a/apps/purepoint-macos/purepoint-macos/Views/PaneGrid/PaneTabBar.swift +++ b/apps/purepoint-macos/purepoint-macos/Views/PaneGrid/PaneTabBar.swift @@ -213,6 +213,8 @@ private struct PaneTab: View { Image(systemName: "bubble.left.and.bubble.right").foregroundStyle(.secondary) case .file: Image(systemName: "doc.text").foregroundStyle(.secondary) + case .browser: + Image(systemName: "globe").foregroundStyle(.secondary) case .empty: Image(systemName: "magnifyingglass").foregroundStyle(.secondary) } @@ -246,6 +248,8 @@ private struct PaneTab: View { return "Point Guard" case .file(let path): return path.map { ($0 as NSString).lastPathComponent } ?? "Files" + case .browser(_, let url): + return BrowserAddress.tabTitle(for: url) case .empty: return "New Tab" } diff --git a/apps/purepoint-macos/purepoint-macos/Views/PaneGrid/WorkspacePersistence.swift b/apps/purepoint-macos/purepoint-macos/Views/PaneGrid/WorkspacePersistence.swift index 30b58aa7..a9faeb6b 100644 --- a/apps/purepoint-macos/purepoint-macos/Views/PaneGrid/WorkspacePersistence.swift +++ b/apps/purepoint-macos/purepoint-macos/Views/PaneGrid/WorkspacePersistence.swift @@ -40,21 +40,26 @@ nonisolated final class GridLayoutNode: Codable, Sendable { } } -/// One tab as written to disk. `kind` is `agent`, `file`, `point_guard` or `empty`; an unknown kind +/// One tab as written to disk. `kind` is `agent`, `file`, `browser`, `point_guard` or `empty`; an unknown kind /// (a newer app's file) loads as an empty tab rather than failing the whole document. nonisolated struct PersistedSurface: Codable, Sendable, Equatable { let id: Int let kind: String let agentId: String? let path: String? + /// Browser tabs: the daemon's tab id and the last page shown. + let browserTab: String? + let url: String? init(_ surface: Surface) { id = surface.id switch surface.content { - case .empty: (kind, agentId, path) = ("empty", nil, nil) - case .pointGuard: (kind, agentId, path) = ("point_guard", nil, nil) - case .agent(let agentId): (kind, self.agentId, path) = ("agent", agentId, nil) - case .file(let path): (kind, agentId, self.path) = ("file", nil, path) + case .empty: (kind, agentId, path, browserTab, url) = ("empty", nil, nil, nil, nil) + case .pointGuard: (kind, agentId, path, browserTab, url) = ("point_guard", nil, nil, nil, nil) + case .agent(let agentId): (kind, self.agentId, path, browserTab, url) = ("agent", agentId, nil, nil, nil) + case .file(let path): (kind, agentId, self.path, browserTab, url) = ("file", nil, path, nil, nil) + case .browser(let tabId, let url): + (kind, agentId, path, browserTab, self.url) = ("browser", nil, nil, tabId, url) } } @@ -63,6 +68,7 @@ nonisolated struct PersistedSurface: Codable, Sendable, Equatable { case "agent": Surface(id: id, content: agentId.map { .agent($0) } ?? .empty) case "file": Surface(id: id, content: .file(path: path)) case "point_guard": Surface(id: id, content: .pointGuard) + case "browser": Surface(id: id, content: .browser(tabId: browserTab, url: url)) default: Surface(id: id, content: .empty) } } diff --git a/apps/purepoint-macos/purepoint-macos/Views/Terminal/TerminalPaneView+iOS.swift b/apps/purepoint-macos/purepoint-macos/Views/Terminal/TerminalPaneView+iOS.swift index 6af35bb9..267f0a3d 100644 --- a/apps/purepoint-macos/purepoint-macos/Views/Terminal/TerminalPaneView+iOS.swift +++ b/apps/purepoint-macos/purepoint-macos/Views/Terminal/TerminalPaneView+iOS.swift @@ -72,6 +72,7 @@ class TerminalPaneNSView: UIView { tv.terminalView.hideCursor(source: tv.terminalView.getTerminal()) tv.acceptsFileDrops = false tv.usesRemoteHost = true + tv.openLink = BrowserLinks.handler(agentId: agent.id, isRemote: { true }, fallback: tv.openLink) terminal = tv // Show a small spinner while waiting for first output diff --git a/apps/purepoint-macos/purepoint-macos/Views/Terminal/TerminalPaneView.swift b/apps/purepoint-macos/purepoint-macos/Views/Terminal/TerminalPaneView.swift index 5b38be75..3463483f 100644 --- a/apps/purepoint-macos/purepoint-macos/Views/Terminal/TerminalPaneView.swift +++ b/apps/purepoint-macos/purepoint-macos/Views/Terminal/TerminalPaneView.swift @@ -74,6 +74,8 @@ class TerminalPaneNSView: NSView { tv.terminalView.hideCursor(source: tv.terminalView.getTerminal()) tv.attachmentClient = client tv.usesRemoteHost = !isLocalClient + tv.openLink = BrowserLinks.handler( + agentId: agent.id, isRemote: { [weak tv] in tv?.usesRemoteHost ?? false }, fallback: tv.openLink) terminal = tv // Show a small spinner while waiting for first output diff --git a/apps/purepoint-macos/purepoint-macos/purepoint_macosApp.swift b/apps/purepoint-macos/purepoint-macos/purepoint_macosApp.swift index 22e92f0b..420aba19 100644 --- a/apps/purepoint-macos/purepoint-macos/purepoint_macosApp.swift +++ b/apps/purepoint-macos/purepoint-macos/purepoint_macosApp.swift @@ -42,6 +42,18 @@ struct purepoint_macosApp: App { viewCache.remove(agentId: agentId) appState.projectState(forId: projectId)?.removeAndKillAgent(agentId) } + BrowserLinks.open = { [weak registry] agentId, url in + guard let registry, let workspaceId = registry.workspaceId(forAgent: agentId), + let workspace = registry.workspace(id: workspaceId) + else { return false } + let content = SurfaceContent.browser(tabId: nil, url: url.absoluteString) + return registry.newTab(workspaceId: workspaceId, leafId: workspace.focusedLeafId, content: content) != nil + } + registry.onCloseBrowserTab = { projectId, tabId in + guard let project = appState.projectState(forId: projectId) else { return } + let (client, root) = (project.client, project.projectRoot) + Task { _ = try? await client.send(.browser(projectRoot: root, op: .close(tabId: tabId))) } + } hotkeyMonitor.keyBindingState = keyBindingState hotkeyMonitor.start() CLIInstaller.installIfNeeded() diff --git a/apps/purepoint-macos/purepoint-macosTests/BrowserPaneTests.swift b/apps/purepoint-macos/purepoint-macosTests/BrowserPaneTests.swift new file mode 100644 index 00000000..eb287a39 --- /dev/null +++ b/apps/purepoint-macos/purepoint-macosTests/BrowserPaneTests.swift @@ -0,0 +1,135 @@ +import Foundation +import Testing + +@testable import PurePoint + +/// Browser panes: the wire format they share with the daemon, how a browser tab persists, +/// and which terminal links open in one. +struct BrowserPaneTests { + + private func json(_ value: some Encodable) throws -> [String: Any] { + let data = try JSONEncoder().encode(value) + return try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) + } + + @Test func attachAndOpsEncodeAsTheDaemonReadsThem() throws { + let attach = try json(DaemonRequest.browserAttach(projectRoot: "/p", tabId: "T1")) + #expect(attach["type"] as? String == "browser_attach") + #expect(attach["project_root"] as? String == "/p") + #expect(attach["tab_id"] as? String == "T1") + + let click = try json( + DaemonRequest.browser( + projectRoot: "/p", + op: .input( + tabId: nil, + event: .mouse(action: .down, x: 3, y: 4, button: .left, clickCount: 2, modifiers: 8)))) + #expect(click["type"] as? String == "browser") + let op = try #require(click["op"] as? [String: Any]) + #expect(op["action"] as? String == "input") + #expect(op["tab_id"] == nil) + let event = try #require(op["event"] as? [String: Any]) + #expect(event["kind"] as? String == "mouse") + #expect(event["action"] as? String == "down") + #expect(event["button"] as? String == "left") + #expect(event["click_count"] as? Int == 2) + #expect(event["modifiers"] as? Int == 8) + + let ack = try json(BrowserOp.frameAck(tabId: nil, seq: 7)) + #expect(ack["action"] as? String == "frame_ack") + #expect(ack["seq"] as? Int == 7) + + let resize = try json(BrowserOp.resize(tabId: "T", width: 800, height: 600, scale: 2)) + #expect(resize["width"] as? Int == 800) + #expect(resize["scale"] as? Double == 2) + } + + @Test func framesTabStateAndCloseDecode() { + let frame = DaemonClient.parse( + Data(#"{"type":"browser_frame","tab_id":"T","seq":3,"data":"AAAA","width":1280.0,"height":800.0}"#.utf8)) + guard case .browserFrame(let payload) = frame else { + Issue.record("expected a frame, got \(frame)") + return + } + #expect(payload.seq == 3) + #expect(payload.width == 1280) + + let state = DaemonClient.parse( + Data( + #"{"type":"browser_tab_state","tab":{"tab_id":"T","url":"http://localhost:3000/","title":"App","loading":true,"driver":"human","can_go_back":true,"can_go_forward":false,"width":800,"height":600}}"# + .utf8)) + guard case .browserTabState(let tab) = state else { + Issue.record("expected tab state, got \(state)") + return + } + #expect(tab.isHumanDriving) + #expect(tab.canGoBack) + #expect(tab.loading) + + let closed = DaemonClient.parse(Data(#"{"type":"browser_tab_closed","tab_id":"T"}"#.utf8)) + guard case .browserTabClosed(let tabId) = closed else { + Issue.record("expected closed, got \(closed)") + return + } + #expect(tabId == "T") + } + + @Test func openBrowserGridCommandRoundTrips() throws { + let payload = GridCommandPayload(.openBrowser(leafId: nil, browserTab: "T9")) + let data = try JSONEncoder().encode(payload) + let object = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) + #expect(object["action"] as? String == "open_browser") + #expect(object["browser_tab"] as? String == "T9") + let decoded = try JSONDecoder().decode(GridCommandPayload.self, from: data) + #expect(decoded.action == .openBrowser(leafId: nil, browserTab: "T9")) + } + + @Test func browserTabsPersistTheirTabAndPage() throws { + let surface = Surface(id: 4, content: .browser(tabId: "T1", url: "http://localhost:5173/")) + let data = try JSONEncoder().encode(PersistedSurface(surface)) + let restored = try JSONDecoder().decode(PersistedSurface.self, from: data).surface + #expect(restored == surface) + + // Files written before browser tabs have neither field. + let old = try JSONDecoder().decode( + PersistedSurface.self, from: Data(#"{"id":1,"kind":"file","path":"/a"}"#.utf8)) + #expect(old.surface == Surface(id: 1, content: .file(path: "/a"))) + } + + @Test func onlyLoopbackWebLinksCountAsTheMachines() throws { + for link in ["http://localhost:3000", "https://app.localhost/x", "http://127.0.0.1:8080", "http://0.0.0.0:4000"] { + #expect(BrowserLinks.isLoopback(try #require(URL(string: link))), "\(link)") + } + for link in ["https://example.com", "file:///tmp/a", "ssh://localhost", "http://192.168.1.4"] { + #expect(!BrowserLinks.isLoopback(try #require(URL(string: link))), "\(link)") + } + } + + @Test @MainActor func aRemoteTerminalsLoopbackLinkOpensInABrowserPane() throws { + var opened: [String] = [] + var fellBack: [URL] = [] + BrowserLinks.open = { agentId, url in + opened.append("\(agentId) \(url.absoluteString)") + return true + } + defer { BrowserLinks.open = nil } + let remote = BrowserLinks.handler(agentId: "ag-1", isRemote: { true }, fallback: { fellBack.append($0) }) + remote(try #require(URL(string: "http://localhost:3000"))) + remote(try #require(URL(string: "https://example.com"))) + #expect(opened == ["ag-1 http://localhost:3000"]) + #expect(fellBack.map(\.absoluteString) == ["https://example.com"]) + + let local = BrowserLinks.handler(agentId: "ag-2", isRemote: { false }, fallback: { fellBack.append($0) }) + local(try #require(URL(string: "http://localhost:3000"))) + #expect(opened.count == 1) + #expect(fellBack.count == 2) + } + + @Test func tabTitlesNameTheHost() { + #expect(BrowserAddress.tabTitle(for: nil) == "Browser") + #expect(BrowserAddress.tabTitle(for: "about:blank") == "Browser") + #expect(BrowserAddress.tabTitle(for: "http://localhost:3000/login") == "localhost:3000") + #expect(BrowserAddress.tabTitle(for: "https://docs.rs/tokio") == "docs.rs") + #expect(BrowserAddress.fieldText(for: "about:blank") == "") + } +} diff --git a/apps/purepoint-macos/purepoint-macosTests/PaneTabStackTests.swift b/apps/purepoint-macos/purepoint-macosTests/PaneTabStackTests.swift index 4f547895..48d1a0d5 100644 --- a/apps/purepoint-macos/purepoint-macosTests/PaneTabStackTests.swift +++ b/apps/purepoint-macos/purepoint-macosTests/PaneTabStackTests.swift @@ -23,6 +23,7 @@ import Testing case .file(let path): path ?? "files" case .empty: "+" case .pointGuard: "Point Guard" + case .browser(let tabId, _): "browser:\(tabId ?? "new")" } } ?? [] } diff --git a/crates/pu-cli/assets/plugin/commands/pu.md b/crates/pu-cli/assets/plugin/commands/pu.md index 3d88458c..685f556a 100644 --- a/crates/pu-cli/assets/plugin/commands/pu.md +++ b/crates/pu-cli/assets/plugin/commands/pu.md @@ -248,6 +248,24 @@ pu swarm delete # delete swarm definition pu swarm run # run a swarm ``` +### Browser +The project has one headless browser on this machine, shared with the person's browser pane in the app. Use it to check pages you build (`localhost` is this machine) and for web tasks. +```bash +pu browser open localhost:3000 --show # open a tab (and show it in the app) +pu browser snapshot # page outline; interactive elements carry [ref=eN] +pu browser click e3 # click by ref from the latest snapshot +pu browser type e5 "hello" --submit # replace a field's text, then press Enter +pu browser press Escape # keys and chords: Enter, Tab, Shift+Tab, Control+a +pu browser scroll down 800 +pu browser wait --text "Saved" # wait for text (default 10 s) +pu browser screenshot # PNG path on this machine; read it to see the page +pu browser console # console messages, exceptions and dialogs +pu browser eval "document.title" # run JavaScript, print the value +pu browser goto /path | back | forward | reload +pu browser tabs # --tab targets a tab; default is the last used +``` +Re-run `snapshot` after the page changes: refs do not survive navigation. `BROWSER_HUMAN_DRIVING` means the person took control of the tab in their pane; wait and retry rather than working around it. + ### Other ```bash pu health # daemon status diff --git a/crates/pu-cli/assets/plugin/skills/pu/SKILL.md b/crates/pu-cli/assets/plugin/skills/pu/SKILL.md index 2c8e28a3..11682088 100644 --- a/crates/pu-cli/assets/plugin/skills/pu/SKILL.md +++ b/crates/pu-cli/assets/plugin/skills/pu/SKILL.md @@ -58,6 +58,9 @@ Use `/pu` for the full CLI reference. Key commands: - `pu spawn "prompt" --name ` — spawn a new agent - `pu kill --agent ` — stop an agent - `pu machine list` / `pu --machine ` — work with a daemon on another computer over SSH (project commands need `--project `; never auto-starts it) +- `pu browser open [--show]` — open the project's browser (runs on this machine, shared with the person's browser pane; `--show` puts it on their screen) +- `pu browser snapshot` → `pu browser click e3` / `pu browser type e5 "text" [--submit]` — read the page as an outline with `[ref=eN]` handles, then act on them; re-snapshot after the page changes +- `pu browser wait --text "…"`, `pu browser screenshot`, `pu browser console`, `pu browser eval ""` — check results; `BROWSER_HUMAN_DRIVING` means the person took control: wait and retry, don't fight it ## Conversation Monitoring diff --git a/crates/pu-engine/src/browser/mod.rs b/crates/pu-engine/src/browser/mod.rs index a36525b1..9335064b 100644 --- a/crates/pu-engine/src/browser/mod.rs +++ b/crates/pu-engine/src/browser/mod.rs @@ -799,8 +799,25 @@ async fn wait_for_load( } } +/// Resolves a path (`/login`) against the current page's origin; anything else is kept. +pub fn resolve_against(current: &str, url: &str) -> String { + let url = url.trim(); + if !url.starts_with('/') || url.starts_with("//") { + return url.to_string(); + } + let Some(scheme_end) = current.find("://") else { + return url.to_string(); + }; + let after = ¤t[scheme_end + 3..]; + let host_end = after.find(['/', '?', '#']).unwrap_or(after.len()); + if after[..host_end].is_empty() { + return url.to_string(); + } + format!("{}{url}", ¤t[..scheme_end + 3 + host_end]) +} + async fn navigate(cdp: &Cdp, tab: &Tab, url: &str) -> Result<()> { - let url = normalize_url(url); + let url = normalize_url(&resolve_against(&tab.info().url, url)); let mut events = cdp.subscribe(); let result = cdp .call( @@ -1251,6 +1268,24 @@ mod tests { assert_eq!(normalize_url("file:///tmp/a.html"), "file:///tmp/a.html"); } + #[test] + fn given_a_path_should_resolve_it_against_the_current_origin() { + assert_eq!( + resolve_against("http://localhost:3000/a/b?x=1", "/login"), + "http://localhost:3000/login" + ); + assert_eq!( + resolve_against("https://ex.com", "/docs"), + "https://ex.com/docs" + ); + assert_eq!(resolve_against("about:blank", "/x"), "/x"); + assert_eq!(resolve_against("http://a.com/", "b.com"), "b.com"); + assert_eq!( + resolve_against("http://a.com/", "//cdn.com/x"), + "//cdn.com/x" + ); + } + #[test] fn given_chords_should_split_modifiers_from_the_key() { assert_eq!(parse_chord("Enter"), (0, "Enter".into())); diff --git a/docs/guide/cli-reference.md b/docs/guide/cli-reference.md index 5140893f..081b6033 100644 --- a/docs/guide/cli-reference.md +++ b/docs/guide/cli-reference.md @@ -26,6 +26,7 @@ | [`pu agent`](#agent) | Manage saved agent definitions | | [`pu swarm`](#swarm) | Manage and run swarm compositions | | [`pu grid`](#grid) | Control the pane grid layout | +| [`pu browser`](#browser) | Drive the project's browser | | [`pu schedule`](#schedule) | Manage scheduled tasks | | [`pu trigger`](#trigger) | Manage event-driven triggers | | [`pu gate`](#gate) | Evaluate git hook gates | @@ -293,6 +294,36 @@ Each pane holds an ordered stack of tabs (an agent, a file, or empty). `--leaf` Leaf and tab ids are only unique within a workspace. Without `--workspace`, a command acts on the workspace on screen. When you copy ids from `grid show`, pass that workspace's id with `--workspace`, so they can't land in a different one. +## browser + +Drive the project's headless browser, which runs on the daemon's machine and is shared with browser panes in the app. See [Browser](../product/browser.md). + +```sh +pu browser open [] [--show] +pu browser tabs +pu browser close +pu browser goto +pu browser back | forward | reload +pu browser snapshot +pu browser click +pu browser type [--submit] +pu browser press # Enter, Tab, Escape, ArrowDown, Control+a +pu browser scroll up|down|left|right [] +pu browser screenshot [] [--full-page] +pu browser console [--clear] +pu browser eval +pu browser wait [--text ] [--timeout ] +pu browser control human|agent +``` + +Every subcommand takes `--tab ` (default: the tab used last) and `--json`. Bare addresses get a scheme: `localhost:3000` and other local hosts become `http://`, anything else `https://`. + +`snapshot` prints the page as an indented accessibility outline. Links, buttons, fields and other interactive elements carry `[ref=eN]`; pass that ref to `click` and `type`. Refs last until the next snapshot or page load. `type` replaces the element's contents. + +`open --show` also asks the app to show the tab in a browser pane. While a person drives the tab from a pane (`control human`, or Take Control in the app), page actions fail with `BROWSER_HUMAN_DRIVING`; `snapshot`, `screenshot` and `console` still work. + +The browser is Chrome, Chromium, Edge or Brave on the daemon's machine; set `PU_BROWSER` in the daemon's environment to choose one. Screenshots are saved on the daemon's machine (default `~/.pu/browser/screenshots/`). With `--machine`, pass `--project` and an absolute screenshot path. + ## schedule Manage scheduled tasks. diff --git a/docs/product/browser.md b/docs/product/browser.md new file mode 100644 index 00000000..4b0a152c --- /dev/null +++ b/docs/product/browser.md @@ -0,0 +1,113 @@ +# Browser + +**Maturity: SPECIFIED** | ID Prefix: BROWSER | Dependencies: `architecture/ipc-api.md`, `architecture/daemon-engine.md`, `product/machines.md`, `product/desktop-app.md`, `product/ipad-app.md`, `product/windows-app.md`, `product/cli.md` + +## Purpose + +Give agents and the person directing them one shared web browser per project, running on the machine where the project's agents run. Agents use it to check the pages they build (a dev server on `localhost:3000`) and to do web tasks; the person watches the same tab live in a browser pane and can take over at any moment. Because the browser runs on the project's own machine, `localhost` means the same thing to the agent and to the pane, and a pane works the same whether the project is on this computer or on a machine reached over SSH. + +## Conceptual Model + +- **Project browser** = one headless Chromium per (daemon, project root), started by the daemon on first use and stopped when its last tab closes or the daemon stops. Its profile (cookies, logins, storage) lives in `~/.pu/browser/profiles/-` on that machine and survives restarts. +- **Tab** = a page in the project browser, identified by its DevTools target id. Tabs are shared: any agent in the project, the CLI and every pane can use any tab. Ops that name no tab use the project's most recently opened or used tab. +- **Browser pane** = a pane tab (`SurfaceContent.browser(tabId, url)`) showing one tab: a live screencast plus the person's input. The pane remembers the tab id and its last URL, so it reattaches after an app relaunch and reopens the page if the tab is gone. +- **Driver** = who is in control of a tab: `agent` (default) or `human`. While a person drives, ops that act on the page from anywhere but a viewer stream are refused; reading the page still works. +- **Viewer stream** = a `browser_attach` connection: frames and tab state out, viewer ops in. + +``` +agent in a worktree ── pu browser click e3 ──┐ + ├─► machine's pu-engine ──DevTools pipe (fd 3/4)──► headless Chromium +browser pane (Mac / iPad / Windows) ──────────┘ ▲ (profile per project) + └── over the machine's existing daemon connection (local socket, ssh -L forward, or ssh relay) +``` + +## Research Notes + +**Researched: 2026-11-29.** Chromium's DevTools protocol is available over `--remote-debugging-pipe`: the browser reads NUL-terminated JSON commands on fd 3 and writes replies and events on fd 4. Unlike `--remote-debugging-port`, this opens no TCP port, so no other local user or process can drive the browser; only the daemon holds the pipe ends, which keeps the daemon socket's same-user boundary (IPC-004, MACH-002). When the pipe closes (the daemon exits or is killed) Chromium exits. Flat session mode (`Target.attachToTarget {flatten: true}`) multiplexes every tab over the one pipe. `Page.startScreencast` emits JPEG frames only when the page changes, and waits for each `Page.screencastFrameAck` before the next. `Accessibility.getFullAXTree` gives a compact page outline whose nodes carry backend DOM ids, which `DOM.getContentQuads` / `DOM.resolveNode` turn back into click points and elements. Verified end to end against Chromium 1243 (`crates/pu-engine/tests/browser.rs`). + +Alternatives considered: +- *Browser in the app, driven remotely by agents* (a WKWebView or WebView2 per pane, with agent commands relayed to the app): needs the app open for agents to browse, gives each viewer a different browser, and WKWebView has no DevTools protocol. Rejected. +- *Forward the machine's localhost ports to the viewing device and browse there*: solves viewing, not agent use, and puts dev servers on a second machine's loopback. Rejected for the core; a later port relay can still offer "open in my browser". +- *VNC / WebRTC streaming of a full browser window*: a second protocol and transport beside the daemon's (MACH-002). Rejected. + +## Decisions + +! [BROWSER-001] The browser runs on the daemon's machine, one Chromium per project, driven over `--remote-debugging-pipe`. No DevTools port is ever opened. +! [BROWSER-002] Everything goes through the daemon protocol: agents use `Request::Browser`, panes use `Request::BrowserAttach` on the same connection the app already holds to that machine. Remote projects need no new transport. +! [BROWSER-003] The browser is found as `PU_BROWSER`, else Chrome, Chromium, Edge or Brave in their usual install locations and on `PATH`, else `~/.pu/browser/chrome/chrome`. PurePoint does not ship a browser. +! [BROWSER-004] Frames are JPEG (quality 70) at the viewer's pixel density, sent with ack-based flow control: at most two frames un-acknowledged per viewer, newer frames replacing undrawn ones, so a slow link drops frames instead of queueing them. +! [BROWSER-005] The viewport follows the pane: a viewer's `resize` sets the page's CSS viewport and device scale, so pages lay out for the pane and clicks map 1:1. With several viewers the last resize wins. +! [BROWSER-006] A person can take control of a tab (`driver: human`); agent ops that act on the page are refused with `BROWSER_HUMAN_DRIVING` until they hand it back. Viewer input is always accepted. +! [BROWSER-007] Agents address elements by `[ref=eN]` from the latest `snapshot`, an indented accessibility outline. Refs are invalidated by the next snapshot and by top-level navigation. +! [BROWSER-008] JavaScript dialogs are accepted automatically and recorded in the console, so neither agents nor viewers can be stuck behind one. +! [BROWSER-009] Pages opened by another page (`window.open`, `target=_blank`) become tabs of the project browser. +! [BROWSER-010] Closing the last pane tab that shows a browser tab closes that tab; closing a project's last tab stops its browser. +! [BROWSER-011] A remote agent's terminal links to loopback addresses (`localhost`, `*.localhost`, `127.0.0.1`, `0.0.0.0`, `[::1]`) open in a browser pane of that agent's project, because they name the agent's machine. A local agent's links open in the system browser as before. +! [BROWSER-012] The browser needs a Unix daemon (macOS or Linux). A Windows daemon answers `BROWSER_UNSUPPORTED`; the Windows app can still show browser panes for projects on Mac and Linux machines. + +## Requirements + +### Daemon and agents +- Given `pu browser open localhost:3000` in a project with no browser running, should start the project's browser, open a tab on `http://localhost:3000`, wait up to 15 s for it to load, and print the tab id, URL and title. +- Given `pu browser tabs` with no browser running, should print no tabs and not start one. +- Given `pu browser snapshot`, should print the page as an indented outline with `[ref=eN]` on links, buttons, fields and other interactive elements. +- Given `pu browser click e3` after a snapshot, should scroll the element into view and click its center. +- Given `pu browser type e5 "text"`, should focus the element, replace its contents with the text, and with `--submit` press Enter. +- Given a ref from before the latest snapshot or navigation, should fail with `BROWSER_REF_NOT_FOUND` and ask for a new snapshot. +- Given `pu browser wait --text "Saved"`, should succeed once the text is on the page, or fail with `BROWSER_TIMEOUT` after the timeout (default 10 s, max 120 s). +- Given `pu browser screenshot [path]`, should save a PNG on the daemon's machine (a relative path resolves against the CLI's directory; with `--machine` it must be absolute) and print its path. +- Given `pu browser console`, should print console messages, uncaught exceptions and dialogs since the tab opened, oldest first. +- Given `pu browser open URL --show`, should also ask the app to show the tab in a browser pane (`GridCommand::OpenBrowser`). +- Given an agent in a worktree, should use the project's browser (the CLI resolves the project from `PU_PROJECT_ROOT`). +- Given no Chrome, Chromium or Edge on the machine, should fail with `BROWSER_NOT_FOUND` naming `PU_BROWSER`. +- Given the daemon is killed, should leave no browser processes behind. +- Given a daemon restart, should start a new browser on the same profile, so logins persist. + +### Panes +- Given "Open Browser" in an empty tab, should open a new tab of the project's browser and focus the address field. +- Given a browser pane on screen, should show the tab live, with back, forward, reload, the address and who is driving. +- Given a pane resize, should resize the page's viewport to match, at the display's pixel density. +- Given clicks, drags, scrolling, typing, paste (Cmd/Ctrl+V) and copy (Cmd/Ctrl+C) in the pane, should apply them to the page. +- Given "Take Control", should refuse agents' page actions until "Hand Back". +- Given a pane whose tab was closed elsewhere, should say so and offer to reopen it on its last page. +- Given an app relaunch, should reattach each browser pane to its tab, or reopen its last page if the tab is gone. +- Given a project on a remote machine, should behave the same, running the browser on that machine. +- Given `pu browser open --show` while the tab is already in a pane, should select that pane tab instead of opening another. +- Given the pane is not on screen (another tab selected), should stop the screencast for it. + +## Sum Sheet + +``` +browser(project) := Chromium(profile(project)) on machine(project), lazily started +tab ∈ browser(project).tabs; default tab := most recently used +op(agent, tab) acts_on_page ∧ driver(tab) = human → BROWSER_HUMAN_DRIVING +op(viewer, tab) → always applied +viewer: frames with ≤ 2 un-acked; newest replaces undrawn +pane(surface) := (tabId?, lastUrl?) ; tab gone → open(lastUrl) +closed(last pane showing tab) → close(tab) ; tabs(project) = ∅ → stop(browser) +remote terminal link ∧ loopback(link) → open in browser pane of project +``` + +## Interfaces + +- Protocol 15: `Request::Browser { project_root, op: BrowserOp }`, `Request::BrowserAttach { project_root, tab_id? }`; responses `browser_tab`, `browser_tabs`, `browser_snapshot`, `browser_screenshot`, `browser_console`, `browser_eval_result`, `browser_attached`, `browser_frame`, `browser_tab_state`, `browser_tab_closed`; `GridCommand::OpenBrowser`. See [ipc-api.md](../reference/ipc-api.md#browser). +- CLI: `pu browser open|tabs|close|goto|back|forward|reload|snapshot|click|type|press|scroll|screenshot|console|eval|wait|control`, with `--tab`, `--json` and the global `--machine`/`--project`. See [cli-reference.md](../guide/cli-reference.md#browser). +- Files on the daemon's machine: `~/.pu/browser/profiles/`, `~/.pu/browser/screenshots/`, `~/.pu/browser/chromium.log`. +- Code: `crates/pu-engine/src/browser/` (manager, DevTools client, launcher, snapshot outline, keys), `crates/pu-engine/src/ipc_server/streams.rs` (`handle_browser_stream`), `crates/pu-cli/src/commands/browser.rs`; macOS/iPad `State/BrowserSession.swift`, `Views/Browser/`; Windows `apps/purepoint-windows`. + +## Edge Cases + +- **Stale profile lock.** A daemon killed with `SIGKILL` can leave `SingletonLock` in the profile; the daemon removes it before launching, since a browser it started cannot outlive the pipe. +- **Running as root** (containers, some servers): Chromium refuses its sandbox, so the daemon adds `--no-sandbox` only when its effective uid is 0. +- **Slow pages.** Navigation waits up to 15 s for the load event and then reports the page as it is; `wait` is there for anything slower. +- **Same-document navigation** (`#fragment`): has no load event; navigation returns immediately. +- **Several viewers** of one tab share one screencast; the last resize sets the viewport for all. +- **Keyboard shortcuts.** Cmd/Ctrl+C and +V are handled by the pane (clipboard on the viewing device); other chords are sent to the page with their modifiers, so editing shortcuts follow the browser's platform (Ctrl on a Linux machine). IME composition is sent as committed text. +- **No audio or video capture**, file pickers and downloads are not surfaced in v1. + +## Open Questions + +- Per-project site allowlist for agent navigation, with approval in the pane. +- Gating `eval` behind approval for agents. +- A "open in my browser" port relay for pages a person wants in their own browser. +- Surfacing downloads and file choosers. diff --git a/docs/product/cross-reference-matrix.md b/docs/product/cross-reference-matrix.md index 084f780d..62e56810 100644 --- a/docs/product/cross-reference-matrix.md +++ b/docs/product/cross-reference-matrix.md @@ -20,3 +20,4 @@ Maps every product domain to its architecture dependencies, API operations, stor | Linux Phone Host | Distribution, Desktop App Integration | Point Guard admin (status, auth.*, pairing.*, devices.*), daemon ops via the bridge | `${XDG_STATE_HOME}/purepoint/point-guard/`, `~/.pi/agent/`, `~/.pu/pointguard//` | `pu phone` install/uninstall/start/stop/restart/status/run/pair/devices/grant/rename/revoke/login/model/cwd | iOS Connections (host kind) | | iPad App | Desktop App Integration, IPC & API (via Machines, Desktop App, Point Guard Setup) | Every Desktop App and Machines operation, over SSH exec channels running `pu daemon proxy`; Health for machine state and Start daemon; Point Guard bridge v1 over pinned WSS | iPad container `Application Support/PurePoint/machines.json`; Keychain `PurePoint.SSHIdentity.v1`, `PurePoint.HostKeyPin.v1`, `PiMobile.TrustedHost.v1` | `pu daemon proxy` (run remotely over SSH), `pu health` (Start daemon) | All Desktop App views via `purepoint-ipad` (UIKit twins), Add Machine (device key, host-key trust), remote folder picker, Point Guard pairing (QR, saved Macs) | | Windows App | Daemon Engine, IPC & API, Distribution, Desktop App Integration (via Machines, Desktop App, iPad App) | Every Desktop App and Machines operation over the private named pipe `\\.\pipe\purepoint--daemon` (local) or `ssh.exe pu daemon proxy` (remote); Health for daemon lifecycle and machine state; protocol 14 unchanged | `%USERPROFILE%\.pu\` (`daemon.sock.{pid,lock,projects.json}`, `daemon.log`, `machines.json`, `bin\pu.exe`, `bin\pu-engine.exe`); HKCU `Run` value `PurePoint Engine`; Tauri app data (windows, selection, preferences, key bindings); Credential Manager `PurePoint.PointGuard.Pairing` | Every command on Windows; `pu daemon install/uninstall/status` (Run value), `pu daemon proxy`, `--machine` via `ssh.exe` | All Desktop App views in `apps/purepoint-windows` (Tauri 2 + React + xterm.js), custom title bar, Tauri folder picker, toasts and taskbar badge, updater | +| Browser | Daemon Engine, IPC & API (via Machines, Desktop App) | Browser (open, list, close, navigate, history, snapshot, click, type, press, scroll, screenshot, console, eval, wait, control, input, resize), BrowserAttach (frames, tab state), GridCommand `open_browser` | `~/.pu/browser/profiles/-/`, `~/.pu/browser/screenshots/`, `~/.pu/browser/chromium.log` on the daemon's machine; pane tabs in `.pu/workspaces.json` (`kind: browser`, `browserTab`, `url`) | `pu browser open/tabs/close/goto/back/forward/reload/snapshot/click/type/press/scroll/screenshot/console/eval/wait/control` | Browser pane (BrowserPaneView, BrowserCanvas) on Mac, iPad and Windows; Open Browser in empty tabs | diff --git a/docs/reference/ipc-api.md b/docs/reference/ipc-api.md index eaa4d034..1ef78736 100644 --- a/docs/reference/ipc-api.md +++ b/docs/reference/ipc-api.md @@ -9,7 +9,7 @@ The PurePoint daemon communicates with clients (CLI, macOS app, Windows app) via | Socket path | `~/.pu/daemon.sock` (Unix: mode 0600; the daemon keeps `~/.pu` at 0700) | | Windows endpoint | `\\.\pipe\purepoint--daemon`, where `` is the first 8 bytes of SHA-256 of the normalized socket path. The socket path is not created but still names the `.pid`, `.lock` and `.projects.json` siblings. Protected owner-only DACL, remote clients rejected ([windows-app.md](../product/windows-app.md) WINAPP-003/004) | | Access | Only processes running as the daemon's user. Unix: every accepted connection's peer uid must equal the daemon's effective uid, or it is closed. Windows: the client token's user SID must equal the daemon's, and clients refuse a server whose SID differs or whose PID is not the live PID in `daemon.sock.pid` | -| Protocol version | 14 | +| Protocol version | 15 | | Framing | Newline-delimited JSON (one JSON object per line) | | Max message size | 1 MB (1,048,576 bytes); a longer line gets one `FRAME_TOO_LARGE` error and the connection is closed | | First request | Must arrive within 30 seconds of connecting, or the connection is closed | @@ -461,9 +461,52 @@ GridCommand variants: | `close_tab` | `leaf_id`?, `tab_id`? | Close a tab (default: the pane's active tab) | | `move_tab` | `tab_id`, `to_leaf`, `index`? | Move a tab to another pane at 1-based `index` (default: append) | | `break_tab` | `tab_id`?, `axis` | Move a tab into a new pane split off its pane (default: focused pane's active tab, axis `"v"`) | +| `open_browser` | `leaf_id`?, `browser_tab` | Open a tab after the pane's active tab showing browser tab `browser_tab` (or select the tab already showing it) | `?` marks optional fields. Every command except `get_layout` also takes an optional `workspace_id`; when it is omitted, the command applies to the workspace on screen. An omitted `leaf_id` targets the focused pane; `tab_id` is the stable surface id within the workspace (not its position). `set_agent.leaf_id` became optional in protocol v6. The daemon does not model layout: mutation commands return `ok` and are rebroadcast unchanged as `grid_event` to `subscribe_grid` streams, where the macOS app applies them. +## Browser + +Each project has a headless Chromium on the daemon's machine (`docs/product/browser.md`), started on first use. Ops are `{"type": "browser", "project_root": "/path", "op": {"action": ..., ...}}`. Every op except `open` and `list` takes an optional `tab_id`; without one it acts on the project's most recently opened or used tab. + +| `action` | Fields | Response | +|---|---|---| +| `open` | `url`? | `browser_tab` (starts the browser; waits up to 15 s for the page) | +| `list` | | `browser_tabs` (never starts the browser) | +| `close` | | `ok` (the last tab stops the browser) | +| `navigate` | `url` | `browser_tab` after the page loads (bare hosts get `http://` if local, else `https://`) | +| `history` | `direction`: `back`/`forward`/`reload` | `browser_tab` | +| `snapshot` | | `browser_snapshot` `{tab, tree}`: an indented accessibility outline; interactive elements carry `[ref=eN]` | +| `click` | `ref` | `ok` | +| `type` | `ref`?, `text`, `submit`? | `ok`; replaces the element's contents (or types into the focused element) | +| `press` | `key` (DOM name or chord: `Enter`, `Shift+Tab`, `Control+a`) | `ok` | +| `scroll` | `dx`?, `dy` | `ok` | +| `screenshot` | `path`? (absolute), `full_page`? | `browser_screenshot` `{tab_id, path}` (PNG on the daemon's machine) | +| `console` | `clear`? | `browser_console` `{tab_id, entries: [{level, text, timestamp_ms}]}` | +| `eval` | `expression` | `browser_eval_result` `{tab_id, value}` (promises awaited) | +| `wait` | `text`?, `timeout_ms`? | `browser_tab`, or `BROWSER_TIMEOUT` | +| `control` | `driver`: `agent`/`human` | `browser_tab` | +| `input` | `event` | `ok` (viewer input, see below) | +| `resize` | `width`, `height`, `scale`? | `ok` (CSS viewport and device scale) | +| `frame_ack` | `seq` | attach streams only | + +A tab is `{tab_id, url, title, loading, driver, can_go_back, can_go_forward, width, height}`. Input events are tagged by `kind`: `mouse` `{action: down|up|move, x, y, button?: none|left|middle|right, click_count?, modifiers?}`, `wheel` `{x, y, dx, dy, modifiers?}`, `key` `{action: down|up, key, code?, text?, modifiers?}` and `text` `{text}`. Coordinates are CSS pixels; modifier bits are Alt=1, Ctrl=2, Meta=4, Shift=8. + +Errors: `BROWSER_NOT_FOUND` (no Chrome/Chromium/Edge; set `PU_BROWSER`), `BROWSER_LAUNCH_FAILED`, `BROWSER_UNSUPPORTED` (Windows daemons), `BROWSER_NO_TAB`, `BROWSER_TAB_NOT_FOUND`, `BROWSER_REF_NOT_FOUND`, `BROWSER_NOT_VISIBLE`, `BROWSER_HUMAN_DRIVING` (a person drives the tab), `BROWSER_NAVIGATION_FAILED`, `BROWSER_EVAL_FAILED`, `BROWSER_TIMEOUT`, `BROWSER_INVALID_PATH`, `BROWSER_CLOSED`, `BROWSER_ERROR`. + +### BrowserAttach + +Watch and drive a tab, as a browser pane does. + +**Request**: `{"type": "browser_attach", "project_root": "/path", "tab_id": "…"}` (`tab_id` optional) + +**Response**: `{"type": "browser_attached", "tab": {...}}`, then the stream: +- `{"type": "browser_frame", "tab_id", "seq", "data", "width", "height"}`: a base64 JPEG of the page at the viewer's pixel density; `width`/`height` are the CSS viewport it shows. Ack each drawn frame with a `frame_ack` op. At most two frames are sent un-acknowledged; newer frames replace undrawn ones. +- `{"type": "browser_tab_state", "tab": {...}}` whenever the URL, title, loading state, history, driver or viewport changes. +- `{"type": "browser_tab_closed", "tab_id"}`, after which the connection returns to request mode. + +The client sends `browser` requests on the same connection. They act as the person at the pane (never refused for `BROWSER_HUMAN_DRIVING`) and default to the attached tab. `input`, `resize` and `frame_ack` are answered only on error; other ops run alongside the stream and their responses arrive between frames. Any line that is not a `browser` request ends the stream. Ops sent anywhere but an attach stream act as an agent. + ## Worktree management ### CreateWorktree diff --git a/docs/spec-system.md b/docs/spec-system.md index 1a335367..6a17c111 100644 --- a/docs/spec-system.md +++ b/docs/spec-system.md @@ -75,6 +75,7 @@ What PurePoint does. Each domain captures behavior, requirements, and interfaces | Linux Phone Host | LPH | SPECIFIED | | iPad App | IPAD | SPECIFIED | | Windows App | WINAPP | SPECIFIED | +| Browser | BROWSER | SPECIFIED | ### Reference (Inventory) Reference material for existing codebases and PurePoint CLI commands. From 5600b12be4fea67709d5f3eaf2069ebed48d4cda Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 22:56:56 +0000 Subject: [PATCH 03/30] test(macos): expect protocol 15 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ2eMMzt56iHuDqpo7z --- apps/purepoint-macos/purepoint-macosTests/MachinesTests.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/purepoint-macos/purepoint-macosTests/MachinesTests.swift b/apps/purepoint-macos/purepoint-macosTests/MachinesTests.swift index 2664b50d..70b98b6c 100644 --- a/apps/purepoint-macos/purepoint-macosTests/MachinesTests.swift +++ b/apps/purepoint-macos/purepoint-macosTests/MachinesTests.swift @@ -315,7 +315,7 @@ struct HealthProbeTests { struct DaemonProjectHostRequestTests { @Test func givenProtocolShouldBeCurrentVersion() { - #expect(DaemonProtocol.version == 14) + #expect(DaemonProtocol.version == 15) } @Test func givenReorderProjectsShouldSendTheWholeOrder() throws { From c01bc0bfcb93c03fbd0280200f71619ccaa7e391 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 22:59:02 +0000 Subject: [PATCH 04/30] feat(browser): stop a project's browser after 30 idle minutes Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ2eMMzt56iHuDqpo7z --- crates/pu-engine/src/browser/mod.rs | 58 +++++++++++++++++++++++++++++ crates/pu-engine/tests/browser.rs | 36 ++++++++++++++++++ docs/product/browser.md | 4 +- 3 files changed, 97 insertions(+), 1 deletion(-) diff --git a/crates/pu-engine/src/browser/mod.rs b/crates/pu-engine/src/browser/mod.rs index 9335064b..e8ece789 100644 --- a/crates/pu-engine/src/browser/mod.rs +++ b/crates/pu-engine/src/browser/mod.rs @@ -34,6 +34,10 @@ use tab::{Tab, Viewport}; const LOAD_TIMEOUT: Duration = Duration::from_secs(15); const DEFAULT_WAIT: Duration = Duration::from_secs(10); const MAX_WAIT: Duration = Duration::from_secs(120); +/// A browser nobody has used or watched for this long is stopped; its panes reopen +/// their last page when shown again, and agents open a new tab. +const IDLE_STOP: Duration = Duration::from_secs(30 * 60); +const IDLE_CHECK: Duration = Duration::from_secs(60); /// Who sent an op. Ops from a viewer's attach stream are the person at the pane. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -94,6 +98,8 @@ pub struct Instance { /// The `about:blank` tab Chromium starts with, closed once a real tab exists. initial_targets: std::sync::Mutex>, screenshots: PathBuf, + /// When an op or viewer last used this browser. + last_used: std::sync::Mutex, } impl Drop for Instance { @@ -109,6 +115,23 @@ impl Drop for Instance { } impl Instance { + fn touch(&self) { + *self.last_used.lock().unwrap_or_else(|e| e.into_inner()) = tokio::time::Instant::now(); + } + + /// Unused for `idle` with nobody watching any of its tabs. + fn is_idle(&self, idle: Duration) -> bool { + if self.tab_list().iter().any(|t| t.has_viewers()) { + self.touch(); + return false; + } + self.last_used + .lock() + .unwrap_or_else(|e| e.into_inner()) + .elapsed() + >= idle + } + fn tab_list(&self) -> Vec> { self.tabs .lock() @@ -346,6 +369,7 @@ async fn refresh_history(cdp: &Cdp, tab: &Tab) { pub struct BrowserManager { instances: Mutex>>, base_dir: Option, + idle_stop: Duration, } impl Default for BrowserManager { @@ -364,9 +388,16 @@ impl BrowserManager { Self { instances: Mutex::new(HashMap::new()), base_dir, + idle_stop: IDLE_STOP, } } + /// Stop a project's browser after `idle` unused instead of 30 minutes. + pub fn with_idle_stop(mut self, idle: Duration) -> Self { + self.idle_stop = idle; + self + } + /// Stops every project's browser. pub async fn shutdown(&self) { self.instances.lock().await.clear(); @@ -492,14 +523,17 @@ impl BrowserManager { tabs: std::sync::Mutex::new(IndexMap::new()), initial_targets: std::sync::Mutex::new(initial), screenshots, + last_used: std::sync::Mutex::new(tokio::time::Instant::now()), }); tokio::spawn(pump(Arc::downgrade(&instance), cdp, events)); + tokio::spawn(stop_when_idle(Arc::downgrade(&instance), self.idle_stop)); Ok(instance) } /// The tab a new attach stream will show. Never starts the browser. pub async fn attach(&self, root: &str, tab_id: Option<&str>) -> Result<(Arc, Arc)> { let instance = self.running(root).await?; + instance.touch(); let tab = instance.resolve(tab_id)?; Ok((instance.cdp.clone(), tab)) } @@ -522,6 +556,7 @@ impl BrowserManager { } BrowserOp::Open { url } => { let instance = self.get_or_launch(root).await?; + instance.touch(); let tab = instance.create_tab().await?; if let Some(url) = url.filter(|u| !u.trim().is_empty()) { navigate(&instance.cdp, &tab, &url).await?; @@ -549,6 +584,7 @@ impl BrowserManager { } let instance = self.running(root).await?; + instance.touch(); let tab = instance.resolve(op.tab_id())?; if op.acts_on_page() && caller == Caller::Agent && tab.driver() == BrowserDriver::Human { return Err(BrowserError::new( @@ -699,6 +735,28 @@ impl BrowserManager { } } +/// Stops the browser once it has gone unused, by ending its process group: the +/// pump then closes its tabs, and the next op starts a fresh browser. +async fn stop_when_idle(instance: Weak, idle: Duration) { + loop { + tokio::time::sleep(IDLE_CHECK.min(idle)).await; + let Some(instance) = instance.upgrade() else { + return; + }; + if !instance.cdp.is_alive() { + return; + } + if instance.is_idle(idle) { + tracing::info!(pid = instance.pid, "stopping idle browser"); + #[cfg(unix)] + if let Some(pid) = instance.pid { + launch::unix::stop_group(pid); + } + return; + } + } +} + async fn pump( instance: Weak, cdp: Arc, diff --git a/crates/pu-engine/tests/browser.rs b/crates/pu-engine/tests/browser.rs index ba3ba483..0e4f4297 100644 --- a/crates/pu-engine/tests/browser.rs +++ b/crates/pu-engine/tests/browser.rs @@ -460,3 +460,39 @@ async fn given_an_agent_and_a_viewer_should_share_one_live_tab() { )); engine.kill_all_sessions(Duration::from_millis(10)).await; } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn given_an_unused_browser_should_stop_it_and_start_fresh_on_next_use() { + if !have_browser() { + eprintln!("skipping: no Chrome/Chromium on this machine (set PU_BROWSER)"); + return; + } + use pu_engine::browser::{BrowserManager, Caller}; + let tmp = TempDir::new().unwrap(); + let manager = BrowserManager::new(Some(tmp.path().join("browser"))) + .with_idle_stop(Duration::from_secs(1)); + let open = || BrowserOp::Open { + url: Some("about:blank".into()), + }; + assert!(matches!( + manager.handle("/p", open(), Caller::Agent).await, + Response::BrowserTab { .. } + )); + let deadline = tokio::time::Instant::now() + Duration::from_secs(10); + loop { + let tabs = manager.handle("/p", BrowserOp::List, Caller::Agent).await; + if matches!(&tabs, Response::BrowserTabs { tabs } if tabs.is_empty()) { + break; + } + assert!( + tokio::time::Instant::now() < deadline, + "idle browser kept running: {tabs:?}" + ); + tokio::time::sleep(Duration::from_millis(200)).await; + } + assert!(matches!( + manager.handle("/p", open(), Caller::Agent).await, + Response::BrowserTab { .. } + )); + manager.shutdown().await; +} diff --git a/docs/product/browser.md b/docs/product/browser.md index 4b0a152c..d8da4648 100644 --- a/docs/product/browser.md +++ b/docs/product/browser.md @@ -8,7 +8,7 @@ Give agents and the person directing them one shared web browser per project, ru ## Conceptual Model -- **Project browser** = one headless Chromium per (daemon, project root), started by the daemon on first use and stopped when its last tab closes or the daemon stops. Its profile (cookies, logins, storage) lives in `~/.pu/browser/profiles/-` on that machine and survives restarts. +- **Project browser** = one headless Chromium per (daemon, project root), started by the daemon on first use and stopped when its last tab closes, after 30 idle minutes, or when the daemon stops. Its profile (cookies, logins, storage) lives in `~/.pu/browser/profiles/-` on that machine and survives restarts. - **Tab** = a page in the project browser, identified by its DevTools target id. Tabs are shared: any agent in the project, the CLI and every pane can use any tab. Ops that name no tab use the project's most recently opened or used tab. - **Browser pane** = a pane tab (`SurfaceContent.browser(tabId, url)`) showing one tab: a live screencast plus the person's input. The pane remembers the tab id and its last URL, so it reattaches after an app relaunch and reopens the page if the tab is gone. - **Driver** = who is in control of a tab: `agent` (default) or `human`. While a person drives, ops that act on the page from anywhere but a viewer stream are refused; reading the page still works. @@ -43,6 +43,7 @@ Alternatives considered: ! [BROWSER-009] Pages opened by another page (`window.open`, `target=_blank`) become tabs of the project browser. ! [BROWSER-010] Closing the last pane tab that shows a browser tab closes that tab; closing a project's last tab stops its browser. ! [BROWSER-011] A remote agent's terminal links to loopback addresses (`localhost`, `*.localhost`, `127.0.0.1`, `0.0.0.0`, `[::1]`) open in a browser pane of that agent's project, because they name the agent's machine. A local agent's links open in the system browser as before. +! [BROWSER-013] A project's browser that no op has used and no pane has watched for 30 minutes is stopped. Its panes reopen their last page when shown again, and agents open a new tab (`BROWSER_NO_TAB` tells them to). ! [BROWSER-012] The browser needs a Unix daemon (macOS or Linux). A Windows daemon answers `BROWSER_UNSUPPORTED`; the Windows app can still show browser panes for projects on Mac and Linux machines. ## Requirements @@ -62,6 +63,7 @@ Alternatives considered: - Given no Chrome, Chromium or Edge on the machine, should fail with `BROWSER_NOT_FOUND` naming `PU_BROWSER`. - Given the daemon is killed, should leave no browser processes behind. - Given a daemon restart, should start a new browser on the same profile, so logins persist. +- Given a browser unused and unwatched for 30 minutes, should stop it; the next `open` starts it again. ### Panes - Given "Open Browser" in an empty tab, should open a new tab of the project's browser and focus the address field. From 51a04d913ea5a8bf9316287807c921e432bad688 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 23:02:14 +0000 Subject: [PATCH 05/30] fix(macos): harden browser session reconnect and frame decode Ignore stream errors from a stopped session, close only the stream a session attached, and hand decoded frames back in a Sendable box. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ2eMMzt56iHuDqpo7z --- .../State/BrowserSession.swift | 31 +++++++++++++------ 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/apps/purepoint-macos/purepoint-macos/State/BrowserSession.swift b/apps/purepoint-macos/purepoint-macos/State/BrowserSession.swift index c2b48131..b5ef4da3 100644 --- a/apps/purepoint-macos/purepoint-macos/State/BrowserSession.swift +++ b/apps/purepoint-macos/purepoint-macos/State/BrowserSession.swift @@ -83,6 +83,7 @@ final class BrowserSession { @ObservationIgnored private var viewport: (width: Int, height: Int, scale: Double)? @ObservationIgnored private var pendingCopy = false @ObservationIgnored private var noticeTask: Task? + @ObservationIgnored private var attachedStream: (any DaemonByteStream)? init( client: DaemonClient, projectRoot: String, tabId: String?, url: String?, @@ -106,7 +107,10 @@ final class BrowserSession { func stop() { streamTask?.cancel() streamTask = nil - Task { [writer] in await writer.close() } + // The stream this session attached; a reopen's new stream is never closed by it. + let stream = attachedStream + attachedStream = nil + Task { [writer] in await writer.close(stream) } } /// Opens a fresh tab on the last page, after the tab closed. @@ -180,8 +184,10 @@ final class BrowserSession { phase = .failed(BrowserSession.describe(code: code, message: message)) return } catch { + // A stopped session's stream fails as it closes; that is not a reconnect. + guard !Task.isCancelled else { return } #if os(iOS) - if await AppActivity.shared.isInBackground { + if AppActivity.shared.isInBackground { await AppActivity.shared.untilForeground() failures = 0 continue @@ -209,6 +215,7 @@ final class BrowserSession { } let (stream, reader) = try await client.connect() await writer.use(stream) + attachedStream = stream defer { Task { [writer] in await writer.close(stream) } } try await DaemonClient.write(.browserAttach(projectRoot: projectRoot, tabId: tabId), to: stream) @@ -237,8 +244,10 @@ final class BrowserSession { let line = try await reader.readLine() switch DaemonClient.parse(line) { case .browserFrame(let payload): - let image = await Task.detached(priority: .userInitiated) { BrowserSession.decode(payload.data) }.value - if let image { + let decoded = await Task.detached(priority: .userInitiated) { + DecodedFrame(image: BrowserSession.decode(payload.data)) + }.value + if let image = decoded.image { frame = image frameSize = CGSize(width: payload.width, height: payload.height) } @@ -290,6 +299,11 @@ final class BrowserSession { } } +/// A decoded frame handed back from the decoding task; a CGImage is immutable. +nonisolated struct DecodedFrame: @unchecked Sendable { + let image: CGImage? +} + nonisolated enum BrowserSessionError: Error, LocalizedError { case daemon(String, String) case unexpected @@ -318,11 +332,10 @@ actor BrowserStreamWriter { try? await DaemonClient.write(request, to: stream) } - /// Closes `stream` if it is still the current one (or the current one, given none). + /// Closes `which` (or, given none, the current stream), forgetting it if it is current. func close(_ which: (any DaemonByteStream)? = nil) { - guard let current = stream else { return } - if let which, which !== current { return } - current.close() - stream = nil + guard let target = which ?? stream else { return } + target.close() + if stream === target { stream = nil } } } From 49d6f06ebbe7b1693e795768509e40cc0a145838 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 23:21:35 +0000 Subject: [PATCH 06/30] feat(win-app): browser pane Ports the macOS browser pane to the Windows app: a browser surface kind persisted in the shared workspaces.json shape, a Tauri backend session that holds the browser_attach stream on the local daemon or a machine's ssh relay (reopening lost tabs on their last page), and a React pane with toolbar, canvas frames acked after drawing, pointer/wheel/key input, resize to the pane, paste/copy and Take Control. Grid open_browser, Open Browser in empty tabs, close hook, and remote loopback terminal links open in a browser pane. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ2eMMzt56iHuDqpo7z --- .../src-tauri/src/browser/mod.rs | 247 +++++++++ .../src-tauri/src/browser/session.rs | 385 +++++++++++++ .../src-tauri/src/browser/session_tests.rs | 363 ++++++++++++ apps/purepoint-windows/src-tauri/src/lib.rs | 14 +- .../ui/src/model/browser.test.ts | 212 +++++++ .../purepoint-windows/ui/src/model/browser.ts | 302 ++++++++++ .../ui/src/model/workspace.ts | 15 +- .../ui/src/model/workspacePersistence.test.ts | 35 +- .../ui/src/model/workspacePersistence.ts | 19 +- .../ui/src/protocol/protocol.test.ts | 2 +- .../ui/src/services/attach.ts | 2 +- .../ui/src/services/browser.ts | 78 +++ .../ui/src/services/daemonConnection.ts | 12 + .../ui/src/state/browserSession.test.ts | 267 +++++++++ .../ui/src/state/browserSession.ts | 316 +++++++++++ .../ui/src/state/gridCommands.test.ts | 103 ++++ .../src/state/workspaceRegistry.tabs.test.ts | 2 + .../ui/src/state/workspaceRegistry.ts | 77 +++ .../views/browser/BrowserPaneView.test.tsx | 145 +++++ .../ui/src/views/browser/BrowserPaneView.tsx | 521 ++++++++++++++++++ .../ui/src/views/browser/browser.css | 163 ++++++ .../ui/src/views/panegrid/PaneCellView.tsx | 104 +++- .../ui/src/views/panegrid/PaneTabBar.tsx | 5 + .../ui/src/views/panegrid/paneGrid.test.tsx | 19 + .../ui/src/views/panegrid/panegrid.css | 15 + .../ui/src/views/shell/bootstrap.test.ts | 24 +- .../ui/src/views/shell/bootstrap.ts | 20 + .../ui/src/views/terminal/terminalPaneView.ts | 3 + .../ui/src/views/terminal/terminals.test.ts | 23 + .../ui/src/views/terminal/terminals.ts | 21 + 30 files changed, 3493 insertions(+), 21 deletions(-) create mode 100644 apps/purepoint-windows/src-tauri/src/browser/mod.rs create mode 100644 apps/purepoint-windows/src-tauri/src/browser/session.rs create mode 100644 apps/purepoint-windows/src-tauri/src/browser/session_tests.rs create mode 100644 apps/purepoint-windows/ui/src/model/browser.test.ts create mode 100644 apps/purepoint-windows/ui/src/model/browser.ts create mode 100644 apps/purepoint-windows/ui/src/services/browser.ts create mode 100644 apps/purepoint-windows/ui/src/state/browserSession.test.ts create mode 100644 apps/purepoint-windows/ui/src/state/browserSession.ts create mode 100644 apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.test.tsx create mode 100644 apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.tsx create mode 100644 apps/purepoint-windows/ui/src/views/browser/browser.css create mode 100644 apps/purepoint-windows/ui/src/views/terminal/terminals.test.ts diff --git a/apps/purepoint-windows/src-tauri/src/browser/mod.rs b/apps/purepoint-windows/src-tauri/src/browser/mod.rs new file mode 100644 index 00000000..ab731706 --- /dev/null +++ b/apps/purepoint-windows/src-tauri/src/browser/mod.rs @@ -0,0 +1,247 @@ +//! Browser panes: live views of the project's headless browser (protocol 15). +//! +//! - `session`: the stream half of `State/BrowserSession.swift`, one daemon connection per pane. +//! +//! The browser runs on the project's daemon's machine. A local project's pane talks to this +//! user's daemon; a remote project's pane to its machine's daemon through the same ssh relay +//! client its terminals use ([`MachineClients`]), so a remote browser works exactly like a +//! remote terminal. +//! +//! Tauri surface (front end: `ui/src/services/browser.ts`): `browser_open` returns a session id +//! and streams every [`session::BrowserEvent`] over the caller's `Channel` as JSON, in stream +//! order. Frames stay the daemon's base64 JPEG strings (`frame.data`): the page decodes them +//! straight into an image, so the backend never decodes and re-encodes them. `browser_send` +//! writes one `BrowserOp` (a protocol `BrowserOp` JSON object; a missing `tab_id` means the +//! session's tab) on the session's stream, and `browser_close` ends the session. One-shot +//! ops outside a stream (closing a tab whose last pane closed) go through `daemon_request` / +//! `machine_request` like any other request. + +pub mod session; + +use std::collections::HashMap; +use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; +use std::sync::{Arc, Mutex, Weak}; + +use pu_core::protocol::BrowserOp; +use tauri::State; +use tauri::ipc::{Channel, InvokeResponseBody}; + +use crate::daemon::DaemonState; +use crate::daemon::client::{DaemonClient, DaemonError}; +use crate::daemon::machine::MachineClients; +use session::{BrowserEvent, BrowserOptions, BrowserSession, BrowserSink}; + +type Sessions = HashMap>; + +fn lock(sessions: &Mutex) -> std::sync::MutexGuard<'_, Sessions> { + sessions.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// A Tauri channel as a [`BrowserSink`]. As with terminal sessions, the first send that fails +/// (the page reloaded or its renderer crashed) removes the session, which closes its stream. +pub struct ChannelSink { + channel: Channel, + failed: AtomicBool, + id: u32, + sessions: Weak>, +} + +impl ChannelSink { + fn new(channel: Channel, id: u32, sessions: &Arc>) -> Self { + Self { + channel, + failed: AtomicBool::new(false), + id, + sessions: Arc::downgrade(sessions), + } + } + + fn failed(&self) -> bool { + self.failed.load(Ordering::Acquire) + } +} + +impl BrowserSink for ChannelSink { + fn event(&self, event: BrowserEvent) { + if self.failed() { + return; + } + let Ok(json) = serde_json::to_string(&event) else { + return; + }; + if self.channel.send(InvokeResponseBody::Json(json)).is_err() + && !self.failed.swap(true, Ordering::AcqRel) + { + let removed = self + .sessions + .upgrade() + .and_then(|sessions| lock(&sessions).remove(&self.id)); + // Dropped outside the lock: this aborts the session's own task. + drop(removed); + } + } +} + +/// Tauri state: the open browser sessions by id. +#[derive(Default)] +pub struct BrowserState { + next_id: AtomicU32, + sessions: Arc>, +} + +impl BrowserState { + /// Starts a session streaming to `channel` and returns its id. + pub fn open( + &self, + client: DaemonClient, + options: BrowserOptions, + channel: Channel, + ) -> u32 { + let id = self.next_id.fetch_add(1, Ordering::Relaxed) + 1; + let sink = Arc::new(ChannelSink::new(channel, id, &self.sessions)); + let session = BrowserSession::start(client, options, sink.clone()); + let mut sessions = lock(&self.sessions); + // The channel may already have failed (a reload raced the open): then never insert. + if !sink.failed() { + sessions.insert(id, Arc::new(session)); + } + id + } + + fn get(&self, id: u32) -> Result, DaemonError> { + lock(&self.sessions) + .get(&id) + .cloned() + .ok_or_else(|| DaemonError::InvalidRequest(format!("no browser session {id}"))) + } + + fn remove(&self, id: u32) -> Option> { + lock(&self.sessions).remove(&id) + } + + /// Closes every session (the page that opened them is gone). Returns how many. + pub fn clear(&self) -> usize { + let drained: Vec<_> = lock(&self.sessions).drain().collect(); + drained.len() + } + + pub fn len(&self) -> usize { + lock(&self.sessions).len() + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } +} + +/// Open a session on `project_root`'s browser (on `machine_id`'s daemon when given), showing +/// `tab_id`, or a new tab on `url` when there is none. Returns the session id. +#[allow(clippy::too_many_arguments)] +#[tauri::command] +pub async fn browser_open( + daemon: State<'_, DaemonState>, + machines: State<'_, MachineClients>, + browser: State<'_, BrowserState>, + project_root: String, + tab_id: Option, + url: Option, + on_event: Channel, + machine_id: Option, +) -> Result { + let client = match machine_id { + Some(machine) => machines.client(&machine), + None => daemon.lifecycle()?.client().clone(), + }; + let options = BrowserOptions::new(project_root, tab_id, url); + Ok(browser.open(client, options, on_event)) +} + +/// Write one op on the session's stream (dropped while it reconnects, except `resize`). +#[tauri::command] +pub fn browser_send( + browser: State<'_, BrowserState>, + session_id: u32, + op: serde_json::Value, +) -> Result<(), DaemonError> { + let op: BrowserOp = + serde_json::from_value(op).map_err(|e| DaemonError::InvalidRequest(e.to_string()))?; + browser.get(session_id)?.send(op); + Ok(()) +} + +/// End the session and its stream. Closing an unknown id is a no-op. The tab stays open. +#[tauri::command] +pub fn browser_close(browser: State<'_, BrowserState>, session_id: u32) { + browser.remove(session_id); +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::Duration; + + #[test] + fn given_events_should_serialize_tagged_with_camel_case_fields() { + let frame = serde_json::to_value(BrowserEvent::Frame { + seq: 4, + data: "/9j/".into(), + width: 1280.0, + height: 800.0, + }) + .unwrap(); + assert_eq!( + frame, + serde_json::json!({"type": "frame", "seq": 4, "data": "/9j/", "width": 1280.0, "height": 800.0}) + ); + let retrying = serde_json::to_value(BrowserEvent::Retrying { + attempt: 2, + delay_ms: 300, + message: "x".into(), + }) + .unwrap(); + assert_eq!( + retrying, + serde_json::json!({"type": "retrying", "attempt": 2, "delayMs": 300, "message": "x"}) + ); + assert_eq!( + serde_json::to_value(BrowserEvent::Closed).unwrap(), + serde_json::json!({"type": "closed"}) + ); + } + + #[test] + fn given_page_ops_should_decode_as_protocol_ops() { + let op: BrowserOp = + serde_json::from_value(serde_json::json!({"action": "frame_ack", "seq": 3})).unwrap(); + assert_eq!( + op, + BrowserOp::FrameAck { + tab_id: None, + seq: 3 + } + ); + } + + #[tokio::test] + async fn given_a_failed_channel_send_should_tear_the_session_down() { + let dir = tempfile::tempdir().unwrap(); + let client = DaemonClient::local(&dir.path().join("pu.sock")).unwrap(); + let browser = BrowserState::default(); + let mut options = BrowserOptions::new("/p", Some("t1".into()), None); + options.fast_delay = Duration::from_millis(10); + let id = browser.open( + client, + options, + Channel::new(|_| Err(tauri::Error::WebviewNotFound)), + ); + for _ in 0..250 { + if browser.is_empty() { + break; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + assert!(browser.is_empty(), "session {id} is still open"); + assert!(browser.get(id).is_err()); + assert_eq!(browser.clear(), 0); + } +} diff --git a/apps/purepoint-windows/src-tauri/src/browser/session.rs b/apps/purepoint-windows/src-tauri/src/browser/session.rs new file mode 100644 index 00000000..ed57f525 --- /dev/null +++ b/apps/purepoint-windows/src-tauri/src/browser/session.rs @@ -0,0 +1,385 @@ +//! Port of `State/BrowserSession.swift`'s stream half: one browser pane's live view of a tab of +//! the project's browser. +//! +//! The browser runs on the project's daemon's machine (this PC's daemon, or a machine's over the +//! ssh relay: the session is handed that daemon's [`DaemonClient`], exactly as a terminal's +//! attach session is). A session holds one `browser_attach` stream, forwards what the daemon +//! streams to a [`BrowserSink`], and writes the pane's ops on the same connection. +//! +//! The loop follows the Swift `run()`/`attachOnce()`: +//! - a session without a tab opens one first (a one-shot `browser {op: open, url: last_url}`); +//! - `BROWSER_TAB_NOT_FOUND` / `BROWSER_NO_TAB` on attach means the tab is gone (the browser or +//! daemon restarted): forget it and open a new one on its last page; +//! - any other daemon error is final ([`BrowserEvent::Failed`]): the person has to act; +//! - `browser_tab_closed` ends the session ([`BrowserEvent::Closed`]); the pane offers Reopen, +//! which is a new session without a tab; +//! - every other failure retries for as long as the session is open: 300 ms apart for the first +//! three, then every 2 s ([`retry_delay`]); the view shows "failed" after the third. +//! +//! Frames are forwarded as they come (base64 JPEG, see [`BrowserEvent::Frame`]); the view acks +//! each one with a `frame_ack` op once it is drawn, so the daemon keeps at most two frames +//! ahead of the screen. Ops sent while no stream is up are dropped, as on the Mac, except the +//! last `resize`, which is replayed on every attach. +//! +//! Difference from Swift: the failure count resets once a stream is live, so a long-lived pane +//! that loses its connection now and then retries fast again each time. + +use std::sync::Arc; +use std::time::Duration; + +use pu_core::protocol::{BrowserOp, BrowserTabInfo, Request, Response}; +use serde::Serialize; +use tokio::sync::mpsc; + +use crate::daemon::client::{DaemonClient, DaemonError, write_request}; + +/// What the session tells the view. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde( + tag = "type", + rename_all = "snake_case", + rename_all_fields = "camelCase" +)] +pub enum BrowserEvent { + /// The tab the session shows, or its new state (url, title, loading, driver, history). + /// `tab` keeps the protocol's snake_case fields (`BrowserTabInfo`). + Tab { tab: BrowserTabInfo }, + /// The stream is attached; frames follow. + Live, + /// One screencast frame: `data` is the daemon's base64 JPEG, unchanged; `width` and + /// `height` are the CSS viewport it shows. Ack `seq` once drawn. + Frame { + seq: u64, + data: String, + width: f64, + height: f64, + }, + /// The answer to an `eval` sent on the stream. + EvalResult { value: serde_json::Value }, + /// A transient problem to show over the page (a failed navigation, a refused action). + Notice { code: String, message: String }, + /// The connection failed; the session tries again after `delay_ms`. + Retrying { + attempt: u32, + delay_ms: u64, + message: String, + }, + /// The tab closed (`pu browser close`, or the browser exited). The session has ended. + Closed, + /// The daemon refused in a way only the person can fix. The session has ended. + Failed { code: String, message: String }, +} + +/// Where a session delivers what the daemon streams. +pub trait BrowserSink: Send + Sync + 'static { + fn event(&self, event: BrowserEvent); +} + +/// How a pane opens its session. +#[derive(Debug, Clone)] +pub struct BrowserOptions { + pub project_root: String, + /// The daemon's tab, `None` to open one. + pub tab_id: Option, + /// The last page shown: a new tab opens on it. + pub url: Option, + /// Waits between attempts (tests shorten them). + pub fast_delay: Duration, + pub slow_delay: Duration, +} + +impl BrowserOptions { + pub fn new( + project_root: impl Into, + tab_id: Option, + url: Option, + ) -> Self { + Self { + project_root: project_root.into(), + tab_id, + url, + fast_delay: Duration::from_millis(300), + slow_delay: Duration::from_secs(2), + } + } +} + +/// Swift's schedule: three quick retries, then every two seconds. +pub const FAST_RETRIES: u32 = 3; + +/// The wait before retry `attempt` (1-based). +pub fn retry_delay(attempt: u32, fast: Duration, slow: Duration) -> Duration { + if attempt <= FAST_RETRIES { fast } else { slow } +} + +/// Whether a daemon error code means the tab is gone and a new one should be opened. +pub fn is_lost_tab(code: &str) -> bool { + code == "BROWSER_TAB_NOT_FOUND" || code == "BROWSER_NO_TAB" +} + +/// Swift `BrowserSession.describe`: the message the pane shows for a final error. +pub fn describe(code: &str, message: &str) -> String { + match code { + "BROWSER_NOT_FOUND" => "No Chrome, Chromium or Edge on the project's machine. Install one there, or set PU_BROWSER for its daemon.".into(), + "BROWSER_UNSUPPORTED" => "The browser runs on macOS and Linux machines.".into(), + _ => message.to_string(), + } +} + +/// Aborts the session task when the session is dropped. +struct TaskGuard(tokio::task::JoinHandle<()>); + +impl Drop for TaskGuard { + fn drop(&mut self) { + self.0.abort(); + } +} + +/// A running browser session. Dropping it closes the connection. +pub struct BrowserSession { + ops: mpsc::UnboundedSender, + _task: TaskGuard, +} + +impl BrowserSession { + /// Start streaming on the current Tokio runtime. + pub fn start( + client: DaemonClient, + options: BrowserOptions, + sink: Arc, + ) -> Self { + let (ops, rx) = mpsc::unbounded_channel(); + let worker = Worker { + client, + project_root: options.project_root, + tab_id: options.tab_id, + last_url: options.url, + fast_delay: options.fast_delay, + slow_delay: options.slow_delay, + viewport: None, + sink, + ops: rx, + }; + Self { + ops, + _task: TaskGuard(tokio::spawn(worker.run())), + } + } + + /// An op on the session's tab (a `None` tab id means it). Dropped while the stream is + /// down, except `resize`, which is kept for the next attach. + pub fn send(&self, op: BrowserOp) { + let _ = self.ops.send(op); + } +} + +/// Why one attach attempt ended. +#[derive(Debug)] +enum End { + /// The session was dropped. + Stopped, + /// The daemon closed the tab. + TabClosed, + /// A final daemon error. + Daemon(String, String), + /// Anything else: try again. `live` when the stream had attached. + Retry { message: String, live: bool }, +} + +struct Worker { + client: DaemonClient, + project_root: String, + tab_id: Option, + last_url: Option, + fast_delay: Duration, + slow_delay: Duration, + /// The last `resize` the pane sent: (width, height, scale). + viewport: Option<(u32, u32, f64)>, + sink: Arc, + ops: mpsc::UnboundedReceiver, +} + +impl Worker { + async fn run(mut self) { + let mut failures = 0; + loop { + match self.attach_once().await { + End::Stopped => return, + End::TabClosed => return self.sink.event(BrowserEvent::Closed), + End::Daemon(code, message) => { + let message = describe(&code, &message); + return self.sink.event(BrowserEvent::Failed { code, message }); + } + End::Retry { message, live } => { + failures = if live { 1 } else { failures + 1 }; + let delay = retry_delay(failures, self.fast_delay, self.slow_delay); + self.sink.event(BrowserEvent::Retrying { + attempt: failures, + delay_ms: delay.as_millis() as u64, + message, + }); + if !self.wait(delay).await { + return; + } + } + } + } + } + + /// Sleep between attempts, still taking ops (only a resize is kept). False once stopped. + async fn wait(&mut self, delay: Duration) -> bool { + let sleep = tokio::time::sleep(delay); + tokio::pin!(sleep); + loop { + tokio::select! { + _ = &mut sleep => return true, + op = self.ops.recv() => match op { + None => return false, + Some(op) => self.remember(&op), + }, + } + } + } + + fn remember(&mut self, op: &BrowserOp) { + if let BrowserOp::Resize { + width, + height, + scale, + .. + } = op + { + self.viewport = Some((*width, *height, *scale)); + } + } + + /// Swift `adopt`: the tab the stream shows, and its last real page. + fn adopt(&mut self, tab: BrowserTabInfo) { + self.tab_id = Some(tab.tab_id.clone()); + if tab.url != "about:blank" { + self.last_url = Some(tab.url.clone()); + } + self.sink.event(BrowserEvent::Tab { tab }); + } + + fn request(&self, op: BrowserOp) -> Request { + Request::Browser { + project_root: self.project_root.clone(), + op, + } + } + + async fn attach_once(&mut self) -> End { + let retry = |message: String| End::Retry { + message, + live: false, + }; + if self.tab_id.is_none() { + let open = self.request(BrowserOp::Open { + url: self.last_url.clone(), + }); + match self.client.request(&open).await { + Ok(Response::BrowserTab { tab }) => self.adopt(tab), + Ok(Response::Error { code, message }) => return End::Daemon(code, message), + Ok(_) => return retry("Unexpected reply from the daemon".into()), + Err(error) => return retry(error.to_string()), + } + } + + // Dropping the session aborts this task, so a connect needs no close check. + let (mut reader, mut writer) = match self.client.connect().await { + Ok(halves) => halves, + Err(error) => return retry(error.to_string()), + }; + let attach = Request::BrowserAttach { + project_root: self.project_root.clone(), + tab_id: self.tab_id.clone(), + }; + if let Err(error) = write_request(&mut writer, &attach).await { + return retry(error.to_string()); + } + + // A dedicated reader, so a line half read is never lost to `select!`. + let (lines_tx, mut lines) = mpsc::channel::>(8); + let _reader = TaskGuard(tokio::spawn(async move { + loop { + let response = reader.next_response().await; + let last = response.is_err(); + if lines_tx.send(response).await.is_err() || last { + return; + } + } + })); + + // The first line: the attach's answer. Ops wait in the channel meanwhile. + match lines.recv().await { + Some(Ok(Response::BrowserAttached { tab })) => self.adopt(tab), + Some(Ok(Response::BrowserTabClosed { .. })) => return End::TabClosed, + Some(Ok(Response::Error { code, .. })) if is_lost_tab(&code) => { + // The tab is gone (browser or daemon restarted): open a new one on its last page. + self.tab_id = None; + return retry("Reopening the tab".into()); + } + Some(Ok(Response::Error { code, message })) => return End::Daemon(code, message), + Some(Ok(_)) => return retry("Unexpected reply from the daemon".into()), + Some(Err(error)) => return retry(error.to_string()), + None => return retry(DaemonError::Eof.to_string()), + } + self.sink.event(BrowserEvent::Live); + if let Some((width, height, scale)) = self.viewport { + let resize = self.request(BrowserOp::Resize { + tab_id: None, + width, + height, + scale, + }); + if let Err(error) = write_request(&mut writer, &resize).await { + return End::Retry { + message: error.to_string(), + live: true, + }; + } + } + + loop { + tokio::select! { + biased; + op = self.ops.recv() => { + let Some(op) = op else { return End::Stopped }; + self.remember(&op); + let request = self.request(op); + if let Err(error) = write_request(&mut writer, &request).await { + return End::Retry { message: error.to_string(), live: true }; + } + } + line = lines.recv() => { + let response = match line { + Some(Ok(response)) => response, + Some(Err(error)) => return End::Retry { message: error.to_string(), live: true }, + None => return End::Retry { message: DaemonError::Eof.to_string(), live: true }, + }; + match response { + Response::BrowserFrame { seq, data, width, height, .. } => { + self.sink.event(BrowserEvent::Frame { seq, data, width, height }); + } + Response::BrowserTabState { tab } | Response::BrowserTab { tab } => { + self.adopt(tab); + } + Response::BrowserTabClosed { .. } => return End::TabClosed, + Response::BrowserEvalResult { value, .. } => { + self.sink.event(BrowserEvent::EvalResult { value }); + } + Response::Error { code, message } => { + self.sink.event(BrowserEvent::Notice { code, message }); + } + _ => {} + } + } + } + } + } +} + +#[cfg(test)] +#[path = "session_tests.rs"] +mod tests; diff --git a/apps/purepoint-windows/src-tauri/src/browser/session_tests.rs b/apps/purepoint-windows/src-tauri/src/browser/session_tests.rs new file mode 100644 index 00000000..0d5622c3 --- /dev/null +++ b/apps/purepoint-windows/src-tauri/src/browser/session_tests.rs @@ -0,0 +1,363 @@ +use std::path::PathBuf; + +use pu_core::protocol::{BrowserDriver, BrowserHistory}; +use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; +use tokio::time::timeout; + +use super::*; + +const WAIT: Duration = Duration::from_secs(10); + +struct TestSink(mpsc::UnboundedSender); + +impl BrowserSink for TestSink { + fn event(&self, event: BrowserEvent) { + let _ = self.0.send(event); + } +} + +fn sink() -> (Arc, mpsc::UnboundedReceiver) { + let (tx, rx) = mpsc::unbounded_channel(); + (Arc::new(TestSink(tx)), rx) +} + +async fn next(seen: &mut mpsc::UnboundedReceiver) -> BrowserEvent { + timeout(WAIT, seen.recv()) + .await + .expect("timed out waiting for the session") + .expect("session sink closed") +} + +/// One accepted connection on the fake daemon: the requests it sent and its write half. +struct ServerConn { + requests: mpsc::UnboundedReceiver, + writer: pu_transport::WriteHalf, + _reader: TaskGuard, +} + +impl ServerConn { + async fn request(&mut self) -> Request { + timeout(WAIT, self.requests.recv()) + .await + .expect("timed out waiting for a request") + .expect("client closed the connection") + } + + async fn send(&mut self, response: &Response) { + let mut line = serde_json::to_vec(response).unwrap(); + line.push(b'\n'); + self.writer.write_all(&line).await.unwrap(); + self.writer.flush().await.unwrap(); + } +} + +/// A fake daemon on a `pu_transport::Listener` handing each connection to the test. +struct FakeDaemon { + connections: mpsc::UnboundedReceiver, + task: tokio::task::JoinHandle<()>, + _home: tempfile::TempDir, + socket: PathBuf, +} + +impl FakeDaemon { + fn start() -> Self { + let home = tempfile::TempDir::new().unwrap(); + let socket = home.path().join("d.sock"); + let endpoint = pu_transport::Endpoint::for_socket(&socket).unwrap(); + let mut listener = pu_transport::Listener::bind(&endpoint).unwrap(); + let (tx, connections) = mpsc::unbounded_channel(); + let task = tokio::spawn(async move { + loop { + let Ok((stream, _peer)) = listener.accept().await else { + continue; + }; + let (read, writer) = stream.into_split(); + let (requests_tx, requests) = mpsc::unbounded_channel(); + let reader = tokio::spawn(async move { + let mut lines = BufReader::new(read).lines(); + while let Ok(Some(line)) = lines.next_line().await { + if requests_tx + .send(serde_json::from_str(&line).unwrap()) + .is_err() + { + break; + } + } + }); + if tx + .send(ServerConn { + requests, + writer, + _reader: TaskGuard(reader), + }) + .is_err() + { + return; + } + } + }); + Self { + connections, + task, + _home: home, + socket, + } + } + + fn client(&self) -> DaemonClient { + DaemonClient::local(&self.socket).unwrap() + } + + async fn accept(&mut self) -> ServerConn { + timeout(WAIT, self.connections.recv()) + .await + .expect("timed out waiting for a connection") + .unwrap() + } +} + +impl Drop for FakeDaemon { + fn drop(&mut self) { + self.task.abort(); + } +} + +/// `Request` has no `PartialEq`; compare the wire form. +fn assert_request(got: Request, want: serde_json::Value) { + assert_eq!(serde_json::to_value(got).unwrap(), want); +} + +fn tab(id: &str, url: &str) -> BrowserTabInfo { + BrowserTabInfo { + tab_id: id.into(), + url: url.into(), + title: String::new(), + loading: false, + driver: BrowserDriver::Agent, + can_go_back: false, + can_go_forward: false, + width: 1280, + height: 800, + } +} + +fn options(tab_id: Option<&str>, url: Option<&str>) -> BrowserOptions { + let mut options = BrowserOptions::new("/p", tab_id.map(Into::into), url.map(Into::into)); + options.fast_delay = Duration::from_millis(10); + options.slow_delay = Duration::from_millis(40); + options +} + +#[test] +fn given_swift_schedule_should_retry_three_times_fast_then_slow() { + let (fast, slow) = (Duration::from_millis(300), Duration::from_secs(2)); + let delays: Vec<_> = (1..=5).map(|n| retry_delay(n, fast, slow)).collect(); + assert_eq!(delays, vec![fast, fast, fast, slow, slow]); + assert!(is_lost_tab("BROWSER_TAB_NOT_FOUND") && is_lost_tab("BROWSER_NO_TAB")); + assert!(!is_lost_tab("BROWSER_NOT_FOUND")); + assert!(describe("BROWSER_NOT_FOUND", "x").contains("Chrome")); + assert_eq!(describe("OTHER", "why"), "why"); +} + +#[tokio::test] +async fn given_no_tab_should_open_one_on_the_last_page_then_attach_and_stream() { + let mut daemon = FakeDaemon::start(); + let (sink, mut seen) = sink(); + let session = BrowserSession::start( + daemon.client(), + options(None, Some("http://localhost:3000/")), + sink, + ); + + let mut open = daemon.accept().await; + assert_request( + open.request().await, + serde_json::json!({"type": "browser", "project_root": "/p", "op": {"action": "open", "url": "http://localhost:3000/"}}), + ); + open.send(&Response::BrowserTab { + tab: tab("t1", "http://localhost:3000/"), + }) + .await; + assert_eq!( + next(&mut seen).await, + BrowserEvent::Tab { + tab: tab("t1", "http://localhost:3000/") + } + ); + + let mut stream = daemon.accept().await; + assert_request( + stream.request().await, + serde_json::json!({"type": "browser_attach", "project_root": "/p", "tab_id": "t1"}), + ); + stream + .send(&Response::BrowserAttached { + tab: tab("t1", "http://localhost:3000/"), + }) + .await; + assert!(matches!(next(&mut seen).await, BrowserEvent::Tab { .. })); + assert_eq!(next(&mut seen).await, BrowserEvent::Live); + + stream + .send(&Response::BrowserFrame { + tab_id: "t1".into(), + seq: 1, + data: "/9j/".into(), + width: 1280.0, + height: 800.0, + }) + .await; + assert_eq!( + next(&mut seen).await, + BrowserEvent::Frame { + seq: 1, + data: "/9j/".into(), + width: 1280.0, + height: 800.0 + } + ); + + // Ops go out on the stream, defaulting to its tab. + session.send(BrowserOp::FrameAck { + tab_id: None, + seq: 1, + }); + session.send(BrowserOp::History { + tab_id: None, + direction: BrowserHistory::Back, + }); + assert_request( + stream.request().await, + serde_json::json!({"type": "browser", "project_root": "/p", "op": {"action": "frame_ack", "tab_id": null, "seq": 1}}), + ); + assert_request( + stream.request().await, + serde_json::json!({"type": "browser", "project_root": "/p", "op": {"action": "history", "tab_id": null, "direction": "back"}}), + ); + + stream + .send(&Response::Error { + code: "BROWSER_NAVIGATION_FAILED".into(), + message: "net::ERR".into(), + }) + .await; + assert_eq!( + next(&mut seen).await, + BrowserEvent::Notice { + code: "BROWSER_NAVIGATION_FAILED".into(), + message: "net::ERR".into() + } + ); + + stream + .send(&Response::BrowserTabClosed { + tab_id: "t1".into(), + }) + .await; + assert_eq!(next(&mut seen).await, BrowserEvent::Closed); +} + +#[tokio::test] +async fn given_a_lost_tab_should_open_a_new_one_on_its_last_page() { + let mut daemon = FakeDaemon::start(); + let (sink, mut seen) = sink(); + let _session = BrowserSession::start( + daemon.client(), + options(Some("old"), Some("http://localhost:5173/a")), + sink, + ); + + let mut stream = daemon.accept().await; + assert!(matches!( + stream.request().await, + Request::BrowserAttach { tab_id: Some(id), .. } if id == "old" + )); + stream + .send(&Response::Error { + code: "BROWSER_TAB_NOT_FOUND".into(), + message: "no tab old".into(), + }) + .await; + assert!(matches!( + next(&mut seen).await, + BrowserEvent::Retrying { attempt: 1, .. } + )); + + let mut open = daemon.accept().await; + assert_request( + open.request().await, + serde_json::json!({"type": "browser", "project_root": "/p", "op": {"action": "open", "url": "http://localhost:5173/a"}}), + ); + open.send(&Response::BrowserTab { + tab: tab("new", "about:blank"), + }) + .await; + assert!(matches!(next(&mut seen).await, BrowserEvent::Tab { .. })); + let mut stream = daemon.accept().await; + assert!(matches!( + stream.request().await, + Request::BrowserAttach { tab_id: Some(id), .. } if id == "new" + )); +} + +#[tokio::test] +async fn given_a_final_daemon_error_should_fail_with_its_description() { + let mut daemon = FakeDaemon::start(); + let (sink, mut seen) = sink(); + let _session = BrowserSession::start(daemon.client(), options(None, None), sink); + let mut open = daemon.accept().await; + let _ = open.request().await; + open.send(&Response::Error { + code: "BROWSER_NOT_FOUND".into(), + message: "no chrome".into(), + }) + .await; + match next(&mut seen).await { + BrowserEvent::Failed { code, message } => { + assert_eq!(code, "BROWSER_NOT_FOUND"); + assert!(message.contains("PU_BROWSER")); + } + other => panic!("expected failed, got {other:?}"), + } +} + +#[tokio::test] +async fn given_a_dropped_stream_should_reattach_and_replay_the_last_resize() { + let mut daemon = FakeDaemon::start(); + let (sink, mut seen) = sink(); + let session = BrowserSession::start(daemon.client(), options(Some("t1"), None), sink); + + let mut stream = daemon.accept().await; + let _ = stream.request().await; + stream + .send(&Response::BrowserAttached { + tab: tab("t1", "http://localhost/"), + }) + .await; + assert!(matches!(next(&mut seen).await, BrowserEvent::Tab { .. })); + assert_eq!(next(&mut seen).await, BrowserEvent::Live); + session.send(BrowserOp::Resize { + tab_id: None, + width: 640, + height: 480, + scale: 2.0, + }); + let _ = stream.request().await; + drop(stream); + assert!(matches!( + next(&mut seen).await, + BrowserEvent::Retrying { attempt: 1, .. } + )); + + let mut stream = daemon.accept().await; + let _ = stream.request().await; + stream + .send(&Response::BrowserAttached { + tab: tab("t1", "http://localhost/"), + }) + .await; + assert_request( + stream.request().await, + serde_json::json!({"type": "browser", "project_root": "/p", "op": {"action": "resize", "tab_id": null, "width": 640, "height": 480, "scale": 2.0}}), + ); +} diff --git a/apps/purepoint-windows/src-tauri/src/lib.rs b/apps/purepoint-windows/src-tauri/src/lib.rs index b1eda629..fe1fe006 100644 --- a/apps/purepoint-windows/src-tauri/src/lib.rs +++ b/apps/purepoint-windows/src-tauri/src/lib.rs @@ -2,6 +2,7 @@ pub mod attach; pub mod automation; +pub mod browser; pub mod chrome; pub mod conversations; pub mod daemon; @@ -36,9 +37,9 @@ pub fn protocol_version() -> u32 { /// The main window's page started loading (a reload, or the renderer restarted after a crash): /// nothing on the old page reads its channels or will close what it opened, so the backend -/// drops it all before the new page starts its own. Terminal sessions and chat sockets close, -/// watchers stop (and release tokens are forgotten), and subscriptions stop. Also runs on the -/// first load, when everything is still empty. +/// drops it all before the new page starts its own. Terminal and browser sessions and chat +/// sockets close, watchers stop (and release tokens are forgotten), and subscriptions stop. Also +/// runs on the first load, when everything is still empty. /// Build the main window from its `tauri.conf.json` declaration, with the WebDriver switches /// a debug build under tauri-driver needs ([`automation::browser_args`]). fn create_main_window(app: &tauri::App) -> tauri::Result<()> { @@ -67,6 +68,9 @@ fn reset_for_page_load(app: &tauri::AppHandle) { if let Some(attach) = app.try_state::() { attach.clear(); } + if let Some(browser) = app.try_state::() { + browser.clear(); + } if let Some(sockets) = app.try_state::() { sockets.clear(); } @@ -100,6 +104,7 @@ pub fn run() { .plugin(tauri_plugin_updater::Builder::new().build()) .manage(git::commands::GitState::default()) .manage(attach::AttachState::default()) + .manage(browser::BrowserState::default()) // Each machine's daemon client over the ssh relay (WIN-8.14). .manage(daemon::machine::MachineClients::default()) .manage(pointguard::chat::ChatSockets::default()) @@ -157,6 +162,9 @@ pub fn run() { attach::attach_claim_size, attach::attach_blur, attach::attach_close, + browser::browser_open, + browser::browser_send, + browser::browser_close, watchers::commands::watch_manifest, watchers::commands::watch_worktree, watchers::commands::watch_file_tree, diff --git a/apps/purepoint-windows/ui/src/model/browser.test.ts b/apps/purepoint-windows/ui/src/model/browser.test.ts new file mode 100644 index 00000000..eb961767 --- /dev/null +++ b/apps/purepoint-windows/ui/src/model/browser.test.ts @@ -0,0 +1,212 @@ +// Tests for the browser pane's pure parts (BrowserAddress, BrowserLinks and BrowserCanvas's input +// mapping in the Swift app; see BrowserPaneTests.swift). +import { describe, expect, it, vi } from 'vitest'; +import { + BROWSER_MODIFIERS, + addressFieldText, + browserModifiers, + browserTabTitle, + evalText, + hoverInput, + isLoopbackUrl, + keyInput, + mouseButton, + mouseInput, + pagePoint, + terminalLinkHandler, + viewportOf, + wheelInput, +} from './browser'; + +const NONE = { altKey: false, ctrlKey: false, metaKey: false, shiftKey: false }; + +describe('browser addresses', () => { + it('givenUrlShouldTitleTheTabWithItsHostAndPort', () => { + expect(browserTabTitle('http://localhost:3000/app')).toBe('localhost:3000'); + expect(browserTabTitle('https://example.com/a?b')).toBe('example.com'); + expect(browserTabTitle(null)).toBe('Browser'); + expect(browserTabTitle('')).toBe('Browser'); + expect(browserTabTitle('about:blank')).toBe('Browser'); + expect(browserTabTitle('not a url')).toBe('not a url'); + }); + + it('givenBlankPageShouldLeaveTheAddressFieldEmpty', () => { + expect(addressFieldText('about:blank')).toBe(''); + expect(addressFieldText(null)).toBe(''); + expect(addressFieldText('http://localhost/')).toBe('http://localhost/'); + }); + + it('givenLoopbackLinksShouldRecognizeEveryLoopbackHost', () => { + for (const url of [ + 'http://localhost:3000', + 'https://LOCALHOST/x', + 'http://app.localhost:8080/', + 'http://127.0.0.1:5173/', + 'http://0.0.0.0:8000', + 'http://[::1]:3000/', + ]) { + expect(isLoopbackUrl(url), url).toBe(true); + } + for (const url of [ + 'http://example.com', + 'http://localhost.example.com', + 'ftp://localhost/', + 'file:///C:/x', + 'nonsense', + 'http://127.0.0.2/', + ]) { + expect(isLoopbackUrl(url), url).toBe(false); + } + }); + + it('givenEvalResultShouldCopyOnlyNonEmptyText', () => { + expect(evalText('hi')).toBe('hi'); + expect(evalText('')).toBeNull(); + expect(evalText(3)).toBeNull(); + expect(evalText(null)).toBeNull(); + }); +}); + +describe('terminal links', () => { + it('givenRemoteAgentLoopbackLinkShouldOpenItInABrowserPane', () => { + const pane = vi.fn(() => true); + const system = vi.fn(); + terminalLinkHandler(() => true, pane, system)('http://localhost:3000/'); + expect(pane).toHaveBeenCalledWith('http://localhost:3000/'); + expect(system).not.toHaveBeenCalled(); + }); + + it('givenLocalAgentOrOtherLinkShouldOpenTheSystemBrowser', () => { + const pane = vi.fn(() => true); + const system = vi.fn(); + terminalLinkHandler(() => false, pane, system)('http://localhost:3000/'); + terminalLinkHandler(() => true, pane, system)('https://example.com/'); + expect(pane).not.toHaveBeenCalled(); + expect(system.mock.calls).toEqual([['http://localhost:3000/'], ['https://example.com/']]); + }); + + it('givenNoPaneCouldOpenShouldFallBackToTheSystemBrowser', () => { + const system = vi.fn(); + terminalLinkHandler( + () => true, + () => false, + system, + )('http://127.0.0.1/'); + expect(system).toHaveBeenCalledWith('http://127.0.0.1/'); + }); +}); + +describe('browser input mapping', () => { + const view = { width: 640, height: 400 }; + const page = { width: 1280, height: 800 }; + + it('givenPaneSmallerThanTheViewportShouldScalePointsToCssPixels', () => { + expect(pagePoint(10, 20, view, page)).toEqual({ x: 20, y: 40 }); + expect(pagePoint(10, 20, { width: 0, height: 0 }, page)).toEqual({ x: 10, y: 20 }); + }); + + it('givenModifierKeysShouldUseChromiumsBits', () => { + expect(browserModifiers(NONE)).toBe(0); + expect(browserModifiers({ altKey: true, ctrlKey: true, metaKey: true, shiftKey: true })).toBe( + BROWSER_MODIFIERS.alt | + BROWSER_MODIFIERS.control | + BROWSER_MODIFIERS.meta | + BROWSER_MODIFIERS.shift, + ); + expect(browserModifiers({ ...NONE, shiftKey: true })).toBe(8); + }); + + it('givenMouseButtonsShouldNameThem', () => { + expect([0, 1, 2, 3].map(mouseButton)).toEqual(['left', 'middle', 'right', 'none']); + }); + + it('givenAClickShouldSendItInPagePixelsWithItsCount', () => { + const input = { ...NONE, x: 100, y: 50, button: 0, detail: 2, ctrlKey: true }; + expect(mouseInput('down', input, view, page)).toEqual({ + kind: 'mouse', + action: 'down', + x: 200, + y: 100, + button: 'left', + click_count: 2, + modifiers: 2, + }); + expect(mouseInput('up', { ...input, detail: 0 }, view, page)).toMatchObject({ + click_count: 1, + }); + expect(hoverInput(input, view, page)).toEqual({ + kind: 'mouse', + action: 'move', + x: 200, + y: 100, + button: 'none', + click_count: 0, + modifiers: 2, + }); + }); + + it('givenWheelShouldScrollByPixelsAndLines', () => { + const base = { ...NONE, x: 10, y: 10, deltaX: 0, deltaY: 120, deltaMode: 0 }; + expect(wheelInput(base, view, page)).toEqual({ + kind: 'wheel', + x: 20, + y: 20, + dx: 0, + dy: 120, + modifiers: 0, + }); + expect(wheelInput({ ...base, deltaY: -3, deltaMode: 1 }, view, page)).toMatchObject({ + dy: -120, + }); + }); + + it('givenPlainKeysShouldTypeTheirText', () => { + expect(keyInput({ ...NONE, key: 'a', code: 'KeyA' }, true)).toEqual({ + kind: 'send', + event: { kind: 'key', action: 'down', key: 'a', code: 'KeyA', text: 'a', modifiers: 0 }, + }); + expect(keyInput({ ...NONE, key: 'A', code: 'KeyA', shiftKey: true }, true)).toMatchObject({ + event: { text: 'A', modifiers: 8 }, + }); + expect(keyInput({ ...NONE, key: 'a', code: 'KeyA' }, false)).toMatchObject({ + event: { action: 'up', text: null }, + }); + }); + + it('givenNamedKeysShouldSendThemWithoutTextExceptEnter', () => { + expect(keyInput({ ...NONE, key: 'ArrowLeft', code: 'ArrowLeft' }, true)).toMatchObject({ + event: { key: 'ArrowLeft', text: null }, + }); + expect(keyInput({ ...NONE, key: 'Enter', code: 'Enter' }, true)).toMatchObject({ + event: { key: 'Enter', text: '\r' }, + }); + expect(keyInput({ ...NONE, key: 'Backspace', code: 'Backspace' }, true)).toMatchObject({ + event: { key: 'Backspace', text: null }, + }); + }); + + it('givenChordsShouldSendKeysWithoutTextAndPasteAndCopyShouldBeTheApps', () => { + expect(keyInput({ ...NONE, key: 'a', code: 'KeyA', ctrlKey: true }, true)).toMatchObject({ + event: { key: 'a', text: null, modifiers: 2 }, + }); + expect(keyInput({ ...NONE, key: 'v', code: 'KeyV', ctrlKey: true }, true)).toEqual({ + kind: 'paste', + }); + expect(keyInput({ ...NONE, key: 'c', code: 'KeyC', ctrlKey: true }, true)).toEqual({ + kind: 'copy', + }); + // AltGr (Ctrl+Alt) types its character. + expect( + keyInput({ ...NONE, key: '@', code: 'KeyQ', ctrlKey: true, altKey: true }, true), + ).toMatchObject({ event: { text: '@' } }); + expect(keyInput({ ...NONE, key: 'Shift', code: 'ShiftLeft', shiftKey: true }, true)).toEqual({ + kind: 'ignore', + }); + }); + + it('givenPaneSizeShouldAskForWholeCssPixelsAndItsDensity', () => { + expect(viewportOf(640.4, 399.6, 1.5)).toEqual({ width: 640, height: 400, scale: 1.5 }); + expect(viewportOf(0, 400, 1)).toBeNull(); + expect(viewportOf(10, 10, 0)).toEqual({ width: 10, height: 10, scale: 1 }); + }); +}); diff --git a/apps/purepoint-windows/ui/src/model/browser.ts b/apps/purepoint-windows/ui/src/model/browser.ts new file mode 100644 index 00000000..6bd069d9 --- /dev/null +++ b/apps/purepoint-windows/ui/src/model/browser.ts @@ -0,0 +1,302 @@ +// Port of the pure parts of apps/purepoint-macos/purepoint-macos/State/BrowserSession.swift +// (`BrowserAddress`, `BrowserLinks.isLoopback`) and Views/Browser/BrowserCanvas.swift (the input +// mapping), for browser panes: live views of a tab of the project's headless browser, which runs +// on the project's machine. +// +// Everything here is pure, so the pane's DOM handlers (views/browser/BrowserPaneView.tsx) only +// read the event and send what these return. +// +// Differences from Swift: +// - Keys come from DOM `KeyboardEvent`s, whose `key` is already the DOM key name the daemon +// wants, so there is no virtual-key-code table. `code` is passed through. +// - Paste and copy are Ctrl+V / Ctrl+C (Cmd on the Mac); Ctrl+Shift+V pastes too. +// - Wheel deltas arrive in pixels (`deltaMode` 0) or lines/pages, scaled like the Mac's +// non-precise wheel (40 px a line). + +import type { BrowserInputEvent, BrowserMouseButton, BrowserTabInfo } from '../protocol'; + +// MARK: - Addresses + +/** A pane tab's title: the page's host (and port), or "Browser" before a page loads. */ +export function browserTabTitle(url: string | null): string { + if (url === null || url === '' || url === 'about:blank') return 'Browser'; + let parsed: URL; + try { + parsed = new URL(url); + } catch { + return url; + } + if (parsed.hostname === '') return url; + return parsed.port === '' ? parsed.hostname : `${parsed.hostname}:${parsed.port}`; +} + +/** What the address field shows: blank for a blank page. */ +export function addressFieldText(url: string | null): string { + if (url === null || url === 'about:blank') return ''; + return url; +} + +/** + * Whether a link points at the machine it was printed on: `localhost` (and `*.localhost`), + * 127.0.0.1, 0.0.0.0 or [::1], over http(s). Swift `BrowserLinks.isLoopback`. + */ +export function isLoopbackUrl(url: string): boolean { + let parsed: URL; + try { + parsed = new URL(url); + } catch { + return false; + } + if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return false; + const host = parsed.hostname.toLowerCase(); + return ( + host === 'localhost' || + host.endsWith('.localhost') || + host === '127.0.0.1' || + host === '0.0.0.0' || + host === '::1' || + host === '[::1]' + ); +} + +// MARK: - Session state + +/** Swift `BrowserSession.Phase`. */ +export type BrowserPhase = + | { readonly kind: 'connecting' } + | { readonly kind: 'live' } + /** The tab closed (from `pu browser close`, or the browser exited). */ + | { readonly kind: 'closed' } + | { readonly kind: 'failed'; readonly message: string }; + +/** After this many failed attempts in a row the pane says the connection failed (Swift: > 3). */ +export const BROWSER_FAILED_AFTER = 3; + +/** How long a notice stays over the page. */ +export const BROWSER_NOTICE_MS = 4000; + +/** The viewport the pane assumes before the first frame (Swift `frameSize`). */ +export const DEFAULT_FRAME_SIZE = { width: 1280, height: 800 } as const; + +/** Whether the person drives the tab (agents' actions wait). */ +export function isHumanDriving(tab: BrowserTabInfo | null): boolean { + return tab?.driver === 'human'; +} + +/** + * Text an `eval` result carries for Copy: only a non-empty string (Swift `BrowserJSONValue`). + */ +export function evalText(value: unknown): string | null { + return typeof value === 'string' && value !== '' ? value : null; +} + +/** The expression Copy evaluates: the page's selected text. */ +export const COPY_SELECTION_EXPRESSION = "String(getSelection ? getSelection() : '')"; + +// MARK: - Input mapping + +/** Modifier bits, as Chromium numbers them. */ +export const BROWSER_MODIFIERS = { alt: 1, control: 2, meta: 4, shift: 8 } as const; + +export interface ModifierKeys { + readonly altKey: boolean; + readonly ctrlKey: boolean; + readonly metaKey: boolean; + readonly shiftKey: boolean; +} + +export function browserModifiers(event: ModifierKeys): number { + let bits = 0; + if (event.altKey) bits |= BROWSER_MODIFIERS.alt; + if (event.ctrlKey) bits |= BROWSER_MODIFIERS.control; + if (event.metaKey) bits |= BROWSER_MODIFIERS.meta; + if (event.shiftKey) bits |= BROWSER_MODIFIERS.shift; + return bits; +} + +export interface Size { + readonly width: number; + readonly height: number; +} + +/** + * A point in the pane (CSS pixels from its top-left) as CSS pixels in the page, whose viewport + * (`page`) may differ from the pane's size while a resize is on its way. + */ +export function pagePoint(x: number, y: number, view: Size, page: Size): { x: number; y: number } { + const sx = view.width > 0 ? page.width / view.width : 1; + const sy = view.height > 0 ? page.height / view.height : 1; + return { x: x * sx, y: y * sy }; +} + +/** `MouseEvent.button` as the daemon names it. */ +export function mouseButton(button: number): BrowserMouseButton { + switch (button) { + case 0: + return 'left'; + case 1: + return 'middle'; + case 2: + return 'right'; + default: + return 'none'; + } +} + +export interface PointerInput extends ModifierKeys { + readonly x: number; + readonly y: number; + readonly button: number; + readonly detail: number; +} + +/** A mouse press, release or drag. */ +export function mouseInput( + action: 'down' | 'up' | 'move', + input: PointerInput, + view: Size, + page: Size, +): BrowserInputEvent { + const p = pagePoint(input.x, input.y, view, page); + return { + kind: 'mouse', + action, + x: p.x, + y: p.y, + button: mouseButton(input.button), + click_count: Math.max(input.detail, action === 'move' ? 0 : 1), + modifiers: browserModifiers(input), + }; +} + +/** A hover: no button. */ +export function hoverInput(input: PointerInput, view: Size, page: Size): BrowserInputEvent { + const p = pagePoint(input.x, input.y, view, page); + return { + kind: 'mouse', + action: 'move', + x: p.x, + y: p.y, + button: 'none', + click_count: 0, + modifiers: browserModifiers(input), + }; +} + +/** Hover only needs to keep up with the eye; over ssh every line costs (Swift: 30 a second). */ +export const HOVER_INTERVAL_MS = 1000 / 30; + +export interface WheelInput extends ModifierKeys { + readonly x: number; + readonly y: number; + readonly deltaX: number; + readonly deltaY: number; + /** `WheelEvent.deltaMode`: 0 pixels, 1 lines, 2 pages. */ + readonly deltaMode: number; +} + +/** Pixels a wheel line scrolls (the Mac's factor for a non-precise wheel). */ +export const WHEEL_LINE_PX = 40; + +/** + * A wheel turn. DOM deltas are positive scrolling down, which is what the daemon's `dx`/`dy` + * mean, so they keep their sign (the Mac negates AppKit's opposite convention). + */ +export function wheelInput(input: WheelInput, view: Size, page: Size): BrowserInputEvent { + const p = pagePoint(input.x, input.y, view, page); + const factor = + input.deltaMode === 1 ? WHEEL_LINE_PX : input.deltaMode === 2 ? Math.max(view.height, 1) : 1; + return { + kind: 'wheel', + x: p.x, + y: p.y, + dx: input.deltaX * factor, + dy: input.deltaY * factor, + modifiers: browserModifiers(input), + }; +} + +export interface KeyInput extends ModifierKeys { + readonly key: string; + readonly code: string; +} + +/** What a key press in the pane means. */ +export type KeyAction = + | { readonly kind: 'send'; readonly event: BrowserInputEvent } + /** Ctrl+V: paste the clipboard as typed text. */ + | { readonly kind: 'paste' } + /** Ctrl+C: copy the page's selection. */ + | { readonly kind: 'copy' } + /** Not the page's (a lone modifier, or a key the app keeps). */ + | { readonly kind: 'ignore' }; + +const MODIFIER_KEYS = new Set(['Alt', 'AltGraph', 'Control', 'Meta', 'Shift', 'CapsLock', 'OS']); + +/** + * A DOM key event as page input (Swift `BrowserCanvasNSView.key`). Text is typed only by a plain + * (or shifted) press of a printable key; chords are shortcuts. AltGr arrives as Ctrl+Alt with a + * printable key, and types its character. + */ +export function keyInput(input: KeyInput, down: boolean): KeyAction { + if (MODIFIER_KEYS.has(input.key) || input.key === 'Unidentified' || input.key === '') { + return { kind: 'ignore' }; + } + const chord = input.ctrlKey && !input.altKey; + if (down && chord && !input.metaKey) { + const lower = input.key.toLowerCase(); + if (lower === 'v') return { kind: 'paste' }; + if (lower === 'c' && !input.shiftKey) return { kind: 'copy' }; + } + // One character (a key name such as `ArrowLeft` is longer). + const printable = /^.$/u.test(input.key); + const altGr = input.ctrlKey && input.altKey; + const typing = printable && (!input.ctrlKey || altGr) && !input.metaKey; + let text: string | null = null; + if (down) { + if (input.key === 'Enter') text = '\r'; + else if (typing) text = input.key; + } + return { + kind: 'send', + event: { + kind: 'key', + action: down ? 'down' : 'up', + key: input.key, + code: input.code === '' ? null : input.code, + text, + modifiers: browserModifiers(input), + }, + }; +} + +/** The viewport a pane asks for: its size in whole CSS pixels and its pixel density. */ +export function viewportOf( + width: number, + height: number, + devicePixelRatio: number, +): { width: number; height: number; scale: number } | null { + const w = Math.round(width); + const h = Math.round(height); + if (w < 1 || h < 1) return null; + return { width: w, height: h, scale: devicePixelRatio > 0 ? devicePixelRatio : 1 }; +} + +// MARK: - Terminal links + +/** + * Swift `BrowserLinks.handler`: a terminal's link handler. `http://localhost:3000` printed by an + * agent on another machine means that machine, so its loopback links open in a browser pane of + * the agent's project (whose browser runs there); every other link, and a local agent's, opens + * in the system browser (`fallback`). `openInPane` returns false when it could not. + */ +export function terminalLinkHandler( + isRemote: () => boolean, + openInPane: (url: string) => boolean, + fallback: (url: string) => void, +): (url: string) => void { + return (url) => { + if (isRemote() && isLoopbackUrl(url) && openInPane(url)) return; + fallback(url); + }; +} diff --git a/apps/purepoint-windows/ui/src/model/workspace.ts b/apps/purepoint-windows/ui/src/model/workspace.ts index 0fb8ca06..41006900 100644 --- a/apps/purepoint-windows/ui/src/model/workspace.ts +++ b/apps/purepoint-windows/ui/src/model/workspace.ts @@ -69,7 +69,13 @@ export type SurfaceContent = | { readonly kind: 'pointGuard' } | { readonly kind: 'agent'; readonly agentId: string } /** The file navigator/editor. `path` is the absolute file to show; `null` opens the navigator alone. */ - | { readonly kind: 'file'; readonly path: string | null }; + | { readonly kind: 'file'; readonly path: string | null } + /** + * A tab of the project's browser, which runs on the project's machine. `tabId` is the daemon's + * tab (`null` until opened); `url` is the last page shown, so a tab lost to a daemon or browser + * restart reopens where it was. + */ + | { readonly kind: 'browser'; readonly tabId: string | null; readonly url: string | null }; export const EMPTY_CONTENT: SurfaceContent = { kind: 'empty' }; export const POINT_GUARD_CONTENT: SurfaceContent = { kind: 'pointGuard' }; @@ -82,6 +88,13 @@ export function fileContent(path: string | null): SurfaceContent { return { kind: 'file', path }; } +export function browserContent( + tabId: string | null = null, + url: string | null = null, +): SurfaceContent { + return { kind: 'browser', tabId, url }; +} + export function contentAgentId(content: SurfaceContent): string | null { return content.kind === 'agent' ? content.agentId : null; } diff --git a/apps/purepoint-windows/ui/src/model/workspacePersistence.test.ts b/apps/purepoint-windows/ui/src/model/workspacePersistence.test.ts index a81294cf..a2a1b991 100644 --- a/apps/purepoint-windows/ui/src/model/workspacePersistence.test.ts +++ b/apps/purepoint-windows/ui/src/model/workspacePersistence.test.ts @@ -18,6 +18,7 @@ import { PROJECT_ROOT, adoptingWorkspace, agentContent, + browserContent, isPointGuard, pointGuardId, pointGuardWorkspace, @@ -153,7 +154,7 @@ describe('WorkspacePersistence', () => { }); it('givenUnknownTabKindShouldLoadItAsAnEmptyTabRatherThanFail', () => { - const text = v3.replace('"kind" : "file"', '"kind" : "browser"'); + const text = v3.replace('"kind" : "file"', '"kind" : "hologram"'); const tabs = workspacesFromText(text, ROOT)[0]?.panes[0]?.tabs; expect(tabs?.map((tab) => tab.content.kind)).toEqual(['agent', 'empty']); }); @@ -256,6 +257,38 @@ describe('WorkspacePersistence', () => { expect(io.files.has(legacyGridLayoutPath(ROOT))).toBe(false); }); + it('givenBrowserTabShouldSaveItsTabIdAndUrlAndReadThemBack', async () => { + const io = memoryWorkspaceFileIO(); + const workspace = adoptingWorkspace('ag-a', PROJECT_ROOT); + const withBrowser: Workspace = { + ...workspace, + panes: { + ...workspace.panes, + [workspace.focusedLeafId]: { + tabs: [ + ...(workspace.panes[workspace.focusedLeafId]?.tabs ?? []), + { id: 7, content: browserContent('tab-3', 'http://localhost:3000/') }, + { id: 8, content: browserContent() }, + ], + activeTabId: 7, + }, + }, + nextSurfaceId: 9, + }; + await saveWorkspaces(io, ROOT, [withBrowser]); + const text = io.files.get(workspaceFilePath(ROOT)) ?? ''; + // The Mac's field names, so either app reads the other's tabs. + expect(text).toContain('"browserTab" : "tab-3"'); + expect(text).toContain('"kind" : "browser"'); + expect(text).toContain('"url" : "http:\\/\\/localhost:3000\\/"'); + const [restored] = await loadWorkspaces(io, ROOT); + const tabs = restored?.panes[workspace.focusedLeafId]?.tabs.map((tab) => tab.content); + expect(tabs?.slice(1)).toEqual([ + browserContent('tab-3', 'http://localhost:3000/'), + browserContent(null, null), + ]); + }); + it('givenPointGuardWorkspaceShouldSaveItsTabAsPointGuard', async () => { const io = memoryWorkspaceFileIO(); await saveWorkspaces(io, ROOT, [pointGuardWorkspace(ROOT)]); diff --git a/apps/purepoint-windows/ui/src/model/workspacePersistence.ts b/apps/purepoint-windows/ui/src/model/workspacePersistence.ts index 2459568f..b68866b3 100644 --- a/apps/purepoint-windows/ui/src/model/workspacePersistence.ts +++ b/apps/purepoint-windows/ui/src/model/workspacePersistence.ts @@ -29,6 +29,7 @@ import { POINT_GUARD_CONTENT, PROJECT_ROOT, agentContent, + browserContent, containerWorktreeId, contentAgentId, fileContent, @@ -50,12 +51,16 @@ import { */ export const CURRENT_DOCUMENT_VERSION = 4; -/** Swift `PersistedSurface`. `kind` is `agent`, `file`, `point_guard` or `empty`. */ +/** Swift `PersistedSurface`. `kind` is `agent`, `file`, `browser`, `point_guard` or `empty`. */ export interface PersistedSurface { readonly id: number; readonly kind: string; readonly agentId?: string; readonly path?: string; + /** Browser tabs: the daemon's tab id. */ + readonly browserTab?: string; + /** Browser tabs: the last page shown. */ + readonly url?: string; } /** @@ -204,6 +209,8 @@ function decodeSurface(value: unknown): PersistedSurface { kind: required(object, 'kind', asString), ...present('agentId', optional(object, 'agentId', asString)), ...present('path', optional(object, 'path', asString)), + ...present('browserTab', optional(object, 'browserTab', asString)), + ...present('url', optional(object, 'url', asString)), }; } @@ -327,6 +334,13 @@ export function persistedSurface(surface: Surface): PersistedSurface { return { id, kind: 'agent', agentId: content.agentId }; case 'file': return { id, kind: 'file', ...present('path', content.path ?? undefined) }; + case 'browser': + return { + id, + kind: 'browser', + ...present('browserTab', content.tabId ?? undefined), + ...present('url', content.url ?? undefined), + }; } } @@ -343,6 +357,9 @@ export function surfaceFromPersisted(persisted: PersistedSurface): Surface { case 'point_guard': content = POINT_GUARD_CONTENT; break; + case 'browser': + content = browserContent(persisted.browserTab ?? null, persisted.url ?? null); + break; default: content = EMPTY_CONTENT; } diff --git a/apps/purepoint-windows/ui/src/protocol/protocol.test.ts b/apps/purepoint-windows/ui/src/protocol/protocol.test.ts index 4130d20a..bbb9d4ea 100644 --- a/apps/purepoint-windows/ui/src/protocol/protocol.test.ts +++ b/apps/purepoint-windows/ui/src/protocol/protocol.test.ts @@ -40,7 +40,7 @@ const wrongTag: GridCommand = { type: 'get_layout' }; describe('generated protocol types', () => { it('match the pu-core protocol version', () => { - expect(PROTOCOL_VERSION).toBe(14); + expect(PROTOCOL_VERSION).toBe(15); }); it('carry samples for every direction', () => { diff --git a/apps/purepoint-windows/ui/src/services/attach.ts b/apps/purepoint-windows/ui/src/services/attach.ts index b1ce080b..77880b70 100644 --- a/apps/purepoint-windows/ui/src/services/attach.ts +++ b/apps/purepoint-windows/ui/src/services/attach.ts @@ -79,7 +79,7 @@ function wireData(data: string | Uint8Array): string | number[] { * calls in flight together can reach the session in either order, and fast typing came out * transposed ("menu" as "meun"). The Mac writes keystrokes to its socket in order on one queue. */ -function serialSender(): (send: () => Promise) => Promise { +export function serialSender(): (send: () => Promise) => Promise { let tail: Promise = Promise.resolve(); return (send: () => Promise): Promise => { const result = tail.then(send, send); diff --git a/apps/purepoint-windows/ui/src/services/browser.ts b/apps/purepoint-windows/ui/src/services/browser.ts new file mode 100644 index 00000000..3fe9f10a --- /dev/null +++ b/apps/purepoint-windows/ui/src/services/browser.ts @@ -0,0 +1,78 @@ +// Front end of the browser pane sessions: `src-tauri/src/browser/`, the stream half of +// State/BrowserSession.swift. Each browser pane opens one session, which holds its own +// `browser_attach` stream to the project's daemon (this PC's, or a machine's over the same ssh +// relay as its terminals). Every message is a JSON {@link BrowserStreamEvent}, in stream order; +// frames carry the daemon's base64 JPEG unchanged. +import { Channel, invoke } from '@tauri-apps/api/core'; +import type { BrowserOp, BrowserTabInfo } from '../protocol'; +import { serialSender } from './attach'; + +export type BrowserSessionId = number; + +/** What the backend reports (`session::BrowserEvent`). */ +export type BrowserStreamEvent = + /** The tab the session shows, or its new state. */ + | { type: 'tab'; tab: BrowserTabInfo } + /** Attached; frames follow. */ + | { type: 'live' } + /** A frame: `data` is a base64 JPEG of the CSS viewport `width` x `height`. Ack `seq` once drawn. */ + | { type: 'frame'; seq: number; data: string; width: number; height: number } + /** The answer to an `eval` sent on the stream. */ + | { type: 'eval_result'; value: unknown } + /** A transient problem to show over the page. */ + | { type: 'notice'; code: string; message: string } + /** The connection failed; the session tries again after `delayMs`. */ + | { type: 'retrying'; attempt: number; delayMs: number; message: string } + /** The tab closed. The session has ended. */ + | { type: 'closed' } + /** A refusal only the person can fix. The session has ended. */ + | { type: 'failed'; code: string; message: string }; + +export interface BrowserOpenOptions { + /** The daemon's tab, `null` to open one (on `url`). */ + tabId: string | null; + url: string | null; + /** A remote machine's daemon instead of the local one. */ + machineId?: string | null; +} + +/** One pane's stream. */ +export interface BrowserStream { + readonly id: BrowserSessionId; + /** An op on the stream's tab (leave `tab_id` out). */ + send(op: BrowserOp): Promise; + close(): Promise; +} + +/** Opens a stream; injectable so the session logic tests without Tauri. */ +export type OpenBrowserStream = ( + projectRoot: string, + options: BrowserOpenOptions, + onEvent: (event: BrowserStreamEvent) => void, +) => Promise; + +/** Open a browser session on `projectRoot`'s browser (`browser_open`). */ +export const openBrowserStream: OpenBrowserStream = async (projectRoot, options, onEvent) => { + const channel = new Channel((event) => { + onEvent(event); + }); + const id = await invoke('browser_open', { + projectRoot, + tabId: options.tabId, + url: options.url, + onEvent: channel, + machineId: options.machineId ?? null, + }); + // Input reaches the page in the order it was sent (key down before up, press before release): + // concurrent invocations could otherwise arrive in either order (see `serialSender`). + const inOrder = serialSender(); + return { + id, + async send(op) { + await inOrder(() => invoke('browser_send', { sessionId: id, op })); + }, + async close() { + await invoke('browser_close', { sessionId: id }); + }, + }; +}; diff --git a/apps/purepoint-windows/ui/src/services/daemonConnection.ts b/apps/purepoint-windows/ui/src/services/daemonConnection.ts index b0ffde4e..274077ac 100644 --- a/apps/purepoint-windows/ui/src/services/daemonConnection.ts +++ b/apps/purepoint-windows/ui/src/services/daemonConnection.ts @@ -424,6 +424,18 @@ const DECODERS: { readonly [K in Response['type']]: VariantDecoder } = { agent_id: at(o, 'agent_id', string, '$'), data: at(o, 'data', string, '$'), }), + // Browser panes stream through the backend (`src-tauri/src/browser/`), which decodes them; + // a one-shot browser reply is read only by its type and tab. + browser_tab: passthrough(), + browser_tabs: passthrough(), + browser_snapshot: passthrough(), + browser_screenshot: passthrough(), + browser_console: passthrough(), + browser_eval_result: passthrough(), + browser_attached: passthrough(), + browser_frame: passthrough(), + browser_tab_state: passthrough(), + browser_tab_closed: passthrough(), grid_subscribed: () => ({ type: 'grid_subscribed' }), grid_layout: passthrough(), grid_event: passthrough(), diff --git a/apps/purepoint-windows/ui/src/state/browserSession.test.ts b/apps/purepoint-windows/ui/src/state/browserSession.test.ts new file mode 100644 index 00000000..76b09b32 --- /dev/null +++ b/apps/purepoint-windows/ui/src/state/browserSession.test.ts @@ -0,0 +1,267 @@ +// Tests for the BrowserSession.swift port's state and actions, over a fake backend stream. +import { describe, expect, it, vi } from 'vitest'; +import type { BrowserOp, BrowserTabInfo } from '../protocol'; +import type { + BrowserOpenOptions, + BrowserStream, + BrowserStreamEvent, + OpenBrowserStream, +} from '../services/browser'; +import { BrowserSession, type BrowserSessionOptions } from './browserSession'; + +interface FakeStream { + readonly projectRoot: string; + readonly options: BrowserOpenOptions; + readonly emit: (event: BrowserStreamEvent) => void; + readonly sent: BrowserOp[]; + closed: boolean; +} + +/** A backend whose streams the test drives; each open resolves at once unless held. */ +function fakeBackend() { + const streams: FakeStream[] = []; + const open: OpenBrowserStream = (projectRoot, options, onEvent) => { + const fake: FakeStream = { projectRoot, options, emit: onEvent, sent: [], closed: false }; + streams.push(fake); + const stream: BrowserStream = { + id: streams.length, + send: (op) => { + fake.sent.push(op); + return Promise.resolve(); + }, + close: () => { + fake.closed = true; + return Promise.resolve(); + }, + }; + return Promise.resolve(stream); + }; + return { open, streams }; +} + +function tab(overrides: Partial = {}): BrowserTabInfo { + return { + tab_id: 't1', + url: 'http://localhost:3000/', + title: '', + loading: false, + driver: 'agent', + can_go_back: false, + can_go_forward: false, + width: 1280, + height: 800, + ...overrides, + }; +} + +async function settle(): Promise { + await Promise.resolve(); + await Promise.resolve(); +} + +function makeSession(overrides: Partial = {}) { + const backend = fakeBackend(); + const onTabChange = vi.fn(); + const copy = vi.fn(); + const session = new BrowserSession({ + projectRoot: '/p', + machineId: 'm1', + tabId: null, + url: 'http://localhost:3000/', + onTabChange, + open: backend.open, + copy, + ...overrides, + }); + const stream = (index = 0): FakeStream => { + const found = backend.streams[index]; + if (found === undefined) throw new Error(`no stream ${String(index)}`); + return found; + }; + return { session, backend, onTabChange, copy, stream }; +} + +describe('BrowserSession', () => { + it('givenStartShouldOpenAStreamOnTheProjectsMachineWithItsTabAndPage', async () => { + const { session, stream } = makeSession({ tabId: 't0' }); + session.start(); + session.start(); // once only + await settle(); + expect(stream().projectRoot).toBe('/p'); + expect(stream().options).toEqual({ + tabId: 't0', + url: 'http://localhost:3000/', + machineId: 'm1', + }); + expect(session.state.phase).toEqual({ kind: 'connecting' }); + }); + + it('givenTabEventsShouldRecordANewTabOrPageOnlyWhenItChanges', async () => { + const { session, stream, onTabChange } = makeSession(); + session.start(); + await settle(); + stream().emit({ type: 'tab', tab: tab() }); + stream().emit({ type: 'tab', tab: tab({ loading: true }) }); + stream().emit({ type: 'tab', tab: tab({ url: 'http://localhost:3000/b' }) }); + // A blank page keeps the last real page as the one to reopen. + stream().emit({ type: 'tab', tab: tab({ url: 'about:blank' }) }); + stream().emit({ type: 'live' }); + expect(onTabChange.mock.calls).toEqual([ + ['t1', 'http://localhost:3000/'], + ['t1', 'http://localhost:3000/b'], + ['t1', 'http://localhost:3000/b'], + ]); + expect(session.state.phase).toEqual({ kind: 'live' }); + expect(session.state.tab?.url).toBe('about:blank'); + }); + + it('givenResizeBeforeTheStreamExistsShouldSendItOnceItDoesAndSkipRepeats', async () => { + const { session, stream } = makeSession(); + session.start(); + session.resize(640, 400, 1.5); + await settle(); + session.resize(640, 400, 1.5); + session.resize(0, 400, 1.5); + session.resize(800, 400, 1.5); + expect(stream().sent).toEqual([ + { action: 'resize', width: 640, height: 400, scale: 1.5 }, + { action: 'resize', width: 800, height: 400, scale: 1.5 }, + ]); + }); + + it('givenFramesShouldShowThemAndAckOnlyOnceDrawn', async () => { + const { session, stream } = makeSession(); + session.start(); + await settle(); + stream().emit({ type: 'frame', seq: 3, data: '/9j/', width: 1024, height: 768 }); + expect(session.state.frame).toEqual({ seq: 3, data: '/9j/', width: 1024, height: 768 }); + expect(session.state.frameSize).toEqual({ width: 1024, height: 768 }); + expect(stream().sent).toEqual([]); + session.frameDrawn(3); + expect(stream().sent).toEqual([{ action: 'frame_ack', seq: 3 }]); + }); + + it('givenActionsShouldSendTheirOpsOnTheStream', async () => { + const { session, stream } = makeSession(); + session.start(); + await settle(); + session.navigate(' localhost:5173 '); + session.navigate(' '); + session.goBack(); + session.goForward(); + session.reload(); + session.setHumanDriving(true); + session.setHumanDriving(false); + session.input({ kind: 'text', text: 'hi' }); + expect(stream().sent).toEqual([ + { action: 'navigate', url: 'localhost:5173' }, + { action: 'history', direction: 'back' }, + { action: 'history', direction: 'forward' }, + { action: 'history', direction: 'reload' }, + { action: 'control', driver: 'human' }, + { action: 'control', driver: 'agent' }, + { action: 'input', event: { kind: 'text', text: 'hi' } }, + ]); + }); + + it('givenCopyShouldPutTheSelectionOnTheClipboardOnce', async () => { + const { session, stream, copy } = makeSession(); + session.start(); + await settle(); + session.copySelection(); + expect(stream().sent[0]).toMatchObject({ action: 'eval' }); + stream().emit({ type: 'eval_result', value: 'selected' }); + stream().emit({ type: 'eval_result', value: 'again' }); + expect(copy.mock.calls).toEqual([['selected']]); + }); + + it('givenRetriesShouldSayConnectingThenFailedAfterThree', async () => { + const { session, stream } = makeSession(); + session.start(); + await settle(); + stream().emit({ type: 'retrying', attempt: 3, delayMs: 300, message: 'down' }); + expect(session.state.phase).toEqual({ kind: 'connecting' }); + stream().emit({ type: 'retrying', attempt: 4, delayMs: 2000, message: 'down' }); + expect(session.state.phase).toEqual({ kind: 'failed', message: 'down' }); + stream().emit({ type: 'live' }); + expect(session.state.phase).toEqual({ kind: 'live' }); + }); + + it('givenClosedTabShouldReopenANewTabOnTheLastPage', async () => { + const { session, stream } = makeSession({ tabId: 't0', url: null }); + session.start(); + await settle(); + stream().emit({ type: 'tab', tab: tab({ tab_id: 't0', url: 'http://localhost:8080/x' }) }); + stream().emit({ type: 'frame', seq: 1, data: 'x', width: 1, height: 1 }); + stream().emit({ type: 'closed' }); + expect(session.state.phase).toEqual({ kind: 'closed' }); + expect(session.state.frame).toBeNull(); + expect(stream().closed).toBe(true); + + session.reopen(); + await settle(); + expect(stream(1).options).toEqual({ + tabId: null, + url: 'http://localhost:8080/x', + machineId: 'm1', + }); + expect(session.state.phase).toEqual({ kind: 'connecting' }); + }); + + it('givenFinalFailureShouldShowItsMessage', async () => { + const { session, stream } = makeSession(); + session.start(); + await settle(); + stream().emit({ type: 'failed', code: 'BROWSER_NOT_FOUND', message: 'Install Chrome' }); + expect(session.state.phase).toEqual({ kind: 'failed', message: 'Install Chrome' }); + }); + + it('givenOpenFailsShouldFail', async () => { + const session = new BrowserSession({ + projectRoot: '/p', + machineId: null, + tabId: null, + url: null, + open: () => Promise.reject(new Error('no backend')), + }); + session.start(); + await settle(); + expect(session.state.phase).toEqual({ kind: 'failed', message: 'no backend' }); + }); + + it('givenStopShouldCloseTheStreamAndDropItsLateEvents', async () => { + const { session, stream } = makeSession(); + session.start(); + await settle(); + session.stop(); + expect(stream().closed).toBe(true); + stream().emit({ type: 'tab', tab: tab() }); + expect(session.state.tab).toBeNull(); + session.goBack(); + expect(stream().sent).toEqual([]); + }); + + it('givenStopBeforeTheStreamOpensShouldCloseItWhenItArrives', async () => { + const { session, stream } = makeSession(); + session.start(); + session.stop(); + await settle(); + expect(stream().closed).toBe(true); + }); + + it('givenNoticeShouldShowItForAWhile', async () => { + const timers: (() => void)[] = []; + const { session, stream } = makeSession({ + setTimer: (run) => timers.push(run), + clearTimer: () => undefined, + }); + session.start(); + await settle(); + stream().emit({ type: 'notice', code: 'BROWSER_NAVIGATION_FAILED', message: 'net::ERR' }); + expect(session.state.notice).toBe('net::ERR'); + timers.forEach((run) => { + run(); + }); + expect(session.state.notice).toBeNull(); + }); +}); diff --git a/apps/purepoint-windows/ui/src/state/browserSession.ts b/apps/purepoint-windows/ui/src/state/browserSession.ts new file mode 100644 index 00000000..1360021f --- /dev/null +++ b/apps/purepoint-windows/ui/src/state/browserSession.ts @@ -0,0 +1,316 @@ +// Port of apps/purepoint-macos/purepoint-macos/State/BrowserSession.swift (the session's state and +// actions): one browser pane's live view of a tab of the project's browser. +// +// The browser runs on the project's daemon's machine. The stream itself (open a tab if the pane +// has none, attach, reopen a lost tab on its last page, reconnect) runs in the backend +// (`src-tauri/src/browser/session.rs`, through services/browser.ts); this keeps what the pane +// shows and turns the person's actions into ops on that stream. +// +// Differences from Swift: +// - Frames are acked by the view once it has drawn them (`frameDrawn`), not here: the decode +// happens in the view's canvas. +// - A resize asked for before the backend session exists is kept and sent once it does (the +// backend then replays it on every reattach, as the Swift session does). +import { createStore, type StoreApi } from 'zustand/vanilla'; +import type { BrowserInputEvent, BrowserOp, BrowserTabInfo } from '../protocol'; +import { + BROWSER_FAILED_AFTER, + BROWSER_NOTICE_MS, + COPY_SELECTION_EXPRESSION, + DEFAULT_FRAME_SIZE, + type BrowserPhase, + type Size, + evalText, + isHumanDriving, +} from '../model/browser'; +import { + type BrowserStream, + type BrowserStreamEvent, + type OpenBrowserStream, + openBrowserStream, +} from '../services/browser'; + +/** The frame on screen: a base64 JPEG and the CSS viewport it shows. */ +export interface BrowserFrame { + readonly seq: number; + readonly data: string; + readonly width: number; + readonly height: number; +} + +export interface BrowserSessionFields { + readonly phase: BrowserPhase; + readonly tab: BrowserTabInfo | null; + readonly frame: BrowserFrame | null; + /** The CSS viewport the current frame shows, for mapping input coordinates. */ + readonly frameSize: Size; + /** A transient problem to show over the page. */ + readonly notice: string | null; +} + +export interface BrowserSessionOptions { + readonly projectRoot: string; + /** A remote project's machine, whose daemon runs its browser. */ + readonly machineId: string | null; + readonly tabId: string | null; + readonly url: string | null; + /** The pane shows another tab or page: record it so it reattaches after a relaunch. */ + readonly onTabChange?: (tabId: string, url: string | null) => void; + readonly open?: OpenBrowserStream; + /** Puts Copy's text on the clipboard. */ + readonly copy?: (text: string) => void; + readonly setTimer?: (run: () => void, ms: number) => unknown; + readonly clearTimer?: (handle: unknown) => void; +} + +type Viewport = { width: number; height: number; scale: number }; + +export class BrowserSession { + readonly store: StoreApi; + readonly projectRoot: string; + private onTabChange: (tabId: string, url: string | null) => void; + private readonly options: BrowserSessionOptions; + private readonly open: OpenBrowserStream; + private tabId: string | null; + private lastUrl: string | null; + private stream: BrowserStream | null = null; + /** Bumped per start and stop, so a superseded stream's late events are dropped. */ + private generation = 0; + private started = false; + private viewport: Viewport | null = null; + private pendingCopy = false; + private noticeTimer: unknown = null; + + constructor(options: BrowserSessionOptions) { + this.options = options; + this.projectRoot = options.projectRoot; + this.open = options.open ?? openBrowserStream; + this.onTabChange = options.onTabChange ?? (() => undefined); + this.tabId = options.tabId; + this.lastUrl = options.url; + this.store = createStore()(() => ({ + phase: { kind: 'connecting' }, + tab: null, + frame: null, + frameSize: DEFAULT_FRAME_SIZE, + notice: null, + })); + } + + /** Who records the tab and page the pane shows (the view keeps it current). */ + setOnTabChange(onTabChange: (tabId: string, url: string | null) => void): void { + this.onTabChange = onTabChange; + } + + get state(): BrowserSessionFields { + return this.store.getState(); + } + + get isHumanDriving(): boolean { + return isHumanDriving(this.state.tab); + } + + start(): void { + if (this.started) return; + this.started = true; + const generation = ++this.generation; + this.store.setState({ phase: { kind: 'connecting' } }); + const current = (): boolean => generation === this.generation; + this.open( + this.projectRoot, + { tabId: this.tabId, url: this.lastUrl, machineId: this.options.machineId }, + (event) => { + if (current()) this.handle(event); + }, + ).then( + (stream) => { + if (!current()) { + void stream.close(); + return; + } + this.stream = stream; + if (this.viewport !== null) this.sendResize(this.viewport); + }, + (error: unknown) => { + if (!current()) return; + this.started = false; + this.store.setState({ phase: { kind: 'failed', message: errorText(error) } }); + }, + ); + } + + stop(): void { + this.generation += 1; + this.started = false; + const stream = this.stream; + this.stream = null; + void stream?.close().catch(() => undefined); + this.clearNotice(); + } + + /** Opens a fresh tab on the last page, after the tab closed or the session failed. */ + reopen(): void { + this.stop(); + this.tabId = null; + this.store.setState({ frame: null }); + this.start(); + } + + // MARK: - Actions + + navigate(address: string): void { + const url = address.trim(); + if (url === '') return; + this.send({ action: 'navigate', url }); + } + + goBack(): void { + this.send({ action: 'history', direction: 'back' }); + } + + goForward(): void { + this.send({ action: 'history', direction: 'forward' }); + } + + reload(): void { + this.send({ action: 'history', direction: 'reload' }); + } + + /** Take the tab from agents, or hand it back to them. */ + setHumanDriving(human: boolean): void { + this.send({ action: 'control', driver: human ? 'human' : 'agent' }); + } + + input(event: BrowserInputEvent): void { + this.send({ action: 'input', event }); + } + + /** Copy the page's selected text to the clipboard. */ + copySelection(): void { + this.pendingCopy = true; + this.send({ action: 'eval', expression: COPY_SELECTION_EXPRESSION }); + } + + /** The pane's size in CSS pixels and its pixel density; the page's viewport follows it. */ + resize(width: number, height: number, scale: number): void { + if (width <= 0 || height <= 0) return; + const last = this.viewport; + if (last !== null && last.width === width && last.height === height && last.scale === scale) { + return; + } + this.viewport = { width, height, scale }; + if (this.stream !== null) this.sendResize(this.viewport); + } + + /** The view drew frame `seq`: the daemon may send the next (it keeps at most two ahead). */ + frameDrawn(seq: number): void { + this.send({ action: 'frame_ack', seq }); + } + + private sendResize(viewport: Viewport): void { + this.send({ action: 'resize', ...viewport }); + } + + private send(op: BrowserOp): void { + void this.stream?.send(op).catch(() => undefined); + } + + // MARK: - Stream events + + /** One event from the backend session. Exposed for tests. */ + handle(event: BrowserStreamEvent): void { + switch (event.type) { + case 'tab': + this.adopt(event.tab); + return; + case 'live': + this.store.setState({ phase: { kind: 'live' } }); + return; + case 'frame': + this.store.setState({ + frame: { seq: event.seq, data: event.data, width: event.width, height: event.height }, + frameSize: { width: event.width, height: event.height }, + }); + return; + case 'eval_result': { + const text = evalText(event.value); + if (this.pendingCopy && text !== null) this.options.copy?.(text); + this.pendingCopy = false; + return; + } + case 'notice': + this.showNotice(event.message); + return; + case 'retrying': + // The backend keeps trying; after three misses the pane says so (and offers Try Again). + this.store.setState({ + phase: + event.attempt > BROWSER_FAILED_AFTER + ? { kind: 'failed', message: event.message } + : { kind: 'connecting' }, + }); + return; + case 'closed': + this.ended(); + this.store.setState({ phase: { kind: 'closed' }, frame: null }); + return; + case 'failed': + this.ended(); + this.store.setState({ phase: { kind: 'failed', message: event.message } }); + return; + } + } + + /** The backend session ended on its own: release it (the tab, if any, stays open). */ + private ended(): void { + // A stream still opening is closed when it arrives, like one superseded by `stop`. + this.generation += 1; + this.started = false; + const stream = this.stream; + this.stream = null; + void stream?.close().catch(() => undefined); + } + + private adopt(tab: BrowserTabInfo): void { + const before = this.state.tab; + const changed = before?.tab_id !== tab.tab_id || before.url !== tab.url; + this.store.setState({ tab }); + this.tabId = tab.tab_id; + if (tab.url !== 'about:blank') this.lastUrl = tab.url; + if (changed) this.onTabChange(tab.tab_id, this.lastUrl); + } + + private showNotice(text: string): void { + this.clearNotice(); + this.store.setState({ notice: text }); + const setTimer = this.options.setTimer ?? ((run, ms) => setTimeout(run, ms)); + this.noticeTimer = setTimer(() => { + this.noticeTimer = null; + this.store.setState({ notice: null }); + }, BROWSER_NOTICE_MS); + } + + private clearNotice(): void { + if (this.noticeTimer === null) return; + const clearTimer = + this.options.clearTimer ?? + ((handle) => { + clearTimeout(handle as ReturnType); + }); + clearTimer(this.noticeTimer); + this.noticeTimer = null; + } +} + +function errorText(error: unknown): string { + if (error instanceof Error) return error.message; + if ( + typeof error === 'object' && + error !== null && + 'message' in error && + typeof error.message === 'string' + ) { + return error.message; + } + return String(error); +} diff --git a/apps/purepoint-windows/ui/src/state/gridCommands.test.ts b/apps/purepoint-windows/ui/src/state/gridCommands.test.ts index 3ba2a9ed..0a7c4b8c 100644 --- a/apps/purepoint-windows/ui/src/state/gridCommands.test.ts +++ b/apps/purepoint-windows/ui/src/state/gridCommands.test.ts @@ -7,6 +7,7 @@ import { describe, expect, it } from 'vitest'; import { agentContent, + browserContent, focusedAgentId, focusedSurface, leafIdOfSurface, @@ -307,4 +308,106 @@ describe('grid commands', () => { expect(registry.workspace('ws-ag-a')).toEqual(before); }); + + it('open_browser: opens a tab showing the browser tab in the target pane', () => { + const registry = makeRegistry(); + + apply(registry, { action: 'open_browser', browser_tab: 'tab-1' }); + + const workspace = ws(registry); + expect(tabCount(workspace)).toBe(2); + expect(focusedSurface(workspace)?.content).toEqual(browserContent('tab-1', null)); + }); + + it('open_browser: a browser tab already on screen is brought forward, not opened twice', () => { + const registry = makeRegistry(); + apply(registry, { action: 'open_browser', browser_tab: 'tab-1' }); + const browserSurface = focusedSurface(ws(registry))?.id; + registry.selectTabAt('ws-ag-a', 0, 0); + + apply(registry, { action: 'open_browser', browser_tab: 'tab-1' }); + + const workspace = ws(registry); + expect(tabCount(workspace)).toBe(2); + expect(focusedSurface(workspace)?.id).toBe(browserSurface); + }); + + it('open_browser: an unknown leaf is ignored', () => { + const registry = makeRegistry(); + const before = registry.workspace('ws-ag-a'); + + apply(registry, { action: 'open_browser', leaf_id: 9, browser_tab: 'tab-1' }); + + expect(registry.workspace('ws-ag-a')).toEqual(before); + }); +}); + +describe('browser tabs', () => { + function closedBrowserTabs(registry: WorkspaceRegistry): string[] { + const closed: string[] = []; + registry.onCloseBrowserTab = (projectRoot, tabId) => { + expect(projectRoot).toBe(root); + closed.push(tabId); + }; + return closed; + } + + it('openBrowser shows a new browser in a tab, and updateBrowser records its tab and page', () => { + const registry = makeRegistry(); + const surfaceId = registry.newTab('ws-ag-a', 0); + expect(surfaceId).not.toBeNull(); + const id = surfaceId as number; + + registry.openBrowser('ws-ag-a', id); + expect(focusedSurface(ws(registry))?.content).toEqual(browserContent(null, null)); + + registry.updateBrowser('ws-ag-a', id, 'tab-7', 'http://localhost:3000/'); + expect(focusedSurface(ws(registry))?.content).toEqual( + browserContent('tab-7', 'http://localhost:3000/'), + ); + }); + + it('updateBrowser leaves a tab that shows something else by now alone', () => { + const registry = makeRegistry(); + const id = registry.newTab('ws-ag-a', 0) as number; + + registry.updateBrowser('ws-ag-a', id, 'tab-7', 'http://localhost:3000/'); + + expect(focusedSurface(ws(registry))?.content).toEqual({ kind: 'empty' }); + }); + + it('closing the last pane tab showing a browser tab closes it on the daemon', () => { + const registry = makeRegistry(); + const closed = closedBrowserTabs(registry); + apply(registry, { action: 'open_browser', browser_tab: 'tab-1' }); + const first = focusedSurface(ws(registry))?.id as number; + // A second pane tab on the same browser tab (a reload of the layout, a hand edit). + const second = registry.newTab('ws-ag-a', 0, browserContent('tab-1', null)) as number; + + registry.closeTab('ws-ag-a', first); + expect(closed).toEqual([]); + + registry.closeTab('ws-ag-a', second); + expect(closed).toEqual(['tab-1']); + }); + + it('a browser tab that never opened one closes nothing', () => { + const registry = makeRegistry(); + const closed = closedBrowserTabs(registry); + const id = registry.newTab('ws-ag-a', 0, browserContent()) as number; + + registry.closeTab('ws-ag-a', id); + + expect(closed).toEqual([]); + }); + + it("openBrowserBesideAgent opens a loopback link in a new tab of the agent's workspace", () => { + const registry = makeRegistry(); + + expect(registry.openBrowserBesideAgent('ag-a', 'http://localhost:5173/')).toBe(true); + expect(focusedSurface(ws(registry))?.content).toEqual( + browserContent(null, 'http://localhost:5173/'), + ); + expect(registry.openBrowserBesideAgent('ag-unknown', 'http://localhost/')).toBe(false); + }); }); diff --git a/apps/purepoint-windows/ui/src/state/workspaceRegistry.tabs.test.ts b/apps/purepoint-windows/ui/src/state/workspaceRegistry.tabs.test.ts index f501e45a..5dab436f 100644 --- a/apps/purepoint-windows/ui/src/state/workspaceRegistry.tabs.test.ts +++ b/apps/purepoint-windows/ui/src/state/workspaceRegistry.tabs.test.ts @@ -55,6 +55,8 @@ function labels(workspace: Workspace, leafId: number): string[] { return '+'; case 'pointGuard': return 'Point Guard'; + case 'browser': + return surface.content.url ?? 'browser'; } }); } diff --git a/apps/purepoint-windows/ui/src/state/workspaceRegistry.ts b/apps/purepoint-windows/ui/src/state/workspaceRegistry.ts index 67bb5198..c5b468fc 100644 --- a/apps/purepoint-windows/ui/src/state/workspaceRegistry.ts +++ b/apps/purepoint-windows/ui/src/state/workspaceRegistry.ts @@ -25,6 +25,7 @@ import { POINT_GUARD_CONTENT, agentContent, breakTab, + browserContent, closePane, closeTab, containsAgent, @@ -58,12 +59,14 @@ import { setSplitRatio, setSurfaceContent, splitPane, + surfaceById, workspaceAgentIds, workspaceSurfaces, workspacesEqual, type FocusDirection, type LiveAgent, type PaneEdge, + type Surface, type SurfaceContent, type Workspace, type WorkspaceContainer, @@ -228,6 +231,17 @@ function withEntry( return Object.fromEntries(entries); } +/** The browser tab IDs these surfaces show, in order, without repeats. */ +function browserTabIds(surfaces: readonly { readonly surface: Surface }[]): string[] { + const ids = new Set(); + for (const { surface } of surfaces) { + if (surface.content.kind === 'browser' && surface.content.tabId !== null) { + ids.add(surface.content.tabId); + } + } + return [...ids]; +} + function errorMessage(error: unknown): string { return error instanceof Error ? error.message : String(error); } @@ -283,6 +297,8 @@ export class WorkspaceRegistry { readonly fileTabs = new FileTabStore(); /** Invoked with (projectRoot, agentId) when a tab holding an agent is closed. */ onCloseAgent: ((projectRoot: string, agentId: string) => void) | null = null; + /** Called with (project id, browser tab id) when the last pane tab showing a browser tab closes. */ + onCloseBrowserTab: ((projectRoot: string, tabId: string) => void) | null = null; private readonly persistence: WorkspacePersistence; private readonly loadWorkspaces: (projectRoot: string) => Workspace[]; @@ -860,6 +876,42 @@ export class WorkspaceRegistry { this.mutate(workspaceId, (w) => setSurfaceContent(w, fileContent(path), surfaceId)); } + /** + * Show a browser tab in a tab: an existing tab of the project's browser, or (with no `tabId`) a + * new one the pane opens, on `url` if given. + */ + openBrowser( + workspaceId: string, + surfaceId: number, + tabId: string | null = null, + url: string | null = null, + ): void { + this.mutate(workspaceId, (w) => setSurfaceContent(w, browserContent(tabId, url), surfaceId)); + } + + /** + * Open `url` in a new browser tab beside an agent's terminal, in its workspace's focused pane + * (a remote terminal's loopback link, Swift `BrowserLinks.open`). False when the agent has no + * workspace. + */ + openBrowserBesideAgent(agentId: string, url: string): boolean { + const workspaceId = this.workspaceIdForAgent(agentId); + const workspace = workspaceId === null ? null : this.workspace(workspaceId); + if (workspaceId === null || workspace === null) return false; + return this.newTab(workspaceId, workspace.focusedLeafId, browserContent(null, url)) !== null; + } + + /** + * Record which browser tab a pane shows and its page, so it reattaches after a relaunch. Leaves + * the tab alone if it shows something else by now. + */ + updateBrowser(workspaceId: string, surfaceId: number, tabId: string, url: string | null): void { + const current = this.workspace(workspaceId); + const surface = current === null ? null : surfaceById(current, surfaceId); + if (surface?.content.kind !== 'browser') return; + this.openBrowser(workspaceId, surfaceId, tabId, url); + } + /** * Bind an agent to a tab (`null` empties it). The binding wins over any other tab still claiming * the same agent, and the project is reconciled straight away so selection and persistence see @@ -907,6 +959,11 @@ export class WorkspaceRegistry { const original = list[index]; if (original === undefined) return; + // Browser tabs close with their pane tab, unless another pane tab still shows them. + const closing = new Set(surfaceIds); + const browserTabs = browserTabIds( + workspaceSurfaces(original).filter(({ surface }) => closing.has(surface.id)), + ); const { workspace: changed, killed } = body(original); let workspace = changed; for (const surfaceId of surfaceIds) this.dropReservation(projectRoot, workspaceId, surfaceId); @@ -924,6 +981,10 @@ export class WorkspaceRegistry { this.scheduleSave(projectRoot); for (const agentId of killed) this.onCloseAgent?.(projectRoot, agentId); + const stillShown = new Set(browserTabIds(list.flatMap(workspaceSurfaces))); + for (const tabId of browserTabs) { + if (!stillShown.has(tabId)) this.onCloseBrowserTab?.(projectRoot, tabId); + } } private mutate(workspaceId: string, body: (workspace: Workspace) => Workspace): void { @@ -1031,6 +1092,22 @@ export class WorkspaceRegistry { if (surfaceId !== null) this.breakTab(workspaceId, surfaceId, gridAxis(command.axis)); return; } + case 'open_browser': { + // Already on screen: just bring it forward. + const shown = workspaceSurfaces(current).find( + ({ surface }) => + surface.content.kind === 'browser' && surface.content.tabId === command.browser_tab, + ); + if (shown !== undefined) { + this.selectTab(workspaceId, shown.surface.id); + return; + } + const target = pane(command.leaf_id); + if (target !== null) { + this.newTab(workspaceId, target, browserContent(command.browser_tab, null)); + } + return; + } } } diff --git a/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.test.tsx b/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.test.tsx new file mode 100644 index 00000000..7888f3da --- /dev/null +++ b/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.test.tsx @@ -0,0 +1,145 @@ +// Tests for the BrowserPaneView.swift port: toolbar, overlays and input, over a fake stream. +import { act, fireEvent, render, screen } from '@testing-library/react'; +import { describe, expect, it, vi } from 'vitest'; +import type { BrowserOp, BrowserTabInfo } from '../../protocol'; +import type { BrowserStreamEvent, OpenBrowserStream } from '../../services/browser.ts'; +import { BrowserPaneView } from './BrowserPaneView.tsx'; + +function tab(overrides: Partial = {}): BrowserTabInfo { + return { + tab_id: 't1', + url: 'http://localhost:3000/', + title: '', + loading: false, + driver: 'agent', + can_go_back: false, + can_go_forward: false, + width: 1280, + height: 800, + ...overrides, + }; +} + +function setup(props: { tabId?: string | null; url?: string | null } = {}) { + const sent: BrowserOp[] = []; + const opens: { tabId: string | null; url: string | null }[] = []; + let emit: (event: BrowserStreamEvent) => void = () => undefined; + const open: OpenBrowserStream = (_root, options, onEvent) => { + opens.push({ tabId: options.tabId, url: options.url }); + emit = onEvent; + return Promise.resolve({ + id: opens.length, + send: (op) => { + sent.push(op); + return Promise.resolve(); + }, + close: () => Promise.resolve(), + }); + }; + const onTabChange = vi.fn(); + const clipboard = { + readText: vi.fn(() => Promise.resolve('pasted')), + writeText: vi.fn(() => Promise.resolve()), + }; + render( + undefined} + onTabChange={onTabChange} + open={open} + clipboard={clipboard} + />, + ); + const send = async (event: BrowserStreamEvent) => { + await act(async () => { + await Promise.resolve(); + emit(event); + }); + }; + return { sent, opens, send, onTabChange, clipboard }; +} + +describe('BrowserPaneView', () => { + it('connects, then follows the tab: address, history buttons and the driver', async () => { + const { send, onTabChange } = setup(); + expect(screen.getByTestId('browser-connecting')).toBeInTheDocument(); + await send({ type: 'tab', tab: tab({ can_go_back: true }) }); + await send({ type: 'live' }); + expect(screen.queryByTestId('browser-connecting')).not.toBeInTheDocument(); + expect(screen.getByLabelText('Address')).toHaveValue('http://localhost:3000/'); + expect(screen.getByRole('button', { name: 'Back' })).toBeEnabled(); + expect(screen.getByRole('button', { name: 'Forward' })).toBeDisabled(); + expect(onTabChange).toHaveBeenCalledWith('t1', 'http://localhost:3000/'); + expect(screen.getByRole('button', { name: /Take Control/ })).toBeInTheDocument(); + await send({ type: 'tab', tab: tab({ driver: 'human' }) }); + expect(screen.getByRole('button', { name: /Hand Back/ })).toBeInTheDocument(); + }); + + it('navigates to a typed address and sends toolbar actions', async () => { + const { send, sent } = setup(); + await send({ type: 'live' }); + const field = screen.getByLabelText('Address'); + fireEvent.focus(field); + fireEvent.change(field, { target: { value: 'localhost:5173' } }); + fireEvent.submit(field); + fireEvent.click(screen.getByRole('button', { name: 'Reload' })); + fireEvent.click(screen.getByRole('button', { name: /Take Control/ })); + expect(sent).toEqual([ + { action: 'navigate', url: 'localhost:5173' }, + { action: 'history', direction: 'reload' }, + { action: 'control', driver: 'human' }, + ]); + }); + + it('types into the page, pastes the clipboard as text and copies the selection', async () => { + const { send, sent, clipboard } = setup(); + await send({ type: 'live' }); + const canvas = screen.getByTestId('browser-canvas'); + fireEvent.keyDown(canvas, { key: 'x', code: 'KeyX' }); + fireEvent.keyUp(canvas, { key: 'x', code: 'KeyX' }); + await act(async () => { + fireEvent.keyDown(canvas, { key: 'v', code: 'KeyV', ctrlKey: true }); + await Promise.resolve(); + }); + fireEvent.keyDown(canvas, { key: 'c', code: 'KeyC', ctrlKey: true }); + await send({ type: 'eval_result', value: 'chosen' }); + expect(sent).toEqual([ + { + action: 'input', + event: { kind: 'key', action: 'down', key: 'x', code: 'KeyX', text: 'x', modifiers: 0 }, + }, + { + action: 'input', + event: { kind: 'key', action: 'up', key: 'x', code: 'KeyX', text: null, modifiers: 0 }, + }, + { action: 'input', event: { kind: 'text', text: 'pasted' } }, + { action: 'eval', expression: "String(getSelection ? getSelection() : '')" }, + ]); + expect(clipboard.writeText).toHaveBeenCalledWith('chosen'); + }); + + it('offers to reopen a closed tab, on its last page', async () => { + const { send, opens } = setup({ tabId: 't1', url: 'http://localhost:8080/' }); + await send({ type: 'tab', tab: tab({ url: 'http://localhost:8080/x' }) }); + await send({ type: 'closed' }); + expect(screen.getByText('This browser tab was closed.')).toBeInTheDocument(); + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'Reopen' })); + await Promise.resolve(); + }); + expect(opens.at(-1)).toEqual({ tabId: null, url: 'http://localhost:8080/x' }); + }); + + it('shows a failure with Try Again, and a notice over the page', async () => { + const { send } = setup(); + await send({ type: 'notice', code: 'BROWSER_NAVIGATION_FAILED', message: 'net::ERR' }); + expect(screen.getByRole('status')).toHaveTextContent('net::ERR'); + await send({ type: 'failed', code: 'BROWSER_NOT_FOUND', message: 'Install Chrome there' }); + expect(screen.getByText('Install Chrome there')).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Try Again' })).toBeInTheDocument(); + }); +}); diff --git a/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.tsx b/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.tsx new file mode 100644 index 00000000..33642b5a --- /dev/null +++ b/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.tsx @@ -0,0 +1,521 @@ +// Port of apps/purepoint-macos/purepoint-macos/Views/Browser/BrowserPaneView.swift and +// BrowserCanvas.swift: a browser pane, a live view of a tab of the project's browser, which runs +// headless on the project's machine (this PC, or a remote machine over the ssh relay). Agents +// drive the same tab with `pu browser`; Take Control stops them until the person hands it back. +// +// The toolbar (back, forward, reload, address, Take Control / Hand Back) sits over a canvas that +// draws the tab's frames and turns mouse, wheel and keyboard input into page input in CSS +// pixels (model/browser.ts). The pane's size and `devicePixelRatio` become the page's viewport. +// +// Differences from Swift: +// - Ctrl+V pastes the clipboard as typed text and Ctrl+C copies the page's selection (Cmd on +// the Mac). Other Ctrl chords go to the page and on to the app's shortcuts too (they are not +// swallowed), where the Mac sends Cmd chords to its menus first. +// - SF Symbols without a Lucide entry in the parity matrix: Take Control shows `keyboard` +// (the Mac's `hand.raised`), Hand Back `person` (`person.fill`). +import { + type KeyboardEvent as ReactKeyboardEvent, + type MouseEvent as ReactMouseEvent, + type Ref, + useCallback, + useEffect, + useLayoutEffect, + useRef, + useState, +} from 'react'; +import { useStore } from 'zustand'; +import { + HOVER_INTERVAL_MS, + addressFieldText, + hoverInput, + isHumanDriving, + keyInput, + mouseInput, + viewportOf, + wheelInput, + type Size, +} from '../../model/browser.ts'; +import type { BrowserInputEvent } from '../../protocol'; +import type { OpenBrowserStream } from '../../services/browser.ts'; +import { BrowserSession, type BrowserFrame } from '../../state/browserSession.ts'; +import { Icon } from '../../theme/Icon.tsx'; +import './browser.css'; + +export interface BrowserPaneViewProps { + /** The project's root on its machine. */ + projectRoot: string; + /** A remote project's machine; `null` for this PC. */ + machineId: string | null; + tabId: string | null; + url: string | null; + isFocused: boolean; + onFocus: () => void; + /** The pane now shows another tab or page (`WorkspaceRegistry.updateBrowser`). */ + onTabChange: (tabId: string, url: string | null) => void; + /** Tests stream from a fake; the app from the backend. */ + open?: OpenBrowserStream; + clipboard?: Pick; +} + +function systemClipboard(): Pick | null { + return typeof navigator !== 'undefined' && 'clipboard' in navigator ? navigator.clipboard : null; +} + +export function BrowserPaneView({ + projectRoot, + machineId, + tabId, + url, + isFocused, + onFocus, + onTabChange, + open, + clipboard, +}: BrowserPaneViewProps) { + const clip = clipboard ?? systemClipboard(); + const [session] = useState( + () => + new BrowserSession({ + projectRoot, + machineId, + tabId, + url, + ...(open === undefined ? {} : { open }), + copy: (text) => { + void clip?.writeText(text).catch(() => undefined); + }, + }), + ); + useLayoutEffect(() => { + session.setOnTabChange(onTabChange); + }, [onTabChange, session]); + const [startsBlank] = useState(tabId === null && url === null); + /** What the person is typing in the address field; `null` while it shows the page's URL. */ + const [draft, setDraft] = useState(null); + const addressRef = useRef(null); + const canvasRef = useRef(null); + + const phase = useStore(session.store, (s) => s.phase); + const tab = useStore(session.store, (s) => s.tab); + const frame = useStore(session.store, (s) => s.frame); + const frameSize = useStore(session.store, (s) => s.frameSize); + const notice = useStore(session.store, (s) => s.notice); + + useEffect(() => { + session.start(); + return () => { + session.stop(); + }; + }, [session]); + + useEffect(() => { + if (startsBlank) addressRef.current?.focus(); + }, [startsBlank]); + + // The field follows the tab's URL unless the person is typing an address. + const address = draft ?? addressFieldText(tab?.url ?? url); + + // A pane that takes the grid's focus gives the page the keyboard. + useEffect(() => { + if (isFocused && !startsBlank && document.activeElement !== addressRef.current) { + canvasRef.current?.focus({ preventScroll: true }); + } + }, [isFocused, startsBlank]); + + const paste = useCallback(() => { + clip?.readText().then( + (text) => { + if (text !== '') session.input({ kind: 'text', text }); + }, + () => undefined, + ); + }, [clip, session]); + + const human = isHumanDriving(tab); + return ( +
+
{ + event.preventDefault(); + session.navigate(address); + setDraft(null); + canvasRef.current?.focus({ preventScroll: true }); + }} + > + + + + { + setDraft(event.target.value); + }} + onFocus={(event) => { + setDraft(address); + event.target.select(); + }} + onBlur={() => { + setDraft(null); + }} + /> + {human ? ( + + ) : ( + + )} +
+
+ { + session.input(event); + }} + onResize={(width, height, scale) => { + session.resize(width, height, scale); + }} + onDrawn={(seq) => { + session.frameDrawn(seq); + }} + onCopy={() => { + session.copySelection(); + }} + onPaste={paste} + onFocus={() => { + addressRef.current?.blur(); + onFocus(); + }} + /> + {phase.kind === 'connecting' && frame === null && ( +
+
+ )} + {phase.kind === 'closed' && ( + { + session.reopen(); + }} + /> + )} + {phase.kind === 'failed' && ( + { + session.reopen(); + }} + /> + )} + {notice !== null && ( +
+ {notice} +
+ )} +
+
+ ); +} + +function BrowserMessage({ + text, + action, + onAction, +}: { + text: string; + action: string; + onAction: () => void; +}) { + return ( +
+ + {text} + +
+ ); +} + +interface BrowserCanvasProps { + ref: Ref; + frame: BrowserFrame | null; + /** The CSS viewport the frame shows. */ + cssSize: Size; + onInput: (event: BrowserInputEvent) => void; + onResize: (width: number, height: number, scale: number) => void; + onDrawn: (seq: number) => void; + onCopy: () => void; + onPaste: () => void; + onFocus: () => void; +} + +/** Decodes a frame's base64 JPEG (an `ImageBitmap` where the page has one). */ +async function decodeFrame(data: string): Promise { + const image = new Image(); + image.src = `data:image/jpeg;base64,${data}`; + await image.decode(); + return image; +} + +/** Swift `BrowserCanvas`: draws frames, reports its size, and maps input to the page. */ +function BrowserCanvas({ + ref, + frame, + cssSize, + onInput, + onResize, + onDrawn, + onCopy, + onPaste, + onFocus, +}: BrowserCanvasProps) { + const canvas = useRef(null); + const box = useRef(null); + const lastHover = useRef(0); + const drawnSeq = useRef(-1); + const handlers = useRef({ onResize, onDrawn }); + useLayoutEffect(() => { + handlers.current = { onResize, onDrawn }; + }); + + const setBox = useCallback( + (element: HTMLDivElement | null) => { + box.current = element; + if (typeof ref === 'function') ref(element); + else if (ref !== null) ref.current = element; + }, + [ref], + ); + + // The pane's size (and density) is the page's viewport. + useEffect(() => { + const element = box.current; + if (element === null || typeof ResizeObserver === 'undefined') return; + const report = () => { + const rect = element.getBoundingClientRect(); + const viewport = viewportOf(rect.width, rect.height, window.devicePixelRatio); + if (viewport === null) return; + const target = canvas.current; + if (target !== null) { + target.width = Math.round(viewport.width * viewport.scale); + target.height = Math.round(viewport.height * viewport.scale); + } + handlers.current.onResize(viewport.width, viewport.height, viewport.scale); + }; + const observer = new ResizeObserver(report); + observer.observe(element); + report(); + return () => { + observer.disconnect(); + }; + }, []); + + // Draw each frame, then ack it: the daemon sends at most two ahead of the screen. + useEffect(() => { + if (frame === null) { + // The tab closed (or reopens): blank the page; a new tab numbers its frames afresh. + if (drawnSeq.current >= 0) { + const target = canvas.current; + target?.getContext('2d')?.clearRect(0, 0, target.width, target.height); + drawnSeq.current = -1; + } + return; + } + let cancelled = false; + const { seq, data } = frame; + decodeFrame(data) + .then((image) => { + const target = canvas.current; + // A newer frame may have been drawn while this one decoded. + if (cancelled || target === null || seq < drawnSeq.current) return; + drawnSeq.current = seq; + target.getContext('2d')?.drawImage(image, 0, 0, target.width, target.height); + }) + .catch(() => undefined) + .finally(() => { + handlers.current.onDrawn(seq); + }); + return () => { + cancelled = true; + }; + }, [frame]); + + const geometry = (clientX: number, clientY: number) => { + const rect = box.current?.getBoundingClientRect(); + const view = { width: rect?.width ?? 0, height: rect?.height ?? 0 }; + return { x: clientX - (rect?.left ?? 0), y: clientY - (rect?.top ?? 0), view }; + }; + + const mouse = (event: ReactMouseEvent) => { + const { x, y, view } = geometry(event.clientX, event.clientY); + return { + view, + input: { + x, + y, + button: event.button, + // The click count on `mousedown`/`mouseup` (0 on moves). + detail: event.detail, + altKey: event.altKey, + ctrlKey: event.ctrlKey, + metaKey: event.metaKey, + shiftKey: event.shiftKey, + }, + }; + }; + + return ( +
{ + // Captured, so a drag that leaves the pane keeps reaching the page until release. + event.currentTarget.setPointerCapture(event.pointerId); + }} + onMouseDown={(event) => { + event.currentTarget.focus({ preventScroll: true }); + onFocus(); + const { view, input } = mouse(event); + onInput(mouseInput('down', input, view, cssSize)); + }} + onMouseUp={(event) => { + const { view, input } = mouse(event); + onInput(mouseInput('up', input, view, cssSize)); + }} + onMouseMove={(event) => { + const { view, input } = mouse(event); + if ((event.buttons & 1) !== 0) { + onInput(mouseInput('move', { ...input, button: 0, detail: 0 }, view, cssSize)); + return; + } + const now = performance.now(); + if (now - lastHover.current < HOVER_INTERVAL_MS) return; + lastHover.current = now; + onInput(hoverInput(input, view, cssSize)); + }} + onContextMenu={(event) => { + event.preventDefault(); + }} + onWheel={(event) => { + const { x, y, view } = geometry(event.clientX, event.clientY); + onInput( + wheelInput( + { + x, + y, + deltaX: event.deltaX, + deltaY: event.deltaY, + deltaMode: event.deltaMode, + altKey: event.altKey, + ctrlKey: event.ctrlKey, + metaKey: event.metaKey, + shiftKey: event.shiftKey, + }, + view, + cssSize, + ), + ); + }} + onKeyDown={(event) => { + handleKey(event, true); + }} + onKeyUp={(event) => { + handleKey(event, false); + }} + > + +
+ ); + + function handleKey(event: ReactKeyboardEvent, down: boolean) { + const action = keyInput(event, down); + switch (action.kind) { + case 'paste': + event.preventDefault(); + onPaste(); + return; + case 'copy': + event.preventDefault(); + onCopy(); + return; + case 'ignore': + return; + case 'send': + onInput(action.event); + // A chord also reaches the app's shortcuts (hotkeys skip prevented keys); everything + // else is the page's alone (Tab must not move focus out of the pane). + if (!(event.ctrlKey && !event.altKey) && !event.metaKey) event.preventDefault(); + return; + } + } +} diff --git a/apps/purepoint-windows/ui/src/views/browser/browser.css b/apps/purepoint-windows/ui/src/views/browser/browser.css new file mode 100644 index 00000000..d6748287 --- /dev/null +++ b/apps/purepoint-windows/ui/src/views/browser/browser.css @@ -0,0 +1,163 @@ +/* Browser panes: toolbar over the tab's frames (BrowserPaneView.swift). */ +.browser-pane { + flex: 1; + min-width: 0; + min-height: 0; + display: flex; + flex-direction: column; + background: var(--pp-card-background); + color: var(--pp-app-text); + font-family: var(--pp-font-ui); +} + +.browser-toolbar { + flex: none; + display: flex; + align-items: center; + gap: 6px; + padding: 5px 8px; + border-bottom: 1px solid var(--pane-separator); +} + +.browser-toolbar-button { + flex: none; + display: inline-flex; + align-items: center; + gap: 4px; + height: 24px; + min-width: 24px; + padding: 0 4px; + border: none; + border-radius: 4px; + background: transparent; + color: inherit; + font: inherit; + font-size: 12px; +} + +.browser-toolbar-button:hover:not(:disabled) { + background: rgba(127, 127, 127, 0.15); +} + +.browser-toolbar-button:disabled { + opacity: 0.35; +} + +.browser-toolbar-button[data-loading='true'] svg { + animation: browser-spin 1s linear infinite; +} + +.browser-driver[data-driver='human'] { + color: #ff9500; +} + +.browser-address { + flex: 1; + min-width: 60px; + height: 24px; + padding: 0 8px; + border: 1px solid var(--pane-separator); + border-radius: 5px; + background: rgba(127, 127, 127, 0.12); + color: inherit; + font: inherit; + font-size: 12px; +} + +.browser-address:focus { + outline: 2px solid #0a84ff; + outline-offset: -1px; +} + +.browser-body { + position: relative; + flex: 1; + min-height: 0; + display: flex; +} + +.browser-canvas { + flex: 1; + min-width: 0; + min-height: 0; + position: relative; + overflow: hidden; + background: #ffffff; + outline: none; +} + +.browser-canvas-surface { + position: absolute; + inset: 0; + width: 100%; + height: 100%; +} + +.browser-overlay { + position: absolute; + inset: 0; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 12px; + padding: 16px; + color: var(--secondary-text); + font-size: 13px; + text-align: center; +} + +.browser-message { + background: var(--pp-card-background); +} + +.browser-overlay-text { + max-width: 360px; +} + +.browser-message-icon { + opacity: 0.4; +} + +.browser-message-button { + padding: 4px 12px; + border: 1px solid var(--pane-separator); + border-radius: 4px; + background: rgba(127, 127, 127, 0.12); + color: var(--pp-app-text); + font: inherit; + font-size: 12px; +} + +.browser-message-button:hover { + background: rgba(127, 127, 127, 0.2); +} + +.browser-spinner { + width: 18px; + height: 18px; + border: 2px solid rgba(127, 127, 127, 0.3); + border-top-color: rgba(127, 127, 127, 0.9); + border-radius: 50%; + animation: browser-spin 0.8s linear infinite; +} + +.browser-notice { + position: absolute; + top: 8px; + left: 50%; + transform: translateX(-50%); + max-width: calc(100% - 32px); + padding: 6px 12px; + border-radius: 999px; + background: rgba(30, 30, 30, 0.85); + color: #ffffff; + font-size: 12px; + pointer-events: none; +} + +@keyframes browser-spin { + to { + transform: rotate(360deg); + } +} diff --git a/apps/purepoint-windows/ui/src/views/panegrid/PaneCellView.tsx b/apps/purepoint-windows/ui/src/views/panegrid/PaneCellView.tsx index 19971796..fbc8fedd 100644 --- a/apps/purepoint-windows/ui/src/views/panegrid/PaneCellView.tsx +++ b/apps/purepoint-windows/ui/src/views/panegrid/PaneCellView.tsx @@ -1,6 +1,6 @@ // Port of apps/purepoint-macos/purepoint-macos/Views/PaneGrid/PaneCellView.swift (WIN-7.4): one pane -// of the grid, its tab strip above the active tab's content: a terminal, the file navigator, or -// the empty-tab placeholder. +// of the grid, its tab strip above the active tab's content: a terminal, the file navigator, a +// browser, or the empty-tab placeholder. // // Only the active tab is rendered. A background agent's terminal stays alive in the terminal cache // (keyed by agent ID), so switching back is instant and keeps scrollback. @@ -8,6 +8,8 @@ // Differences from Swift: // - A file tab is FilePaneView (WIN-8.5), rooted at `AppState.fileRoot` on the project's host. // - Point Guard's chat surface is WIN-9.x; its tab shows a placeholder naming that view. +// - A browser tab is BrowserPaneView, on the project's daemon (a remote project's machine runs +// its browser, reached through the same relay as its terminals). // - The empty tab's New Agent button, and the tab a split or New Tab creates, open the command // palette (views/palette/openPalette.ts `openEmptyTabPalette`). // - While a tab is dragged, the content is covered by a drop overlay: the centre appends the tab @@ -23,6 +25,7 @@ import { openEmptyTabPalette } from '../palette/openPalette.ts'; import { useAppState } from '../shell/appContext.ts'; import { TerminalPane } from '../terminal/TerminalPane.tsx'; import { PointGuardChatSurfaceView } from '../chat/PointGuardView.tsx'; +import { BrowserPaneView } from '../browser/BrowserPaneView.tsx'; import { PaneTabBar } from './PaneTabBar.tsx'; import { type PaneDropZone, @@ -118,6 +121,19 @@ function PaneContent({ registry={registry} /> ); + case 'browser': + return ( + + ); case 'empty': return ( void; + registry: WorkspaceRegistry; +}) { + const app = useAppState(); + const projectId = registry.projectRoot(workspaceId); + const project = useStore(app.store, () => + projectId === null ? null : app.projectState(projectId), + ); + const onTabChange = useCallback( + (nextTab: string, nextUrl: string | null) => { + registry.updateBrowser(workspaceId, surfaceId, nextTab, nextUrl); + }, + [registry, surfaceId, workspaceId], + ); + if (project === null) { + return ( +
+ The project is not connected +
+ ); + } + return ( + + ); +} + /** Swift `EmptyTabView`: an empty tab, which opens the palette to spawn an agent or open files. */ function EmptyTabView({ workspaceId, @@ -191,16 +258,29 @@ function EmptyTabView({
Empty Tab - Spawn a new agent, or open files - + + Spawn a new agent, open files, or open a browser + +
+ + +
); } diff --git a/apps/purepoint-windows/ui/src/views/panegrid/PaneTabBar.tsx b/apps/purepoint-windows/ui/src/views/panegrid/PaneTabBar.tsx index f790f29c..18a88cc8 100644 --- a/apps/purepoint-windows/ui/src/views/panegrid/PaneTabBar.tsx +++ b/apps/purepoint-windows/ui/src/views/panegrid/PaneTabBar.tsx @@ -9,6 +9,7 @@ import { type DragEvent, createContext, useContext, useState, useSyncExternalStore } from 'react'; import { useStore } from 'zustand'; import { isAgentStatusAlive } from '../../model/agentStatus.ts'; +import { browserTabTitle } from '../../model/browser.ts'; import { canSplit, topTrailingLeafId } from '../../model/paneSplit.ts'; import { agentDisplayName, type AgentModel } from '../../model/workspaceModel.ts'; import { contentAgentId, paneActiveTab, paneCount, type Surface } from '../../model/workspace.ts'; @@ -197,6 +198,8 @@ function tabIcon(surface: Surface, agent: AgentModel | null): [SfSymbolName, str return ['bubble.left.and.bubble.right', 'secondary']; case 'file': return ['doc.text', 'secondary']; + case 'browser': + return ['globe', 'secondary']; case 'empty': return ['magnifyingglass', 'secondary']; } @@ -214,6 +217,8 @@ export function tabTitle(surface: Surface, agent: AgentModel | null): string { if (path === null) return 'Files'; return path.split(/[\\/]/).filter(Boolean).at(-1) ?? path; } + case 'browser': + return browserTabTitle(surface.content.url); case 'empty': return 'New Tab'; } diff --git a/apps/purepoint-windows/ui/src/views/panegrid/paneGrid.test.tsx b/apps/purepoint-windows/ui/src/views/panegrid/paneGrid.test.tsx index 487b1b50..b7d17a11 100644 --- a/apps/purepoint-windows/ui/src/views/panegrid/paneGrid.test.tsx +++ b/apps/purepoint-windows/ui/src/views/panegrid/paneGrid.test.tsx @@ -191,6 +191,25 @@ describe('PaneGridView', () => { fireEvent.mouseDown(screen.getByTestId('pane-empty-tab')); expect(ws().focusedLeafId).toBe(1); }); + + it("opens a browser from an empty tab, titled 'Browser' until a page loads", () => { + const { registry, ws } = setup(); + let surfaceId: number | null = null; + act(() => { + surfaceId = registry.newTab('ws', 1); + }); + fireEvent.click(screen.getByRole('button', { name: 'Open Browser' })); + const id = surfaceId as unknown as number; + expect(ws().panes[1]?.tabs.find((t) => t.id === id)?.content).toEqual({ + kind: 'browser', + tabId: null, + url: null, + }); + expect(tab(id)).toHaveTextContent('Browser'); + expect(tab(id).querySelector('[data-symbol="globe"]')).not.toBeNull(); + // The test app has no project for the workspace, so there is no daemon to stream from. + expect(screen.getByText('The project is not connected')).toBeInTheDocument(); + }); }); describe('PaneTabBar', () => { diff --git a/apps/purepoint-windows/ui/src/views/panegrid/panegrid.css b/apps/purepoint-windows/ui/src/views/panegrid/panegrid.css index 06dc15ef..781a5ad6 100644 --- a/apps/purepoint-windows/ui/src/views/panegrid/panegrid.css +++ b/apps/purepoint-windows/ui/src/views/panegrid/panegrid.css @@ -302,6 +302,21 @@ color: rgba(255, 255, 255, 0.1); } +.pane-empty-tab-buttons { + display: flex; + gap: 8px; +} + +.pane-browser-unavailable { + flex: 1; + display: flex; + align-items: center; + justify-content: center; + color: var(--secondary-text); + font-family: var(--pp-font-ui); + font-size: 13px; +} + .pane-empty-tab-button { padding: 4px 12px; border: 1px solid var(--pane-separator); diff --git a/apps/purepoint-windows/ui/src/views/shell/bootstrap.test.ts b/apps/purepoint-windows/ui/src/views/shell/bootstrap.test.ts index 447be727..ca41445b 100644 --- a/apps/purepoint-windows/ui/src/views/shell/bootstrap.test.ts +++ b/apps/purepoint-windows/ui/src/views/shell/bootstrap.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it, vi } from 'vitest'; import type { DaemonConnectionState } from '../../services/daemon.ts'; import type { InstallerState } from '../../services/installer.ts'; import type { AppState } from '../../state/appState.ts'; -import { startApp, type StartAppDeps } from './bootstrap.ts'; +import { closeBrowserTab, startApp, type StartAppDeps } from './bootstrap.ts'; function fakeApp() { const stopListening = vi.fn(); @@ -103,3 +103,25 @@ describe('startApp', () => { expect(app.restoreProjects).not.toHaveBeenCalled(); }); }); + +describe('closeBrowserTab', () => { + it("closes the tab on the project's own daemon, by its root on that machine", async () => { + const send = vi.fn(() => Promise.resolve({ type: 'ok' as const })); + const project = { projectRoot: '/home/dev/app', client: { send } }; + const app = { + projectState: (id: string) => (id === 'machine:m1:/home/dev/app' ? project : null), + }; + closeBrowserTab(app as unknown as AppState, 'machine:m1:/home/dev/app', 'tab-2'); + closeBrowserTab(app as unknown as AppState, '/gone', 'tab-3'); + await Promise.resolve(); + expect(send.mock.calls).toEqual([ + [ + { + type: 'browser', + project_root: '/home/dev/app', + op: { action: 'close', tab_id: 'tab-2' }, + }, + ], + ]); + }); +}); diff --git a/apps/purepoint-windows/ui/src/views/shell/bootstrap.ts b/apps/purepoint-windows/ui/src/views/shell/bootstrap.ts index 24963fcd..512daa1c 100644 --- a/apps/purepoint-windows/ui/src/views/shell/bootstrap.ts +++ b/apps/purepoint-windows/ui/src/views/shell/bootstrap.ts @@ -55,6 +55,9 @@ const defaultDeps: StartAppDeps = { loadMachines: (app) => { configureTerminals({ machineIdFor: (agentId) => app.projectStateForAgent(agentId)?.machineId ?? undefined, + // A remote agent's `http://localhost:…` is its machine's: open it in a browser pane. + openBrowserLink: (agentId, url) => + app.registry?.openBrowserBesideAgent(agentId, url) ?? false, }); app.loadMachines().catch(logged('loading machines')); }, @@ -121,9 +124,26 @@ export function createAppState(): AppState { registry.onCloseAgent = (projectId, agentId) => { app.projectState(projectId)?.removeAndKillAgent(agentId); }; + // The last pane tab showing a browser tab closed: close the tab on the project's daemon. + registry.onCloseBrowserTab = (projectId, tabId) => { + closeBrowserTab(app, projectId, tabId); + }; return app; } +/** Closes a tab of a project's browser (one-shot, on the project's own daemon). */ +export function closeBrowserTab(app: AppState, projectId: string, tabId: string): void { + const project = app.projectState(projectId); + if (project === null) return; + project.client + .send({ + type: 'browser', + project_root: project.projectRoot, + op: { action: 'close', tab_id: tabId }, + }) + .catch(logged('closing a browser tab')); +} + /** Starts everything; returns the function that stops the listeners. */ export function startApp(app: AppState, deps: StartAppDeps = defaultDeps): () => void { let stopped = false; diff --git a/apps/purepoint-windows/ui/src/views/terminal/terminalPaneView.ts b/apps/purepoint-windows/ui/src/views/terminal/terminalPaneView.ts index 8f8778d6..277cb46e 100644 --- a/apps/purepoint-windows/ui/src/views/terminal/terminalPaneView.ts +++ b/apps/purepoint-windows/ui/src/views/terminal/terminalPaneView.ts @@ -68,6 +68,8 @@ export interface TerminalPaneOptions { /** The daemon confirmed the agent is gone. */ onGone?: () => void; machineId?: string; + /** Opens a link the person Ctrl+clicked (the system browser when unset). */ + openLink?: (url: string) => void; fontSize?: number; heartbeatMs?: number; } @@ -129,6 +131,7 @@ export class TerminalPaneController { const create = options.createSurface ?? ((o) => new ScrollableTerminal(o)); this.surface = create({ fontSize: options.fontSize ?? TERMINAL_DEFAULT_FONT_SIZE, + ...(options.openLink === undefined ? {} : { openLink: options.openLink }), onData: (data) => { this.send(data); }, diff --git a/apps/purepoint-windows/ui/src/views/terminal/terminals.test.ts b/apps/purepoint-windows/ui/src/views/terminal/terminals.test.ts new file mode 100644 index 00000000..3d5b1af3 --- /dev/null +++ b/apps/purepoint-windows/ui/src/views/terminal/terminals.test.ts @@ -0,0 +1,23 @@ +// Remote terminals' loopback links (Swift `BrowserLinks.handler`, wired in TerminalPaneView). +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { configureTerminals, terminalLinkOpener } from './terminals.ts'; + +afterEach(() => { + configureTerminals({ machineIdFor: () => undefined, openBrowserLink: () => false }); +}); + +describe('terminalLinkOpener', () => { + it("opens a remote agent's loopback link in a browser pane of its project", () => { + const pane = vi.fn(() => true); + const system = vi.fn(); + configureTerminals({ + machineIdFor: (agentId) => (agentId === 'ag-remote' ? 'm1' : undefined), + openBrowserLink: pane, + }); + terminalLinkOpener('ag-remote', system)('http://localhost:3000/'); + terminalLinkOpener('ag-local', system)('http://localhost:3000/'); + terminalLinkOpener('ag-remote', system)('https://example.com/'); + expect(pane.mock.calls).toEqual([['ag-remote', 'http://localhost:3000/']]); + expect(system.mock.calls).toEqual([['http://localhost:3000/'], ['https://example.com/']]); + }); +}); diff --git a/apps/purepoint-windows/ui/src/views/terminal/terminals.ts b/apps/purepoint-windows/ui/src/views/terminal/terminals.ts index aa9fdb83..5e2bcfda 100644 --- a/apps/purepoint-windows/ui/src/views/terminal/terminals.ts +++ b/apps/purepoint-windows/ui/src/views/terminal/terminals.ts @@ -1,6 +1,8 @@ // The app's terminal cache (WIN-7.3): one `TerminalViewCache` of `TerminalPaneController`s, the // hidden element that parks hidden terminals, and live font-size and appearance changes. // `configureTerminals` is how the app tells it agents' live status (Swift `agentStatus`). +import { terminalLinkHandler } from '../../model/browser.ts'; +import { openExternal } from '../../services/opener.ts'; import { TerminalPaneController, type TerminalPaneOptions } from './terminalPaneView.ts'; import { terminalFontStore } from './terminalFontStore.ts'; import { TerminalViewCache } from './terminalViewCache.ts'; @@ -14,13 +16,31 @@ export interface TerminalHost { interface TerminalConfig { isAgentAlive: (agentId: string) => boolean; machineIdFor: (agentId: string) => string | undefined; + /** + * Opens a remote agent's loopback link in a browser pane of its project (Swift + * `BrowserLinks.open`); false when it could not, and the link goes to the system browser. + */ + openBrowserLink: (agentId: string, url: string) => boolean; } const config: TerminalConfig = { isAgentAlive: () => false, machineIdFor: () => undefined, + openBrowserLink: () => false, }; +/** A terminal's link handler: remote agents' loopback links open in a browser pane. */ +export function terminalLinkOpener( + agentId: string, + fallback: (url: string) => void = openExternal, +): (url: string) => void { + return terminalLinkHandler( + () => config.machineIdFor(agentId) !== undefined, + (url) => config.openBrowserLink(agentId, url), + fallback, + ); +} + /** Live agent status and owning machine, from the app state. */ export function configureTerminals(next: Partial): void { Object.assign(config, next); @@ -54,6 +74,7 @@ export function createTerminalHost( cache.agentGone(agentId); }, ...(machineId === undefined ? {} : { machineId }), + openLink: terminalLinkOpener(agentId), ...options, }); }); From 143377b6daeebdcf1c5574487e7ba8bbcf70ac65 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 23:29:42 +0000 Subject: [PATCH 07/30] fix(browser): send HiDPI frames to Retina panes Chromium's screencast captures at the browser's own device scale, not the emulated one, so a 2x pane got 1x frames. Start the browser at 2x; each viewer's frames stay capped at its own width x scale. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ2eMMzt56iHuDqpo7z --- crates/pu-engine/src/browser/launch.rs | 7 +++++++ docs/product/browser.md | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/pu-engine/src/browser/launch.rs b/crates/pu-engine/src/browser/launch.rs index 6daff606..b4627661 100644 --- a/crates/pu-engine/src/browser/launch.rs +++ b/crates/pu-engine/src/browser/launch.rs @@ -11,6 +11,8 @@ pub const BROWSER_ENV: &str = "PU_BROWSER"; const DEFAULT_WIDTH: u32 = 1280; const DEFAULT_HEIGHT: u32 = 800; +/// The density screencast frames are captured at (Retina and most HiDPI screens). +const CAPTURE_SCALE: u32 = 2; /// Candidate executables, most preferred first. pub fn candidates(path_var: Option<&str>) -> Vec { @@ -98,6 +100,10 @@ pub fn args(profile: &Path, as_root: bool) -> Vec { "--disable-features=Translate,MediaRouter,OptimizationHints".to_string(), "--mute-audio".to_string(), format!("--window-size={DEFAULT_WIDTH},{DEFAULT_HEIGHT}"), + // Screencast frames are captured at the browser's own scale, not the emulated one, so + // without this a Retina pane gets 1x frames. Each viewer's frames are still capped at + // its own width x scale, so a 1x pane gets 1x frames. + format!("--force-device-scale-factor={CAPTURE_SCALE}"), ]; if as_root { // Chromium refuses to run its sandbox as root (containers, some servers). @@ -256,6 +262,7 @@ mod tests { let as_user = args(profile, false); assert!(as_user.contains(&"--remote-debugging-pipe".to_string())); assert!(as_user.contains(&"--user-data-dir=/p".to_string())); + assert!(as_user.contains(&"--force-device-scale-factor=2".to_string())); assert!( !as_user .iter() diff --git a/docs/product/browser.md b/docs/product/browser.md index d8da4648..9924c228 100644 --- a/docs/product/browser.md +++ b/docs/product/browser.md @@ -35,7 +35,7 @@ Alternatives considered: ! [BROWSER-001] The browser runs on the daemon's machine, one Chromium per project, driven over `--remote-debugging-pipe`. No DevTools port is ever opened. ! [BROWSER-002] Everything goes through the daemon protocol: agents use `Request::Browser`, panes use `Request::BrowserAttach` on the same connection the app already holds to that machine. Remote projects need no new transport. ! [BROWSER-003] The browser is found as `PU_BROWSER`, else Chrome, Chromium, Edge or Brave in their usual install locations and on `PATH`, else `~/.pu/browser/chrome/chrome`. PurePoint does not ship a browser. -! [BROWSER-004] Frames are JPEG (quality 70) at the viewer's pixel density, sent with ack-based flow control: at most two frames un-acknowledged per viewer, newer frames replacing undrawn ones, so a slow link drops frames instead of queueing them. +! [BROWSER-004] Frames are JPEG (quality 70) at the viewer's pixel density (Chromium is started at `--force-device-scale-factor=2`, because its screencast captures at the browser's own scale, not the emulated one; each viewer's frames are capped at its width × scale), sent with ack-based flow control: at most two frames un-acknowledged per viewer, newer frames replacing undrawn ones, so a slow link drops frames instead of queueing them. ! [BROWSER-005] The viewport follows the pane: a viewer's `resize` sets the page's CSS viewport and device scale, so pages lay out for the pane and clicks map 1:1. With several viewers the last resize wins. ! [BROWSER-006] A person can take control of a tab (`driver: human`); agent ops that act on the page are refused with `BROWSER_HUMAN_DRIVING` until they hand it back. Viewer input is always accepted. ! [BROWSER-007] Agents address elements by `[ref=eN]` from the latest `snapshot`, an indented accessibility outline. Refs are invalidated by the next snapshot and by top-level navigation. From e3f6f0b38ab4fdfe7592dcad62cd9271552197f0 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 01:15:45 +0000 Subject: [PATCH 08/30] fix(browser): build on macOS and Windows macOS has no pipe2: create the DevTools pipe with pipe() and set close-on-exec with fcntl. Windows daemons cannot launch the browser, so its launch and event helpers are unused there; allow that instead of failing -D warnings. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ2eMMzt56iHuDqpo7z --- crates/pu-engine/src/browser/launch.rs | 9 ++++++++- crates/pu-engine/src/browser/mod.rs | 4 ++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/crates/pu-engine/src/browser/launch.rs b/crates/pu-engine/src/browser/launch.rs index b4627661..7eaf8355 100644 --- a/crates/pu-engine/src/browser/launch.rs +++ b/crates/pu-engine/src/browser/launch.rs @@ -153,8 +153,15 @@ pub mod unix { pub writer: pipe::Sender, } + /// A pipe whose ends close on exec. macOS has no `pipe2`, so the flag is set after; + /// only the daemon itself spawns processes here, under the engine's own control. fn cloexec_pipe() -> std::io::Result<(OwnedFd, OwnedFd)> { - nix::unistd::pipe2(nix::fcntl::OFlag::O_CLOEXEC).map_err(std::io::Error::from) + use nix::fcntl::{FcntlArg, FdFlag, fcntl}; + let (read, write) = nix::unistd::pipe().map_err(std::io::Error::from)?; + for fd in [&read, &write] { + fcntl(fd, FcntlArg::F_SETFD(FdFlag::FD_CLOEXEC)).map_err(std::io::Error::from)?; + } + Ok((read, write)) } fn set_nonblocking(fd: &OwnedFd) -> std::io::Result<()> { diff --git a/crates/pu-engine/src/browser/mod.rs b/crates/pu-engine/src/browser/mod.rs index e8ece789..9f081c38 100644 --- a/crates/pu-engine/src/browser/mod.rs +++ b/crates/pu-engine/src/browser/mod.rs @@ -5,6 +5,10 @@ //! restarts. Agents drive it with `Request::Browser`; browser panes watch and //! drive it over `Request::BrowserAttach`. Both go through the machine's //! daemon connection, so a pane works the same for a local or a remote project. +//! +//! Launching needs a Unix daemon (BROWSER-012): on Windows every op answers +//! `BROWSER_UNSUPPORTED`, which leaves the launch and event helpers unused there. +#![cfg_attr(not(unix), allow(dead_code, unused_imports))] pub mod cdp; pub mod keys; From 1f3acf9b42c0edea4ae52e4bba26aaa753812f77 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 01:20:07 +0000 Subject: [PATCH 09/30] test(cli): build the expected screenshot path with the platform's separator Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ2eMMzt56iHuDqpo7z --- crates/pu-cli/src/commands/browser.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/pu-cli/src/commands/browser.rs b/crates/pu-cli/src/commands/browser.rs index 3026d247..92b0d78a 100644 --- a/crates/pu-cli/src/commands/browser.rs +++ b/crates/pu-cli/src/commands/browser.rs @@ -252,9 +252,11 @@ mod tests { full_page: false, }; let local = op_for(action(), None, Some(Path::new("/work"))); - assert!( - matches!(local, BrowserOp::Screenshot { path: Some(p), .. } if p == "/work/shot.png") - ); + let expected = Path::new("/work") + .join("shot.png") + .to_string_lossy() + .into_owned(); + assert!(matches!(local, BrowserOp::Screenshot { path: Some(p), .. } if *p == expected)); let remote = op_for(action(), None, None); assert!(matches!(remote, BrowserOp::Screenshot { path: Some(p), .. } if p == "shot.png")); } From 2a10bc2c62fb01531f84bea445ccb0568331c4d1 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 01:43:26 +0000 Subject: [PATCH 10/30] test(macos): use a kind that does not exist for the unknown-surface test "browser" is now a real tab kind. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ2eMMzt56iHuDqpo7z --- .../purepoint-macosTests/purepoint_macosTests.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/purepoint-macos/purepoint-macosTests/purepoint_macosTests.swift b/apps/purepoint-macos/purepoint-macosTests/purepoint_macosTests.swift index ee1b4b90..af0d1712 100644 --- a/apps/purepoint-macos/purepoint-macosTests/purepoint_macosTests.swift +++ b/apps/purepoint-macos/purepoint-macosTests/purepoint_macosTests.swift @@ -597,7 +597,7 @@ struct GridLayoutPersistenceTests { @Test func unknownSurfaceKindLoadsAsEmptyTab() throws { let json = """ - {"type":"leaf","leafId":0,"activeTabId":4,"tabs":[{"id":4,"kind":"browser"}]} + {"type":"leaf","leafId":0,"activeTabId":4,"tabs":[{"id":4,"kind":"hologram"}]} """ let node = try JSONDecoder().decode(GridLayoutNode.self, from: Data(json.utf8)) var panes: [Int: Pane] = [:] From 0aa302b7ca123fe1a31f568dfbeab72080198f23 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 19:20:38 +0000 Subject: [PATCH 11/30] fix(browser): type AltGr characters; drop a tab whose first load fails Windows layouts report AltGr as Ctrl+Alt, so characters such as @ were sent as shortcuts and never typed; Ctrl+Alt with text now types. An open whose first navigation fails returned an error after registering the tab, so the caller never learned its id and each retry left another tab behind. The tab is now closed (and the browser stopped if it was the last). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ2eMMzt56iHuDqpo7z --- crates/pu-engine/src/browser/keys.rs | 17 +++++++++++++++-- crates/pu-engine/src/browser/mod.rs | 20 ++++++++++++++++++-- crates/pu-engine/tests/browser.rs | 26 ++++++++++++++++++++++++++ 3 files changed, 59 insertions(+), 4 deletions(-) diff --git a/crates/pu-engine/src/browser/keys.rs b/crates/pu-engine/src/browser/keys.rs index 9abb9cf4..b1c6c94f 100644 --- a/crates/pu-engine/src/browser/keys.rs +++ b/crates/pu-engine/src/browser/keys.rs @@ -72,8 +72,11 @@ pub fn lookup(name: &str) -> KeyInfo { /// The `Input.dispatchKeyEvent` params for one press or release. pub fn key_event(down: bool, info: &KeyInfo, modifiers: u32) -> Value { // A key that types something is a `keyDown` with text; Chromium inserts it. - // Ctrl/Meta chords must not type (they are shortcuts). - let types = down && modifiers & (super::modifiers::CTRL | super::modifiers::META) == 0; + // Ctrl/Meta chords must not type (they are shortcuts), except AltGr: Windows + // layouts report it as Ctrl+Alt, and it types characters such as `@`. + use super::modifiers::{ALT, CTRL, META}; + let alt_gr = modifiers & (CTRL | ALT) == CTRL | ALT && modifiers & META == 0; + let types = down && (modifiers & (CTRL | META) == 0 || alt_gr); let kind = match (down, types && info.text.is_some()) { (true, true) => "keyDown", (true, false) => "rawKeyDown", @@ -128,6 +131,16 @@ mod tests { assert_eq!(params["text"], "a"); } + #[test] + fn given_altgr_text_should_type_it() { + use super::super::modifiers::{ALT, CTRL}; + let mut at = lookup("q"); + at.text = Some("@".into()); + let params = key_event(true, &at, CTRL | ALT); + assert_eq!(params["type"], "keyDown"); + assert_eq!(params["text"], "@"); + } + #[test] fn given_a_shortcut_or_release_should_not_type() { let chord = key_event(true, &lookup("a"), super::super::modifiers::META); diff --git a/crates/pu-engine/src/browser/mod.rs b/crates/pu-engine/src/browser/mod.rs index 9f081c38..a04dbdff 100644 --- a/crates/pu-engine/src/browser/mod.rs +++ b/crates/pu-engine/src/browser/mod.rs @@ -562,8 +562,24 @@ impl BrowserManager { let instance = self.get_or_launch(root).await?; instance.touch(); let tab = instance.create_tab().await?; - if let Some(url) = url.filter(|u| !u.trim().is_empty()) { - navigate(&instance.cdp, &tab, &url).await?; + if let Some(url) = url.filter(|u| !u.trim().is_empty()) + && let Err(error) = navigate(&instance.cdp, &tab, &url).await + { + // The caller never learns this tab's id, so it must not linger: + // a retry would open another beside it. + let _ = instance + .cdp + .call( + None, + "Target.closeTarget", + json!({ "targetId": tab.target_id }), + ) + .await; + instance.remove_tab(&tab.target_id); + if instance.is_empty() { + self.instances.lock().await.remove(root); + } + return Err(error); } return Ok(Response::BrowserTab { tab: tab.info() }); } diff --git a/crates/pu-engine/tests/browser.rs b/crates/pu-engine/tests/browser.rs index 0e4f4297..0fe9ed4f 100644 --- a/crates/pu-engine/tests/browser.rs +++ b/crates/pu-engine/tests/browser.rs @@ -496,3 +496,29 @@ async fn given_an_unused_browser_should_stop_it_and_start_fresh_on_next_use() { )); manager.shutdown().await; } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn given_an_open_whose_page_fails_to_load_should_leave_no_tab_behind() { + if !have_browser() { + eprintln!("skipping: no Chrome/Chromium on this machine (set PU_BROWSER)"); + return; + } + use pu_engine::browser::{BrowserManager, Caller}; + let tmp = TempDir::new().unwrap(); + let manager = BrowserManager::new(Some(tmp.path().join("browser"))); + // Nothing listens on port 1, so the load fails. + let open = BrowserOp::Open { + url: Some("http://127.0.0.1:1/".into()), + }; + for _ in 0..2 { + match manager.handle("/p", open.clone(), Caller::Agent).await { + Response::Error { code, .. } => assert_eq!(code, "BROWSER_NAVIGATION_FAILED"), + other => panic!("expected a failed load, got {other:?}"), + } + } + assert!(matches!( + manager.handle("/p", BrowserOp::List, Caller::Agent).await, + Response::BrowserTabs { tabs } if tabs.is_empty() + )); + manager.shutdown().await; +} From 971f6b25abcfa71252f95c2b524fd443f830794b Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 19:24:16 +0000 Subject: [PATCH 12/30] fix(browser): type AltGr text without Ctrl+Alt; keep agent chords as chords Linux Chromium drops typed characters that carry Ctrl, so AltGr text from a Windows viewer still did not type there, and the previous fix made an agent's `press Control+Alt+q` type q. AltGr is now handled where a viewer's key with text arrives: Ctrl+Alt is cleared on that key only. Proven against Linux Chromium (the old behaviour types nothing there). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ2eMMzt56iHuDqpo7z --- crates/pu-engine/src/browser/keys.rs | 18 ++------ crates/pu-engine/src/browser/mod.rs | 37 +++++++++++++++- crates/pu-engine/tests/browser.rs | 64 ++++++++++++++++++++++++++++ 3 files changed, 103 insertions(+), 16 deletions(-) diff --git a/crates/pu-engine/src/browser/keys.rs b/crates/pu-engine/src/browser/keys.rs index b1c6c94f..78f25f92 100644 --- a/crates/pu-engine/src/browser/keys.rs +++ b/crates/pu-engine/src/browser/keys.rs @@ -72,11 +72,9 @@ pub fn lookup(name: &str) -> KeyInfo { /// The `Input.dispatchKeyEvent` params for one press or release. pub fn key_event(down: bool, info: &KeyInfo, modifiers: u32) -> Value { // A key that types something is a `keyDown` with text; Chromium inserts it. - // Ctrl/Meta chords must not type (they are shortcuts), except AltGr: Windows - // layouts report it as Ctrl+Alt, and it types characters such as `@`. - use super::modifiers::{ALT, CTRL, META}; - let alt_gr = modifiers & (CTRL | ALT) == CTRL | ALT && modifiers & META == 0; - let types = down && (modifiers & (CTRL | META) == 0 || alt_gr); + // Ctrl/Meta chords must not type (they are shortcuts). AltGr is handled + // before this, where a viewer's key arrives (`input_command`). + let types = down && modifiers & (super::modifiers::CTRL | super::modifiers::META) == 0; let kind = match (down, types && info.text.is_some()) { (true, true) => "keyDown", (true, false) => "rawKeyDown", @@ -131,16 +129,6 @@ mod tests { assert_eq!(params["text"], "a"); } - #[test] - fn given_altgr_text_should_type_it() { - use super::super::modifiers::{ALT, CTRL}; - let mut at = lookup("q"); - at.text = Some("@".into()); - let params = key_event(true, &at, CTRL | ALT); - assert_eq!(params["type"], "keyDown"); - assert_eq!(params["text"], "@"); - } - #[test] fn given_a_shortcut_or_release_should_not_type() { let chord = key_event(true, &lookup("a"), super::super::modifiers::META); diff --git a/crates/pu-engine/src/browser/mod.rs b/crates/pu-engine/src/browser/mod.rs index a04dbdff..9f9af7a1 100644 --- a/crates/pu-engine/src/browser/mod.rs +++ b/crates/pu-engine/src/browser/mod.rs @@ -1313,9 +1313,20 @@ pub fn input_command(event: &BrowserInputEvent) -> (&'static str, Value) { if text.is_some() { info.text = text.clone().filter(|t| !t.is_empty()); } + // Windows layouts report AltGr as Ctrl+Alt; the key still types its text + // (`@`). Typed text must not carry Ctrl: Linux Chromium drops it as a + // shortcut. Only a viewer's key with text gets here; an agent's + // `press Control+Alt+q` stays a chord. + let mut mods = *modifiers; + let alt_gr = mods & (modifiers::CTRL | modifiers::ALT) + == modifiers::CTRL | modifiers::ALT + && mods & modifiers::META == 0; + if alt_gr && info.text.is_some() && text.is_some() { + mods &= !(modifiers::CTRL | modifiers::ALT); + } ( "Input.dispatchKeyEvent", - keys::key_event(*action == BrowserKeyAction::Down, &info, *modifiers), + keys::key_event(*action == BrowserKeyAction::Down, &info, mods), ) } BrowserInputEvent::Text { text } => ("Input.insertText", json!({ "text": text })), @@ -1417,6 +1428,30 @@ mod tests { assert_eq!(up["buttons"], 0); } + #[test] + fn given_altgr_text_from_a_viewer_should_type_it_without_ctrl() { + let (_, params) = input_command(&BrowserInputEvent::Key { + action: BrowserKeyAction::Down, + key: "@".into(), + code: Some("KeyQ".into()), + text: Some("@".into()), + modifiers: modifiers::CTRL | modifiers::ALT, + }); + assert_eq!(params["type"], "keyDown"); + assert_eq!(params["text"], "@"); + assert_eq!(params["modifiers"], 0); + // A chord without text stays a chord. + let (_, chord) = input_command(&BrowserInputEvent::Key { + action: BrowserKeyAction::Down, + key: "q".into(), + code: None, + text: None, + modifiers: modifiers::CTRL | modifiers::ALT, + }); + assert_eq!(chord["type"], "rawKeyDown"); + assert!(chord.get("text").is_none()); + } + #[test] fn given_viewer_keys_and_text_should_map_to_key_events_and_inserted_text() { let (method, params) = input_command(&BrowserInputEvent::Key { diff --git a/crates/pu-engine/tests/browser.rs b/crates/pu-engine/tests/browser.rs index 0fe9ed4f..f4e0f672 100644 --- a/crates/pu-engine/tests/browser.rs +++ b/crates/pu-engine/tests/browser.rs @@ -522,3 +522,67 @@ async fn given_an_open_whose_page_fails_to_load_should_leave_no_tab_behind() { )); manager.shutdown().await; } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn given_altgr_text_from_a_viewer_should_type_it_on_linux_chromium() { + if !have_browser() { + eprintln!("skipping: no Chrome/Chromium on this machine (set PU_BROWSER)"); + return; + } + use pu_core::protocol::{BrowserKeyAction, modifiers}; + use pu_engine::browser::{BrowserManager, Caller}; + let tmp = TempDir::new().unwrap(); + let manager = BrowserManager::new(Some(tmp.path().join("browser"))); + let open = BrowserOp::Open { + url: Some("data:text/html,".into()), + }; + assert!(matches!( + manager.handle("/p", open, Caller::Agent).await, + Response::BrowserTab { .. } + )); + manager + .handle( + "/p", + BrowserOp::Eval { + tab_id: None, + expression: "document.getElementById('f').focus()".into(), + }, + Caller::Agent, + ) + .await; + // A Windows viewer on a German layout: AltGr+Q types `@`, reported as Ctrl+Alt. + for action in [BrowserKeyAction::Down, BrowserKeyAction::Up] { + manager + .handle( + "/p", + BrowserOp::Input { + tab_id: None, + event: BrowserInputEvent::Key { + action, + key: "@".into(), + code: Some("KeyQ".into()), + text: Some("@".into()), + modifiers: modifiers::CTRL | modifiers::ALT, + }, + }, + Caller::Viewer, + ) + .await; + } + tokio::time::sleep(Duration::from_millis(300)).await; + match manager + .handle( + "/p", + BrowserOp::Eval { + tab_id: None, + expression: "document.getElementById('f').value".into(), + }, + Caller::Agent, + ) + .await + { + Response::BrowserEvalResult { value, .. } => assert_eq!(value, "@"), + other => panic!("eval: {other:?}"), + } + manager.shutdown().await; +} From eb120be317f9255f163218d685d6b6ab4c7fb458 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 19:24:40 +0000 Subject: [PATCH 13/30] docs(browser): say IME composition is not supported yet Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ2eMMzt56iHuDqpo7z --- docs/product/browser.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/product/browser.md b/docs/product/browser.md index 9924c228..f0087ad2 100644 --- a/docs/product/browser.md +++ b/docs/product/browser.md @@ -104,11 +104,14 @@ remote terminal link ∧ loopback(link) → open in browser pane of project - **Slow pages.** Navigation waits up to 15 s for the load event and then reports the page as it is; `wait` is there for anything slower. - **Same-document navigation** (`#fragment`): has no load event; navigation returns immediately. - **Several viewers** of one tab share one screencast; the last resize sets the viewport for all. -- **Keyboard shortcuts.** Cmd/Ctrl+C and +V are handled by the pane (clipboard on the viewing device); other chords are sent to the page with their modifiers, so editing shortcuts follow the browser's platform (Ctrl on a Linux machine). IME composition is sent as committed text. +- **Keyboard shortcuts.** Cmd/Ctrl+C and +V are handled by the pane (clipboard on the viewing device); other chords are sent to the page with their modifiers, so editing shortcuts follow the browser's platform (Ctrl on a Linux machine). AltGr (Ctrl+Alt on Windows layouts) types its character. +- **IME composition is not supported yet.** No pane is a text-input client (macOS has no `NSTextInputClient`, the iPad canvas is `UIKeyInput` without `UITextInput`, the Windows canvas is a non-editable element), so CJK and other composed input does not reach the page. Paste works as a workaround. - **No audio or video capture**, file pickers and downloads are not surfaced in v1. ## Open Questions +- IME composition in all three panes: a composition-capable input target that sends committed text as a `text` event and holds key forwarding while composing. + - Per-project site allowlist for agent navigation, with approval in the pane. - Gating `eval` behind approval for agents. - A "open in my browser" port relay for pages a person wants in their own browser. From 214b8b5ea6ab6640b30a8f972cbaa48dda8be610 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 19:41:10 +0000 Subject: [PATCH 14/30] fix(browser): address review findings on concurrency and robustness Daemon: - A project's browser startup no longer holds the manager map, so a slow Chromium start never blocks other projects; one startup per project. - A dead browser is stopped and awaited before its profile is reused. - Close (and a failed open) retire a browser only if no open is pending and it is still the current instance. - A tab that fails to initialize is rolled back and its target closed. - Snapshot refs are dropped if the page navigated while they were read. - A failed resize stays retryable; viewport is recorded after Chromium accepts it. - type stops when focusing the element throws. - Linux creates the DevTools pipe with O_CLOEXEC atomically. - DevTools calls racing the browser's exit fail at once. - Bare addresses only count as having a scheme when it leads the string; outlines escape backslashes and keep numeric values. Viewer stream: - New viewers get the tab's current state at once. - When the last viewer leaves, a person's control returns to agents. - Stuck frame writes time out and end the connection. - Resizes run on an ordered worker so frames and input keep flowing. Apps: - Windows: the attach reply has a deadline; a newer frame no longer cancels an older frame's decode, so slow decoding cannot starve the canvas. - macOS: pane writes go out in call order; a stopped session does not draw a decoded frame. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ2eMMzt56iHuDqpo7z --- .../State/BrowserSession.swift | 11 +- .../src-tauri/src/browser/session.rs | 13 +- .../src-tauri/src/browser/session_tests.rs | 21 +++ .../views/browser/BrowserPaneView.test.tsx | 41 +++++ .../ui/src/views/browser/BrowserPaneView.tsx | 24 ++- crates/pu-engine/src/browser/cdp.rs | 13 +- crates/pu-engine/src/browser/launch.rs | 24 ++- crates/pu-engine/src/browser/mod.rs | 151 +++++++++++++++--- crates/pu-engine/src/browser/snapshot.rs | 44 ++++- crates/pu-engine/src/browser/tab.rs | 64 +++++++- crates/pu-engine/src/ipc_server/streams.rs | 53 +++++- 11 files changed, 406 insertions(+), 53 deletions(-) diff --git a/apps/purepoint-macos/purepoint-macos/State/BrowserSession.swift b/apps/purepoint-macos/purepoint-macos/State/BrowserSession.swift index b5ef4da3..13f54a53 100644 --- a/apps/purepoint-macos/purepoint-macos/State/BrowserSession.swift +++ b/apps/purepoint-macos/purepoint-macos/State/BrowserSession.swift @@ -84,6 +84,7 @@ final class BrowserSession { @ObservationIgnored private var pendingCopy = false @ObservationIgnored private var noticeTask: Task? @ObservationIgnored private var attachedStream: (any DaemonByteStream)? + @ObservationIgnored private var lastSend: Task? init( client: DaemonClient, projectRoot: String, tabId: String?, url: String?, @@ -155,8 +156,14 @@ final class BrowserSession { send(.resize(tabId: nil, width: width, height: height, scale: scale)) } + /// Writes in call order: each send waits for the one before it, so a click's + /// mouse-up can never reach the daemon ahead of its mouse-down. private func send(_ op: BrowserOp) { - Task { [writer, projectRoot] in await writer.send(.browser(projectRoot: projectRoot, op: op)) } + let previous = lastSend + lastSend = Task { [writer, projectRoot] in + await previous?.value + await writer.send(.browser(projectRoot: projectRoot, op: op)) + } } private func show(notice text: String) { @@ -247,6 +254,8 @@ final class BrowserSession { let decoded = await Task.detached(priority: .userInitiated) { DecodedFrame(image: BrowserSession.decode(payload.data)) }.value + // A session stopped while the frame decoded must not touch the pane. + guard !Task.isCancelled else { return } if let image = decoded.image { frame = image frameSize = CGSize(width: payload.width, height: payload.height) diff --git a/apps/purepoint-windows/src-tauri/src/browser/session.rs b/apps/purepoint-windows/src-tauri/src/browser/session.rs index ed57f525..2597a40c 100644 --- a/apps/purepoint-windows/src-tauri/src/browser/session.rs +++ b/apps/purepoint-windows/src-tauri/src/browser/session.rs @@ -86,6 +86,8 @@ pub struct BrowserOptions { /// Waits between attempts (tests shorten them). pub fast_delay: Duration, pub slow_delay: Duration, + /// How long the daemon may take to answer an attach (tests shorten it). + pub attach_timeout: Duration, } impl BrowserOptions { @@ -100,6 +102,7 @@ impl BrowserOptions { url, fast_delay: Duration::from_millis(300), slow_delay: Duration::from_secs(2), + attach_timeout: crate::daemon::client::REQUEST_TIMEOUT, } } } @@ -156,6 +159,7 @@ impl BrowserSession { last_url: options.url, fast_delay: options.fast_delay, slow_delay: options.slow_delay, + attach_timeout: options.attach_timeout, viewport: None, sink, ops: rx, @@ -193,6 +197,7 @@ struct Worker { last_url: Option, fast_delay: Duration, slow_delay: Duration, + attach_timeout: Duration, /// The last `resize` the pane sent: (width, height, scale). viewport: Option<(u32, u32, f64)>, sink: Arc, @@ -312,7 +317,13 @@ impl Worker { })); // The first line: the attach's answer. Ops wait in the channel meanwhile. - match lines.recv().await { + // Bounded, so a daemon that accepts but never answers leads to a retry; + // the live stream after it may rightly stay quiet, so it is not. + let first = match tokio::time::timeout(self.attach_timeout, lines.recv()).await { + Ok(first) => first, + Err(_) => return retry("The daemon did not answer the attach in time".into()), + }; + match first { Some(Ok(Response::BrowserAttached { tab })) => self.adopt(tab), Some(Ok(Response::BrowserTabClosed { .. })) => return End::TabClosed, Some(Ok(Response::Error { code, .. })) if is_lost_tab(&code) => { diff --git a/apps/purepoint-windows/src-tauri/src/browser/session_tests.rs b/apps/purepoint-windows/src-tauri/src/browser/session_tests.rs index 0d5622c3..7bf40781 100644 --- a/apps/purepoint-windows/src-tauri/src/browser/session_tests.rs +++ b/apps/purepoint-windows/src-tauri/src/browser/session_tests.rs @@ -145,6 +145,7 @@ fn options(tab_id: Option<&str>, url: Option<&str>) -> BrowserOptions { let mut options = BrowserOptions::new("/p", tab_id.map(Into::into), url.map(Into::into)); options.fast_delay = Duration::from_millis(10); options.slow_delay = Duration::from_millis(40); + options.attach_timeout = Duration::from_millis(200); options } @@ -361,3 +362,23 @@ async fn given_a_dropped_stream_should_reattach_and_replay_the_last_resize() { serde_json::json!({"type": "browser", "project_root": "/p", "op": {"action": "resize", "tab_id": null, "width": 640, "height": 480, "scale": 2.0}}), ); } + +#[tokio::test] +async fn given_a_daemon_that_never_answers_the_attach_should_retry() { + let mut daemon = FakeDaemon::start(); + let (sink, mut seen) = sink(); + let _session = BrowserSession::start(daemon.client(), options(Some("t1"), None), sink); + let mut silent = daemon.accept().await; + let _ = silent.request().await; + // No reply: the session gives up on this connection and reconnects. + match next(&mut seen).await { + BrowserEvent::Retrying { message, .. } => assert!(message.contains("attach"), "{message}"), + other => panic!("expected a retry, got {other:?}"), + } + let mut again = daemon.accept().await; + assert_request( + again.request().await, + serde_json::json!({"type": "browser_attach", "project_root": "/p", "tab_id": "t1"}), + ); + drop(silent); +} diff --git a/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.test.tsx b/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.test.tsx index 7888f3da..f15dce89 100644 --- a/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.test.tsx +++ b/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.test.tsx @@ -142,4 +142,45 @@ describe('BrowserPaneView', () => { expect(screen.getByText('Install Chrome there')).toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Try Again' })).toBeInTheDocument(); }); + + it('draws a frame whose decode outlasts the next frame, and acks both', async () => { + const decodes: (() => void)[] = []; + // jsdom has no `decode`: stand one in whose completion the test controls. + const original = Object.getOwnPropertyDescriptor(HTMLImageElement.prototype, 'decode'); + Object.defineProperty(HTMLImageElement.prototype, 'decode', { + configurable: true, + value: () => new Promise((resolve) => decodes.push(resolve)), + }); + const drawImage = vi.fn(); + const getContext = vi + .spyOn(HTMLCanvasElement.prototype, 'getContext') + .mockImplementation(() => ({ drawImage, clearRect: vi.fn() }) as never); + try { + const { send, sent } = setup(); + await send({ type: 'tab', tab: tab() }); + await send({ type: 'live' }); + await send({ type: 'frame', seq: 1, data: 'AAAA', width: 1280, height: 800 }); + // Frame 2 arrives while frame 1 is still decoding. + await send({ type: 'frame', seq: 2, data: 'BBBB', width: 1280, height: 800 }); + expect(decodes).toHaveLength(2); + await act(async () => { + decodes[0]?.(); + await Promise.resolve(); + await Promise.resolve(); + }); + expect(drawImage).toHaveBeenCalledTimes(1); + await act(async () => { + decodes[1]?.(); + await Promise.resolve(); + await Promise.resolve(); + }); + expect(drawImage).toHaveBeenCalledTimes(2); + const acks = sent.filter((op) => op.action === 'frame_ack').map((op) => op.seq); + expect(acks).toEqual([1, 2]); + } finally { + if (original) Object.defineProperty(HTMLImageElement.prototype, 'decode', original); + else delete (HTMLImageElement.prototype as { decode?: unknown }).decode; + getContext.mockRestore(); + } + }); }); diff --git a/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.tsx b/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.tsx index 33642b5a..158387c3 100644 --- a/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.tsx +++ b/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.tsx @@ -341,6 +341,9 @@ function BrowserCanvas({ const box = useRef(null); const lastHover = useRef(0); const drawnSeq = useRef(-1); + /** Bumped when the tab closes or reopens, so a decode started before it never draws. */ + const epoch = useRef(0); + const unmounted = useRef(false); const handlers = useRef({ onResize, onDrawn }); useLayoutEffect(() => { handlers.current = { onResize, onDrawn }; @@ -379,9 +382,14 @@ function BrowserCanvas({ }, []); // Draw each frame, then ack it: the daemon sends at most two ahead of the screen. + // A newer frame never cancels an older one's decode (when decoding is slower + // than frames arrive, that would starve the canvas); `seq` keeps an older frame + // from painting over a newer one. Only unmounting or a closed/reopened tab + // (a new `epoch`) drops a pending draw. useEffect(() => { if (frame === null) { // The tab closed (or reopens): blank the page; a new tab numbers its frames afresh. + epoch.current += 1; if (drawnSeq.current >= 0) { const target = canvas.current; target?.getContext('2d')?.clearRect(0, 0, target.width, target.height); @@ -389,24 +397,28 @@ function BrowserCanvas({ } return; } - let cancelled = false; const { seq, data } = frame; + const startedIn = epoch.current; decodeFrame(data) .then((image) => { const target = canvas.current; - // A newer frame may have been drawn while this one decoded. - if (cancelled || target === null || seq < drawnSeq.current) return; + if (unmounted.current || startedIn !== epoch.current || target === null) return; + if (seq < drawnSeq.current) return; // a newer frame is already on screen drawnSeq.current = seq; target.getContext('2d')?.drawImage(image, 0, 0, target.width, target.height); }) .catch(() => undefined) .finally(() => { - handlers.current.onDrawn(seq); + if (!unmounted.current) handlers.current.onDrawn(seq); }); + }, [frame]); + + useEffect(() => { + unmounted.current = false; return () => { - cancelled = true; + unmounted.current = true; }; - }, [frame]); + }, []); const geometry = (clientX: number, clientY: number) => { const rect = box.current?.getBoundingClientRect(); diff --git a/crates/pu-engine/src/browser/cdp.rs b/crates/pu-engine/src/browser/cdp.rs index f5a5e0a7..6617f186 100644 --- a/crates/pu-engine/src/browser/cdp.rs +++ b/crates/pu-engine/src/browser/cdp.rs @@ -155,10 +155,15 @@ impl Cdp { bytes.push(0); let (tx, rx) = oneshot::channel(); - self.pending - .lock() - .await - .insert(id, (method.to_string(), tx)); + { + // Checked under the lock the reader drains with: a call that registers + // after the browser closed would otherwise wait out the full timeout. + let mut pending = self.pending.lock().await; + if !self.is_alive() { + return Err(CdpError::Closed); + } + pending.insert(id, (method.to_string(), tx)); + } if self.outbox.send(bytes).is_err() { self.pending.lock().await.remove(&id); return Err(CdpError::Closed); diff --git a/crates/pu-engine/src/browser/launch.rs b/crates/pu-engine/src/browser/launch.rs index 7eaf8355..386ff1eb 100644 --- a/crates/pu-engine/src/browser/launch.rs +++ b/crates/pu-engine/src/browser/launch.rs @@ -153,15 +153,25 @@ pub mod unix { pub writer: pipe::Sender, } - /// A pipe whose ends close on exec. macOS has no `pipe2`, so the flag is set after; - /// only the daemon itself spawns processes here, under the engine's own control. + /// A pipe whose ends close on exec, so no process the engine forks (agents, + /// shells) inherits a DevTools end; one that did could keep the browser alive + /// after the daemon dies. Linux sets the flag atomically. macOS has no `pipe2`, + /// so a fork in the instant between `pipe` and `fcntl` could still inherit an + /// end there; that window is a few instructions wide. fn cloexec_pipe() -> std::io::Result<(OwnedFd, OwnedFd)> { - use nix::fcntl::{FcntlArg, FdFlag, fcntl}; - let (read, write) = nix::unistd::pipe().map_err(std::io::Error::from)?; - for fd in [&read, &write] { - fcntl(fd, FcntlArg::F_SETFD(FdFlag::FD_CLOEXEC)).map_err(std::io::Error::from)?; + #[cfg(any(target_os = "linux", target_os = "android"))] + { + nix::unistd::pipe2(nix::fcntl::OFlag::O_CLOEXEC).map_err(std::io::Error::from) + } + #[cfg(not(any(target_os = "linux", target_os = "android")))] + { + use nix::fcntl::{FcntlArg, FdFlag, fcntl}; + let (read, write) = nix::unistd::pipe().map_err(std::io::Error::from)?; + for fd in [&read, &write] { + fcntl(fd, FcntlArg::F_SETFD(FdFlag::FD_CLOEXEC)).map_err(std::io::Error::from)?; + } + Ok((read, write)) } - Ok((read, write)) } fn set_nonblocking(fd: &OwnedFd) -> std::io::Result<()> { diff --git a/crates/pu-engine/src/browser/mod.rs b/crates/pu-engine/src/browser/mod.rs index 9f9af7a1..29057e06 100644 --- a/crates/pu-engine/src/browser/mod.rs +++ b/crates/pu-engine/src/browser/mod.rs @@ -104,6 +104,8 @@ pub struct Instance { screenshots: PathBuf, /// When an op or viewer last used this browser. last_used: std::sync::Mutex, + /// Opens creating a tab right now: the browser is not retired while any runs. + pending_opens: std::sync::atomic::AtomicUsize, } impl Drop for Instance { @@ -119,6 +121,19 @@ impl Drop for Instance { } impl Instance { + /// Ends the browser's process group and waits (briefly) for it to exit. + async fn stop_and_wait(&self) { + #[cfg(unix)] + if let Some(pid) = self.pid { + launch::unix::stop_group(pid); + } + let child = self._child.lock().unwrap_or_else(|e| e.into_inner()).take(); + if let Some(mut child) = child { + let _ = child.start_kill(); + let _ = tokio::time::timeout(Duration::from_secs(5), child.wait()).await; + } + } + fn touch(&self) { *self.last_used.lock().unwrap_or_else(|e| e.into_inner()) = tokio::time::Instant::now(); } @@ -251,7 +266,18 @@ impl Instance { .lock() .unwrap_or_else(|e| e.into_inner()) .insert(target_id.to_string(), tab.clone()); - let session = Some(session_id.as_str()); + if let Err(error) = self.init_tab(&tab).await { + // A half-initialized tab must not be listed or become the default. + self.remove_tab(target_id); + self.cdp + .send(None, "Target.closeTarget", json!({ "targetId": target_id })); + return Err(error); + } + Ok(tab) + } + + async fn init_tab(&self, tab: &Tab) -> Result<()> { + let session = Some(tab.session_id.as_str()); for domain in [ "Page.enable", "Runtime.enable", @@ -260,8 +286,7 @@ impl Instance { ] { self.cdp.call(session, domain, json!({})).await?; } - apply_viewport(&self.cdp, &tab).await?; - Ok(tab) + apply_viewport(&self.cdp, tab, tab.viewport()).await } fn on_event(self: &Arc, event: &CdpEvent) { @@ -331,8 +356,7 @@ impl Instance { } } -async fn apply_viewport(cdp: &Cdp, tab: &Tab) -> Result<()> { - let viewport = tab.viewport(); +async fn apply_viewport(cdp: &Cdp, tab: &Tab, viewport: Viewport) -> Result<()> { cdp.call( Some(&tab.session_id), "Emulation.setDeviceMetricsOverride", @@ -372,6 +396,8 @@ async fn refresh_history(cdp: &Cdp, tab: &Tab) { /// The browsers of every project on this daemon. pub struct BrowserManager { instances: Mutex>>, + /// Serializes each project's browser startup. + startups: Mutex>>>, base_dir: Option, idle_stop: Duration, } @@ -391,6 +417,7 @@ impl BrowserManager { pub fn new(base_dir: Option) -> Self { Self { instances: Mutex::new(HashMap::new()), + startups: Mutex::new(HashMap::new()), base_dir, idle_stop: IDLE_STOP, } @@ -429,15 +456,52 @@ impl BrowserManager { } async fn get_or_launch(&self, root: &str) -> Result> { - let mut instances = self.instances.lock().await; - if let Some(instance) = instances.get(root).filter(|i| i.cdp.is_alive()) { - return Ok(instance.clone()); + // One startup per project at a time; other projects are never held up by it. + let startup = self + .startups + .lock() + .await + .entry(root.to_string()) + .or_default() + .clone(); + let _starting = startup.lock().await; + let dead = { + let mut instances = self.instances.lock().await; + match instances.get(root) { + Some(instance) if instance.cdp.is_alive() => return Ok(instance.clone()), + Some(_) => instances.remove(root), + None => None, + } + }; + if let Some(dead) = dead { + // Its profile is reused next: make sure the old process is gone first. + dead.stop_and_wait().await; } let instance = self.launch(root).await?; - instances.insert(root.to_string(), instance.clone()); + self.instances + .lock() + .await + .insert(root.to_string(), instance.clone()); Ok(instance) } + /// Forgets a project's browser once it has no tabs and no open in progress. + async fn retire_if_unused(&self, root: &str, instance: &Arc) { + let mut instances = self.instances.lock().await; + let same = instances + .get(root) + .is_some_and(|current| Arc::ptr_eq(current, instance)); + if same + && instance.is_empty() + && instance + .pending_opens + .load(std::sync::atomic::Ordering::SeqCst) + == 0 + { + instances.remove(root); + } + } + #[cfg(not(unix))] async fn launch(&self, _root: &str) -> Result> { Err(BrowserError::new( @@ -528,6 +592,7 @@ impl BrowserManager { initial_targets: std::sync::Mutex::new(initial), screenshots, last_used: std::sync::Mutex::new(tokio::time::Instant::now()), + pending_opens: std::sync::atomic::AtomicUsize::new(0), }); tokio::spawn(pump(Arc::downgrade(&instance), cdp, events)); tokio::spawn(stop_when_idle(Arc::downgrade(&instance), self.idle_stop)); @@ -561,7 +626,19 @@ impl BrowserManager { BrowserOp::Open { url } => { let instance = self.get_or_launch(root).await?; instance.touch(); - let tab = instance.create_tab().await?; + instance + .pending_opens + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let tab = match instance.create_tab().await { + Ok(tab) => tab, + Err(error) => { + instance + .pending_opens + .fetch_sub(1, std::sync::atomic::Ordering::SeqCst); + self.retire_if_unused(root, &instance).await; + return Err(error); + } + }; if let Some(url) = url.filter(|u| !u.trim().is_empty()) && let Err(error) = navigate(&instance.cdp, &tab, &url).await { @@ -576,11 +653,15 @@ impl BrowserManager { ) .await; instance.remove_tab(&tab.target_id); - if instance.is_empty() { - self.instances.lock().await.remove(root); - } + instance + .pending_opens + .fetch_sub(1, std::sync::atomic::Ordering::SeqCst); + self.retire_if_unused(root, &instance).await; return Err(error); } + instance + .pending_opens + .fetch_sub(1, std::sync::atomic::Ordering::SeqCst); return Ok(Response::BrowserTab { tab: tab.info() }); } BrowserOp::Close { tab_id } => { @@ -595,9 +676,7 @@ impl BrowserManager { ) .await; instance.remove_tab(&tab.target_id); - if instance.is_empty() { - self.instances.lock().await.remove(root); - } + self.retire_if_unused(root, &instance).await; return Ok(Response::Ok); } _ => {} @@ -625,6 +704,7 @@ impl BrowserManager { Ok(Response::BrowserTab { tab: tab.info() }) } BrowserOp::Snapshot { .. } => { + let generation = tab.document_generation(); let tree = cdp .call(session, "Accessibility.getFullAXTree", json!({})) .await?; @@ -634,7 +714,14 @@ impl BrowserManager { .cloned() .unwrap_or_default(); let snapshot = snapshot::format(&nodes); - tab.store_refs(snapshot.refs); + // The page may have navigated while the outline was built; its refs + // would then point into a document that is gone. + if !tab.store_refs_for(generation, snapshot.refs) { + return Err(BrowserError::new( + "BROWSER_PAGE_CHANGED", + "the page navigated while it was read; take a new snapshot", + )); + } Ok(Response::BrowserSnapshot { tab: tab.info(), tree: snapshot.tree, @@ -737,8 +824,9 @@ impl BrowserManager { }, }; if viewport != tab.viewport() { + // Recorded only once Chromium accepts it, so a failed resize is retried. + apply_viewport(cdp, &tab, viewport).await?; tab.set_viewport(viewport); - apply_viewport(cdp, &tab).await?; if tab.has_viewers() { // New frame bounds take effect on a fresh screencast. cdp.send(session, "Page.stopScreencast", json!({})); @@ -819,7 +907,15 @@ fn create_private_dir(dir: &Path) -> std::io::Result<()> { /// Adds a scheme to a bare address: local hosts get `http://`, others `https://`. pub fn normalize_url(url: &str) -> String { let url = url.trim(); - if url.contains("://") + // A scheme only counts at the start (`localhost:3000/?r=http://x` has none). + let has_scheme = url.find("://").is_some_and(|end| { + let scheme = &url[..end]; + scheme.starts_with(|c: char| c.is_ascii_alphabetic()) + && scheme + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')) + }); + if has_scheme || [ "about:", "data:", @@ -1054,7 +1150,7 @@ async fn focus_and_select(cdp: &Cdp, tab: &Tab, backend: i64) -> Result<()> { "the element is gone; take a new snapshot", ) })?; - cdp.call( + let focused = cdp.call( session, "Runtime.callFunctionOn", json!({ @@ -1063,6 +1159,17 @@ async fn focus_and_select(cdp: &Cdp, tab: &Tab, backend: i64) -> Result<()> { }), ) .await?; + // A throw (say, an element that cannot take focus) is a successful reply with + // `exceptionDetails`; typing on would land in whatever field had focus before. + if let Some(details) = focused.get("exceptionDetails") { + let text = details + .get("exception") + .and_then(|e| e.get("description")) + .and_then(Value::as_str) + .or_else(|| details.get("text").and_then(Value::as_str)) + .unwrap_or("the element could not take focus"); + return Err(BrowserError::new("BROWSER_NOT_FOCUSABLE", text)); + } Ok(()) } @@ -1354,6 +1461,10 @@ mod tests { ); assert_eq!(normalize_url(" https://a.b "), "https://a.b"); assert_eq!(normalize_url("about:blank"), "about:blank"); + assert_eq!( + normalize_url("localhost:3000/?r=http://x"), + "http://localhost:3000/?r=http://x" + ); assert_eq!(normalize_url("file:///tmp/a.html"), "file:///tmp/a.html"); } diff --git a/crates/pu-engine/src/browser/snapshot.rs b/crates/pu-engine/src/browser/snapshot.rs index 6f6bb4df..dd215dc7 100644 --- a/crates/pu-engine/src/browser/snapshot.rs +++ b/crates/pu-engine/src/browser/snapshot.rs @@ -145,7 +145,8 @@ impl<'a> Writer<'a> { if !name.is_empty() { line.push_str(&format!(" \"{}\"", clip(name))); } - let value = ax_str(node, "value").trim(); + let value = ax_value(node); + let value = value.trim(); if !value.is_empty() { line.push_str(&format!(" value=\"{}\"", clip(value))); } @@ -165,6 +166,15 @@ impl<'a> Writer<'a> { } } +/// A node's value as text: strings as they are, numbers (sliders, spinbuttons) printed. +fn ax_value(node: &Value) -> String { + match node.get("value").and_then(|v| v.get("value")) { + Some(Value::String(s)) => s.clone(), + Some(Value::Number(n)) => n.to_string(), + _ => String::new(), + } +} + fn ax_str<'v>(node: &'v Value, key: &str) -> &'v str { node.get(key) .and_then(|v| v.get("value")) @@ -204,12 +214,17 @@ fn clip(text: &str) -> String { .chars() .map(|c| if c.is_control() { ' ' } else { c }) .collect(); - let escaped = single.replace('"', "\\\""); - if escaped.chars().count() <= MAX_NAME { - escaped + // Cut first, then escape, so an escape is never split. + let (cut, clipped) = if single.chars().count() <= MAX_NAME { + (single, false) } else { - let cut: String = escaped.chars().take(MAX_NAME).collect(); - format!("{cut}…") + (single.chars().take(MAX_NAME).collect(), true) + }; + let escaped = cut.replace('\\', "\\\\").replace('"', "\\\""); + if clipped { + format!("{escaped}…") + } else { + escaped } } @@ -309,6 +324,23 @@ mod tests { ); } + #[test] + fn given_backslashes_and_numeric_values_should_escape_and_keep_them() { + let mut slider = node("3", Some("1"), "slider", "Volume", &[]); + slider["value"] = json!({"type": "number", "value": 7}); + let nodes = vec![ + node("1", None, "RootWebArea", "", &["2", "3"]), + node("2", Some("1"), "StaticText", "C:\\dir", &[]), + slider, + ]; + let tree = format(&nodes).tree; + assert!(tree.contains("- text \"C:\\\\dir\"\n"), "{tree}"); + assert!( + tree.contains("- slider \"Volume\" value=\"7\" [ref=e1]"), + "{tree}" + ); + } + #[test] fn given_no_nodes_should_return_an_empty_outline() { let snapshot = format(&[]); diff --git a/crates/pu-engine/src/browser/tab.rs b/crates/pu-engine/src/browser/tab.rs index 9ab77e3a..beedf070 100644 --- a/crates/pu-engine/src/browser/tab.rs +++ b/crates/pu-engine/src/browser/tab.rs @@ -48,6 +48,8 @@ pub struct Tab { viewport: Mutex, console: Mutex>, refs: Mutex>, + /// Bumped on every top-level navigation, under the `refs` lock. + document: AtomicU64, } impl Tab { @@ -74,6 +76,7 @@ impl Tab { viewport: Mutex::new(viewport), console: Mutex::default(), refs: Mutex::default(), + document: AtomicU64::new(0), } } @@ -163,6 +166,29 @@ impl Tab { *self.refs.lock().unwrap_or_else(|e| e.into_inner()) = refs; } + /// Which document the page shows; a snapshot taken under one generation must + /// not publish refs after the page moved on. + pub fn document_generation(&self) -> u64 { + self.document.load(Ordering::SeqCst) + } + + /// Stores a snapshot's refs if the page is still on `generation`. + pub fn store_refs_for(&self, generation: u64, refs: HashMap) -> bool { + let mut current = self.refs.lock().unwrap_or_else(|e| e.into_inner()); + if self.document.load(Ordering::SeqCst) != generation { + return false; + } + *current = refs; + true + } + + /// A new document: its refs start empty and earlier snapshots are stale. + fn new_document(&self) { + let mut refs = self.refs.lock().unwrap_or_else(|e| e.into_inner()); + self.document.fetch_add(1, Ordering::SeqCst); + refs.clear(); + } + pub fn resolve_ref(&self, reference: &str) -> Option { let reference = reference .trim() @@ -214,6 +240,8 @@ impl Tab { *viewers = viewers.saturating_sub(1); if *viewers == 0 { cdp.send(Some(&self.session_id), "Page.stopScreencast", json!({})); + // Control belongs to a person at a pane: with no pane left, agents resume. + self.set_driver(BrowserDriver::Agent); } } @@ -286,7 +314,7 @@ impl Tab { let url = frame.and_then(|f| f.get("url")).and_then(Value::as_str); self.set_page(url, None); // Old refs point into the previous document. - self.store_refs(HashMap::new()); + self.new_document(); } } "Page.navigatedWithinDocument" if self.is_main_frame(params) => { @@ -501,6 +529,40 @@ mod tests { assert!(tab.console(false).is_empty()); } + #[tokio::test] + async fn given_a_navigation_during_a_snapshot_should_refuse_its_refs() { + let tab = tab(); + let cdp = cdp(); + let generation = tab.document_generation(); + tab.on_event( + &event( + "Page.frameNavigated", + json!({"frame": {"id": "T1", "url": "http://b/"}}), + ), + &cdp, + ); + assert!(!tab.store_refs_for(generation, HashMap::from([("e1".to_string(), 1)]))); + assert_eq!(tab.resolve_ref("e1"), None); + assert!(tab.store_refs_for( + tab.document_generation(), + HashMap::from([("e1".to_string(), 1)]) + )); + assert_eq!(tab.resolve_ref("e1"), Some(1)); + } + + #[tokio::test] + async fn given_the_last_viewer_leaves_should_hand_the_tab_back_to_agents() { + let tab = tab(); + let cdp = cdp(); + tab.add_viewer(&cdp); + tab.add_viewer(&cdp); + tab.set_driver(BrowserDriver::Human); + tab.remove_viewer(&cdp); + assert_eq!(tab.driver(), BrowserDriver::Human); + tab.remove_viewer(&cdp); + assert_eq!(tab.driver(), BrowserDriver::Agent); + } + #[test] fn given_ref_spellings_should_resolve_the_same_element() { let tab = tab(); diff --git a/crates/pu-engine/src/ipc_server/streams.rs b/crates/pu-engine/src/ipc_server/streams.rs index d0989830..5e54a14a 100644 --- a/crates/pu-engine/src/ipc_server/streams.rs +++ b/crates/pu-engine/src/ipc_server/streams.rs @@ -562,6 +562,22 @@ pub(super) async fn handle_fs_stream( tracing::debug!(root = root_str, "fs stream ended"); } +/// A viewer that stops reading must not hold its stream (and its tab's +/// screencast) forever: a write stuck this long ends the connection. +const BROWSER_WRITE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(20); + +/// `write_response` with [`BROWSER_WRITE_TIMEOUT`]. A timed-out write may have +/// sent part of a line, so the caller must close the connection on any error. +async fn write_bounded(writer: &mut IpcWriter, response: &Response) -> std::io::Result<()> { + match tokio::time::timeout(BROWSER_WRITE_TIMEOUT, write_response(writer, response)).await { + Ok(result) => result, + Err(_) => Err(std::io::Error::new( + std::io::ErrorKind::TimedOut, + "viewer stopped reading", + )), + } +} + /// Viewers may have this many frames sent but not yet drawn; newer frames /// replace undrawn ones, so a slow link drops frames instead of queueing them. const BROWSER_FRAMES_IN_FLIGHT: usize = 2; @@ -586,7 +602,7 @@ pub(super) async fn handle_browser_stream( let closed = Response::BrowserTabClosed { tab_id: tab_id.to_string(), }; - return write_response(writer, &closed).await.is_ok(); + return write_bounded(writer, &closed).await.is_ok(); } }; tab.add_viewer(&cdp); @@ -614,15 +630,34 @@ async fn browser_stream_loop( let mut closed = tab.subscribe_closed(); // A frame drawn before this viewer arrived is still worth showing now. frames.mark_changed(); + // So is the tab's state: a change between `BrowserAttached` and here (another + // pane taking control, say) must not wait for the next one to show. + info.mark_changed(); let mut in_flight: VecDeque = VecDeque::new(); let (replies_tx, mut replies_rx) = tokio::sync::mpsc::unbounded_channel::(); + // Resizes wait on Chromium; they run in order beside the stream so frames, + // input and acks keep flowing, and report only failures. + let (resizes_tx, mut resizes_rx) = tokio::sync::mpsc::unbounded_channel::(); + { + let browsers = browsers.clone(); + let root = project_root.to_string(); + let replies = replies_tx.clone(); + tokio::spawn(async move { + while let Some(op) = resizes_rx.recv().await { + let resp = browsers.handle(&root, op, Caller::Viewer).await; + if matches!(resp, Response::Error { .. }) && replies.send(resp).is_err() { + break; + } + } + }); + } let tab_id = tab.target_id.clone(); let closed_response = || Response::BrowserTabClosed { tab_id: tab_id.clone(), }; if *closed.borrow() { - return write_response(writer, &closed_response()).await.is_ok(); + return write_bounded(writer, &closed_response()).await.is_ok(); } loop { @@ -640,7 +675,7 @@ async fn browser_stream_loop( width: frame.width, height: frame.height, }; - if write_response(writer, &resp).await.is_err() { + if write_bounded(writer, &resp).await.is_err() { return false; } in_flight.push_back(frame.seq); @@ -651,17 +686,17 @@ async fn browser_stream_loop( break; } let state = info.borrow_and_update().clone(); - if write_response(writer, &Response::BrowserTabState { tab: state }).await.is_err() { + if write_bounded(writer, &Response::BrowserTabState { tab: state }).await.is_err() { return false; } } changed = closed.changed() => { if changed.is_err() || *closed.borrow() { - return write_response(writer, &closed_response()).await.is_ok(); + return write_bounded(writer, &closed_response()).await.is_ok(); } } Some(reply) = replies_rx.recv() => { - if write_response(writer, &reply).await.is_err() { + if write_bounded(writer, &reply).await.is_err() { return false; } } @@ -685,10 +720,14 @@ async fn browser_stream_loop( } continue; } + if matches!(op, BrowserOp::Resize { .. }) { + let _ = resizes_tx.send(op); + continue; + } if op.is_quiet_on_stream() { let resp = browsers.handle(project_root, op, Caller::Viewer).await; if matches!(resp, Response::Error { .. }) - && write_response(writer, &resp).await.is_err() + && write_bounded(writer, &resp).await.is_err() { return false; } From 3a8f7a5943793f05d3383eb703ea38b371a65dad Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 19:43:03 +0000 Subject: [PATCH 15/30] test(browser): bound the Take Control retry loop Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ2eMMzt56iHuDqpo7z --- crates/pu-engine/tests/browser.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/crates/pu-engine/tests/browser.rs b/crates/pu-engine/tests/browser.rs index f4e0f672..ea42844f 100644 --- a/crates/pu-engine/tests/browser.rs +++ b/crates/pu-engine/tests/browser.rs @@ -328,7 +328,14 @@ async fn given_an_agent_and_a_viewer_should_share_one_live_tab() { }, )) .await; + // The viewer's Control lands asynchronously: accept a few Oks while it does, + // but never wait forever. + let takeover_deadline = tokio::time::Instant::now() + Duration::from_secs(10); let refused = loop { + assert!( + tokio::time::Instant::now() < takeover_deadline, + "Take Control never took effect: agent presses were still accepted" + ); let resp = agent .call(&browser( &root, From e02a02fc2b79e4652d791482272c96c817935dbb Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 19:44:13 +0000 Subject: [PATCH 16/30] fix(browser): stop a dead browser before any relaunch; count opens under the map lock existing() no longer drops a dead instance from the map, so only get_or_launch removes one, after stopping it and waiting for its exit; its profile locks are never cleared while the old process lives. get_or_launch counts the pending open while it holds the map, so a Close cannot retire the browser in between. BROWSER-006 now says control also returns to agents when the last pane watching the tab closes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ2eMMzt56iHuDqpo7z --- crates/pu-engine/src/browser/mod.rs | 33 +++++++++++++++++------------ docs/product/browser.md | 4 ++-- 2 files changed, 22 insertions(+), 15 deletions(-) diff --git a/crates/pu-engine/src/browser/mod.rs b/crates/pu-engine/src/browser/mod.rs index 29057e06..ec545fdc 100644 --- a/crates/pu-engine/src/browser/mod.rs +++ b/crates/pu-engine/src/browser/mod.rs @@ -434,16 +434,16 @@ impl BrowserManager { self.instances.lock().await.clear(); } + /// The project's running browser. A dead one stays in the map: only + /// `get_or_launch` removes it, after stopping it and waiting for it to exit, + /// so its profile is never reused while the old process lives. async fn existing(&self, root: &str) -> Option> { - let mut instances = self.instances.lock().await; - match instances.get(root) { - Some(instance) if instance.cdp.is_alive() => Some(instance.clone()), - Some(_) => { - instances.remove(root); - None - } - None => None, - } + self.instances + .lock() + .await + .get(root) + .filter(|instance| instance.cdp.is_alive()) + .cloned() } async fn running(&self, root: &str) -> Result> { @@ -468,7 +468,13 @@ impl BrowserManager { let dead = { let mut instances = self.instances.lock().await; match instances.get(root) { - Some(instance) if instance.cdp.is_alive() => return Ok(instance.clone()), + Some(instance) if instance.cdp.is_alive() => { + // Counted while the map is held, so a Close cannot retire it in between. + instance + .pending_opens + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); + return Ok(instance.clone()); + } Some(_) => instances.remove(root), None => None, } @@ -478,6 +484,9 @@ impl BrowserManager { dead.stop_and_wait().await; } let instance = self.launch(root).await?; + instance + .pending_opens + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); self.instances .lock() .await @@ -624,11 +633,9 @@ impl BrowserManager { return Ok(Response::BrowserTabs { tabs }); } BrowserOp::Open { url } => { + // Counted as a pending open from inside `get_or_launch`. let instance = self.get_or_launch(root).await?; instance.touch(); - instance - .pending_opens - .fetch_add(1, std::sync::atomic::Ordering::SeqCst); let tab = match instance.create_tab().await { Ok(tab) => tab, Err(error) => { diff --git a/docs/product/browser.md b/docs/product/browser.md index f0087ad2..67d7103a 100644 --- a/docs/product/browser.md +++ b/docs/product/browser.md @@ -37,7 +37,7 @@ Alternatives considered: ! [BROWSER-003] The browser is found as `PU_BROWSER`, else Chrome, Chromium, Edge or Brave in their usual install locations and on `PATH`, else `~/.pu/browser/chrome/chrome`. PurePoint does not ship a browser. ! [BROWSER-004] Frames are JPEG (quality 70) at the viewer's pixel density (Chromium is started at `--force-device-scale-factor=2`, because its screencast captures at the browser's own scale, not the emulated one; each viewer's frames are capped at its width × scale), sent with ack-based flow control: at most two frames un-acknowledged per viewer, newer frames replacing undrawn ones, so a slow link drops frames instead of queueing them. ! [BROWSER-005] The viewport follows the pane: a viewer's `resize` sets the page's CSS viewport and device scale, so pages lay out for the pane and clicks map 1:1. With several viewers the last resize wins. -! [BROWSER-006] A person can take control of a tab (`driver: human`); agent ops that act on the page are refused with `BROWSER_HUMAN_DRIVING` until they hand it back. Viewer input is always accepted. +! [BROWSER-006] A person can take control of a tab (`driver: human`); agent ops that act on the page are refused with `BROWSER_HUMAN_DRIVING` until they hand it back, or until the last pane watching the tab closes or disconnects: control belongs to a person at a pane, so a closed pane never locks agents out. Viewer input is always accepted. ! [BROWSER-007] Agents address elements by `[ref=eN]` from the latest `snapshot`, an indented accessibility outline. Refs are invalidated by the next snapshot and by top-level navigation. ! [BROWSER-008] JavaScript dialogs are accepted automatically and recorded in the console, so neither agents nor viewers can be stuck behind one. ! [BROWSER-009] Pages opened by another page (`window.open`, `target=_blank`) become tabs of the project browser. @@ -70,7 +70,7 @@ Alternatives considered: - Given a browser pane on screen, should show the tab live, with back, forward, reload, the address and who is driving. - Given a pane resize, should resize the page's viewport to match, at the display's pixel density. - Given clicks, drags, scrolling, typing, paste (Cmd/Ctrl+V) and copy (Cmd/Ctrl+C) in the pane, should apply them to the page. -- Given "Take Control", should refuse agents' page actions until "Hand Back". +- Given "Take Control", should refuse agents' page actions until "Hand Back", or until the last pane showing the tab closes or disconnects. - Given a pane whose tab was closed elsewhere, should say so and offer to reopen it on its last page. - Given an app relaunch, should reattach each browser pane to its tab, or reopen its last page if the tab is gone. - Given a project on a remote machine, should behave the same, running the browser on that machine. From 9ff7e2b54b4d72157175aaad997aeacf9ef6fccc Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 19:52:27 +0000 Subject: [PATCH 17/30] fix(browser): publish a navigation's page and drop its refs atomically A navigation now bumps the document generation, clears the refs and publishes the new page under the refs lock, and a snapshot stores its refs and reads the page info under the same lock. A snapshot can no longer return one page's refs with another page's URL. Race test added (fails with the old ordering). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ2eMMzt56iHuDqpo7z --- crates/pu-engine/src/browser/mod.rs | 6 +-- crates/pu-engine/src/browser/tab.rs | 65 +++++++++++++++++++++++------ 2 files changed, 55 insertions(+), 16 deletions(-) diff --git a/crates/pu-engine/src/browser/mod.rs b/crates/pu-engine/src/browser/mod.rs index ec545fdc..04f0278f 100644 --- a/crates/pu-engine/src/browser/mod.rs +++ b/crates/pu-engine/src/browser/mod.rs @@ -723,14 +723,14 @@ impl BrowserManager { let snapshot = snapshot::format(&nodes); // The page may have navigated while the outline was built; its refs // would then point into a document that is gone. - if !tab.store_refs_for(generation, snapshot.refs) { + let Some(info) = tab.store_refs_for(generation, snapshot.refs) else { return Err(BrowserError::new( "BROWSER_PAGE_CHANGED", "the page navigated while it was read; take a new snapshot", )); - } + }; Ok(Response::BrowserSnapshot { - tab: tab.info(), + tab: info, tree: snapshot.tree, }) } diff --git a/crates/pu-engine/src/browser/tab.rs b/crates/pu-engine/src/browser/tab.rs index beedf070..5af58226 100644 --- a/crates/pu-engine/src/browser/tab.rs +++ b/crates/pu-engine/src/browser/tab.rs @@ -172,21 +172,30 @@ impl Tab { self.document.load(Ordering::SeqCst) } - /// Stores a snapshot's refs if the page is still on `generation`. - pub fn store_refs_for(&self, generation: u64, refs: HashMap) -> bool { + /// Stores a snapshot's refs if the page is still on `generation`, and returns + /// the tab as it is at that moment. Both happen under the refs lock, which a + /// navigation also holds while it publishes the new page and drops the old + /// refs, so the refs and the page info a snapshot returns always match. + pub fn store_refs_for( + &self, + generation: u64, + refs: HashMap, + ) -> Option { let mut current = self.refs.lock().unwrap_or_else(|e| e.into_inner()); if self.document.load(Ordering::SeqCst) != generation { - return false; + return None; } *current = refs; - true + Some(self.info()) } - /// A new document: its refs start empty and earlier snapshots are stale. - fn new_document(&self) { + /// A new document at `url`: under the refs lock, earlier snapshots become + /// stale, the old refs go, and only then is the new page published. + fn new_document(&self, url: Option<&str>) { let mut refs = self.refs.lock().unwrap_or_else(|e| e.into_inner()); self.document.fetch_add(1, Ordering::SeqCst); refs.clear(); + self.set_page(url, None); } pub fn resolve_ref(&self, reference: &str) -> Option { @@ -312,9 +321,8 @@ impl Tab { let top = frame.is_some_and(|f| f.get("parentId").is_none()); if top { let url = frame.and_then(|f| f.get("url")).and_then(Value::as_str); - self.set_page(url, None); // Old refs point into the previous document. - self.new_document(); + self.new_document(url); } } "Page.navigatedWithinDocument" if self.is_main_frame(params) => { @@ -541,15 +549,46 @@ mod tests { ), &cdp, ); - assert!(!tab.store_refs_for(generation, HashMap::from([("e1".to_string(), 1)]))); + assert!( + tab.store_refs_for(generation, HashMap::from([("e1".to_string(), 1)])) + .is_none() + ); assert_eq!(tab.resolve_ref("e1"), None); - assert!(tab.store_refs_for( - tab.document_generation(), - HashMap::from([("e1".to_string(), 1)]) - )); + // A snapshot of the new page returns its refs with the new page's info. + let info = tab + .store_refs_for( + tab.document_generation(), + HashMap::from([("e1".to_string(), 1)]), + ) + .expect("current generation"); + assert_eq!(info.url, "http://b/"); assert_eq!(tab.resolve_ref("e1"), Some(1)); } + #[test] + fn given_navigations_racing_snapshots_should_never_pair_refs_with_another_page() { + // Generation n is page `p{n}`. A snapshot commit that succeeds for generation + // n must return page p{n}, however the navigation thread interleaves. + let tab = Arc::new(tab()); + let navigator = { + let tab = tab.clone(); + std::thread::spawn(move || { + for n in 1..=5000u64 { + tab.new_document(Some(&format!("http://p{n}/"))); + } + }) + }; + while !navigator.is_finished() { + let generation = tab.document_generation(); + if let Some(info) = tab.store_refs_for(generation, HashMap::new()) + && generation > 0 + { + assert_eq!(info.url, format!("http://p{generation}/")); + } + } + navigator.join().unwrap(); + } + #[tokio::test] async fn given_the_last_viewer_leaves_should_hand_the_tab_back_to_agents() { let tab = tab(); From cb1a638627aae93487bb6441f267843679868adf Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 19:56:34 +0000 Subject: [PATCH 18/30] fix(browser): keep Control in stream order, confirm browser exit before reuse, bound reject write, ack only current-stream frames Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ2eMMzt56iHuDqpo7z --- .../ui/src/services/browser.ts | 2 +- .../ui/src/state/browserSession.ts | 5 +- .../views/browser/BrowserPaneView.test.tsx | 39 ++++++++++ .../ui/src/views/browser/BrowserPaneView.tsx | 7 +- crates/pu-engine/src/browser/mod.rs | 75 ++++++++++++++----- crates/pu-engine/src/ipc_server/streams.rs | 17 ++++- crates/pu-engine/tests/browser.rs | 37 +++++++++ 7 files changed, 159 insertions(+), 23 deletions(-) diff --git a/apps/purepoint-windows/ui/src/services/browser.ts b/apps/purepoint-windows/ui/src/services/browser.ts index 3fe9f10a..248b5779 100644 --- a/apps/purepoint-windows/ui/src/services/browser.ts +++ b/apps/purepoint-windows/ui/src/services/browser.ts @@ -15,7 +15,7 @@ export type BrowserStreamEvent = | { type: 'tab'; tab: BrowserTabInfo } /** Attached; frames follow. */ | { type: 'live' } - /** A frame: `data` is a base64 JPEG of the CSS viewport `width` x `height`. Ack `seq` once drawn. */ + /** A frame: `data` is a base64 JPEG of the CSS viewport `width` x `height`. Ack `seq` once handled (drawn, superseded or undecodable). */ | { type: 'frame'; seq: number; data: string; width: number; height: number } /** The answer to an `eval` sent on the stream. */ | { type: 'eval_result'; value: unknown } diff --git a/apps/purepoint-windows/ui/src/state/browserSession.ts b/apps/purepoint-windows/ui/src/state/browserSession.ts index 1360021f..3c00dfc2 100644 --- a/apps/purepoint-windows/ui/src/state/browserSession.ts +++ b/apps/purepoint-windows/ui/src/state/browserSession.ts @@ -7,8 +7,9 @@ // shows and turns the person's actions into ops on that stream. // // Differences from Swift: -// - Frames are acked by the view once it has drawn them (`frameDrawn`), not here: the decode -// happens in the view's canvas. +// - Frames are acked by the view once it has handled them (`frameDrawn`), not here: the +// decode happens in the view's canvas. Handled means drawn, superseded by a newer drawn +// frame, or undecodable; a frame from a closed or reopened tab's stream is never acked. // - A resize asked for before the backend session exists is kept and sent once it does (the // backend then replays it on every reattach, as the Swift session does). import { createStore, type StoreApi } from 'zustand/vanilla'; diff --git a/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.test.tsx b/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.test.tsx index f15dce89..f7825f3f 100644 --- a/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.test.tsx +++ b/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.test.tsx @@ -183,4 +183,43 @@ describe('BrowserPaneView', () => { getContext.mockRestore(); } }); + + it('acks an undecodable frame but never a frame from before the tab reopened', async () => { + const decodes: { resolve: () => void; reject: (e: Error) => void }[] = []; + const original = Object.getOwnPropertyDescriptor(HTMLImageElement.prototype, 'decode'); + Object.defineProperty(HTMLImageElement.prototype, 'decode', { + configurable: true, + value: () => new Promise((resolve, reject) => decodes.push({ resolve, reject })), + }); + const getContext = vi + .spyOn(HTMLCanvasElement.prototype, 'getContext') + .mockImplementation(() => ({ drawImage: vi.fn(), clearRect: vi.fn() }) as never); + try { + const { send, sent } = setup(); + const acks = () => sent.filter((op) => op.action === 'frame_ack').map((op) => op.seq); + await send({ type: 'tab', tab: tab() }); + await send({ type: 'live' }); + await send({ type: 'frame', seq: 1, data: 'AAAA', width: 1280, height: 800 }); + await act(async () => { + decodes[0]?.reject(new Error('corrupt')); + await Promise.resolve(); + await Promise.resolve(); + }); + // Undecodable, but handled: acked so it cannot pin a flow-control slot. + expect(acks()).toEqual([1]); + await send({ type: 'frame', seq: 2, data: 'BBBB', width: 1280, height: 800 }); + // The tab closes while frame 2 decodes; its late decode must not ack. + await send({ type: 'closed' }); + await act(async () => { + decodes[1]?.resolve(); + await Promise.resolve(); + await Promise.resolve(); + }); + expect(acks()).toEqual([1]); + } finally { + if (original) Object.defineProperty(HTMLImageElement.prototype, 'decode', original); + else delete (HTMLImageElement.prototype as { decode?: unknown }).decode; + getContext.mockRestore(); + } + }); }); diff --git a/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.tsx b/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.tsx index 158387c3..3e1e6362 100644 --- a/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.tsx +++ b/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.tsx @@ -409,7 +409,12 @@ function BrowserCanvas({ }) .catch(() => undefined) .finally(() => { - if (!unmounted.current) handlers.current.onDrawn(seq); + // Ack frames this stream sent once they are handled: drawn, superseded by a + // newer drawn frame, or undecodable (unacked, it would pin one of only two + // flow-control slots and stall the pane). A frame from before the tab closed + // or reopened belongs to an old stream and is never acked on the new one. + if (unmounted.current || startedIn !== epoch.current) return; + handlers.current.onDrawn(seq); }); }, [frame]); diff --git a/crates/pu-engine/src/browser/mod.rs b/crates/pu-engine/src/browser/mod.rs index 04f0278f..d6ba2b59 100644 --- a/crates/pu-engine/src/browser/mod.rs +++ b/crates/pu-engine/src/browser/mod.rs @@ -122,15 +122,25 @@ impl Drop for Instance { impl Instance { /// Ends the browser's process group and waits (briefly) for it to exit. - async fn stop_and_wait(&self) { + /// Ends the browser's process group and waits (up to 5 s) for it to exit. + /// Returns whether the exit is confirmed; if not, this instance keeps owning + /// the process (and its profile), so the caller must not start another on it. + async fn stop_and_wait(&self) -> bool { #[cfg(unix)] if let Some(pid) = self.pid { launch::unix::stop_group(pid); } let child = self._child.lock().unwrap_or_else(|e| e.into_inner()).take(); - if let Some(mut child) = child { - let _ = child.start_kill(); - let _ = tokio::time::timeout(Duration::from_secs(5), child.wait()).await; + let Some(mut child) = child else { + return true; // already reaped + }; + let _ = child.start_kill(); + match tokio::time::timeout(Duration::from_secs(5), child.wait()).await { + Ok(Ok(_)) => true, + _ => { + *self._child.lock().unwrap_or_else(|e| e.into_inner()) = Some(child); + false + } } } @@ -479,9 +489,15 @@ impl BrowserManager { None => None, } }; - if let Some(dead) = dead { - // Its profile is reused next: make sure the old process is gone first. - dead.stop_and_wait().await; + if let Some(dead) = dead + && !dead.stop_and_wait().await + { + // Its profile is reused next: never while the old process may live. + self.instances.lock().await.insert(root.to_string(), dead); + return Err(BrowserError::new( + "BROWSER_LAUNCH_FAILED", + "the project's previous browser has not exited yet; try again shortly", + )); } let instance = self.launch(root).await?; instance @@ -495,19 +511,42 @@ impl BrowserManager { } /// Forgets a project's browser once it has no tabs and no open in progress. + /// Serialized with startup (same per-project lock), so a new browser never + /// starts on the profile while this one is still exiting. async fn retire_if_unused(&self, root: &str, instance: &Arc) { - let mut instances = self.instances.lock().await; - let same = instances - .get(root) - .is_some_and(|current| Arc::ptr_eq(current, instance)); - if same - && instance.is_empty() - && instance - .pending_opens - .load(std::sync::atomic::Ordering::SeqCst) - == 0 + let startup = self + .startups + .lock() + .await + .entry(root.to_string()) + .or_default() + .clone(); + let _starting = startup.lock().await; + let retired = { + let mut instances = self.instances.lock().await; + let same = instances + .get(root) + .is_some_and(|current| Arc::ptr_eq(current, instance)); + let unused = instance.is_empty() + && instance + .pending_opens + .load(std::sync::atomic::Ordering::SeqCst) + == 0; + if same && unused { + instances.remove(root) + } else { + None + } + }; + if let Some(retired) = retired + && !retired.stop_and_wait().await { - instances.remove(root); + // Not confirmed gone: keep owning it, so the next open waits for it. + self.instances + .lock() + .await + .entry(root.to_string()) + .or_insert(retired); } } diff --git a/crates/pu-engine/src/ipc_server/streams.rs b/crates/pu-engine/src/ipc_server/streams.rs index 5e54a14a..1cf496f1 100644 --- a/crates/pu-engine/src/ipc_server/streams.rs +++ b/crates/pu-engine/src/ipc_server/streams.rs @@ -705,7 +705,13 @@ async fn browser_stream_loop( Ok(Frame::Line(line)) => line, Ok(Frame::Eof) => return false, Ok(Frame::TooLarge) => { - reject_frame_too_large(writer).await; + // Bounded like every write here, so a viewer that sends an + // oversized line and stops reading cannot hold the stream. + let _ = tokio::time::timeout( + BROWSER_WRITE_TIMEOUT, + reject_frame_too_large(writer), + ) + .await; return false; } Err(_) => return false, @@ -724,6 +730,15 @@ async fn browser_stream_loop( let _ = resizes_tx.send(op); continue; } + // Control only flips the driver; run it here, in stream order, so it + // can never land after this viewer's teardown handed the tab back. + if matches!(op, BrowserOp::Control { .. }) { + let resp = browsers.handle(project_root, op, Caller::Viewer).await; + if write_bounded(writer, &resp).await.is_err() { + return false; + } + continue; + } if op.is_quiet_on_stream() { let resp = browsers.handle(project_root, op, Caller::Viewer).await; if matches!(resp, Response::Error { .. }) diff --git a/crates/pu-engine/tests/browser.rs b/crates/pu-engine/tests/browser.rs index ea42844f..f0b0764e 100644 --- a/crates/pu-engine/tests/browser.rs +++ b/crates/pu-engine/tests/browser.rs @@ -593,3 +593,40 @@ async fn given_altgr_text_from_a_viewer_should_type_it_on_linux_chromium() { } manager.shutdown().await; } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn given_the_last_tab_closed_should_open_again_on_a_fresh_browser() { + if !have_browser() { + eprintln!("skipping: no Chrome/Chromium on this machine (set PU_BROWSER)"); + return; + } + use pu_engine::browser::{BrowserManager, Caller}; + let tmp = TempDir::new().unwrap(); + let manager = BrowserManager::new(Some(tmp.path().join("browser"))); + let open = || BrowserOp::Open { + url: Some("about:blank".into()), + }; + for round in 0..3 { + let tab = match manager.handle("/p", open(), Caller::Agent).await { + Response::BrowserTab { tab } => tab, + other => panic!("round {round}: open failed: {other:?}"), + }; + // Closing the last tab retires the browser and waits for it to exit, + // so the next open (same profile) always starts cleanly. + let closed = manager + .handle( + "/p", + BrowserOp::Close { + tab_id: Some(tab.tab_id), + }, + Caller::Agent, + ) + .await; + assert!(matches!(closed, Response::Ok), "round {round}: {closed:?}"); + assert!(matches!( + manager.handle("/p", BrowserOp::List, Caller::Agent).await, + Response::BrowserTabs { tabs } if tabs.is_empty() + )); + } + manager.shutdown().await; +} From d12929d349b57c5629dd80e2063dddf9ed8614c2 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 19:58:47 +0000 Subject: [PATCH 19/30] fix(browser): refuse a snapshot whose page URL changed before frameNavigated; bound the whole takeover wait in the test Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ2eMMzt56iHuDqpo7z --- crates/pu-engine/src/browser/mod.rs | 4 +- crates/pu-engine/src/browser/tab.rs | 100 ++++++++++++++++++++++------ crates/pu-engine/tests/browser.rs | 38 +++++------ 3 files changed, 99 insertions(+), 43 deletions(-) diff --git a/crates/pu-engine/src/browser/mod.rs b/crates/pu-engine/src/browser/mod.rs index d6ba2b59..f3563515 100644 --- a/crates/pu-engine/src/browser/mod.rs +++ b/crates/pu-engine/src/browser/mod.rs @@ -750,7 +750,7 @@ impl BrowserManager { Ok(Response::BrowserTab { tab: tab.info() }) } BrowserOp::Snapshot { .. } => { - let generation = tab.document_generation(); + let mark = tab.document_mark(); let tree = cdp .call(session, "Accessibility.getFullAXTree", json!({})) .await?; @@ -762,7 +762,7 @@ impl BrowserManager { let snapshot = snapshot::format(&nodes); // The page may have navigated while the outline was built; its refs // would then point into a document that is gone. - let Some(info) = tab.store_refs_for(generation, snapshot.refs) else { + let Some(info) = tab.store_refs_for(&mark, snapshot.refs) else { return Err(BrowserError::new( "BROWSER_PAGE_CHANGED", "the page navigated while it was read; take a new snapshot", diff --git a/crates/pu-engine/src/browser/tab.rs b/crates/pu-engine/src/browser/tab.rs index 5af58226..140f7bfd 100644 --- a/crates/pu-engine/src/browser/tab.rs +++ b/crates/pu-engine/src/browser/tab.rs @@ -37,6 +37,13 @@ pub struct Viewport { pub scale: f64, } +/// The document and URL a snapshot started on. +#[derive(Debug, Clone)] +pub struct DocumentMark { + generation: u64, + url: String, +} + pub struct Tab { pub target_id: String, pub session_id: String, @@ -139,7 +146,14 @@ impl Tab { }); } + /// Publishes the page's URL and title. Held under the refs lock, so a snapshot + /// commit never sees the URL change halfway (see `store_refs_for`). pub fn set_page(&self, url: Option<&str>, title: Option<&str>) { + let _refs = self.refs.lock().unwrap_or_else(|e| e.into_inner()); + self.publish_page(url, title); + } + + fn publish_page(&self, url: Option<&str>, title: Option<&str>) { self.info.send_if_modified(|info| { let mut changed = false; if let Some(url) = url.filter(|u| *u != info.url) { @@ -166,27 +180,33 @@ impl Tab { *self.refs.lock().unwrap_or_else(|e| e.into_inner()) = refs; } - /// Which document the page shows; a snapshot taken under one generation must - /// not publish refs after the page moved on. - pub fn document_generation(&self) -> u64 { - self.document.load(Ordering::SeqCst) + /// Which document the page shows, and at what URL, as a snapshot starts. + pub fn document_mark(&self) -> DocumentMark { + let _refs = self.refs.lock().unwrap_or_else(|e| e.into_inner()); + DocumentMark { + generation: self.document.load(Ordering::SeqCst), + url: self.info.borrow().url.clone(), + } } - /// Stores a snapshot's refs if the page is still on `generation`, and returns - /// the tab as it is at that moment. Both happen under the refs lock, which a - /// navigation also holds while it publishes the new page and drops the old - /// refs, so the refs and the page info a snapshot returns always match. + /// Stores a snapshot's refs if the page is still the document and URL in + /// `mark`, and returns the tab as it is at that moment. A new document bumps + /// the generation; the URL check also catches a URL published before the + /// browser's `frameNavigated` reached the event pump (a navigate's own + /// report, `targetInfoChanged`). Every URL change holds the refs lock, so the + /// refs and the page info a snapshot returns always match. pub fn store_refs_for( &self, - generation: u64, + mark: &DocumentMark, refs: HashMap, ) -> Option { let mut current = self.refs.lock().unwrap_or_else(|e| e.into_inner()); - if self.document.load(Ordering::SeqCst) != generation { + let info = self.info(); + if self.document.load(Ordering::SeqCst) != mark.generation || info.url != mark.url { return None; } *current = refs; - Some(self.info()) + Some(info) } /// A new document at `url`: under the refs lock, earlier snapshots become @@ -195,7 +215,7 @@ impl Tab { let mut refs = self.refs.lock().unwrap_or_else(|e| e.into_inner()); self.document.fetch_add(1, Ordering::SeqCst); refs.clear(); - self.set_page(url, None); + self.publish_page(url, None); } pub fn resolve_ref(&self, reference: &str) -> Option { @@ -541,7 +561,7 @@ mod tests { async fn given_a_navigation_during_a_snapshot_should_refuse_its_refs() { let tab = tab(); let cdp = cdp(); - let generation = tab.document_generation(); + let mark = tab.document_mark(); tab.on_event( &event( "Page.frameNavigated", @@ -550,16 +570,13 @@ mod tests { &cdp, ); assert!( - tab.store_refs_for(generation, HashMap::from([("e1".to_string(), 1)])) + tab.store_refs_for(&mark, HashMap::from([("e1".to_string(), 1)])) .is_none() ); assert_eq!(tab.resolve_ref("e1"), None); // A snapshot of the new page returns its refs with the new page's info. let info = tab - .store_refs_for( - tab.document_generation(), - HashMap::from([("e1".to_string(), 1)]), - ) + .store_refs_for(&tab.document_mark(), HashMap::from([("e1".to_string(), 1)])) .expect("current generation"); assert_eq!(info.url, "http://b/"); assert_eq!(tab.resolve_ref("e1"), Some(1)); @@ -579,16 +596,55 @@ mod tests { }) }; while !navigator.is_finished() { - let generation = tab.document_generation(); - if let Some(info) = tab.store_refs_for(generation, HashMap::new()) - && generation > 0 + let mark = tab.document_mark(); + if let Some(info) = tab.store_refs_for(&mark, HashMap::new()) + && mark.generation > 0 { - assert_eq!(info.url, format!("http://p{generation}/")); + assert_eq!(info.url, format!("http://p{}/", mark.generation)); } } navigator.join().unwrap(); } + #[test] + fn given_the_url_published_before_frame_navigated_should_refuse_the_snapshot() { + // `navigate` (or `targetInfoChanged`) can publish the new URL while the + // event pump has not yet handled `frameNavigated`: the generation is still + // the old page's, but a snapshot of page A must not come back as page B. + let tab = tab(); + tab.set_page(Some("http://a/"), None); + let mark = tab.document_mark(); + tab.set_page(Some("http://b/"), None); + assert!( + tab.store_refs_for(&mark, HashMap::from([("e1".to_string(), 1)])) + .is_none() + ); + assert_eq!(tab.resolve_ref("e1"), None); + } + + #[test] + fn given_url_reports_racing_snapshots_should_never_pair_refs_with_another_url() { + // Page A's outline is committed only while the tab still reports A. + let tab = Arc::new(tab()); + tab.set_page(Some("http://a/"), None); + let reporter = { + let tab = tab.clone(); + std::thread::spawn(move || { + for n in 0..5000u64 { + let url = if n % 2 == 0 { "http://b/" } else { "http://a/" }; + tab.set_page(Some(url), None); + } + }) + }; + while !reporter.is_finished() { + let mark = tab.document_mark(); + if let Some(info) = tab.store_refs_for(&mark, HashMap::new()) { + assert_eq!(info.url, mark.url); + } + } + reporter.join().unwrap(); + } + #[tokio::test] async fn given_the_last_viewer_leaves_should_hand_the_tab_back_to_agents() { let tab = tab(); diff --git a/crates/pu-engine/tests/browser.rs b/crates/pu-engine/tests/browser.rs index f0b0764e..1e4d8961 100644 --- a/crates/pu-engine/tests/browser.rs +++ b/crates/pu-engine/tests/browser.rs @@ -329,27 +329,27 @@ async fn given_an_agent_and_a_viewer_should_share_one_live_tab() { )) .await; // The viewer's Control lands asynchronously: accept a few Oks while it does, - // but never wait forever. - let takeover_deadline = tokio::time::Instant::now() + Duration::from_secs(10); - let refused = loop { - assert!( - tokio::time::Instant::now() < takeover_deadline, - "Take Control never took effect: agent presses were still accepted" - ); - let resp = agent - .call(&browser( - &root, - BrowserOp::Press { - tab_id: None, - key: "Tab".into(), - }, - )) - .await; - match resp { - Response::Ok => tokio::time::sleep(Duration::from_millis(50)).await, - other => break other, + // but bound the whole wait, calls and sleeps included. + let takeover = async { + loop { + let resp = agent + .call(&browser( + &root, + BrowserOp::Press { + tab_id: None, + key: "Tab".into(), + }, + )) + .await; + match resp { + Response::Ok => tokio::time::sleep(Duration::from_millis(50)).await, + other => break other, + } } }; + let refused = tokio::time::timeout(Duration::from_secs(10), takeover) + .await + .expect("Take Control never took effect: agent presses were still accepted"); assert!( matches!(&refused, Response::Error { code, .. } if code == "BROWSER_HUMAN_DRIVING"), "{refused:?}" From 3782d67f494a8121cc365ce3c42bd33ef5e83336 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 20:03:55 +0000 Subject: [PATCH 20/30] fix(browser): reap a browser whose startup failed before reusing its profile; reset a pane's frame tracking per attach stream Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ2eMMzt56iHuDqpo7z --- .../ui/src/state/browserSession.test.ts | 8 +- .../ui/src/state/browserSession.ts | 13 +- .../views/browser/BrowserPaneView.test.tsx | 43 ++++++ .../ui/src/views/browser/BrowserPaneView.tsx | 19 ++- crates/pu-engine/src/browser/mod.rs | 133 ++++++++++++------ crates/pu-engine/tests/browser.rs | 82 +++++++++++ crates/pu-engine/tests/browser_launch.rs | 71 ++++++++++ 7 files changed, 317 insertions(+), 52 deletions(-) create mode 100644 crates/pu-engine/tests/browser_launch.rs diff --git a/apps/purepoint-windows/ui/src/state/browserSession.test.ts b/apps/purepoint-windows/ui/src/state/browserSession.test.ts index 76b09b32..b6069ca9 100644 --- a/apps/purepoint-windows/ui/src/state/browserSession.test.ts +++ b/apps/purepoint-windows/ui/src/state/browserSession.test.ts @@ -134,7 +134,13 @@ describe('BrowserSession', () => { session.start(); await settle(); stream().emit({ type: 'frame', seq: 3, data: '/9j/', width: 1024, height: 768 }); - expect(session.state.frame).toEqual({ seq: 3, data: '/9j/', width: 1024, height: 768 }); + expect(session.state.frame).toEqual({ + stream: 0, + seq: 3, + data: '/9j/', + width: 1024, + height: 768, + }); expect(session.state.frameSize).toEqual({ width: 1024, height: 768 }); expect(stream().sent).toEqual([]); session.frameDrawn(3); diff --git a/apps/purepoint-windows/ui/src/state/browserSession.ts b/apps/purepoint-windows/ui/src/state/browserSession.ts index 3c00dfc2..134a6c7c 100644 --- a/apps/purepoint-windows/ui/src/state/browserSession.ts +++ b/apps/purepoint-windows/ui/src/state/browserSession.ts @@ -33,6 +33,8 @@ import { /** The frame on screen: a base64 JPEG and the CSS viewport it shows. */ export interface BrowserFrame { + /** Which attach stream sent it: a new stream (a reconnect, or a replaced tab) numbers frames afresh. */ + readonly stream: number; readonly seq: number; readonly data: string; readonly width: number; @@ -77,6 +79,8 @@ export class BrowserSession { private stream: BrowserStream | null = null; /** Bumped per start and stop, so a superseded stream's late events are dropped. */ private generation = 0; + /** Counts attach streams that went live; each frame carries the one it came on. */ + private attachedStreams = 0; private started = false; private viewport: Viewport | null = null; private pendingCopy = false; @@ -225,11 +229,18 @@ export class BrowserSession { this.adopt(event.tab); return; case 'live': + this.attachedStreams += 1; this.store.setState({ phase: { kind: 'live' } }); return; case 'frame': this.store.setState({ - frame: { seq: event.seq, data: event.data, width: event.width, height: event.height }, + frame: { + stream: this.attachedStreams, + seq: event.seq, + data: event.data, + width: event.width, + height: event.height, + }, frameSize: { width: event.width, height: event.height }, }); return; diff --git a/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.test.tsx b/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.test.tsx index f7825f3f..6ff7ecc4 100644 --- a/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.test.tsx +++ b/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.test.tsx @@ -222,4 +222,47 @@ describe('BrowserPaneView', () => { getContext.mockRestore(); } }); + + it("drops an old tab's pending frame when a lost tab is replaced without a close", async () => { + const decodes: (() => void)[] = []; + const original = Object.getOwnPropertyDescriptor(HTMLImageElement.prototype, 'decode'); + Object.defineProperty(HTMLImageElement.prototype, 'decode', { + configurable: true, + value: () => new Promise((resolve) => decodes.push(resolve)), + }); + const drawImage = vi.fn(); + const getContext = vi + .spyOn(HTMLCanvasElement.prototype, 'getContext') + .mockImplementation(() => ({ drawImage, clearRect: vi.fn() }) as never); + try { + const { send, sent } = setup(); + const acks = () => sent.filter((op) => op.action === 'frame_ack').map((op) => op.seq); + await send({ type: 'tab', tab: tab() }); + await send({ type: 'live' }); + await send({ type: 'frame', seq: 5, data: 'AAAA', width: 1280, height: 800 }); + // The connection drops; the backend reopens the lost tab as t2 and reattaches. + await send({ type: 'tab', tab: tab({ tab_id: 't2' }) }); + await send({ type: 'live' }); + await send({ type: 'frame', seq: 1, data: 'BBBB', width: 1280, height: 800 }); + await act(async () => { + decodes[0]?.(); // t1's frame 5 finishes late + await Promise.resolve(); + await Promise.resolve(); + }); + expect(drawImage).not.toHaveBeenCalled(); + expect(acks()).toEqual([]); + await act(async () => { + decodes[1]?.(); + await Promise.resolve(); + await Promise.resolve(); + }); + // t2's frame 1 draws although t1 had reached frame 5. + expect(drawImage).toHaveBeenCalledTimes(1); + expect(acks()).toEqual([1]); + } finally { + if (original) Object.defineProperty(HTMLImageElement.prototype, 'decode', original); + else delete (HTMLImageElement.prototype as { decode?: unknown }).decode; + getContext.mockRestore(); + } + }); }); diff --git a/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.tsx b/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.tsx index 3e1e6362..223eb88f 100644 --- a/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.tsx +++ b/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.tsx @@ -341,8 +341,10 @@ function BrowserCanvas({ const box = useRef(null); const lastHover = useRef(0); const drawnSeq = useRef(-1); - /** Bumped when the tab closes or reopens, so a decode started before it never draws. */ + /** Bumped when the tab closes or a new stream starts, so a decode started before it never draws. */ const epoch = useRef(0); + /** The attach stream whose frames the canvas shows. */ + const frameStream = useRef(null); const unmounted = useRef(false); const handlers = useRef({ onResize, onDrawn }); useLayoutEffect(() => { @@ -384,8 +386,9 @@ function BrowserCanvas({ // Draw each frame, then ack it: the daemon sends at most two ahead of the screen. // A newer frame never cancels an older one's decode (when decoding is slower // than frames arrive, that would starve the canvas); `seq` keeps an older frame - // from painting over a newer one. Only unmounting or a closed/reopened tab - // (a new `epoch`) drops a pending draw. + // from painting over a newer one. Only unmounting, a closed tab or a new attach + // stream (a reconnect, or a lost tab replaced without a close) starts a new + // `epoch`, which drops pending draws: a replaced tab numbers its frames from 1. useEffect(() => { if (frame === null) { // The tab closed (or reopens): blank the page; a new tab numbers its frames afresh. @@ -397,7 +400,13 @@ function BrowserCanvas({ } return; } - const { seq, data } = frame; + const { stream, seq, data } = frame; + if (stream !== frameStream.current) { + // The old picture stays until the new stream's first frame replaces it. + frameStream.current = stream; + epoch.current += 1; + drawnSeq.current = -1; + } const startedIn = epoch.current; decodeFrame(data) .then((image) => { @@ -412,7 +421,7 @@ function BrowserCanvas({ // Ack frames this stream sent once they are handled: drawn, superseded by a // newer drawn frame, or undecodable (unacked, it would pin one of only two // flow-control slots and stall the pane). A frame from before the tab closed - // or reopened belongs to an old stream and is never acked on the new one. + // or the stream changed belongs to an old stream and is never acked on the new one. if (unmounted.current || startedIn !== epoch.current) return; handlers.current.onDrawn(seq); }); diff --git a/crates/pu-engine/src/browser/mod.rs b/crates/pu-engine/src/browser/mod.rs index f3563515..2ae90aee 100644 --- a/crates/pu-engine/src/browser/mod.rs +++ b/crates/pu-engine/src/browser/mod.rs @@ -121,23 +121,14 @@ impl Drop for Instance { } impl Instance { - /// Ends the browser's process group and waits (briefly) for it to exit. /// Ends the browser's process group and waits (up to 5 s) for it to exit. /// Returns whether the exit is confirmed; if not, this instance keeps owning /// the process (and its profile), so the caller must not start another on it. async fn stop_and_wait(&self) -> bool { - #[cfg(unix)] - if let Some(pid) = self.pid { - launch::unix::stop_group(pid); - } let child = self._child.lock().unwrap_or_else(|e| e.into_inner()).take(); - let Some(mut child) = child else { - return true; // already reaped - }; - let _ = child.start_kill(); - match tokio::time::timeout(Duration::from_secs(5), child.wait()).await { - Ok(Ok(_)) => true, - _ => { + match stop_child(self.pid, child).await { + Ok(()) => true, + Err(child) => { *self._child.lock().unwrap_or_else(|e| e.into_inner()) = Some(child); false } @@ -403,11 +394,74 @@ async fn refresh_history(cdp: &Cdp, tab: &Tab) { tab.set_history(index > 0, index + 1 < count); } +/// Ends a browser's process group and waits (up to 5 s) for it to exit. +/// Hands the child back if its exit is not confirmed. +async fn stop_child( + pid: Option, + child: Option, +) -> std::result::Result<(), tokio::process::Child> { + #[cfg(unix)] + if let Some(pid) = pid { + launch::unix::stop_group(pid); + } + #[cfg(not(unix))] + let _ = pid; + let Some(mut child) = child else { + return Ok(()); // already reaped + }; + let _ = child.start_kill(); + match tokio::time::timeout(Duration::from_secs(5), child.wait()).await { + Ok(Ok(_)) => Ok(()), + _ => Err(child), + } +} + +/// The browser's first exchange: target discovery on, and its starting tabs. +#[cfg(unix)] +async fn initialize(cdp: &Cdp, executable: &Path, log: &Path) -> Result> { + cdp.call( + None, + "Target.setDiscoverTargets", + json!({ "discover": true }), + ) + .await + .map_err(|e| { + BrowserError::new( + "BROWSER_LAUNCH_FAILED", + format!( + "{} started but did not answer ({e}); see {}", + executable.display(), + log.display() + ), + ) + })?; + let targets = cdp.call(None, "Target.getTargets", json!({})).await?; + Ok(targets + .get("targetInfos") + .and_then(Value::as_array) + .map(|infos| { + infos + .iter() + .filter(|i| i.get("type").and_then(Value::as_str) == Some("page")) + .filter_map(|i| { + i.get("targetId") + .and_then(Value::as_str) + .map(str::to_string) + }) + .collect() + }) + .unwrap_or_default()) +} + /// The browsers of every project on this daemon. pub struct BrowserManager { instances: Mutex>>, /// Serializes each project's browser startup. startups: Mutex>>>, + /// A browser whose startup failed and whose exit was not confirmed yet: its + /// profile is not reused until it has exited. + #[cfg_attr(not(unix), allow(dead_code))] + lingering: Mutex>, base_dir: Option, idle_stop: Duration, } @@ -428,6 +482,7 @@ impl BrowserManager { Self { instances: Mutex::new(HashMap::new()), startups: Mutex::new(HashMap::new()), + lingering: Mutex::new(HashMap::new()), base_dir, idle_stop: IDLE_STOP, } @@ -582,6 +637,15 @@ impl BrowserManager { BrowserError::new("BROWSER_ERROR", format!("{}: {e}", dir.display())) })?; } + // A failed earlier startup's browser must be gone before its profile is reused. + let lingering = self.lingering.lock().await.remove(root); + if let Err(child) = stop_child(None, lingering).await { + self.lingering.lock().await.insert(root.to_string(), child); + return Err(BrowserError::new( + "BROWSER_LAUNCH_FAILED", + "the project's previous browser has not exited yet; try again shortly", + )); + } // A daemon that was killed can leave the profile's singleton lock behind; // with it Chromium hands off to a browser that no longer exists and exits. for lock in ["SingletonLock", "SingletonSocket", "SingletonCookie"] { @@ -597,45 +661,24 @@ impl BrowserManager { ) })?; let pid = launched.child.id(); + let mut child = Some(launched.child); let cdp = Cdp::start(launched.reader, launched.writer); let events = cdp.subscribe(); - cdp.call( - None, - "Target.setDiscoverTargets", - json!({ "discover": true }), - ) - .await - .map_err(|e| { - BrowserError::new( - "BROWSER_LAUNCH_FAILED", - format!( - "{} started but did not answer ({e}); see {}", - executable.display(), - log.display() - ), - ) - })?; - let targets = cdp.call(None, "Target.getTargets", json!({})).await?; - let initial = targets - .get("targetInfos") - .and_then(Value::as_array) - .map(|infos| { - infos - .iter() - .filter(|i| i.get("type").and_then(Value::as_str) == Some("page")) - .filter_map(|i| { - i.get("targetId") - .and_then(Value::as_str) - .map(str::to_string) - }) - .collect() - }) - .unwrap_or_default(); + let initial = match initialize(&cdp, &executable, &log).await { + Ok(initial) => initial, + Err(error) => { + // Own the process until it has exited: a retry reuses its profile. + if let Err(child) = stop_child(pid, child.take()).await { + self.lingering.lock().await.insert(root.to_string(), child); + } + return Err(error); + } + }; tracing::info!(project_root = root, pid, browser = %executable.display(), "browser started"); let instance = Arc::new(Instance { cdp: cdp.clone(), pid, - _child: std::sync::Mutex::new(Some(launched.child)), + _child: std::sync::Mutex::new(child), tabs: std::sync::Mutex::new(IndexMap::new()), initial_targets: std::sync::Mutex::new(initial), screenshots, diff --git a/crates/pu-engine/tests/browser.rs b/crates/pu-engine/tests/browser.rs index 1e4d8961..d44c8032 100644 --- a/crates/pu-engine/tests/browser.rs +++ b/crates/pu-engine/tests/browser.rs @@ -107,6 +107,13 @@ impl Client { } } +async fn driver_of(agent: &mut Client, root: &str) -> BrowserDriver { + match agent.call(&browser(root, BrowserOp::List)).await { + Response::BrowserTabs { tabs } => tabs[0].driver, + other => panic!("list: {other:?}"), + } +} + fn browser(root: &str, op: BrowserOp) -> Request { Request::Browser { project_root: root.to_string(), @@ -630,3 +637,78 @@ async fn given_the_last_tab_closed_should_open_again_on_a_fresh_browser() { } manager.shutdown().await; } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn given_take_control_then_an_immediate_disconnect_should_hand_the_tab_back_to_agents() { + if !have_browser() { + eprintln!("skipping: no Chrome/Chromium on this machine (set PU_BROWSER)"); + return; + } + let tmp = TempDir::new().unwrap(); + let sock = tmp.path().join("daemon.sock"); + let project = tmp.path().join("app"); + std::fs::create_dir_all(&project).unwrap(); + let engine = pu_engine::engine::Engine::new().with_browser_dir(tmp.path().join("browser")); + let server = pu_engine::ipc_server::IpcServer::bind(&sock, engine).unwrap(); + let engine = server.engine().clone(); + tokio::spawn(async move { server.run().await.ok() }); + let root = pu_core::canon::canonicalize(&project) + .unwrap() + .to_string_lossy() + .into_owned(); + let mut agent = Client::connect(&sock).await; + let tab = match agent + .call(&browser( + &root, + BrowserOp::Open { + url: Some("about:blank".into()), + }, + )) + .await + { + Response::BrowserTab { tab } => tab, + other => panic!("open: {other:?}"), + }; + // A pane takes control and its connection drops right after: the Control + // must never land after the viewer is gone and lock agents out. + for round in 0..10 { + let mut viewer = Client::connect(&sock).await; + assert!(matches!( + viewer + .call(&Request::BrowserAttach { + project_root: root.clone(), + tab_id: Some(tab.tab_id.clone()), + }) + .await, + Response::BrowserAttached { .. } + )); + viewer + .write(&browser( + &root, + BrowserOp::Control { + tab_id: None, + driver: BrowserDriver::Human, + }, + )) + .await; + drop(viewer); + let back = tokio::time::timeout(Duration::from_secs(10), async { + while driver_of(&mut agent, &root).await != BrowserDriver::Agent { + tokio::time::sleep(Duration::from_millis(20)).await; + } + }) + .await; + assert!( + back.is_ok(), + "round {round}: the tab stayed with the person" + ); + // And it stays with agents: no late Control takes it again. + tokio::time::sleep(Duration::from_millis(200)).await; + assert_eq!( + driver_of(&mut agent, &root).await, + BrowserDriver::Agent, + "round {round}" + ); + } + engine.kill_all_sessions(Duration::from_millis(10)).await; +} diff --git a/crates/pu-engine/tests/browser_launch.rs b/crates/pu-engine/tests/browser_launch.rs new file mode 100644 index 00000000..ab224f89 --- /dev/null +++ b/crates/pu-engine/tests/browser_launch.rs @@ -0,0 +1,71 @@ +//! Browser startup failures, with a stand-in browser (its own test binary: +//! it sets `PU_BROWSER` for the whole process). +#![cfg(unix)] + +use std::os::unix::fs::PermissionsExt; +use std::time::Duration; + +use pu_core::protocol::{BrowserOp, Response}; +use pu_engine::browser::{BrowserManager, Caller}; +use tempfile::TempDir; + +fn alive(pid: i32) -> bool { + // SAFETY: signal 0 only checks that the process exists. + unsafe { libc::kill(pid, 0) == 0 } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn given_a_browser_that_never_answers_should_fail_the_open_and_reap_it_first() { + let tmp = TempDir::new().unwrap(); + // Closes its DevTools pipe at once but keeps running, like a browser that + // started and then hung: the open must fail fast, and the process must be + // gone (reaped, not left exiting) before the open returns, since a retry + // reuses its profile. + let pid_file = tmp.path().join("pid"); + let fake = tmp.path().join("fake-browser"); + std::fs::write( + &fake, + format!( + "#!/bin/sh\necho $$ > '{}'\nexec 3<&- 4>&-\nexec sleep 60\n", + pid_file.display() + ), + ) + .unwrap(); + std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap(); + // SAFETY: the only test in this binary; nothing reads the environment concurrently. + unsafe { std::env::set_var("PU_BROWSER", &fake) }; + + let manager = BrowserManager::new(Some(tmp.path().join("browser"))); + for round in 0..2 { + let open = tokio::time::timeout( + Duration::from_secs(20), + manager.handle( + "/p", + BrowserOp::Open { + url: Some("about:blank".into()), + }, + Caller::Agent, + ), + ) + .await + .expect("a browser that closed its pipe must fail the open fast"); + assert!( + matches!(&open, Response::Error { code, .. } if code == "BROWSER_LAUNCH_FAILED"), + "round {round}: {open:?}" + ); + let pid: i32 = std::fs::read_to_string(&pid_file) + .unwrap() + .trim() + .parse() + .unwrap(); + assert!( + !alive(pid), + "round {round}: the failed browser {pid} still exists" + ); + std::fs::remove_file(&pid_file).unwrap(); + } + assert!(matches!( + manager.handle("/p", BrowserOp::List, Caller::Agent).await, + Response::BrowserTabs { tabs } if tabs.is_empty() + )); +} From 1816415aac031fa032235991c336f92f7cdcb146 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 20:33:23 +0000 Subject: [PATCH 21/30] fix(browser): drop refs when another document's URL is published; test an unconfirmed exit and control-then-disconnect deterministically; new pane epoch when a stream goes live Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ2eMMzt56iHuDqpo7z --- .../ui/src/state/browserSession.ts | 10 +- .../views/browser/BrowserPaneView.test.tsx | 42 +++++++ .../ui/src/views/browser/BrowserPaneView.tsx | 25 +++- crates/pu-engine/src/browser/mod.rs | 36 ++++-- crates/pu-engine/src/browser/tab.rs | 31 ++++- crates/pu-engine/tests/browser.rs | 56 +++++++-- crates/pu-engine/tests/browser_launch.rs | 111 +++++++++++++----- 7 files changed, 253 insertions(+), 58 deletions(-) diff --git a/apps/purepoint-windows/ui/src/state/browserSession.ts b/apps/purepoint-windows/ui/src/state/browserSession.ts index 134a6c7c..235376ca 100644 --- a/apps/purepoint-windows/ui/src/state/browserSession.ts +++ b/apps/purepoint-windows/ui/src/state/browserSession.ts @@ -49,6 +49,8 @@ export interface BrowserSessionFields { readonly frameSize: Size; /** A transient problem to show over the page. */ readonly notice: string | null; + /** The attach stream now live (counted from 1): its frames number afresh. */ + readonly stream: number; } export interface BrowserSessionOptions { @@ -79,8 +81,6 @@ export class BrowserSession { private stream: BrowserStream | null = null; /** Bumped per start and stop, so a superseded stream's late events are dropped. */ private generation = 0; - /** Counts attach streams that went live; each frame carries the one it came on. */ - private attachedStreams = 0; private started = false; private viewport: Viewport | null = null; private pendingCopy = false; @@ -99,6 +99,7 @@ export class BrowserSession { frame: null, frameSize: DEFAULT_FRAME_SIZE, notice: null, + stream: 0, })); } @@ -229,13 +230,12 @@ export class BrowserSession { this.adopt(event.tab); return; case 'live': - this.attachedStreams += 1; - this.store.setState({ phase: { kind: 'live' } }); + this.store.setState({ phase: { kind: 'live' }, stream: this.state.stream + 1 }); return; case 'frame': this.store.setState({ frame: { - stream: this.attachedStreams, + stream: this.state.stream, seq: event.seq, data: event.data, width: event.width, diff --git a/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.test.tsx b/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.test.tsx index 6ff7ecc4..a71be09c 100644 --- a/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.test.tsx +++ b/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.test.tsx @@ -265,4 +265,46 @@ describe('BrowserPaneView', () => { getContext.mockRestore(); } }); + + it("never draws or acks an old stream's frame once a new stream is live", async () => { + const decodes: (() => void)[] = []; + const original = Object.getOwnPropertyDescriptor(HTMLImageElement.prototype, 'decode'); + Object.defineProperty(HTMLImageElement.prototype, 'decode', { + configurable: true, + value: () => new Promise((resolve) => decodes.push(resolve)), + }); + const drawImage = vi.fn(); + const getContext = vi + .spyOn(HTMLCanvasElement.prototype, 'getContext') + .mockImplementation(() => ({ drawImage, clearRect: vi.fn() }) as never); + try { + const { send, sent } = setup(); + const acks = () => sent.filter((op) => op.action === 'frame_ack').map((op) => op.seq); + await send({ type: 'tab', tab: tab() }); + await send({ type: 'live' }); + await send({ type: 'frame', seq: 5, data: 'AAAA', width: 1280, height: 800 }); + // The lost tab is replaced and the new stream is live, before its first frame. + await send({ type: 'tab', tab: tab({ tab_id: 't2' }) }); + await send({ type: 'live' }); + await act(async () => { + decodes[0]?.(); // t1's frame 5 finishes in that gap + await Promise.resolve(); + await Promise.resolve(); + }); + expect(drawImage).not.toHaveBeenCalled(); + expect(acks()).toEqual([]); + await send({ type: 'frame', seq: 1, data: 'BBBB', width: 1280, height: 800 }); + await act(async () => { + decodes[1]?.(); + await Promise.resolve(); + await Promise.resolve(); + }); + expect(drawImage).toHaveBeenCalledTimes(1); + expect(acks()).toEqual([1]); + } finally { + if (original) Object.defineProperty(HTMLImageElement.prototype, 'decode', original); + else delete (HTMLImageElement.prototype as { decode?: unknown }).decode; + getContext.mockRestore(); + } + }); }); diff --git a/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.tsx b/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.tsx index 223eb88f..4e77c5df 100644 --- a/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.tsx +++ b/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.tsx @@ -99,6 +99,7 @@ export function BrowserPaneView({ const tab = useStore(session.store, (s) => s.tab); const frame = useStore(session.store, (s) => s.frame); const frameSize = useStore(session.store, (s) => s.frameSize); + const stream = useStore(session.store, (s) => s.stream); const notice = useStore(session.store, (s) => s.notice); useEffect(() => { @@ -231,6 +232,7 @@ export function BrowserPaneView({ { session.input(event); @@ -307,6 +309,8 @@ function BrowserMessage({ interface BrowserCanvasProps { ref: Ref; frame: BrowserFrame | null; + /** The attach stream now live; a new one drops the old stream's pending frames. */ + stream: number; /** The CSS viewport the frame shows. */ cssSize: Size; onInput: (event: BrowserInputEvent) => void; @@ -329,6 +333,7 @@ async function decodeFrame(data: string): Promise { function BrowserCanvas({ ref, frame, + stream, cssSize, onInput, onResize, @@ -383,6 +388,17 @@ function BrowserCanvas({ }; }, []); + // A new attach stream (a reconnect, or a lost tab replaced without a close) starts + // a new epoch as soon as it is live, before its first frame: a frame of the old + // stream still decoding then neither draws nor acks on the new one. Declared + // before the draw effect, so it runs first when both change together. + useEffect(() => { + if (stream === frameStream.current) return; + frameStream.current = stream; + epoch.current += 1; + drawnSeq.current = -1; + }, [stream]); + // Draw each frame, then ack it: the daemon sends at most two ahead of the screen. // A newer frame never cancels an older one's decode (when decoding is slower // than frames arrive, that would starve the canvas); `seq` keeps an older frame @@ -400,10 +416,11 @@ function BrowserCanvas({ } return; } - const { stream, seq, data } = frame; - if (stream !== frameStream.current) { - // The old picture stays until the new stream's first frame replaces it. - frameStream.current = stream; + const { seq, data } = frame; + if (frame.stream !== frameStream.current) { + // A frame from a stream the canvas has not seen go live yet (the stream effect + // normally runs first). The old picture stays until this frame replaces it. + frameStream.current = frame.stream; epoch.current += 1; drawnSeq.current = -1; } diff --git a/crates/pu-engine/src/browser/mod.rs b/crates/pu-engine/src/browser/mod.rs index 2ae90aee..856c95d0 100644 --- a/crates/pu-engine/src/browser/mod.rs +++ b/crates/pu-engine/src/browser/mod.rs @@ -41,6 +41,8 @@ const MAX_WAIT: Duration = Duration::from_secs(120); /// A browser nobody has used or watched for this long is stopped; its panes reopen /// their last page when shown again, and agents open a new tab. const IDLE_STOP: Duration = Duration::from_secs(30 * 60); +/// How long a stopped browser may take to exit before its profile is reused. +const EXIT_WAIT: Duration = Duration::from_secs(5); const IDLE_CHECK: Duration = Duration::from_secs(60); /// Who sent an op. Ops from a viewer's attach stream are the person at the pane. @@ -124,9 +126,9 @@ impl Instance { /// Ends the browser's process group and waits (up to 5 s) for it to exit. /// Returns whether the exit is confirmed; if not, this instance keeps owning /// the process (and its profile), so the caller must not start another on it. - async fn stop_and_wait(&self) -> bool { + async fn stop_and_wait(&self, wait: Duration) -> bool { let child = self._child.lock().unwrap_or_else(|e| e.into_inner()).take(); - match stop_child(self.pid, child).await { + match stop_child(self.pid, child, wait).await { Ok(()) => true, Err(child) => { *self._child.lock().unwrap_or_else(|e| e.into_inner()) = Some(child); @@ -394,11 +396,13 @@ async fn refresh_history(cdp: &Cdp, tab: &Tab) { tab.set_history(index > 0, index + 1 < count); } -/// Ends a browser's process group and waits (up to 5 s) for it to exit. -/// Hands the child back if its exit is not confirmed. +/// Ends a browser's process group and waits (up to `wait`) for it to exit. +/// Hands the child back if its exit is not confirmed; a zero `wait` never +/// confirms one (tests use it to stand in for a browser that will not exit). async fn stop_child( pid: Option, child: Option, + wait: Duration, ) -> std::result::Result<(), tokio::process::Child> { #[cfg(unix)] if let Some(pid) = pid { @@ -410,7 +414,10 @@ async fn stop_child( return Ok(()); // already reaped }; let _ = child.start_kill(); - match tokio::time::timeout(Duration::from_secs(5), child.wait()).await { + if wait.is_zero() { + return Err(child); + } + match tokio::time::timeout(wait, child.wait()).await { Ok(Ok(_)) => Ok(()), _ => Err(child), } @@ -464,6 +471,8 @@ pub struct BrowserManager { lingering: Mutex>, base_dir: Option, idle_stop: Duration, + /// How long a stopped browser may take to exit before it counts as still running. + exit_wait: Duration, } impl Default for BrowserManager { @@ -485,6 +494,7 @@ impl BrowserManager { lingering: Mutex::new(HashMap::new()), base_dir, idle_stop: IDLE_STOP, + exit_wait: EXIT_WAIT, } } @@ -494,6 +504,14 @@ impl BrowserManager { self } + /// How long a stopped browser may take to exit (5 s). A zero wait never + /// confirms an exit: tests use it for a browser that will not go away. + #[doc(hidden)] + pub fn with_exit_wait(mut self, wait: Duration) -> Self { + self.exit_wait = wait; + self + } + /// Stops every project's browser. pub async fn shutdown(&self) { self.instances.lock().await.clear(); @@ -545,7 +563,7 @@ impl BrowserManager { } }; if let Some(dead) = dead - && !dead.stop_and_wait().await + && !dead.stop_and_wait(self.exit_wait).await { // Its profile is reused next: never while the old process may live. self.instances.lock().await.insert(root.to_string(), dead); @@ -594,7 +612,7 @@ impl BrowserManager { } }; if let Some(retired) = retired - && !retired.stop_and_wait().await + && !retired.stop_and_wait(self.exit_wait).await { // Not confirmed gone: keep owning it, so the next open waits for it. self.instances @@ -639,7 +657,7 @@ impl BrowserManager { } // A failed earlier startup's browser must be gone before its profile is reused. let lingering = self.lingering.lock().await.remove(root); - if let Err(child) = stop_child(None, lingering).await { + if let Err(child) = stop_child(None, lingering, self.exit_wait).await { self.lingering.lock().await.insert(root.to_string(), child); return Err(BrowserError::new( "BROWSER_LAUNCH_FAILED", @@ -668,7 +686,7 @@ impl BrowserManager { Ok(initial) => initial, Err(error) => { // Own the process until it has exited: a retry reuses its profile. - if let Err(child) = stop_child(pid, child.take()).await { + if let Err(child) = stop_child(pid, child.take(), self.exit_wait).await { self.lingering.lock().await.insert(root.to_string(), child); } return Err(error); diff --git a/crates/pu-engine/src/browser/tab.rs b/crates/pu-engine/src/browser/tab.rs index 140f7bfd..557da7d5 100644 --- a/crates/pu-engine/src/browser/tab.rs +++ b/crates/pu-engine/src/browser/tab.rs @@ -37,6 +37,11 @@ pub struct Viewport { pub scale: f64, } +/// A URL without its `#fragment`: a fragment change stays in the same document. +fn without_fragment(url: &str) -> &str { + url.split_once('#').map_or(url, |(base, _)| base) +} + /// The document and URL a snapshot started on. #[derive(Debug, Clone)] pub struct DocumentMark { @@ -148,8 +153,17 @@ impl Tab { /// Publishes the page's URL and title. Held under the refs lock, so a snapshot /// commit never sees the URL change halfway (see `store_refs_for`). + /// + /// A URL for another document (a `navigate`'s own report or `targetInfoChanged`, + /// which can arrive before `frameNavigated` reaches the event pump) also drops + /// the refs, so a click can never send the old page's node ids to the new one. pub fn set_page(&self, url: Option<&str>, title: Option<&str>) { - let _refs = self.refs.lock().unwrap_or_else(|e| e.into_inner()); + let mut refs = self.refs.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(url) = url + && without_fragment(url) != without_fragment(&self.info.borrow().url) + { + refs.clear(); + } self.publish_page(url, title); } @@ -622,6 +636,21 @@ mod tests { assert_eq!(tab.resolve_ref("e1"), None); } + #[test] + fn given_another_documents_url_before_frame_navigated_should_drop_the_old_refs() { + let tab = tab(); + tab.set_page(Some("http://a/"), None); + let mark = tab.document_mark(); + tab.store_refs_for(&mark, HashMap::from([("e1".to_string(), 7)])) + .expect("same page"); + // A fragment or a title stays on the same document: its refs still resolve. + tab.set_page(Some("http://a/#section"), Some("A")); + assert_eq!(tab.resolve_ref("e1"), Some(7)); + // `navigate` publishes page B while the pump has not seen `frameNavigated`. + tab.set_page(Some("http://b/"), None); + assert_eq!(tab.resolve_ref("e1"), None); + } + #[test] fn given_url_reports_racing_snapshots_should_never_pair_refs_with_another_url() { // Page A's outline is committed only while the tab still reports A. diff --git a/crates/pu-engine/tests/browser.rs b/crates/pu-engine/tests/browser.rs index d44c8032..f565b0c0 100644 --- a/crates/pu-engine/tests/browser.rs +++ b/crates/pu-engine/tests/browser.rs @@ -669,8 +669,17 @@ async fn given_take_control_then_an_immediate_disconnect_should_hand_the_tab_bac Response::BrowserTab { tab } => tab, other => panic!("open: {other:?}"), }; - // A pane takes control and its connection drops right after: the Control - // must never land after the viewer is gone and lock agents out. + // The daemon's own handle on the tab: whether a viewer is still attached. + let (_, handle) = engine + .browsers() + .attach(&root, Some(&tab.tab_id)) + .await + .expect("the tab is open"); + + // A pane takes control and its connection ends right after. Even rounds close + // only the pane's sending side, so the daemon's Control reply can still be read + // (it proves the Control ran); odd rounds drop the whole connection at once. + // Either way the Control must never land after the viewer is gone. for round in 0..10 { let mut viewer = Client::connect(&sock).await; assert!(matches!( @@ -691,19 +700,42 @@ async fn given_take_control_then_an_immediate_disconnect_should_hand_the_tab_bac }, )) .await; - drop(viewer); - let back = tokio::time::timeout(Duration::from_secs(10), async { - while driver_of(&mut agent, &root).await != BrowserDriver::Agent { - tokio::time::sleep(Duration::from_millis(20)).await; + if round % 2 == 0 { + viewer.writer.shutdown().await.unwrap(); + // Read until the daemon closes the stream: the Control's reply comes + // first, since the stream reads the Control before the end of input. + let mut took = false; + let mut line = String::new(); + loop { + line.clear(); + let n = tokio::time::timeout( + Duration::from_secs(10), + viewer.reader.read_line(&mut line), + ) + .await + .expect("the daemon ends the stream") + .unwrap(); + if n == 0 { + break; + } + if let Ok(Response::BrowserTab { tab }) = serde_json::from_str(line.trim()) { + took = tab.driver == BrowserDriver::Human; + } + } + assert!(took, "round {round}: the Control was never processed"); + } else { + drop(viewer); + } + // The viewer's teardown has run... + let detached = tokio::time::timeout(Duration::from_secs(10), async { + while handle.has_viewers() { + tokio::time::sleep(Duration::from_millis(10)).await; } }) .await; - assert!( - back.is_ok(), - "round {round}: the tab stayed with the person" - ); - // And it stays with agents: no late Control takes it again. - tokio::time::sleep(Duration::from_millis(200)).await; + assert!(detached.is_ok(), "round {round}: the viewer never detached"); + // ...and, with the Control already applied before it, left the tab to agents. + assert_eq!(handle.driver(), BrowserDriver::Agent, "round {round}"); assert_eq!( driver_of(&mut agent, &root).await, BrowserDriver::Agent, diff --git a/crates/pu-engine/tests/browser_launch.rs b/crates/pu-engine/tests/browser_launch.rs index ab224f89..779f4f99 100644 --- a/crates/pu-engine/tests/browser_launch.rs +++ b/crates/pu-engine/tests/browser_launch.rs @@ -1,5 +1,5 @@ //! Browser startup failures, with a stand-in browser (its own test binary: -//! it sets `PU_BROWSER` for the whole process). +//! it sets `PU_BROWSER` for the whole process, so its tests take turns). #![cfg(unix)] use std::os::unix::fs::PermissionsExt; @@ -9,20 +9,14 @@ use pu_core::protocol::{BrowserOp, Response}; use pu_engine::browser::{BrowserManager, Caller}; use tempfile::TempDir; -fn alive(pid: i32) -> bool { - // SAFETY: signal 0 only checks that the process exists. - unsafe { libc::kill(pid, 0) == 0 } -} +/// `PU_BROWSER` is process-wide: one test at a time points it at its stand-in. +static BROWSER_ENV: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn given_a_browser_that_never_answers_should_fail_the_open_and_reap_it_first() { - let tmp = TempDir::new().unwrap(); - // Closes its DevTools pipe at once but keeps running, like a browser that - // started and then hung: the open must fail fast, and the process must be - // gone (reaped, not left exiting) before the open returns, since a retry - // reuses its profile. - let pid_file = tmp.path().join("pid"); - let fake = tmp.path().join("fake-browser"); +/// A stand-in browser that records its pid, then closes its DevTools pipe but keeps +/// running, like a browser that started and then hung. +fn hung_browser(dir: &std::path::Path) -> std::path::PathBuf { + let pid_file = dir.join("pid"); + let fake = dir.join("fake-browser"); std::fs::write( &fake, format!( @@ -32,23 +26,41 @@ async fn given_a_browser_that_never_answers_should_fail_the_open_and_reap_it_fir ) .unwrap(); std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap(); - // SAFETY: the only test in this binary; nothing reads the environment concurrently. + // SAFETY: tests here hold BROWSER_ENV; nothing else reads the environment concurrently. unsafe { std::env::set_var("PU_BROWSER", &fake) }; + pid_file +} + +async fn open(manager: &BrowserManager) -> Response { + tokio::time::timeout( + Duration::from_secs(20), + manager.handle( + "/p", + BrowserOp::Open { + url: Some("about:blank".into()), + }, + Caller::Agent, + ), + ) + .await + .expect("a browser that closed its pipe must fail the open fast") +} + +fn alive(pid: i32) -> bool { + // SAFETY: signal 0 only checks that the process exists. + unsafe { libc::kill(pid, 0) == 0 } +} +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn given_a_browser_that_never_answers_should_fail_the_open_and_reap_it_first() { + let _env = BROWSER_ENV.lock().await; + let tmp = TempDir::new().unwrap(); + // The open must fail fast, and the process must be gone (reaped, not left + // exiting) before the open returns, since a retry reuses its profile. + let pid_file = hung_browser(tmp.path()); let manager = BrowserManager::new(Some(tmp.path().join("browser"))); for round in 0..2 { - let open = tokio::time::timeout( - Duration::from_secs(20), - manager.handle( - "/p", - BrowserOp::Open { - url: Some("about:blank".into()), - }, - Caller::Agent, - ), - ) - .await - .expect("a browser that closed its pipe must fail the open fast"); + let open = open(&manager).await; assert!( matches!(&open, Response::Error { code, .. } if code == "BROWSER_LAUNCH_FAILED"), "round {round}: {open:?}" @@ -69,3 +81,48 @@ async fn given_a_browser_that_never_answers_should_fail_the_open_and_reap_it_fir Response::BrowserTabs { tabs } if tabs.is_empty() )); } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn given_a_failed_browser_whose_exit_is_not_confirmed_should_not_relaunch_on_its_profile() { + let _env = BROWSER_ENV.lock().await; + let tmp = TempDir::new().unwrap(); + let pid_file = hung_browser(tmp.path()); + let base = tmp.path().join("browser"); + // A zero exit wait never confirms an exit: a browser that will not go away. + let manager = BrowserManager::new(Some(base.clone())).with_exit_wait(Duration::ZERO); + + let first = open(&manager).await; + assert!( + matches!(&first, Response::Error { code, .. } if code == "BROWSER_LAUNCH_FAILED"), + "{first:?}" + ); + let pid: i32 = std::fs::read_to_string(&pid_file) + .unwrap() + .trim() + .parse() + .unwrap(); + // Still owned (not reaped): the daemon keeps the child until its exit is confirmed. + assert!(alive(pid), "the unconfirmed browser {pid} was let go"); + std::fs::remove_file(&pid_file).unwrap(); + + // The profile's locks belong to that process: a retry must neither remove them + // nor start a second browser on the profile. + let profile = base + .join("profiles") + .join(pu_engine::browser::launch::profile_key("/p")); + let lock = profile.join("SingletonLock"); + std::fs::write(&lock, "held").unwrap(); + let retry = open(&manager).await; + assert!( + matches!(&retry, Response::Error { code, message } if code == "BROWSER_LAUNCH_FAILED" && message.contains("has not exited yet")), + "{retry:?}" + ); + assert!( + lock.exists(), + "the retry removed the old browser's profile lock" + ); + assert!( + !pid_file.exists(), + "the retry started another browser on the profile" + ); +} From d53b9527fbbfb1c61c28388cca0108df8f69731e Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 20:58:09 +0000 Subject: [PATCH 22/30] fix(browser): address review findings on the devtools pipe, launch, page actions, resize and stream lifetimes - cdp: never send a command whose caller timed out; bound the queue; a failed write closes the connection; refuse an oversized message before buffering it - launch: finish fallible pipe setup before spawning the browser - close a created target whose attach fails - clicks and targeted typing refuse once the page has moved on; typing requires the target to have actually taken focus - serialize each tab's resizes; only the latest navigation publishes its URL - snapshot: walk the tree iteratively with a work limit - a viewer's resize worker starts no work after its stream ends - Mac/iPad: a stopped session never closes or updates a replacement's stream - Windows: bound stream writes; drop non-resize input sent while no stream was live - changelog: the browser runs on macOS and Linux daemons Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ2eMMzt56iHuDqpo7z --- CHANGELOG.md | 2 +- .../State/BrowserSession.swift | 19 +- .../src-tauri/src/browser/session.rs | 53 ++- .../src-tauri/src/browser/session_tests.rs | 102 ++++++ crates/pu-engine/src/browser/cdp.rs | 311 ++++++++++++++---- crates/pu-engine/src/browser/launch.rs | 11 +- crates/pu-engine/src/browser/mod.rs | 70 +++- crates/pu-engine/src/browser/snapshot.rs | 77 ++++- crates/pu-engine/src/browser/tab.rs | 93 +++++- crates/pu-engine/src/ipc_server/streams.rs | 20 +- crates/pu-engine/tests/browser.rs | 78 +++++ 11 files changed, 728 insertions(+), 108 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dbbb77df..73c982fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ All notable changes to PurePoint are documented here. Format follows [Keep a Cha ## [Unreleased] ### Added -- A browser for agents and for you. Each project gets a headless Chrome (or Chromium, Edge or Brave) on the machine where its agents run. Agents drive it with `pu browser` (`open`, `snapshot` with `[ref=eN]` handles, `click`, `type`, `press`, `scroll`, `screenshot`, `console`, `eval`, `wait`), and you watch and use the same tab live in a new browser pane: choose Open Browser in an empty tab, or have an agent run `pu browser open --show`. Take Control stops agents' page actions until you hand the tab back. Because the browser runs on the project's machine, `localhost` means the same thing to agents and to you, and panes work for remote machines. A remote agent's `localhost` links now open in a browser pane instead of your own browser. Logins persist per project in `~/.pu/browser/profiles` on that machine. See [Browser](docs/product/browser.md). +- A browser for agents and for you. Each project gets a headless Chrome (or Chromium, Edge or Brave) on the machine where its agents run. Agents drive it with `pu browser` (`open`, `snapshot` with `[ref=eN]` handles, `click`, `type`, `press`, `scroll`, `screenshot`, `console`, `eval`, `wait`), and you watch and use the same tab live in a new browser pane: choose Open Browser in an empty tab, or have an agent run `pu browser open --show`. Take Control stops agents' page actions until you hand the tab back. Because the browser runs on the project's machine, `localhost` means the same thing to agents and to you, and panes work for remote machines. A remote agent's `localhost` links now open in a browser pane instead of your own browser. Logins persist per project in `~/.pu/browser/profiles` on that machine. The browser runs on a macOS or Linux daemon; a project on a Windows daemon cannot start one yet, though the Windows app can open browser panes for projects on a Mac or Linux machine. See [Browser](docs/product/browser.md). - PurePoint runs natively on Windows 11 (x64 and arm64), with no WSL. `pu-engine` and `pu` are native Windows programs: the daemon listens on a private named pipe, agents run in ConPTY terminals and are stopped as a whole process tree, `pu daemon install` starts the daemon at sign-in through your user's Run key, and `pu phone` runs Point Guard for phone pairing over Tailscale. See [PurePoint on Windows](docs/guide/windows.md). - A Windows desktop app (`PurePoint__-setup.exe`, a per-user installer that needs no administrator rights) with the macOS app's features. On first launch it installs `pu` and `pu-engine` to `%USERPROFILE%\.pu\bin`, adds that folder to your user `PATH`, installs the Claude Code plugin and supervises the daemon. The arm64 installer has not been tested on Arm hardware yet. - `scripts/install.ps1` installs the Windows CLI from PowerShell (`irm https://raw.githubusercontent.com/2witstudios/PurePoint/main/scripts/install.ps1 | iex`). Like `install.sh`, it verifies the release's minisign signature or its GitHub attestation before installing, and stops if neither can be checked unless `PU_INSTALL_SKIP_VERIFY=1` is set. diff --git a/apps/purepoint-macos/purepoint-macos/State/BrowserSession.swift b/apps/purepoint-macos/purepoint-macos/State/BrowserSession.swift index 13f54a53..9040f118 100644 --- a/apps/purepoint-macos/purepoint-macos/State/BrowserSession.swift +++ b/apps/purepoint-macos/purepoint-macos/State/BrowserSession.swift @@ -109,7 +109,10 @@ final class BrowserSession { streamTask?.cancel() streamTask = nil // The stream this session attached; a reopen's new stream is never closed by it. - let stream = attachedStream + // With none attached yet (still connecting) there is nothing to close here: the + // cancelled attach closes its own stream, and `writer.close(nil)` would pick + // whichever stream is current by then, possibly a replacement's. + guard let stream = attachedStream else { return } attachedStream = nil Task { [writer] in await writer.close(stream) } } @@ -211,6 +214,8 @@ final class BrowserSession { private func attachOnce() async throws { if tabId == nil { let opened = try await client.send(.browser(projectRoot: projectRoot, op: .open(url: lastURL))) + // A session stopped (or reopened) while this waited must not adopt the reply. + try Task.checkCancellation() switch opened { case .browserTab(let info): adopt(info) @@ -221,12 +226,21 @@ final class BrowserSession { } } let (stream, reader) = try await client.connect() + // Stopped while connecting: `stop()` found no stream to close, so this one + // is closed here, before the writer could take it in place of a replacement's. + if Task.isCancelled { + stream.close() + throw CancellationError() + } await writer.use(stream) attachedStream = stream defer { Task { [writer] in await writer.close(stream) } } + // Stopped during the hop into the writer: the defer closes this stream. + try Task.checkCancellation() try await DaemonClient.write(.browserAttach(projectRoot: projectRoot, tabId: tabId), to: stream) let first = try await reader.readLine() + try Task.checkCancellation() switch DaemonClient.parse(first) { case .browserAttached(let info): adopt(info) @@ -249,6 +263,9 @@ final class BrowserSession { while !Task.isCancelled { let line = try await reader.readLine() + // A read that finished after this session stopped (or reopened) belongs to + // the old stream: it must not close, clear or update the pane now. + try Task.checkCancellation() switch DaemonClient.parse(line) { case .browserFrame(let payload): let decoded = await Task.detached(priority: .userInitiated) { diff --git a/apps/purepoint-windows/src-tauri/src/browser/session.rs b/apps/purepoint-windows/src-tauri/src/browser/session.rs index 2597a40c..9cd9bc06 100644 --- a/apps/purepoint-windows/src-tauri/src/browser/session.rs +++ b/apps/purepoint-windows/src-tauri/src/browser/session.rs @@ -88,6 +88,9 @@ pub struct BrowserOptions { pub slow_delay: Duration, /// How long the daemon may take to answer an attach (tests shorten it). pub attach_timeout: Duration, + /// How long one write to the stream may take before the connection counts as + /// stalled and is replaced (tests shorten it). + pub write_timeout: Duration, } impl BrowserOptions { @@ -103,10 +106,14 @@ impl BrowserOptions { fast_delay: Duration::from_millis(300), slow_delay: Duration::from_secs(2), attach_timeout: crate::daemon::client::REQUEST_TIMEOUT, + write_timeout: WRITE_TIMEOUT, } } } +/// A write the relay has not taken in this long means the connection is stalled. +pub const WRITE_TIMEOUT: Duration = Duration::from_secs(20); + /// Swift's schedule: three quick retries, then every two seconds. pub const FAST_RETRIES: u32 = 3; @@ -160,6 +167,7 @@ impl BrowserSession { fast_delay: options.fast_delay, slow_delay: options.slow_delay, attach_timeout: options.attach_timeout, + write_timeout: options.write_timeout, viewport: None, sink, ops: rx, @@ -198,6 +206,7 @@ struct Worker { fast_delay: Duration, slow_delay: Duration, attach_timeout: Duration, + write_timeout: Duration, /// The last `resize` the pane sent: (width, height, scale). viewport: Option<(u32, u32, f64)>, sink: Arc, @@ -267,6 +276,34 @@ impl Worker { self.sink.event(BrowserEvent::Tab { tab }); } + /// Writes one request within `write_timeout`. A stalled relay (it stopped taking + /// bytes) ends the attempt: the connection is dropped and a new one made, since + /// the daemon may already hold part of the request. + async fn write( + &self, + writer: &mut crate::daemon::client::BoxWrite, + request: &Request, + ) -> Result<(), String> { + match tokio::time::timeout(self.write_timeout, write_request(writer, request)).await { + Ok(Ok(())) => Ok(()), + Ok(Err(error)) => Err(error.to_string()), + Err(_) => Err("The connection stopped taking data".into()), + } + } + + /// Ops the pane sent while no stream was live: keep the latest resize (it is + /// replayed), drop the rest, since input aimed at the old stream must not reach a + /// new one (possibly a replacement tab). False once the session is stopped. + fn drop_stale_ops(&mut self) -> bool { + loop { + match self.ops.try_recv() { + Ok(op) => self.remember(&op), + Err(mpsc::error::TryRecvError::Empty) => return true, + Err(mpsc::error::TryRecvError::Disconnected) => return false, + } + } + } + fn request(&self, op: BrowserOp) -> Request { Request::Browser { project_root: self.project_root.clone(), @@ -300,8 +337,8 @@ impl Worker { project_root: self.project_root.clone(), tab_id: self.tab_id.clone(), }; - if let Err(error) = write_request(&mut writer, &attach).await { - return retry(error.to_string()); + if let Err(error) = self.write(&mut writer, &attach).await { + return retry(error); } // A dedicated reader, so a line half read is never lost to `select!`. @@ -336,6 +373,10 @@ impl Worker { Some(Err(error)) => return retry(error.to_string()), None => return retry(DaemonError::Eof.to_string()), } + // Live from here: what the pane sent before belongs to no stream. + if !self.drop_stale_ops() { + return End::Stopped; + } self.sink.event(BrowserEvent::Live); if let Some((width, height, scale)) = self.viewport { let resize = self.request(BrowserOp::Resize { @@ -344,9 +385,9 @@ impl Worker { height, scale, }); - if let Err(error) = write_request(&mut writer, &resize).await { + if let Err(message) = self.write(&mut writer, &resize).await { return End::Retry { - message: error.to_string(), + message, live: true, }; } @@ -359,8 +400,8 @@ impl Worker { let Some(op) = op else { return End::Stopped }; self.remember(&op); let request = self.request(op); - if let Err(error) = write_request(&mut writer, &request).await { - return End::Retry { message: error.to_string(), live: true }; + if let Err(message) = self.write(&mut writer, &request).await { + return End::Retry { message, live: true }; } } line = lines.recv() => { diff --git a/apps/purepoint-windows/src-tauri/src/browser/session_tests.rs b/apps/purepoint-windows/src-tauri/src/browser/session_tests.rs index 7bf40781..89e55954 100644 --- a/apps/purepoint-windows/src-tauri/src/browser/session_tests.rs +++ b/apps/purepoint-windows/src-tauri/src/browser/session_tests.rs @@ -382,3 +382,105 @@ async fn given_a_daemon_that_never_answers_the_attach_should_retry() { ); drop(silent); } + +#[tokio::test] +async fn given_input_sent_before_the_attach_answers_should_drop_it_and_keep_the_resize() { + let mut daemon = FakeDaemon::start(); + let (sink, mut seen) = sink(); + let session = BrowserSession::start(daemon.client(), options(Some("t1"), None), sink); + let mut stream = daemon.accept().await; + let _ = stream.request().await; // the attach + // The pane clicks and resizes while the attach is still unanswered. + session.send(BrowserOp::Input { + tab_id: None, + event: pu_core::protocol::BrowserInputEvent::Text { + text: "stale".into(), + }, + }); + session.send(BrowserOp::Resize { + tab_id: None, + width: 640, + height: 480, + scale: 2.0, + }); + tokio::time::sleep(Duration::from_millis(50)).await; + stream + .send(&Response::BrowserAttached { + tab: tab("t1", "http://localhost/"), + }) + .await; + assert!(matches!(next(&mut seen).await, BrowserEvent::Tab { .. })); + assert_eq!(next(&mut seen).await, BrowserEvent::Live); + // Only the resize reaches the live stream; the text belonged to no stream. + assert_request( + stream.request().await, + serde_json::json!({"type": "browser", "project_root": "/p", "op": {"action": "resize", "tab_id": null, "width": 640, "height": 480, "scale": 2.0}}), + ); + session.send(BrowserOp::History { + tab_id: None, + direction: BrowserHistory::Reload, + }); + assert_request( + stream.request().await, + serde_json::json!({"type": "browser", "project_root": "/p", "op": {"action": "history", "tab_id": null, "direction": "reload"}}), + ); +} + +/// A connection whose writes never complete: a relay that stopped taking bytes. +struct StalledConnector; + +struct NeverWrites; + +impl tokio::io::AsyncWrite for NeverWrites { + fn poll_write( + self: std::pin::Pin<&mut Self>, + _cx: &mut std::task::Context<'_>, + _buf: &[u8], + ) -> std::task::Poll> { + std::task::Poll::Pending + } + fn poll_flush( + self: std::pin::Pin<&mut Self>, + _cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + std::task::Poll::Pending + } + fn poll_shutdown( + self: std::pin::Pin<&mut Self>, + _cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + std::task::Poll::Ready(Ok(())) + } +} + +impl crate::daemon::client::Connector for StalledConnector { + fn open(&self) -> crate::daemon::client::OpenFuture<'_> { + Box::pin(async { + let (_ours, theirs) = tokio::io::duplex(64); + Ok(( + Box::new(theirs) as crate::daemon::client::BoxRead, + Box::new(NeverWrites) as crate::daemon::client::BoxWrite, + )) + }) + } + fn describe(&self) -> String { + "a stalled relay".into() + } +} + +#[tokio::test] +async fn given_a_relay_that_stops_taking_bytes_should_give_up_the_write_and_retry() { + let (sink, mut seen) = sink(); + let mut options = options(Some("t1"), None); + options.write_timeout = Duration::from_millis(100); + let _session = + BrowserSession::start(DaemonClient::new(Arc::new(StalledConnector)), options, sink); + // The attach write never completes: the session drops the connection and retries + // instead of waiting forever. + match next(&mut seen).await { + BrowserEvent::Retrying { message, .. } => { + assert!(message.contains("stopped taking data"), "{message}") + } + other => panic!("expected a retry, got {other:?}"), + } +} diff --git a/crates/pu-engine/src/browser/cdp.rs b/crates/pu-engine/src/browser/cdp.rs index 6617f186..4dfc8f3d 100644 --- a/crates/pu-engine/src/browser/cdp.rs +++ b/crates/pu-engine/src/browser/cdp.rs @@ -12,7 +12,7 @@ use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::time::Duration; use serde_json::{Value, json}; -use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader}; +use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader}; use tokio::sync::{Mutex, broadcast, mpsc, oneshot}; /// No single command should take this long; a hung browser must not hang a client. @@ -20,9 +20,18 @@ const CALL_TIMEOUT: Duration = Duration::from_secs(30); /// Chromium can emit large bursts (screencast frames, console floods). A /// subscriber that falls this far behind loses events rather than stalling the reader. const EVENT_CAPACITY: usize = 4096; -/// Messages beyond this are dropped (a full-page screenshot of a huge page can -/// still be tens of MB, so the limit is generous). +/// A message longer than this ends the connection: Chromium is never expected to +/// send one (a full-page screenshot of a huge page can still be tens of MB), and it +/// is refused before it is buffered whole. +#[cfg(not(test))] const MAX_MESSAGE: usize = 256 * 1024 * 1024; +#[cfg(test)] +const MAX_MESSAGE: usize = 64 * 1024; +/// Commands waiting for the browser to read them. Past this the browser is not +/// reading: fire-and-forget input is dropped and calls fail at once. +const MAX_QUEUED: usize = 1024; +/// Fire-and-forget input older than this when the browser gets to it is stale. +const SEND_TTL: Duration = Duration::from_secs(5); #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum CdpError { @@ -44,13 +53,71 @@ pub struct CdpEvent { type Pending = Arc>)>>>; -pub struct Cdp { - outbox: mpsc::UnboundedSender>, +/// A command waiting to be written. One whose caller has given up (its deadline +/// passed) is never sent: the caller already reported a timeout. +struct Outgoing { + bytes: Vec, + deadline: tokio::time::Instant, +} + +/// What both pipe tasks share: either one failing ends the connection. +struct Shared { pending: Pending, + alive: AtomicBool, + closed: tokio::sync::Notify, + queued: std::sync::atomic::AtomicUsize, +} + +impl Shared { + /// Marks the browser gone, fails every waiting call and wakes `closed()` + /// waiters. Idempotent: the reader and the writer may both get here. + async fn shut_down(&self) { + self.alive.store(false, Ordering::SeqCst); + for (_, (_, tx)) in self.pending.lock().await.drain() { + let _ = tx.send(Err(CdpError::Closed)); + } + self.closed.notify_waiters(); + } +} + +pub struct Cdp { + outbox: mpsc::UnboundedSender, + shared: Arc, next_id: AtomicU64, events: broadcast::Sender>, - alive: Arc, - closed: Arc, +} + +/// How reading one message ended. +enum Read { + Message, + Eof, + TooLarge, +} + +/// Reads one NUL-terminated message into `buf` (without the NUL), refusing one +/// longer than `MAX_MESSAGE` before buffering past it. +async fn read_message( + reader: &mut R, + buf: &mut Vec, +) -> std::io::Result { + loop { + let available = reader.fill_buf().await?; + if available.is_empty() { + return Ok(Read::Eof); + } + let (chunk, end) = match available.iter().position(|b| *b == 0) { + Some(nul) => (nul, true), + None => (available.len(), false), + }; + if buf.len() + chunk > MAX_MESSAGE { + return Ok(Read::TooLarge); + } + buf.extend_from_slice(&available[..chunk]); + reader.consume(if end { chunk + 1 } else { chunk }); + if end { + return Ok(Read::Message); + } + } } impl Cdp { @@ -61,71 +128,80 @@ impl Cdp { R: AsyncRead + Unpin + Send + 'static, W: AsyncWrite + Unpin + Send + 'static, { - let (outbox, mut outbox_rx) = mpsc::unbounded_channel::>(); - let pending: Pending = Arc::default(); + let (outbox, mut outbox_rx) = mpsc::unbounded_channel::(); + let shared = Arc::new(Shared { + pending: Arc::default(), + alive: AtomicBool::new(true), + closed: tokio::sync::Notify::new(), + queued: std::sync::atomic::AtomicUsize::new(0), + }); let (events, _) = broadcast::channel(EVENT_CAPACITY); - let alive = Arc::new(AtomicBool::new(true)); - let closed = Arc::new(tokio::sync::Notify::new()); let mut writer = writer; + let writer_shared = shared.clone(); tokio::spawn(async move { while let Some(message) = outbox_rx.recv().await { - if writer.write_all(&message).await.is_err() || writer.flush().await.is_err() { + writer_shared.queued.fetch_sub(1, Ordering::SeqCst); + if tokio::time::Instant::now() >= message.deadline { + continue; // its caller already gave up: never act on it late + } + if writer.write_all(&message.bytes).await.is_err() || writer.flush().await.is_err() + { break; } } + // The browser stopped taking commands: nothing sent from now on will be + // answered, whatever its output pipe still does. + writer_shared.shut_down().await; }); - let reader_pending = pending.clone(); + let reader_shared = shared.clone(); let reader_events = events.clone(); - let reader_alive = alive.clone(); - let reader_closed = closed.clone(); tokio::spawn(async move { let mut reader = BufReader::new(reader); let mut buf = Vec::new(); loop { buf.clear(); - match reader.read_until(0, &mut buf).await { - Ok(0) | Err(_) => break, - Ok(_) => {} + match read_message(&mut reader, &mut buf).await { + Ok(Read::Message) => {} + Ok(Read::Eof) | Err(_) => break, + Ok(Read::TooLarge) => { + tracing::warn!( + limit = MAX_MESSAGE, + "devtools message too large; closing the browser connection" + ); + break; + } } - if buf.last() == Some(&0) { - buf.pop(); + if !buf.is_empty() { + match serde_json::from_slice::(&buf) { + Ok(message) => { + dispatch(message, &reader_shared.pending, &reader_events).await + } + Err(_) => tracing::debug!("unparseable devtools message"), + } } - if buf.is_empty() || buf.len() > MAX_MESSAGE { - continue; - } - let Ok(message) = serde_json::from_slice::(&buf) else { - tracing::debug!("unparseable devtools message"); - continue; - }; - dispatch(message, &reader_pending, &reader_events).await; - } - reader_alive.store(false, Ordering::SeqCst); - // Fail every waiting call: nothing will answer them now. - for (_, (_, tx)) in reader_pending.lock().await.drain() { - let _ = tx.send(Err(CdpError::Closed)); + // A large reply (a screenshot) must not pin its buffer for good. + buf.shrink_to(64 * 1024); } - reader_closed.notify_waiters(); + reader_shared.shut_down().await; }); Arc::new(Self { outbox, - pending, + shared, next_id: AtomicU64::new(1), events, - alive, - closed, }) } pub fn is_alive(&self) -> bool { - self.alive.load(Ordering::SeqCst) + self.shared.alive.load(Ordering::SeqCst) } - /// Resolves once the browser's output has closed. + /// Resolves once the browser's connection has ended. pub async fn closed(&self) { - let notified = self.closed.notified(); + let notified = self.shared.closed.notified(); if !self.is_alive() { return; } @@ -136,58 +212,91 @@ impl Cdp { self.events.subscribe() } + fn message(&self, session_id: Option<&str>, method: &str, params: Value) -> (u64, Vec) { + let id = self.next_id.fetch_add(1, Ordering::Relaxed); + let mut message = json!({ "id": id, "method": method, "params": params }); + if let Some(session_id) = session_id { + message["sessionId"] = Value::String(session_id.to_string()); + } + let mut bytes = serde_json::to_vec(&message).expect("a JSON value always serializes"); + bytes.push(0); + (id, bytes) + } + + /// Queues a message unless the browser has stopped reading; false if dropped. + fn enqueue(&self, bytes: Vec, deadline: tokio::time::Instant) -> bool { + if self.shared.queued.fetch_add(1, Ordering::SeqCst) >= MAX_QUEUED { + self.shared.queued.fetch_sub(1, Ordering::SeqCst); + return false; + } + if self.outbox.send(Outgoing { bytes, deadline }).is_err() { + self.shared.queued.fetch_sub(1, Ordering::SeqCst); + return false; + } + true + } + /// Sends a command and waits for its result. pub async fn call( &self, session_id: Option<&str>, method: &str, params: Value, + ) -> Result { + self.call_within(CALL_TIMEOUT, session_id, method, params) + .await + } + + /// `call` with its own deadline. A command still queued when the deadline + /// passes is never sent, so a timed-out action cannot happen later. + pub async fn call_within( + &self, + timeout: Duration, + session_id: Option<&str>, + method: &str, + params: Value, ) -> Result { if !self.is_alive() { return Err(CdpError::Closed); } - let id = self.next_id.fetch_add(1, Ordering::Relaxed); - let mut message = json!({ "id": id, "method": method, "params": params }); - if let Some(session_id) = session_id { - message["sessionId"] = Value::String(session_id.to_string()); - } - let mut bytes = serde_json::to_vec(&message).expect("a JSON value always serializes"); - bytes.push(0); - + let deadline = tokio::time::Instant::now() + timeout; + let (id, bytes) = self.message(session_id, method, params); let (tx, rx) = oneshot::channel(); { - // Checked under the lock the reader drains with: a call that registers + // Checked under the lock shutdown drains with: a call that registers // after the browser closed would otherwise wait out the full timeout. - let mut pending = self.pending.lock().await; + let mut pending = self.shared.pending.lock().await; if !self.is_alive() { return Err(CdpError::Closed); } pending.insert(id, (method.to_string(), tx)); } - if self.outbox.send(bytes).is_err() { - self.pending.lock().await.remove(&id); - return Err(CdpError::Closed); + if !self.enqueue(bytes, deadline) { + self.shared.pending.lock().await.remove(&id); + return Err(if self.is_alive() { + CdpError::Timeout(method.to_string()) + } else { + CdpError::Closed + }); } - match tokio::time::timeout(CALL_TIMEOUT, rx).await { + match tokio::time::timeout_at(deadline, rx).await { Ok(Ok(result)) => result, Ok(Err(_)) => Err(CdpError::Closed), Err(_) => { - self.pending.lock().await.remove(&id); + self.shared.pending.lock().await.remove(&id); Err(CdpError::Timeout(method.to_string())) } } } /// Sends a command without waiting for its result (acks, input bursts). + /// Dropped if the browser has stopped reading, or if it is still queued + /// `SEND_TTL` later: stale input must not land on whatever the page shows then. pub fn send(&self, session_id: Option<&str>, method: &str, params: Value) { - let id = self.next_id.fetch_add(1, Ordering::Relaxed); - let mut message = json!({ "id": id, "method": method, "params": params }); - if let Some(session_id) = session_id { - message["sessionId"] = Value::String(session_id.to_string()); + let (_, bytes) = self.message(session_id, method, params); + if !self.enqueue(bytes, tokio::time::Instant::now() + SEND_TTL) { + tracing::debug!(method, "browser is not reading; dropped a command"); } - let mut bytes = serde_json::to_vec(&message).expect("a JSON value always serializes"); - bytes.push(0); - let _ = self.outbox.send(bytes); } } @@ -336,4 +445,82 @@ mod tests { Err(CdpError::Closed) ); } + + #[tokio::test] + async fn given_the_browser_stops_taking_commands_should_close_and_fail_calls_at_once() { + let (client_out, browser_in) = duplex(4096); + let (_browser_out, client_in) = duplex(4096); + let cdp = Cdp::start(client_in, client_out); + // Its input pipe is gone while its output pipe stays open. + drop(browser_in); + let call = tokio::time::timeout( + Duration::from_secs(5), + cdp.call(None, "Browser.getVersion", json!({})), + ) + .await + .expect("fails fast, not after the call timeout"); + assert_eq!(call, Err(CdpError::Closed)); + tokio::time::timeout(Duration::from_secs(5), cdp.closed()) + .await + .expect("closed() wakes"); + assert!(!cdp.is_alive()); + } + + #[tokio::test] + async fn given_a_command_that_timed_out_in_the_queue_should_never_send_it() { + // A tiny pipe nobody reads yet: the first command fills it and the writer + // blocks, so the second waits in the queue past its deadline. + let (client_out, mut browser_in) = duplex(64); + let (_browser_out, client_in) = duplex(4096); + let cdp = Cdp::start(client_in, client_out); + let blocker = tokio::spawn({ + let cdp = cdp.clone(); + async move { + cdp.call_within( + Duration::from_secs(5), + None, + "Big.first", + json!({"pad": "x".repeat(500)}), + ) + .await + } + }); + tokio::time::sleep(Duration::from_millis(50)).await; + assert_eq!( + cdp.call_within(Duration::from_millis(50), None, "Late.click", json!({})) + .await, + Err(CdpError::Timeout("Late.click".into())) + ); + // The browser reads again: the first command arrives, the expired one never does. + let first = read_message(&mut browser_in).await; + assert_eq!(first["method"], "Big.first"); + cdp.send(None, "Later.ok", json!({})); + let next = read_message(&mut browser_in).await; + assert_eq!(next["method"], "Later.ok"); + blocker.abort(); + } + + #[tokio::test] + async fn given_a_message_over_the_limit_should_close_without_buffering_it_whole() { + let (client_out, _browser_in) = duplex(4096); + let (mut browser_out, client_in) = duplex(4096); + let cdp = Cdp::start(client_in, client_out); + let call = tokio::spawn({ + let cdp = cdp.clone(); + async move { cdp.call(None, "Page.captureScreenshot", json!({})).await } + }); + // More than MAX_MESSAGE bytes and no terminating NUL. + let chunk = vec![b'x'; 4096]; + for _ in 0..(MAX_MESSAGE / chunk.len() + 2) { + if browser_out.write_all(&chunk).await.is_err() { + break; + } + } + let result = tokio::time::timeout(Duration::from_secs(5), call) + .await + .expect("fails fast, not after the call timeout") + .unwrap(); + assert_eq!(result, Err(CdpError::Closed)); + assert!(!cdp.is_alive()); + } } diff --git a/crates/pu-engine/src/browser/launch.rs b/crates/pu-engine/src/browser/launch.rs index 386ff1eb..34915200 100644 --- a/crates/pu-engine/src/browser/launch.rs +++ b/crates/pu-engine/src/browser/launch.rs @@ -192,6 +192,12 @@ pub mod unix { let (from_browser_read, from_browser_write) = cloexec_pipe()?; let child_in = to_browser_read.as_raw_fd(); let child_out = from_browser_write.as_raw_fd(); + // Everything that can fail is done before the browser starts: once it runs, + // the caller must get its child back to stop it and wait for its exit. + set_nonblocking(&from_browser_read)?; + set_nonblocking(&to_browser_write)?; + let reader = pipe::Receiver::from_owned_fd(from_browser_read)?; + let writer = pipe::Sender::from_owned_fd(to_browser_write)?; let mut command = tokio::process::Command::new(executable); command @@ -231,11 +237,6 @@ pub mod unix { // The browser holds its ends now; closing ours lets EOF reach each side. drop(to_browser_read); drop(from_browser_write); - - set_nonblocking(&from_browser_read)?; - set_nonblocking(&to_browser_write)?; - let reader = pipe::Receiver::from_owned_fd(from_browser_read)?; - let writer = pipe::Sender::from_owned_fd(to_browser_write)?; Ok(Launched { child, reader, diff --git a/crates/pu-engine/src/browser/mod.rs b/crates/pu-engine/src/browser/mod.rs index 856c95d0..428ddb9b 100644 --- a/crates/pu-engine/src/browser/mod.rs +++ b/crates/pu-engine/src/browser/mod.rs @@ -222,7 +222,16 @@ impl Instance { BrowserError::new("BROWSER_ERROR", "Target.createTarget returned no target") })? .to_string(); - let tab = self.adopt(&target_id).await?; + // The new target is this call's until it is adopted: if attaching fails, close + // it, or it would stay open in the browser with no id anyone was given. + let tab = match self.adopt(&target_id).await { + Ok(tab) => tab, + Err(error) => { + self.cdp + .send(None, "Target.closeTarget", json!({ "targetId": target_id })); + return Err(error); + } + }; // Chromium's own startup tab is not one of ours. let initial: Vec = std::mem::take( &mut *self @@ -835,9 +844,11 @@ impl BrowserManager { }) } BrowserOp::Click { element, .. } => { - let backend = element_ref(&tab, &element)?; + let (backend, page) = element_ref(&tab, &element)?; let (x, y) = element_center(cdp, &tab, backend).await?; - click(cdp, &tab, x, y).await?; + // The coordinates belong to `page`: a click after a navigation would + // land on whatever the new page has there. + click(cdp, &tab, &page, x, y).await?; Ok(Response::Ok) } BrowserOp::Type { @@ -847,8 +858,9 @@ impl BrowserManager { .. } => { if let Some(element) = element { - let backend = element_ref(&tab, &element)?; + let (backend, page) = element_ref(&tab, &element)?; focus_and_select(cdp, &tab, backend).await?; + ensure_on(&tab, &page)?; } cdp.call(session, "Input.insertText", json!({ "text": text })) .await?; @@ -930,6 +942,9 @@ impl BrowserManager { 1.0 }, }; + // One resize at a time per tab, across all its viewers: check, apply + // and record as one step, so the record matches what Chromium uses. + let _resizing = tab.lock_resize().await; if viewport != tab.viewport() { // Recorded only once Chromium accepts it, so a failed resize is retried. apply_viewport(cdp, &tab, viewport).await?; @@ -1099,6 +1114,9 @@ pub fn resolve_against(current: &str, url: &str) -> String { async fn navigate(cdp: &Cdp, tab: &Tab, url: &str) -> Result<()> { let url = normalize_url(&resolve_against(&tab.info().url, url)); + // Only the latest navigation publishes its URL: an earlier one that finishes + // late must not overwrite what a newer one already reported. + let revision = tab.begin_navigation(); let mut events = cdp.subscribe(); let result = cdp .call( @@ -1117,7 +1135,7 @@ async fn navigate(cdp: &Cdp, tab: &Tab, url: &str) -> Result<()> { if result.get("loaderId").is_some() { wait_for_load(&mut events, tab, LOAD_TIMEOUT).await; } - tab.set_page(Some(&url), None); + tab.set_page_for(revision, Some(&url), None); refresh_history(cdp, tab).await; // `set_page` above may race the browser's own URL report; the browser wins. if let Ok(info) = cdp @@ -1129,7 +1147,8 @@ async fn navigate(cdp: &Cdp, tab: &Tab, url: &str) -> Result<()> { .await && let Some(info) = info.get("targetInfo") { - tab.set_page( + tab.set_page_for( + revision, info.get("url").and_then(Value::as_str), info.get("title").and_then(Value::as_str), ); @@ -1179,8 +1198,20 @@ async fn history(cdp: &Cdp, tab: &Tab, direction: BrowserHistory) -> Result<()> Ok(()) } -fn element_ref(tab: &Tab, element: &str) -> Result { - tab.resolve_ref(element).ok_or_else(|| { +/// Refuses to act once the tab has left the page an element was resolved on. +fn ensure_on(tab: &Tab, page: &tab::DocumentMark) -> Result<()> { + if tab.is_on(page) { + Ok(()) + } else { + Err(BrowserError::new( + "BROWSER_PAGE_CHANGED", + "the page navigated before the action ran; take a new snapshot", + )) + } +} + +fn element_ref(tab: &Tab, element: &str) -> Result<(i64, tab::DocumentMark)> { + tab.resolve_ref_on_page(element).ok_or_else(|| { BrowserError::new( "BROWSER_REF_NOT_FOUND", format!("no element {element} in the latest snapshot; take a new snapshot"), @@ -1223,9 +1254,14 @@ async fn element_center(cdp: &Cdp, tab: &Tab, backend: i64) -> Result<(f64, f64) Ok((x, y)) } -async fn click(cdp: &Cdp, tab: &Tab, x: f64, y: f64) -> Result<()> { +async fn click(cdp: &Cdp, tab: &Tab, page: &tab::DocumentMark, x: f64, y: f64) -> Result<()> { let session = Some(tab.session_id.as_str()); for (kind, buttons) in [("mouseMoved", 0), ("mousePressed", 1), ("mouseReleased", 0)] { + // Checked before every event: never press on a page the element is not on + // (a release after a press still goes, so no button is left held down). + if kind != "mouseReleased" { + ensure_on(tab, page)?; + } let button = if kind == "mouseMoved" { "none" } else { "left" }; cdp.call( session, @@ -1262,7 +1298,10 @@ async fn focus_and_select(cdp: &Cdp, tab: &Tab, backend: i64) -> Result<()> { "Runtime.callFunctionOn", json!({ "objectId": object_id, - "functionDeclaration": "function() { this.scrollIntoView({block: 'center', inline: 'center'}); this.focus(); if (typeof this.select === 'function') { this.select(); } else if (this.isContentEditable) { const r = document.createRange(); r.selectNodeContents(this); const s = getSelection(); s.removeAllRanges(); s.addRange(r); } }", + // Reports whether focus really moved to the element, in its own document or + // shadow root: `focus()` on a disabled field neither throws nor moves focus. + "functionDeclaration": "function() { this.scrollIntoView({block: 'center', inline: 'center'}); this.focus(); const root = this.getRootNode(); const active = root && root.activeElement; if (active !== this && !(this.isContentEditable && active && active.contains(this))) { return false; } if (typeof this.select === 'function') { this.select(); } else if (this.isContentEditable) { const r = document.createRange(); r.selectNodeContents(this); const s = getSelection(); s.removeAllRanges(); s.addRange(r); } return true; }", + "returnByValue": true, }), ) .await?; @@ -1277,6 +1316,17 @@ async fn focus_and_select(cdp: &Cdp, tab: &Tab, backend: i64) -> Result<()> { .unwrap_or("the element could not take focus"); return Err(BrowserError::new("BROWSER_NOT_FOCUSABLE", text)); } + let took_focus = focused + .get("result") + .and_then(|r| r.get("value")) + .and_then(Value::as_bool) + == Some(true); + if !took_focus { + return Err(BrowserError::new( + "BROWSER_NOT_FOCUSABLE", + "the element did not take focus (disabled, or not focusable); nothing was typed", + )); + } Ok(()) } diff --git a/crates/pu-engine/src/browser/snapshot.rs b/crates/pu-engine/src/browser/snapshot.rs index dd215dc7..edb4ae22 100644 --- a/crates/pu-engine/src/browser/snapshot.rs +++ b/crates/pu-engine/src/browser/snapshot.rs @@ -11,6 +11,9 @@ use serde_json::Value; /// Agents read the outline as text; past this the page is cut off with a note. const MAX_LINES: usize = 3000; +/// Nodes visited, printed or not: ignored and flattened nodes cost work too, and a +/// page can nest them arbitrarily deep. +const MAX_NODES: usize = 200_000; const MAX_NAME: usize = 200; const INTERACTIVE: &[&str] = &[ @@ -67,7 +70,7 @@ pub fn format(nodes: &[Value]) -> Snapshot { truncated: false, }; if let Some(root) = root { - out.visit(root, 0, None); + out.walk(root); } if out.truncated { out.snapshot @@ -85,26 +88,38 @@ struct Writer<'a> { } impl<'a> Writer<'a> { - fn visit(&mut self, node: &'a Value, depth: usize, parent_name: Option<&str>) { - if self.truncated { - return; - } - let role = ax_str(node, "role"); - let name = ax_str(node, "name"); - let ignored = node.get("ignored").and_then(Value::as_bool) == Some(true); + /// Depth-first, in document order, with an explicit stack: the tree's depth is + /// the page's, and must not be the daemon's call depth. + fn walk(&mut self, root: &'a Value) { + // (node, depth, the nearest printed ancestor's name) + let mut stack: Vec<(&'a Value, usize, Option<&'a str>)> = vec![(root, 0, None)]; + let mut visited = 0usize; + while let Some((node, depth, parent_name)) = stack.pop() { + if self.truncated { + return; + } + visited += 1; + if visited > MAX_NODES { + self.truncated = true; + return; + } + let role = ax_str(node, "role"); + let name = ax_str(node, "name"); + let ignored = node.get("ignored").and_then(Value::as_bool) == Some(true); - let printed = !ignored && self.line(node, role, name, depth, parent_name); - let child_depth = if printed { depth + 1 } else { depth }; - let name_for_children = if printed { Some(name) } else { parent_name }; + let printed = !ignored && self.line(node, role, name, depth, parent_name); + let child_depth = if printed { depth + 1 } else { depth }; + let name_for_children = if printed { Some(name) } else { parent_name }; - let Some(children) = node.get("childIds").and_then(Value::as_array) else { - return; - }; - for child in children { - let Some(child) = child.as_str().and_then(|id| self.by_id.get(id)).copied() else { + let Some(children) = node.get("childIds").and_then(Value::as_array) else { continue; }; - self.visit(child, child_depth, name_for_children); + // Pushed last to first, so the first child is visited next. + for child in children.iter().rev() { + if let Some(child) = child.as_str().and_then(|id| self.by_id.get(id)).copied() { + stack.push((child, child_depth, name_for_children)); + } + } } } @@ -341,6 +356,34 @@ mod tests { ); } + #[test] + fn given_a_very_deep_tree_should_outline_it_without_recursing() { + // Far deeper than any call stack allows: generic wrappers around one button. + let depth = 200_000; + let mut nodes = vec![node("0", None, "RootWebArea", "", &["1"])]; + for i in 1..depth { + let id = i.to_string(); + let parent = (i - 1).to_string(); + let child = (i + 1).to_string(); + nodes.push(node(&id, Some(&parent), "generic", "", &[child.as_str()])); + } + let last = depth.to_string(); + let parent = (depth - 1).to_string(); + nodes.push(node(&last, Some(&parent), "button", "Deep", &[])); + let snapshot = format(&nodes); + // Past the work limit the outline is cut off with a note, not a crash. + assert!( + snapshot.tree.starts_with("- document\n"), + "{}", + snapshot.tree + ); + assert!( + snapshot.tree.contains("outline truncated"), + "{}", + snapshot.tree + ); + } + #[test] fn given_no_nodes_should_return_an_empty_outline() { let snapshot = format(&[]); diff --git a/crates/pu-engine/src/browser/tab.rs b/crates/pu-engine/src/browser/tab.rs index 557da7d5..0f7ca1e4 100644 --- a/crates/pu-engine/src/browser/tab.rs +++ b/crates/pu-engine/src/browser/tab.rs @@ -62,6 +62,11 @@ pub struct Tab { refs: Mutex>, /// Bumped on every top-level navigation, under the `refs` lock. document: AtomicU64, + /// Bumped as each `navigate` starts: only the latest one may publish its URL. + navigation: AtomicU64, + /// Held while a resize is checked, applied and recorded, across every viewer + /// stream of the tab, so the recorded viewport is the one Chromium last accepted. + resizing: tokio::sync::Mutex<()>, } impl Tab { @@ -89,6 +94,8 @@ impl Tab { console: Mutex::default(), refs: Mutex::default(), document: AtomicU64::new(0), + navigation: AtomicU64::new(0), + resizing: tokio::sync::Mutex::new(()), } } @@ -159,6 +166,15 @@ impl Tab { /// the refs, so a click can never send the old page's node ids to the new one. pub fn set_page(&self, url: Option<&str>, title: Option<&str>) { let mut refs = self.refs.lock().unwrap_or_else(|e| e.into_inner()); + self.set_page_locked(&mut refs, url, title); + } + + fn set_page_locked( + &self, + refs: &mut HashMap, + url: Option<&str>, + title: Option<&str>, + ) { if let Some(url) = url && without_fragment(url) != without_fragment(&self.info.borrow().url) { @@ -233,16 +249,54 @@ impl Tab { } pub fn resolve_ref(&self, reference: &str) -> Option { + self.resolve_ref_on_page(reference).map(|(node, _)| node) + } + + /// A ref's node and the page it belongs to, read together: an action on the + /// node must check `is_on(&mark)` before acting, since the tab may navigate + /// while the action is underway. + pub fn resolve_ref_on_page(&self, reference: &str) -> Option<(i64, DocumentMark)> { let reference = reference .trim() .trim_matches(|c| c == '[' || c == ']') .trim_start_matches('@'); let reference = reference.strip_prefix("ref=").unwrap_or(reference); - self.refs - .lock() - .unwrap_or_else(|e| e.into_inner()) - .get(reference) - .copied() + let refs = self.refs.lock().unwrap_or_else(|e| e.into_inner()); + let node = refs.get(reference).copied()?; + Some(( + node, + DocumentMark { + generation: self.document.load(Ordering::SeqCst), + url: self.info.borrow().url.clone(), + }, + )) + } + + /// Whether the tab still shows the document and URL in `mark`. + pub fn is_on(&self, mark: &DocumentMark) -> bool { + let _refs = self.refs.lock().unwrap_or_else(|e| e.into_inner()); + self.document.load(Ordering::SeqCst) == mark.generation + && self.info.borrow().url == mark.url + } + + /// Starts a navigation; its URL reports go through `set_page_for`. + pub fn begin_navigation(&self) -> u64 { + self.navigation.fetch_add(1, Ordering::SeqCst) + 1 + } + + /// `set_page` for navigation `revision`, ignored once a later navigation has + /// started: an older navigation's late report must not overwrite the current URL. + pub fn set_page_for(&self, revision: u64, url: Option<&str>, title: Option<&str>) { + let mut refs = self.refs.lock().unwrap_or_else(|e| e.into_inner()); + if self.navigation.load(Ordering::SeqCst) != revision { + return; + } + self.set_page_locked(&mut refs, url, title); + } + + /// Serializes this tab's resizes (see the `resizing` field). + pub async fn lock_resize(&self) -> tokio::sync::MutexGuard<'_, ()> { + self.resizing.lock().await } pub fn console(&self, clear: bool) -> Vec { @@ -651,6 +705,35 @@ mod tests { assert_eq!(tab.resolve_ref("e1"), None); } + #[test] + fn given_a_resolved_ref_should_know_when_the_tab_left_its_page() { + let tab = tab(); + tab.set_page(Some("http://a/"), None); + let mark = tab.document_mark(); + tab.store_refs_for(&mark, HashMap::from([("e1".to_string(), 7)])) + .expect("same page"); + let (node, page) = tab.resolve_ref_on_page("e1").expect("stored"); + assert_eq!(node, 7); + assert!(tab.is_on(&page)); + // A new document (or another page's URL) means coordinates from `page` are stale. + tab.new_document(Some("http://b/")); + assert!(!tab.is_on(&page)); + } + + #[test] + fn given_an_older_navigation_reporting_late_should_keep_the_newer_url() { + let tab = tab(); + let first = tab.begin_navigation(); + let second = tab.begin_navigation(); + tab.set_page_for(second, Some("http://b/"), None); + // The first navigation's report arrives after the second one's. + tab.set_page_for(first, Some("http://a/"), None); + assert_eq!(tab.info().url, "http://b/"); + // The browser's own reports (events) still apply. + tab.set_page(Some("http://c/"), None); + assert_eq!(tab.info().url, "http://c/"); + } + #[test] fn given_url_reports_racing_snapshots_should_never_pair_refs_with_another_url() { // Page A's outline is committed only while the tab still reports A. diff --git a/crates/pu-engine/src/ipc_server/streams.rs b/crates/pu-engine/src/ipc_server/streams.rs index 1cf496f1..8985ff0e 100644 --- a/crates/pu-engine/src/ipc_server/streams.rs +++ b/crates/pu-engine/src/ipc_server/streams.rs @@ -638,12 +638,30 @@ async fn browser_stream_loop( // Resizes wait on Chromium; they run in order beside the stream so frames, // input and acks keep flowing, and report only failures. let (resizes_tx, mut resizes_rx) = tokio::sync::mpsc::unbounded_channel::(); + // Set when this stream ends, however it returns: the worker then starts no more + // resizes for a viewer that has left (one already waiting on Chromium finishes). + let ended = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + struct EndOnDrop(std::sync::Arc); + impl Drop for EndOnDrop { + fn drop(&mut self) { + self.0.store(true, std::sync::atomic::Ordering::SeqCst); + } + } + let _end_resizes = EndOnDrop(ended.clone()); { let browsers = browsers.clone(); let root = project_root.to_string(); let replies = replies_tx.clone(); + let ended = ended.clone(); tokio::spawn(async move { - while let Some(op) = resizes_rx.recv().await { + while let Some(mut op) = resizes_rx.recv().await { + // Only the newest waiting size matters; older ones are already stale. + while let Ok(newer) = resizes_rx.try_recv() { + op = newer; + } + if ended.load(std::sync::atomic::Ordering::SeqCst) { + break; + } let resp = browsers.handle(&root, op, Caller::Viewer).await; if matches!(resp, Response::Error { .. }) && replies.send(resp).is_err() { break; diff --git a/crates/pu-engine/tests/browser.rs b/crates/pu-engine/tests/browser.rs index f565b0c0..30c2eb20 100644 --- a/crates/pu-engine/tests/browser.rs +++ b/crates/pu-engine/tests/browser.rs @@ -744,3 +744,81 @@ async fn given_take_control_then_an_immediate_disconnect_should_hand_the_tab_bac } engine.kill_all_sessions(Duration::from_millis(10)).await; } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn given_a_disabled_target_should_refuse_to_type_rather_than_type_elsewhere() { + if !have_browser() { + eprintln!("skipping: no Chrome/Chromium on this machine (set PU_BROWSER)"); + return; + } + use pu_engine::browser::{BrowserManager, Caller}; + let tmp = TempDir::new().unwrap(); + let manager = BrowserManager::new(Some(tmp.path().join("browser"))); + let page = "data:text/html,"; + assert!(matches!( + manager + .handle( + "/p", + BrowserOp::Open { + url: Some(page.into()) + }, + Caller::Agent + ) + .await, + Response::BrowserTab { .. } + )); + let eval = |expression: &str| BrowserOp::Eval { + tab_id: None, + expression: expression.into(), + }; + manager + .handle( + "/p", + eval("document.getElementById('a').focus()"), + Caller::Agent, + ) + .await; + let tree = match manager + .handle("/p", BrowserOp::Snapshot { tab_id: None }, Caller::Agent) + .await + { + Response::BrowserSnapshot { tree, .. } => tree, + other => panic!("snapshot: {other:?}"), + }; + let locked = tree + .lines() + .find(|l| l.contains("\"Locked\"")) + .and_then(|l| l.split("[ref=").nth(1)) + .and_then(|r| r.split(']').next()) + .unwrap_or_else(|| panic!("no ref for Locked in\n{tree}")) + .to_string(); + let typed = manager + .handle( + "/p", + BrowserOp::Type { + tab_id: None, + element: Some(locked), + text: "secret".into(), + submit: false, + }, + Caller::Agent, + ) + .await; + assert!( + matches!(&typed, Response::Error { code, .. } if code == "BROWSER_NOT_FOCUSABLE"), + "{typed:?}" + ); + // Nothing landed in the field that kept focus. + match manager + .handle( + "/p", + eval("document.getElementById('a').value"), + Caller::Agent, + ) + .await + { + Response::BrowserEvalResult { value, .. } => assert_eq!(value, serde_json::json!("")), + other => panic!("eval: {other:?}"), + } + manager.shutdown().await; +} From 066fcca4cd538851b5c439e78a232c1ab85fa570 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 21:41:20 +0000 Subject: [PATCH 23/30] fix(browser): address follow-up review findings - cdp: a command whose caller timed out is never started, even once dequeued onto a full pipe; clear the read buffer before shrinking it; bound test waits - a pane's control, input and resize always act on its attached tab - drop the cached frame when the last viewer leaves, and ignore late frames - close a tab whose open reply could not be delivered - Mac/iPad: streams are registered per attach, so a stopped attach never displaces its replacement; ops are bound to the live stream; the attach reply is bounded; copy requests are counted - Windows: a decode finishing before React sees a new stream neither draws nor acks; refocus follows the pane's current blank state - tests: wait for viewer registration; narrower attach timeout; one stream - docs: automatic hand-back and one protocol version in the changelog; browser spec requirement ids, discovery wording and future work Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ2eMMzt56iHuDqpo7z --- CHANGELOG.md | 7 +- .../State/BrowserSession.swift | 111 +++++++++++++--- .../BrowserPaneTests.swift | 28 ++++ .../src-tauri/src/browser/session_tests.rs | 6 +- .../ui/src/state/browserSession.test.ts | 3 +- .../ui/src/views/browser/BrowserPaneView.tsx | 24 +++- crates/pu-engine/src/browser/cdp.rs | 122 +++++++++++++++--- crates/pu-engine/src/browser/tab.rs | 29 +++++ crates/pu-engine/src/ipc_server/mod.rs | 18 +++ crates/pu-engine/src/ipc_server/streams.rs | 8 ++ crates/pu-engine/tests/browser.rs | 9 ++ docs/product/browser.md | 57 ++++---- 12 files changed, 349 insertions(+), 73 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 73c982fd..f9cbac56 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ All notable changes to PurePoint are documented here. Format follows [Keep a Cha ## [Unreleased] ### Added -- A browser for agents and for you. Each project gets a headless Chrome (or Chromium, Edge or Brave) on the machine where its agents run. Agents drive it with `pu browser` (`open`, `snapshot` with `[ref=eN]` handles, `click`, `type`, `press`, `scroll`, `screenshot`, `console`, `eval`, `wait`), and you watch and use the same tab live in a new browser pane: choose Open Browser in an empty tab, or have an agent run `pu browser open --show`. Take Control stops agents' page actions until you hand the tab back. Because the browser runs on the project's machine, `localhost` means the same thing to agents and to you, and panes work for remote machines. A remote agent's `localhost` links now open in a browser pane instead of your own browser. Logins persist per project in `~/.pu/browser/profiles` on that machine. The browser runs on a macOS or Linux daemon; a project on a Windows daemon cannot start one yet, though the Windows app can open browser panes for projects on a Mac or Linux machine. See [Browser](docs/product/browser.md). +- A browser for agents and for you. Each project gets a headless Chrome (or Chromium, Edge or Brave) on the machine where its agents run. Agents drive it with `pu browser` (`open`, `snapshot` with `[ref=eN]` handles, `click`, `type`, `press`, `scroll`, `screenshot`, `console`, `eval`, `wait`), and you watch and use the same tab live in a new browser pane: choose Open Browser in an empty tab, or have an agent run `pu browser open --show`. Take Control stops agents' page actions until you hand the tab back, or until the last pane showing the tab closes or disconnects, so a closed pane never locks agents out. Because the browser runs on the project's machine, `localhost` means the same thing to agents and to you, and panes work for remote machines. A remote agent's `localhost` links now open in a browser pane instead of your own browser. Logins persist per project in `~/.pu/browser/profiles` on that machine. The browser runs on a macOS or Linux daemon; a project on a Windows daemon cannot start one yet, though the Windows app can open browser panes for projects on a Mac or Linux machine. See [Browser](docs/product/browser.md). - PurePoint runs natively on Windows 11 (x64 and arm64), with no WSL. `pu-engine` and `pu` are native Windows programs: the daemon listens on a private named pipe, agents run in ConPTY terminals and are stopped as a whole process tree, `pu daemon install` starts the daemon at sign-in through your user's Run key, and `pu phone` runs Point Guard for phone pairing over Tailscale. See [PurePoint on Windows](docs/guide/windows.md). - A Windows desktop app (`PurePoint__-setup.exe`, a per-user installer that needs no administrator rights) with the macOS app's features. On first launch it installs `pu` and `pu-engine` to `%USERPROFILE%\.pu\bin`, adds that folder to your user `PATH`, installs the Claude Code plugin and supervises the daemon. The arm64 installer has not been tested on Arm hardware yet. - `scripts/install.ps1` installs the Windows CLI from PowerShell (`irm https://raw.githubusercontent.com/2witstudios/PurePoint/main/scripts/install.ps1 | iex`). Like `install.sh`, it verifies the release's minisign signature or its GitHub attestation before installing, and stops if neither can be checked unless `PU_INSTALL_SKIP_VERIFY=1` is set. @@ -15,11 +15,9 @@ All notable changes to PurePoint are documented here. Format follows [Keep a Cha - Send photos and files to an agent from the iPhone and iPad. On the iPhone, the **+** menu beside an agent's prompt offers Photos and Files; each upload's path is added to your draft so you can write around it before sending. On the iPad, each agent pane has a paperclip button (Photos, Files), and you can paste an image or drag files in from other apps; the path is typed at the agent's prompt without pressing Enter. Photos are sent as JPEG, at most 2048 px on the long edge. The phone bridge relays uploads with a new `agent.attach` operation, which needs Full access; phone uploads are limited to 20 MB per file. ### Changed -- The daemon protocol is now version 15, for the new `browser` and `browser_attach` requests. Update PurePoint on every machine and restart its daemon. +- The daemon protocol is now version 15. This release adds the `browser`, `browser_attach`, `reorder_projects` and `attach_file` requests and changes the launch args request and response shapes. Update PurePoint on every machine and restart its daemon; `pu` and the macOS app reject an older daemon with update guidance instead of appearing to save launch args an old daemon drops. - Point Guard now runs on its bundled Node.js 26 LTS (26.13.0), up from Node 22, on macOS and on Linux phone hosts. Nothing to install: the runtime ships inside PurePoint. Linux phone hosts still need glibc 2.28 or newer, and now also `libatomic` (`libatomic1` on Debian/Ubuntu, `libatomic` on Fedora/RHEL), which Node 26's Linux builds link; the installer names it if it's missing. -- The daemon protocol is now version 14, for the new `reorder_projects` request. Update PurePoint on every machine and restart its daemon. - Phones and iPads now pair with full access (agents, terminals, workspace management and Point Guard chat). Point Guard setup shows each device on one line with a single Access menu (Full access, Terminals only, View only, No access) and a Revoke button. Revoked devices are removed instead of lingering as "Revoked", and the redundant "Require re-pair" button is gone. Devices that are already paired keep their current access. -- The daemon protocol is now version 12, for the new `attach_file` request. Update PurePoint on every machine and restart its daemon. - **Breaking: `scripts/install.sh` installs a Linux release only after verifying who built it.** Linux tarballs are signed with a PurePoint minisign key whose public half is embedded in the script, and releases carry GitHub build provenance attestations. The script checks the signature (with `minisign`, or OpenSSL 3 when minisign isn't installed) and, when the GitHub CLI is installed and signed in, runs `gh attestation verify`. If neither check can run, for example for releases published before signing started, it stops; set `PU_INSTALL_SKIP_VERIFY=1` to install anyway with a warning. A check that fails always stops the install. - Releases now include CycloneDX SBOMs for `pu`, `pu-engine` and the Point Guard npm runtime, attested against the DMG and Linux tarballs. - The update feed (`appcast.xml`) is now signed with the Sparkle update key, and the app requires a signed feed and verifies each update before extracting it. @@ -33,7 +31,6 @@ All notable changes to PurePoint are documented here. Format follows [Keep a Cha Projects that already set `launchArgs` are unaffected. - `launchArgs` is now one free-form string, split like a shell command line (`launchArgs: "--model opus --append-system-prompt 'be terse'"`), so new or renamed CLI flags work without a PurePoint update. Existing list values (`launchArgs: [..]`, `launchArgs: []`) still load the same; PurePoint writes the string form when it saves. A project value, even `""`, takes precedence over the machine-level one. - `pu spawn --no-auto` now launches the bare command and ignores project and machine-level launch args. `--agent-args` still apply. The choice is saved with the agent, so it still launches bare after `pu bench`/`pu play`, suspend/resume or a daemon restart. -- The daemon protocol is now version 11 because the launch args request and response shapes changed. Restart the daemon after updating (`pu` and the macOS app reject a v10 daemon with update guidance instead of appearing to save launch args that an old daemon drops). - Settings → Agents replaces the per-flag pickers for Claude, Codex and OpenCode with one launch args field per agent next to its command, for this project and for all projects. Each field's placeholder shows a flag that CLI accepts (`--model opus` for Claude, `--search` for Codex, `--auto` for OpenCode). - **Breaking:** `pu` no longer searches `PATH` or `~/.cargo/bin` when it auto-starts the daemon. It starts the `pu-engine` beside itself, then `~/.pu/bin/pu-engine`; a `pu` inside the macOS app starts only the app's own engine. To run another build, set `PU_ENGINE_PATH` to its path (or to a name to look up on `PATH`). The chosen binary must be owned by you or root (or, for the app's own engine, by whoever owns the app) and not writable by group or others. If none qualifies, the error says why each candidate was refused. - The macOS app now installs `pu-engine` next to `pu` in `~/.pu/bin`, so `~/.pu/bin/pu` can start the daemon when the app isn't running. Both are copied to a temporary file and renamed into place, so a daemon running from `~/.pu/bin` is never modified underneath itself. diff --git a/apps/purepoint-macos/purepoint-macos/State/BrowserSession.swift b/apps/purepoint-macos/purepoint-macos/State/BrowserSession.swift index 9040f118..c6c406b8 100644 --- a/apps/purepoint-macos/purepoint-macos/State/BrowserSession.swift +++ b/apps/purepoint-macos/purepoint-macos/State/BrowserSession.swift @@ -81,7 +81,15 @@ final class BrowserSession { @ObservationIgnored private var streamTask: Task? @ObservationIgnored private let writer = BrowserStreamWriter() @ObservationIgnored private var viewport: (width: Int, height: Int, scale: Double)? - @ObservationIgnored private var pendingCopy = false + /// Copy requests sent on the live stream and not yet answered. Every eval this pane + /// sends is a copy, so each eval result answers one of them, in whatever order. + @ObservationIgnored private var pendingCopies = 0 + /// Counts attach attempts. A stream is registered only by the latest one, so an + /// attempt that was stopped can never displace a replacement's stream. + @ObservationIgnored private var latestAttach = 0 + /// The attach whose stream is live (its reply read), or nil while (re)attaching: + /// ops are sent only on a live stream, never queued for the next one. + @ObservationIgnored private var liveAttach: Int? @ObservationIgnored private var noticeTask: Task? @ObservationIgnored private var attachedStream: (any DaemonByteStream)? @ObservationIgnored private var lastSend: Task? @@ -145,7 +153,8 @@ final class BrowserSession { /// Copy the page's selected text to the clipboard (`copy` is called with it). func copySelection() { - pendingCopy = true + guard liveAttach != nil else { return } + pendingCopies += 1 send(.eval(tabId: nil, expression: "String(getSelection ? getSelection() : '')")) } @@ -160,12 +169,16 @@ final class BrowserSession { } /// Writes in call order: each send waits for the one before it, so a click's - /// mouse-up can never reach the daemon ahead of its mouse-down. + /// mouse-up can never reach the daemon ahead of its mouse-down. An op is bound to the + /// stream live when it was made: one made while (re)attaching is dropped (the next + /// attach replays the size), and one still queued when its stream ends never reaches + /// the replacement. private func send(_ op: BrowserOp) { + guard let attach = liveAttach else { return } let previous = lastSend lastSend = Task { [writer, projectRoot] in await previous?.value - await writer.send(.browser(projectRoot: projectRoot, op: op)) + await writer.send(.browser(projectRoot: projectRoot, op: op), on: attach) } } @@ -211,7 +224,15 @@ final class BrowserSession { } } + /// How long the daemon may take to answer an attach; the live stream after it may + /// rightly stay quiet, so only this first reply is bounded. + nonisolated static let attachTimeout: Duration = .seconds(30) + private func attachOnce() async throws { + latestAttach += 1 + let attach = latestAttach + liveAttach = nil + pendingCopies = 0 if tabId == nil { let opened = try await client.send(.browser(projectRoot: projectRoot, op: .open(url: lastURL))) // A session stopped (or reopened) while this waited must not adopt the reply. @@ -232,14 +253,35 @@ final class BrowserSession { stream.close() throw CancellationError() } - await writer.use(stream) + defer { + Task { [writer] in await writer.close(stream) } + if attachedStream === stream { attachedStream = nil } + if liveAttach == attach { liveAttach = nil } + } + // The writer takes a stream only from a newer attach than its current one, and only + // the latest attach records it: a stopped attempt resuming late never displaces a + // replacement's stream, here or in `stop()`. + let registered = await writer.use(stream, for: attach) + guard registered, attach == latestAttach, !Task.isCancelled else { throw CancellationError() } attachedStream = stream - defer { Task { [writer] in await writer.close(stream) } } - // Stopped during the hop into the writer: the defer closes this stream. - try Task.checkCancellation() try await DaemonClient.write(.browserAttach(projectRoot: projectRoot, tabId: tabId), to: stream) - let first = try await reader.readLine() + // Bounded: a daemon that accepts the attach but never answers leads to a retry. + let answered = BrowserAttachDeadline() + let deadline = Task { [answered] in + try? await Task.sleep(for: BrowserSession.attachTimeout) + if await answered.expire() { stream.close() } + } + let first: Data + do { + first = try await reader.readLine() + deadline.cancel() + guard await answered.answer() else { throw BrowserSessionError.attachTimedOut } + } catch { + deadline.cancel() + if await answered.expired { throw BrowserSessionError.attachTimedOut } + throw error + } try Task.checkCancellation() switch DaemonClient.parse(first) { case .browserAttached(let info): @@ -254,11 +296,13 @@ final class BrowserSession { throw BrowserSessionError.unexpected } phase = .live + liveAttach = attach if let viewport { await writer.send( .browser( projectRoot: projectRoot, - op: .resize(tabId: nil, width: viewport.width, height: viewport.height, scale: viewport.scale))) + op: .resize(tabId: nil, width: viewport.width, height: viewport.height, scale: viewport.scale)), + on: attach) } while !Task.isCancelled { @@ -278,7 +322,8 @@ final class BrowserSession { frameSize = CGSize(width: payload.width, height: payload.height) } // Acked once drawn: the daemon sends at most two frames ahead of the screen. - await writer.send(.browser(projectRoot: projectRoot, op: .frameAck(tabId: nil, seq: payload.seq))) + await writer.send( + .browser(projectRoot: projectRoot, op: .frameAck(tabId: nil, seq: payload.seq)), on: attach) case .browserTabState(let info): adopt(info) case .browserTabClosed: @@ -288,8 +333,11 @@ final class BrowserSession { case .browserTab(let info): adopt(info) case .browserEvalResult(let value): - if pendingCopy, let value, !value.isEmpty { copy?(value) } - pendingCopy = false + // Each result answers one copy request (they may arrive out of order). + if pendingCopies > 0 { + pendingCopies -= 1 + if let value, !value.isEmpty { copy?(value) } + } case .error(_, let message): show(notice: message) default: @@ -335,26 +383,57 @@ nonisolated enum BrowserSessionError: Error, LocalizedError { case unexpected /// The tab was gone; try again with a new one. case retry + /// The daemon accepted the attach but did not answer it in time; try again. + case attachTimedOut var errorDescription: String? { switch self { case .daemon(_, let message): message case .unexpected: "Unexpected reply from the daemon" case .retry: "Reopening the tab" + case .attachTimedOut: "The daemon did not answer in time" } } } +/// Whether an attach was answered before its deadline closed the stream. +actor BrowserAttachDeadline { + private var settled = false + private(set) var expired = false + + /// The reply arrived; false if the deadline had already expired. + func answer() -> Bool { + if settled { return !expired } + settled = true + return true + } + + /// The deadline passed; true if no reply had arrived (the caller closes the stream). + func expire() -> Bool { + if settled { return false } + settled = true + expired = true + return true + } +} + /// Serializes writes to a pane's attach stream so JSON lines never interleave. actor BrowserStreamWriter { private var stream: (any DaemonByteStream)? + /// The attach `stream` belongs to; a stream from an older attach is refused. + private var attach = 0 - func use(_ stream: any DaemonByteStream) { + /// Makes `stream` current if `attach` is newer than the current one's. + func use(_ stream: any DaemonByteStream, for attach: Int) -> Bool { + guard attach > self.attach else { return false } + self.attach = attach self.stream = stream + return true } - func send(_ request: DaemonRequest) async { - guard let stream else { return } + /// Writes `request` if `attach`'s stream is still the current one. + func send(_ request: DaemonRequest, on attach: Int) async { + guard let stream, attach == self.attach else { return } try? await DaemonClient.write(request, to: stream) } diff --git a/apps/purepoint-macos/purepoint-macosTests/BrowserPaneTests.swift b/apps/purepoint-macos/purepoint-macosTests/BrowserPaneTests.swift index eb287a39..f99c5c69 100644 --- a/apps/purepoint-macos/purepoint-macosTests/BrowserPaneTests.swift +++ b/apps/purepoint-macos/purepoint-macosTests/BrowserPaneTests.swift @@ -132,4 +132,32 @@ struct BrowserPaneTests { #expect(BrowserAddress.tabTitle(for: "https://docs.rs/tokio") == "docs.rs") #expect(BrowserAddress.fieldText(for: "about:blank") == "") } + + @Test func aStoppedAttachNeverDisplacesItsReplacementsStream() async throws { + let writer = BrowserStreamWriter() + let replacement = RecordingByteStream() + let stale = RecordingByteStream() + // The replacement attach registers first; the stopped one resumes late. + #expect(await writer.use(replacement, for: 2)) + #expect(!(await writer.use(stale, for: 1))) + let op = DaemonRequest.browser(projectRoot: "/p", op: .frameAck(tabId: nil, seq: 1)) + // An op bound to the old attach never reaches the replacement's stream. + await writer.send(op, on: 1) + #expect(replacement.written.isEmpty) + await writer.send(op, on: 2) + #expect(replacement.written.count == 1) + #expect(stale.written.isEmpty) + } +} + +/// A stream that records what is written to it and never receives anything. +private final class RecordingByteStream: DaemonByteStream, @unchecked Sendable { + private let lock = NSLock() + private var chunks: [Data] = [] + + var written: [Data] { lock.withLock { chunks } } + + func send(_ data: Data) async throws { lock.withLock { chunks.append(data) } } + func receive() async throws -> Data { throw CancellationError() } + func close() {} } diff --git a/apps/purepoint-windows/src-tauri/src/browser/session_tests.rs b/apps/purepoint-windows/src-tauri/src/browser/session_tests.rs index 89e55954..bbcb614c 100644 --- a/apps/purepoint-windows/src-tauri/src/browser/session_tests.rs +++ b/apps/purepoint-windows/src-tauri/src/browser/session_tests.rs @@ -145,7 +145,6 @@ fn options(tab_id: Option<&str>, url: Option<&str>) -> BrowserOptions { let mut options = BrowserOptions::new("/p", tab_id.map(Into::into), url.map(Into::into)); options.fast_delay = Duration::from_millis(10); options.slow_delay = Duration::from_millis(40); - options.attach_timeout = Duration::from_millis(200); options } @@ -367,7 +366,10 @@ async fn given_a_dropped_stream_should_reattach_and_replay_the_last_resize() { async fn given_a_daemon_that_never_answers_the_attach_should_retry() { let mut daemon = FakeDaemon::start(); let (sink, mut seen) = sink(); - let _session = BrowserSession::start(daemon.client(), options(Some("t1"), None), sink); + // Only this test withholds the reply, so only it shortens the attach deadline. + let mut options = options(Some("t1"), None); + options.attach_timeout = Duration::from_millis(200); + let _session = BrowserSession::start(daemon.client(), options, sink); let mut silent = daemon.accept().await; let _ = silent.request().await; // No reply: the session gives up on this connection and reconnects. diff --git a/apps/purepoint-windows/ui/src/state/browserSession.test.ts b/apps/purepoint-windows/ui/src/state/browserSession.test.ts index b6069ca9..fac44e84 100644 --- a/apps/purepoint-windows/ui/src/state/browserSession.test.ts +++ b/apps/purepoint-windows/ui/src/state/browserSession.test.ts @@ -83,10 +83,11 @@ function makeSession(overrides: Partial = {}) { describe('BrowserSession', () => { it('givenStartShouldOpenAStreamOnTheProjectsMachineWithItsTabAndPage', async () => { - const { session, stream } = makeSession({ tabId: 't0' }); + const { session, stream, backend } = makeSession({ tabId: 't0' }); session.start(); session.start(); // once only await settle(); + expect(backend.streams).toHaveLength(1); expect(stream().projectRoot).toBe('/p'); expect(stream().options).toEqual({ tabId: 't0', diff --git a/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.tsx b/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.tsx index 4e77c5df..6c72135d 100644 --- a/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.tsx +++ b/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.tsx @@ -116,12 +116,14 @@ export function BrowserPaneView({ // The field follows the tab's URL unless the person is typing an address. const address = draft ?? addressFieldText(tab?.url ?? url); - // A pane that takes the grid's focus gives the page the keyboard. + // A pane with no page yet keeps the address field's focus; once a page shows, a pane + // that takes the grid's focus gives the page the keyboard. + const isBlank = addressFieldText(tab?.url ?? url) === ''; useEffect(() => { - if (isFocused && !startsBlank && document.activeElement !== addressRef.current) { + if (isFocused && !isBlank && document.activeElement !== addressRef.current) { canvasRef.current?.focus({ preventScroll: true }); } - }, [isFocused, startsBlank]); + }, [isFocused, isBlank]); const paste = useCallback(() => { clip?.readText().then( @@ -233,6 +235,7 @@ export function BrowserPaneView({ ref={canvasRef} frame={frame} stream={stream} + liveStream={() => session.store.getState().stream} cssSize={frameSize} onInput={(event) => { session.input(event); @@ -311,6 +314,11 @@ interface BrowserCanvasProps { frame: BrowserFrame | null; /** The attach stream now live; a new one drops the old stream's pending frames. */ stream: number; + /** + * The live stream right now, read from the session: it moves on before React re-renders, + * so a decode finishing in between still sees that its frame's stream has ended. + */ + liveStream: () => number; /** The CSS viewport the frame shows. */ cssSize: Size; onInput: (event: BrowserInputEvent) => void; @@ -334,6 +342,7 @@ function BrowserCanvas({ ref, frame, stream, + liveStream, cssSize, onInput, onResize, @@ -351,9 +360,9 @@ function BrowserCanvas({ /** The attach stream whose frames the canvas shows. */ const frameStream = useRef(null); const unmounted = useRef(false); - const handlers = useRef({ onResize, onDrawn }); + const handlers = useRef({ onResize, onDrawn, liveStream }); useLayoutEffect(() => { - handlers.current = { onResize, onDrawn }; + handlers.current = { onResize, onDrawn, liveStream }; }); const setBox = useCallback( @@ -428,7 +437,9 @@ function BrowserCanvas({ decodeFrame(data) .then((image) => { const target = canvas.current; - if (unmounted.current || startedIn !== epoch.current || target === null) return; + const current = + startedIn === epoch.current && frame.stream === handlers.current.liveStream(); + if (unmounted.current || !current || target === null) return; if (seq < drawnSeq.current) return; // a newer frame is already on screen drawnSeq.current = seq; target.getContext('2d')?.drawImage(image, 0, 0, target.width, target.height); @@ -440,6 +451,7 @@ function BrowserCanvas({ // flow-control slots and stall the pane). A frame from before the tab closed // or the stream changed belongs to an old stream and is never acked on the new one. if (unmounted.current || startedIn !== epoch.current) return; + if (frame.stream !== handlers.current.liveStream()) return; handlers.current.onDrawn(seq); }); }, [frame]); diff --git a/crates/pu-engine/src/browser/cdp.rs b/crates/pu-engine/src/browser/cdp.rs index 4dfc8f3d..0a7a9688 100644 --- a/crates/pu-engine/src/browser/cdp.rs +++ b/crates/pu-engine/src/browser/cdp.rs @@ -142,10 +142,23 @@ impl Cdp { tokio::spawn(async move { while let Some(message) = outbox_rx.recv().await { writer_shared.queued.fetch_sub(1, Ordering::SeqCst); - if tokio::time::Instant::now() >= message.deadline { - continue; // its caller already gave up: never act on it late - } - if writer.write_all(&message.bytes).await.is_err() || writer.flush().await.is_err() + // Its caller may give up while the pipe is full: the deadline holds until + // the first byte is written (a pending write writes nothing, so dropping + // it leaves the stream intact). Once a command has started it is + // finished, or the stream would be corrupt. + // `biased`: the deadline is checked before every poll of the write, so a + // command whose caller timed out is never started, however late the + // writer gets to it. + let first = tokio::select! { + biased; + () = tokio::time::sleep_until(message.deadline) => continue, + written = writer.write(&message.bytes) => match written { + Ok(0) | Err(_) => break, + Ok(n) => n, + }, + }; + if writer.write_all(&message.bytes[first..]).await.is_err() + || writer.flush().await.is_err() { break; } @@ -161,7 +174,10 @@ impl Cdp { let mut reader = BufReader::new(reader); let mut buf = Vec::new(); loop { + // Cleared first, so a large reply (a screenshot) does not keep its + // allocation: a Vec cannot shrink below its length. buf.clear(); + buf.shrink_to(64 * 1024); match read_message(&mut reader, &mut buf).await { Ok(Read::Message) => {} Ok(Read::Eof) | Err(_) => break, @@ -181,8 +197,6 @@ impl Cdp { Err(_) => tracing::debug!("unparseable devtools message"), } } - // A large reply (a screenshot) must not pin its buffer for good. - buf.shrink_to(64 * 1024); } reader_shared.shut_down().await; }); @@ -338,17 +352,24 @@ mod tests { use super::*; use tokio::io::{AsyncReadExt, duplex}; + /// How long a fixture waits before failing the test instead of hanging it. + const FIXTURE_WAIT: Duration = Duration::from_secs(5); + /// Reads one NUL-terminated message the client wrote. async fn read_message(stream: &mut (impl AsyncRead + Unpin)) -> Value { - let mut bytes = Vec::new(); - loop { - let byte = stream.read_u8().await.unwrap(); - if byte == 0 { - break; + tokio::time::timeout(FIXTURE_WAIT, async { + let mut bytes = Vec::new(); + loop { + let byte = stream.read_u8().await.unwrap(); + if byte == 0 { + break; + } + bytes.push(byte); } - bytes.push(byte); - } - serde_json::from_slice(&bytes).unwrap() + serde_json::from_slice(&bytes).unwrap() + }) + .await + .expect("the client wrote a whole message in time") } async fn write_message(stream: &mut (impl AsyncWrite + Unpin), value: Value) { @@ -419,7 +440,10 @@ mod tests { json!({"method": "Page.loadEventFired", "params": {"timestamp": 1}, "sessionId": "S2"}), ) .await; - let event = events.recv().await.unwrap(); + let event = tokio::time::timeout(FIXTURE_WAIT, events.recv()) + .await + .expect("the event was delivered in time") + .unwrap(); assert_eq!(event.method, "Page.loadEventFired"); assert_eq!(event.session_id.as_deref(), Some("S2")); assert_eq!(event.params["timestamp"], 1); @@ -523,4 +547,72 @@ mod tests { assert_eq!(result, Err(CdpError::Closed)); assert!(!cdp.is_alive()); } + + /// (open, a write waiting for it to open, what was written) + type GateState = (bool, Option, Vec); + + /// A browser input pipe that takes nothing until it is opened. + #[derive(Clone, Default)] + struct Gate(Arc>); + + impl AsyncWrite for Gate { + fn poll_write( + self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + buf: &[u8], + ) -> std::task::Poll> { + let mut state = self.0.lock().unwrap(); + if !state.0 { + state.1 = Some(cx.waker().clone()); + return std::task::Poll::Pending; + } + state.2.extend_from_slice(buf); + std::task::Poll::Ready(Ok(buf.len())) + } + fn poll_flush( + self: std::pin::Pin<&mut Self>, + _: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + std::task::Poll::Ready(Ok(())) + } + fn poll_shutdown( + self: std::pin::Pin<&mut Self>, + _: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + std::task::Poll::Ready(Ok(())) + } + } + + #[tokio::test] + async fn given_a_command_that_times_out_while_its_write_waits_should_never_send_it() { + let gate = Gate::default(); + let (_browser_out, client_in) = duplex(4096); + let cdp = Cdp::start(client_in, gate.clone()); + // The writer takes this command at once and waits on the full pipe. + assert_eq!( + cdp.call_within(Duration::from_millis(50), None, "Late.click", json!({})) + .await, + Err(CdpError::Timeout("Late.click".into())) + ); + cdp.send(None, "Later.ok", json!({})); + // The browser reads again. + let waker = { + let mut state = gate.0.lock().unwrap(); + state.0 = true; + state.1.take() + }; + if let Some(waker) = waker { + waker.wake(); + } + tokio::time::timeout(FIXTURE_WAIT, async { + while !gate.0.lock().unwrap().2.contains(&0) { + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .expect("the live command was written"); + let written = String::from_utf8(gate.0.lock().unwrap().2.clone()).unwrap(); + assert!(written.contains("Later.ok"), "{written}"); + assert!(!written.contains("Late.click"), "{written}"); + } } diff --git a/crates/pu-engine/src/browser/tab.rs b/crates/pu-engine/src/browser/tab.rs index 0f7ca1e4..bcb4a536 100644 --- a/crates/pu-engine/src/browser/tab.rs +++ b/crates/pu-engine/src/browser/tab.rs @@ -337,6 +337,9 @@ impl Tab { *viewers = viewers.saturating_sub(1); if *viewers == 0 { cdp.send(Some(&self.session_id), "Page.stopScreencast", json!({})); + // The last frame of the ended cast is stale by the time anyone attaches + // again: the next viewer waits for the new cast's first frame instead. + self.frame.send_replace(None); // Control belongs to a person at a pane: with no pane left, agents resume. self.set_driver(BrowserDriver::Agent); } @@ -383,6 +386,11 @@ impl Tab { let Some(data) = params.get("data").and_then(Value::as_str) else { return false; }; + // A frame of a cast that ended (its last viewer left) arriving late must + // not become the cached frame a later viewer is shown first. + if !self.has_viewers() { + return false; + } let metadata = params.get("metadata"); let viewport = self.viewport(); let dim = |key: &str, fallback: u32| { @@ -523,6 +531,7 @@ mod tests { async fn given_screencast_frames_should_keep_only_the_newest_numbered_in_order() { let tab = tab(); let cdp = cdp(); + tab.add_viewer(&cdp); let frames = tab.subscribe_frames(); for data in ["AAA", "BBB"] { tab.on_event( @@ -770,6 +779,26 @@ mod tests { assert_eq!(tab.driver(), BrowserDriver::Agent); } + #[tokio::test] + async fn given_the_last_viewer_leaves_should_drop_the_cached_frame_and_late_frames() { + let tab = tab(); + let cdp = cdp(); + let frame = |data: &str| { + event( + "Page.screencastFrame", + json!({"data": data, "sessionId": 1, "metadata": {"deviceWidth": 800, "deviceHeight": 600}}), + ) + }; + tab.add_viewer(&cdp); + tab.on_event(&frame("AAA"), &cdp); + assert!(tab.subscribe_frames().borrow().is_some()); + tab.remove_viewer(&cdp); + assert!(tab.subscribe_frames().borrow().is_none()); + // A frame of the ended cast arriving late is not cached for the next viewer. + tab.on_event(&frame("LATE"), &cdp); + assert!(tab.subscribe_frames().borrow().is_none()); + } + #[test] fn given_ref_spellings_should_resolve_the_same_element() { let tab = tab(); diff --git a/crates/pu-engine/src/ipc_server/mod.rs b/crates/pu-engine/src/ipc_server/mod.rs index d622d6f0..de82bf16 100644 --- a/crates/pu-engine/src/ipc_server/mod.rs +++ b/crates/pu-engine/src/ipc_server/mod.rs @@ -286,6 +286,15 @@ impl IpcServer { } let is_shutdown = matches!(request, Request::Shutdown); let stream_mode = StreamMode::from_request(&request); + // A browser `open` whose reply cannot be delivered made a tab nobody knows the + // id of: it is closed again below. + let opened_browser_in = match &request { + Request::Browser { + project_root, + op: pu_core::protocol::BrowserOp::Open { .. }, + } => Some(project_root.clone()), + _ => None, + }; let cancel_on_disconnect = matches!( &request, @@ -309,6 +318,15 @@ impl IpcServer { if !matches!(stream_mode, StreamMode::Attach(..)) && write_response(writer, &response).await.is_err() { + if let (Some(root), Response::BrowserTab { tab }) = (&opened_browser_in, &response) { + let close = pu_core::protocol::BrowserOp::Close { + tab_id: Some(tab.tab_id.clone()), + }; + engine + .browsers() + .handle(root, close, crate::browser::Caller::Agent) + .await; + } if is_shutdown { shutdown.notify_one(); } diff --git a/crates/pu-engine/src/ipc_server/streams.rs b/crates/pu-engine/src/ipc_server/streams.rs index 8985ff0e..06f315cd 100644 --- a/crates/pu-engine/src/ipc_server/streams.rs +++ b/crates/pu-engine/src/ipc_server/streams.rs @@ -738,6 +738,14 @@ async fn browser_stream_loop( break; }; op.default_tab(&tab_id); + // The pane's own ops act on the tab it is attached to, whatever tab id + // they name: a pane can never take control of (or type into) another tab. + if let BrowserOp::Control { tab_id: target, .. } + | BrowserOp::Input { tab_id: target, .. } + | BrowserOp::Resize { tab_id: target, .. } = &mut op + { + *target = Some(tab_id.clone()); + } if let BrowserOp::FrameAck { seq, .. } = op { while in_flight.front().is_some_and(|sent| *sent <= seq) { in_flight.pop_front(); diff --git a/crates/pu-engine/tests/browser.rs b/crates/pu-engine/tests/browser.rs index 30c2eb20..81725883 100644 --- a/crates/pu-engine/tests/browser.rs +++ b/crates/pu-engine/tests/browser.rs @@ -691,6 +691,15 @@ async fn given_take_control_then_an_immediate_disconnect_should_hand_the_tab_bac .await, Response::BrowserAttached { .. } )); + // The daemon replies to the attach before it registers the viewer: wait for + // the registration, so "no viewers" below can only mean the teardown ran. + tokio::time::timeout(Duration::from_secs(10), async { + while !handle.has_viewers() { + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .expect("the viewer registered"); viewer .write(&browser( &root, diff --git a/docs/product/browser.md b/docs/product/browser.md index 67d7103a..48dc41a6 100644 --- a/docs/product/browser.md +++ b/docs/product/browser.md @@ -49,33 +49,33 @@ Alternatives considered: ## Requirements ### Daemon and agents -- Given `pu browser open localhost:3000` in a project with no browser running, should start the project's browser, open a tab on `http://localhost:3000`, wait up to 15 s for it to load, and print the tab id, URL and title. -- Given `pu browser tabs` with no browser running, should print no tabs and not start one. -- Given `pu browser snapshot`, should print the page as an indented outline with `[ref=eN]` on links, buttons, fields and other interactive elements. -- Given `pu browser click e3` after a snapshot, should scroll the element into view and click its center. -- Given `pu browser type e5 "text"`, should focus the element, replace its contents with the text, and with `--submit` press Enter. -- Given a ref from before the latest snapshot or navigation, should fail with `BROWSER_REF_NOT_FOUND` and ask for a new snapshot. -- Given `pu browser wait --text "Saved"`, should succeed once the text is on the page, or fail with `BROWSER_TIMEOUT` after the timeout (default 10 s, max 120 s). -- Given `pu browser screenshot [path]`, should save a PNG on the daemon's machine (a relative path resolves against the CLI's directory; with `--machine` it must be absolute) and print its path. -- Given `pu browser console`, should print console messages, uncaught exceptions and dialogs since the tab opened, oldest first. -- Given `pu browser open URL --show`, should also ask the app to show the tab in a browser pane (`GridCommand::OpenBrowser`). -- Given an agent in a worktree, should use the project's browser (the CLI resolves the project from `PU_PROJECT_ROOT`). -- Given no Chrome, Chromium or Edge on the machine, should fail with `BROWSER_NOT_FOUND` naming `PU_BROWSER`. -- Given the daemon is killed, should leave no browser processes behind. -- Given a daemon restart, should start a new browser on the same profile, so logins persist. -- Given a browser unused and unwatched for 30 minutes, should stop it; the next `open` starts it again. +- REQ-BROWSER-001: Given `pu browser open localhost:3000` in a project with no browser running, should start the project's browser, open a tab on `http://localhost:3000`, wait up to 15 s for it to load, and print the tab id, URL and title. +- REQ-BROWSER-002: Given `pu browser tabs` with no browser running, should print no tabs and not start one. +- REQ-BROWSER-003: Given `pu browser snapshot`, should print the page as an indented outline with `[ref=eN]` on links, buttons, fields and other interactive elements. +- REQ-BROWSER-004: Given `pu browser click e3` after a snapshot, should scroll the element into view and click its center. +- REQ-BROWSER-005: Given `pu browser type e5 "text"`, should focus the element, replace its contents with the text, and with `--submit` press Enter. +- REQ-BROWSER-006: Given a ref from before the latest snapshot or navigation, should fail with `BROWSER_REF_NOT_FOUND` and ask for a new snapshot. +- REQ-BROWSER-007: Given `pu browser wait --text "Saved"`, should succeed once the text is on the page, or fail with `BROWSER_TIMEOUT` after the timeout (default 10 s, max 120 s). +- REQ-BROWSER-008: Given `pu browser screenshot [path]`, should save a PNG on the daemon's machine (a relative path resolves against the CLI's directory; with `--machine` it must be absolute) and print its path. +- REQ-BROWSER-009: Given `pu browser console`, should print console messages, uncaught exceptions and dialogs since the tab opened, oldest first. +- REQ-BROWSER-010: Given `pu browser open URL --show`, should also ask the app to show the tab in a browser pane (`GridCommand::OpenBrowser`). +- REQ-BROWSER-011: Given an agent in a worktree, should use the project's browser (the CLI resolves the project from `PU_PROJECT_ROOT`). +- REQ-BROWSER-012: Given no browser found by any of the ways in [BROWSER-003] (no `PU_BROWSER`, no Chrome, Chromium, Edge or Brave in its usual install location or on `PATH`, and no `~/.pu/browser/chrome/chrome`), should fail with `BROWSER_NOT_FOUND` naming `PU_BROWSER`. +- REQ-BROWSER-013: Given the daemon is killed, should leave no browser processes behind. +- REQ-BROWSER-014: Given a daemon restart, should start a new browser on the same profile, so logins persist. +- REQ-BROWSER-015: Given a browser unused and unwatched for 30 minutes, should stop it; the next `open` starts it again. ### Panes -- Given "Open Browser" in an empty tab, should open a new tab of the project's browser and focus the address field. -- Given a browser pane on screen, should show the tab live, with back, forward, reload, the address and who is driving. -- Given a pane resize, should resize the page's viewport to match, at the display's pixel density. -- Given clicks, drags, scrolling, typing, paste (Cmd/Ctrl+V) and copy (Cmd/Ctrl+C) in the pane, should apply them to the page. -- Given "Take Control", should refuse agents' page actions until "Hand Back", or until the last pane showing the tab closes or disconnects. -- Given a pane whose tab was closed elsewhere, should say so and offer to reopen it on its last page. -- Given an app relaunch, should reattach each browser pane to its tab, or reopen its last page if the tab is gone. -- Given a project on a remote machine, should behave the same, running the browser on that machine. -- Given `pu browser open --show` while the tab is already in a pane, should select that pane tab instead of opening another. -- Given the pane is not on screen (another tab selected), should stop the screencast for it. +- REQ-BROWSER-016: Given "Open Browser" in an empty tab, should open a new tab of the project's browser and focus the address field. +- REQ-BROWSER-017: Given a browser pane on screen, should show the tab live, with back, forward, reload, the address and who is driving. +- REQ-BROWSER-018: Given a pane resize, should resize the page's viewport to match, at the display's pixel density. +- REQ-BROWSER-019: Given clicks, drags, scrolling, typing, paste (Cmd/Ctrl+V) and copy (Cmd/Ctrl+C) in the pane, should apply them to the page. +- REQ-BROWSER-020: Given "Take Control", should refuse agents' page actions until "Hand Back", or until the last pane showing the tab closes or disconnects. +- REQ-BROWSER-021: Given a pane whose tab was closed elsewhere, should say so and offer to reopen it on its last page. +- REQ-BROWSER-022: Given an app relaunch, should reattach each browser pane to its tab, or reopen its last page if the tab is gone. +- REQ-BROWSER-023: Given a project on a remote machine, should behave the same, running the browser on that machine. +- REQ-BROWSER-024: Given `pu browser open --show` while the tab is already in a pane, should select that pane tab instead of opening another. +- REQ-BROWSER-025: Given the pane is not on screen (another tab selected), should stop the screencast for it. ## Sum Sheet @@ -108,11 +108,12 @@ remote terminal link ∧ loopback(link) → open in browser pane of project - **IME composition is not supported yet.** No pane is a text-input client (macOS has no `NSTextInputClient`, the iPad canvas is `UIKeyInput` without `UITextInput`, the Windows canvas is a non-editable element), so CJK and other composed input does not reach the page. Paste works as a workaround. - **No audio or video capture**, file pickers and downloads are not surfaced in v1. -## Open Questions +## Future Work -- IME composition in all three panes: a composition-capable input target that sends committed text as a `text` event and holds key forwarding while composing. +Deferred from v1 by decision, not open questions: the spec is complete without them. +- IME composition in all three panes: a composition-capable input target that sends committed text as a `text` event and holds key forwarding while composing (see Edge Cases). - Per-project site allowlist for agent navigation, with approval in the pane. - Gating `eval` behind approval for agents. -- A "open in my browser" port relay for pages a person wants in their own browser. +- An "open in my browser" port relay for pages a person wants in their own browser. - Surfacing downloads and file choosers. From b728a3e4dc39c513abff5b4d4658b944af8e4320 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 22:25:31 +0000 Subject: [PATCH 24/30] fix(browser): bound per-pane work, scope streams to their tab, harden shutdown Engine - CDP writer: a command that times out while its write waits is never sent; the rest of a command is written under a deadline, and a stalled pipe shuts the connection down. - BrowserManager::shutdown waits for launches and instances, refuses new ones, and a per-profile flock keeps a second daemon off a profile in use (BROWSER_PROFILE_IN_USE). - Snapshot refs continue one sequence per tab, so a stale ref never names a new element; history refreshes and viewport records reject stale results. - Click always releases after a press; Control to human with no pane watching is refused (BROWSER_NO_VIEWER). - Attach streams act only on their tab (BROWSER_OTHER_TAB), refuse open (BROWSER_NOT_ON_STREAM), cap outstanding replying ops at 8 (BROWSER_BUSY), keep only the newest resize, and recheck the pane after the resize lock. - The reply to a plain open is written under a deadline; on failure the tab is closed. Apps - macOS: the attach deadline covers the attach write and ends cleanly when cancelled; stop() refuses further pane ops; 127.0.0.0/8 counts as loopback. - Windows: paste is bound to the stream that took the shortcut; acks stop at canvas removal; pointer input maps with the drawn frame's size; only a stream that stayed up resets the retry schedule; the session loop polls input and replies fairly; tooltips say what happens to agents. Docs: browser.md and ipc-api.md describe the stream rules, error codes and the DevTools pipe boundary. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ2eMMzt56iHuDqpo7z --- .../State/BrowserSession.swift | 22 +- .../BrowserPaneTests.swift | 14 +- .../src-tauri/src/browser/session.rs | 25 +- .../src-tauri/src/browser/session_tests.rs | 65 ++++- .../ui/src/model/browser.test.ts | 4 +- .../purepoint-windows/ui/src/model/browser.ts | 4 +- .../ui/src/state/browserSession.test.ts | 5 +- .../views/browser/BrowserPaneView.test.tsx | 21 ++ .../ui/src/views/browser/BrowserPaneView.tsx | 48 +++- crates/pu-engine/src/browser/cdp.rs | 75 ++++- crates/pu-engine/src/browser/launch.rs | 48 ++-- crates/pu-engine/src/browser/mod.rs | 190 +++++++++++-- crates/pu-engine/src/browser/snapshot.rs | 61 ++-- crates/pu-engine/src/browser/tab.rs | 84 +++++- crates/pu-engine/src/ipc_server/mod.rs | 21 +- crates/pu-engine/src/ipc_server/streams.rs | 85 ++++-- crates/pu-engine/tests/browser.rs | 260 ++++++++++++++++++ crates/pu-engine/tests/browser_launch.rs | 36 +++ docs/product/browser.md | 12 +- docs/reference/ipc-api.md | 4 +- 20 files changed, 957 insertions(+), 127 deletions(-) diff --git a/apps/purepoint-macos/purepoint-macos/State/BrowserSession.swift b/apps/purepoint-macos/purepoint-macos/State/BrowserSession.swift index c6c406b8..bdea8ff1 100644 --- a/apps/purepoint-macos/purepoint-macos/State/BrowserSession.swift +++ b/apps/purepoint-macos/purepoint-macos/State/BrowserSession.swift @@ -34,10 +34,20 @@ enum BrowserLinks { guard let scheme = url.scheme?.lowercased(), scheme == "http" || scheme == "https", let host = url.host?.lowercased() else { return false } - return host == "localhost" || host.hasSuffix(".localhost") || host == "127.0.0.1" || host == "0.0.0.0" + return host == "localhost" || host.hasSuffix(".localhost") || isLoopbackIPv4(host) || host == "0.0.0.0" || host == "::1" || host == "[::1]" } + /// Any of 127.0.0.0/8, written as a dotted quad. + nonisolated private static func isLoopbackIPv4(_ host: String) -> Bool { + let parts = host.split(separator: ".", omittingEmptySubsequences: false) + guard parts.count == 4, parts.first == "127" else { return false } + return parts.allSatisfy { part in + !part.isEmpty && part.count <= 3 && part.allSatisfy(\.isASCII) && part.allSatisfy(\.isNumber) + && (Int(part) ?? 256) <= 255 + } + } + /// The terminal link handler: loopback links of a remote agent go to a browser pane. static func handler(agentId: String, isRemote: @escaping () -> Bool, fallback: @escaping (URL) -> Void) -> (URL) -> Void @@ -116,6 +126,8 @@ final class BrowserSession { func stop() { streamTask?.cancel() streamTask = nil + // Nothing more goes out on the stopped attach, even before its task unwinds. + liveAttach = nil // The stream this session attached; a reopen's new stream is never closed by it. // With none attached yet (still connecting) there is nothing to close here: the // cancelled attach closes its own stream, and `writer.close(nil)` would pick @@ -264,16 +276,18 @@ final class BrowserSession { let registered = await writer.use(stream, for: attach) guard registered, attach == latestAttach, !Task.isCancelled else { throw CancellationError() } attachedStream = stream - try await DaemonClient.write(.browserAttach(projectRoot: projectRoot, tabId: tabId), to: stream) - // Bounded: a daemon that accepts the attach but never answers leads to a retry. + // Bounded from the request on: a daemon that stops reading (so the write never + // finishes) or never answers the attach leads to a retry. A deadline cancelled + // before it fires ends without expiring the attach. let answered = BrowserAttachDeadline() let deadline = Task { [answered] in - try? await Task.sleep(for: BrowserSession.attachTimeout) + do { try await Task.sleep(for: BrowserSession.attachTimeout) } catch { return } if await answered.expire() { stream.close() } } let first: Data do { + try await DaemonClient.write(.browserAttach(projectRoot: projectRoot, tabId: tabId), to: stream) first = try await reader.readLine() deadline.cancel() guard await answered.answer() else { throw BrowserSessionError.attachTimedOut } diff --git a/apps/purepoint-macos/purepoint-macosTests/BrowserPaneTests.swift b/apps/purepoint-macos/purepoint-macosTests/BrowserPaneTests.swift index f99c5c69..625d752e 100644 --- a/apps/purepoint-macos/purepoint-macosTests/BrowserPaneTests.swift +++ b/apps/purepoint-macos/purepoint-macosTests/BrowserPaneTests.swift @@ -97,10 +97,16 @@ struct BrowserPaneTests { } @Test func onlyLoopbackWebLinksCountAsTheMachines() throws { - for link in ["http://localhost:3000", "https://app.localhost/x", "http://127.0.0.1:8080", "http://0.0.0.0:4000"] { + for link in [ + "http://localhost:3000", "https://app.localhost/x", "http://127.0.0.1:8080", "http://127.0.1.1:5173", + "http://0.0.0.0:4000", + ] { #expect(BrowserLinks.isLoopback(try #require(URL(string: link))), "\(link)") } - for link in ["https://example.com", "file:///tmp/a", "ssh://localhost", "http://192.168.1.4"] { + for link in [ + "https://example.com", "file:///tmp/a", "ssh://localhost", "http://192.168.1.4", + "http://127.0.0.256", "http://127.example.com", + ] { #expect(!BrowserLinks.isLoopback(try #require(URL(string: link))), "\(link)") } } @@ -108,11 +114,13 @@ struct BrowserPaneTests { @Test @MainActor func aRemoteTerminalsLoopbackLinkOpensInABrowserPane() throws { var opened: [String] = [] var fellBack: [URL] = [] + // Restores whatever opener the app installed, so other tests see it unchanged. + let installed = BrowserLinks.open + defer { BrowserLinks.open = installed } BrowserLinks.open = { agentId, url in opened.append("\(agentId) \(url.absoluteString)") return true } - defer { BrowserLinks.open = nil } let remote = BrowserLinks.handler(agentId: "ag-1", isRemote: { true }, fallback: { fellBack.append($0) }) remote(try #require(URL(string: "http://localhost:3000"))) remote(try #require(URL(string: "https://example.com"))) diff --git a/apps/purepoint-windows/src-tauri/src/browser/session.rs b/apps/purepoint-windows/src-tauri/src/browser/session.rs index 9cd9bc06..4c9aef48 100644 --- a/apps/purepoint-windows/src-tauri/src/browser/session.rs +++ b/apps/purepoint-windows/src-tauri/src/browser/session.rs @@ -91,6 +91,9 @@ pub struct BrowserOptions { /// How long one write to the stream may take before the connection counts as /// stalled and is replaced (tests shorten it). pub write_timeout: Duration, + /// How long a stream must stay live before a later drop counts as a fresh + /// start of the retry schedule; one that drops sooner keeps counting failures. + pub stable_after: Duration, } impl BrowserOptions { @@ -107,10 +110,14 @@ impl BrowserOptions { slow_delay: Duration::from_secs(2), attach_timeout: crate::daemon::client::REQUEST_TIMEOUT, write_timeout: WRITE_TIMEOUT, + stable_after: STABLE_AFTER, } } } +/// A stream live this long was a working connection: its loss restarts the retry schedule. +pub const STABLE_AFTER: Duration = Duration::from_secs(10); + /// A write the relay has not taken in this long means the connection is stalled. pub const WRITE_TIMEOUT: Duration = Duration::from_secs(20); @@ -168,6 +175,8 @@ impl BrowserSession { slow_delay: options.slow_delay, attach_timeout: options.attach_timeout, write_timeout: options.write_timeout, + stable_after: options.stable_after, + live_since: None, viewport: None, sink, ops: rx, @@ -207,6 +216,9 @@ struct Worker { slow_delay: Duration, attach_timeout: Duration, write_timeout: Duration, + stable_after: Duration, + /// When the current attempt's stream went live, if it did. + live_since: Option, /// The last `resize` the pane sent: (width, height, scale). viewport: Option<(u32, u32, f64)>, sink: Arc, @@ -225,7 +237,13 @@ impl Worker { return self.sink.event(BrowserEvent::Failed { code, message }); } End::Retry { message, live } => { - failures = if live { 1 } else { failures + 1 }; + // Only a stream that stayed up resets the schedule: one that attaches + // and drops at once keeps backing off like any other failure. + let stable = live + && self + .live_since + .is_some_and(|since| since.elapsed() >= self.stable_after); + failures = if stable { 1 } else { failures + 1 }; let delay = retry_delay(failures, self.fast_delay, self.slow_delay); self.sink.event(BrowserEvent::Retrying { attempt: failures, @@ -312,6 +330,7 @@ impl Worker { } async fn attach_once(&mut self) -> End { + self.live_since = None; let retry = |message: String| End::Retry { message, live: false, @@ -377,6 +396,7 @@ impl Worker { if !self.drop_stale_ops() { return End::Stopped; } + self.live_since = Some(tokio::time::Instant::now()); self.sink.event(BrowserEvent::Live); if let Some((width, height, scale)) = self.viewport { let resize = self.request(BrowserOp::Resize { @@ -393,9 +413,10 @@ impl Worker { } } + // Unbiased: a backlog of pane input must not hold back a buffered reply + // (a closed tab, say); each side still keeps its own order. loop { tokio::select! { - biased; op = self.ops.recv() => { let Some(op) = op else { return End::Stopped }; self.remember(&op); diff --git a/apps/purepoint-windows/src-tauri/src/browser/session_tests.rs b/apps/purepoint-windows/src-tauri/src/browser/session_tests.rs index bbcb614c..227077dd 100644 --- a/apps/purepoint-windows/src-tauri/src/browser/session_tests.rs +++ b/apps/purepoint-windows/src-tauri/src/browser/session_tests.rs @@ -480,9 +480,72 @@ async fn given_a_relay_that_stops_taking_bytes_should_give_up_the_write_and_retr // The attach write never completes: the session drops the connection and retries // instead of waiting forever. match next(&mut seen).await { - BrowserEvent::Retrying { message, .. } => { + BrowserEvent::Retrying { + attempt: 1, + message, + .. + } => { assert!(message.contains("stopped taking data"), "{message}") } + other => panic!("expected a first retry, got {other:?}"), + } + // ...and then really tries again, on a new connection. + match next(&mut seen).await { + BrowserEvent::Retrying { + attempt: 2, + message, + .. + } => { + assert!(message.contains("stopped taking data"), "{message}") + } + other => panic!("expected a second attempt, got {other:?}"), + } +} + +/// Attaches on a fresh connection, goes live, then drops it; returns the retry's attempt. +async fn attach_then_drop( + daemon: &mut FakeDaemon, + seen: &mut mpsc::UnboundedReceiver, +) -> u32 { + let mut stream = daemon.accept().await; + let _ = stream.request().await; + stream + .send(&Response::BrowserAttached { + tab: tab("t1", "http://localhost/"), + }) + .await; + assert!(matches!(next(seen).await, BrowserEvent::Tab { .. })); + assert_eq!(next(seen).await, BrowserEvent::Live); + drop(stream); + match next(seen).await { + BrowserEvent::Retrying { attempt, .. } => attempt, other => panic!("expected a retry, got {other:?}"), } } + +#[tokio::test] +async fn given_a_stream_that_drops_right_after_attaching_should_keep_backing_off() { + let mut daemon = FakeDaemon::start(); + let (sink, mut seen) = sink(); + let _session = BrowserSession::start(daemon.client(), options(Some("t1"), None), sink); + let attempts = [ + attach_then_drop(&mut daemon, &mut seen).await, + attach_then_drop(&mut daemon, &mut seen).await, + attach_then_drop(&mut daemon, &mut seen).await, + ]; + assert_eq!(attempts, [1, 2, 3]); +} + +#[tokio::test] +async fn given_a_stream_that_stayed_up_should_start_the_retry_schedule_over() { + let mut daemon = FakeDaemon::start(); + let (sink, mut seen) = sink(); + let mut options = options(Some("t1"), None); + options.stable_after = Duration::ZERO; + let _session = BrowserSession::start(daemon.client(), options, sink); + let attempts = [ + attach_then_drop(&mut daemon, &mut seen).await, + attach_then_drop(&mut daemon, &mut seen).await, + ]; + assert_eq!(attempts, [1, 1]); +} diff --git a/apps/purepoint-windows/ui/src/model/browser.test.ts b/apps/purepoint-windows/ui/src/model/browser.test.ts index eb961767..e94e8d18 100644 --- a/apps/purepoint-windows/ui/src/model/browser.test.ts +++ b/apps/purepoint-windows/ui/src/model/browser.test.ts @@ -42,6 +42,7 @@ describe('browser addresses', () => { 'https://LOCALHOST/x', 'http://app.localhost:8080/', 'http://127.0.0.1:5173/', + 'http://127.0.1.1:5173/', 'http://0.0.0.0:8000', 'http://[::1]:3000/', ]) { @@ -53,7 +54,8 @@ describe('browser addresses', () => { 'ftp://localhost/', 'file:///C:/x', 'nonsense', - 'http://127.0.0.2/', + 'http://127.example.com/', + 'http://128.0.0.1/', ]) { expect(isLoopbackUrl(url), url).toBe(false); } diff --git a/apps/purepoint-windows/ui/src/model/browser.ts b/apps/purepoint-windows/ui/src/model/browser.ts index 6bd069d9..7a4e45f7 100644 --- a/apps/purepoint-windows/ui/src/model/browser.ts +++ b/apps/purepoint-windows/ui/src/model/browser.ts @@ -38,7 +38,7 @@ export function addressFieldText(url: string | null): string { /** * Whether a link points at the machine it was printed on: `localhost` (and `*.localhost`), - * 127.0.0.1, 0.0.0.0 or [::1], over http(s). Swift `BrowserLinks.isLoopback`. + * any of 127.0.0.0/8, 0.0.0.0 or [::1], over http(s). Swift `BrowserLinks.isLoopback`. */ export function isLoopbackUrl(url: string): boolean { let parsed: URL; @@ -52,7 +52,7 @@ export function isLoopbackUrl(url: string): boolean { return ( host === 'localhost' || host.endsWith('.localhost') || - host === '127.0.0.1' || + /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(host) || host === '0.0.0.0' || host === '::1' || host === '[::1]' diff --git a/apps/purepoint-windows/ui/src/state/browserSession.test.ts b/apps/purepoint-windows/ui/src/state/browserSession.test.ts index fac44e84..5fcc8b2b 100644 --- a/apps/purepoint-windows/ui/src/state/browserSession.test.ts +++ b/apps/purepoint-windows/ui/src/state/browserSession.test.ts @@ -134,9 +134,10 @@ describe('BrowserSession', () => { const { session, stream } = makeSession(); session.start(); await settle(); + stream().emit({ type: 'live' }); stream().emit({ type: 'frame', seq: 3, data: '/9j/', width: 1024, height: 768 }); expect(session.state.frame).toEqual({ - stream: 0, + stream: 1, seq: 3, data: '/9j/', width: 1024, @@ -152,6 +153,7 @@ describe('BrowserSession', () => { const { session, stream } = makeSession(); session.start(); await settle(); + stream().emit({ type: 'live' }); session.navigate(' localhost:5173 '); session.navigate(' '); session.goBack(); @@ -175,6 +177,7 @@ describe('BrowserSession', () => { const { session, stream, copy } = makeSession(); session.start(); await settle(); + stream().emit({ type: 'live' }); session.copySelection(); expect(stream().sent[0]).toMatchObject({ action: 'eval' }); stream().emit({ type: 'eval_result', value: 'selected' }); diff --git a/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.test.tsx b/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.test.tsx index a71be09c..6f6a8555 100644 --- a/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.test.tsx +++ b/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.test.tsx @@ -122,6 +122,27 @@ describe('BrowserPaneView', () => { expect(clipboard.writeText).toHaveBeenCalledWith('chosen'); }); + it('drops a paste whose clipboard read finishes on a newer stream', async () => { + const { send, sent, clipboard } = setup(); + await send({ type: 'live' }); + let release: (text: string) => void = () => undefined; + clipboard.readText.mockImplementationOnce( + () => + new Promise((resolve) => { + release = resolve; + }), + ); + const canvas = screen.getByTestId('browser-canvas'); + fireEvent.keyDown(canvas, { key: 'v', code: 'KeyV', ctrlKey: true }); + // The pane reconnects (or moves to a replacement tab) before the clipboard answers. + await send({ type: 'live' }); + await act(async () => { + release('secret'); + await Promise.resolve(); + }); + expect(sent.filter((op) => op.action === 'input')).toEqual([]); + }); + it('offers to reopen a closed tab, on its last page', async () => { const { send, opens } = setup({ tabId: 't1', url: 'http://localhost:8080/' }); await send({ type: 'tab', tab: tab({ url: 'http://localhost:8080/x' }) }); diff --git a/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.tsx b/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.tsx index 6c72135d..896f2130 100644 --- a/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.tsx +++ b/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.tsx @@ -125,9 +125,22 @@ export function BrowserPaneView({ } }, [isFocused, isBlank]); + // Paste goes to the stream that took the shortcut: text read after the pane closed, or + // after it moved to another (or reopened) tab, is dropped rather than typed there. + const mounted = useRef(true); + useEffect(() => { + mounted.current = true; + return () => { + mounted.current = false; + }; + }, []); const paste = useCallback(() => { + const started = session.store.getState(); + if (started.phase.kind !== 'live') return; clip?.readText().then( (text) => { + const now = session.store.getState(); + if (!mounted.current || now.phase.kind !== 'live' || now.stream !== started.stream) return; if (text !== '') session.input({ kind: 'text', text }); }, () => undefined, @@ -207,7 +220,7 @@ export function BrowserPaneView({ type="button" className="browser-toolbar-button browser-driver" data-driver="human" - title="You are driving; agents' browser actions wait. Hand the tab back to them." + title="You are driving: agents' page actions are refused until you hand the tab back or close this pane." onClick={() => { session.setHumanDriving(false); }} @@ -220,7 +233,7 @@ export function BrowserPaneView({ type="button" className="browser-toolbar-button browser-driver" data-driver="agent" - title="Stop agents from acting in this tab until you hand it back." + title="Take the tab from agents: their page actions are refused until you hand it back or close this pane." onClick={() => { session.setHumanDriving(true); }} @@ -319,7 +332,7 @@ interface BrowserCanvasProps { * so a decode finishing in between still sees that its frame's stream has ended. */ liveStream: () => number; - /** The CSS viewport the frame shows. */ + /** The CSS viewport of the newest frame; input maps with it until a frame is drawn. */ cssSize: Size; onInput: (event: BrowserInputEvent) => void; onResize: (width: number, height: number, scale: number) => void; @@ -355,6 +368,11 @@ function BrowserCanvas({ const box = useRef(null); const lastHover = useRef(0); const drawnSeq = useRef(-1); + /** + * The CSS viewport of the frame on screen. A newer frame's size arrives before its + * picture decodes; until it draws, clicks land on the old picture, so they map with this. + */ + const drawnSize = useRef(null); /** Bumped when the tab closes or a new stream starts, so a decode started before it never draws. */ const epoch = useRef(0); /** The attach stream whose frames the canvas shows. */ @@ -423,6 +441,7 @@ function BrowserCanvas({ target?.getContext('2d')?.clearRect(0, 0, target.width, target.height); drawnSeq.current = -1; } + drawnSize.current = null; return; } const { seq, data } = frame; @@ -443,26 +462,33 @@ function BrowserCanvas({ if (seq < drawnSeq.current) return; // a newer frame is already on screen drawnSeq.current = seq; target.getContext('2d')?.drawImage(image, 0, 0, target.width, target.height); + drawnSize.current = { width: frame.width, height: frame.height }; }) .catch(() => undefined) .finally(() => { // Ack frames this stream sent once they are handled: drawn, superseded by a // newer drawn frame, or undecodable (unacked, it would pin one of only two // flow-control slots and stall the pane). A frame from before the tab closed - // or the stream changed belongs to an old stream and is never acked on the new one. - if (unmounted.current || startedIn !== epoch.current) return; + // or the stream changed belongs to an old stream and is never acked on the new one, + // and nothing is acked once the canvas is gone. + if (unmounted.current || canvas.current === null || startedIn !== epoch.current) return; if (frame.stream !== handlers.current.liveStream()) return; handlers.current.onDrawn(seq); }); }, [frame]); - useEffect(() => { + // A layout effect, so the flag flips as the canvas leaves the page, before passive + // cleanup: a decode settling in between neither draws nor acks. + useLayoutEffect(() => { unmounted.current = false; return () => { unmounted.current = true; }; }, []); + /** The page size input maps to: the picture on screen, else the newest frame's. */ + const pageSize = (): Size => drawnSize.current ?? cssSize; + const geometry = (clientX: number, clientY: number) => { const rect = box.current?.getBoundingClientRect(); const view = { width: rect?.width ?? 0, height: rect?.height ?? 0 }; @@ -501,22 +527,22 @@ function BrowserCanvas({ event.currentTarget.focus({ preventScroll: true }); onFocus(); const { view, input } = mouse(event); - onInput(mouseInput('down', input, view, cssSize)); + onInput(mouseInput('down', input, view, pageSize())); }} onMouseUp={(event) => { const { view, input } = mouse(event); - onInput(mouseInput('up', input, view, cssSize)); + onInput(mouseInput('up', input, view, pageSize())); }} onMouseMove={(event) => { const { view, input } = mouse(event); if ((event.buttons & 1) !== 0) { - onInput(mouseInput('move', { ...input, button: 0, detail: 0 }, view, cssSize)); + onInput(mouseInput('move', { ...input, button: 0, detail: 0 }, view, pageSize())); return; } const now = performance.now(); if (now - lastHover.current < HOVER_INTERVAL_MS) return; lastHover.current = now; - onInput(hoverInput(input, view, cssSize)); + onInput(hoverInput(input, view, pageSize())); }} onContextMenu={(event) => { event.preventDefault(); @@ -537,7 +563,7 @@ function BrowserCanvas({ shiftKey: event.shiftKey, }, view, - cssSize, + pageSize(), ), ); }} diff --git a/crates/pu-engine/src/browser/cdp.rs b/crates/pu-engine/src/browser/cdp.rs index 0a7a9688..6941b013 100644 --- a/crates/pu-engine/src/browser/cdp.rs +++ b/crates/pu-engine/src/browser/cdp.rs @@ -149,18 +149,33 @@ impl Cdp { // `biased`: the deadline is checked before every poll of the write, so a // command whose caller timed out is never started, however late the // writer gets to it. + // A connection the reader already closed takes nothing more: its callers + // were told `Closed`, so nothing may be sent for them afterwards. + let closed = writer_shared.closed.notified(); + tokio::pin!(closed); + closed.as_mut().enable(); + if !writer_shared.alive.load(Ordering::SeqCst) { + break; + } let first = tokio::select! { biased; + () = &mut closed => break, () = tokio::time::sleep_until(message.deadline) => continue, written = writer.write(&message.bytes) => match written { Ok(0) | Err(_) => break, Ok(n) => n, }, }; - if writer.write_all(&message.bytes[first..]).await.is_err() - || writer.flush().await.is_err() - { - break; + // The rest of a started command is bounded too: a browser that stops + // reading mid-command is unusable (the pipe holds half a message), so + // the connection ends instead of hanging this writer. + let rest = async { + writer.write_all(&message.bytes[first..]).await?; + writer.flush().await + }; + match tokio::time::timeout(CALL_TIMEOUT, rest).await { + Ok(Ok(())) => {} + Ok(Err(_)) | Err(_) => break, } } // The browser stopped taking commands: nothing sent from now on will be @@ -588,10 +603,24 @@ mod tests { let gate = Gate::default(); let (_browser_out, client_in) = duplex(4096); let cdp = Cdp::start(client_in, gate.clone()); - // The writer takes this command at once and waits on the full pipe. + // The writer takes this command at once and waits on the full pipe; the + // deadline passes while that write is blocked, not while it is queued. + let late = tokio::spawn({ + let cdp = cdp.clone(); + async move { + cdp.call_within(Duration::from_millis(300), None, "Late.click", json!({})) + .await + } + }); + tokio::time::timeout(FIXTURE_WAIT, async { + while gate.0.lock().unwrap().1.is_none() { + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .expect("the writer is blocked on the command's first write"); assert_eq!( - cdp.call_within(Duration::from_millis(50), None, "Late.click", json!({})) - .await, + late.await.unwrap(), Err(CdpError::Timeout("Late.click".into())) ); cdp.send(None, "Later.ok", json!({})); @@ -615,4 +644,36 @@ mod tests { assert!(written.contains("Later.ok"), "{written}"); assert!(!written.contains("Late.click"), "{written}"); } + + #[tokio::test] + async fn given_the_browser_closes_while_a_write_waits_should_never_send_it() { + let gate = Gate::default(); + let (browser_out, client_in) = duplex(4096); + let cdp = Cdp::start(client_in, gate.clone()); + let call = tokio::spawn({ + let cdp = cdp.clone(); + async move { cdp.call(None, "Orphan.click", json!({})).await } + }); + tokio::time::timeout(FIXTURE_WAIT, async { + while gate.0.lock().unwrap().1.is_none() { + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .expect("the writer is blocked on the command"); + // The browser's output closes: the caller is told `Closed` at once... + drop(browser_out); + assert_eq!(call.await.unwrap(), Err(CdpError::Closed)); + // ...and its command is not sent when the pipe takes bytes again. + let waker = { + let mut state = gate.0.lock().unwrap(); + state.0 = true; + state.1.take() + }; + if let Some(waker) = waker { + waker.wake(); + } + tokio::time::sleep(Duration::from_millis(50)).await; + assert!(gate.0.lock().unwrap().2.is_empty()); + } } diff --git a/crates/pu-engine/src/browser/launch.rs b/crates/pu-engine/src/browser/launch.rs index 34915200..96644def 100644 --- a/crates/pu-engine/src/browser/launch.rs +++ b/crates/pu-engine/src/browser/launch.rs @@ -88,28 +88,31 @@ fn is_executable(path: &Path) -> bool { } } -/// The command-line flags for a headless, pipe-driven browser on `profile`. -pub fn args(profile: &Path, as_root: bool) -> Vec { - let mut args = vec![ - "--headless=new".to_string(), - "--remote-debugging-pipe".to_string(), - format!("--user-data-dir={}", profile.display()), - "--no-first-run".to_string(), - "--no-default-browser-check".to_string(), - "--disable-background-networking".to_string(), - "--disable-features=Translate,MediaRouter,OptimizationHints".to_string(), - "--mute-audio".to_string(), - format!("--window-size={DEFAULT_WIDTH},{DEFAULT_HEIGHT}"), +/// The command-line flags for a headless, pipe-driven browser on `profile`. As +/// `OsString`s, so a profile path that is not UTF-8 reaches Chromium unchanged. +pub fn args(profile: &Path, as_root: bool) -> Vec { + let mut user_data_dir = std::ffi::OsString::from("--user-data-dir="); + user_data_dir.push(profile.as_os_str()); + let mut args: Vec = vec![ + "--headless=new".into(), + "--remote-debugging-pipe".into(), + user_data_dir, + "--no-first-run".into(), + "--no-default-browser-check".into(), + "--disable-background-networking".into(), + "--disable-features=Translate,MediaRouter,OptimizationHints".into(), + "--mute-audio".into(), + format!("--window-size={DEFAULT_WIDTH},{DEFAULT_HEIGHT}").into(), // Screencast frames are captured at the browser's own scale, not the emulated one, so // without this a Retina pane gets 1x frames. Each viewer's frames are still capped at // its own width x scale, so a 1x pane gets 1x frames. - format!("--force-device-scale-factor={CAPTURE_SCALE}"), + format!("--force-device-scale-factor={CAPTURE_SCALE}").into(), ]; if as_root { // Chromium refuses to run its sandbox as root (containers, some servers). - args.push("--no-sandbox".to_string()); + args.push("--no-sandbox".into()); } - args.push("about:blank".to_string()); + args.push("about:blank".into()); args } @@ -184,7 +187,7 @@ pub mod unix { pub fn spawn( executable: &Path, - args: &[String], + args: &[std::ffi::OsString], log: Option<&Path>, ) -> std::io::Result { // Browser reads `to_browser_read` (fd 3), writes `from_browser_write` (fd 4). @@ -277,17 +280,18 @@ mod tests { #[test] fn given_root_should_disable_the_sandbox_and_always_use_the_pipe() { let profile = Path::new("/p"); + let has = |args: &[std::ffi::OsString], flag: &str| args.iter().any(|a| a == flag); let as_user = args(profile, false); - assert!(as_user.contains(&"--remote-debugging-pipe".to_string())); - assert!(as_user.contains(&"--user-data-dir=/p".to_string())); - assert!(as_user.contains(&"--force-device-scale-factor=2".to_string())); + assert!(has(&as_user, "--remote-debugging-pipe")); + assert!(has(&as_user, "--user-data-dir=/p")); + assert!(has(&as_user, "--force-device-scale-factor=2")); assert!( !as_user .iter() - .any(|a| a.starts_with("--remote-debugging-port")) + .any(|a| a.to_string_lossy().starts_with("--remote-debugging-port")) ); - assert!(!as_user.contains(&"--no-sandbox".to_string())); - assert!(args(profile, true).contains(&"--no-sandbox".to_string())); + assert!(!has(&as_user, "--no-sandbox")); + assert!(has(&args(profile, true), "--no-sandbox")); } #[test] diff --git a/crates/pu-engine/src/browser/mod.rs b/crates/pu-engine/src/browser/mod.rs index 428ddb9b..918b7d7b 100644 --- a/crates/pu-engine/src/browser/mod.rs +++ b/crates/pu-engine/src/browser/mod.rs @@ -384,6 +384,9 @@ async fn apply_viewport(cdp: &Cdp, tab: &Tab, viewport: Viewport) -> Result<()> } async fn refresh_history(cdp: &Cdp, tab: &Tab) { + // Refreshes run concurrently (after navigations and after load events): only the + // latest one started may publish, so an older reply never overwrites a newer one. + let revision = tab.begin_history_refresh(); let Ok(history) = cdp .call( Some(&tab.session_id), @@ -402,7 +405,7 @@ async fn refresh_history(cdp: &Cdp, tab: &Tab) { .get("entries") .and_then(Value::as_array) .map_or(0, |e| e.len() as i64); - tab.set_history(index > 0, index + 1 < count); + tab.set_history_for(revision, index > 0, index + 1 < count); } /// Ends a browser's process group and waits (up to `wait`) for it to exit. @@ -478,6 +481,13 @@ pub struct BrowserManager { /// profile is not reused until it has exited. #[cfg_attr(not(unix), allow(dead_code))] lingering: Mutex>, + /// Profiles this daemon owns: an exclusive `flock` on each, taken before its + /// first launch and held until shutdown, so a second daemon (another socket, + /// same `~/.pu/browser`) can never start a browser on a profile in use here. + #[cfg_attr(not(unix), allow(dead_code))] + profile_locks: std::sync::Mutex>, + /// Set once shutdown starts: no startup may publish a browser after it. + closing: std::sync::atomic::AtomicBool, base_dir: Option, idle_stop: Duration, /// How long a stopped browser may take to exit before it counts as still running. @@ -501,6 +511,8 @@ impl BrowserManager { instances: Mutex::new(HashMap::new()), startups: Mutex::new(HashMap::new()), lingering: Mutex::new(HashMap::new()), + profile_locks: std::sync::Mutex::new(HashMap::new()), + closing: std::sync::atomic::AtomicBool::new(false), base_dir, idle_stop: IDLE_STOP, exit_wait: EXIT_WAIT, @@ -522,8 +534,45 @@ impl BrowserManager { } /// Stops every project's browser. + /// + /// Startups in flight are waited for (each holds its project's startup lock) and + /// may not publish once this has begun; every browser, including one an op still + /// holds, is stopped and waited for rather than just forgotten. pub async fn shutdown(&self) { - self.instances.lock().await.clear(); + self.closing + .store(true, std::sync::atomic::Ordering::SeqCst); + let startups: Vec<_> = self.startups.lock().await.values().cloned().collect(); + for startup in startups { + drop(startup.lock().await); + } + let instances: Vec<_> = self + .instances + .lock() + .await + .drain() + .map(|(_, i)| i) + .collect(); + for instance in instances { + instance.stop_and_wait(self.exit_wait).await; + } + let lingering: Vec<_> = self + .lingering + .lock() + .await + .drain() + .map(|(_, c)| c) + .collect(); + for child in lingering { + let _ = stop_child(None, Some(child), self.exit_wait).await; + } + self.profile_locks + .lock() + .unwrap_or_else(|e| e.into_inner()) + .clear(); + } + + fn closing_error() -> BrowserError { + BrowserError::new("BROWSER_SHUTTING_DOWN", "the daemon is shutting down") } /// The project's running browser. A dead one stays in the map: only @@ -557,6 +606,9 @@ impl BrowserManager { .or_default() .clone(); let _starting = startup.lock().await; + if self.closing.load(std::sync::atomic::Ordering::SeqCst) { + return Err(Self::closing_error()); + } let dead = { let mut instances = self.instances.lock().await; match instances.get(root) { @@ -582,6 +634,11 @@ impl BrowserManager { )); } let instance = self.launch(root).await?; + // Shutdown began while this browser started: it never becomes reachable. + if self.closing.load(std::sync::atomic::Ordering::SeqCst) { + instance.stop_and_wait(self.exit_wait).await; + return Err(Self::closing_error()); + } instance .pending_opens .fetch_add(1, std::sync::atomic::Ordering::SeqCst); @@ -673,6 +730,9 @@ impl BrowserManager { "the project's previous browser has not exited yet; try again shortly", )); } + // Another daemon's browser may be using this profile: only its owner may clear + // the singleton files (a live browser's lock must never be removed). + self.own_profile(root, &profile)?; // A daemon that was killed can leave the profile's singleton lock behind; // with it Chromium hands off to a browser that no longer exists and exits. for lock in ["SingletonLock", "SingletonSocket", "SingletonCookie"] { @@ -717,6 +777,37 @@ impl BrowserManager { Ok(instance) } + /// Takes (once per daemon) an exclusive lock on the project's profile, held until + /// shutdown. Refused while another process holds it; a lock left by a process that + /// died is released by the kernel, so a stale profile is still reclaimed. + #[cfg(unix)] + fn own_profile(&self, root: &str, profile: &Path) -> Result<()> { + use std::os::fd::AsRawFd; + let mut locks = self.profile_locks.lock().unwrap_or_else(|e| e.into_inner()); + if locks.contains_key(root) { + return Ok(()); + } + let path = profile.join(".pu-daemon.lock"); + let file = std::fs::OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .open(&path) + .map_err(|e| BrowserError::new("BROWSER_ERROR", format!("{}: {e}", path.display())))?; + // SAFETY: flock on a file descriptor this function owns. + if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } != 0 { + return Err(BrowserError::new( + "BROWSER_PROFILE_IN_USE", + format!( + "another PurePoint daemon is using this project's browser profile ({}); stop it or use its socket", + profile.display() + ), + )); + } + locks.insert(root.to_string(), file); + Ok(()) + } + /// The tab a new attach stream will show. Never starts the browser. pub async fn attach(&self, root: &str, tab_id: Option<&str>) -> Result<(Arc, Arc)> { let instance = self.running(root).await?; @@ -726,13 +817,35 @@ impl BrowserManager { } pub async fn handle(&self, root: &str, op: BrowserOp, caller: Caller) -> Response { - match self.run(root, op, caller).await { + match self.run(root, op, caller, None).await { Ok(response) => response, Err(error) => error.into_response(), } } - async fn run(&self, root: &str, op: BrowserOp, caller: Caller) -> Result { + /// A viewer stream's `resize`, applied only while the stream lives: `ended` is + /// checked once the tab's resize turn comes, so a pane that left while waiting + /// behind another pane's resize never sets the size for the panes that remain. + pub async fn resize_for_viewer( + &self, + root: &str, + op: BrowserOp, + ended: &std::sync::atomic::AtomicBool, + ) -> Response { + debug_assert!(matches!(op, BrowserOp::Resize { .. })); + match self.run(root, op, Caller::Viewer, Some(ended)).await { + Ok(response) => response, + Err(error) => error.into_response(), + } + } + + async fn run( + &self, + root: &str, + op: BrowserOp, + caller: Caller, + ended: Option<&std::sync::atomic::AtomicBool>, + ) -> Result { match op { BrowserOp::List => { let tabs = match self.existing(root).await { @@ -820,6 +933,10 @@ impl BrowserManager { Ok(Response::BrowserTab { tab: tab.info() }) } BrowserOp::Snapshot { .. } => { + // Refs continue one sequence per tab (e3 never comes back), so an agent's + // ref from an earlier snapshot of the same page cannot name a new element. + let _snapshotting = tab.lock_snapshot().await; + let first = tab.next_ref(); let mark = tab.document_mark(); let tree = cdp .call(session, "Accessibility.getFullAXTree", json!({})) @@ -829,15 +946,17 @@ impl BrowserManager { .and_then(Value::as_array) .cloned() .unwrap_or_default(); - let snapshot = snapshot::format(&nodes); + let snapshot = snapshot::format_from(&nodes, first); // The page may have navigated while the outline was built; its refs // would then point into a document that is gone. + let used = snapshot.refs.len(); let Some(info) = tab.store_refs_for(&mark, snapshot.refs) else { return Err(BrowserError::new( "BROWSER_PAGE_CHANGED", "the page navigated while it was read; take a new snapshot", )); }; + tab.advance_refs(used); Ok(Response::BrowserSnapshot { tab: info, tree: snapshot.tree, @@ -920,6 +1039,14 @@ impl BrowserManager { Ok(Response::BrowserTab { tab: tab.info() }) } BrowserOp::Control { driver, .. } => { + // Control belongs to a person at a pane: with no pane watching the tab, + // nobody could hand it back, so a human driver needs a viewer. + if driver == BrowserDriver::Human && !tab.has_viewers() { + return Err(BrowserError::new( + "BROWSER_NO_VIEWER", + "take control from a browser pane showing this tab", + )); + } tab.set_driver(driver); Ok(Response::BrowserTab { tab: tab.info() }) } @@ -945,9 +1072,18 @@ impl BrowserManager { // One resize at a time per tab, across all its viewers: check, apply // and record as one step, so the record matches what Chromium uses. let _resizing = tab.lock_resize().await; - if viewport != tab.viewport() { + if ended.is_some_and(|ended| ended.load(std::sync::atomic::Ordering::SeqCst)) { + return Ok(Response::Ok); + } + if !tab.viewport_is(viewport) { // Recorded only once Chromium accepts it, so a failed resize is retried. - apply_viewport(cdp, &tab, viewport).await?; + // A failure may still have applied part of it (a timeout after Chromium + // got the command): the record is then marked unknown, so the next + // request for any size, the recorded one included, is applied. + if let Err(error) = apply_viewport(cdp, &tab, viewport).await { + tab.viewport_unknown(); + return Err(error); + } tab.set_viewport(viewport); if tab.has_viewers() { // New frame bounds take effect on a fresh screencast. @@ -1052,7 +1188,11 @@ pub fn normalize_url(url: &str) -> String { return url.to_string(); } let host = url.split(['/', '?', '#']).next().unwrap_or(""); - let bare_host = host.rsplit_once(':').map_or(host, |(h, _)| h); + let bare_host = host + .rsplit_once(':') + .map_or(host, |(h, _)| h) + .to_ascii_lowercase(); + let bare_host = bare_host.as_str(); let local = bare_host == "localhost" || bare_host.ends_with(".localhost") || bare_host.ends_with(".local") @@ -1256,20 +1396,34 @@ async fn element_center(cdp: &Cdp, tab: &Tab, backend: i64) -> Result<(f64, f64) async fn click(cdp: &Cdp, tab: &Tab, page: &tab::DocumentMark, x: f64, y: f64) -> Result<()> { let session = Some(tab.session_id.as_str()); - for (kind, buttons) in [("mouseMoved", 0), ("mousePressed", 1), ("mouseReleased", 0)] { - // Checked before every event: never press on a page the element is not on - // (a release after a press still goes, so no button is left held down). - if kind != "mouseReleased" { - ensure_on(tab, page)?; - } + let mouse = |kind: &str, buttons: u32| { let button = if kind == "mouseMoved" { "none" } else { "left" }; - cdp.call( + json!({ "type": kind, "x": x, "y": y, "button": button, "buttons": buttons, "clickCount": 1 }) + }; + // Checked before the move and the press: never press on a page the element is + // not on. + ensure_on(tab, page)?; + cdp.call(session, "Input.dispatchMouseEvent", mouse("mouseMoved", 0)) + .await?; + ensure_on(tab, page)?; + let pressed = cdp + .call( session, "Input.dispatchMouseEvent", - json!({ "type": kind, "x": x, "y": y, "button": button, "buttons": buttons, "clickCount": 1 }), + mouse("mousePressed", 1), ) - .await?; - } + .await; + // The release is sent even after a failed press (it may have reached the page, + // say a timeout), so no button is left held down; the press's error is reported. + let released = cdp + .call( + session, + "Input.dispatchMouseEvent", + mouse("mouseReleased", 0), + ) + .await; + pressed?; + released?; Ok(()) } diff --git a/crates/pu-engine/src/browser/snapshot.rs b/crates/pu-engine/src/browser/snapshot.rs index edb4ae22..3646cdb0 100644 --- a/crates/pu-engine/src/browser/snapshot.rs +++ b/crates/pu-engine/src/browser/snapshot.rs @@ -55,6 +55,12 @@ pub struct Snapshot { } pub fn format(nodes: &[Value]) -> Snapshot { + format_from(nodes, 1) +} + +/// `format`, numbering refs from `e{first}`: a tab's snapshots continue one sequence, +/// so a ref from an earlier snapshot never names an element of a later one. +pub fn format_from(nodes: &[Value], first: usize) -> Snapshot { let by_id: HashMap<&str, &Value> = nodes .iter() .filter_map(|n| Some((n.get("nodeId")?.as_str()?, n))) @@ -65,6 +71,7 @@ pub fn format(nodes: &[Value]) -> Snapshot { .or_else(|| nodes.first()); let mut out = Writer { by_id, + first_ref: first, snapshot: Snapshot::default(), lines: 0, truncated: false, @@ -82,6 +89,7 @@ pub fn format(nodes: &[Value]) -> Snapshot { struct Writer<'a> { by_id: HashMap<&'a str, &'a Value>, + first_ref: usize, snapshot: Snapshot, lines: usize, truncated: bool, @@ -171,7 +179,7 @@ impl<'a> Writer<'a> { if INTERACTIVE.contains(&role) && let Some(backend) = node.get("backendDOMNodeId").and_then(Value::as_i64) { - let reference = format!("e{}", self.snapshot.refs.len() + 1); + let reference = format!("e{}", self.first_ref + self.snapshot.refs.len()); line.push_str(&format!(" [ref={reference}]")); self.snapshot.refs.insert(reference, backend); } @@ -182,11 +190,11 @@ impl<'a> Writer<'a> { } /// A node's value as text: strings as they are, numbers (sliders, spinbuttons) printed. -fn ax_value(node: &Value) -> String { +fn ax_value(node: &Value) -> std::borrow::Cow<'_, str> { match node.get("value").and_then(|v| v.get("value")) { - Some(Value::String(s)) => s.clone(), - Some(Value::Number(n)) => n.to_string(), - _ => String::new(), + Some(Value::String(s)) => std::borrow::Cow::Borrowed(s), + Some(Value::Number(n)) => std::borrow::Cow::Owned(n.to_string()), + _ => std::borrow::Cow::Borrowed(""), } } @@ -225,22 +233,22 @@ fn states(node: &Value) -> Vec { } fn clip(text: &str) -> String { - let single: String = text - .chars() - .map(|c| if c.is_control() { ' ' } else { c }) - .collect(); - // Cut first, then escape, so an escape is never split. - let (cut, clipped) = if single.chars().count() <= MAX_NAME { - (single, false) - } else { - (single.chars().take(MAX_NAME).collect(), true) - }; - let escaped = cut.replace('\\', "\\\\").replace('"', "\\\""); - if clipped { - format!("{escaped}…") - } else { - escaped + // One pass over at most MAX_NAME + 1 characters: the rest of a long name is never + // read. Cut first, then escape, so an escape is never split. + let mut chars = text.chars(); + let mut out = String::with_capacity(text.len().min(MAX_NAME * 2)); + for c in chars.by_ref().take(MAX_NAME) { + match c { + '\\' => out.push_str("\\\\"), + '"' => out.push_str("\\\""), + c if c.is_control() => out.push(' '), + c => out.push(c), + } + } + if chars.next().is_some() { + out.push('…'); } + out } #[cfg(test)] @@ -384,6 +392,19 @@ mod tests { ); } + #[test] + fn given_a_first_ref_number_should_continue_the_sequence() { + let nodes = vec![ + node("1", None, "RootWebArea", "", &["2", "3"]), + node("2", Some("1"), "link", "A", &[]), + node("3", Some("1"), "button", "B", &[]), + ]; + let snapshot = format_from(&nodes, 7); + assert!(snapshot.tree.contains("[ref=e7]") && snapshot.tree.contains("[ref=e8]")); + assert_eq!(snapshot.refs.get("e7"), Some(&102)); + assert!(!snapshot.refs.contains_key("e1")); + } + #[test] fn given_no_nodes_should_return_an_empty_outline() { let snapshot = format(&[]); diff --git a/crates/pu-engine/src/browser/tab.rs b/crates/pu-engine/src/browser/tab.rs index bcb4a536..b721c545 100644 --- a/crates/pu-engine/src/browser/tab.rs +++ b/crates/pu-engine/src/browser/tab.rs @@ -67,6 +67,16 @@ pub struct Tab { /// Held while a resize is checked, applied and recorded, across every viewer /// stream of the tab, so the recorded viewport is the one Chromium last accepted. resizing: tokio::sync::Mutex<()>, + /// Held while a snapshot is taken and its refs stored, so ref numbers are + /// handed out in order. + snapshotting: tokio::sync::Mutex<()>, + /// The number the next snapshot's first ref gets. + next_ref: AtomicU64, + /// Bumped as each history refresh starts: only the latest may publish. + history: AtomicU64, + /// Whether the recorded viewport is known to be the one Chromium uses (false + /// after a resize failed partway, so the next one is applied, not skipped). + viewport_confirmed: std::sync::atomic::AtomicBool, } impl Tab { @@ -96,6 +106,10 @@ impl Tab { document: AtomicU64::new(0), navigation: AtomicU64::new(0), resizing: tokio::sync::Mutex::new(()), + snapshotting: tokio::sync::Mutex::new(()), + next_ref: AtomicU64::new(1), + history: AtomicU64::new(0), + viewport_confirmed: std::sync::atomic::AtomicBool::new(true), } } @@ -140,6 +154,7 @@ impl Tab { } pub fn set_viewport(&self, viewport: Viewport) { + self.viewport_confirmed.store(true, Ordering::SeqCst); *self.viewport.lock().unwrap_or_else(|e| e.into_inner()) = viewport; self.info.send_if_modified(|info| { let changed = info.width != viewport.width || info.height != viewport.height; @@ -149,6 +164,27 @@ impl Tab { }); } + pub fn begin_history_refresh(&self) -> u64 { + self.history.fetch_add(1, Ordering::SeqCst) + 1 + } + + /// `set_history` for refresh `revision`, ignored once a later refresh started. + pub fn set_history_for(&self, revision: u64, can_go_back: bool, can_go_forward: bool) { + if self.history.load(Ordering::SeqCst) == revision { + self.set_history(can_go_back, can_go_forward); + } + } + + /// Whether `viewport` is what Chromium is known to use now. + pub fn viewport_is(&self, viewport: Viewport) -> bool { + self.viewport_confirmed.load(Ordering::SeqCst) && self.viewport() == viewport + } + + /// A resize failed partway: Chromium's viewport is unknown until the next one. + pub fn viewport_unknown(&self) { + self.viewport_confirmed.store(false, Ordering::SeqCst); + } + pub fn set_history(&self, can_go_back: bool, can_go_forward: bool) { self.info.send_if_modified(|info| { let changed = info.can_go_back != can_go_back || info.can_go_forward != can_go_forward; @@ -294,6 +330,20 @@ impl Tab { self.set_page_locked(&mut refs, url, title); } + /// Serializes this tab's snapshots; with the guard held, `next_ref` is this + /// snapshot's first number and `advance_refs` reserves the ones it used. + pub async fn lock_snapshot(&self) -> tokio::sync::MutexGuard<'_, ()> { + self.snapshotting.lock().await + } + + pub fn next_ref(&self) -> usize { + self.next_ref.load(Ordering::SeqCst) as usize + } + + pub fn advance_refs(&self, used: usize) { + self.next_ref.fetch_add(used as u64, Ordering::SeqCst); + } + /// Serializes this tab's resizes (see the `resizing` field). pub async fn lock_resize(&self) -> tokio::sync::MutexGuard<'_, ()> { self.resizing.lock().await @@ -387,8 +437,11 @@ impl Tab { return false; }; // A frame of a cast that ended (its last viewer left) arriving late must - // not become the cached frame a later viewer is shown first. - if !self.has_viewers() { + // not become the cached frame a later viewer is shown first. Checked and + // published under the viewers lock, which `remove_viewer` holds while it + // clears the cache, so the two can never interleave. + let viewers = self.viewers.lock().unwrap_or_else(|e| e.into_inner()); + if *viewers == 0 { return false; } let metadata = params.get("metadata"); @@ -799,6 +852,33 @@ mod tests { assert!(tab.subscribe_frames().borrow().is_none()); } + #[test] + fn given_an_older_history_refresh_replying_late_should_keep_the_newer_state() { + let tab = tab(); + let older = tab.begin_history_refresh(); + let newer = tab.begin_history_refresh(); + tab.set_history_for(newer, true, false); + tab.set_history_for(older, false, true); + let info = tab.info(); + assert!(info.can_go_back && !info.can_go_forward); + } + + #[test] + fn given_a_resize_that_failed_partway_should_not_skip_the_recorded_size() { + let tab = tab(); + let size = Viewport { + width: 800, + height: 600, + scale: 2.0, + }; + tab.set_viewport(size); + assert!(tab.viewport_is(size)); + tab.viewport_unknown(); + assert!(!tab.viewport_is(size)); + tab.set_viewport(size); + assert!(tab.viewport_is(size)); + } + #[test] fn given_ref_spellings_should_resolve_the_same_element() { let tab = tab(); diff --git a/crates/pu-engine/src/ipc_server/mod.rs b/crates/pu-engine/src/ipc_server/mod.rs index de82bf16..5945d104 100644 --- a/crates/pu-engine/src/ipc_server/mod.rs +++ b/crates/pu-engine/src/ipc_server/mod.rs @@ -15,6 +15,9 @@ const ATTACH_OUTPUT_CHUNK_SIZE: usize = 64 * 1024; /// How long a new connection may take to send its first complete request. /// Streams and request loops have no idle limit once a request has arrived. const FIRST_LINE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30); +/// How long a client gets to take the reply to a browser `open` before the tab +/// it opened is closed again rather than left behind. +const OPEN_REPLY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(20); use crate::engine::Engine; use pu_core::protocol::{Request, Response}; @@ -315,9 +318,21 @@ impl IpcServer { } else { engine.handle_prepared_request(request).await }; - if !matches!(stream_mode, StreamMode::Attach(..)) - && write_response(writer, &response).await.is_err() - { + // A tab this request opened belongs to whoever reads the reply. A client that + // stops reading must not hold it open: its write is bounded, and on failure + // or timeout the tab is closed again. + let written = if matches!(stream_mode, StreamMode::Attach(..)) { + Ok(()) + } else if opened_browser_in.is_some() { + match tokio::time::timeout(OPEN_REPLY_TIMEOUT, write_response(writer, &response)).await + { + Ok(written) => written.map_err(|_| ()), + Err(_) => Err(()), + } + } else { + write_response(writer, &response).await.map_err(|_| ()) + }; + if written.is_err() { if let (Some(root), Response::BrowserTab { tab }) = (&opened_browser_in, &response) { let close = pu_core::protocol::BrowserOp::Close { tab_id: Some(tab.tab_id.clone()), diff --git a/crates/pu-engine/src/ipc_server/streams.rs b/crates/pu-engine/src/ipc_server/streams.rs index 06f315cd..fe4f29a3 100644 --- a/crates/pu-engine/src/ipc_server/streams.rs +++ b/crates/pu-engine/src/ipc_server/streams.rs @@ -582,6 +582,17 @@ async fn write_bounded(writer: &mut IpcWriter, response: &Response) -> std::io:: /// replace undrawn ones, so a slow link drops frames instead of queueing them. const BROWSER_FRAMES_IN_FLIGHT: usize = 2; +/// Ops (navigate, snapshot, click, …) one viewer stream may have running or +/// waiting to be written at once. Beyond it they are refused with `BROWSER_BUSY`. +const BROWSER_OPS_OUTSTANDING: usize = 8; + +fn stream_refusal(code: &str, message: impl Into) -> Response { + Response::Error { + code: code.into(), + message: message.into(), + } +} + /// Browser pane stream: frames and tab state out, viewer ops in. Ops on the /// stream act as the person at the pane (`Caller::Viewer`) and default to the /// attached tab. Input, resize and frame acks are answered only on error; @@ -634,10 +645,17 @@ async fn browser_stream_loop( // pane taking control, say) must not wait for the next one to show. info.mark_changed(); let mut in_flight: VecDeque = VecDeque::new(); - let (replies_tx, mut replies_rx) = tokio::sync::mpsc::unbounded_channel::(); - // Resizes wait on Chromium; they run in order beside the stream so frames, - // input and acks keep flowing, and report only failures. - let (resizes_tx, mut resizes_rx) = tokio::sync::mpsc::unbounded_channel::(); + // Replies carry the permit of the op that made them, so an op counts against + // BROWSER_OPS_OUTSTANDING until its reply is written, not just until it ran. + let (replies_tx, mut replies_rx) = tokio::sync::mpsc::unbounded_channel::<( + Response, + Option, + )>(); + let ops = std::sync::Arc::new(tokio::sync::Semaphore::new(BROWSER_OPS_OUTSTANDING)); + // Resizes wait on Chromium; they run beside the stream so frames, input and + // acks keep flowing, and report only failures. The slot holds only the newest + // size: older ones are stale, and a viewer cannot queue them without bound. + let (resize_tx, mut resize_rx) = tokio::sync::watch::channel::>(None); // Set when this stream ends, however it returns: the worker then starts no more // resizes for a viewer that has left (one already waiting on Chromium finishes). let ended = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); @@ -654,16 +672,16 @@ async fn browser_stream_loop( let replies = replies_tx.clone(); let ended = ended.clone(); tokio::spawn(async move { - while let Some(mut op) = resizes_rx.recv().await { - // Only the newest waiting size matters; older ones are already stale. - while let Ok(newer) = resizes_rx.try_recv() { - op = newer; - } + while resize_rx.changed().await.is_ok() { + let Some(op) = resize_rx.borrow_and_update().clone() else { + continue; + }; if ended.load(std::sync::atomic::Ordering::SeqCst) { break; } - let resp = browsers.handle(&root, op, Caller::Viewer).await; - if matches!(resp, Response::Error { .. }) && replies.send(resp).is_err() { + // Rechecked once the tab's resize turn comes (another pane's may run first). + let resp = browsers.resize_for_viewer(&root, op, &ended).await; + if matches!(resp, Response::Error { .. }) && replies.send((resp, None)).is_err() { break; } } @@ -713,8 +731,10 @@ async fn browser_stream_loop( return write_bounded(writer, &closed_response()).await.is_ok(); } } - Some(reply) = replies_rx.recv() => { - if write_bounded(writer, &reply).await.is_err() { + Some((reply, permit)) = replies_rx.recv() => { + let written = write_bounded(writer, &reply).await; + drop(permit); + if written.is_err() { return false; } } @@ -737,15 +757,24 @@ async fn browser_stream_loop( let Some(Request::Browser { mut op, .. }) = parse_stream_request(&line) else { break; }; - op.default_tab(&tab_id); - // The pane's own ops act on the tab it is attached to, whatever tab id - // they name: a pane can never take control of (or type into) another tab. - if let BrowserOp::Control { tab_id: target, .. } - | BrowserOp::Input { tab_id: target, .. } - | BrowserOp::Resize { tab_id: target, .. } = &mut op - { - *target = Some(tab_id.clone()); + // A pane's stream is scoped to the tab it attached to: it cannot open + // tabs, and an op naming another tab is refused, so a pane can never + // drive, type into or take control of a tab it is not showing. + if matches!(op, BrowserOp::Open { .. }) { + let refused = stream_refusal("BROWSER_NOT_ON_STREAM", "open a tab with a plain browser request, then attach to it"); + if write_bounded(writer, &refused).await.is_err() { + return false; + } + continue; } + if op.tab_id().is_some_and(|named| named != tab_id) { + let refused = stream_refusal("BROWSER_OTHER_TAB", format!("this stream is attached to tab {tab_id}")); + if write_bounded(writer, &refused).await.is_err() { + return false; + } + continue; + } + op.default_tab(&tab_id); if let BrowserOp::FrameAck { seq, .. } = op { while in_flight.front().is_some_and(|sent| *sent <= seq) { in_flight.pop_front(); @@ -753,7 +782,7 @@ async fn browser_stream_loop( continue; } if matches!(op, BrowserOp::Resize { .. }) { - let _ = resizes_tx.send(op); + resize_tx.send_replace(Some(op)); continue; } // Control only flips the driver; run it here, in stream order, so it @@ -774,11 +803,21 @@ async fn browser_stream_loop( } continue; } + // Acks, input and teardown never wait on this cap; only ops that + // answer with a reply do, and past it the viewer is told to wait. + let Ok(permit) = ops.clone().try_acquire_owned() else { + let refused = stream_refusal("BROWSER_BUSY", "too many browser requests are waiting on this stream; retry when one finishes"); + if write_bounded(writer, &refused).await.is_err() { + return false; + } + continue; + }; let browsers = browsers.clone(); let root = project_root.to_string(); let replies = replies_tx.clone(); tokio::spawn(async move { - let _ = replies.send(browsers.handle(&root, op, Caller::Viewer).await); + let resp = browsers.handle(&root, op, Caller::Viewer).await; + let _ = replies.send((resp, Some(permit))); }); } } diff --git a/crates/pu-engine/tests/browser.rs b/crates/pu-engine/tests/browser.rs index 81725883..9643cfaf 100644 --- a/crates/pu-engine/tests/browser.rs +++ b/crates/pu-engine/tests/browser.rs @@ -114,6 +114,20 @@ async fn driver_of(agent: &mut Client, root: &str) -> BrowserDriver { } } +async fn snapshot_tree(manager: &pu_engine::browser::BrowserManager) -> String { + match manager + .handle( + "/p", + BrowserOp::Snapshot { tab_id: None }, + pu_engine::browser::Caller::Agent, + ) + .await + { + Response::BrowserSnapshot { tree, .. } => tree, + other => panic!("snapshot: {other:?}"), + } +} + fn browser(root: &str, op: BrowserOp) -> Request { Request::Browser { project_root: root.to_string(), @@ -787,6 +801,18 @@ async fn given_a_disabled_target_should_refuse_to_type_rather_than_type_elsewher Caller::Agent, ) .await; + // The setup holds: the enabled field has focus before typing is tried elsewhere. + match manager + .handle( + "/p", + eval("document.activeElement && document.activeElement.id"), + Caller::Agent, + ) + .await + { + Response::BrowserEvalResult { value, .. } => assert_eq!(value, serde_json::json!("a")), + other => panic!("eval: {other:?}"), + } let tree = match manager .handle("/p", BrowserOp::Snapshot { tab_id: None }, Caller::Agent) .await @@ -831,3 +857,237 @@ async fn given_a_disabled_target_should_refuse_to_type_rather_than_type_elsewher } manager.shutdown().await; } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn given_a_ref_from_an_earlier_snapshot_of_the_same_page_should_refuse_it() { + if !have_browser() { + eprintln!("skipping: no Chrome/Chromium on this machine (set PU_BROWSER)"); + return; + } + use pu_engine::browser::{BrowserManager, Caller}; + let tmp = TempDir::new().unwrap(); + let manager = BrowserManager::new(Some(tmp.path().join("browser"))); + let page = "data:text/html,"; + assert!(matches!( + manager + .handle( + "/p", + BrowserOp::Open { + url: Some(page.into()) + }, + Caller::Agent + ) + .await, + Response::BrowserTab { .. } + )); + let first = snapshot_tree(&manager).await; + assert!(first.contains("[ref=e1]"), "{first}"); + let second = snapshot_tree(&manager).await; + // The same page again: new numbers, so the old e1 names nothing now. + assert!(!second.contains("[ref=e1]"), "{second}"); + let clicked = manager + .handle( + "/p", + BrowserOp::Click { + tab_id: None, + element: "e1".into(), + }, + Caller::Agent, + ) + .await; + assert!( + matches!(&clicked, Response::Error { code, .. } if code == "BROWSER_REF_NOT_FOUND"), + "{clicked:?}" + ); + manager.shutdown().await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn given_no_pane_watching_should_refuse_to_hand_the_tab_to_a_person() { + if !have_browser() { + eprintln!("skipping: no Chrome/Chromium on this machine (set PU_BROWSER)"); + return; + } + use pu_engine::browser::{BrowserManager, Caller}; + let tmp = TempDir::new().unwrap(); + let manager = BrowserManager::new(Some(tmp.path().join("browser"))); + assert!(matches!( + manager + .handle( + "/p", + BrowserOp::Open { + url: Some("about:blank".into()) + }, + Caller::Agent + ) + .await, + Response::BrowserTab { .. } + )); + // Nobody could hand it back: agents would be locked out. + let refused = manager + .handle( + "/p", + BrowserOp::Control { + tab_id: None, + driver: BrowserDriver::Human, + }, + Caller::Agent, + ) + .await; + assert!( + matches!(&refused, Response::Error { code, .. } if code == "BROWSER_NO_VIEWER"), + "{refused:?}" + ); + manager.shutdown().await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn given_a_pane_stream_should_act_only_on_the_tab_it_attached_to() { + if !have_browser() { + eprintln!("skipping: no Chrome/Chromium on this machine (set PU_BROWSER)"); + return; + } + let tmp = TempDir::new().unwrap(); + let sock = tmp.path().join("daemon.sock"); + let project = tmp.path().join("app"); + std::fs::create_dir_all(&project).unwrap(); + let engine = pu_engine::engine::Engine::new().with_browser_dir(tmp.path().join("browser")); + let server = pu_engine::ipc_server::IpcServer::bind(&sock, engine).unwrap(); + let engine = server.engine().clone(); + tokio::spawn(async move { server.run().await.ok() }); + let root = pu_core::canon::canonicalize(&project) + .unwrap() + .to_string_lossy() + .into_owned(); + let mut agent = Client::connect(&sock).await; + let mut open = async || match agent + .call(&browser( + &root, + BrowserOp::Open { + url: Some("about:blank".into()), + }, + )) + .await + { + Response::BrowserTab { tab } => tab, + other => panic!("open: {other:?}"), + }; + let shown = open().await; + let other = open().await; + + let mut viewer = Client::connect(&sock).await; + assert!(matches!( + viewer + .call(&Request::BrowserAttach { + project_root: root.clone(), + tab_id: Some(shown.tab_id.clone()), + }) + .await, + Response::BrowserAttached { .. } + )); + // The pane's replies, past the frames and state the stream also carries. + async fn reply(viewer: &mut Client) -> Response { + loop { + match viewer.read().await { + Response::BrowserFrame { .. } | Response::BrowserTabState { .. } => continue, + other => return other, + } + } + } + + // Driving another tab is refused, and the other tab is untouched. + viewer + .write(&browser( + &root, + BrowserOp::Close { + tab_id: Some(other.tab_id.clone()), + }, + )) + .await; + let refused = reply(&mut viewer).await; + assert!( + matches!(&refused, Response::Error { code, .. } if code == "BROWSER_OTHER_TAB"), + "{refused:?}" + ); + // So is opening a tab from the pane's stream. + viewer + .write(&browser(&root, BrowserOp::Open { url: None })) + .await; + let refused = reply(&mut viewer).await; + assert!( + matches!(&refused, Response::Error { code, .. } if code == "BROWSER_NOT_ON_STREAM"), + "{refused:?}" + ); + match agent.call(&browser(&root, BrowserOp::List)).await { + Response::BrowserTabs { tabs } => assert_eq!(tabs.len(), 2, "{tabs:?}"), + other => panic!("list: {other:?}"), + } + + // Its own tab, named or not, still answers. + viewer + .write(&browser( + &root, + BrowserOp::Snapshot { + tab_id: Some(shown.tab_id.clone()), + }, + )) + .await; + let answered = reply(&mut viewer).await; + assert!( + matches!(&answered, Response::BrowserSnapshot { .. }), + "{answered:?}" + ); + engine.kill_all_sessions(Duration::from_millis(10)).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn given_a_pane_that_left_before_its_resize_turn_should_leave_the_size_alone() { + if !have_browser() { + eprintln!("skipping: no Chrome/Chromium on this machine (set PU_BROWSER)"); + return; + } + use pu_engine::browser::{BrowserManager, Caller}; + use std::sync::atomic::AtomicBool; + let tmp = TempDir::new().unwrap(); + let manager = BrowserManager::new(Some(tmp.path().join("browser"))); + let size = async |manager: &BrowserManager| match manager + .handle("/p", BrowserOp::List, Caller::Agent) + .await + { + Response::BrowserTabs { tabs } => (tabs[0].width, tabs[0].height), + other => panic!("list: {other:?}"), + }; + assert!(matches!( + manager + .handle( + "/p", + BrowserOp::Open { + url: Some("about:blank".into()) + }, + Caller::Agent + ) + .await, + Response::BrowserTab { .. } + )); + let resize = |width| BrowserOp::Resize { + tab_id: None, + width, + height: 500, + scale: 1.0, + }; + // A live pane's resize applies... + let live = AtomicBool::new(false); + assert!(matches!( + manager.resize_for_viewer("/p", resize(700), &live).await, + Response::Ok + )); + assert_eq!(size(&manager).await, (700, 500)); + // ...one whose stream ended before its turn does not. + let ended = AtomicBool::new(true); + assert!(matches!( + manager.resize_for_viewer("/p", resize(900), &ended).await, + Response::Ok + )); + assert_eq!(size(&manager).await, (700, 500)); + manager.shutdown().await; +} diff --git a/crates/pu-engine/tests/browser_launch.rs b/crates/pu-engine/tests/browser_launch.rs index 779f4f99..692aa30c 100644 --- a/crates/pu-engine/tests/browser_launch.rs +++ b/crates/pu-engine/tests/browser_launch.rs @@ -126,3 +126,39 @@ async fn given_a_failed_browser_whose_exit_is_not_confirmed_should_not_relaunch_ "the retry started another browser on the profile" ); } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn given_another_daemon_owns_the_profile_should_refuse_to_touch_it() { + let _env = BROWSER_ENV.lock().await; + let tmp = TempDir::new().unwrap(); + hung_browser(tmp.path()); + let base = tmp.path().join("browser"); + // Two daemons (different sockets) sharing one `~/.pu/browser`. + let first = BrowserManager::new(Some(base.clone())); + let second = BrowserManager::new(Some(base.clone())); + // The first takes the profile (its stand-in browser then fails to answer). + let opened = open(&first).await; + assert!( + matches!(&opened, Response::Error { code, .. } if code == "BROWSER_LAUNCH_FAILED"), + "{opened:?}" + ); + let lock = base + .join("profiles") + .join(pu_engine::browser::launch::profile_key("/p")) + .join("SingletonLock"); + std::fs::write(&lock, "first daemon's browser").unwrap(); + // The second is refused before it removes the first's singleton files. + let refused = open(&second).await; + assert!( + matches!(&refused, Response::Error { code, .. } if code == "BROWSER_PROFILE_IN_USE"), + "{refused:?}" + ); + assert!(lock.exists()); + // Once the first daemon is gone the profile is free again. + first.shutdown().await; + let retried = open(&second).await; + assert!( + matches!(&retried, Response::Error { code, .. } if code == "BROWSER_LAUNCH_FAILED"), + "{retried:?}" + ); +} diff --git a/docs/product/browser.md b/docs/product/browser.md index 48dc41a6..da7a743c 100644 --- a/docs/product/browser.md +++ b/docs/product/browser.md @@ -23,7 +23,7 @@ browser pane (Mac / iPad / Windows) ──────────┘ ▲ ## Research Notes -**Researched: 2026-11-29.** Chromium's DevTools protocol is available over `--remote-debugging-pipe`: the browser reads NUL-terminated JSON commands on fd 3 and writes replies and events on fd 4. Unlike `--remote-debugging-port`, this opens no TCP port, so no other local user or process can drive the browser; only the daemon holds the pipe ends, which keeps the daemon socket's same-user boundary (IPC-004, MACH-002). When the pipe closes (the daemon exits or is killed) Chromium exits. Flat session mode (`Target.attachToTarget {flatten: true}`) multiplexes every tab over the one pipe. `Page.startScreencast` emits JPEG frames only when the page changes, and waits for each `Page.screencastFrameAck` before the next. `Accessibility.getFullAXTree` gives a compact page outline whose nodes carry backend DOM ids, which `DOM.getContentQuads` / `DOM.resolveNode` turn back into click points and elements. Verified end to end against Chromium 1243 (`crates/pu-engine/tests/browser.rs`). +**Researched: 2026-11-29.** Chromium's DevTools protocol is available over `--remote-debugging-pipe`: the browser reads NUL-terminated JSON commands on fd 3 and writes replies and events on fd 4. Unlike `--remote-debugging-port`, this opens no TCP port, so no other local user or process can reach DevTools directly: only the daemon holds the pipe ends. That is a boundary on DevTools, not on the browser: any client the daemon accepts (the same user's `pu`, agents and panes, per IPC-004 and MACH-002) can drive the browser through the daemon's browser ops, by design. When the pipe closes (the daemon exits or is killed) Chromium exits. Flat session mode (`Target.attachToTarget {flatten: true}`) multiplexes every tab over the one pipe. `Page.startScreencast` emits JPEG frames only when the page changes, and waits for each `Page.screencastFrameAck` before the next. `Accessibility.getFullAXTree` gives a compact page outline whose nodes carry backend DOM ids, which `DOM.getContentQuads` / `DOM.resolveNode` turn back into click points and elements. Verified end to end against Chromium 1243 (`crates/pu-engine/tests/browser.rs`). Alternatives considered: - *Browser in the app, driven remotely by agents* (a WKWebView or WebView2 per pane, with agent commands relayed to the app): needs the app open for agents to browse, gives each viewer a different browser, and WKWebView has no DevTools protocol. Rejected. @@ -37,14 +37,15 @@ Alternatives considered: ! [BROWSER-003] The browser is found as `PU_BROWSER`, else Chrome, Chromium, Edge or Brave in their usual install locations and on `PATH`, else `~/.pu/browser/chrome/chrome`. PurePoint does not ship a browser. ! [BROWSER-004] Frames are JPEG (quality 70) at the viewer's pixel density (Chromium is started at `--force-device-scale-factor=2`, because its screencast captures at the browser's own scale, not the emulated one; each viewer's frames are capped at its width × scale), sent with ack-based flow control: at most two frames un-acknowledged per viewer, newer frames replacing undrawn ones, so a slow link drops frames instead of queueing them. ! [BROWSER-005] The viewport follows the pane: a viewer's `resize` sets the page's CSS viewport and device scale, so pages lay out for the pane and clicks map 1:1. With several viewers the last resize wins. -! [BROWSER-006] A person can take control of a tab (`driver: human`); agent ops that act on the page are refused with `BROWSER_HUMAN_DRIVING` until they hand it back, or until the last pane watching the tab closes or disconnects: control belongs to a person at a pane, so a closed pane never locks agents out. Viewer input is always accepted. -! [BROWSER-007] Agents address elements by `[ref=eN]` from the latest `snapshot`, an indented accessibility outline. Refs are invalidated by the next snapshot and by top-level navigation. +! [BROWSER-006] A person can take control of a tab (`driver: human`); agent ops that act on the page are refused with `BROWSER_HUMAN_DRIVING` until they hand it back, or until the last pane watching the tab closes or disconnects: control belongs to a person at a pane, so a closed pane never locks agents out. A `control` to `human` for a tab no pane is watching is refused with `BROWSER_NO_VIEWER`, whoever sends it. Viewer input is always accepted. +! [BROWSER-007] Agents address elements by `[ref=eN]` from the latest `snapshot`, an indented accessibility outline. Refs are invalidated by the next snapshot and by top-level navigation. Ref numbers continue across a tab's snapshots (a new snapshot never reuses an earlier `eN`), so a stale ref can never name a different element. ! [BROWSER-008] JavaScript dialogs are accepted automatically and recorded in the console, so neither agents nor viewers can be stuck behind one. ! [BROWSER-009] Pages opened by another page (`window.open`, `target=_blank`) become tabs of the project browser. ! [BROWSER-010] Closing the last pane tab that shows a browser tab closes that tab; closing a project's last tab stops its browser. -! [BROWSER-011] A remote agent's terminal links to loopback addresses (`localhost`, `*.localhost`, `127.0.0.1`, `0.0.0.0`, `[::1]`) open in a browser pane of that agent's project, because they name the agent's machine. A local agent's links open in the system browser as before. +! [BROWSER-011] A remote agent's terminal links to loopback addresses (`localhost`, `*.localhost`, `127.0.0.0/8`, `0.0.0.0`, `[::1]`) open in a browser pane of that agent's project, because they name the agent's machine. A local agent's links open in the system browser as before. ! [BROWSER-013] A project's browser that no op has used and no pane has watched for 30 minutes is stopped. Its panes reopen their last page when shown again, and agents open a new tab (`BROWSER_NO_TAB` tells them to). ! [BROWSER-012] The browser needs a Unix daemon (macOS or Linux). A Windows daemon answers `BROWSER_UNSUPPORTED`; the Windows app can still show browser panes for projects on Mac and Linux machines. +! [BROWSER-014] A pane's attach stream acts only on the tab it attached to: an op naming another tab is refused with `BROWSER_OTHER_TAB`, and `open` with `BROWSER_NOT_ON_STREAM` (a pane opens tabs with a plain `browser` request). At most 8 of a stream's replying ops (navigate, snapshot, click, …) may be running or waiting to be written; past that they are refused with `BROWSER_BUSY`. Acks, input and resizes are never refused, and only a stream's newest resize is applied. ## Requirements @@ -54,7 +55,7 @@ Alternatives considered: - REQ-BROWSER-003: Given `pu browser snapshot`, should print the page as an indented outline with `[ref=eN]` on links, buttons, fields and other interactive elements. - REQ-BROWSER-004: Given `pu browser click e3` after a snapshot, should scroll the element into view and click its center. - REQ-BROWSER-005: Given `pu browser type e5 "text"`, should focus the element, replace its contents with the text, and with `--submit` press Enter. -- REQ-BROWSER-006: Given a ref from before the latest snapshot or navigation, should fail with `BROWSER_REF_NOT_FOUND` and ask for a new snapshot. +- REQ-BROWSER-006: Given a ref from before the latest snapshot or navigation, should fail with `BROWSER_REF_NOT_FOUND` and ask for a new snapshot, even when the page is unchanged. - REQ-BROWSER-007: Given `pu browser wait --text "Saved"`, should succeed once the text is on the page, or fail with `BROWSER_TIMEOUT` after the timeout (default 10 s, max 120 s). - REQ-BROWSER-008: Given `pu browser screenshot [path]`, should save a PNG on the daemon's machine (a relative path resolves against the CLI's directory; with `--machine` it must be absolute) and print its path. - REQ-BROWSER-009: Given `pu browser console`, should print console messages, uncaught exceptions and dialogs since the tab opened, oldest first. @@ -76,6 +77,7 @@ Alternatives considered: - REQ-BROWSER-023: Given a project on a remote machine, should behave the same, running the browser on that machine. - REQ-BROWSER-024: Given `pu browser open --show` while the tab is already in a pane, should select that pane tab instead of opening another. - REQ-BROWSER-025: Given the pane is not on screen (another tab selected), should stop the screencast for it. +- REQ-BROWSER-026: Given an op on a pane's attach stream that names another tab, or an `open`, should refuse it and leave the other tab untouched. ## Sum Sheet diff --git a/docs/reference/ipc-api.md b/docs/reference/ipc-api.md index 1ef78736..bf33895e 100644 --- a/docs/reference/ipc-api.md +++ b/docs/reference/ipc-api.md @@ -492,7 +492,7 @@ Each project has a headless Chromium on the daemon's machine (`docs/product/brow A tab is `{tab_id, url, title, loading, driver, can_go_back, can_go_forward, width, height}`. Input events are tagged by `kind`: `mouse` `{action: down|up|move, x, y, button?: none|left|middle|right, click_count?, modifiers?}`, `wheel` `{x, y, dx, dy, modifiers?}`, `key` `{action: down|up, key, code?, text?, modifiers?}` and `text` `{text}`. Coordinates are CSS pixels; modifier bits are Alt=1, Ctrl=2, Meta=4, Shift=8. -Errors: `BROWSER_NOT_FOUND` (no Chrome/Chromium/Edge; set `PU_BROWSER`), `BROWSER_LAUNCH_FAILED`, `BROWSER_UNSUPPORTED` (Windows daemons), `BROWSER_NO_TAB`, `BROWSER_TAB_NOT_FOUND`, `BROWSER_REF_NOT_FOUND`, `BROWSER_NOT_VISIBLE`, `BROWSER_HUMAN_DRIVING` (a person drives the tab), `BROWSER_NAVIGATION_FAILED`, `BROWSER_EVAL_FAILED`, `BROWSER_TIMEOUT`, `BROWSER_INVALID_PATH`, `BROWSER_CLOSED`, `BROWSER_ERROR`. +Errors: `BROWSER_NOT_FOUND` (no Chrome/Chromium/Edge; set `PU_BROWSER`), `BROWSER_LAUNCH_FAILED`, `BROWSER_UNSUPPORTED` (Windows daemons), `BROWSER_NO_TAB`, `BROWSER_TAB_NOT_FOUND`, `BROWSER_REF_NOT_FOUND`, `BROWSER_NOT_VISIBLE`, `BROWSER_HUMAN_DRIVING` (a person drives the tab), `BROWSER_NAVIGATION_FAILED`, `BROWSER_EVAL_FAILED`, `BROWSER_TIMEOUT`, `BROWSER_INVALID_PATH`, `BROWSER_CLOSED`, `BROWSER_NO_VIEWER` (a `control` to `human` with no pane watching the tab), `BROWSER_PROFILE_IN_USE` (another daemon owns the project's browser profile), `BROWSER_SHUTTING_DOWN`, `BROWSER_ERROR`; on attach streams also `BROWSER_OTHER_TAB`, `BROWSER_NOT_ON_STREAM` and `BROWSER_BUSY`. ### BrowserAttach @@ -505,7 +505,7 @@ Watch and drive a tab, as a browser pane does. - `{"type": "browser_tab_state", "tab": {...}}` whenever the URL, title, loading state, history, driver or viewport changes. - `{"type": "browser_tab_closed", "tab_id"}`, after which the connection returns to request mode. -The client sends `browser` requests on the same connection. They act as the person at the pane (never refused for `BROWSER_HUMAN_DRIVING`) and default to the attached tab. `input`, `resize` and `frame_ack` are answered only on error; other ops run alongside the stream and their responses arrive between frames. Any line that is not a `browser` request ends the stream. Ops sent anywhere but an attach stream act as an agent. +The client sends `browser` requests on the same connection. They act as the person at the pane (never refused for `BROWSER_HUMAN_DRIVING`) and only on the attached tab: an op naming another tab is refused with `BROWSER_OTHER_TAB`, and `open` with `BROWSER_NOT_ON_STREAM`. `input`, `resize` and `frame_ack` are answered only on error, and only the newest waiting `resize` is applied; other ops run alongside the stream and their responses arrive between frames, at most 8 outstanding (running or waiting to be written) before further ones are refused with `BROWSER_BUSY`. Any line that is not a `browser` request ends the stream. Ops sent anywhere but an attach stream act as an agent. ## Worktree management From cd9ae941733873bae1ae5c5e13b29766067d7551 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 22:31:02 +0000 Subject: [PATCH 25/30] fix(windows): bind pane ops to the stream they were made for A frame ack (or keystroke) the pane sent just before a reconnect could reach the backend after the new stream went live and be written on it, releasing the replacement's flow-control slots early. The UI now tags each op with the backend session's live-stream number; the backend drops an op tagged for an earlier stream. Resizes still apply, since only the newest size matters. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ2eMMzt56iHuDqpo7z --- .../src-tauri/src/browser/mod.rs | 8 ++- .../src-tauri/src/browser/session.rs | 28 +++++++--- .../src-tauri/src/browser/session_tests.rs | 54 +++++++++++++++++++ .../ui/src/services/browser.ts | 13 +++-- .../ui/src/state/browserSession.test.ts | 39 +++++++++++++- .../ui/src/state/browserSession.ts | 11 +++- 6 files changed, 139 insertions(+), 14 deletions(-) diff --git a/apps/purepoint-windows/src-tauri/src/browser/mod.rs b/apps/purepoint-windows/src-tauri/src/browser/mod.rs index ab731706..71ed4427 100644 --- a/apps/purepoint-windows/src-tauri/src/browser/mod.rs +++ b/apps/purepoint-windows/src-tauri/src/browser/mod.rs @@ -157,15 +157,21 @@ pub async fn browser_open( } /// Write one op on the session's stream (dropped while it reconnects, except `resize`). +/// With `stream`, the live stream it was made for: it is dropped if another is live by then. #[tauri::command] pub fn browser_send( browser: State<'_, BrowserState>, session_id: u32, op: serde_json::Value, + stream: Option, ) -> Result<(), DaemonError> { let op: BrowserOp = serde_json::from_value(op).map_err(|e| DaemonError::InvalidRequest(e.to_string()))?; - browser.get(session_id)?.send(op); + let session = browser.get(session_id)?; + match stream { + Some(stream) => session.send_on(op, stream), + None => session.send(op), + } Ok(()) } diff --git a/apps/purepoint-windows/src-tauri/src/browser/session.rs b/apps/purepoint-windows/src-tauri/src/browser/session.rs index 4c9aef48..e0244c8b 100644 --- a/apps/purepoint-windows/src-tauri/src/browser/session.rs +++ b/apps/purepoint-windows/src-tauri/src/browser/session.rs @@ -154,7 +154,7 @@ impl Drop for TaskGuard { /// A running browser session. Dropping it closes the connection. pub struct BrowserSession { - ops: mpsc::UnboundedSender, + ops: mpsc::UnboundedSender<(BrowserOp, Option)>, _task: TaskGuard, } @@ -177,6 +177,7 @@ impl BrowserSession { write_timeout: options.write_timeout, stable_after: options.stable_after, live_since: None, + streams: 0, viewport: None, sink, ops: rx, @@ -190,7 +191,15 @@ impl BrowserSession { /// An op on the session's tab (a `None` tab id means it). Dropped while the stream is /// down, except `resize`, which is kept for the next attach. pub fn send(&self, op: BrowserOp) { - let _ = self.ops.send(op); + let _ = self.ops.send((op, None)); + } + + /// An op made for live stream `stream` (counted from 1, one per `Live` event). It is + /// dropped if another stream is live by the time it is written, so a late ack or + /// input from before a reconnect never reaches the replacement stream. A `resize` + /// still applies: only the newest size matters. + pub fn send_on(&self, op: BrowserOp, stream: u64) { + let _ = self.ops.send((op, Some(stream))); } } @@ -219,10 +228,12 @@ struct Worker { stable_after: Duration, /// When the current attempt's stream went live, if it did. live_since: Option, + /// How many streams have gone live (the current one's number while live). + streams: u64, /// The last `resize` the pane sent: (width, height, scale). viewport: Option<(u32, u32, f64)>, sink: Arc, - ops: mpsc::UnboundedReceiver, + ops: mpsc::UnboundedReceiver<(BrowserOp, Option)>, } impl Worker { @@ -267,7 +278,7 @@ impl Worker { _ = &mut sleep => return true, op = self.ops.recv() => match op { None => return false, - Some(op) => self.remember(&op), + Some((op, _)) => self.remember(&op), }, } } @@ -315,7 +326,7 @@ impl Worker { fn drop_stale_ops(&mut self) -> bool { loop { match self.ops.try_recv() { - Ok(op) => self.remember(&op), + Ok((op, _)) => self.remember(&op), Err(mpsc::error::TryRecvError::Empty) => return true, Err(mpsc::error::TryRecvError::Disconnected) => return false, } @@ -397,6 +408,7 @@ impl Worker { return End::Stopped; } self.live_since = Some(tokio::time::Instant::now()); + self.streams += 1; self.sink.event(BrowserEvent::Live); if let Some((width, height, scale)) = self.viewport { let resize = self.request(BrowserOp::Resize { @@ -418,8 +430,12 @@ impl Worker { loop { tokio::select! { op = self.ops.recv() => { - let Some(op) = op else { return End::Stopped }; + let Some((op, made_for)) = op else { return End::Stopped }; self.remember(&op); + let stale = made_for.is_some_and(|stream| stream != self.streams); + if stale && !matches!(op, BrowserOp::Resize { .. }) { + continue; + } let request = self.request(op); if let Err(message) = self.write(&mut writer, &request).await { return End::Retry { message, live: true }; diff --git a/apps/purepoint-windows/src-tauri/src/browser/session_tests.rs b/apps/purepoint-windows/src-tauri/src/browser/session_tests.rs index 227077dd..0d360db3 100644 --- a/apps/purepoint-windows/src-tauri/src/browser/session_tests.rs +++ b/apps/purepoint-windows/src-tauri/src/browser/session_tests.rs @@ -549,3 +549,57 @@ async fn given_a_stream_that_stayed_up_should_start_the_retry_schedule_over() { ]; assert_eq!(attempts, [1, 1]); } + +#[tokio::test] +async fn given_an_op_made_for_an_earlier_stream_should_drop_it_but_keep_a_resize() { + let mut daemon = FakeDaemon::start(); + let (sink, mut seen) = sink(); + let session = BrowserSession::start(daemon.client(), options(Some("t1"), None), sink); + assert_eq!(attach_then_drop(&mut daemon, &mut seen).await, 1); + + // The second stream goes live. + let mut stream = daemon.accept().await; + let _ = stream.request().await; + stream + .send(&Response::BrowserAttached { + tab: tab("t1", "http://localhost/"), + }) + .await; + assert!(matches!(next(&mut seen).await, BrowserEvent::Tab { .. })); + assert_eq!(next(&mut seen).await, BrowserEvent::Live); + + // An ack the pane made for the first stream arrives late: it never reaches this one. + session.send_on( + BrowserOp::FrameAck { + tab_id: None, + seq: 9, + }, + 1, + ); + // A late resize still applies (only the newest size matters)... + session.send_on( + BrowserOp::Resize { + tab_id: None, + width: 640, + height: 480, + scale: 1.0, + }, + 1, + ); + // ...and an op made for this stream goes through. + session.send_on( + BrowserOp::FrameAck { + tab_id: None, + seq: 2, + }, + 2, + ); + assert_request( + stream.request().await, + serde_json::json!({"type": "browser", "project_root": "/p", "op": {"action": "resize", "tab_id": null, "width": 640, "height": 480, "scale": 1.0}}), + ); + assert_request( + stream.request().await, + serde_json::json!({"type": "browser", "project_root": "/p", "op": {"action": "frame_ack", "tab_id": null, "seq": 2}}), + ); +} diff --git a/apps/purepoint-windows/ui/src/services/browser.ts b/apps/purepoint-windows/ui/src/services/browser.ts index 248b5779..cae7c547 100644 --- a/apps/purepoint-windows/ui/src/services/browser.ts +++ b/apps/purepoint-windows/ui/src/services/browser.ts @@ -39,8 +39,13 @@ export interface BrowserOpenOptions { /** One pane's stream. */ export interface BrowserStream { readonly id: BrowserSessionId; - /** An op on the stream's tab (leave `tab_id` out). */ - send(op: BrowserOp): Promise; + /** + * An op on the stream's tab (leave `tab_id` out). With `live`, the live stream it was + * made for (counted from 1, one per `live` event): the backend drops it if another + * stream is live by the time it is written, so a late ack or keystroke never reaches a + * replacement stream. Resizes still apply. + */ + send(op: BrowserOp, live?: number): Promise; close(): Promise; } @@ -68,8 +73,8 @@ export const openBrowserStream: OpenBrowserStream = async (projectRoot, options, const inOrder = serialSender(); return { id, - async send(op) { - await inOrder(() => invoke('browser_send', { sessionId: id, op })); + async send(op, live) { + await inOrder(() => invoke('browser_send', { sessionId: id, op, stream: live ?? null })); }, async close() { await invoke('browser_close', { sessionId: id }); diff --git a/apps/purepoint-windows/ui/src/state/browserSession.test.ts b/apps/purepoint-windows/ui/src/state/browserSession.test.ts index 5fcc8b2b..baa38780 100644 --- a/apps/purepoint-windows/ui/src/state/browserSession.test.ts +++ b/apps/purepoint-windows/ui/src/state/browserSession.test.ts @@ -14,6 +14,8 @@ interface FakeStream { readonly options: BrowserOpenOptions; readonly emit: (event: BrowserStreamEvent) => void; readonly sent: BrowserOp[]; + /** The live stream each sent op was bound to (`undefined` when none was live). */ + readonly bound: (number | undefined)[]; closed: boolean; } @@ -21,12 +23,20 @@ interface FakeStream { function fakeBackend() { const streams: FakeStream[] = []; const open: OpenBrowserStream = (projectRoot, options, onEvent) => { - const fake: FakeStream = { projectRoot, options, emit: onEvent, sent: [], closed: false }; + const fake: FakeStream = { + projectRoot, + options, + emit: onEvent, + sent: [], + bound: [], + closed: false, + }; streams.push(fake); const stream: BrowserStream = { id: streams.length, - send: (op) => { + send: (op, live) => { fake.sent.push(op); + fake.bound.push(live); return Promise.resolve(); }, close: () => { @@ -173,6 +183,31 @@ describe('BrowserSession', () => { ]); }); + it('givenOpsShouldBeBoundToTheLiveStreamAsTheBackendNumbersIt', async () => { + const { session, stream, backend } = makeSession(); + session.start(); + await settle(); + // Before any stream is live, nothing is bound (the backend keeps only the resize). + session.resize(640, 400, 1); + stream().emit({ type: 'live' }); + session.frameDrawn(1); + // A reconnect: the backend's second live stream. + stream().emit({ type: 'retrying', attempt: 1, delayMs: 300, message: 'down' }); + stream().emit({ type: 'live' }); + session.frameDrawn(1); + expect(stream().bound).toEqual([undefined, 1, 2]); + // A reopen starts a new backend session, which numbers its streams from 1 again, + // while the store's own count (for the canvas) carries on. + session.reopen(); + await settle(); + const reopened = backend.streams[1]; + if (reopened === undefined) throw new Error('no reopened stream'); + reopened.emit({ type: 'live' }); + session.frameDrawn(1); + expect(reopened.bound.at(-1)).toBe(1); + expect(session.state.stream).toBe(3); + }); + it('givenCopyShouldPutTheSelectionOnTheClipboardOnce', async () => { const { session, stream, copy } = makeSession(); session.start(); diff --git a/apps/purepoint-windows/ui/src/state/browserSession.ts b/apps/purepoint-windows/ui/src/state/browserSession.ts index 235376ca..a69b448f 100644 --- a/apps/purepoint-windows/ui/src/state/browserSession.ts +++ b/apps/purepoint-windows/ui/src/state/browserSession.ts @@ -79,6 +79,11 @@ export class BrowserSession { private tabId: string | null; private lastUrl: string | null; private stream: BrowserStream | null = null; + /** + * Streams gone live on the current backend session (one per `live` event), which is how + * the backend numbers them. Unlike the store's `stream`, it restarts with each session. + */ + private sessionLive = 0; /** Bumped per start and stop, so a superseded stream's late events are dropped. */ private generation = 0; private started = false; @@ -120,6 +125,7 @@ export class BrowserSession { if (this.started) return; this.started = true; const generation = ++this.generation; + this.sessionLive = 0; this.store.setState({ phase: { kind: 'connecting' } }); const current = (): boolean => generation === this.generation; this.open( @@ -217,8 +223,10 @@ export class BrowserSession { this.send({ action: 'resize', ...viewport }); } + /** Sends `op` bound to the live stream, if one is live (see `BrowserStream.send`). */ private send(op: BrowserOp): void { - void this.stream?.send(op).catch(() => undefined); + const live = this.state.phase.kind === 'live' ? this.sessionLive : undefined; + void this.stream?.send(op, live).catch(() => undefined); } // MARK: - Stream events @@ -230,6 +238,7 @@ export class BrowserSession { this.adopt(event.tab); return; case 'live': + this.sessionLive += 1; this.store.setState({ phase: { kind: 'live' }, stream: this.state.stream + 1 }); return; case 'frame': From 30365e43f1220a4739c17acd643a697e5d52c0bf Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 22:37:18 +0000 Subject: [PATCH 26/30] fix(windows): bind ops made while reconnecting to the stream that ended An ack (or other op) the pane made during a retry was sent untagged, so the backend wrote it on the next stream if it arrived after that one went live. The pane now always tags ops with the backend session's latest stream number (0 before any), so an op from a retry is dropped once a newer stream is live. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ2eMMzt56iHuDqpo7z --- apps/purepoint-windows/ui/src/services/browser.ts | 8 ++++---- .../ui/src/state/browserSession.test.ts | 12 ++++++++---- .../purepoint-windows/ui/src/state/browserSession.ts | 10 +++++++--- 3 files changed, 19 insertions(+), 11 deletions(-) diff --git a/apps/purepoint-windows/ui/src/services/browser.ts b/apps/purepoint-windows/ui/src/services/browser.ts index cae7c547..347bf41e 100644 --- a/apps/purepoint-windows/ui/src/services/browser.ts +++ b/apps/purepoint-windows/ui/src/services/browser.ts @@ -40,10 +40,10 @@ export interface BrowserOpenOptions { export interface BrowserStream { readonly id: BrowserSessionId; /** - * An op on the stream's tab (leave `tab_id` out). With `live`, the live stream it was - * made for (counted from 1, one per `live` event): the backend drops it if another - * stream is live by the time it is written, so a late ack or keystroke never reaches a - * replacement stream. Resizes still apply. + * An op on the stream's tab (leave `tab_id` out). With `live`, the stream it was made + * for (counted from 1, one per `live` event; 0 before any): the backend drops it unless + * that stream is the live one when it is written, so a late ack or keystroke never + * reaches a replacement stream. Resizes still apply. */ send(op: BrowserOp, live?: number): Promise; close(): Promise; diff --git a/apps/purepoint-windows/ui/src/state/browserSession.test.ts b/apps/purepoint-windows/ui/src/state/browserSession.test.ts index baa38780..8bfb8f74 100644 --- a/apps/purepoint-windows/ui/src/state/browserSession.test.ts +++ b/apps/purepoint-windows/ui/src/state/browserSession.test.ts @@ -14,7 +14,7 @@ interface FakeStream { readonly options: BrowserOpenOptions; readonly emit: (event: BrowserStreamEvent) => void; readonly sent: BrowserOp[]; - /** The live stream each sent op was bound to (`undefined` when none was live). */ + /** The stream each sent op was bound to. */ readonly bound: (number | undefined)[]; closed: boolean; } @@ -187,15 +187,19 @@ describe('BrowserSession', () => { const { session, stream, backend } = makeSession(); session.start(); await settle(); - // Before any stream is live, nothing is bound (the backend keeps only the resize). + // Before any stream is live, ops name stream 0, which none has (the backend keeps + // only the resize). session.resize(640, 400, 1); stream().emit({ type: 'live' }); session.frameDrawn(1); - // A reconnect: the backend's second live stream. + // An ack made while reconnecting still names the stream that ended, so the backend + // drops it if it arrives after the next stream is live. stream().emit({ type: 'retrying', attempt: 1, delayMs: 300, message: 'down' }); + session.frameDrawn(2); + // The backend's second live stream. stream().emit({ type: 'live' }); session.frameDrawn(1); - expect(stream().bound).toEqual([undefined, 1, 2]); + expect(stream().bound).toEqual([0, 1, 1, 2]); // A reopen starts a new backend session, which numbers its streams from 1 again, // while the store's own count (for the canvas) carries on. session.reopen(); diff --git a/apps/purepoint-windows/ui/src/state/browserSession.ts b/apps/purepoint-windows/ui/src/state/browserSession.ts index a69b448f..40a40661 100644 --- a/apps/purepoint-windows/ui/src/state/browserSession.ts +++ b/apps/purepoint-windows/ui/src/state/browserSession.ts @@ -223,10 +223,14 @@ export class BrowserSession { this.send({ action: 'resize', ...viewport }); } - /** Sends `op` bound to the live stream, if one is live (see `BrowserStream.send`). */ + /** + * Sends `op` bound to the backend session's latest stream (see `BrowserStream.send`), + * live or not: an op made while reconnecting (an ack of an old frame, say) then names + * the stream that ended, and the backend drops it once a newer one is live. Before + * any stream it names 0, which no stream has. + */ private send(op: BrowserOp): void { - const live = this.state.phase.kind === 'live' ? this.sessionLive : undefined; - void this.stream?.send(op, live).catch(() => undefined); + void this.stream?.send(op, this.sessionLive).catch(() => undefined); } // MARK: - Stream events From 7e8e434a9657ae960f4108406b0d76f179552742 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 22:39:36 +0000 Subject: [PATCH 27/30] fix(browser): end a half-written CDP command at its caller's deadline The rest of a command already started was written under a fresh 30 s timer, so a browser that stalled mid-command and then resumed could receive the whole command after its caller had been told it timed out. The rest is now bounded by the command's own deadline; if that passes, the connection ends and the half-written command never runs. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ2eMMzt56iHuDqpo7z --- crates/pu-engine/src/browser/cdp.rs | 101 ++++++++++++++++++++++++++-- 1 file changed, 97 insertions(+), 4 deletions(-) diff --git a/crates/pu-engine/src/browser/cdp.rs b/crates/pu-engine/src/browser/cdp.rs index 6941b013..00bca2a0 100644 --- a/crates/pu-engine/src/browser/cdp.rs +++ b/crates/pu-engine/src/browser/cdp.rs @@ -166,14 +166,16 @@ impl Cdp { Ok(n) => n, }, }; - // The rest of a started command is bounded too: a browser that stops - // reading mid-command is unusable (the pipe holds half a message), so - // the connection ends instead of hanging this writer. + // The rest of a started command is bounded by the same deadline: a + // browser that stops reading mid-command is unusable (the pipe holds half + // a message), and the command must not be completed after its caller was + // told it timed out. Either way the connection ends, so the half-written + // command never runs. let rest = async { writer.write_all(&message.bytes[first..]).await?; writer.flush().await }; - match tokio::time::timeout(CALL_TIMEOUT, rest).await { + match tokio::time::timeout_at(message.deadline, rest).await { Ok(Ok(())) => {} Ok(Err(_)) | Err(_) => break, } @@ -645,6 +647,97 @@ mod tests { assert!(!written.contains("Late.click"), "{written}"); } + type TrickleState = (usize, Option, Vec); + + /// A browser input pipe that takes `budget` bytes, then nothing until given more. + #[derive(Clone, Default)] + struct Trickle(Arc>); + + impl AsyncWrite for Trickle { + fn poll_write( + self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + buf: &[u8], + ) -> std::task::Poll> { + let mut state = self.0.lock().unwrap(); + if state.0 == 0 { + state.1 = Some(cx.waker().clone()); + return std::task::Poll::Pending; + } + let n = state.0.min(buf.len()); + state.0 -= n; + state.2.extend_from_slice(&buf[..n]); + std::task::Poll::Ready(Ok(n)) + } + fn poll_flush( + self: std::pin::Pin<&mut Self>, + _: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + std::task::Poll::Ready(Ok(())) + } + fn poll_shutdown( + self: std::pin::Pin<&mut Self>, + _: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + std::task::Poll::Ready(Ok(())) + } + } + + #[tokio::test] + async fn given_a_command_that_times_out_halfway_written_should_never_finish_it() { + let pipe = Trickle::default(); + pipe.0.lock().unwrap().0 = 8; + let (_browser_out, client_in) = duplex(4096); + let cdp = Cdp::start(client_in, pipe.clone()); + // The browser takes the command's first bytes, then stops reading. + let late = tokio::spawn({ + let cdp = cdp.clone(); + async move { + cdp.call_within(Duration::from_millis(300), None, "Late.type", json!({})) + .await + } + }); + tokio::time::timeout(FIXTURE_WAIT, async { + loop { + { + let state = pipe.0.lock().unwrap(); + if state.2.len() == 8 && state.1.is_some() { + break; + } + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .expect("the writer is blocked partway through the command"); + assert_eq!( + late.await.unwrap(), + Err(CdpError::Timeout("Late.type".into())) + ); + // The browser reads again: the timed-out command must not be completed. + let waker = { + let mut state = pipe.0.lock().unwrap(); + state.0 = usize::MAX; + state.1.take() + }; + if let Some(waker) = waker { + waker.wake(); + } + tokio::time::sleep(Duration::from_millis(100)).await; + let written = pipe.0.lock().unwrap().2.clone(); + assert!( + !written.contains(&0), + "{:?}", + String::from_utf8_lossy(&written) + ); + // The half-written connection was given up. + assert_eq!( + cdp.call_within(Duration::from_secs(1), None, "After.ok", json!({})) + .await, + Err(CdpError::Closed) + ); + } + #[tokio::test] async fn given_the_browser_closes_while_a_write_waits_should_never_send_it() { let gate = Gate::default(); From 2d671b114689e0c81f0328da338b5b742987a92a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 22:42:13 +0000 Subject: [PATCH 28/30] fix(browser): keep shutdown and retirement ordered; keep an unconfirmed profile locked Shutdown released each project's startup lock before draining the browsers, so a retirement could take an instance out of the map in between and leave it exiting unseen. Shutdown now holds every startup lock until it is done. It also released every profile lock even when a browser's exit could not be confirmed, letting another daemon clear a live browser's singleton files. Such a browser (or lingering child) is now kept, and its profile stays locked until the process really goes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ2eMMzt56iHuDqpo7z --- crates/pu-engine/src/browser/mod.rs | 45 +++++++++------- crates/pu-engine/tests/browser.rs | 67 ++++++++++++++++++++++++ crates/pu-engine/tests/browser_launch.rs | 46 ++++++++++++++++ 3 files changed, 138 insertions(+), 20 deletions(-) diff --git a/crates/pu-engine/src/browser/mod.rs b/crates/pu-engine/src/browser/mod.rs index 918b7d7b..88b9219b 100644 --- a/crates/pu-engine/src/browser/mod.rs +++ b/crates/pu-engine/src/browser/mod.rs @@ -541,34 +541,39 @@ impl BrowserManager { pub async fn shutdown(&self) { self.closing .store(true, std::sync::atomic::Ordering::SeqCst); + // Every project's startup lock is held until the end: a launch or a retirement + // already running finishes first, and none starts during the drain (so a + // retirement cannot take an instance out of the map and leave it exiting + // unseen while this returns). let startups: Vec<_> = self.startups.lock().await.values().cloned().collect(); + let mut held = Vec::with_capacity(startups.len()); for startup in startups { - drop(startup.lock().await); + held.push(startup.lock_owned().await); } - let instances: Vec<_> = self - .instances - .lock() - .await - .drain() - .map(|(_, i)| i) - .collect(); - for instance in instances { - instance.stop_and_wait(self.exit_wait).await; + let instances: Vec<_> = self.instances.lock().await.drain().collect(); + // Projects whose browser may still be running: their profile stays locked. + let mut unconfirmed = std::collections::HashSet::new(); + for (root, instance) in instances { + if !instance.stop_and_wait(self.exit_wait).await { + // Kept, so the process stays owned (and is killed when dropped). + self.instances.lock().await.insert(root.clone(), instance); + unconfirmed.insert(root); + } } - let lingering: Vec<_> = self - .lingering - .lock() - .await - .drain() - .map(|(_, c)| c) - .collect(); - for child in lingering { - let _ = stop_child(None, Some(child), self.exit_wait).await; + let lingering: Vec<_> = self.lingering.lock().await.drain().collect(); + for (root, child) in lingering { + if let Err(child) = stop_child(None, Some(child), self.exit_wait).await { + self.lingering.lock().await.insert(root.clone(), child); + unconfirmed.insert(root); + } } + // Only a profile whose browser is confirmed gone is released: another daemon + // could otherwise take it and clear the singleton files of a live browser. self.profile_locks .lock() .unwrap_or_else(|e| e.into_inner()) - .clear(); + .retain(|root, _| unconfirmed.contains(root)); + drop(held); } fn closing_error() -> BrowserError { diff --git a/crates/pu-engine/tests/browser.rs b/crates/pu-engine/tests/browser.rs index 9643cfaf..7a4ba0da 100644 --- a/crates/pu-engine/tests/browser.rs +++ b/crates/pu-engine/tests/browser.rs @@ -1091,3 +1091,70 @@ async fn given_a_pane_that_left_before_its_resize_turn_should_leave_the_size_alo assert_eq!(size(&manager).await, (700, 500)); manager.shutdown().await; } + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn given_shutdown_while_the_last_tab_closes_should_wait_for_the_browser_to_exit() { + if !have_browser() { + eprintln!("skipping: no Chrome/Chromium on this machine (set PU_BROWSER)"); + return; + } + use pu_engine::browser::{BrowserManager, Caller}; + for round in 0..5 { + let tmp = TempDir::new().unwrap(); + let base = tmp.path().join("browser"); + let manager = std::sync::Arc::new(BrowserManager::new(Some(base.clone()))); + let tab = match manager + .handle( + "/p", + BrowserOp::Open { + url: Some("about:blank".into()), + }, + Caller::Agent, + ) + .await + { + Response::BrowserTab { tab } => tab, + other => panic!("open: {other:?}"), + }; + // Chromium records its pid in the profile's SingletonLock link: "host-pid". + let lock = base + .join("profiles") + .join(pu_engine::browser::launch::profile_key("/p")) + .join("SingletonLock"); + let target = std::fs::read_link(&lock).expect("Chromium's SingletonLock"); + let pid: i32 = target + .to_string_lossy() + .rsplit('-') + .next() + .unwrap() + .parse() + .unwrap(); + // Closing the last tab retires the browser (and waits for it) while shutdown + // runs: shutdown must not return before that browser is gone. + let closing = tokio::spawn({ + let manager = manager.clone(); + async move { + manager + .handle( + "/p", + BrowserOp::Close { + tab_id: Some(tab.tab_id), + }, + Caller::Agent, + ) + .await + } + }); + tokio::time::sleep(Duration::from_millis(round * 10)).await; + manager.shutdown().await; + // SAFETY: signal 0 only checks that the process exists. + let alive = unsafe { libc::kill(pid, 0) } == 0; + // A zombie still "exists" to kill(0); it is gone once reaped, which the + // manager does before reporting an exit. + assert!( + !alive, + "round {round}: shutdown returned with browser {pid} still running" + ); + let _ = closing.await; + } +} diff --git a/crates/pu-engine/tests/browser_launch.rs b/crates/pu-engine/tests/browser_launch.rs index 692aa30c..b8089efd 100644 --- a/crates/pu-engine/tests/browser_launch.rs +++ b/crates/pu-engine/tests/browser_launch.rs @@ -162,3 +162,49 @@ async fn given_another_daemon_owns_the_profile_should_refuse_to_touch_it() { "{retried:?}" ); } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn given_shutdown_cannot_confirm_a_browser_exit_should_keep_its_profile_locked() { + let _env = BROWSER_ENV.lock().await; + let tmp = TempDir::new().unwrap(); + let pid_file = hung_browser(tmp.path()); + let base = tmp.path().join("browser"); + // A zero exit wait never confirms an exit: a browser that will not go away. + let first = BrowserManager::new(Some(base.clone())).with_exit_wait(Duration::ZERO); + let second = BrowserManager::new(Some(base.clone())); + let opened = open(&first).await; + assert!( + matches!(&opened, Response::Error { code, .. } if code == "BROWSER_LAUNCH_FAILED"), + "{opened:?}" + ); + let pid: i32 = std::fs::read_to_string(&pid_file) + .unwrap() + .trim() + .parse() + .unwrap(); + std::fs::remove_file(&pid_file).unwrap(); + + // Shutdown cannot confirm that browser is gone, so the profile stays locked: + // another daemon must not clear the singleton files of a browser that may live. + first.shutdown().await; + assert!(alive(pid), "the unconfirmed browser {pid} was let go"); + let refused = open(&second).await; + assert!( + matches!(&refused, Response::Error { code, .. } if code == "BROWSER_PROFILE_IN_USE"), + "{refused:?}" + ); + assert!( + !pid_file.exists(), + "a second browser started on the profile" + ); + + // Once the first daemon is really gone (its child killed, its lock released by + // the kernel), the profile is free again. + drop(first); + let retried = open(&second).await; + assert!( + matches!(&retried, Response::Error { code, .. } if code == "BROWSER_LAUNCH_FAILED"), + "{retried:?}" + ); + second.shutdown().await; +} From a49b048179e279a5a20339e09bd03dc91ad1939c Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 22:56:04 +0000 Subject: [PATCH 29/30] fix(browser): deadline-first remaining CDP write; atomic take-over; keep unclosed tabs - CDP writer: the rest of a started command races its deadline with the deadline checked first, so nothing more is written once it has passed. - Take Control checks for a watching pane and hands the tab to the person under the viewer count's lock (Tab::take_control), so the last pane leaving cannot slip in between and leave the tab locked to agents. - History refreshes start and publish under one lock. - Close forgets a tab only once Chromium closed it; a failed close returns its error and leaves the tab listed. - A browser that started while shutdown began is kept if its exit is not confirmed, so shutdown keeps owning it and its profile lock. - Docs: cleanup of an unread open reply is best effort; tooltips name the last pane watching the tab. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ2eMMzt56iHuDqpo7z --- .../views/browser/BrowserPaneView.test.tsx | 27 ++++++- .../ui/src/views/browser/BrowserPaneView.tsx | 8 +- crates/pu-engine/src/browser/cdp.rs | 74 +++++++++++++++++-- crates/pu-engine/src/browser/mod.rs | 33 ++++++--- crates/pu-engine/src/browser/tab.rs | 49 +++++++++++- crates/pu-engine/src/ipc_server/mod.rs | 4 +- crates/pu-engine/tests/browser.rs | 60 +++++++++++++++ docs/reference/ipc-api.md | 2 +- 8 files changed, 231 insertions(+), 26 deletions(-) diff --git a/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.test.tsx b/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.test.tsx index 6f6a8555..41122fc1 100644 --- a/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.test.tsx +++ b/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.test.tsx @@ -41,7 +41,7 @@ function setup(props: { tabId?: string | null; url?: string | null } = {}) { readText: vi.fn(() => Promise.resolve('pasted')), writeText: vi.fn(() => Promise.resolve()), }; - render( + const { unmount } = render( { @@ -143,6 +143,29 @@ describe('BrowserPaneView', () => { expect(sent.filter((op) => op.action === 'input')).toEqual([]); }); + it('drops a paste whose clipboard read finishes after the pane closed', async () => { + const { send, sent, clipboard, unmount } = setup(); + await send({ type: 'live' }); + let release: (text: string) => void = () => undefined; + clipboard.readText.mockImplementationOnce( + () => + new Promise((resolve) => { + release = resolve; + }), + ); + fireEvent.keyDown(screen.getByTestId('browser-canvas'), { + key: 'v', + code: 'KeyV', + ctrlKey: true, + }); + unmount(); + await act(async () => { + release('secret'); + await Promise.resolve(); + }); + expect(sent.filter((op) => op.action === 'input')).toEqual([]); + }); + it('offers to reopen a closed tab, on its last page', async () => { const { send, opens } = setup({ tabId: 't1', url: 'http://localhost:8080/' }); await send({ type: 'tab', tab: tab({ url: 'http://localhost:8080/x' }) }); diff --git a/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.tsx b/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.tsx index 896f2130..936f4305 100644 --- a/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.tsx +++ b/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.tsx @@ -127,8 +127,10 @@ export function BrowserPaneView({ // Paste goes to the stream that took the shortcut: text read after the pane closed, or // after it moved to another (or reopened) tab, is dropped rather than typed there. + // A layout effect, so the flag clears as the pane leaves the page, before passive + // cleanup: a clipboard read finishing in between types nothing. const mounted = useRef(true); - useEffect(() => { + useLayoutEffect(() => { mounted.current = true; return () => { mounted.current = false; @@ -220,7 +222,7 @@ export function BrowserPaneView({ type="button" className="browser-toolbar-button browser-driver" data-driver="human" - title="You are driving: agents' page actions are refused until you hand the tab back or close this pane." + title="You are driving: agents' page actions are refused until you hand the tab back or the last pane watching this tab closes." onClick={() => { session.setHumanDriving(false); }} @@ -233,7 +235,7 @@ export function BrowserPaneView({ type="button" className="browser-toolbar-button browser-driver" data-driver="agent" - title="Take the tab from agents: their page actions are refused until you hand it back or close this pane." + title="Take the tab from agents: their page actions are refused until you hand it back or the last pane watching this tab closes." onClick={() => { session.setHumanDriving(true); }} diff --git a/crates/pu-engine/src/browser/cdp.rs b/crates/pu-engine/src/browser/cdp.rs index 00bca2a0..e87e9f59 100644 --- a/crates/pu-engine/src/browser/cdp.rs +++ b/crates/pu-engine/src/browser/cdp.rs @@ -171,13 +171,24 @@ impl Cdp { // a message), and the command must not be completed after its caller was // told it timed out. Either way the connection ends, so the half-written // command never runs. + // `biased`, deadline first, like the first write: once the deadline + // has passed, no more of the command is written, even if the pipe + // became writable in the meantime. let rest = async { writer.write_all(&message.bytes[first..]).await?; writer.flush().await }; - match tokio::time::timeout_at(message.deadline, rest).await { - Ok(Ok(())) => {} - Ok(Err(_)) | Err(_) => break, + tokio::pin!(rest); + // A connection the reader closed meanwhile is given up too: its + // callers were told `Closed`, so the command must not complete. + let finished = tokio::select! { + biased; + () = &mut closed => false, + () = tokio::time::sleep_until(message.deadline) => false, + written = &mut rest => written.is_ok(), + }; + if !finished { + break; } } // The browser stopped taking commands: nothing sent from now on will be @@ -710,9 +721,12 @@ mod tests { }) .await .expect("the writer is blocked partway through the command"); - assert_eq!( - late.await.unwrap(), - Err(CdpError::Timeout("Late.type".into())) + // Timed out, or (if the writer gave up first) failed as closed: either way + // the caller was told the command did not complete. + let outcome = late.await.unwrap(); + assert!( + matches!(&outcome, Err(CdpError::Timeout(_)) | Err(CdpError::Closed)), + "{outcome:?}" ); // The browser reads again: the timed-out command must not be completed. let waker = { @@ -738,6 +752,54 @@ mod tests { ); } + #[tokio::test] + async fn given_the_browser_closes_halfway_through_a_command_should_never_finish_it() { + let pipe = Trickle::default(); + pipe.0.lock().unwrap().0 = 8; + let (browser_out, client_in) = duplex(4096); + let cdp = Cdp::start(client_in, pipe.clone()); + // A long deadline: only the browser closing can stop this command. + let call = tokio::spawn({ + let cdp = cdp.clone(); + async move { + cdp.call_within(Duration::from_secs(30), None, "Half.type", json!({})) + .await + } + }); + tokio::time::timeout(FIXTURE_WAIT, async { + loop { + { + let state = pipe.0.lock().unwrap(); + if state.2.len() == 8 && state.1.is_some() { + break; + } + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .expect("the writer is blocked partway through the command"); + // The browser's output closes: callers are told `Closed`. + drop(browser_out); + assert_eq!(call.await.unwrap(), Err(CdpError::Closed)); + // The pipe then takes bytes again: the command must not be completed. + let waker = { + let mut state = pipe.0.lock().unwrap(); + state.0 = usize::MAX; + state.1.take() + }; + if let Some(waker) = waker { + waker.wake(); + } + tokio::time::sleep(Duration::from_millis(100)).await; + let written = pipe.0.lock().unwrap().2.clone(); + assert!( + !written.contains(&0), + "{:?}", + String::from_utf8_lossy(&written) + ); + } + #[tokio::test] async fn given_the_browser_closes_while_a_write_waits_should_never_send_it() { let gate = Gate::default(); diff --git a/crates/pu-engine/src/browser/mod.rs b/crates/pu-engine/src/browser/mod.rs index 88b9219b..c70c87d9 100644 --- a/crates/pu-engine/src/browser/mod.rs +++ b/crates/pu-engine/src/browser/mod.rs @@ -641,7 +641,14 @@ impl BrowserManager { let instance = self.launch(root).await?; // Shutdown began while this browser started: it never becomes reachable. if self.closing.load(std::sync::atomic::Ordering::SeqCst) { - instance.stop_and_wait(self.exit_wait).await; + // Not confirmed gone: kept, so shutdown (waiting on this startup lock) + // finds it, keeps owning it and keeps its profile locked. + if !instance.stop_and_wait(self.exit_wait).await { + self.instances + .lock() + .await + .insert(root.to_string(), instance); + } return Err(Self::closing_error()); } instance @@ -901,14 +908,16 @@ impl BrowserManager { BrowserOp::Close { tab_id } => { let instance = self.running(root).await?; let tab = instance.resolve(tab_id.as_deref())?; - let _ = instance + // The tab is forgotten only once Chromium has closed it: a close that + // did not get through leaves it listed, so it can be closed again. + instance .cdp .call( None, "Target.closeTarget", json!({ "targetId": tab.target_id }), ) - .await; + .await?; instance.remove_tab(&tab.target_id); self.retire_if_unused(root, &instance).await; return Ok(Response::Ok); @@ -1046,13 +1055,19 @@ impl BrowserManager { BrowserOp::Control { driver, .. } => { // Control belongs to a person at a pane: with no pane watching the tab, // nobody could hand it back, so a human driver needs a viewer. - if driver == BrowserDriver::Human && !tab.has_viewers() { - return Err(BrowserError::new( - "BROWSER_NO_VIEWER", - "take control from a browser pane showing this tab", - )); + // Checked and set as one step with the viewer count (`take_control`), + // so the last pane leaving cannot slip in between. Handing back + // needs no pane. + if driver == BrowserDriver::Human { + if !tab.take_control() { + return Err(BrowserError::new( + "BROWSER_NO_VIEWER", + "take control from a browser pane showing this tab", + )); + } + } else { + tab.set_driver(driver); } - tab.set_driver(driver); Ok(Response::BrowserTab { tab: tab.info() }) } BrowserOp::Input { event, .. } => { diff --git a/crates/pu-engine/src/browser/tab.rs b/crates/pu-engine/src/browser/tab.rs index b721c545..fe6f720c 100644 --- a/crates/pu-engine/src/browser/tab.rs +++ b/crates/pu-engine/src/browser/tab.rs @@ -73,7 +73,7 @@ pub struct Tab { /// The number the next snapshot's first ref gets. next_ref: AtomicU64, /// Bumped as each history refresh starts: only the latest may publish. - history: AtomicU64, + history: Mutex, /// Whether the recorded viewport is known to be the one Chromium uses (false /// after a resize failed partway, so the next one is applied, not skipped). viewport_confirmed: std::sync::atomic::AtomicBool, @@ -108,7 +108,7 @@ impl Tab { resizing: tokio::sync::Mutex::new(()), snapshotting: tokio::sync::Mutex::new(()), next_ref: AtomicU64::new(1), - history: AtomicU64::new(0), + history: Mutex::new(0), viewport_confirmed: std::sync::atomic::AtomicBool::new(true), } } @@ -165,12 +165,17 @@ impl Tab { } pub fn begin_history_refresh(&self) -> u64 { - self.history.fetch_add(1, Ordering::SeqCst) + 1 + let mut history = self.history.lock().unwrap_or_else(|e| e.into_inner()); + *history += 1; + *history } /// `set_history` for refresh `revision`, ignored once a later refresh started. + /// Checked and published under the lock a refresh starts under, so a newer + /// refresh can never start between an older one's check and its publication. pub fn set_history_for(&self, revision: u64, can_go_back: bool, can_go_forward: bool) { - if self.history.load(Ordering::SeqCst) == revision { + let history = self.history.lock().unwrap_or_else(|e| e.into_inner()); + if *history == revision { self.set_history(can_go_back, can_go_forward); } } @@ -395,6 +400,18 @@ impl Tab { } } + /// Hands the tab to the person at a pane, if a pane is watching it. Checked and + /// set under the viewer count's lock, so the last viewer leaving (which hands the + /// tab back to agents) cannot slip between the check and the change. + pub fn take_control(&self) -> bool { + let viewers = self.viewers.lock().unwrap_or_else(|e| e.into_inner()); + if *viewers == 0 { + return false; + } + self.set_driver(BrowserDriver::Human); + true + } + pub fn has_viewers(&self) -> bool { *self.viewers.lock().unwrap_or_else(|e| e.into_inner()) > 0 } @@ -832,6 +849,30 @@ mod tests { assert_eq!(tab.driver(), BrowserDriver::Agent); } + #[tokio::test] + async fn given_no_viewer_should_refuse_control_and_never_outlive_the_last_viewer() { + let tab = tab(); + let cdp = cdp(); + assert!(!tab.take_control()); + assert_eq!(tab.driver(), BrowserDriver::Agent); + tab.add_viewer(&cdp); + assert!(tab.take_control()); + assert_eq!(tab.driver(), BrowserDriver::Human); + tab.remove_viewer(&cdp); + assert_eq!(tab.driver(), BrowserDriver::Agent); + // A take-over racing the last viewer's departure: whichever lands first, a + // tab with no viewer always ends with agents. + for round in 0..500 { + tab.add_viewer(&cdp); + std::thread::scope(|scope| { + scope.spawn(|| tab.take_control()); + scope.spawn(|| tab.remove_viewer(&cdp)); + }); + assert!(!tab.has_viewers()); + assert_eq!(tab.driver(), BrowserDriver::Agent, "round {round}"); + } + } + #[tokio::test] async fn given_the_last_viewer_leaves_should_drop_the_cached_frame_and_late_frames() { let tab = tab(); diff --git a/crates/pu-engine/src/ipc_server/mod.rs b/crates/pu-engine/src/ipc_server/mod.rs index 5945d104..7462f7f8 100644 --- a/crates/pu-engine/src/ipc_server/mod.rs +++ b/crates/pu-engine/src/ipc_server/mod.rs @@ -320,7 +320,9 @@ impl IpcServer { }; // A tab this request opened belongs to whoever reads the reply. A client that // stops reading must not hold it open: its write is bounded, and on failure - // or timeout the tab is closed again. + // or timeout the tab is closed again. This is best effort: a reply written in + // full but never read is not detected, and that tab stays open (listed, and + // closed by the idle stop like any other) until someone closes it. let written = if matches!(stream_mode, StreamMode::Attach(..)) { Ok(()) } else if opened_browser_in.is_some() { diff --git a/crates/pu-engine/tests/browser.rs b/crates/pu-engine/tests/browser.rs index 7a4ba0da..240a5853 100644 --- a/crates/pu-engine/tests/browser.rs +++ b/crates/pu-engine/tests/browser.rs @@ -1158,3 +1158,63 @@ async fn given_shutdown_while_the_last_tab_closes_should_wait_for_the_browser_to let _ = closing.await; } } + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn given_shutdown_during_a_launch_whose_exit_is_unconfirmed_should_keep_the_profile_locked() { + if !have_browser() { + eprintln!("skipping: no Chrome/Chromium on this machine (set PU_BROWSER)"); + return; + } + use pu_engine::browser::{BrowserManager, Caller}; + let tmp = TempDir::new().unwrap(); + let base = tmp.path().join("browser"); + // A zero exit wait never confirms an exit: a browser that might still be running. + let first = + std::sync::Arc::new(BrowserManager::new(Some(base.clone())).with_exit_wait(Duration::ZERO)); + let opening = tokio::spawn({ + let first = first.clone(); + async move { + first + .handle( + "/p", + BrowserOp::Open { + url: Some("about:blank".into()), + }, + Caller::Agent, + ) + .await + } + }); + // The launch has begun once the daemon owns the profile (just before Chromium starts). + let owned = base + .join("profiles") + .join(pu_engine::browser::launch::profile_key("/p")) + .join(".pu-daemon.lock"); + tokio::time::timeout(Duration::from_secs(20), async { + while !owned.exists() { + tokio::time::sleep(Duration::from_millis(2)).await; + } + }) + .await + .expect("the launch took the profile"); + first.shutdown().await; + // However the open ended (refused as shutting down, or finished just before), + // its browser's exit was never confirmed, so the profile stays locked. + let _ = opening.await.unwrap(); + let second = BrowserManager::new(Some(base.clone())); + let refused = second + .handle( + "/p", + BrowserOp::Open { + url: Some("about:blank".into()), + }, + Caller::Agent, + ) + .await; + assert!( + matches!(&refused, Response::Error { code, .. } if code == "BROWSER_PROFILE_IN_USE"), + "{refused:?}" + ); + drop(first); + second.shutdown().await; +} diff --git a/docs/reference/ipc-api.md b/docs/reference/ipc-api.md index bf33895e..b28da0bf 100644 --- a/docs/reference/ipc-api.md +++ b/docs/reference/ipc-api.md @@ -471,7 +471,7 @@ Each project has a headless Chromium on the daemon's machine (`docs/product/brow | `action` | Fields | Response | |---|---|---| -| `open` | `url`? | `browser_tab` (starts the browser; waits up to 15 s for the page) | +| `open` | `url`? | `browser_tab` (starts the browser; waits up to 15 s for the page). If the reply cannot be written (the client left, or stopped reading for 20 s), the new tab is closed again. This is best effort: a reply written but never read leaves the tab open | | `list` | | `browser_tabs` (never starts the browser) | | `close` | | `ok` (the last tab stops the browser) | | `navigate` | `url` | `browser_tab` after the page loads (bare hosts get `http://` if local, else `https://`) | From 9a272c6fa9c2ae8d5000975e8c6b2ad8e1fcc907 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 23:12:40 +0000 Subject: [PATCH 30/30] test(engine): wait for the resumed agent's command line to settle `given_default_spawn_should_resume_with_configured_launch_args` read the resumed process's argv once, right after Resume, and intermittently saw a transitional bare `bash` without the launch args (failing on CI for cd9ae94 and a49b048). It now re-reads for up to a second until the launch arg shows. The no-auto test is unaffected: it reads the settled value. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ2eMMzt56iHuDqpo7z --- crates/pu-engine/src/engine/agent_lifecycle.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/crates/pu-engine/src/engine/agent_lifecycle.rs b/crates/pu-engine/src/engine/agent_lifecycle.rs index 10827a86..1536e950 100644 --- a/crates/pu-engine/src/engine/agent_lifecycle.rs +++ b/crates/pu-engine/src/engine/agent_lifecycle.rs @@ -941,7 +941,18 @@ mod bare_launch_resume_tests { panic!("agent missing from manifest"); }; let pid = agent.pid.expect("resumed agent has a pid"); - let argv = resumed_argv(pid); + // Read the command line once the process has settled into it: just after a + // resume, `ps` can still report a transitional one (bare `bash`), with the + // launch args not yet visible. A no-auto resume never shows them, so it + // just reads the final value after the same wait. + let mut argv = resumed_argv(pid); + for _ in 0..40 { + if has_launch_arg(&argv) { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(25)).await; + argv = resumed_argv(pid); + } let bare = agent.bare_launch; engine.kill_agents(&[agent_id]).await; (bare, argv)