mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-21 04:12:08 +03:00
fix(app): keep browser refs through downloads and blocked navigations (#61855)
This commit is contained in:
committed by
GitHub
Unverified
parent
6469454d35
commit
6b4fdc28ed
@@ -8,6 +8,15 @@ import { createBrowserFiles } from "./files"
|
||||
import { createDiagnostics } from "./diagnostics"
|
||||
import { loadIcon } from "./icon"
|
||||
import { pageLetter, pageReload, pageShortcut, type PageShortcut } from "./keys"
|
||||
import {
|
||||
createDocumentState,
|
||||
documentGeneration,
|
||||
documentIcon,
|
||||
documentTab,
|
||||
isDocumentClosed,
|
||||
transitionDocument,
|
||||
type DocumentEvent,
|
||||
} from "./page-machine"
|
||||
import { createProfiling, type Recording } from "./profiling"
|
||||
import type { BrowserNetwork } from "./network"
|
||||
import {
|
||||
@@ -230,15 +239,15 @@ export function createBrowserPage(
|
||||
options.zoomed?.()
|
||||
}
|
||||
|
||||
let icon: string | undefined
|
||||
// Bumped by every icon change, so a slow fetch for an earlier icon cannot replace a later one.
|
||||
let iconRequest = 0
|
||||
let documentState = createDocumentState(options.restore)
|
||||
const closed = () => isDocumentClosed(documentState)
|
||||
let reported = ""
|
||||
|
||||
const detail = () => {
|
||||
if (closed) return
|
||||
if (closed()) return
|
||||
// Chromium's factor for the outermost presets can land a rounding error outside them.
|
||||
const next: PageDetail = { zoom: Math.min(5, Math.max(0.25, contents.getZoomFactor())) }
|
||||
const icon = documentIcon(documentState)
|
||||
|
||||
if (icon) next.icon = icon
|
||||
const key = `${next.zoom}:${next.icon ?? ""}`
|
||||
@@ -248,14 +257,6 @@ export function createBrowserPage(
|
||||
options.detail?.(next)
|
||||
}
|
||||
|
||||
contents.on("page-favicon-updated", (_event, favicons) => {
|
||||
const request = ++iconRequest
|
||||
void loadIcon(favicons, options.network).then((value) => {
|
||||
if (closed || request !== iconRequest) return
|
||||
icon = value
|
||||
detail()
|
||||
})
|
||||
})
|
||||
const cdp = createCdp(contents)
|
||||
const documents = new Map<string, string>()
|
||||
const sourceURLs = () => [...new Set([contents.getURL(), ...documents.values()])].sort()
|
||||
@@ -277,8 +278,6 @@ export function createBrowserPage(
|
||||
let dialog: { type: string; message: string; defaultValue: string } | null = null
|
||||
let dialogURL = ""
|
||||
let dialogRevision = 0
|
||||
// The first restored navigation consumes the generation reserved in the unloaded inventory.
|
||||
let generation = options.restore ? options.restore.generation - 1 : 0
|
||||
let revision = 0
|
||||
cdp.on("Page.frameNavigated", ({ frame }) => {
|
||||
documents.set(frame.id, frame.url)
|
||||
@@ -288,113 +287,84 @@ export function createBrowserPage(
|
||||
documents.delete(frameId)
|
||||
revision++
|
||||
})
|
||||
let closed = false
|
||||
// The committed document's origin; its icon stays while navigations remain on it.
|
||||
let origin = ""
|
||||
// Whether the native surface holds a real document worth showing. Chromium keeps the
|
||||
// previous document painted until the next one renders, so a shown page stays shown
|
||||
// through later navigations; blank and failed documents hide until a real one is ready.
|
||||
let content = false
|
||||
let failure: { url: string; message: string } | undefined
|
||||
// A blank document is never shown, so its load does not count as loading: a new tab shows its new tab page at once.
|
||||
let blank = options.initialize !== false && !options.restore?.url
|
||||
// Chromium names a document after its URL until its <title> parses. A navigation on the same site keeps the shown
|
||||
// title until the new document names itself or stops loading, so a page that reloads or redirects to itself does
|
||||
// not flash its URL in the tab strip.
|
||||
let title = ""
|
||||
|
||||
const state = (): Browser.Tab => {
|
||||
const page = {
|
||||
const state = () =>
|
||||
documentTab(documentState, {
|
||||
id: options.id,
|
||||
url: (failure?.url ?? contents.getURL()).slice(0, 16_384),
|
||||
title: title.slice(0, 2_048),
|
||||
loading: contents.isLoading() && !blank,
|
||||
}
|
||||
|
||||
const history = {
|
||||
canGoBack: contents.navigationHistory.canGoBack(),
|
||||
canGoForward: contents.navigationHistory.canGoForward(),
|
||||
generation,
|
||||
}
|
||||
})
|
||||
|
||||
return failure ? { ...page, loadError: failure.message, ...history } : { ...page, ...history }
|
||||
// Every state report goes through here, so a page that was disposed publishes nothing.
|
||||
const publish = (error?: string) => {
|
||||
if (!closed()) options.publish(error)
|
||||
}
|
||||
|
||||
const publish = () => {
|
||||
if (!closed) options.publish()
|
||||
const dispatch = (event: DocumentEvent) => {
|
||||
const next = transitionDocument(documentState, event)
|
||||
documentState = next.state
|
||||
next.effects.forEach((effect) => {
|
||||
switch (effect.type) {
|
||||
case "reset-document":
|
||||
documents.clear()
|
||||
refs.clear()
|
||||
picked.clear()
|
||||
|
||||
if (inspecting) void toggleInspect(false)
|
||||
break
|
||||
case "clear-diagnostics":
|
||||
diagnostics.clear()
|
||||
break
|
||||
case "show":
|
||||
// The renderer's layout requests may lag behind navigation; the page decides
|
||||
// whether there is a document worth exposing over the themed background.
|
||||
embed.show(effect.visible)
|
||||
break
|
||||
case "publish":
|
||||
publish()
|
||||
break
|
||||
case "detail":
|
||||
detail()
|
||||
break
|
||||
case "load-icon":
|
||||
// Never rejects: an icon that does not load is none.
|
||||
void loadIcon(effect.favicons, options.network).then((icon) =>
|
||||
dispatch({ type: "icon.loaded", attempt: effect.attempt, icon }),
|
||||
)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const reset = (event: Electron.Event<{ url: string; isMainFrame: boolean; isSameDocument: boolean }>) => {
|
||||
if (!event.isMainFrame || event.isSameDocument) return
|
||||
blank = event.url === "about:blank"
|
||||
failure = undefined
|
||||
generation++
|
||||
documents.clear()
|
||||
refs.clear()
|
||||
picked.clear()
|
||||
diagnostics.clear()
|
||||
|
||||
if (inspecting) void toggleInspect(false)
|
||||
publish()
|
||||
}
|
||||
|
||||
const settle = () => {
|
||||
content = contents.getURL() !== "about:blank" && !failure
|
||||
updateVisibility()
|
||||
}
|
||||
|
||||
contents.on("did-start-navigation", reset)
|
||||
contents.on("did-navigate", (_event, url, status, statusText) => {
|
||||
// The server-network proxy answers an unreachable HTTP target with an empty 502. Other
|
||||
// error statuses are real documents from the user's server and stay visible.
|
||||
if (status === 502) failure = { url, message: `${status} ${statusText}`.trim().slice(0, 2_048) }
|
||||
|
||||
// Another site's icon arrives with its document; the same site keeps its icon meanwhile, as tabs do. Files and blank
|
||||
// pages have no shared origin, so each keeps none.
|
||||
const next = destinationOrigin(url) ?? url
|
||||
|
||||
if (next !== origin) {
|
||||
icon = undefined
|
||||
iconRequest++
|
||||
title = contents.getTitle()
|
||||
}
|
||||
|
||||
origin = next
|
||||
|
||||
// A blank or failed document paints at commit; a real one waits for dom-ready.
|
||||
if (url === "about:blank" || failure) settle()
|
||||
publish()
|
||||
// After the state that names the new URL. Chromium keeps a zoom per origin, so a new site may have its own.
|
||||
detail()
|
||||
})
|
||||
contents.on("did-fail-load", (_event, code, description, url, isMainFrame) => {
|
||||
// Cancelled navigation and failed subframes do not replace the current page.
|
||||
if (!isMainFrame || code === -3) return
|
||||
failure = { url, message: description.slice(0, 2_048) }
|
||||
settle()
|
||||
publish()
|
||||
})
|
||||
contents.on("dom-ready", settle)
|
||||
|
||||
const retitle = () => {
|
||||
title = contents.getTitle()
|
||||
publish()
|
||||
}
|
||||
|
||||
contents.on("did-stop-loading", () => {
|
||||
settle()
|
||||
retitle()
|
||||
})
|
||||
contents.on("did-navigate-in-page", retitle)
|
||||
contents.on("did-start-loading", () => dispatch({ type: "loading.started" }))
|
||||
contents.on("did-stop-loading", () => dispatch({ type: "loading.stopped", title: contents.getTitle() }))
|
||||
contents.on("did-start-navigation", (event) =>
|
||||
dispatch({
|
||||
type: "navigation.started",
|
||||
url: event.url,
|
||||
isMainFrame: event.isMainFrame,
|
||||
isSameDocument: event.isSameDocument,
|
||||
}),
|
||||
)
|
||||
contents.on("did-navigate", (_event, url, status, statusText) =>
|
||||
dispatch({ type: "navigation.committed", url, status, statusText, title: contents.getTitle() }),
|
||||
)
|
||||
contents.on("did-fail-load", (_event, code, description, url, isMainFrame) =>
|
||||
dispatch({ type: "navigation.failed", code, description, url, isMainFrame }),
|
||||
)
|
||||
contents.on("did-navigate-in-page", (_event, url, isMainFrame) =>
|
||||
dispatch({ type: "navigation.in-page", url, title: contents.getTitle(), isMainFrame }),
|
||||
)
|
||||
contents.on("dom-ready", () => dispatch({ type: "document.ready" }))
|
||||
contents.on("page-title-updated", () => dispatch({ type: "title.updated", title: contents.getTitle() }))
|
||||
contents.on("page-favicon-updated", (_event, favicons) => dispatch({ type: "icon.updated", favicons }))
|
||||
contents.on("focus", () => {
|
||||
if (!closed) options.focused?.()
|
||||
if (!closed()) options.focused?.()
|
||||
})
|
||||
contents.on("page-title-updated", retitle)
|
||||
contents.on("render-process-gone", () => {
|
||||
if (!closed) options.fail()
|
||||
if (!closed()) options.fail()
|
||||
})
|
||||
contents.debugger.on("detach", () => {
|
||||
if (!closed) options.fail()
|
||||
if (!closed()) options.fail()
|
||||
})
|
||||
contents.session.setPermissionRequestHandler((_contents, _permission, callback) => callback(false))
|
||||
contents.session.setPermissionCheckHandler(() => false)
|
||||
@@ -412,7 +382,7 @@ export function createBrowserPage(
|
||||
if (!event.isMainFrame && fileURLWithin(event.url, policy.fileRoots ?? [])) return
|
||||
event.preventDefault()
|
||||
// The same reason a typed address gets, so a blocked link and a blocked address read alike.
|
||||
options.publish(refusal(event.url, policy) ?? "ERR_BLOCKED_BY_CLIENT")
|
||||
publish(refusal(event.url, policy) ?? "ERR_BLOCKED_BY_CLIENT")
|
||||
}
|
||||
|
||||
contents.on("will-frame-navigate", guard)
|
||||
@@ -462,7 +432,7 @@ export function createBrowserPage(
|
||||
})
|
||||
} catch {
|
||||
item.cancel()
|
||||
options.publish("download_failed")
|
||||
publish("download_failed")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -538,13 +508,10 @@ export function createBrowserPage(
|
||||
// A hidden page cannot be picked from, and a comment's frozen still already shows the
|
||||
// picked element, so hiding ends the picker, any pick in progress, and the highlight.
|
||||
embed.on("visible", (visible) => {
|
||||
if (visible || closed) return
|
||||
if (visible || closed()) return
|
||||
picks++
|
||||
void (inspecting ? toggleInspect(false) : hideHighlight())
|
||||
})
|
||||
// The renderer's layout requests may lag behind navigation; the page decides
|
||||
// whether there is a document worth exposing over the themed background.
|
||||
const updateVisibility = () => embed.show(content)
|
||||
|
||||
const load = (url: string) => {
|
||||
let committed = false
|
||||
@@ -571,7 +538,7 @@ export function createBrowserPage(
|
||||
load(normalizeURL(options.restore?.url || "about:blank", policy)).catch((error: Error) => {
|
||||
if (!options.restore) throw error
|
||||
// A dev server may have stopped while this page was unloaded. Keep its tab available to retry.
|
||||
options.publish(error.message)
|
||||
publish(error.message)
|
||||
}),
|
||||
]),
|
||||
diagnostics.enable(),
|
||||
@@ -593,21 +560,21 @@ export function createBrowserPage(
|
||||
/** The host embed the renderer lays this page out with. */
|
||||
embed: embed.id,
|
||||
async inspect(enabled: boolean) {
|
||||
if (closed) return
|
||||
if (closed()) return
|
||||
await ready
|
||||
await toggleInspect(enabled)
|
||||
},
|
||||
async highlight(ref?: Browser.Ref) {
|
||||
if (closed) return
|
||||
if (closed()) return
|
||||
await highlightPicked(ref).catch(() => undefined)
|
||||
},
|
||||
zoom(direction: "in" | "out" | "reset") {
|
||||
if (!closed) zoom(direction)
|
||||
if (!closed()) zoom(direction)
|
||||
},
|
||||
async site() {
|
||||
const url = contents.getURL()
|
||||
|
||||
if (closed || !destinationOrigin(url)) return { cookies: 0 }
|
||||
if (closed() || !destinationOrigin(url)) return { cookies: 0 }
|
||||
|
||||
return { cookies: (await contents.session.cookies.get({ url })).length }
|
||||
},
|
||||
@@ -619,7 +586,7 @@ export function createBrowserPage(
|
||||
const url = contents.getURL()
|
||||
const origin = destinationOrigin(url)
|
||||
|
||||
if (closed || !origin) return
|
||||
if (closed() || !origin) return
|
||||
const cookies = await contents.session.cookies.get({ url })
|
||||
await Promise.all(cookies.map((cookie) => contents.session.cookies.remove(cookieURL(cookie), cookie.name)))
|
||||
await contents.session.clearStorageData({
|
||||
@@ -627,10 +594,12 @@ export function createBrowserPage(
|
||||
storages: ["localstorage", "indexdb", "serviceworkers", "cachestorage", "filesystem", "shadercache"],
|
||||
})
|
||||
|
||||
if (closed) return
|
||||
if (closed()) return
|
||||
contents.reload()
|
||||
// A slow page still cleared; the count then reads what it set so far.
|
||||
await waitFor(() => closed || !contents.isLoading(), new AbortController().signal, 30_000).catch(() => undefined)
|
||||
await waitFor(() => closed() || !contents.isLoading(), new AbortController().signal, 30_000).catch(
|
||||
() => undefined,
|
||||
)
|
||||
},
|
||||
/** Reports the page's icon and zoom when either changed since the last report. */
|
||||
detail,
|
||||
@@ -638,7 +607,7 @@ export function createBrowserPage(
|
||||
await ready
|
||||
abortError(signal)
|
||||
|
||||
if (closed)
|
||||
if (closed())
|
||||
throw new Error(
|
||||
"Browser tab was closed. Call browser.tabs.list({}) and choose an existing tabID; do not reuse the closed tab's refs.",
|
||||
)
|
||||
@@ -659,7 +628,7 @@ export function createBrowserPage(
|
||||
|
||||
if (
|
||||
command.generation !== undefined &&
|
||||
command.generation !== generation &&
|
||||
command.generation !== documentGeneration(documentState) &&
|
||||
!retainedOperations.includes(command.action.type)
|
||||
)
|
||||
throw new Error(
|
||||
@@ -707,8 +676,8 @@ export function createBrowserPage(
|
||||
}
|
||||
},
|
||||
async dispose() {
|
||||
if (closed) return
|
||||
closed = true
|
||||
if (closed()) return
|
||||
dispatch({ type: "disposed" })
|
||||
clearTimeout(flash)
|
||||
detachNetwork?.()
|
||||
contents.session.off("will-download", download)
|
||||
@@ -1136,7 +1105,7 @@ export function createBrowserPage(
|
||||
if (action.type === "dialog")
|
||||
return {
|
||||
resources: [dialog ? dialogURL : contents.getURL()],
|
||||
key: `${generation}:${dialogRevision}:${Boolean(dialog)}`,
|
||||
key: `${documentGeneration(documentState)}:${dialogRevision}:${Boolean(dialog)}`,
|
||||
}
|
||||
|
||||
const fileIDs =
|
||||
@@ -1194,7 +1163,7 @@ export function createBrowserPage(
|
||||
: [contents.getURL()],
|
||||
),
|
||||
].sort(),
|
||||
key: JSON.stringify([generation, revision, selected]),
|
||||
key: JSON.stringify([documentGeneration(documentState), revision, selected]),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1596,7 +1565,7 @@ export function createBrowserPage(
|
||||
async function inspected(backendID: number, sessionID?: string) {
|
||||
inspecting = false
|
||||
const pick = ++picks
|
||||
const navigation = generation
|
||||
const navigation = documentGeneration(documentState)
|
||||
await Promise.all(
|
||||
[undefined, ...sessions.values()].map((id) =>
|
||||
cdp.send("Overlay.setInspectMode", inspectOff, id).catch(() => undefined),
|
||||
@@ -1609,9 +1578,9 @@ export function createBrowserPage(
|
||||
await painted(sessionID)
|
||||
|
||||
// Escape, a toggle, hiding, or navigation while the element was described cancels the pick.
|
||||
if (closed) return
|
||||
if (closed()) return
|
||||
|
||||
if (pick !== picks || navigation !== generation) {
|
||||
if (pick !== picks || navigation !== documentGeneration(documentState)) {
|
||||
if (!inspecting) await hideHighlight()
|
||||
options.inspect?.({ active: inspecting })
|
||||
|
||||
|
||||
@@ -0,0 +1,352 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { Browser } from "@opencode/plugin-browser/rpc"
|
||||
import {
|
||||
createDocumentState,
|
||||
documentGeneration,
|
||||
documentTab,
|
||||
documentVisible,
|
||||
isDocumentLoading,
|
||||
transitionDocument,
|
||||
type DocumentEvent,
|
||||
type DocumentState,
|
||||
type DocumentTransition,
|
||||
} from "./page-machine"
|
||||
|
||||
const history = { id: Browser.TabID.make(`tab_${"0".repeat(36)}`), canGoBack: false, canGoForward: false }
|
||||
|
||||
// Folds the events in order and returns the last transition, with every effect on the way.
|
||||
const replay = (events: readonly DocumentEvent[], state: DocumentState = createDocumentState()) =>
|
||||
events.reduce<DocumentTransition & { all: DocumentTransition["effects"] }>(
|
||||
(last, event) => {
|
||||
const next = transitionDocument(last.state, event)
|
||||
|
||||
return { ...next, all: [...last.all, ...next.effects] }
|
||||
},
|
||||
{ state, effects: [], all: [] },
|
||||
)
|
||||
|
||||
const types = (effects: DocumentTransition["effects"]) => effects.map((effect) => effect.type)
|
||||
|
||||
// Electron's events for a navigation that commits and finishes loading.
|
||||
const visit = (url: string, title = url): DocumentEvent[] => [
|
||||
{ type: "navigation.started", url, isMainFrame: true, isSameDocument: false },
|
||||
{ type: "loading.started" },
|
||||
{ type: "navigation.committed", url, status: 200, statusText: "OK", title },
|
||||
{ type: "document.ready" },
|
||||
{ type: "loading.stopped", title },
|
||||
]
|
||||
|
||||
// A new tab that loaded about:blank, then a shown page at generation 2 with an icon.
|
||||
const shown = () =>
|
||||
replay([
|
||||
...visit("about:blank", ""),
|
||||
...visit("https://alpha.example/", "Alpha"),
|
||||
{ type: "icon.updated", favicons: ["https://alpha.example/favicon.ico"] },
|
||||
{ type: "icon.loaded", attempt: 3, icon: "data:image/png;base64,AA" },
|
||||
]).state
|
||||
|
||||
describe("uncommitted navigations keep the document", () => {
|
||||
test("a download keeps the generation, refs and the shown page", () => {
|
||||
const start = shown()
|
||||
expect(documentGeneration(start)).toBe(2)
|
||||
|
||||
const pending = replay(
|
||||
[
|
||||
{
|
||||
type: "navigation.started",
|
||||
url: "https://alpha.example/report.zip",
|
||||
isMainFrame: true,
|
||||
isSameDocument: false,
|
||||
},
|
||||
{ type: "loading.started" },
|
||||
],
|
||||
start,
|
||||
)
|
||||
|
||||
expect(isDocumentLoading(pending.state)).toBe(true)
|
||||
expect(documentGeneration(pending.state)).toBe(2)
|
||||
|
||||
const done = replay([{ type: "loading.stopped", title: "Alpha" }], pending.state)
|
||||
expect(isDocumentLoading(done.state)).toBe(false)
|
||||
expect(documentGeneration(done.state)).toBe(2)
|
||||
expect(documentVisible(done.state)).toBe(true)
|
||||
expect(types([...pending.all, ...done.all])).not.toContain("reset-document")
|
||||
expect(documentTab(done.state, history)).toMatchObject({ url: "https://alpha.example/", title: "Alpha" })
|
||||
})
|
||||
|
||||
test("a blocked or cancelled navigation keeps the document", () => {
|
||||
const start = shown()
|
||||
|
||||
const result = replay(
|
||||
[
|
||||
{ type: "navigation.started", url: "https://blocked.example/", isMainFrame: true, isSameDocument: false },
|
||||
{ type: "loading.started" },
|
||||
{
|
||||
type: "navigation.failed",
|
||||
code: -3,
|
||||
description: "ERR_ABORTED",
|
||||
url: "https://blocked.example/",
|
||||
isMainFrame: true,
|
||||
},
|
||||
{ type: "loading.stopped", title: "Alpha" },
|
||||
],
|
||||
start,
|
||||
)
|
||||
|
||||
expect(types(result.all)).not.toContain("reset-document")
|
||||
expect(types(result.all)).not.toContain("show")
|
||||
expect(result.state).toMatchObject({
|
||||
status: "loaded",
|
||||
url: "https://alpha.example/",
|
||||
title: "Alpha",
|
||||
icon: "data:image/png;base64,AA",
|
||||
generation: 2,
|
||||
revealed: true,
|
||||
})
|
||||
})
|
||||
|
||||
test("only the commit bumps the generation and resets the document", () => {
|
||||
const start = shown()
|
||||
|
||||
const started = replay(
|
||||
[{ type: "navigation.started", url: "https://beta.example/", isMainFrame: true, isSameDocument: false }],
|
||||
start,
|
||||
)
|
||||
|
||||
expect(types(started.effects)).toEqual(["clear-diagnostics", "publish"])
|
||||
expect(documentGeneration(started.state)).toBe(2)
|
||||
|
||||
const committed = replay(
|
||||
[{ type: "navigation.committed", url: "https://beta.example/", status: 200, statusText: "OK", title: "beta" }],
|
||||
started.state,
|
||||
)
|
||||
|
||||
expect(types(committed.effects)).toEqual(["reset-document", "publish", "detail"])
|
||||
expect(documentGeneration(committed.state)).toBe(3)
|
||||
})
|
||||
})
|
||||
|
||||
test("a popup on about:blank is not loading until it navigates away", () => {
|
||||
const blank = replay([{ type: "loading.started" }]).state
|
||||
expect(blank.status).toBe("blank")
|
||||
expect(isDocumentLoading(blank)).toBe(false)
|
||||
|
||||
const started = replay(
|
||||
[{ type: "navigation.started", url: "https://popup.example/", isMainFrame: true, isSameDocument: false }],
|
||||
blank,
|
||||
)
|
||||
|
||||
expect(isDocumentLoading(started.state)).toBe(true)
|
||||
|
||||
const committed = replay(
|
||||
[{ type: "navigation.committed", url: "https://popup.example/", status: 200, statusText: "OK", title: "" }],
|
||||
started.state,
|
||||
)
|
||||
|
||||
expect(documentGeneration(committed.state)).toBe(1)
|
||||
expect(isDocumentLoading(committed.state)).toBe(true)
|
||||
})
|
||||
|
||||
describe("failed documents", () => {
|
||||
const dead = () =>
|
||||
replay([
|
||||
...visit("about:blank", ""),
|
||||
{ type: "navigation.started", url: "https://dead.example/", isMainFrame: true, isSameDocument: false },
|
||||
{ type: "loading.started" },
|
||||
{
|
||||
type: "navigation.failed",
|
||||
code: -102,
|
||||
description: "ERR_CONNECTION_REFUSED",
|
||||
url: "https://dead.example/",
|
||||
isMainFrame: true,
|
||||
},
|
||||
{ type: "loading.stopped", title: "dead.example" },
|
||||
]).state
|
||||
|
||||
test("a stopped reload of a failed page never reveals Chromium's error page", () => {
|
||||
const start = dead()
|
||||
expect(documentTab(start, history).loadError).toBe("ERR_CONNECTION_REFUSED")
|
||||
|
||||
const reloading = replay(
|
||||
[
|
||||
{ type: "navigation.started", url: "https://dead.example/", isMainFrame: true, isSameDocument: false },
|
||||
{ type: "loading.started" },
|
||||
],
|
||||
start,
|
||||
)
|
||||
|
||||
expect(documentTab(reloading.state, history).loading).toBe(true)
|
||||
expect(documentTab(reloading.state, history)).not.toHaveProperty("loadError")
|
||||
|
||||
const stopped = replay(
|
||||
[
|
||||
{
|
||||
type: "navigation.failed",
|
||||
code: -3,
|
||||
description: "ERR_ABORTED",
|
||||
url: "https://dead.example/",
|
||||
isMainFrame: true,
|
||||
},
|
||||
{ type: "loading.stopped", title: "dead.example" },
|
||||
],
|
||||
reloading.state,
|
||||
)
|
||||
|
||||
expect(documentTab(stopped.state, history)).toMatchObject({ loading: false, loadError: "ERR_CONNECTION_REFUSED" })
|
||||
expect(documentVisible(stopped.state)).toBe(false)
|
||||
expect(types([...reloading.all, ...stopped.all])).not.toContain("show")
|
||||
})
|
||||
|
||||
test("the proxy's 502 stays failed and hidden through dom-ready and stop", () => {
|
||||
const result = replay([
|
||||
...visit("https://alpha.example/", "Alpha"),
|
||||
{ type: "navigation.started", url: "https://alpha.example/down", isMainFrame: true, isSameDocument: false },
|
||||
{
|
||||
type: "navigation.committed",
|
||||
url: "https://alpha.example/down",
|
||||
status: 502,
|
||||
statusText: "Bad Gateway",
|
||||
title: "",
|
||||
},
|
||||
{ type: "document.ready" },
|
||||
{ type: "loading.stopped", title: "" },
|
||||
])
|
||||
|
||||
expect(result.state.status).toBe("failed")
|
||||
expect(documentVisible(result.state)).toBe(false)
|
||||
expect(documentTab(result.state, history).loadError).toBe("502 Bad Gateway")
|
||||
expect(result.all.filter((effect) => effect.type === "show")).toEqual([
|
||||
{ type: "show", visible: true },
|
||||
{ type: "show", visible: false },
|
||||
])
|
||||
})
|
||||
|
||||
test("a failure after the commit keeps the committed generation", () => {
|
||||
const result = replay([
|
||||
...visit("https://alpha.example/", "Alpha"),
|
||||
{ type: "navigation.started", url: "https://alpha.example/next", isMainFrame: true, isSameDocument: false },
|
||||
{ type: "navigation.committed", url: "https://alpha.example/next", status: 200, statusText: "OK", title: "" },
|
||||
{
|
||||
type: "navigation.failed",
|
||||
code: -2,
|
||||
description: "ERR_FAILED",
|
||||
url: "https://alpha.example/next",
|
||||
isMainFrame: true,
|
||||
},
|
||||
])
|
||||
|
||||
expect(result.state.status).toBe("failed")
|
||||
expect(documentGeneration(result.state)).toBe(2)
|
||||
expect(types(result.effects)).toEqual(["show", "publish"])
|
||||
})
|
||||
|
||||
test("a failed subframe does not replace the page", () => {
|
||||
const start = shown()
|
||||
|
||||
const result = transitionDocument(start, {
|
||||
type: "navigation.failed",
|
||||
code: -105,
|
||||
description: "ERR_NAME_NOT_RESOLVED",
|
||||
url: "https://ads.example/",
|
||||
isMainFrame: false,
|
||||
})
|
||||
|
||||
expect(result.state).toBe(start)
|
||||
expect(result.effects).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe("restored tabs", () => {
|
||||
const restore = { url: "https://alpha.example/", title: "Alpha", generation: 4 }
|
||||
|
||||
test("the first commit consumes the reserved generation", () => {
|
||||
const start = createDocumentState(restore)
|
||||
expect(documentTab(start, history)).toMatchObject({ url: "https://alpha.example/", generation: 4, loading: false })
|
||||
|
||||
const events = visit("https://alpha.example/", "Alpha")
|
||||
|
||||
expect(events.map((_, index) => documentGeneration(replay(events.slice(0, index + 1), start).state))).toEqual([
|
||||
4, 4, 4, 4, 4,
|
||||
])
|
||||
|
||||
const loaded = replay(events, start).state
|
||||
expect(documentGeneration(replay(visit("https://alpha.example/b"), loaded).state)).toBe(5)
|
||||
})
|
||||
|
||||
test("a failed first load consumes it too", () => {
|
||||
const result = replay(
|
||||
[
|
||||
{ type: "navigation.started", url: "https://alpha.example/", isMainFrame: true, isSameDocument: false },
|
||||
{
|
||||
type: "navigation.failed",
|
||||
code: -102,
|
||||
description: "ERR_CONNECTION_REFUSED",
|
||||
url: "https://alpha.example/",
|
||||
isMainFrame: true,
|
||||
},
|
||||
],
|
||||
createDocumentState(restore),
|
||||
)
|
||||
|
||||
expect(result.state).toMatchObject({ status: "failed", generation: 4, url: "https://alpha.example/" })
|
||||
})
|
||||
})
|
||||
|
||||
describe("title and icon", () => {
|
||||
test("the same site keeps its title and icon until the new document names itself", () => {
|
||||
const start = shown()
|
||||
|
||||
const committed = transitionDocument(start, {
|
||||
type: "navigation.committed",
|
||||
url: "https://alpha.example/next",
|
||||
status: 200,
|
||||
statusText: "OK",
|
||||
title: "alpha.example/next",
|
||||
}).state
|
||||
|
||||
expect(committed).toMatchObject({ title: "Alpha", icon: "data:image/png;base64,AA" })
|
||||
expect(transitionDocument(committed, { type: "title.updated", title: "Next" }).state).toMatchObject({
|
||||
title: "Next",
|
||||
})
|
||||
})
|
||||
|
||||
test("another site drops the icon and ignores the earlier site's slow fetch", () => {
|
||||
const pending = replay([{ type: "icon.updated", favicons: ["https://alpha.example/new.ico"] }], shown()).state
|
||||
|
||||
const committed = replay(
|
||||
[
|
||||
{ type: "navigation.started", url: "https://beta.example/", isMainFrame: true, isSameDocument: false },
|
||||
{
|
||||
type: "navigation.committed",
|
||||
url: "https://beta.example/",
|
||||
status: 200,
|
||||
statusText: "OK",
|
||||
title: "beta.example",
|
||||
},
|
||||
],
|
||||
pending,
|
||||
).state
|
||||
|
||||
expect(committed).toMatchObject({ title: "beta.example", icon: undefined })
|
||||
const late = transitionDocument(committed, { type: "icon.loaded", attempt: 3, icon: "data:image/png;base64,BB" })
|
||||
expect(late.state).toBe(committed)
|
||||
expect(late.effects).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
test("a disposed document ignores every later event", () => {
|
||||
const closed = transitionDocument(shown(), { type: "disposed" }).state
|
||||
expect(closed.status).toBe("closed")
|
||||
|
||||
const events: DocumentEvent[] = [
|
||||
...visit("https://beta.example/"),
|
||||
{ type: "icon.loaded", attempt: 2, icon: undefined },
|
||||
{ type: "title.updated", title: "Beta" },
|
||||
]
|
||||
|
||||
events.forEach((event) => {
|
||||
const next = transitionDocument(closed, event)
|
||||
expect(next.state).toBe(closed)
|
||||
expect(next.effects).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,298 @@
|
||||
import type { Browser } from "@opencode/plugin-browser/rpc"
|
||||
import { destinationOrigin } from "./policy"
|
||||
|
||||
// The document a browser page shows, folded from Electron's navigation events. Electron-free so it stays
|
||||
// unit-testable under Bun.
|
||||
|
||||
type Document = {
|
||||
/** Bumped when a navigation replaces the document; refs and operations from an older one are stale. */
|
||||
readonly generation: number
|
||||
readonly url: string
|
||||
/**
|
||||
* Chromium names a document after its URL until its <title> parses. A navigation on the same site keeps the shown
|
||||
* title until the new document names itself or stops loading, so a page that reloads or redirects to itself does
|
||||
* not flash its URL in the tab strip.
|
||||
*/
|
||||
readonly title: string
|
||||
/** The committed document's origin; its icon stays while navigations remain on it. */
|
||||
readonly origin: string
|
||||
readonly icon: string | undefined
|
||||
/** Bumped by every icon change, so a slow fetch for an earlier icon cannot replace a later one. */
|
||||
readonly iconAttempt: number
|
||||
/**
|
||||
* The main-frame navigation that started and has not committed, failed, or stopped. Downloads, blocked links and
|
||||
* cancelled loads start a navigation that never commits, so the document stays.
|
||||
*/
|
||||
readonly pending: string | undefined
|
||||
/** Between Chromium's did-start-loading and did-stop-loading, subframes included. */
|
||||
readonly busy: boolean
|
||||
}
|
||||
|
||||
export type DocumentState =
|
||||
/** A blank document: never shown, so its load does not count as loading and a new tab shows its new tab page. */
|
||||
| (Document & { readonly status: "blank" })
|
||||
/** A restored tab before its first navigation settles; that navigation consumes the generation it reserved. */
|
||||
| (Document & { readonly status: "restoring" })
|
||||
/**
|
||||
* A real document. Chromium keeps the previous document painted until the next one renders, so a revealed page
|
||||
* stays revealed through later navigations; a page that follows a blank or failed one waits for dom-ready.
|
||||
*/
|
||||
| (Document & { readonly status: "loaded"; readonly revealed: boolean })
|
||||
/** A failed load: Chromium's error page or the proxy's empty 502, which the window replaces with its own. */
|
||||
| (Document & { readonly status: "failed"; readonly message: string })
|
||||
| { readonly status: "closed" }
|
||||
|
||||
export type DocumentEvent =
|
||||
| { readonly type: "loading.started" }
|
||||
| { readonly type: "loading.stopped"; readonly title: string }
|
||||
| {
|
||||
readonly type: "navigation.started"
|
||||
readonly url: string
|
||||
readonly isMainFrame: boolean
|
||||
readonly isSameDocument: boolean
|
||||
}
|
||||
/** Electron's did-navigate: a main-frame document committed. */
|
||||
| {
|
||||
readonly type: "navigation.committed"
|
||||
readonly url: string
|
||||
readonly status: number
|
||||
readonly statusText: string
|
||||
readonly title: string
|
||||
}
|
||||
| {
|
||||
readonly type: "navigation.failed"
|
||||
readonly code: number
|
||||
readonly description: string
|
||||
readonly url: string
|
||||
readonly isMainFrame: boolean
|
||||
}
|
||||
| { readonly type: "navigation.in-page"; readonly url: string; readonly title: string; readonly isMainFrame: boolean }
|
||||
| { readonly type: "document.ready" }
|
||||
| { readonly type: "title.updated"; readonly title: string }
|
||||
| { readonly type: "icon.updated"; readonly favicons: readonly string[] }
|
||||
| { readonly type: "icon.loaded"; readonly attempt: number; readonly icon: string | undefined }
|
||||
| { readonly type: "disposed" }
|
||||
|
||||
export type DocumentEffect =
|
||||
/** A new document replaced the old one: forget its frames, snapshot refs and picked elements, and end the picker. */
|
||||
| { readonly type: "reset-document" }
|
||||
/** A main-frame navigation started: console and network entries restart with it, its own request included. */
|
||||
| { readonly type: "clear-diagnostics" }
|
||||
| { readonly type: "show"; readonly visible: boolean }
|
||||
| { readonly type: "publish" }
|
||||
/** Reports the icon and zoom; Chromium keeps a zoom per origin, so a new document may have its own. */
|
||||
| { readonly type: "detail" }
|
||||
| { readonly type: "load-icon"; readonly attempt: number; readonly favicons: readonly string[] }
|
||||
|
||||
export type DocumentTransition = { readonly state: DocumentState; readonly effects: readonly DocumentEffect[] }
|
||||
|
||||
type Open = Exclude<DocumentState, { status: "closed" }>
|
||||
|
||||
const CLOSED: DocumentState = { status: "closed" }
|
||||
|
||||
const RESET: DocumentEffect = { type: "reset-document" }
|
||||
|
||||
const CLEAR: DocumentEffect = { type: "clear-diagnostics" }
|
||||
|
||||
const PUBLISH: DocumentEffect = { type: "publish" }
|
||||
|
||||
const DETAIL: DocumentEffect = { type: "detail" }
|
||||
|
||||
export function createDocumentState(restore?: { url: string; title: string; generation: number }): DocumentState {
|
||||
const document = {
|
||||
url: "about:blank",
|
||||
title: "",
|
||||
origin: "",
|
||||
icon: undefined,
|
||||
iconAttempt: 0,
|
||||
pending: undefined,
|
||||
busy: false,
|
||||
}
|
||||
|
||||
if (restore)
|
||||
return {
|
||||
...document,
|
||||
status: "restoring",
|
||||
url: restore.url || "about:blank",
|
||||
title: restore.title,
|
||||
generation: restore.generation,
|
||||
}
|
||||
|
||||
return { ...document, status: "blank", generation: 0 }
|
||||
}
|
||||
|
||||
export function transitionDocument(state: DocumentState, event: DocumentEvent): DocumentTransition {
|
||||
if (state.status === "closed") return unchanged(state)
|
||||
|
||||
switch (event.type) {
|
||||
case "disposed":
|
||||
return { state: CLOSED, effects: [] }
|
||||
case "loading.started":
|
||||
return state.busy ? unchanged(state) : settle(state, { ...state, busy: true }, [])
|
||||
case "loading.stopped":
|
||||
return stopped(state, event.title)
|
||||
case "navigation.started":
|
||||
if (!event.isMainFrame || event.isSameDocument) return unchanged(state)
|
||||
|
||||
return settle(state, { ...state, pending: event.url }, [CLEAR, PUBLISH])
|
||||
case "navigation.committed":
|
||||
return committed(state, event)
|
||||
case "navigation.failed":
|
||||
return failed(state, event)
|
||||
case "navigation.in-page":
|
||||
if (!event.isMainFrame) return unchanged(state)
|
||||
|
||||
return settle(
|
||||
state,
|
||||
state.status === "loaded" ? { ...state, url: event.url, title: event.title } : { ...state, title: event.title },
|
||||
[PUBLISH],
|
||||
)
|
||||
case "document.ready":
|
||||
return state.status === "loaded" && !state.revealed
|
||||
? settle(state, { ...state, revealed: true }, [])
|
||||
: unchanged(state)
|
||||
case "title.updated":
|
||||
return event.title === state.title ? unchanged(state) : settle(state, { ...state, title: event.title }, [PUBLISH])
|
||||
case "icon.updated": {
|
||||
const attempt = state.iconAttempt + 1
|
||||
|
||||
return {
|
||||
state: { ...state, iconAttempt: attempt },
|
||||
effects: [{ type: "load-icon", attempt, favicons: event.favicons }],
|
||||
}
|
||||
}
|
||||
|
||||
case "icon.loaded":
|
||||
if (event.attempt !== state.iconAttempt || event.icon === state.icon) return unchanged(state)
|
||||
|
||||
return { state: { ...state, icon: event.icon }, effects: [DETAIL] }
|
||||
}
|
||||
}
|
||||
|
||||
export function isDocumentClosed(state: DocumentState) {
|
||||
return state.status === "closed"
|
||||
}
|
||||
|
||||
export function documentGeneration(state: DocumentState) {
|
||||
return state.status === "closed" ? 0 : state.generation
|
||||
}
|
||||
|
||||
/** Whether the native surface holds a document worth exposing over the themed background. */
|
||||
export function documentVisible(state: DocumentState) {
|
||||
return state.status === "loaded" && state.revealed
|
||||
}
|
||||
|
||||
export function documentIcon(state: DocumentState) {
|
||||
return state.status === "closed" ? undefined : state.icon
|
||||
}
|
||||
|
||||
/** A blank document's load is not shown as loading; a navigation away from it is. */
|
||||
export function isDocumentLoading(state: DocumentState) {
|
||||
if (state.status === "closed" || !state.busy) return false
|
||||
|
||||
if (state.pending !== undefined) return state.pending !== "about:blank"
|
||||
|
||||
return state.status === "loaded"
|
||||
}
|
||||
|
||||
export function documentTab(
|
||||
state: DocumentState,
|
||||
history: { readonly id: Browser.TabID; readonly canGoBack: boolean; readonly canGoForward: boolean },
|
||||
): Browser.Tab {
|
||||
if (state.status === "closed") return { ...history, url: "", title: "", loading: false, generation: 0 }
|
||||
|
||||
const loading = isDocumentLoading(state)
|
||||
|
||||
const tab = {
|
||||
id: history.id,
|
||||
url: state.url.slice(0, 16_384),
|
||||
title: state.title.slice(0, 2_048),
|
||||
loading,
|
||||
canGoBack: history.canGoBack,
|
||||
canGoForward: history.canGoForward,
|
||||
generation: state.generation,
|
||||
}
|
||||
|
||||
// A reload of a failed page shows its progress, and the error again if it stops without a document.
|
||||
return state.status === "failed" && !loading ? { ...tab, loadError: state.message } : tab
|
||||
}
|
||||
|
||||
function committed(state: Open, event: Extract<DocumentEvent, { type: "navigation.committed" }>): DocumentTransition {
|
||||
// Another site's icon arrives with its document; the same site keeps its icon meanwhile, as tabs do. Files and blank
|
||||
// pages have no shared origin, so each keeps none.
|
||||
const origin = destinationOrigin(event.url) ?? event.url
|
||||
const same = origin === state.origin
|
||||
|
||||
const document = {
|
||||
generation: state.status === "restoring" ? state.generation : state.generation + 1,
|
||||
url: event.url,
|
||||
title: same ? state.title : event.title,
|
||||
origin,
|
||||
icon: same ? state.icon : undefined,
|
||||
iconAttempt: same ? state.iconAttempt : state.iconAttempt + 1,
|
||||
pending: undefined,
|
||||
busy: state.busy,
|
||||
}
|
||||
|
||||
const next: Open =
|
||||
event.url === "about:blank"
|
||||
? { ...document, status: "blank" }
|
||||
: // The server-network proxy answers an unreachable HTTP target with an empty 502. Other error statuses are
|
||||
// real documents from the user's server and stay visible.
|
||||
event.status === 502
|
||||
? { ...document, status: "failed", message: `${event.status} ${event.statusText}`.trim().slice(0, 2_048) }
|
||||
: { ...document, status: "loaded", revealed: documentVisible(state) }
|
||||
|
||||
return settle(state, next, [RESET, PUBLISH, DETAIL])
|
||||
}
|
||||
|
||||
function failed(state: Open, event: Extract<DocumentEvent, { type: "navigation.failed" }>): DocumentTransition {
|
||||
// Cancelled navigations and failed subframes do not replace the current page.
|
||||
if (!event.isMainFrame || event.code === -3) return unchanged(state)
|
||||
|
||||
// A failure with a navigation in flight commits an error page in place of the document. One without, after the
|
||||
// document committed, fails that document, which keeps its generation.
|
||||
const replaced = state.pending !== undefined || state.status === "restoring"
|
||||
|
||||
const next: Open = {
|
||||
status: "failed",
|
||||
generation: replaced && state.status !== "restoring" ? state.generation + 1 : state.generation,
|
||||
url: event.url,
|
||||
title: state.title,
|
||||
origin: state.origin,
|
||||
icon: state.icon,
|
||||
iconAttempt: state.iconAttempt,
|
||||
pending: undefined,
|
||||
busy: state.busy,
|
||||
message: event.description.slice(0, 2_048),
|
||||
}
|
||||
|
||||
return settle(state, next, replaced ? [RESET, PUBLISH] : [PUBLISH])
|
||||
}
|
||||
|
||||
function stopped(state: Open, title: string): DocumentTransition {
|
||||
const document = { title, pending: undefined, busy: false }
|
||||
|
||||
// A restore whose navigation never committed, such as a download, leaves the blank document it started on.
|
||||
if (state.status === "restoring")
|
||||
return settle(state, { ...state, ...document, status: "blank", url: "about:blank" }, [PUBLISH])
|
||||
|
||||
return settle(
|
||||
state,
|
||||
state.status === "loaded" ? { ...state, ...document, revealed: true } : { ...state, ...document },
|
||||
[PUBLISH],
|
||||
)
|
||||
}
|
||||
|
||||
/** Adds the effects a change implies: showing or hiding the surface, and publishing a change of loading. */
|
||||
function settle(previous: Open, next: Open, effects: readonly DocumentEffect[]): DocumentTransition {
|
||||
const visible = documentVisible(next)
|
||||
const shown: readonly DocumentEffect[] = visible === documentVisible(previous) ? [] : [{ type: "show", visible }]
|
||||
const publish = isDocumentLoading(next) !== isDocumentLoading(previous) && !effects.includes(PUBLISH)
|
||||
|
||||
return { state: next, effects: [...shown, ...effects, ...(publish ? [PUBLISH] : [])] }
|
||||
}
|
||||
|
||||
function unchanged(state: DocumentState): DocumentTransition {
|
||||
return { state, effects: [] }
|
||||
}
|
||||
Reference in New Issue
Block a user