From dca57f8f474efcbd57b1bb5fc6d35d23d8a5ba72 Mon Sep 17 00:00:00 2001 From: James Long Date: Mon, 9 Nov 2026 16:19:24 +0000 Subject: [PATCH] feat(desktop): keep live browser pages across lock and reconnect The desktop now keeps each session's browser partition, proxy, pages and tab IDs in main across a server disconnect and a screen lock. A locked screen ends the server attachment, stops retries and commands, and revokes the browser tools; unlocking reattaches the same WebContents, rebinds the tunnel and restores the tools. In-flight requests are cancelled, no command is replayed, and permanent closes (window close, session removal, plugin dispose) still release everything. User decisions: - Lock ends the browser attachment and removes the browser tools - Unlock reattaches the same live pages automatically - Browser pages, tab IDs, profile, cookies, storage, form and scroll state survive - Always on, with no setting --- .../desktop/src/main/native/screen-lock.ts | 12 +- packages/gui-plugins/src/browser/i18n/en.ts | 1 + packages/gui-plugins/src/browser/ipc.ts | 3 + .../gui-plugins/src/browser/machine.test.ts | 126 ++++++-- packages/gui-plugins/src/browser/machine.ts | 187 +++++++++++- packages/gui-plugins/src/browser/model.ts | 7 +- packages/gui-plugins/src/browser/network.ts | 72 +++-- .../src/browser/pane-machine.test.ts | 54 +++- .../gui-plugins/src/browser/pane-machine.ts | 39 ++- packages/gui-plugins/src/browser/pane.ts | 275 +++++++++++++++--- packages/gui-plugins/src/browser/panel.tsx | 11 + 11 files changed, 676 insertions(+), 111 deletions(-) diff --git a/packages/desktop/src/main/native/screen-lock.ts b/packages/desktop/src/main/native/screen-lock.ts index 904d97a447d..52feb5b5831 100644 --- a/packages/desktop/src/main/native/screen-lock.ts +++ b/packages/desktop/src/main/native/screen-lock.ts @@ -22,8 +22,15 @@ function createScreenLock(): ScreenLock { let state = initialScreenLockState let started = false - // The threshold only separates `active` from `idle`, which both mean unlocked here. - const idle = () => powerMonitor.getSystemIdleState(60) + // The threshold only separates `active` from `idle`, which both mean unlocked here. A platform that cannot answer + // reports `unknown`, which changes nothing. + const idle = (): ReturnType => { + try { + return powerMonitor.getSystemIdleState(60) + } catch { + return "unknown" + } + } const apply = (event: ScreenLockEvent) => { const before = isScreenLocked(state) @@ -36,6 +43,7 @@ function createScreenLock(): ScreenLock { const start = () => { if (started) return started = true + apply({ type: "probed", idle: idle() }) powerMonitor.on("lock-screen", () => apply({ type: "screen", locked: true })) powerMonitor.on("unlock-screen", () => apply({ type: "screen", locked: false })) diff --git a/packages/gui-plugins/src/browser/i18n/en.ts b/packages/gui-plugins/src/browser/i18n/en.ts index b33085d6a27..80563c3e288 100644 --- a/packages/gui-plugins/src/browser/i18n/en.ts +++ b/packages/gui-plugins/src/browser/i18n/en.ts @@ -26,6 +26,7 @@ export default { replaced: "Browser control moved to another desktop window.", unsupported: "This desktop app does not support the browser pane.", suspended: "Browser suspended. Interact with this session to reconnect.", + "connection.disconnected": "Disconnected — this page won't update until OpenCode reconnects.", "home.title": "Open a page", "home.description": "Preview your app, read docs, or browse the web.", "home.recent": "Recent", diff --git a/packages/gui-plugins/src/browser/ipc.ts b/packages/gui-plugins/src/browser/ipc.ts index f164b534c71..186baa5455a 100644 --- a/packages/gui-plugins/src/browser/ipc.ts +++ b/packages/gui-plugins/src/browser/ipc.ts @@ -75,6 +75,8 @@ export type PaneEvent = typeof PaneEvent.Type * - `"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.disconnected"`: the connection to the server went away after it accepted the binding. The desktop + * keeps the live pages and reconnects on its own; the event carries the tabs the binding had. * - `"browser.pane.locked"`: the screen is locked, so main ends every attachment and refuses new ones until it unlocks. * The event carries the tabs the binding had; the window registers again on the `screen` event that reports unlock. * - `"browser.pane.missing"`: the session no longer exists. The event carries no tabs, and main forgot its saved tabs. @@ -85,6 +87,7 @@ export const PaneCloseReason = Schema.Literals([ "browser.pane.unsupported", "browser.pane.replaced", "browser.pane.suspended", + "browser.pane.disconnected", "browser.pane.locked", "browser.pane.missing", "browser.pane.registration.closed", diff --git a/packages/gui-plugins/src/browser/machine.test.ts b/packages/gui-plugins/src/browser/machine.test.ts index 479f6acab40..f204770062e 100644 --- a/packages/gui-plugins/src/browser/machine.test.ts +++ b/packages/gui-plugins/src/browser/machine.test.ts @@ -5,6 +5,7 @@ import { createInitialState, REGISTER_TIMEOUT_MS, serverSupported, + sessionConnection, sessionError, sessionPending, sessionSuspended, @@ -534,6 +535,83 @@ describe("browser pane machine", () => { expect(later.effects).toEqual([]) }) + test("a lost connection keeps the live pages and retries on its own", () => { + const start = ready() + + const embedded = transition(start, { + type: "pane.embed", + sessionKey: key, + attempt: attempt(start), + tabID: tabA, + embed: "e1", + }).state + + const lost = transition(embedded, paneState(embedded, inventory(tab(tabA)), "browser.pane.disconnected")) + expect(phase(lost.state)).toMatchObject({ status: "reconnecting", attempts: 1 }) + expect(attachment(lost.state)?.browser).toEqual(inventory(tab(tabA))) + expect(attachment(lost.state)?.embeds).toEqual({ [tabA]: "e1" }) + expect(sessionConnection(lost.state, key)).toBe("reconnecting") + expect(sessionSuspended(lost.state, key)).toBe(false) + expect(lost.effects).toContainEqual(expect.objectContaining({ type: "schedule-retry", delayMs: 1_000 })) + + const retry = attempt(lost.state) + const registering = transition(lost.state, { type: "retry.due", sessionKey: key, attempt: retry }) + expect(phase(registering.state)).toMatchObject({ status: "registering", attempts: 1 }) + expect(registering.effects).toContainEqual({ + type: "open-registration", + sessionKey: key, + attempt: attempt(registering.state), + restore: inventory(tab(tabA)), + }) + expect(attachment(registering.state)?.embeds).toEqual({ [tabA]: "e1" }) + + const failed = transition(registering.state, { + type: "register.failed", + sessionKey: key, + attempt: attempt(registering.state), + unavailable: false, + closed: false, + locked: false, + }) + + expect(phase(failed.state)).toMatchObject({ status: "backoff", attempts: 2 }) + expect(attachment(failed.state)?.embeds).toEqual({ [tabA]: "e1" }) + expect(sessionConnection(failed.state, key)).toBe("reconnecting") + + const again = transition(failed.state, { + type: "retry.due", + sessionKey: key, + attempt: attempt(failed.state), + }).state + + const accepted = transition(again, { + type: "register.accepted", + sessionKey: key, + attempt: attempt(again), + }).state + + expect(sessionConnection(accepted, key)).toBe("connected") + expect(attachment(accepted)?.embeds).toEqual({ [tabA]: "e1" }) + }) + + test("a restarted server retries a lost connection at once", () => { + const start = ready() + const lost = transition(start, paneState(start, inventory(tab(tabA)), "browser.pane.disconnected")).state + const early = transition(lost, { type: "session.reconnect", sessionKey: key }) + + expect(phase(early.state)).toMatchObject({ status: "registering", attempts: 1 }) + expect(early.effects).toContainEqual({ type: "cancel-retry", sessionKey: key }) + expect(early.effects).toContainEqual( + expect.objectContaining({ type: "open-registration", restore: inventory(tab(tabA)) }), + ) + }) + + test("a suspended pane without retries reads as disconnected", () => { + const start = ready() + const idle = transition(start, paneState(start, inventory(tab(tabA)), "browser.pane.suspended")).state + expect(sessionConnection(idle, key)).toBe("disconnected") + }) + test("a missing session waits without an error until the server creates it", () => { const start = replay(attach()).state const missing = transition(start, paneState(start, null, "browser.pane.missing")).state @@ -627,31 +705,43 @@ describe("browser pane machine", () => { test("a locked screen keeps the tabs and registers again only once it unlocks", () => { const start = ready() - const locked = transition(start, paneState(start, inventory(tab(tabA)), "browser.pane.locked")).state - expect(phase(locked)).toEqual({ status: "suspended", reason: "locked" }) - expect(attachment(locked)?.browser?.tabs.map((item) => item.id)).toEqual([tabA]) - - // An edge while still locked registers, main refuses it, and the pane waits without a retry timer. - const woken = transition(locked, { type: "session.wake", sessionKey: key }) - expect(types(woken.effects)).toEqual(["open-registration", "schedule-register-timeout"]) - - const refused = transition(woken.state, { - type: "register.failed", + const embedded = transition(start, { + type: "pane.embed", sessionKey: key, - attempt: attempt(woken.state), - unavailable: false, - closed: false, - locked: true, - }) + attempt: attempt(start), + tabID: tabA, + embed: "e1", + }).state + const held = transition(embedded, { type: "screen.locked" }) + expect(held.state.status === "open" && held.state.locked).toBe(true) + expect(phase(held.state)).toEqual({ status: "suspended", reason: "locked" }) + expect(attachment(held.state)?.browser?.tabs.map((item) => item.id)).toEqual([tabA]) + expect(attachment(held.state)?.embeds).toEqual({ [tabA]: "e1" }) - expect(phase(refused.state)).toEqual({ status: "suspended", reason: "locked" }) - expect(types(refused.effects)).not.toContain("schedule-retry") + // No edge, retry, or command may register or reach the pane while locked. + const woken = transition(held.state, { type: "session.wake", sessionKey: key }) + expect(woken.state).toBe(held.state) + expect(woken.effects).toEqual([]) - const unlocked = transition(refused.state, { type: "screen.unlocked" }) + const commanded = replay([command()], held.state) + expect(types(commanded.effects)).toEqual(["reject-command"]) + expect(commanded.effects).toContainEqual(expect.objectContaining({ error: "browser.pane.locked" })) + + const unlocked = transition(held.state, { type: "screen.unlocked" }) + expect(unlocked.state.status === "open" && unlocked.state.locked).toBe(false) expect(phase(unlocked.state)).toMatchObject({ status: "registering" }) expect(unlocked.effects).toContainEqual( expect.objectContaining({ type: "open-registration", restore: inventory(tab(tabA)) }), ) + expect(attachment(unlocked.state)?.embeds).toEqual({ [tabA]: "e1" }) + }) + + test("a locked pane.state keeps the tabs without a retry timer", () => { + const start = ready() + const locked = transition(start, paneState(start, inventory(tab(tabA)), "browser.pane.locked")).state + + expect(phase(locked)).toEqual({ status: "suspended", reason: "locked" }) + expect(types(transition(locked, { type: "session.wake", sessionKey: key }).effects)).toEqual([]) }) test("unlocking leaves panes the lock did not suspend alone", () => { diff --git a/packages/gui-plugins/src/browser/machine.ts b/packages/gui-plugins/src/browser/machine.ts index 7019e4ea36c..094a117a54c 100644 --- a/packages/gui-plugins/src/browser/machine.ts +++ b/packages/gui-plugins/src/browser/machine.ts @@ -21,6 +21,8 @@ export type Ipc = * - `registering`: a binding waits for main to take it. * - `ready`: main took the binding. * - `backoff`: main closed or refused the binding; a timer registers again. + * - `reconnecting`: the server connection went away after it accepted the binding; the live pages stay, and a timer + * registers again. * - `suspended`: the tabs stay without a binding. `idle`: the server evicted it, and a user or agent wakes it. `ipc`: * the pane's Ipc is gone, and it registers again once the Ipc is back. `locked`: the screen is locked, and it * registers again once it unlocks. @@ -33,6 +35,7 @@ export type Phase = | { readonly status: "registering"; readonly attempt: number; readonly attempts: number } | { readonly status: "ready"; readonly attempt: number } | { readonly status: "backoff"; readonly attempt: number; readonly attempts: number } + | { readonly status: "reconnecting"; readonly attempt: number; readonly attempts: number } | { readonly status: "suspended"; readonly reason: SuspendReason } | { readonly status: "blocked"; readonly reason: "replaced" | "missing" } @@ -87,12 +90,16 @@ export type State = readonly issued: number readonly unsupported: Readonly> readonly sessions: Readonly> + /** The screen is locked: no attachment may start and commands are refused. */ + readonly locked: boolean } | { readonly status: "disposed" } export type Event = | { readonly type: "disposed" } | { readonly type: "ipc.changed"; readonly ipc: Ipc } + /** The screen locked: every attachment stops and no register may start until it unlocks. */ + | { readonly type: "screen.locked" } /** The screen unlocked: attachments the lock ended register again. */ | { readonly type: "screen.unlocked" } /** An unsupported server reconnected, restarted, or is no longer listed: it may have the browser RPC now. */ @@ -108,6 +115,8 @@ export type Event = | { readonly type: "session.located"; readonly sessionKey: string; readonly located: boolean } /** A user or agent edge asks for the pane: focus, a key, the route, or a Session execution. */ | { readonly type: "session.wake"; readonly sessionKey: string } + /** The server announced that it is back; a pane that lost the connection retries now. */ + | { readonly type: "session.reconnect"; readonly sessionKey: string } /** The server finished creating the session. */ | { readonly type: "session.created"; readonly sessionKey: string } | { @@ -233,6 +242,7 @@ type SessionEvent = Exclude< | "disposed" | "ipc.changed" | "server.changed" + | "screen.locked" | "screen.unlocked" | "session.attached" | "session.removed" @@ -245,7 +255,7 @@ type SessionEvent = Exclude< const noFocus = (): AddressFocus => ({ status: "none" }) export function createInitialState(ipc: Ipc): State { - return { status: "open", ipc, issued: 0, unsupported: {}, sessions: {} } + return { status: "open", ipc, issued: 0, unsupported: {}, sessions: {}, locked: false } } export function transition(state: State, event: Event): Transition { @@ -255,9 +265,12 @@ export function transition(state: State, event: Event): Transition { if (event.type === "ipc.changed") return ipcChanged(state, event.ipc) - if (event.type === "server.changed") return serverChanged(state, event.serverID) + if (event.type === "screen.locked") return locked(state) - if (event.type === "screen.unlocked") return unlocked(state) + if (event.type === "screen.unlocked") + return state.locked ? unlocked({ ...state, locked: false }) : { state, effects: [] } + + if (event.type === "server.changed") return serverChanged(state, event.serverID) if (event.type === "session.attached") return attached(state, event) @@ -330,6 +343,28 @@ export function sessionSuspended(state: State, sessionKey: string) { return attachmentOf(state, sessionKey)?.phase.status === "suspended" } +export type BrowserConnection = "connected" | "disconnected" | "reconnecting" + +/** How the pane's server connection reads: ready, retrying a lost connection, or waiting for a user edge. */ +export function sessionConnection(state: State, sessionKey: string): BrowserConnection { + const attachment = attachmentOf(state, sessionKey) + + if (!attachment) return "disconnected" + const phase = attachment.phase + + if (phase.status === "reconnecting") return "reconnecting" + + if (phase.status === "backoff" && attachment.browser) return "reconnecting" + + if (phase.status === "registering" && attachment.browser) return "reconnecting" + + if (phase.status === "suspended") return "disconnected" + + if (phase.status === "blocked") return "disconnected" + + return "connected" +} + export function sessionError(state: State, sessionKey: string) { return attachmentOf(state, sessionKey)?.error } @@ -469,6 +504,8 @@ function session(state: Open, key: string, attachment: Attachment, event: Sessio return located(state, key, attachment, event.located) case "session.wake": return wake(state, key, attachment, false) + case "session.reconnect": + return reconnectNow(state, key, attachment) case "session.created": return wake(state, key, attachment, true) case "session.command": @@ -503,7 +540,7 @@ function session(state: Open, key: string, attachment: Attachment, event: Sessio if (event.unavailable) return put(state, key, suspend(attachment, "ipc"), stop(key, phase)) - if (event.locked) return put(state, key, suspend(attachment, "locked"), stop(key, phase)) + if (event.locked) return put({ ...state, locked: true }, key, hold(attachment, "locked"), stop(key, phase)) // Main closed a binding it took; its closed-state event decides, and the register timeout bounds the wait. if (event.closed) return { state, effects: [] } @@ -518,9 +555,13 @@ function session(state: Open, key: string, attachment: Attachment, event: Sessio } case "retry.due": { - if (phase.status !== "backoff" || phase.attempt !== event.attempt) return { state, effects: [] } + if (state.locked) return put(state, key, hold(attachment, "locked"), stop(key, phase)) + + if ((phase.status !== "backoff" && phase.status !== "reconnecting") || phase.attempt !== event.attempt) + return { state, effects: [] } if (state.ipc.status !== "active") return put(state, key, suspend(attachment, "ipc")) + const attempt = state.issued + 1 return put( @@ -529,7 +570,6 @@ function session(state: Open, key: string, attachment: Attachment, event: Sessio { ...attachment, phase: { status: "registering", attempt, attempts: phase.attempts }, - embeds: {}, error: undefined, }, register(key, attempt, attachment.browser), @@ -581,6 +621,22 @@ function located(state: Open, key: string, attachment: Attachment, value: boolea ) } +// A locked screen stops every attachment where it is. The tabs, live-page embeds and browser inventory stay; unlock +// wakes only the attachments the lock ended. +function locked(state: Open): Transition { + return listed(state.sessions).reduce( + (result, [key, attachment]) => { + if (attachment.phase.status === "blocked") return result + + return put(result.state, key, hold(attachment, "locked", attachment.browser), [ + ...result.effects, + ...stop(key, attachment.phase), + ]) + }, + { state: { ...state, locked: true }, effects: [] }, + ) +} + // Every attachment the locked screen ended registers again. One woken before the unlock already did. function unlocked(state: Open): Transition { return listed(state.sessions).reduce( @@ -594,11 +650,37 @@ function unlocked(state: Open): Transition { ) } +/** A restarted server lets a lost connection retry now, instead of waiting out its backoff. */ +function reconnectNow(state: Open, key: string, attachment: Attachment): Transition { + if (state.locked) return { state, effects: [] } + const phase = attachment.phase + + if (phase.status !== "reconnecting" && !(phase.status === "backoff" && attachment.browser)) + return { state, effects: [] } + + if (state.ipc.status !== "active") return put(state, key, suspend(attachment, "ipc")) + const attempt = state.issued + 1 + + return put( + state, + key, + { + ...attachment, + phase: { status: "registering", attempt, attempts: "attempts" in phase ? phase.attempts : 0 }, + error: undefined, + }, + [...stop(key, phase), ...register(key, attempt, attachment.browser)], + attempt, + ) +} + // Passive edges wake an idle or suspended pane without bypassing transport backoff or duplicating a binding. Only the // server creating the session lifts `missing`; nothing lifts `replaced` but the user's next session visit elsewhere. function wake(state: Open, key: string, attachment: Attachment, created: boolean): Transition & { state: Open } { const phase = attachment.phase + if (state.locked) return { state, effects: [] } + if (phase.status === "registering" || phase.status === "ready" || phase.status === "backoff") return { state, effects: [] } @@ -616,8 +698,8 @@ function wake(state: Open, key: string, attachment: Attachment, created: boolean return put( state, key, - { ...attachment, phase: { status: "registering", attempt, attempts: 0 }, embeds: {}, error: undefined }, - register(key, attempt, restore), + { ...attachment, phase: { status: "registering", attempt, attempts: 0 }, error: undefined }, + [...stop(key, phase), ...register(key, attempt, restore)], attempt, ) } @@ -637,6 +719,15 @@ function command( ? { status: "opening", request, known: attachment.browser?.tabs.map((tab) => tab.id) ?? [], settled: false } : attachment.addressFocus + if (state.locked) + return put( + state, + key, + { ...attachment, error: undefined, addressFocus: noFocus() }, + [{ type: "reject-command", sessionKey: key, request, error: "browser.pane.locked", unavailable: false }], + request, + ) + if (phase.status === "registering" || phase.status === "ready") return put( state, @@ -710,6 +801,10 @@ function commandFailed( return put(state, key, { ...attachment, addressFocus: focus }) } + // A command refused by the lock is expected, not an error the window shows. + if (event.error === "browser.pane.locked") + return put(state, key, { ...attachment, error: undefined, addressFocus: focus }) + const replaced = attachment.phase.status === "blocked" && attachment.phase.reason === "replaced" return put(state, key, { @@ -766,6 +861,15 @@ function paneState( ) } + // The server accepted this binding, then the connection went away. Keep the inventory and the live-page embeds while + // retrying, so the pages stay rendered and the next binding can adopt them. + if (event.error === "browser.pane.disconnected") { + const browser = event.state ?? attachment.browser + const mirrored = event.state ? mirror(key, attachment.strip, browser, false) : undefined + + return reconnect(state, key, attachment, phase, browser, mirrored?.effects ?? [], mirrored?.strip) + } + // Main closed the binding, or never took it. Keep the tabs and register again with backoff. if (event.error === "browser.pane.registration.closed") return backoff(state, key, attachment, phase) @@ -775,10 +879,15 @@ function paneState( const mirrored = event.state ? mirror(key, attachment.strip, browser, false) : undefined const reason = event.error === "browser.pane.locked" ? "locked" : "idle" - return put(state, key, { ...suspend(attachment, reason, browser), strip: mirrored?.strip ?? attachment.strip }, [ - ...stop(key, phase), - ...(mirrored?.effects ?? []), - ]) + const next = + event.error === "browser.pane.locked" ? hold(attachment, reason, browser) : suspend(attachment, reason, browser) + + return put( + event.error === "browser.pane.locked" ? { ...state, locked: true } : state, + key, + { ...next, strip: mirrored?.strip ?? attachment.strip }, + [...stop(key, phase), ...(mirrored?.effects ?? [])], + ) } const mirrored = mirror(key, attachment.strip, event.state, true) @@ -802,6 +911,46 @@ function paneState( ) } +/** Keeps the live pages and their embeds while a lost server connection retries with bounded backoff. */ +function reconnect( + state: Open, + key: string, + attachment: Attachment, + phase: Phase, + browser: Browser.State | null, + mirroredEffects: readonly MachineEffect[], + mirroredStrip: Strip | undefined, +): Transition { + const prior = phase.status === "reconnecting" || phase.status === "registering" ? phase.attempts : 0 + const attempt = state.issued + 1 + + return put( + state, + key, + { + ...attachment, + phase: { status: "reconnecting", attempt, attempts: prior + 1 }, + browser, + error: undefined, + strip: mirroredStrip ?? attachment.strip, + addressFocus: noFocus(), + }, + [ + ...stop(key, phase), + ...mirroredEffects, + { + type: "schedule-retry", + sessionKey: key, + attempt, + // A disconnected pane retries often enough to catch a server whose plugin is still booting; the cap keeps it + // from spinning while the server stays away. + delayMs: Math.min(5_000, RETRY_BASE_MS * 2 ** Math.min(prior, 10)), + }, + ], + attempt, + ) +} + function backoff(state: Open, key: string, attachment: Attachment, phase: Bound): Transition { const prior = phase.status === "registering" ? phase.attempts : 0 const attempt = state.issued + 1 @@ -812,7 +961,6 @@ function backoff(state: Open, key: string, attachment: Attachment, phase: Bound) { ...attachment, phase: { status: "backoff", attempt, attempts: prior + 1 }, - embeds: {}, error: undefined, addressFocus: noFocus(), }, @@ -897,6 +1045,17 @@ function suspend(attachment: Attachment, reason: SuspendReason, browser = attach } } +/** A lock suspension keeps the embeds: the same live pages stay on screen while the attachment is gone. */ +function hold(attachment: Attachment, reason: SuspendReason, browser = attachment.browser): Attachment { + return { + ...attachment, + phase: { status: "suspended", reason }, + browser, + error: undefined, + addressFocus: noFocus(), + } +} + function current(phase: Phase, attempt: number) { return (phase.status === "registering" || phase.status === "ready") && phase.attempt === attempt ? phase : undefined } @@ -917,7 +1076,7 @@ function stop(key: string, phase: Phase): MachineEffect[] { if (phase.status === "ready") return [{ type: "close-registration", sessionKey: key, attempt: phase.attempt }] - if (phase.status === "backoff") return [{ type: "cancel-retry", sessionKey: key }] + if (phase.status === "backoff" || phase.status === "reconnecting") return [{ type: "cancel-retry", sessionKey: key }] return [] } diff --git a/packages/gui-plugins/src/browser/model.ts b/packages/gui-plugins/src/browser/model.ts index 3d06dc77c1d..115842714ac 100644 --- a/packages/gui-plugins/src/browser/model.ts +++ b/packages/gui-plugins/src/browser/model.ts @@ -23,6 +23,7 @@ import { serverSupported, sessionAttached, sessionBrowser, + sessionConnection, sessionEmbed, sessionError, sessionPending, @@ -412,7 +413,7 @@ export function createModel(ctx: SetupContext) { createKeyed(pane, (current) => current.on("event", (value) => listeners.get(value.binding)?.(value.event))) createKeyed(pane, (current) => current.on("screen", (value) => { - if (!value.locked) dispatch({ type: "screen.unlocked" }) + dispatch({ type: value.locked ? "screen.locked" : "screen.unlocked" }) }), ) @@ -458,6 +459,9 @@ export function createModel(ctx: SetupContext) { if (event.data.sessionID === ref.id) dispatch({ type: "session.wake", sessionKey }) }), ) + // A restarted server announces itself; a pane that lost the connection retries at once instead of waiting + // out the rest of its backoff. + onCleanup(data.on("server.connected", () => dispatch({ type: "session.reconnect", sessionKey }))) }, ) @@ -631,6 +635,7 @@ export function createModel(ctx: SetupContext) { return code === undefined ? undefined : describe(code) }, suspended: (session: Session) => sessionSuspended(machine(), session.key), + connection: (session: Session) => sessionConnection(machine(), session.key), /** The host embed of a tab's page, once main created the page. */ embed: (session: Session, tabID: string) => sessionEmbed(machine(), session.key, tabID), /** diff --git a/packages/gui-plugins/src/browser/network.ts b/packages/gui-plugins/src/browser/network.ts index 82cb66eee2c..0ac68c1699e 100644 --- a/packages/gui-plugins/src/browser/network.ts +++ b/packages/gui-plugins/src/browser/network.ts @@ -6,32 +6,68 @@ import { BrowserProxy } from "@opencode/plugin-browser/proxy" import { Effect } from "effect" import { Base64 } from "effect/encoding" +/** The connection a live page's proxy tunnels through. Absent while the server is disconnected. */ +export type BrowserNetworkUpstream = { + readonly rpc: RpcClient + readonly attachment: { sessionID: Session.ID; connectionID: string } + readonly location: { directory: string; workspace?: string } +} + export type BrowserNetwork = Effect.Success> +/** A session's proxy and partition, kept for as long as the session's live pages are. */ export const createBrowserNetwork = Effect.fn("BrowserNetwork.create")(function* (input: { - rpc: RpcClient - attachment: { sessionID: Session.ID; connectionID: string } - location: { directory: string; workspace?: string } - partition: string + readonly partition: string + /** The current binding's tunnel RPC, or undefined while the server is disconnected. */ + readonly upstream: () => BrowserNetworkUpstream | undefined }) { - const options = { location: input.location } + const current = () => { + const upstream = input.upstream() + + if (!upstream) throw new Error("browser.network.disconnected") + + return upstream + } const proxy = yield* Effect.acquireRelease( Effect.tryPromise(() => BrowserProxy.make({ - open: (target, signal) => - Effect.runPromise(input.rpc["tunnel.open"]({ ...input.attachment, target }, options), { signal }), - read: (tunnelID, signal) => - Effect.runPromise(input.rpc["tunnel.read"]({ ...input.attachment, tunnelID }, options), { signal }), - write: (tunnelID, data, end, signal) => - Effect.runPromise( - input.rpc["tunnel.write"]({ ...input.attachment, tunnelID, data: Base64.encode(data), end }, options), + open: (target, signal) => { + const upstream = current() + + return Effect.runPromise( + upstream.rpc["tunnel.open"]({ ...upstream.attachment, target }, { location: upstream.location }), { signal }, - ), - close: (tunnelID) => - Effect.runPromise( - input.rpc["tunnel.close"]({ ...input.attachment, tunnelID }, options).pipe(Effect.timeout("5 seconds")), - ), + ) + }, + read: (tunnelID, signal) => { + const upstream = current() + + return Effect.runPromise( + upstream.rpc["tunnel.read"]({ ...upstream.attachment, tunnelID }, { location: upstream.location }), + { signal }, + ) + }, + write: (tunnelID, data, end, signal) => { + const upstream = current() + + return Effect.runPromise( + upstream.rpc["tunnel.write"]( + { ...upstream.attachment, tunnelID, data: Base64.encode(data), end }, + { location: upstream.location }, + ), + { signal }, + ) + }, + close: (tunnelID) => { + const upstream = current() + + return Effect.runPromise( + upstream.rpc["tunnel.close"]({ ...upstream.attachment, tunnelID }, { location: upstream.location }).pipe( + Effect.timeout("5 seconds"), + ), + ) + }, }), ), (proxy) => Effect.promise(() => proxy.close()), @@ -71,6 +107,8 @@ export const createBrowserNetwork = Effect.fn("BrowserNetwork.create")(function* return () => contents.off("login", login) }, + /** Ends the page connections that still run through the old binding; new requests fail fast. */ + disconnect: () => partition.closeAllConnections(), /** * Fetches a page icon through the server's network, as the page loaded it. Resolves undefined for anything but a * small image: a failure, a timeout, another content type, or more than `MAX_ICON_BYTES`. diff --git a/packages/gui-plugins/src/browser/pane-machine.test.ts b/packages/gui-plugins/src/browser/pane-machine.test.ts index 2631cefca8f..d3d5ed08770 100644 --- a/packages/gui-plugins/src/browser/pane-machine.test.ts +++ b/packages/gui-plugins/src/browser/pane-machine.test.ts @@ -150,13 +150,15 @@ describe("binding close reason", () => { 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", () => { + test("an unavailable server keeps an attached binding's pages 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" }, + { state: { tabs: [tab(tabA, dashboard, "", 1)], focusedTabID: tabA }, error: "browser.pane.disconnected" }, ]) expect(suspended.effects.map((effect) => effect.type)).not.toContain("remove-restore") + expect(suspended.effects.map((effect) => effect.type)).not.toContain("release-pages") + expect(suspended.effects.map((effect) => effect.type)).not.toContain("release-record") const connecting = play( createPaneState(), @@ -168,6 +170,46 @@ describe("binding close reason", () => { expect(connecting.effects.at(-1)).toEqual({ type: "teardown", binding: "b1" }) }) + test("a lost connection keeps the live pages for the reconnecting binding", () => { + const live = liveDashboard() + const lost = play(live, on({ type: "attachment.ended", outcome: "closed" })) + + expect(closeEvents(lost.effects)).toEqual([ + { + state: { tabs: [tab(tabA, dashboard, "Dashboard", 1)], focusedTabID: tabA }, + error: "browser.pane.disconnected", + }, + ]) + expect(lost.effects.map((effect) => effect.type)).not.toContain("release-pages") + expect(lost.effects.map((effect) => effect.type)).not.toContain("release-record") + expect(lost.effects.map((effect) => effect.type)).not.toContain("remove-restore") + }) + + test("closing the pane releases its live pages and its session record", () => { + const closed = play(liveDashboard(), on({ type: "client.closed" })) + + expect(closeEvents(closed.effects)).toEqual([{ state: null, error: "browser.pane.registration.closed" }]) + expect(closed.effects).toContainEqual({ type: "release-pages", binding: "b1", attempts: [1] }) + expect(closed.effects).toContainEqual({ type: "release-record", storageKey: "server\nb1" }) + }) + + test("a reconnect adopts the same tab ID into the new binding", () => { + const live = liveDashboard() + expect(selectBinding(live, "b1")?.nextAttempt).toBe(2) + + const reopened = play( + createPaneState(), + registered({ tabs: [tab(tabA, dashboard, "Dashboard")], focusedTabID: tabA }), + on({ type: "server.attached", fileRoots: [] }), + on({ type: "tab.opened", tabID: tabA, attempt: 1, tab: tab(tabA, dashboard, "Dashboard", 2) }), + on({ type: "tab.published", tabID: tabA, attempt: 1, tab: tab(tabA, dashboard, "Dashboard", 2) }), + ) + + expect(entry(reopened.state).tabs.get(tabA)).toMatchObject({ status: "live", attempt: 1 }) + expect(entry(reopened.state).focusedTabID).toBe(tabA) + expect(entry(reopened.state).nextAttempt).toBe(2) + }) + test("classifies attachment failures", () => { expect(attachmentFailure(new SessionNotFoundError({ sessionID: "ses_1", message: "Session not found" }))).toBe( "missing", @@ -188,7 +230,7 @@ describe("binding close reason", () => { expect(removes({ type: "attachment.ended", outcome: "closed" })).toBe(false) }) - test("disposing the pane suspends every binding with its tabs and refuses new ones", () => { + test("disposing the pane closes every binding and releases its pages", () => { const restore = { tabs: [tab(tabA, dashboard)], focusedTabID: tabA } const disposed = play( @@ -201,9 +243,11 @@ describe("binding close reason", () => { 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" }, + { state: null, error: "browser.pane.registration.closed" }, + { state: null, error: "browser.pane.registration.closed" }, ]) + expect(disposed.effects).toContainEqual({ type: "release-record", storageKey: "server\nb1" }) + expect(disposed.effects).toContainEqual({ type: "release-record", storageKey: "server\nb2" }) expect(transitionPane(disposed.state, registered())).toEqual({ state: disposed.state, effects: [] }) }) diff --git a/packages/gui-plugins/src/browser/pane-machine.ts b/packages/gui-plugins/src/browser/pane-machine.ts index 822cca70bbb..e290ef8e76c 100644 --- a/packages/gui-plugins/src/browser/pane-machine.ts +++ b/packages/gui-plugins/src/browser/pane-machine.ts @@ -80,7 +80,7 @@ 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: "attachment.ended"; readonly outcome: AttachmentOutcome; readonly keep?: boolean } | { readonly type: "register.timed-out" } /** The window navigated or was destroyed. */ | { readonly type: "owner.closed" } @@ -144,6 +144,8 @@ export type PaneEffect = | { 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[] } + /** The session's live pages, proxy and partition are going away with its last binding. */ + | { readonly type: "release-record"; readonly storageKey: string } /** 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 } @@ -268,7 +270,8 @@ function closeReason(state: ActiveBinding, event: BindingEvent): PaneCloseReason if (event.type === "owner.closed" || event.type === "client.closed") return "browser.pane.registration.closed" - if (event.type === "pane.disposed") return "browser.pane.suspended" + // The plugin is going away, taking its pages with it. + if (event.type === "pane.disposed") return "browser.pane.registration.closed" if (event.type === "screen.locked") return "browser.pane.locked" @@ -283,34 +286,45 @@ function closeReason(state: ActiveBinding, event: BindingEvent): PaneCloseReason 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" + // A retry of a session whose pages are still alive keeps them, even though this attempt never reached the server. + if (event.keep) return "browser.pane.disconnected" - return "browser.pane.registration.closed" + // A server that drops an attachment it accepted, as on idle eviction or a lost connection, keeps the session's live + // pages. One that never accepted it has no browser plugin. + if (event.outcome === "unavailable") + return state.status === "attached" ? "browser.pane.disconnected" : "browser.pane.unsupported" + + // The stream ended after the server accepted the binding: the connection went away, not the window. + return state.status === "attached" ? "browser.pane.disconnected" : "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[] = [] + // A lost server connection leaves the live pages, their proxy and partition in place. The record waits for the + // reconnecting binding that adopts it; only a close that ends the pane releases them. + + const keep = + reason === "browser.pane.disconnected" || reason === "browser.pane.suspended" || reason === "browser.pane.locked" if (forget) effects.push({ type: "remove-restore", storageKey: state.storageKey }) if (requestIDs.length) effects.push({ type: "abort-requests", binding: state.binding, requestIDs }) - // A suspended or locked binding hands its tabs to the window, which keeps them until it registers again. + // A kept binding, including a locked one, 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" || reason === "browser.pane.locked" ? selectInventory(state) : null, + state: keep ? selectInventory(state) : null, error: reason, }, }) - if (attempts.length) effects.push({ type: "release-pages", binding: state.binding, attempts }) + if (attempts.length && !keep) effects.push({ type: "release-pages", binding: state.binding, attempts }) + + if (!keep) effects.push({ type: "release-record", storageKey: state.storageKey }) effects.push({ type: "teardown", binding: state.binding }) return { state: { status: "closed", binding: state.binding, reason }, effects } @@ -532,6 +546,11 @@ export function selectTabSlot(state: PaneState, binding: string, tabID: Browser. return entry?.status === "attached" ? entry.tabs.get(tabID) : undefined } +/** The attempt the binding's next new page gets; live pages adopted from a previous binding take the ones before it. */ +export function selectNextAttempt(state: PaneState, binding: string) { + return selectBinding(state, binding)?.nextAttempt +} + /** 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) diff --git a/packages/gui-plugins/src/browser/pane.ts b/packages/gui-plugins/src/browser/pane.ts index 992328cb330..d4d30779374 100644 --- a/packages/gui-plugins/src/browser/pane.ts +++ b/packages/gui-plugins/src/browser/pane.ts @@ -3,13 +3,13 @@ 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 { Cause, Deferred, Effect, ManagedRuntime, Option, Queue, Schedule, Schema, Stream } from "effect" +import { Cause, Deferred, Effect, Exit, ManagedRuntime, Option, Queue, Schedule, Schema, Scope, 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" import { createBrowserPage, type BrowserPage, type Shared } from "./chromium" import { browserFailure } from "./errors" -import { createBrowserNetwork, type BrowserNetwork } from "./network" +import { createBrowserNetwork, type BrowserNetwork, type BrowserNetworkUpstream } from "./network" import { destinationOrigin, fileURLWithin, refusal } from "./policy" import { createRefs } from "./refs" import type { PaneEvent } from "./ipc" @@ -25,6 +25,7 @@ import { selectBinding, selectFileRoots, selectInventory, + selectNextAttempt, selectOwnedBinding, selectPageAttempt, selectTabSlot, @@ -39,19 +40,37 @@ import { createBrowserRestoreStore } from "./restore" type Target = { readonly server: string; readonly session: string; readonly restore?: Browser.State } +/** Where a live page currently reports: the binding and attempt that own it. Adoption updates it in place. */ +type PageOwner = { binding: string; attempt: number } + +/** A page kept for a session across bindings. The same WebContents and partition serve every reconnection. */ +type PageEntry = { readonly tabID: Browser.TabID; readonly page: BrowserPage; owner: PageOwner } + +/** A session's browser, kept while the app runs so a reconnect adopts its live pages. */ +type SessionRecord = { + readonly storageKey: string + readonly partition: string + readonly pages: Map + scoped: Scope.Closeable + network: BrowserNetwork + /** The current binding's tunnel. Absent while the server is disconnected. */ + upstream?: BrowserNetworkUpstream + /** The binding currently allowed to use this record. */ + 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 + record: SessionRecord abort: AbortController registered: ReturnType> cleanup: () => void timer?: ReturnType - network?: BrowserNetwork sendState?: (state: Browser.State) => void - /** Pages by attempt. */ - pages: Map + /** Pages live in this binding, by attempt. */ + pages: Map /** Agent requests in flight by request ID. */ requests: Map } @@ -74,11 +93,13 @@ export function createBrowserPane(input: { }) { const machine: PaneMachine = { state: createPaneState() } const handles = new Map() + const records = 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 releasingRecords = new Set>() const disposals = new WeakMap>() // Keep long-lived RPC requests off Chromium's shared HTTP connection pool. const runtime = ManagedRuntime.make(NodeHttpClient.layerNodeHttp) @@ -99,15 +120,16 @@ export function createBrowserPane(input: { 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 partition = `opencode-browser-${crypto.randomUUID()}` + const existing = records.get(storageKey) + // One window owns a session's pages at a time. A disconnected record has no binding, so the next register adopts it. - // 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(partition) - .webRequest.onBeforeRequest({ urls: ["file://*/*"] }, (details, callback) => - callback({ cancel: !fileURLWithin(details.url, selectFileRoots(machine.state, binding)) }), - ) + if (existing?.binding && selectBinding(machine.state, existing.binding)) + throw new Error("browser.pane.owner.invalid") + const record = existing ?? (await createRecord(storageKey)) + + if (input.locked()) throw new Error("browser.pane.locked") + + record.binding = binding const closed = () => dispatchBinding(binding, { type: "owner.closed" }) @@ -121,7 +143,7 @@ export function createBrowserPane(input: { const handle: Handle = { window, win, - partition, + record, abort: new AbortController(), registered: Promise.withResolvers(), cleanup: () => { @@ -170,7 +192,8 @@ export function createBrowserPane(input: { const attachment = { sessionID, connectionID: crypto.randomUUID() } const rpc = client.rpc(Browser.Definition) - handle.network = yield* createBrowserNetwork({ rpc, attachment, location: options.location, partition }) + // The proxy is stable for the session; only its upstream changes with the binding. + const upstream: BrowserNetworkUpstream = { rpc, attachment, location: options.location } const connected = yield* Deferred.make() const outbound = yield* Queue.unbounded>() @@ -263,7 +286,15 @@ export function createBrowserPane(input: { if (frame.kind === "foreign") return - if (frame.kind === "attached") return dispatchBinding(binding, { type: "server.attached", fileRoots }) + if (frame.kind === "attached") { + if (input.locked() || !selectBinding(machine.state, binding)) return + + record.upstream = upstream + dispatchBinding(binding, { type: "server.attached", fileRoots }) + adopt(binding, record) + + return + } if (frame.kind === "incompatible") return dispatchBinding(binding, { type: "handshake.unsupported" }) @@ -297,12 +328,32 @@ export function createBrowserPane(input: { }), // 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.tap((outcome) => + Effect.sync(() => { + // Only clear the upstream this binding installed: a replacement may already own the record. + if (record.binding === binding) { + record.upstream = undefined + void record.network.disconnect().catch(() => undefined) + } + + dispatchBinding(binding, { + type: "attachment.ended", + outcome, + keep: record.pages.size > 0, + }) + }), + ), Effect.scoped, ), { signal: handle.abort.signal }, ) - .catch(() => dispatchBinding(binding, { type: "attachment.ended", outcome: "closed" })) + .catch(() => + dispatchBinding(binding, { + type: "attachment.ended", + outcome: "closed", + keep: record.pages.size > 0, + }), + ) await handle.registered.promise if (!selectBinding(machine.state, binding)) throw new Error("browser.pane.registration.closed") @@ -353,6 +404,11 @@ export function createBrowserPane(input: { }, /** The screen locked: every attachment ends, so the server drops this desktop's browser tools until it unlocks. */ lock() { + // The pages stay live behind the local proxy, but it has no upstream to tunnel through while locked. + records.forEach((record) => { + record.upstream = undefined + void record.network.disconnect().catch(() => undefined) + }) dispatch({ type: "locked" }) }, /** @@ -361,6 +417,8 @@ export function createBrowserPane(input: { */ async dispose() { dispatch({ type: "disposed" }) + await Promise.all(Array.from(records.keys(), (storageKey) => releaseLater(storageKey))) + await Promise.all(releasingRecords) await Promise.all(releasing) await runtime.dispose() }, @@ -381,6 +439,8 @@ export function createBrowserPane(input: { if (effect.type === "remove-restore") return restore.remove(effect.storageKey) + if (effect.type === "release-record") return void releaseLater(effect.storageKey) + if (effect.type === "warn") return void runtime.runFork(Effect.logWarning(effect.message, effect.detail)) const handle = handles.get(effect.binding) @@ -411,12 +471,19 @@ export function createBrowserPane(input: { if (effect.type === "release-pages") return effect.attempts.forEach((attempt) => { - const page = handle.pages.get(attempt) + const entry = handle.pages.get(attempt) handle.pages.delete(attempt) - if (page) release(page) + if (!entry) return + + if (entry.owner.binding !== effect.binding || entry.owner.attempt !== attempt) return + + if (handle.record.pages.get(entry.tabID) === entry) handle.record.pages.delete(entry.tabID) + release(entry.page) }) handles.delete(effect.binding) + + if (handle.record.binding === effect.binding) handle.record.binding = undefined clearTimeout(handle.timer) handle.registered.reject(new Error("browser.pane.registration.closed")) handle.cleanup() @@ -443,6 +510,103 @@ export function createBrowserPane(input: { void settled.finally(() => releasing.delete(settled)) } + async function createRecord(storageKey: string) { + const partition = `opencode-browser-${crypto.randomUUID()}` + + let upstream: BrowserNetworkUpstream | undefined + const scoped = await runtime.runPromise(Scope.make()) + + const network = await runtime.runPromise( + createBrowserNetwork({ partition, upstream: () => upstream }).pipe(Effect.provideService(Scope.Scope, scoped)), + ) + + const record: SessionRecord = { + storageKey, + partition, + pages: new Map(), + scoped, + network, + get upstream() { + return upstream + }, + set upstream(value) { + upstream = value + }, + } + + // Navigation guards cover documents; subresources (img, script, fetch) also must not read file: URLs outside the + // roots. One listener per partition covers every page for the session, across bindings. + electron.session + .fromPartition(partition) + .webRequest.onBeforeRequest({ urls: ["file://*/*"] }, (details, callback) => + callback({ + cancel: !fileURLWithin(details.url, record.binding ? selectFileRoots(machine.state, record.binding) : []), + }), + ) + + records.set(storageKey, record) + + return record + } + + async function releaseRecord(storageKey: string) { + const record = records.get(storageKey) + + if (!record) return + records.delete(storageKey) + record.upstream = undefined + await record.network.disconnect().catch(() => undefined) + record.pages.forEach((entry) => release(entry.page)) + record.pages.clear() + await Promise.all(releasing) + await runtime.runPromise(Scope.close(record.scoped, Exit.void)).catch(() => undefined) + } + + function releaseLater(storageKey: string) { + const done = releaseRecord(storageKey) + releasingRecords.add(done) + void done.finally(() => releasingRecords.delete(done)) + + return done + } + + /** + * Adopts the session's live pages into a newly attached binding. Their WebContents, tab IDs and page state stay as + * they were; only the owner and attempts the machine tracks change. Tabs with no live page stay unloaded. + */ + function adopt(binding: string, record: SessionRecord) { + const entry = selectBinding(machine.state, binding) + const handle = handles.get(binding) + + if (entry?.status !== "attached" || !handle) return + const tabs = new Set(entry.tabs.keys()) + + record.pages.forEach((page, tabID) => { + if (tabs.has(tabID) && !page.page.contents.isDestroyed()) return + record.pages.delete(tabID) + release(page.page) + }) + + let attempt = selectNextAttempt(machine.state, binding) + + if (attempt === undefined) return + let published: { tabID: Browser.TabID; attempt: number; tab: Browser.Tab } | undefined + + record.pages.forEach((page, tabID) => { + if (attempt === undefined) return + page.owner.binding = binding + page.owner.attempt = attempt + handle.pages.set(attempt, page) + const tab = page.page.state() + dispatchBinding(binding, { type: "tab.opened", tabID, attempt, tab }) + emit(binding, { type: "embed", tabID, embed: page.page.embed }) + published = { tabID, attempt, tab } + attempt = selectNextAttempt(machine.state, binding) + }) + + if (published) dispatchBinding(binding, { type: "tab.published", ...published }) + } + function inventory(binding: string): Browser.State { const entry = selectBinding(machine.state, binding) @@ -453,7 +617,7 @@ export function createBrowserPane(input: { function page(binding: string, tabID: Browser.TabID) { const attempt = selectPageAttempt(machine.state, binding, tabID) - return attempt === undefined ? undefined : handles.get(binding)?.pages.get(attempt) + return attempt === undefined ? undefined : handles.get(binding)?.pages.get(attempt)?.page } /** The tab's page, created the first time the pane shows a restored or crashed tab or a command names it. */ @@ -491,73 +655,96 @@ export function createBrowserPane(input: { 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.") + if (entry?.status !== "attached" || !handle) 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 owner: PageOwner = { binding, attempt } + let page!: BrowserPage + let live: PageEntry | undefined + // Every callback is fenced to this page: a later page of the same tab has another attempt, and adoption updates + // the owner in place so the same page keeps reporting to whichever binding now owns it. + + const current = () => + live !== undefined && + handle.record.pages.get(id) === live && + isCurrentPage(machine.state, owner.binding, id, owner.attempt) + + const focused = () => current() && isFocusedPage(machine.state, owner.binding, id, owner.attempt) const fail = () => { if (current()) - dispatchBinding(binding, { + dispatchBinding(owner.binding, { type: "tab.crashed", tabID: id, - attempt, + attempt: owner.attempt, tab: page.contents.isDestroyed() ? undefined : page.state(), }) } - const page = createBrowserPage(win, { + page = createBrowserPage(win, { id, - partition: handle.partition, - network: handle.network, + partition: handle.record.partition, + network: handle.record.network, initialize: options.initialize, restore: options.restore, popupOptions: options.popupOptions, - fileRoots: () => selectFileRoots(machine.state, binding), + fileRoots: () => selectFileRoots(machine.state, owner.binding), shared, embeds: input.embeds, fail, publish: (error) => { - if (current()) dispatchBinding(binding, { type: "tab.published", tabID: id, attempt, tab: page.state(), error }) + if (current()) + dispatchBinding(owner.binding, { + type: "tab.published", + tabID: id, + attempt: owner.attempt, + tab: page.state(), + error, + }) }, inspect: (event) => { - if (current()) emit(binding, { type: "inspect", tabID: id, ...event }) + if (current()) emit(owner.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 (current()) emit(binding, { type: "page", tabID: id, ...value }) + if (current()) emit(owner.binding, { type: "page", tabID: id, ...value }) }, - zoomed: () => handles.get(binding)?.pages.forEach((page) => page.detail()), + zoomed: () => handle.pages.forEach((item) => item.page.detail()), shortcut: (shortcut) => { 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 (win.isFocused()) win.webContents.focus() - emit(binding, { type: "shortcut", ...shortcut }) + emit(owner.binding, { type: "shortcut", ...shortcut }) }, focused: () => { - if (focused()) emit(binding, { type: "focused", tabID: id }) + if (focused()) emit(owner.binding, { type: "focused", tabID: id }) }, popup: (popupOptions, background) => { - const popup = create(binding, { initialize: false, popupOptions }) + const popup = create(owner.binding, { initialize: false, popupOptions }) - if (!background) dispatchBinding(binding, { type: "tab.focused", tabID: popup.state().id }) + if (!background) dispatchBinding(owner.binding, { type: "tab.focused", tabID: popup.state().id }) return popup.contents }, }) - handle.pages.set(attempt, page) + live = { tabID: id, page, owner } + handle.record.pages.set(id, live) + handle.pages.set(attempt, live) 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. 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() }) + if (current()) + dispatchBinding(owner.binding, { + type: "tab.published", + tabID: id, + attempt: owner.attempt, + tab: page.state(), + }) }, fail) return page @@ -567,7 +754,7 @@ export function createBrowserPane(input: { 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 + if (attempt === undefined || handles.get(binding)?.pages.get(attempt)?.page !== page) return dispatchBinding(binding, { type: "tab.published", tabID, attempt, tab: page.state() }) } diff --git a/packages/gui-plugins/src/browser/panel.tsx b/packages/gui-plugins/src/browser/panel.tsx index 8e9b1b6d0b2..fa362ec5195 100644 --- a/packages/gui-plugins/src/browser/panel.tsx +++ b/packages/gui-plugins/src/browser/panel.tsx @@ -76,6 +76,7 @@ export default function SessionBrowserPane(props: { const address = () => (state()?.url === "about:blank" ? "" : (state()?.url ?? "")) const failed = () => !!state()?.loadError const suspended = () => props.model.suspended(props.session) + const connection = () => props.model.connection(props.session) const command = (action: Browser.Action) => props.model.command(props.session, action) const page = () => { @@ -401,6 +402,7 @@ export default function SessionBrowserPane(props: { id="browser-panel" // A click on the pane's own surface, like its loading or error view, keeps focus here, so its shortcuts apply. tabIndex={-1} + data-browser-connection={connection()} class="relative size-full min-w-0 overflow-hidden bg-v2-background-bg-base flex flex-col outline-none" >
+ +
+ {plugin.t("connection.disconnected")} +
+