From 57b7c58b5f331a96bbd3e4f3e056b6c59e768a67 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Wed, 4 Nov 2026 19:25:30 -0600 Subject: [PATCH] fix(gui-plugins): drive browser pane bindings and tabs through one state machine (#61853) --- packages/gui-plugins/src/browser/ipc.ts | 23 + .../src/browser/pane-machine.test.ts | 329 +++++++++ .../gui-plugins/src/browser/pane-machine.ts | 534 ++++++++++++++ packages/gui-plugins/src/browser/pane.ts | 676 +++++++++--------- 4 files changed, 1231 insertions(+), 331 deletions(-) create mode 100644 packages/gui-plugins/src/browser/pane-machine.test.ts create mode 100644 packages/gui-plugins/src/browser/pane-machine.ts diff --git a/packages/gui-plugins/src/browser/ipc.ts b/packages/gui-plugins/src/browser/ipc.ts index 495a5e42f85..2bcd0e93ed8 100644 --- a/packages/gui-plugins/src/browser/ipc.ts +++ b/packages/gui-plugins/src/browser/ipc.ts @@ -66,6 +66,29 @@ export const PaneEvent = Schema.Union([ export type PaneEvent = typeof PaneEvent.Type +/** + * The `error` of the last `state` event of a binding that main closed. Other errors on a `state` event, such as + * `"page_crashed"` or a refused address, leave the binding open. + * + * - `"browser.pane.unsupported"`: the server has no browser plugin, or its `attached` handshake names a protocol this + * desktop cannot speak. The event carries no tabs. A control event of an unknown type closes nothing. + * - `"browser.pane.replaced"`: another window attached to the same session. The event carries no tabs. + * - `"browser.pane.suspended"`: the server dropped an attached binding (idle eviction), or main's plugin is going away. + * The event carries the tabs the binding had. + * - `"browser.pane.missing"`: the session no longer exists. The event carries no tabs, and main forgot its saved tabs. + * - `"browser.pane.registration.closed"`: the stream or attachment ended, registration timed out, the window navigated + * or closed, or the window closed the binding. The event carries no tabs; the window may register again. + */ +export const PaneCloseReason = Schema.Literals([ + "browser.pane.unsupported", + "browser.pane.replaced", + "browser.pane.suspended", + "browser.pane.missing", + "browser.pane.registration.closed", +]) + +export type PaneCloseReason = typeof PaneCloseReason.Type + /** * The native browser pane in the main process. A binding is one registration of a session's pane * by a window; its events go to that window only. diff --git a/packages/gui-plugins/src/browser/pane-machine.test.ts b/packages/gui-plugins/src/browser/pane-machine.test.ts new file mode 100644 index 00000000000..f817c99974d --- /dev/null +++ b/packages/gui-plugins/src/browser/pane-machine.test.ts @@ -0,0 +1,329 @@ +import { describe, expect, test } from "bun:test" +import { Browser } from "@opencode/plugin-browser/rpc" +import { SessionNotFoundError } from "@opencode/protocol/errors" +import { + attachmentFailure, + createPaneState, + decodeControl, + decodeControlHeader, + isCurrentPage, + resolveControlFrame, + selectBinding, + transitionBinding, + transitionPane, + type BindingEvent, + type PaneEffect, + type PaneMachineEvent, + type PaneState, +} from "./pane-machine" + +const connectionID = "connection-1" + +const tabA = Browser.TabID.make("tab_00000000-0000-0000-0000-00000000000a") + +const tabB = Browser.TabID.make("tab_00000000-0000-0000-0000-00000000000b") + +const missing = Browser.TabID.make("tab_00000000-0000-0000-0000-0000000000ff") + +const dashboard = "http://localhost:4173/dashboard" + +function tab(id: Browser.TabID, url: string, title = "", generation = 0): Browser.Tab { + return { id, url, title, loading: false, canGoBack: false, canGoForward: false, generation } +} + +function registered(restore?: Browser.State, binding = "b1"): PaneMachineEvent { + return { + type: "registered", + binding, + window: 1, + storageKey: `server\n${binding}`, + restore, + saved: { tabs: [], focusedTabID: null }, + } +} + +function on(event: BindingEvent, binding = "b1"): PaneMachineEvent { + return { type: "binding", binding, event } +} + +// Replays events through the pure machine and collects every effect it asked for, in order. +function play(state: PaneState, ...events: PaneMachineEvent[]) { + return events.reduce<{ state: PaneState; effects: readonly PaneEffect[] }>( + (result, event) => { + const next = transitionPane(result.state, event) + + return { state: next.state, effects: [...result.effects, ...next.effects] } + }, + { state, effects: [] }, + ) +} + +// The server reads the raw control event exactly as the driver does. +function frame(data: { + readonly type: string + readonly connectionID: string + readonly version?: number + readonly requestID?: string +}) { + return resolveControlFrame(connectionID, decodeControlHeader(data), decodeControl(data)) +} + +function attached(restore?: Browser.State) { + return play(createPaneState(), registered(restore), on({ type: "server.attached", fileRoots: [] })).state +} + +function entry(state: PaneState, binding = "b1") { + const value = selectBinding(state, binding) + + if (!value) throw new Error(`binding ${binding} is not active`) + + return value +} + +function closeEvents(effects: readonly PaneEffect[]) { + return effects.flatMap((effect) => + effect.type === "emit" && effect.event.type === "state" + ? [{ state: effect.event.state, error: effect.event.error }] + : [], + ) +} + +// tab_a restored at the dashboard, loaded as attempt 1, and published live. +function liveDashboard() { + return play( + attached({ tabs: [tab(tabA, dashboard, "Dashboard")], focusedTabID: tabA }), + on({ type: "tab.opened", tabID: tabA, attempt: 1, tab: tab(tabA, dashboard, "Dashboard", 1) }), + on({ type: "tab.published", tabID: tabA, attempt: 1, tab: tab(tabA, dashboard, "Dashboard", 1) }), + ).state +} + +describe("control events", () => { + test("an unknown control type from a newer server leaves the binding open", () => { + const unknown = frame({ type: "future.ping", connectionID }) + expect(unknown).toEqual({ kind: "unrecognized", controlType: "future.ping" }) + + const connecting = entry(play(createPaneState(), registered()).state) + + const open = entry(attached()) + + ;[connecting, open].forEach((state) => { + const next = transitionBinding(state, { type: "control.unrecognized", controlType: "future.ping" }) + expect(next.state).toBe(state) + expect(next.effects.map((effect) => effect.type)).toEqual(["warn"]) + }) + }) + + test("an attached handshake this desktop cannot decode marks the server unsupported", () => { + expect(frame({ type: "attached", connectionID, version: 5 })).toEqual({ kind: "incompatible" }) + expect(frame({ type: "attached", connectionID })).toEqual({ kind: "incompatible" }) + + const next = play(attached(), on({ type: "handshake.unsupported" })) + expect(selectBinding(next.state, "b1")).toBeUndefined() + expect(closeEvents(next.effects)).toEqual([{ state: null, error: "browser.pane.unsupported" }]) + }) + + test("decodes this connection's handshake and requests and ignores other connections", () => { + expect(frame({ type: "attached", connectionID: "other", version: 5 })).toEqual({ kind: "foreign" }) + expect(frame({ type: "attached", connectionID, version: 4 })).toEqual({ kind: "attached" }) + expect(frame({ type: "command", connectionID, requestID: "r1" })).toEqual({ kind: "command", requestID: "r1" }) + expect(frame({ type: "cancel", connectionID, requestID: "r1" })).toEqual({ kind: "cancel", requestID: "r1" }) + }) +}) + +describe("binding close reason", () => { + test("the first close reason wins over every later one", () => { + const replaced = play(attached(), on({ type: "attachment.ended", outcome: "replaced" })) + expect(closeEvents(replaced.effects)).toEqual([{ state: null, error: "browser.pane.replaced" }]) + + const later = play( + replaced.state, + on({ type: "attachment.ended", outcome: "unavailable" }), + on({ type: "owner.closed" }), + on({ type: "client.closed" }), + on({ type: "register.timed-out" }), + { type: "disposed" }, + ) + + expect(later.effects).toEqual([]) + + const closed = transitionBinding(entry(attached()), { type: "attachment.ended", outcome: "replaced" }).state + expect(transitionBinding(closed, { type: "pane.disposed" })).toEqual({ state: closed, effects: [] }) + }) + + test("an unavailable server suspends an attached binding with its tabs and rejects a connecting one", () => { + const restore = { tabs: [tab(tabA, dashboard)], focusedTabID: tabA } + const suspended = play(attached(restore), on({ type: "attachment.ended", outcome: "unavailable" })) + expect(closeEvents(suspended.effects)).toEqual([ + { state: { tabs: [tab(tabA, dashboard, "", 1)], focusedTabID: tabA }, error: "browser.pane.suspended" }, + ]) + expect(suspended.effects.map((effect) => effect.type)).not.toContain("remove-restore") + + const connecting = play( + createPaneState(), + registered(restore), + on({ type: "attachment.ended", outcome: attachmentFailure({ type: "rpc.unavailable", message: "gone" }) }), + ) + + expect(closeEvents(connecting.effects)).toEqual([{ state: null, error: "browser.pane.unsupported" }]) + expect(connecting.effects.at(-1)).toEqual({ type: "teardown", binding: "b1" }) + }) + + test("classifies attachment failures", () => { + expect(attachmentFailure(new SessionNotFoundError({ sessionID: "ses_1", message: "Session not found" }))).toBe( + "missing", + ) + expect(attachmentFailure({ type: "rpc.method_not_found" })).toBe("unsupported") + expect(attachmentFailure({ type: "rpc.invalid_input" })).toBe("unsupported") + expect(attachmentFailure({ type: "unavailable" })).toBe("closed") + expect(attachmentFailure(new Error("socket hang up"))).toBe("closed") + }) + + test("a missing session and the window's close forget the saved tabs; other closes keep them", () => { + const removes = (event: BindingEvent) => + play(attached(), on(event)).effects.some((effect) => effect.type === "remove-restore") + + expect(removes({ type: "attachment.ended", outcome: "missing" })).toBe(true) + expect(removes({ type: "client.closed" })).toBe(true) + expect(removes({ type: "owner.closed" })).toBe(false) + expect(removes({ type: "attachment.ended", outcome: "closed" })).toBe(false) + }) + + test("disposing the pane suspends every binding with its tabs and refuses new ones", () => { + const restore = { tabs: [tab(tabA, dashboard)], focusedTabID: tabA } + + const disposed = play( + createPaneState(), + registered(restore, "b1"), + registered(undefined, "b2"), + on({ type: "server.attached", fileRoots: [] }, "b2"), + { type: "disposed" }, + ) + + expect(disposed.state).toEqual({ status: "disposed" }) + expect(closeEvents(disposed.effects)).toEqual([ + { state: { tabs: [tab(tabA, dashboard, "", 1)], focusedTabID: tabA }, error: "browser.pane.suspended" }, + { state: { tabs: [], focusedTabID: null }, error: "browser.pane.suspended" }, + ]) + expect(transitionPane(disposed.state, registered())).toEqual({ state: disposed.state, effects: [] }) + }) + + test("the registration timeout closes only a binding still connecting", () => { + const timedOut = play(createPaneState(), registered(), on({ type: "register.timed-out" })) + expect(closeEvents(timedOut.effects)).toEqual([{ state: null, error: "browser.pane.registration.closed" }]) + expect(timedOut.effects.at(-1)).toEqual({ type: "teardown", binding: "b1" }) + + const open = attached() + expect(transitionPane(open, on({ type: "register.timed-out" }))).toEqual({ state: open, effects: [] }) + }) + + test("attaching resolves the registration and reports the restored tabs", () => { + const next = play(createPaneState(), registered(), on({ type: "server.attached", fileRoots: ["/repo"] })) + expect(next.effects.map((effect) => effect.type)).toEqual([ + "start-timer", + "resolve-register", + "save-restore", + "report", + ]) + }) +}) + +describe("tabs", () => { + test("a crashed page keeps its tab unloaded and loads again as a new attempt", () => { + const crashed = play( + liveDashboard(), + on({ type: "request.started", requestID: "req_1" }), + on({ type: "request.targeted", requestID: "req_1", tabID: tabA }), + on({ type: "tab.crashed", tabID: tabA, attempt: 1, tab: tab(tabA, dashboard, "Dashboard", 1) }), + ) + + const binding = entry(crashed.state) + expect(binding.tabs.get(tabA)).toEqual({ + status: "unloaded", + tab: { ...tab(tabA, dashboard, "Dashboard", 2), loadError: "page_crashed" }, + }) + expect(binding.focusedTabID).toBe(tabA) + expect(crashed.effects).toContainEqual({ type: "abort-requests", binding: "b1", requestIDs: ["req_1"] }) + expect(crashed.effects).toContainEqual({ type: "release-pages", binding: "b1", attempts: [1] }) + expect(crashed.effects).toContainEqual({ + type: "save-restore", + storageKey: "server\nb1", + snapshot: { tabs: [{ id: tabA, url: dashboard }], focusedTabID: tabA }, + }) + expect(crashed.effects.findLast((effect) => effect.type === "report")).toMatchObject({ + event: { error: "page_crashed" }, + }) + + const reloaded = play( + crashed.state, + on({ type: "tab.opened", tabID: tabA, attempt: 2, tab: tab(tabA, dashboard, "Dashboard", 2) }), + ) + + expect(entry(reloaded.state).tabs.get(tabA)).toMatchObject({ status: "live", attempt: 2 }) + expect(isCurrentPage(reloaded.state, "b1", tabA, 2)).toBe(true) + }) + + test("a page that crashes before committing its address keeps the last known address", () => { + const crashed = play( + liveDashboard(), + on({ type: "tab.published", tabID: tabA, attempt: 1, tab: tab(tabA, "", "", 2) }), + on({ type: "tab.crashed", tabID: tabA, attempt: 1, tab: tab(tabA, "", "", 2) }), + ) + + expect(entry(crashed.state).tabs.get(tabA)).toMatchObject({ status: "unloaded", tab: { url: dashboard } }) + }) + + test("results from an earlier page of the same tab are ignored", () => { + const current = play( + liveDashboard(), + on({ type: "tab.crashed", tabID: tabA, attempt: 1 }), + on({ type: "tab.opened", tabID: tabA, attempt: 2, tab: tab(tabA, dashboard, "", 2) }), + ).state + + ;[ + on({ type: "tab.crashed", tabID: tabA, attempt: 1 }), + on({ type: "tab.published", tabID: tabA, attempt: 1, tab: tab(tabA, "http://stale.test", "", 9) }), + on({ type: "tab.opened", tabID: tabA, attempt: 1, tab: tab(tabA, dashboard) }), + ].forEach((event) => expect(transitionPane(current, event)).toEqual({ state: current, effects: [] })) + expect(isCurrentPage(current, "b1", tabA, 1)).toBe(false) + }) + + test("an unchanged state is saved but not reported again", () => { + const published = on({ type: "tab.published", tabID: tabA, attempt: 1, tab: tab(tabA, dashboard, "Dashboard", 1) }) + const again = transitionPane(liveDashboard(), published) + expect(again.effects.map((effect) => effect.type)).toEqual(["save-restore"]) + }) + + test("tab events before the server attaches are ignored", () => { + const connecting = play(createPaneState(), registered()).state + const event = on({ type: "tab.opened", tabID: tabA, attempt: 1, tab: tab(tabA, dashboard) }) + expect(transitionPane(connecting, event)).toEqual({ state: connecting, effects: [] }) + }) +}) + +describe("focus", () => { + test("a restored focus that names no tab falls back to the first tab, or none", () => { + const stale = attached({ tabs: [tab(tabA, dashboard)], focusedTabID: missing }) + expect(entry(stale).focusedTabID).toBe(tabA) + expect(entry(attached({ tabs: [], focusedTabID: missing })).focusedTabID).toBeNull() + expect(transitionPane(stale, on({ type: "tab.focused", tabID: missing }))).toEqual({ state: stale, effects: [] }) + }) + + test("closing the focused tab focuses the next one and aborts only its requests", () => { + const closed = play( + attached({ tabs: [tab(tabA, dashboard), tab(tabB, "http://b.test")], focusedTabID: tabA }), + on({ type: "tab.opened", tabID: tabA, attempt: 1, tab: tab(tabA, dashboard) }), + on({ type: "request.started", requestID: "on-a" }), + on({ type: "request.targeted", requestID: "on-a", tabID: tabA }), + on({ type: "request.started", requestID: "on-b" }), + on({ type: "request.targeted", requestID: "on-b", tabID: tabB }), + on({ type: "tab.closed", tabID: tabA }), + ) + + const binding = entry(closed.state) + expect(binding.focusedTabID).toBe(tabB) + expect(Array.from(binding.tabs.keys())).toEqual([tabB]) + expect(closed.effects).toContainEqual({ type: "abort-requests", binding: "b1", requestIDs: ["on-a"] }) + expect(closed.effects).toContainEqual({ type: "release-pages", binding: "b1", attempts: [1] }) + expect(binding.status === "attached" && Array.from(binding.requests.keys())).toEqual(["on-b"]) + }) +}) diff --git a/packages/gui-plugins/src/browser/pane-machine.ts b/packages/gui-plugins/src/browser/pane-machine.ts new file mode 100644 index 00000000000..47f4a469796 --- /dev/null +++ b/packages/gui-plugins/src/browser/pane-machine.ts @@ -0,0 +1,534 @@ +import { Browser } from "@opencode/plugin-browser/rpc" +import { Option, Predicate, Schema } from "effect" +import type { PaneCloseReason, PaneEvent } from "./ipc" + +/** How long a binding may wait for the server's `attached` handshake before it closes. */ +export const REGISTER_TIMEOUT_MS = 15_000 + +/** + * One tab of a binding. A closed tab is absent from its binding's `tabs`. + * + * - `unloaded`: only the tab's metadata. A restored tab stays here until the pane shows it or an agent command names + * it; a tab whose page crashed returns here, with `loadError`, so it can be loaded again. + * - `live`: a page exists for `attempt`. Results from an earlier page of the same tab carry another attempt. + * `url` is the last address the page reported, kept while a new document has not committed one. + */ +export type TabSlot = + | { readonly status: "unloaded"; readonly tab: Browser.Tab } + | { readonly status: "live"; readonly attempt: number; readonly tab: Browser.Tab; readonly url: string } + +type Inventory = { + readonly binding: string + readonly window: number + readonly storageKey: string + readonly tabs: ReadonlyMap + /** Null or a key of `tabs`. */ + readonly focusedTabID: Browser.TabID | null + /** The attempt the next page of this binding gets. */ + readonly nextAttempt: number +} + +/** + * One window's registration of a session's pane. + * + * - `connecting`: waiting for the server's `attached` handshake; the window's `register` call is pending. + * - `attached`: the server accepted the attachment; tabs open and agent requests run. + * - `closed`: final. The first reason wins; every later event is ignored. + */ +export type BindingState = + | (Inventory & { readonly status: "connecting" }) + | (Inventory & { + readonly status: "attached" + /** Workspace directories whose files may load as file:// documents; empty unless the server shares this disk. */ + readonly fileRoots: readonly string[] + /** Agent requests in flight, with the tab each one targets once known. */ + readonly requests: ReadonlyMap + /** The last state event reported, so an unchanged state is not sent again. */ + readonly published: string | undefined + }) + | { readonly status: "closed"; readonly binding: string; readonly reason: PaneCloseReason } + +export type ActiveBinding = Exclude + +type AttachedBinding = Extract + +/** Every binding of the main process, until the plugin goes away. */ +export type PaneState = + | { readonly status: "active"; readonly bindings: ReadonlyMap } + | { readonly status: "disposed" } + +/** How the attachment's Effect ended: the attach call's result, or the error it failed with. */ +export type AttachmentOutcome = "closed" | "replaced" | "missing" | "unavailable" | "unsupported" + +/** A browser control event from the server's stream, as this binding reads it. */ +export type ControlFrame = + | { readonly kind: "foreign" } + | { readonly kind: "attached" } + | { readonly kind: "command"; readonly requestID: string } + | { readonly kind: "cancel"; readonly requestID: string } + /** An `attached` handshake this desktop cannot decode: the server speaks another protocol version. */ + | { readonly kind: "incompatible" } + /** Any other event this desktop cannot decode, such as a control type a newer server added. */ + | { readonly kind: "unrecognized"; readonly controlType: string | undefined } + +export type StoredRestore = { + readonly tabs: readonly { readonly id: Browser.TabID; readonly url: string }[] + readonly focusedTabID: Browser.TabID | null +} + +export type BindingEvent = + | { readonly type: "server.attached"; readonly fileRoots: readonly string[] } + | { readonly type: "handshake.unsupported" } + | { readonly type: "control.unrecognized"; readonly controlType: string | undefined } + | { readonly type: "attachment.ended"; readonly outcome: AttachmentOutcome } + | { readonly type: "register.timed-out" } + /** The window navigated or was destroyed. */ + | { readonly type: "owner.closed" } + /** The window closed the binding; its saved tabs are forgotten. */ + | { readonly type: "client.closed" } + | { readonly type: "pane.disposed" } + | { readonly type: "request.started"; readonly requestID: string } + | { readonly type: "request.targeted"; readonly requestID: string; readonly tabID: Browser.TabID } + | { readonly type: "request.cancelled"; readonly requestID: string } + | { readonly type: "request.finished"; readonly requestID: string } + /** A page for `tabID` was created as `attempt`, the binding's `nextAttempt`. */ + | { readonly type: "tab.opened"; readonly tabID: Browser.TabID; readonly attempt: number; readonly tab: Browser.Tab } + | { + readonly type: "tab.published" + readonly tabID: Browser.TabID + readonly attempt: number + readonly tab: Browser.Tab + readonly error?: string + } + /** The page's renderer crashed, its debugger detached, or it failed to become ready. */ + | { + readonly type: "tab.crashed" + readonly tabID: Browser.TabID + readonly attempt: number + readonly tab?: Browser.Tab + } + | { readonly type: "tab.focused"; readonly tabID: Browser.TabID } + | { readonly type: "tab.closed"; readonly tabID: Browser.TabID } + +export type PaneMachineEvent = + | { + readonly type: "registered" + readonly binding: string + readonly window: number + readonly storageKey: string + /** The window's inventory, which wins over the saved one. */ + readonly restore: Browser.State | undefined + readonly saved: StoredRestore + } + | { readonly type: "binding"; readonly binding: string; readonly event: BindingEvent } + | { readonly type: "disposed" } + +type StateEvent = Extract + +export type PaneEffect = + | { readonly type: "start-timer"; readonly binding: string; readonly ms: number } + | { readonly type: "resolve-register"; readonly binding: string } + | { readonly type: "save-restore"; readonly storageKey: string; readonly snapshot: StoredRestore } + | { readonly type: "remove-restore"; readonly storageKey: string } + /** To the window and, as the server's copy of the inventory, to the server. */ + | { + readonly type: "report" + readonly binding: string + readonly event: StateEvent & { readonly state: Browser.State } + } + /** To the window only. */ + | { readonly type: "emit"; readonly binding: string; readonly event: PaneEvent } + | { readonly type: "abort-requests"; readonly binding: string; readonly requestIDs: readonly string[] } + | { readonly type: "release-pages"; readonly binding: string; readonly attempts: readonly number[] } + /** Rejects a pending `register` call, stops the timer and listeners, and ends the attachment. Always last. */ + | { readonly type: "teardown"; readonly binding: string } + | { readonly type: "warn"; readonly message: string; readonly detail: string | undefined } + +export type BindingTransition = { readonly state: BindingState; readonly effects: readonly PaneEffect[] } + +export type PaneTransition = { readonly state: PaneState; readonly effects: readonly PaneEffect[] } + +type AttachedTransition = { readonly state: AttachedBinding; readonly effects: readonly PaneEffect[] } + +const ControlHeader = Schema.Struct({ connectionID: Schema.String, type: Schema.optional(Schema.String) }) + +export const decodeControlHeader = Schema.decodeUnknownOption(ControlHeader) + +export const decodeControl = Schema.decodeUnknownOption(Browser.Control) + +export function createPaneState(): PaneState { + return { status: "active", bindings: new Map() } +} + +/** Reads a control event. Only an `attached` handshake this desktop cannot decode makes the server unsupported. */ +export function resolveControlFrame( + connectionID: string, + header: Option.Option, + control: Option.Option, +): ControlFrame { + if (Option.isNone(header) || header.value.connectionID !== connectionID) return { kind: "foreign" } + + if (Option.isNone(control)) + return header.value.type === "attached" + ? { kind: "incompatible" } + : { kind: "unrecognized", controlType: header.value.type } + + if (control.value.type === "attached") return { kind: "attached" } + + return { kind: control.value.type, requestID: control.value.requestID } +} + +export function attachmentFailure(cause: unknown): AttachmentOutcome { + if (Predicate.isTagged(cause, "SessionNotFoundError")) return "missing" + const type = Predicate.hasProperty(cause, "type") ? cause.type : undefined + + if (type === "rpc.unavailable") return "unavailable" + + if (type === "rpc.method_not_found" || type === "rpc.invalid_input") return "unsupported" + + return "closed" +} + +export function transitionPane(state: PaneState, event: PaneMachineEvent): PaneTransition { + if (state.status === "disposed") return { state, effects: [] } + + if (event.type === "disposed") + return { + state: { status: "disposed" }, + effects: Array.from(state.bindings.values()).flatMap( + (binding) => transitionBinding(binding, { type: "pane.disposed" }).effects, + ), + } + + if (event.type === "registered") { + if (state.bindings.has(event.binding)) return { state, effects: [] } + + return { + state: { status: "active", bindings: new Map(state.bindings).set(event.binding, createConnecting(event)) }, + effects: [{ type: "start-timer", binding: event.binding, ms: REGISTER_TIMEOUT_MS }], + } + } + + const binding = state.bindings.get(event.binding) + + if (!binding) return { state, effects: [] } + const next = transitionBinding(binding, event.event) + + if (next.state === binding) return { state, effects: next.effects } + const bindings = new Map(state.bindings) + + if (next.state.status === "closed") bindings.delete(event.binding) + + if (next.state.status !== "closed") bindings.set(event.binding, next.state) + + return { state: { status: "active", bindings }, effects: next.effects } +} + +export function transitionBinding(state: BindingState, event: BindingEvent): BindingTransition { + if (state.status === "closed") return { state, effects: [] } + const reason = closeReason(state, event) + + if (reason) return close(state, reason, event.type === "client.closed" || reason === "browser.pane.missing") + + if (event.type === "control.unrecognized") + return { + state, + effects: [{ type: "warn", message: "Ignored an unrecognized browser control event", detail: event.controlType }], + } + + if (state.status === "attached") return transitionAttached(state, event) + + if (event.type !== "server.attached") return { state, effects: [] } + + const next = publish({ + ...state, + status: "attached", + fileRoots: event.fileRoots, + requests: new Map(), + published: undefined, + }) + + return { state: next.state, effects: [{ type: "resolve-register", binding: state.binding }, ...next.effects] } +} + +function closeReason(state: ActiveBinding, event: BindingEvent): PaneCloseReason | undefined { + if (event.type === "handshake.unsupported") return "browser.pane.unsupported" + + if (event.type === "owner.closed" || event.type === "client.closed") return "browser.pane.registration.closed" + + if (event.type === "pane.disposed") return "browser.pane.suspended" + + if (event.type === "register.timed-out") + return state.status === "connecting" ? "browser.pane.registration.closed" : undefined + + if (event.type !== "attachment.ended") return undefined + + if (event.outcome === "replaced") return "browser.pane.replaced" + + if (event.outcome === "missing") return "browser.pane.missing" + + if (event.outcome === "unsupported") return "browser.pane.unsupported" + + // A server that drops an attachment it accepted, as on idle eviction, suspends it; one that never accepted it has no + // browser plugin. + if (event.outcome === "unavailable") + return state.status === "attached" ? "browser.pane.suspended" : "browser.pane.unsupported" + + return "browser.pane.registration.closed" +} + +function close(state: ActiveBinding, reason: PaneCloseReason, forget: boolean): BindingTransition { + const requestIDs = state.status === "attached" ? Array.from(state.requests.keys()) : [] + const attempts = Array.from(state.tabs.values()).flatMap((slot) => (slot.status === "live" ? [slot.attempt] : [])) + const effects: PaneEffect[] = [] + + if (forget) effects.push({ type: "remove-restore", storageKey: state.storageKey }) + + if (requestIDs.length) effects.push({ type: "abort-requests", binding: state.binding, requestIDs }) + // A suspended binding hands its tabs to the window, which keeps them until it registers again. + effects.push({ + type: "emit", + binding: state.binding, + event: { + type: "state", + state: reason === "browser.pane.suspended" ? selectInventory(state) : null, + error: reason, + }, + }) + + if (attempts.length) effects.push({ type: "release-pages", binding: state.binding, attempts }) + effects.push({ type: "teardown", binding: state.binding }) + + return { state: { status: "closed", binding: state.binding, reason }, effects } +} + +function transitionAttached(state: AttachedBinding, event: BindingEvent): BindingTransition { + if (event.type === "request.started") { + if (state.requests.has(event.requestID)) return { state, effects: [] } + + return { state: { ...state, requests: new Map(state.requests).set(event.requestID, undefined) }, effects: [] } + } + + if (event.type === "request.targeted") { + if (!state.requests.has(event.requestID)) return { state, effects: [] } + + return { state: { ...state, requests: new Map(state.requests).set(event.requestID, event.tabID) }, effects: [] } + } + + if (event.type === "request.cancelled" || event.type === "request.finished") { + if (!state.requests.has(event.requestID)) return { state, effects: [] } + const requests = new Map(state.requests) + requests.delete(event.requestID) + + return { + state: { ...state, requests }, + effects: + event.type === "request.cancelled" + ? [{ type: "abort-requests", binding: state.binding, requestIDs: [event.requestID] }] + : [], + } + } + + if (event.type === "tab.focused") { + if (!state.tabs.has(event.tabID)) return { state, effects: [] } + const next = publish({ ...state, focusedTabID: event.tabID }) + + return { + state: next.state, + effects: [ + ...next.effects, + { type: "emit", binding: state.binding, event: { type: "focus", tabID: event.tabID } }, + ], + } + } + + if (event.type === "tab.opened") { + if (event.attempt !== state.nextAttempt || state.tabs.get(event.tabID)?.status === "live") + return { state, effects: [] } + + return { + state: { + ...state, + tabs: new Map(state.tabs).set(event.tabID, { + status: "live", + attempt: event.attempt, + tab: event.tab, + url: event.tab.url, + }), + nextAttempt: event.attempt + 1, + }, + effects: [], + } + } + + if (event.type === "tab.closed") { + const closed = state.tabs.get(event.tabID) + + if (!closed) return { state, effects: [] } + const tabs = new Map(state.tabs) + tabs.delete(event.tabID) + const focusedTabID = state.focusedTabID === event.tabID ? (tabs.keys().next().value ?? null) : state.focusedTabID + + return withoutTab({ ...state, tabs, focusedTabID }, event.tabID, closed, undefined) + } + + if (event.type !== "tab.published" && event.type !== "tab.crashed") return { state, effects: [] } + const slot = state.tabs.get(event.tabID) + + if (slot?.status !== "live" || slot.attempt !== event.attempt) return { state, effects: [] } + + if (event.type === "tab.published") { + const tabs = new Map(state.tabs).set(event.tabID, { ...slot, tab: event.tab, url: event.tab.url || slot.url }) + + return publish({ ...state, tabs }, event.error) + } + + // A crashed page keeps its tab, unloaded, so showing it or an agent command on it loads its address again. + const latest = event.tab ?? slot.tab + + const tabs = new Map(state.tabs).set(event.tabID, { + status: "unloaded", + tab: { + id: event.tabID, + url: latest.url || slot.url || "about:blank", + title: latest.title, + loading: false, + loadError: "page_crashed", + canGoBack: false, + canGoForward: false, + // The next page's first navigation takes this generation. + generation: latest.generation + 1, + }, + }) + + return withoutTab({ ...state, tabs }, event.tabID, slot, "page_crashed") +} + +/** Aborts the requests that target a tab whose page went away, releases that page, and publishes the result. */ +function withoutTab(state: AttachedBinding, tabID: Browser.TabID, slot: TabSlot, error: string | undefined) { + const targeting = Array.from(state.requests).flatMap(([requestID, target]) => (target === tabID ? [requestID] : [])) + const requests = new Map(state.requests) + targeting.forEach((requestID) => requests.delete(requestID)) + const next = publish({ ...state, requests }, error) + const effects: PaneEffect[] = [] + + if (targeting.length) effects.push({ type: "abort-requests", binding: state.binding, requestIDs: targeting }) + + if (slot.status === "live") effects.push({ type: "release-pages", binding: state.binding, attempts: [slot.attempt] }) + + return { state: next.state, effects: [...effects, ...next.effects] } +} + +/** Saves the tabs for the next launch, and reports the state unless it repeats the last one reported. */ +function publish(state: AttachedBinding, error?: string): AttachedTransition { + const inventory = selectInventory(state) + + const event = + error === undefined + ? { type: "state" as const, state: inventory } + : { type: "state" as const, state: inventory, error } + + const published = JSON.stringify(event) + + const save: PaneEffect = { + type: "save-restore", + storageKey: state.storageKey, + snapshot: { + tabs: Array.from(state.tabs.values(), (slot) => ({ + id: slot.tab.id, + // A page can publish before Chromium assigns its URL. + url: slot.tab.url || (slot.status === "live" ? slot.url : "") || "about:blank", + })), + focusedTabID: state.focusedTabID, + }, + } + + if (published === state.published) return { state, effects: [save] } + + return { state: { ...state, published }, effects: [save, { type: "report", binding: state.binding, event }] } +} + +function createConnecting(event: Extract): ActiveBinding { + const restore = event.restore ?? { + tabs: event.saved.tabs.map((tab) => ({ + id: tab.id, + url: tab.url, + title: "", + loading: false, + canGoBack: false, + canGoForward: false, + generation: 0, + })), + focusedTabID: event.saved.focusedTabID, + } + + const tabs = new Map( + restore.tabs.map((tab): [Browser.TabID, TabSlot] => [ + tab.id, + { + status: "unloaded", + // A restored page's first navigation takes the next generation. + tab: { ...tab, loading: false, canGoBack: false, canGoForward: false, generation: tab.generation + 1 }, + }, + ]), + ) + + return { + status: "connecting", + binding: event.binding, + window: event.window, + storageKey: event.storageKey, + tabs, + focusedTabID: + restore.focusedTabID !== null && tabs.has(restore.focusedTabID) + ? restore.focusedTabID + : (tabs.keys().next().value ?? null), + nextAttempt: 1, + } +} + +export function isPaneDisposed(state: PaneState) { + return state.status === "disposed" +} + +export function selectBinding(state: PaneState, binding: string) { + return state.status === "active" ? state.bindings.get(binding) : undefined +} + +/** The binding when `window` registered it. */ +export function selectOwnedBinding(state: PaneState, window: number, binding: string) { + const entry = selectBinding(state, binding) + + return entry?.window === window ? entry : undefined +} + +export function selectFileRoots(state: PaneState, binding: string): readonly string[] { + const entry = selectBinding(state, binding) + + return entry?.status === "attached" ? entry.fileRoots : [] +} + +export function selectInventory(entry: ActiveBinding): Browser.State { + return { tabs: Array.from(entry.tabs.values(), (slot) => slot.tab), focusedTabID: entry.focusedTabID } +} + +export function selectTabSlot(state: PaneState, binding: string, tabID: Browser.TabID) { + const entry = selectBinding(state, binding) + + return entry?.status === "attached" ? entry.tabs.get(tabID) : undefined +} + +/** The attempt of the tab's current page, if it has one. */ +export function selectPageAttempt(state: PaneState, binding: string, tabID: Browser.TabID) { + const slot = selectTabSlot(state, binding, tabID) + + return slot?.status === "live" ? slot.attempt : undefined +} + +export function isCurrentPage(state: PaneState, binding: string, tabID: Browser.TabID, attempt: number) { + return selectPageAttempt(state, binding, tabID) === attempt +} + +export function isFocusedPage(state: PaneState, binding: string, tabID: Browser.TabID, attempt: number) { + return isCurrentPage(state, binding, tabID, attempt) && selectBinding(state, binding)?.focusedTabID === tabID +} diff --git a/packages/gui-plugins/src/browser/pane.ts b/packages/gui-plugins/src/browser/pane.ts index 96ad4405629..1e25a07d864 100644 --- a/packages/gui-plugins/src/browser/pane.ts +++ b/packages/gui-plugins/src/browser/pane.ts @@ -3,7 +3,7 @@ import { Browser } from "@opencode/plugin-browser/rpc" import { OpenCode } from "@opencode/client/effect" import { SessionID } from "@opencode/schema/session-id" import electron, { type BrowserWindow } from "electron" -import { Deferred, Effect, ManagedRuntime, Predicate, Queue, Schedule, Schema, Stream } from "effect" +import { Cause, Deferred, Effect, ManagedRuntime, Option, Queue, Schedule, Schema, Stream } from "effect" import { HttpClient, HttpClientRequest } from "effect/http" import type { BuiltinMainStorage } from "@opencode/plugin/gui/builtin" import type { Embeds, Persisted, ServerEndpoints, Windows } from "@opencode/plugin/gui/main" @@ -13,33 +13,52 @@ import { createBrowserNetwork, type BrowserNetwork } from "./network" import { destinationOrigin, fileURLWithin, refusal } from "./policy" import { createRefs } from "./refs" import type { PaneEvent } from "./ipc" +import { + attachmentFailure, + createPaneState, + decodeControl, + decodeControlHeader, + isCurrentPage, + isFocusedPage, + isPaneDisposed, + resolveControlFrame, + selectBinding, + selectFileRoots, + selectInventory, + selectOwnedBinding, + selectPageAttempt, + selectTabSlot, + transitionPane, + type AttachmentOutcome, + type BindingEvent, + type PaneEffect, + type PaneMachineEvent, + type PaneState, +} from "./pane-machine" import { createBrowserRestoreStore } from "./restore" type Target = { readonly server: string; readonly session: string; readonly restore?: Browser.State } -type Entry = { - binding: string +/** The Electron and Effect handles of one binding; its phase lives in the pane machine. */ +type Handle = { window: number win: BrowserWindow + partition: string abort: AbortController registered: ReturnType> - requests: Map - report?: (event: PaneEvent) => void - cleanup?: () => void - pages: Map - tabs: Map - focusedTabID: Browser.TabID | null - partition: string - lastState?: string + cleanup: () => void + timer?: ReturnType network?: BrowserNetwork - storageKey: string - /** - * Workspace directories whose files may load as file:// documents. Set only for the desktop's - * own sidecar: a forwarded or explicit loopback server does not share this machine's disk. - */ - fileRoots: string[] + sendState?: (state: Browser.State) => void + /** Pages by attempt. */ + pages: Map + /** Agent requests in flight by request ID. */ + requests: Map } +/** The pane machine's current state; only `dispatch` replaces it. */ +type PaneMachine = { state: PaneState } + export type Pane = ReturnType export function createBrowserPane(input: { @@ -51,98 +70,75 @@ export function createBrowserPane(input: { readonly embeds: Embeds readonly emit: (window: number, value: { readonly binding: string; readonly event: PaneEvent }) => void }) { - const entries = new Map() + const machine: PaneMachine = { state: createPaneState() } + const handles = new Map() const restore = createBrowserRestoreStore(input.storage) const shared: Shared = { ref: createRefs(input.refs) } // Page disposals in flight. Finishing a trace or CPU profile can hold a page open, and the pane's own disposal waits // for them so a replacement never starts beside old pages still recording. const releasing = new Set>() + const disposals = new WeakMap>() // Keep long-lived RPC requests off Chromium's shared HTTP connection pool. const runtime = ManagedRuntime.make(NodeHttpClient.layerNodeHttp) - let disposed = false return { async register(window: number, binding: string, target: Target) { const server = input.serverEndpoints.get(target.server) - if (disposed || !server || !destinationOrigin(server.url)) throw new Error("browser.pane.registration.invalid") + if (isPaneDisposed(machine.state) || !server || !destinationOrigin(server.url)) + throw new Error("browser.pane.registration.invalid") const win = input.windows.get(window) - if (!win || entries.has(binding)) throw new Error("browser.pane.owner.invalid") + if (!win || selectBinding(machine.state, binding) || handles.has(binding)) + throw new Error("browser.pane.owner.invalid") if (win.isDestroyed() || win.webContents.isDestroyed()) throw new Error("browser.pane.owner.unavailable") const sessionID = SessionID.make(target.session) const storageKey = `${target.server}\n${sessionID}` - const saved = restore.load(storageKey) - - const previous = target.restore ?? { - tabs: saved.tabs.map((tab) => ({ - ...tab, - title: "", - generation: 0, - })), - focusedTabID: saved.focusedTabID, - } - - const entry: Entry = { - binding, - window, - win, - abort: new AbortController(), - registered: Promise.withResolvers(), - requests: new Map(), - pages: new Map(), - tabs: new Map( - previous.tabs.map((tab) => [ - tab.id, - { - ...tab, - loading: false, - canGoBack: false, - canGoForward: false, - generation: tab.generation + 1, - }, - ]), - ), - focusedTabID: previous.focusedTabID, - partition: `opencode-browser-${crypto.randomUUID()}`, - storageKey, - fileRoots: [], - } + const partition = `opencode-browser-${crypto.randomUUID()}` // Navigation guards cover documents; subresources (img, script, fetch) also must not read // file: URLs outside the roots. One listener per partition covers every page in this attachment. electron.session - .fromPartition(entry.partition) + .fromPartition(partition) .webRequest.onBeforeRequest({ urls: ["file://*/*"] }, (details, callback) => - callback({ cancel: !fileURLWithin(details.url, entry.fileRoots) }), + callback({ cancel: !fileURLWithin(details.url, selectFileRoots(machine.state, binding)) }), ) - // "unsupported" means the server has no browser plugin; the renderer stops retrying. - let reason: - | "browser.pane.unsupported" - | "browser.pane.replaced" - | "browser.pane.suspended" - | "browser.pane.missing" - | undefined - - let attached = false - const stop = () => close(entry, reason) + const closed = () => dispatchBinding(binding, { type: "owner.closed" }) const navigate = (event: Electron.Event<{ isMainFrame: boolean; isSameDocument: boolean }>) => { - if (event.isMainFrame && !event.isSameDocument) stop() + if (event.isMainFrame && !event.isSameDocument) closed() } - win.webContents.once("destroyed", stop) + win.webContents.once("destroyed", closed) win.webContents.on("did-start-navigation", navigate) - entry.cleanup = () => { - if (win.isDestroyed()) return - win.webContents.off("destroyed", stop) - win.webContents.off("did-start-navigation", navigate) + + const handle: Handle = { + window, + win, + partition, + abort: new AbortController(), + registered: Promise.withResolvers(), + cleanup: () => { + if (win.isDestroyed()) return + win.webContents.off("destroyed", closed) + win.webContents.off("did-start-navigation", navigate) + }, + pages: new Map(), + requests: new Map(), } - entries.set(binding, entry) + handles.set(binding, handle) + dispatch({ + type: "registered", + binding, + window, + storageKey, + restore: target.restore, + saved: restore.load(storageKey), + }) void runtime .runPromise( Effect.gen(function* () { @@ -161,8 +157,9 @@ export function createBrowserPane(input: { const session = yield* client.session.get({ sessionID }) - // The agent can already read this workspace, so showing its files adds no access. - if (server.sameMachine) entry.fileRoots = [session.location.directory] + // The agent can already read this workspace, so showing its files adds no access. A forwarded or explicit + // loopback server does not share this machine's disk. + const fileRoots = server.sameMachine ? [session.location.directory] : [] const options = { location: { directory: session.location.directory, workspace: session.location.workspaceID }, @@ -170,12 +167,7 @@ export function createBrowserPane(input: { const attachment = { sessionID, connectionID: crypto.randomUUID() } const rpc = client.rpc(Browser.Definition) - entry.network = yield* createBrowserNetwork({ - rpc, - attachment, - location: options.location, - partition: entry.partition, - }) + handle.network = yield* createBrowserNetwork({ rpc, attachment, location: options.location, partition }) const connected = yield* Deferred.make() const outbound = yield* Queue.unbounded>() @@ -197,19 +189,57 @@ export function createBrowserPane(input: { // inventory resolves every tab ID, so a state is retried until it arrives or the attachment // ends; the results queued behind it then never name a tab the server lacks. "unavailable" // means the server already dropped this attachment, which attach reports. - entry.report = (event) => { - publish(entry, event) - - if (event.type !== "state") return + handle.sendState = (state) => send( - rpc.state({ ...attachment, state: event.state ?? { tabs: [], focusedTabID: null } }, options).pipe( + rpc.state({ ...attachment, state }, options).pipe( Effect.retry({ while: (error) => !("type" in error && error.type === "unavailable"), schedule: Schedule.min([Schedule.exponential("250 millis"), Schedule.spaced("10 seconds")]), }), ), ) - } + + const run = (requestID: string, abort: AbortController) => + rpc.command({ ...attachment, requestID }, options).pipe( + Effect.flatMap((command) => + Effect.promise(async () => { + if ("tabID" in command.action) + dispatchBinding(binding, { type: "request.targeted", requestID, tabID: command.action.tabID }) + reply( + requestID, + await execute(binding, command, abort.signal).then( + (result) => ({ type: "success" as const, result }), + (cause: unknown) => browserFailure(command.action, cause), + ), + ) + }), + ), + Effect.ensuring( + Effect.sync(() => { + handle.requests.delete(requestID) + dispatchBinding(binding, { type: "request.finished", requestID }) + }), + ), + // An operation this desktop cannot decode comes from a newer plugin; answer it so + // the agent does not wait out the server's timeout. + Effect.tapError((error) => + Effect.sync(() => { + if (!Schema.isSchemaError(error)) return + reply(requestID, { + type: "failure", + code: "unsupported", + message: + "This desktop app does not support the requested browser operation. Ask the user to update the desktop app, or use another operation.", + }) + }), + ), + // A request that vanished (cancelled before retrieval) fails only that request. + // Transport loss surfaces through the event stream and attach call instead. + Effect.catchCause((cause) => + abort.signal.aborted ? Effect.void : Effect.logWarning("Browser command failed", cause), + ), + Effect.forkScoped, + ) const receive = client.event.subscribe().pipe( Stream.runForEach((event) => @@ -220,337 +250,321 @@ export function createBrowserPane(input: { return } - if ( - event.type !== "rpc.experimental.browser.control" || - event.data.connectionID !== attachment.connectionID - ) - return + if (event.type !== "rpc.experimental.browser.control") return - const message = yield* Schema.decodeUnknownEffect(Browser.Control)(event.data).pipe( - Effect.tapError(() => - Effect.sync(() => { - reason = "browser.pane.unsupported" - }), - ), + const frame = resolveControlFrame( + attachment.connectionID, + decodeControlHeader(event.data), + decodeControl(event.data), ) - if (message.type === "attached") { - attached = true + if (frame.kind === "foreign") return - return entry.registered.resolve() - } + if (frame.kind === "attached") return dispatchBinding(binding, { type: "server.attached", fileRoots }) - if (message.type === "cancel") return entry.requests.get(message.requestID)?.abort.abort() + if (frame.kind === "incompatible") return dispatchBinding(binding, { type: "handshake.unsupported" }) + + // A newer server may add control events; this attachment keeps working without them. + if (frame.kind === "unrecognized") + return dispatchBinding(binding, { type: "control.unrecognized", controlType: frame.controlType }) + + if (frame.kind === "cancel") + return dispatchBinding(binding, { type: "request.cancelled", requestID: frame.requestID }) const abort = new AbortController() - entry.requests.set(message.requestID, { abort }) - yield* rpc.command({ ...attachment, requestID: message.requestID }, options).pipe( - Effect.flatMap((command) => - Effect.promise(async () => { - entry.requests.set( - message.requestID, - "tabID" in command.action ? { abort, tabID: command.action.tabID } : { abort }, - ) - reply( - message.requestID, - await execute(entry, command, abort.signal).then( - (result) => ({ type: "success" as const, result }), - (cause: unknown) => browserFailure(command.action, cause), - ), - ) - }), - ), - Effect.ensuring(Effect.sync(() => entry.requests.delete(message.requestID))), - // An operation this desktop cannot decode comes from a newer plugin; answer it so - // the agent does not wait out the server's timeout. - Effect.tapError((error) => - Effect.sync(() => { - if (!Schema.isSchemaError(error)) return - reply(message.requestID, { - type: "failure", - code: "unsupported", - message: - "This desktop app does not support the requested browser operation. Ask the user to update the desktop app, or use another operation.", - }) - }), - ), - // A request that vanished (cancelled before retrieval) fails only that request. - // Transport loss surfaces through the event stream and attach call instead. - Effect.catchCause((cause) => - abort.signal.aborted ? Effect.void : Effect.logWarning("Browser command failed", cause), - ), - Effect.forkScoped, - ) + handle.requests.set(frame.requestID, abort) + dispatchBinding(binding, { type: "request.started", requestID: frame.requestID }) + yield* run(frame.requestID, abort) }), ), ) - yield* Effect.raceAllFirst([ + return yield* Effect.raceAllFirst([ receive, Stream.fromQueue(outbound).pipe(Stream.runForEach((send) => send)), - Deferred.await(connected).pipe( - Effect.andThen(rpc.attach({ ...attachment, version: 4 }, options)), - Effect.tap((result) => - Effect.sync(() => { - if (result === "replaced") reason = "browser.pane.replaced" - }), - ), - ), + Deferred.await(connected).pipe(Effect.andThen(rpc.attach({ ...attachment, version: 4 }, options))), ]) }).pipe( + Effect.matchCause({ + onSuccess: (result): AttachmentOutcome => (result === "replaced" ? "replaced" : "closed"), + onFailure: (cause) => + Option.match(Cause.findErrorOption(cause), { + onNone: (): AttachmentOutcome => "closed", + onSome: attachmentFailure, + }), + }), + // Inside the scope: closing the tunnels, the proxy and the partition's connections can take seconds, and + // nothing that happens meanwhile changes why the attachment ended. + Effect.tap((outcome) => Effect.sync(() => dispatchBinding(binding, { type: "attachment.ended", outcome }))), Effect.scoped, - Effect.tapError((error) => - Effect.sync(() => { - if (Predicate.isTagged(error, "SessionNotFoundError")) { - reason = "browser.pane.missing" - restore.remove(entry.storageKey) - - return - } - - const type = error instanceof Object && "type" in error ? error.type : undefined - - if (type === "rpc.unavailable" && attached) { - reason = "browser.pane.suspended" - - return - } - - if (type === "rpc.unavailable" || type === "rpc.method_not_found" || type === "rpc.invalid_input") - reason = "browser.pane.unsupported" - }), - ), - Effect.ensuring(Effect.sync(stop)), ), - { signal: entry.abort.signal }, + { signal: handle.abort.signal }, ) - .catch(stop) - const timeout = setTimeout(stop, 15_000) - await entry.registered.promise.finally(() => clearTimeout(timeout)) + .catch(() => dispatchBinding(binding, { type: "attachment.ended", outcome: "closed" })) + await handle.registered.promise - if (entries.get(binding) !== entry) throw new Error("browser.pane.registration.closed") - publishState(entry) + if (!selectBinding(machine.state, binding)) throw new Error("browser.pane.registration.closed") }, load(window: number, binding: string, tabID: Browser.TabID) { - load(owned(window, binding), tabID) + owned(window, binding) + load(binding, tabID) }, async inspect(window: number, binding: string, tabID: Browser.TabID, enabled: boolean) { - await owned(window, binding).pages.get(tabID)?.inspect(enabled) + owned(window, binding) + await page(binding, tabID)?.inspect(enabled) }, async highlight(window: number, binding: string, tabID: Browser.TabID, ref?: Browser.Ref) { - await owned(window, binding).pages.get(tabID)?.highlight(ref) + owned(window, binding) + await page(binding, tabID)?.highlight(ref) }, zoom(window: number, binding: string, tabID: Browser.TabID, direction: "in" | "out" | "reset") { - owned(window, binding).pages.get(tabID)?.zoom(direction) + owned(window, binding) + page(binding, tabID)?.zoom(direction) }, async site(window: number, binding: string, tabID: Browser.TabID) { - return (await owned(window, binding).pages.get(tabID)?.site()) ?? { cookies: 0 } + owned(window, binding) + + return (await page(binding, tabID)?.site()) ?? { cookies: 0 } }, async clearSite(window: number, binding: string, tabID: Browser.TabID) { - await owned(window, binding).pages.get(tabID)?.clearSite() + owned(window, binding) + await page(binding, tabID)?.clearSite() }, async command(window: number, binding: string, command: Browser.Action) { - const entry = owned(window, binding) + owned(window, binding) const url = command.type === "navigate" || command.type === "tabs.open" ? command.url : undefined + // The window explains a refused address by its code; the agent's commands get main's own message instead. - const reason = url === undefined ? undefined : refusal(url, { fileRoots: entry.fileRoots }) + const reason = + url === undefined ? undefined : refusal(url, { fileRoots: selectFileRoots(machine.state, binding) }) if (reason) throw new Error(reason) // A navigation that the next one replaced, such as a second submit or a redirect, rejects with ERR_ABORTED while // the tab goes on loading. It is not a failed request; a page that fails to load reports its own error. - await execute(entry, { action: command, files: [] }, new AbortController().signal).catch((error: Error) => { + await execute(binding, { action: command, files: [] }, new AbortController().signal).catch((error: Error) => { if (!("code" in error) || error.code !== "ERR_ABORTED") throw error }) }, async close(window: number, binding: string) { - const entry = owned(window, binding) - restore.remove(entry.storageKey) - close(entry) + owned(window, binding) + dispatchBinding(binding, { type: "client.closed" }) }, /** * The plugin is going away (reload, disable, or quit). Windows keep each pane's tabs as a * suspended attachment, like an idle server eviction, and register again once the pane is back. */ async dispose() { - disposed = true - entries.forEach((entry) => close(entry, "browser.pane.suspended")) + dispatch({ type: "disposed" }) await Promise.all(releasing) await runtime.dispose() }, } + function dispatch(event: PaneMachineEvent) { + const next = transitionPane(machine.state, event) + machine.state = next.state + next.effects.forEach(perform) + } + + function dispatchBinding(binding: string, event: BindingEvent) { + dispatch({ type: "binding", binding, event }) + } + + function perform(effect: PaneEffect) { + if (effect.type === "save-restore") return restore.save(effect.storageKey, effect.snapshot) + + if (effect.type === "remove-restore") return restore.remove(effect.storageKey) + + if (effect.type === "warn") return void runtime.runFork(Effect.logWarning(effect.message, effect.detail)) + const handle = handles.get(effect.binding) + + if (!handle) return + + if (effect.type === "start-timer") { + handle.timer = setTimeout(() => dispatchBinding(effect.binding, { type: "register.timed-out" }), effect.ms) + + return + } + + if (effect.type === "resolve-register") { + clearTimeout(handle.timer) + + return handle.registered.resolve() + } + + if (effect.type === "emit") return emit(effect.binding, effect.event) + + if (effect.type === "report") { + emit(effect.binding, effect.event) + + return handle.sendState?.(effect.event.state) + } + + if (effect.type === "abort-requests") + return effect.requestIDs.forEach((requestID) => handle.requests.get(requestID)?.abort()) + + if (effect.type === "release-pages") + return effect.attempts.forEach((attempt) => { + const page = handle.pages.get(attempt) + handle.pages.delete(attempt) + + if (page) release(page) + }) + handles.delete(effect.binding) + clearTimeout(handle.timer) + handle.registered.reject(new Error("browser.pane.registration.closed")) + handle.cleanup() + handle.abort.abort() + } + function owned(window: number, binding: string) { - const entry = entries.get(binding) - - if (!entry || entry.window !== window) throw new Error("browser.pane.unavailable") - - return entry + if (!selectOwnedBinding(machine.state, window, binding)) throw new Error("browser.pane.unavailable") } - function publish(entry: Entry, event: PaneEvent) { - if (!entries.has(entry.binding) || entry.win.isDestroyed() || entry.win.webContents.isDestroyed()) return - input.emit(entry.window, { binding: entry.binding, event }) - } + /** To the window only, while the binding's handle exists; a close event goes out before its teardown. */ + function emit(binding: string, event: PaneEvent) { + const handle = handles.get(binding) - function close(entry: Entry, reason = "browser.pane.registration.closed") { - if (entries.get(entry.binding) !== entry) return - entry.report = undefined - entry.requests.forEach((request) => request.abort.abort()) - entry.requests.clear() - const suspended = reason === "browser.pane.suspended" - - if (suspended) publishState(entry, reason) - entry.pages.forEach((page) => void release(page).catch(() => undefined)) - entry.pages.clear() - entry.tabs.clear() - entry.focusedTabID = null - - if (!suspended) publishState(entry, reason) - entries.delete(entry.binding) - entry.registered.reject(new Error("browser.pane.registration.closed")) - entry.cleanup?.() - entry.abort.abort() - } - - async function closePage(entry: Entry, tabID: Browser.TabID, error?: string) { - const page = entry.pages.get(tabID) - - if (!entry.tabs.has(tabID)) - throw new Error( - "This tab is no longer available. Call browser.tabs.list({}) and use an existing tabID from this session.", - ) - const focused = entry.focusedTabID === tabID - entry.requests.forEach((request) => { - if (request.tabID === tabID) request.abort.abort() - }) - entry.pages.delete(tabID) - entry.tabs.delete(tabID) - - if (focused) entry.focusedTabID = entry.tabs.keys().next().value ?? null - - if (page) await release(page) - publishState(entry, error) + if (!handle || handle.win.isDestroyed() || handle.win.webContents.isDestroyed()) return + input.emit(handle.window, { binding, event }) } function release(page: BrowserPage) { const done = page.dispose() const settled = done.catch(() => undefined) + disposals.set(page, done) releasing.add(settled) void settled.finally(() => releasing.delete(settled)) - - return done } - function publishState(entry: Entry, error?: string) { - const current = { type: "state" as const, state: inventory(entry) } - const event = error === undefined ? current : { ...current, error } + function inventory(binding: string): Browser.State { + const entry = selectBinding(machine.state, binding) - // Teardown publishes an empty inventory to the renderer, but the saved URLs survive app exit. - if (entry.report) - restore.save(entry.storageKey, { - tabs: event.state.tabs.map((tab) => ({ - id: tab.id, - // A restored page can publish before Chromium assigns its URL. - url: tab.url || entry.tabs.get(tab.id)?.url || "about:blank", - })), - focusedTabID: entry.focusedTabID, - }) - const next = JSON.stringify(event) - - if (entry.lastState === next) return - entry.lastState = next - report(entry, event) + return entry ? selectInventory(entry) : { tabs: [], focusedTabID: null } } - function report(entry: Entry, event: PaneEvent) { - if (entry.report) return entry.report(event) - publish(entry, event) + /** The tab's current page. */ + function page(binding: string, tabID: Browser.TabID) { + const attempt = selectPageAttempt(machine.state, binding, tabID) + + return attempt === undefined ? undefined : handles.get(binding)?.pages.get(attempt) } - function inventory(entry: Entry): Browser.State { - return { - tabs: Array.from(entry.tabs, ([id, tab]) => entry.pages.get(id)?.state() ?? tab), - focusedTabID: entry.focusedTabID, - } - } + /** The tab's page, created the first time the pane shows a restored or crashed tab or a command names it. */ + function load(binding: string, tabID: Browser.TabID) { + const existing = page(binding, tabID) - function load(entry: Entry, tabID: Browser.TabID) { - const page = entry.pages.get(tabID) + if (existing) return existing + const slot = selectTabSlot(machine.state, binding, tabID) - if (page) return page - const tab = entry.tabs.get(tabID) + if (slot?.status !== "unloaded") return undefined + const tab = slot.tab - return tab ? create(entry, true, undefined, tab) : undefined + // A crashed tab's error belongs to its last page; the new page reports its own. + return create(binding, { + restore: { + id: tab.id, + url: tab.url, + title: tab.title, + loading: false, + canGoBack: false, + canGoForward: false, + generation: tab.generation, + }, + }) } function create( - entry: Entry, - initialize = true, - popupOptions?: Electron.BrowserWindowConstructorOptions, - restore?: Browser.Tab, + binding: string, + options: { + readonly restore?: Browser.Tab + readonly initialize?: boolean + readonly popupOptions?: Electron.BrowserWindowConstructorOptions + } = {}, ) { - if (!entry.network) throw new Error("Browser network is not ready; no tab was opened.") - const id = restore?.id ?? Browser.TabID.make(`tab_${crypto.randomUUID()}`) + const entry = selectBinding(machine.state, binding) + const handle = handles.get(binding) + + if (entry?.status !== "attached" || !handle?.network) + throw new Error("Browser network is not ready; no tab was opened.") + const id = options.restore?.id ?? Browser.TabID.make(`tab_${crypto.randomUUID()}`) + const attempt = entry.nextAttempt + const win = handle.win + // Every callback is fenced to this page: a later page of the same tab has another attempt. + const current = () => isCurrentPage(machine.state, binding, id, attempt) + const focused = () => isFocusedPage(machine.state, binding, id, attempt) const fail = () => { - if (entry.pages.has(id)) void closePage(entry, id, "page_crashed").catch(() => undefined) + if (current()) + dispatchBinding(binding, { + type: "tab.crashed", + tabID: id, + attempt, + tab: page.contents.isDestroyed() ? undefined : page.state(), + }) } - const page = createBrowserPage(entry.win, { + const page = createBrowserPage(win, { id, - partition: entry.partition, - network: entry.network, - initialize, - restore, - popupOptions, - fileRoots: () => entry.fileRoots, + partition: handle.partition, + network: handle.network, + initialize: options.initialize, + restore: options.restore, + popupOptions: options.popupOptions, + fileRoots: () => selectFileRoots(machine.state, binding), shared, embeds: input.embeds, fail, publish: (error) => { - if (entry.pages.has(id)) publishState(entry, error) + if (current()) dispatchBinding(binding, { type: "tab.published", tabID: id, attempt, tab: page.state(), error }) }, inspect: (event) => { - if (entry.pages.has(id)) report(entry, { type: "inspect", tabID: id, ...event }) + if (current()) emit(binding, { type: "inspect", tabID: id, ...event }) }, // Icons and zoom are local to this desktop, and follow the states reported before them, so the window files a new // page's icon under that page's URL. detail: (value) => { - if (entry.pages.has(id)) report(entry, { type: "page", tabID: id, ...value }) + if (current()) emit(binding, { type: "page", tabID: id, ...value }) }, - zoomed: () => entry.pages.forEach((page) => page.detail()), + zoomed: () => handles.get(binding)?.pages.forEach((page) => page.detail()), shortcut: (shortcut) => { - if (!entry.pages.has(id) || entry.focusedTabID !== id || entry.win.isDestroyed()) return + if (!focused() || win.isDestroyed()) return // The page held keyboard focus; the command runs in the app, which may move focus there, as ⌘L does. - if (entry.win.isFocused()) entry.win.webContents.focus() - publish(entry, { type: "shortcut", ...shortcut }) + if (win.isFocused()) win.webContents.focus() + emit(binding, { type: "shortcut", ...shortcut }) }, focused: () => { - if (entry.pages.has(id) && entry.focusedTabID === id) publish(entry, { type: "focused", tabID: id }) + if (focused()) emit(binding, { type: "focused", tabID: id }) }, popup: (popupOptions, background) => { - const popup = create(entry, false, popupOptions) + const popup = create(binding, { initialize: false, popupOptions }) - if (!background) focus(entry, popup.state().id) + if (!background) dispatchBinding(binding, { type: "tab.focused", tabID: popup.state().id }) return popup.contents }, }) - entry.pages.set(id, page) - entry.tabs.set(id, restore ?? page.state()) + handle.pages.set(attempt, page) + dispatchBinding(binding, { type: "tab.opened", tabID: id, attempt, tab: options.restore ?? page.state() }) // Straight to the window, not through the server report: the embed is local to this desktop. - publish(entry, { type: "embed", tabID: id, embed: page.embed }) - void page.ready - .then(() => { - if (entry.pages.get(id) === page) publishState(entry) - }) - .catch(fail) + emit(binding, { type: "embed", tabID: id, embed: page.embed }) + void page.ready.then(() => { + if (current()) dispatchBinding(binding, { type: "tab.published", tabID: id, attempt, tab: page.state() }) + }, fail) return page } - async function execute(entry: Entry, command: Browser.Command, signal: AbortSignal) { + /** Reports the page's state after a command, which may have changed it without a page event yet. */ + function refresh(binding: string, tabID: Browser.TabID, page: BrowserPage) { + const attempt = selectPageAttempt(machine.state, binding, tabID) + + if (attempt === undefined || handles.get(binding)?.pages.get(attempt) !== page) return + dispatchBinding(binding, { type: "tab.published", tabID, attempt, tab: page.state() }) + } + + async function execute(binding: string, command: Browser.Command, signal: AbortSignal) { const action = command.action if (signal.aborted) @@ -558,59 +572,59 @@ export function createBrowserPane(input: { "Browser request was cancelled. Do not repeat a mutating action until you have inspected its outcome.", ) - if (action.type === "tabs.list") return { value: inventory(entry), files: [] } + if (action.type === "tabs.list") return { value: inventory(binding), files: [] } if (action.type === "preview") { // The renderer owns file tabs; it resolves the path against the session's workspace. - report(entry, { type: "preview", path: action.path }) + emit(binding, { type: "preview", path: action.path }) return { value: { path: action.path }, files: [] } } if (action.type === "tabs.open") { - const page = create(entry) + const page = create(binding) + const tabID = page.state().id - if (action.focus !== false) focus(entry, page.state().id) + if (action.focus !== false) dispatchBinding(binding, { type: "tab.focused", tabID }) await page.ready // A new page already loads about:blank, so only another address needs a navigation. if (action.url !== undefined) - await page.execute({ action: { type: "navigate", tabID: page.state().id, url: action.url }, files: [] }, signal) - publishState(entry) + await page.execute({ action: { type: "navigate", tabID, url: action.url }, files: [] }, signal) + refresh(binding, tabID, page) return { value: page.state(), files: [] } } - const tab = inventory(entry).tabs.find((tab) => tab.id === action.tabID) + const slot = selectTabSlot(machine.state, binding, action.tabID) - if (!tab) + if (!slot) throw new Error( "Browser tab is unavailable. Call browser.tabs.list({}) and use an existing tabID from this session; a closed tab is not replaced automatically.", ) if (action.type === "tabs.focus") { - focus(entry, action.tabID) + dispatchBinding(binding, { type: "tab.focused", tabID: action.tabID }) - return { value: tab, files: [] } + return { value: slot.tab, files: [] } } if (action.type === "tabs.close") { - await closePage(entry, action.tabID) + const closing = page(binding, action.tabID) + dispatchBinding(binding, { type: "tab.closed", tabID: action.tabID }) - return { value: inventory(entry), files: [] } + if (closing) await disposals.get(closing) + + return { value: inventory(binding), files: [] } } - const page = entry.pages.get(action.tabID) ?? create(entry, true, undefined, tab) - await page.ready - const result = await page.execute(command, signal) - publishState(entry) + const target = load(binding, action.tabID) + + if (!target) throw new Error("Browser tab is unavailable. Call browser.tabs.list({}) and use an existing tabID.") + await target.ready + const result = await target.execute(command, signal) + refresh(binding, action.tabID, target) return result } - - function focus(entry: Entry, tabID: Browser.TabID) { - entry.focusedTabID = tabID - publishState(entry) - report(entry, { type: "focus", tabID }) - } }