From d5e398d7823aaeca5b60a006a8a679c0d72035ea Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 05:03:35 +1000 Subject: [PATCH] fix(browser): preserve deferred restores and settle hash navigation --- packages/gui-plugins/src/browser/chromium.ts | 32 ++++++------- .../src/browser/navigation-turn.test.ts | 45 +++++++++++++++++++ .../src/browser/navigation-turn.ts | 18 +++++++- 3 files changed, 79 insertions(+), 16 deletions(-) diff --git a/packages/gui-plugins/src/browser/chromium.ts b/packages/gui-plugins/src/browser/chromium.ts index e769b5a9ff6..67e996b667f 100644 --- a/packages/gui-plugins/src/browser/chromium.ts +++ b/packages/gui-plugins/src/browser/chromium.ts @@ -624,7 +624,7 @@ export function createBrowserPage( contents.on("did-start-loading", () => dispatch({ type: "loading.started" })) contents.on("did-stop-loading", () => dispatch({ type: "loading.stopped", title: pageTitle() })) contents.on("did-start-navigation", (event) => { - if (event.isMainFrame) navigation.cancel() + navigation.nativeStart(event) dispatch({ type: "navigation.started", url: displayURL(event.url), @@ -998,16 +998,17 @@ export function createBrowserPage( } const reload = async (signal = options.signal) => { - navigation.cancel() const tab = state() - if (tab.loadError && /^(?:file|workspace|artifact):/.test(tab.url)) return void await load(tab.url, true) + if (navigation.interrupt("reload", documentState.status === "restoring" ? documentState.url : undefined)) return + + if (tab.loadError && /^(?:file|workspace|artifact):/.test(tab.url)) return void await load(tab.url, true, signal) const actual = contents.getURL() - if (options.workspace?.host(actual) && options.workspace.display(actual) === tab.url) return void await load(tab.url, true) - const address = reloadAddress(actual, state().url, options.workspace?.host(actual), policy.fileRoots ?? [], policy.remote) + if (options.workspace?.host(actual) && options.workspace.display(actual) === tab.url) return void await load(tab.url, true, signal) + const address = reloadAddress(actual, tab.url, options.workspace?.host(actual), policy.fileRoots ?? [], policy.remote) - if (address) return void await load(address, true) + if (address) return void await load(address, true, signal) return begin(signal)(actual, () => contents.reload()) } @@ -1105,7 +1106,7 @@ export function createBrowserPage( * would run with that extension's privileges; every agent operation reaches the page through here. */ async execute(command: Browser.Command, signal: AbortSignal, origin: "agent" | "user"): Promise { - if (["stop", "back", "forward", "reload", "navigate"].includes(command.action.type)) navigation.cancel() + const saved = navigation.interrupt(command.action.type, documentState.status === "restoring" ? documentState.url : undefined) await ready const open = origin === "user" && leavable.includes(command.action.type) ? selectOpenDialog(dialogGate) : undefined @@ -1143,7 +1144,7 @@ export function createBrowserPage( choosers.update().then(() => { abortError(run.controller.signal) - return perform(command, run.controller.signal, origin) + return perform(command, run.controller.signal, origin, saved) }), run.interrupted.promise, ...(signIn ? [signIn.promise] : []), @@ -1189,8 +1190,8 @@ export function createBrowserPage( }, } - async function perform(command: Browser.Command, signal: AbortSignal, origin: "agent" | "user") { - if (origin === "user") return attempt(command, signal, origin) + async function perform(command: Browser.Command, signal: AbortSignal, origin: "agent" | "user", saved?: string) { + if (origin === "user") return attempt(command, signal, origin, saved) // An error document has no inspectable frame. Report the artifact failure before querying Chromium. if (state().loadError === FileVerificationError.code && !leavable.includes(command.action.type)) throw new FileVerificationError() @@ -1203,7 +1204,7 @@ export function createBrowserPage( const framed = await extensionFrameRefusal(used) if (framed) throw new Error(framed) - const result = await attempt(command, signal, origin) + const result = await attempt(command, signal, origin, saved) // A redirect, or a navigation while it ran, may have brought an extension page in, in the tab or in a frame the // action used; its result stays here. const moved = agentRefusal({ type: "snapshot" }, mainDocument()) ?? (await extensionFrameRefusal(used)) @@ -1229,7 +1230,7 @@ export function createBrowserPage( return context } - async function attempt(command: Browser.Command, signal: AbortSignal, origin: "agent" | "user"): Promise { + async function attempt(command: Browser.Command, signal: AbortSignal, origin: "agent" | "user", saved?: string): Promise { if (command.expectedSite && destinationOrigin(contents.mainFrame.url) !== command.expectedSite) throw new Error("The tab is no longer at the approved site; request the action again.") @@ -1254,7 +1255,7 @@ export function createBrowserPage( ) abortError(signal) - return execute(command.action, command.files, signal, origin, command.target) + return execute(command.action, command.files, signal, origin, command.target, saved) } async function execute( @@ -1263,6 +1264,7 @@ export function createBrowserPage( signal: AbortSignal, origin: "agent" | "user", approved?: Browser.Target, + saved?: string, ): Promise { const captureSources = sourceURLs() const transfer = (id: Browser.FileID) => files.transfer(id, approved?.resources) @@ -1307,10 +1309,10 @@ export function createBrowserPage( const index = history.getActiveIndex() + (action.type === "back" ? -1 : 1) const entry = index >= 0 && index < history.length() && history.getEntryAtIndex(index) - if (entry) await begin(signal)(entry.url, () => history.goToIndex(index)) + if (entry) await begin(signal)(entry.url, () => history.goToIndex(index), () => !closed() && contents.isLoading()) } - if (action.type === "reload") await reload(signal) + if (action.type === "reload" && !saved) await reload(signal) if (action.type === "stop") { navigation.cancel() diff --git a/packages/gui-plugins/src/browser/navigation-turn.test.ts b/packages/gui-plugins/src/browser/navigation-turn.test.ts index 9e4aaa8960d..7abe633f1a0 100644 --- a/packages/gui-plugins/src/browser/navigation-turn.test.ts +++ b/packages/gui-plugins/src/browser/navigation-turn.test.ts @@ -1,5 +1,6 @@ import { expect, test } from "bun:test" import { navigationTurn } from "./navigation-turn" +import { createDocumentState, transitionDocument } from "./page-machine" test.each(["stop", "oc-preview://private/report", "https://next.test"])('a later %s wins over a deferred web navigation', async next => { const gate = Promise.withResolvers() @@ -15,3 +16,47 @@ test.each(["stop", "oc-preview://private/report", "https://next.test"])('a later expect(issued).toEqual(next === "stop" ? [] : [next]) expect(spinner.slice(0, 2)).toEqual(["https://first.test", "stop"]) }) + +test("only a cross-document main-frame navigation supersedes a gated load", async () => { + for (const [main, same, expected] of [[true, true, 1], [false, false, 1], [true, false, 0]] as const) { + const gate = Promise.withResolvers() + const issued: string[] = [] + const navigation = navigationTurn(() => gate.promise, () => {}, () => {}) + const opening = navigation.begin(new AbortController().signal)("https://next.test", () => { issued.push("next") }) + navigation.nativeStart({ isMainFrame: main, isSameDocument: same }) + gate.resolve() + await opening + expect(issued).toHaveLength(expected) + } +}) + +test("a gated history traversal settles the spinner when Chromium has no load to stop", async () => { + const gate = Promise.withResolvers() + const events: string[] = [] + const navigation = navigationTurn(() => gate.promise, () => events.push("busy"), () => events.push("idle")) + const back = navigation.begin(new AbortController().signal)("https://app.test/#one", () => { events.push("back") }, () => false) + gate.resolve() + await back + expect(events).toEqual(["busy", "back", "idle"]) +}) + +test("reload during a gated restore joins the saved load rather than bootstrapping a blank page", async () => { + const url = "https://app.test/#report" + let doc = createDocumentState({ url, title: "Report", generation: 1 }) + const gate = Promise.withResolvers() + const issued: string[] = [] + + const navigation = navigationTurn(() => gate.promise, () => { + doc = transitionDocument(doc, { type: "loading.started" }).state + }, () => { doc = transitionDocument(doc, { type: "loading.stopped", title: "" }).state }) + + const load = (address: string) => navigation.begin(new AbortController().signal)(address, () => { issued.push(address) }) + const restore = load(url) + await Promise.resolve() + const saved = navigation.interrupt("reload", doc.status === "restoring" ? doc.url : undefined) + expect(doc).toMatchObject({ status: "restoring", url, busy: true }) + expect(saved).toBe(url) + gate.resolve() + await restore + expect(issued).toEqual([url]) +}) diff --git a/packages/gui-plugins/src/browser/navigation-turn.ts b/packages/gui-plugins/src/browser/navigation-turn.ts index 86a9789143a..26e78a923ca 100644 --- a/packages/gui-plugins/src/browser/navigation-turn.ts +++ b/packages/gui-plugins/src/browser/navigation-turn.ts @@ -1,3 +1,5 @@ +import type { Browser } from "@opencode/plugin-browser/rpc" + /** A page owns at most one not-yet-issued navigation. Once issued, Chromium owns cancellation and history. */ export function navigationTurn( wait: ((url: string, signal: AbortSignal) => Promise | undefined) | undefined, @@ -17,13 +19,24 @@ export function navigationTurn( return { cancel, + nativeStart(event: { isMainFrame: boolean; isSameDocument: boolean }) { + if (event.isMainFrame && !event.isSameDocument) cancel() + }, + interrupt(method: Browser.Method, restoring?: string) { + if (!["stop", "back", "forward", "reload", "navigate"].includes(method)) return + + // This load hasn't been issued yet. Let it satisfy Reload: cancelling would both lose its URL and leave + // initial CDP setup waiting for a renderer that the replacement command cannot start until setup finishes. + if (method === "reload" && pending && restoring && /^https?:\/\//i.test(restoring)) return restoring + cancel() + }, begin(signal: AbortSignal) { cancel() const mine = new AbortController() pending = mine const lifetime = AbortSignal.any([mine.signal, signal]) - return async (url: string, issue: () => void | Promise) => { + return async (url: string, issue: () => void | Promise, loading?: () => boolean) => { if (mine.signal.aborted) return lifetime.throwIfAborted() const waiting = wait?.(url, lifetime) @@ -49,6 +62,9 @@ export function navigationTurn( pending = undefined spinning = false await issue() + + // Same-document history traversal need not emit did-stop-loading to settle our synthetic spinner. + if (waiting && !pending && loading && !loading()) stopped() } }, }