diff --git a/CHANGELOG.md b/CHANGELOG.md index 3dcc398f..f9cbac56 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, 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. @@ -14,10 +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. 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. @@ -31,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/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..bdea8ff1 --- /dev/null +++ b/apps/purepoint-macos/purepoint-macos/State/BrowserSession.swift @@ -0,0 +1,460 @@ +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") || 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 + { + { 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)? + /// 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? + + 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 + // 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 + // 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) } + } + + /// 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() { + guard liveAttach != nil else { return } + pendingCopies += 1 + 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)) + } + + /// 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. 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), on: attach) + } + } + + 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 { + // A stopped session's stream fails as it closes; that is not a reconnect. + guard !Task.isCancelled else { return } + #if os(iOS) + if 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) + } + } + } + + /// 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. + try Task.checkCancellation() + 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() + // 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() + } + 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 + + // 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 + 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 } + } catch { + deadline.cancel() + if await answered.expired { throw BrowserSessionError.attachTimedOut } + throw error + } + try Task.checkCancellation() + 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 + liveAttach = attach + if let viewport { + await writer.send( + .browser( + projectRoot: projectRoot, + op: .resize(tabId: nil, width: viewport.width, height: viewport.height, scale: viewport.scale)), + on: attach) + } + + 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) { + 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) + } + // 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)), on: attach) + case .browserTabState(let info): + adopt(info) + case .browserTabClosed: + phase = .closed + frame = nil + return + case .browserTab(let info): + adopt(info) + case .browserEvalResult(let value): + // 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: + 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 + } + } +} + +/// 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 + /// 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 + + /// 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 + } + + /// 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) + } + + /// Closes `which` (or, given none, the current stream), forgetting it if it is current. + func close(_ which: (any DaemonByteStream)? = nil) { + guard let target = which ?? stream else { return } + target.close() + if stream === target { 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 5275cc14..02154518 100644 --- a/apps/purepoint-macos/purepoint-macos/Views/Terminal/TerminalPaneView+iOS.swift +++ b/apps/purepoint-macos/purepoint-macos/Views/Terminal/TerminalPaneView+iOS.swift @@ -76,6 +76,7 @@ class TerminalPaneNSView: UIView { tv.terminalView.hideCursor(source: tv.terminalView.getTerminal()) tv.attachmentClient = client tv.usesRemoteHost = true + tv.openLink = BrowserLinks.handler(agentId: agent.id, isRemote: { true }, fallback: tv.openLink) tv.onAttachingChanged = { [weak self] attaching in self?.showAttaching(attaching) } tv.onAttachmentError = { [weak self] message in self?.showAttachmentError(message) } terminal = tv 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..625d752e --- /dev/null +++ b/apps/purepoint-macos/purepoint-macosTests/BrowserPaneTests.swift @@ -0,0 +1,171 @@ +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://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", + "http://127.0.0.256", "http://127.example.com", + ] { + #expect(!BrowserLinks.isLoopback(try #require(URL(string: link))), "\(link)") + } + } + + @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 + } + 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") == "") + } + + @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-macos/purepoint-macosTests/MachinesTests.swift b/apps/purepoint-macos/purepoint-macosTests/MachinesTests.swift index 4d6419c3..ae6c8a79 100644 --- a/apps/purepoint-macos/purepoint-macosTests/MachinesTests.swift +++ b/apps/purepoint-macos/purepoint-macosTests/MachinesTests.swift @@ -355,7 +355,7 @@ struct HealthProbeTests { struct DaemonProjectHostRequestTests { @Test func givenProtocolShouldBeCurrentVersion() { - #expect(DaemonProtocol.version == 14) + #expect(DaemonProtocol.version == 15) } @Test func givenReorderProjectsShouldSendTheWholeOrder() throws { 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/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] = [:] 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..71ed4427 --- /dev/null +++ b/apps/purepoint-windows/src-tauri/src/browser/mod.rs @@ -0,0 +1,253 @@ +//! 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`). +/// 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()))?; + let session = browser.get(session_id)?; + match stream { + Some(stream) => session.send_on(op, stream), + None => session.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..e0244c8b --- /dev/null +++ b/apps/purepoint-windows/src-tauri/src/browser/session.rs @@ -0,0 +1,474 @@ +//! 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, + /// 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, + /// 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 { + 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), + 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); + +/// 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<(BrowserOp, Option)>, + _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, + attach_timeout: options.attach_timeout, + write_timeout: options.write_timeout, + stable_after: options.stable_after, + live_since: None, + streams: 0, + 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, 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))); + } +} + +/// 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, + attach_timeout: Duration, + write_timeout: Duration, + 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<(BrowserOp, Option)>, +} + +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 } => { + // 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, + 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 }); + } + + /// 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(), + op, + } + } + + async fn attach_once(&mut self) -> End { + self.live_since = None; + 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) = self.write(&mut writer, &attach).await { + return retry(error); + } + + // 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. + // 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) => { + // 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()), + } + // Live from here: what the pane sent before belongs to no stream. + if !self.drop_stale_ops() { + 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 { + tab_id: None, + width, + height, + scale, + }); + if let Err(message) = self.write(&mut writer, &resize).await { + return End::Retry { + message, + live: true, + }; + } + } + + // 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! { + op = self.ops.recv() => { + 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 }; + } + } + 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..0d360db3 --- /dev/null +++ b/apps/purepoint-windows/src-tauri/src/browser/session_tests.rs @@ -0,0 +1,605 @@ +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}}), + ); +} + +#[tokio::test] +async fn given_a_daemon_that_never_answers_the_attach_should_retry() { + let mut daemon = FakeDaemon::start(); + let (sink, mut seen) = 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. + 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); +} + +#[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 { + 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]); +} + +#[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/src-tauri/src/lib.rs b/apps/purepoint-windows/src-tauri/src/lib.rs index 9d299939..d2578035 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()) @@ -158,6 +163,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..e94e8d18 --- /dev/null +++ b/apps/purepoint-windows/ui/src/model/browser.test.ts @@ -0,0 +1,214 @@ +// 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://127.0.1.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.example.com/', + 'http://128.0.0.1/', + ]) { + 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..7a4e45f7 --- /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`), + * 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; + 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') || + /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(host) || + 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/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/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..347bf41e --- /dev/null +++ b/apps/purepoint-windows/ui/src/services/browser.ts @@ -0,0 +1,83 @@ +// 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 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 } + /** 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). 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; +} + +/** 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, 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/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..8bfb8f74 --- /dev/null +++ b/apps/purepoint-windows/ui/src/state/browserSession.test.ts @@ -0,0 +1,316 @@ +// 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[]; + /** The stream each sent op was bound to. */ + readonly bound: (number | undefined)[]; + 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: [], + bound: [], + closed: false, + }; + streams.push(fake); + const stream: BrowserStream = { + id: streams.length, + send: (op, live) => { + fake.sent.push(op); + fake.bound.push(live); + 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, 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', + 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: 'live' }); + stream().emit({ type: 'frame', seq: 3, data: '/9j/', width: 1024, height: 768 }); + expect(session.state.frame).toEqual({ + stream: 1, + 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(); + stream().emit({ type: 'live' }); + 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('givenOpsShouldBeBoundToTheLiveStreamAsTheBackendNumbersIt', async () => { + const { session, stream, backend } = makeSession(); + session.start(); + await settle(); + // 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); + // 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([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(); + 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(); + await settle(); + stream().emit({ type: 'live' }); + 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..40a40661 --- /dev/null +++ b/apps/purepoint-windows/ui/src/state/browserSession.ts @@ -0,0 +1,341 @@ +// 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 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'; +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 { + /** 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; + 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; + /** The attach stream now live (counted from 1): its frames number afresh. */ + readonly stream: number; +} + +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; + /** + * 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; + 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, + stream: 0, + })); + } + + /** 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.sessionLive = 0; + 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 }); + } + + /** + * 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 { + void this.stream?.send(op, this.sessionLive).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.sessionLive += 1; + this.store.setState({ phase: { kind: 'live' }, stream: this.state.stream + 1 }); + return; + case 'frame': + this.store.setState({ + frame: { + stream: this.state.stream, + 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..41122fc1 --- /dev/null +++ b/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.test.tsx @@ -0,0 +1,354 @@ +// 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()), + }; + const { unmount } = 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, unmount }; +} + +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('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('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' }) }); + 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(); + }); + + 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(); + } + }); + + 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(); + } + }); + + 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(); + } + }); + + 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 new file mode 100644 index 00000000..936f4305 --- /dev/null +++ b/apps/purepoint-windows/ui/src/views/browser/BrowserPaneView.tsx @@ -0,0 +1,604 @@ +// 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 stream = useStore(session.store, (s) => s.stream); + 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 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 && !isBlank && document.activeElement !== addressRef.current) { + canvasRef.current?.focus({ preventScroll: true }); + } + }, [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. + // 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); + useLayoutEffect(() => { + 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, + ); + }, [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.store.getState().stream} + cssSize={frameSize} + onInput={(event) => { + 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 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 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; + 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, + stream, + liveStream, + cssSize, + onInput, + onResize, + onDrawn, + onCopy, + onPaste, + onFocus, +}: BrowserCanvasProps) { + const canvas = useRef(null); + 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. */ + const frameStream = useRef(null); + const unmounted = useRef(false); + const handlers = useRef({ onResize, onDrawn, liveStream }); + useLayoutEffect(() => { + handlers.current = { onResize, onDrawn, liveStream }; + }); + + 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(); + }; + }, []); + + // 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 + // 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. + epoch.current += 1; + if (drawnSeq.current >= 0) { + const target = canvas.current; + target?.getContext('2d')?.clearRect(0, 0, target.width, target.height); + drawnSeq.current = -1; + } + drawnSize.current = null; + return; + } + 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; + } + const startedIn = epoch.current; + decodeFrame(data) + .then((image) => { + const target = canvas.current; + 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); + 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, + // 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]); + + // 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 }; + 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, pageSize())); + }} + onMouseUp={(event) => { + const { view, input } = mouse(event); + 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, pageSize())); + return; + } + const now = performance.now(); + if (now - lastHover.current < HOVER_INTERVAL_MS) return; + lastHover.current = now; + onInput(hoverInput(input, view, pageSize())); + }} + 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, + pageSize(), + ), + ); + }} + 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, }); }); 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-cli/src/commands/browser.rs b/crates/pu-cli/src/commands/browser.rs new file mode 100644 index 00000000..92b0d78a --- /dev/null +++ b/crates/pu-cli/src/commands/browser.rs @@ -0,0 +1,283 @@ +//! `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"))); + 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")); + } + + #[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 916afbfd..743a0862 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 5cfa44e1..3e634919 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, + }, /// Check a machine (`--machine `) for settings that drop connections; changes nothing Doctor { /// Output as JSON @@ -1125,6 +1136,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::Doctor { .. } => unreachable!("pu doctor returns before connecting"), Commands::Clean { worktree, 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..e87e9f59 --- /dev/null +++ b/crates/pu-engine/src/browser/cdp.rs @@ -0,0 +1,834 @@ +//! 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::{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. +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; +/// 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 { + #[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>>)>>>; + +/// 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<u8>, + 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<Outgoing>, + shared: Arc<Shared>, + next_id: AtomicU64, + events: broadcast::Sender<Arc<CdpEvent>>, +} + +/// 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<R: AsyncBufRead + Unpin>( + reader: &mut R, + buf: &mut Vec<u8>, +) -> std::io::Result<Read> { + 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 { + /// 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::<Outgoing>(); + 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 mut writer = writer; + let writer_shared = shared.clone(); + tokio::spawn(async move { + while let Some(message) = outbox_rx.recv().await { + writer_shared.queued.fetch_sub(1, Ordering::SeqCst); + // 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. + // 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, + }, + }; + // 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. + // `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 + }; + 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 + // answered, whatever its output pipe still does. + writer_shared.shut_down().await; + }); + + let reader_shared = shared.clone(); + let reader_events = events.clone(); + tokio::spawn(async move { + 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, + Ok(Read::TooLarge) => { + tracing::warn!( + limit = MAX_MESSAGE, + "devtools message too large; closing the browser connection" + ); + break; + } + } + if !buf.is_empty() { + match serde_json::from_slice::<Value>(&buf) { + Ok(message) => { + dispatch(message, &reader_shared.pending, &reader_events).await + } + Err(_) => tracing::debug!("unparseable devtools message"), + } + } + } + reader_shared.shut_down().await; + }); + + Arc::new(Self { + outbox, + shared, + next_id: AtomicU64::new(1), + events, + }) + } + + pub fn is_alive(&self) -> bool { + self.shared.alive.load(Ordering::SeqCst) + } + + /// Resolves once the browser's connection has ended. + pub async fn closed(&self) { + let notified = self.shared.closed.notified(); + if !self.is_alive() { + return; + } + notified.await; + } + + pub fn subscribe(&self) -> broadcast::Receiver<Arc<CdpEvent>> { + self.events.subscribe() + } + + fn message(&self, session_id: Option<&str>, method: &str, params: Value) -> (u64, Vec<u8>) { + 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<u8>, 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<Value, CdpError> { + 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<Value, CdpError> { + if !self.is_alive() { + return Err(CdpError::Closed); + } + 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 shutdown drains with: a call that registers + // after the browser closed would otherwise wait out the full timeout. + 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.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_at(deadline, rx).await { + Ok(Ok(result)) => result, + Ok(Err(_)) => Err(CdpError::Closed), + Err(_) => { + 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 (_, 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"); + } + } +} + +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}; + + /// 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 { + 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); + } + 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) { + 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 = 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); + } + + #[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) + ); + } + + #[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()); + } + + /// (open, a write waiting for it to open, what was written) + type GateState = (bool, Option<std::task::Waker>, Vec<u8>); + + /// A browser input pipe that takes nothing until it is opened. + #[derive(Clone, Default)] + struct Gate(Arc<std::sync::Mutex<GateState>>); + + impl AsyncWrite for Gate { + fn poll_write( + self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + buf: &[u8], + ) -> std::task::Poll<std::io::Result<usize>> { + 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::io::Result<()>> { + std::task::Poll::Ready(Ok(())) + } + fn poll_shutdown( + self: std::pin::Pin<&mut Self>, + _: &mut std::task::Context<'_>, + ) -> std::task::Poll<std::io::Result<()>> { + 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; 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!( + late.await.unwrap(), + 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}"); + } + + type TrickleState = (usize, Option<std::task::Waker>, Vec<u8>); + + /// A browser input pipe that takes `budget` bytes, then nothing until given more. + #[derive(Clone, Default)] + struct Trickle(Arc<std::sync::Mutex<TrickleState>>); + + impl AsyncWrite for Trickle { + fn poll_write( + self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + buf: &[u8], + ) -> std::task::Poll<std::io::Result<usize>> { + 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::io::Result<()>> { + std::task::Poll::Ready(Ok(())) + } + fn poll_shutdown( + self: std::pin::Pin<&mut Self>, + _: &mut std::task::Context<'_>, + ) -> std::task::Poll<std::io::Result<()>> { + 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"); + // 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 = { + 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_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(); + 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/keys.rs b/crates/pu-engine/src/browser/keys.rs new file mode 100644 index 00000000..78f25f92 --- /dev/null +++ b/crates/pu-engine/src/browser/keys.rs @@ -0,0 +1,142 @@ +//! 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). 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", + (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..96644def --- /dev/null +++ b/crates/pu-engine/src/browser/launch.rs @@ -0,0 +1,305 @@ +//! 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; +/// 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<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`. As +/// `OsString`s, so a profile path that is not UTF-8 reaches Chromium unchanged. +pub fn args(profile: &Path, as_root: bool) -> Vec<std::ffi::OsString> { + let mut user_data_dir = std::ffi::OsString::from("--user-data-dir="); + user_data_dir.push(profile.as_os_str()); + let mut args: Vec<std::ffi::OsString> = 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}").into(), + ]; + if as_root { + // Chromium refuses to run its sandbox as root (containers, some servers). + args.push("--no-sandbox".into()); + } + args.push("about:blank".into()); + 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, + } + + /// 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)> { + #[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)) + } + } + + 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: &[std::ffi::OsString], + 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(); + // 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 + .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); + 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 has = |args: &[std::ffi::OsString], flag: &str| args.iter().any(|a| a == flag); + let as_user = args(profile, false); + 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.to_string_lossy().starts_with("--remote-debugging-port")) + ); + assert!(!has(&as_user, "--no-sandbox")); + assert!(has(&args(profile, true), "--no-sandbox")); + } + + #[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..c70c87d9 --- /dev/null +++ b/crates/pu-engine/src/browser/mod.rs @@ -0,0 +1,1944 @@ +//! 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. +//! +//! 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; +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); +/// 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. +#[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, + /// When an op or viewer last used this browser. + last_used: std::sync::Mutex<tokio::time::Instant>, + /// Opens creating a tab right now: the browser is not retired while any runs. + pending_opens: std::sync::atomic::AtomicUsize, +} + +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 { + /// 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, wait: Duration) -> bool { + let child = self._child.lock().unwrap_or_else(|e| e.into_inner()).take(); + match stop_child(self.pid, child, wait).await { + Ok(()) => true, + Err(child) => { + *self._child.lock().unwrap_or_else(|e| e.into_inner()) = Some(child); + false + } + } + } + + 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<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(); + // 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<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()); + 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", + "DOM.enable", + "Accessibility.enable", + ] { + self.cdp.call(session, domain, json!({})).await?; + } + apply_viewport(&self.cdp, tab, tab.viewport()).await + } + + 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, viewport: Viewport) -> Result<()> { + 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) { + // 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), + "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_for(revision, index > 0, index + 1 < count); +} + +/// 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<u32>, + child: Option<tokio::process::Child>, + wait: Duration, +) -> 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(); + if wait.is_zero() { + return Err(child); + } + match tokio::time::timeout(wait, 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<Vec<String>> { + 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<HashMap<String, Arc<Instance>>>, + /// Serializes each project's browser startup. + startups: Mutex<HashMap<String, Arc<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<HashMap<String, tokio::process::Child>>, + /// 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<HashMap<String, std::fs::File>>, + /// Set once shutdown starts: no startup may publish a browser after it. + closing: std::sync::atomic::AtomicBool, + base_dir: Option<PathBuf>, + 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 { + 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()), + 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, + } + } + + /// 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 + } + + /// 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. + /// + /// 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.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 { + held.push(startup.lock_owned().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().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()) + .retain(|root, _| unconfirmed.contains(root)); + drop(held); + } + + 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 + /// `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<Arc<Instance>> { + self.instances + .lock() + .await + .get(root) + .filter(|instance| instance.cdp.is_alive()) + .cloned() + } + + 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>> { + // 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; + 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) { + 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, + } + }; + if let Some(dead) = dead + && !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); + 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?; + // Shutdown began while this browser started: it never becomes reachable. + if self.closing.load(std::sync::atomic::Ordering::SeqCst) { + // 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 + .pending_opens + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); + 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. + /// 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<Instance>) { + 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(self.exit_wait).await + { + // Not confirmed gone: keep owning it, so the next open waits for it. + self.instances + .lock() + .await + .entry(root.to_string()) + .or_insert(retired); + } + } + + #[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 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, self.exit_wait).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", + )); + } + // 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"] { + 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 mut child = Some(launched.child); + let cdp = Cdp::start(launched.reader, launched.writer); + let events = cdp.subscribe(); + 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(), self.exit_wait).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(child), + 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()), + 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)); + 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<Cdp>, Arc<Tab>)> { + let instance = self.running(root).await?; + instance.touch(); + 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, None).await { + Ok(response) => response, + Err(error) => error.into_response(), + } + } + + /// 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<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 } => { + // Counted as a pending open from inside `get_or_launch`. + let instance = self.get_or_launch(root).await?; + instance.touch(); + 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 + { + // 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); + 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 } => { + let instance = self.running(root).await?; + let tab = instance.resolve(tab_id.as_deref())?; + // 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?; + instance.remove_tab(&tab.target_id); + self.retire_if_unused(root, &instance).await; + return Ok(Response::Ok); + } + _ => {} + } + + 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( + "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 { .. } => { + // 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!({})) + .await?; + let nodes = tree + .get("nodes") + .and_then(Value::as_array) + .cloned() + .unwrap_or_default(); + 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, + }) + } + BrowserOp::Click { element, .. } => { + let (backend, page) = element_ref(&tab, &element)?; + let (x, y) = element_center(cdp, &tab, backend).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 { + element, + text, + submit, + .. + } => { + if let Some(element) = 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?; + 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, .. } => { + // 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. + // 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); + } + 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 + }, + }; + // 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 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. + // 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. + 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", + )), + } + } +} + +/// 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<Instance>, 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<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(); + // 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:", + "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) + .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") + || 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; + } + } + } + } +} + +/// 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(&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( + 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_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 + .call( + None, + "Target.getTargetInfo", + json!({ "targetId": tab.target_id }), + ) + .await + && let Some(info) = info.get("targetInfo") + { + tab.set_page_for( + revision, + 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(()) +} + +/// 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"), + ) + }) +} + +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, page: &tab::DocumentMark, x: f64, y: f64) -> Result<()> { + let session = Some(tab.session_id.as_str()); + let mouse = |kind: &str, buttons: u32| { + let button = if kind == "mouseMoved" { "none" } else { "left" }; + 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", + mouse("mousePressed", 1), + ) + .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(()) +} + +/// 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", + ) + })?; + let focused = cdp.call( + session, + "Runtime.callFunctionOn", + json!({ + "objectId": object_id, + // 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?; + // 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)); + } + 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(()) +} + +/// 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()); + } + // 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, mods), + ) + } + 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("localhost:3000/?r=http://x"), + "http://localhost:3000/?r=http://x" + ); + 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())); + 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_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 { + 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..3646cdb0 --- /dev/null +++ b/crates/pu-engine/src/browser/snapshot.rs @@ -0,0 +1,414 @@ +//! 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; +/// 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] = &[ + "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 { + 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))) + .collect(); + let root = nodes + .iter() + .find(|n| n.get("parentId").is_none()) + .or_else(|| nodes.first()); + let mut out = Writer { + by_id, + first_ref: first, + snapshot: Snapshot::default(), + lines: 0, + truncated: false, + }; + if let Some(root) = root { + out.walk(root); + } + 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>, + first_ref: usize, + snapshot: Snapshot, + lines: usize, + truncated: bool, +} + +impl<'a> Writer<'a> { + /// 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 Some(children) = node.get("childIds").and_then(Value::as_array) else { + continue; + }; + // 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)); + } + } + } + } + + /// 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_value(node); + let value = 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.first_ref + self.snapshot.refs.len()); + line.push_str(&format!(" [ref={reference}]")); + self.snapshot.refs.insert(reference, backend); + } + line.push('\n'); + self.snapshot.tree.push_str(&line); + true + } +} + +/// A node's value as text: strings as they are, numbers (sliders, spinbuttons) printed. +fn ax_value(node: &Value) -> std::borrow::Cow<'_, str> { + match node.get("value").and_then(|v| v.get("value")) { + Some(Value::String(s)) => std::borrow::Cow::Borrowed(s), + Some(Value::Number(n)) => std::borrow::Cow::Owned(n.to_string()), + _ => std::borrow::Cow::Borrowed(""), + } +} + +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 { + // 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)] +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_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_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_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(&[]); + 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..fe6f720c --- /dev/null +++ b/crates/pu-engine/src/browser/tab.rs @@ -0,0 +1,948 @@ +//! 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, +} + +/// 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 { + generation: u64, + url: String, +} + +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>>, + /// 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<()>, + /// 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: Mutex<u64>, + /// 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 { + 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(), + document: AtomicU64::new(0), + navigation: AtomicU64::new(0), + resizing: tokio::sync::Mutex::new(()), + snapshotting: tokio::sync::Mutex::new(()), + next_ref: AtomicU64::new(1), + history: Mutex::new(0), + viewport_confirmed: std::sync::atomic::AtomicBool::new(true), + } + } + + 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_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; + info.width = viewport.width; + info.height = viewport.height; + changed + }); + } + + pub fn begin_history_refresh(&self) -> u64 { + 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) { + let history = self.history.lock().unwrap_or_else(|e| e.into_inner()); + if *history == 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; + info.can_go_back = can_go_back; + info.can_go_forward = can_go_forward; + changed + }); + } + + /// 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 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<String, i64>, + url: Option<&str>, + title: Option<&str>, + ) { + if let Some(url) = url + && without_fragment(url) != without_fragment(&self.info.borrow().url) + { + refs.clear(); + } + 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) { + 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; + } + + /// 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 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, + mark: &DocumentMark, + refs: HashMap<String, i64>, + ) -> Option<BrowserTabInfo> { + let mut current = self.refs.lock().unwrap_or_else(|e| e.into_inner()); + let info = self.info(); + if self.document.load(Ordering::SeqCst) != mark.generation || info.url != mark.url { + return None; + } + *current = refs; + Some(info) + } + + /// 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.publish_page(url, None); + } + + pub fn resolve_ref(&self, reference: &str) -> Option<i64> { + 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); + 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 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 + } + + 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!({})); + // 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); + } + } + + /// 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 + } + + 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; + }; + // 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. 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"); + 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); + // Old refs point into the previous document. + self.new_document(url); + } + } + "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(); + tab.add_viewer(&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()); + } + + #[tokio::test] + async fn given_a_navigation_during_a_snapshot_should_refuse_its_refs() { + let tab = tab(); + let cdp = cdp(); + let mark = tab.document_mark(); + tab.on_event( + &event( + "Page.frameNavigated", + json!({"frame": {"id": "T1", "url": "http://b/"}}), + ), + &cdp, + ); + assert!( + 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_mark(), 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 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{}/", 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_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_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. + 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(); + 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); + } + + #[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(); + 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_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(); + 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/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) 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..7462f7f8 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}; @@ -42,6 +45,7 @@ enum StreamMode { Status(String), Projects, Fs { root: String, recursive: bool }, + Browser(String), } impl StreamMode { @@ -59,6 +63,7 @@ impl StreamMode { root: root.clone(), recursive: *recursive, }, + Request::BrowserAttach { project_root, .. } => Self::Browser(project_root.clone()), _ => Self::None, } } @@ -284,6 +289,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, @@ -304,9 +318,32 @@ 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. 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() { + 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()), + }; + engine + .browsers() + .handle(root, close, crate::browser::Caller::Agent) + .await; + } if is_shutdown { shutdown.notify_one(); } @@ -368,6 +405,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..fe4f29a3 100644 --- a/crates/pu-engine/src/ipc_server/streams.rs +++ b/crates/pu-engine/src/ipc_server/streams.rs @@ -562,6 +562,269 @@ 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; + +/// 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<String>) -> 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; +/// 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_bounded(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(); + // 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<u64> = VecDeque::new(); + // 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<tokio::sync::OwnedSemaphorePermit>, + )>(); + 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::<Option<BrowserOp>>(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)); + struct EndOnDrop(std::sync::Arc<std::sync::atomic::AtomicBool>); + 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 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; + } + // 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; + } + } + }); + } + let tab_id = tab.target_id.clone(); + let closed_response = || Response::BrowserTabClosed { + tab_id: tab_id.clone(), + }; + + if *closed.borrow() { + return write_bounded(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_bounded(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_bounded(writer, &Response::BrowserTabState { tab: state }).await.is_err() { + return false; + } + } + changed = closed.changed() => { + if changed.is_err() || *closed.borrow() { + return write_bounded(writer, &closed_response()).await.is_ok(); + } + } + Some((reply, permit)) = replies_rx.recv() => { + let written = write_bounded(writer, &reply).await; + drop(permit); + if written.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) => { + // 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, + }; + let Some(Request::Browser { mut op, .. }) = parse_stream_request(&line) else { + break; + }; + // 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(); + } + continue; + } + if matches!(op, BrowserOp::Resize { .. }) { + resize_tx.send_replace(Some(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 { .. }) + && write_bounded(writer, &resp).await.is_err() + { + return false; + } + 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 resp = browsers.handle(&root, op, Caller::Viewer).await; + let _ = replies.send((resp, Some(permit))); + }); + } + } + } + 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..240a5853 --- /dev/null +++ b/crates/pu-engine/tests/browser.rs @@ -0,0 +1,1220 @@ +//! 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 + } +} + +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:?}"), + } +} + +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(), + 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; + // The viewer's Control lands asynchronously: accept a few Oks while it does, + // 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:?}" + ); + // 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; +} + +#[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; +} + +#[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; +} + +#[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; +} + +#[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; +} + +#[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:?}"), + }; + // 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!( + viewer + .call(&Request::BrowserAttach { + project_root: root.clone(), + tab_id: Some(tab.tab_id.clone()), + }) + .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, + BrowserOp::Control { + tab_id: None, + driver: BrowserDriver::Human, + }, + )) + .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!(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, + "round {round}" + ); + } + 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; + // 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 + { + 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; +} + +#[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; +} + +#[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; + } +} + +#[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/crates/pu-engine/tests/browser_launch.rs b/crates/pu-engine/tests/browser_launch.rs new file mode 100644 index 00000000..b8089efd --- /dev/null +++ b/crates/pu-engine/tests/browser_launch.rs @@ -0,0 +1,210 @@ +//! Browser startup failures, with a stand-in browser (its own test binary: +//! it sets `PU_BROWSER` for the whole process, so its tests take turns). +#![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; + +/// `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(()); + +/// 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!( + "#!/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: 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 = open(&manager).await; + 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() + )); +} + +#[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" + ); +} + +#[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:?}" + ); +} + +#[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; +} diff --git a/docs/guide/cli-reference.md b/docs/guide/cli-reference.md index b82cf4db..69d03478 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 | @@ -297,6 +298,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..da7a743c --- /dev/null +++ b/docs/product/browser.md @@ -0,0 +1,121 @@ +# 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, 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. +- **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 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. +- *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 (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. 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.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 + +### Daemon and agents +- 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, 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. +- 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 +- 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. +- 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 + +``` +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). 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. + +## Future Work + +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. +- An "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..b28da0bf 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). 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://`) | +| `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_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 + +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 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 ### 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.