GeezerVison is showing github.com — fix(browser): show saved tabs at once when the app reopens, and hold them while they load by Hona · Pull Request #65067 · anomalyco/opencode
fix(browser): show saved tabs at once when the app reopens, and hold them while they load
#65067
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement . We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Show file tree
Hide file tree
Changes from all commits
Commits
File filter
Filter by extension
.ts
(14)
.tsx
(2)
All 2 file types selected
Viewed files
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Hide whitespace
Diff view
Hide whitespace
There are no files selected for viewing
Original file line number
Diff line number
Diff line change
@@ -1,3 +1,4 @@
import type { Locator, Page } from "@playwright/test"
import { expect, sourceURL, story } from "../../stories/playwright/story"
import type { Accessor, ParentProps } from "solid-js"
import type { Command, MenuItem } from "@opencode/plugin/gui"
Expand Down
Expand Up
@@ -692,13 +693,13 @@ story("selects side tabs with ⌘1–9 and ⇧⌘[ ] inside the side panel and s
await expect(selected).toHaveText(/^browser:/)
})
story("keeps a restored browser tab selected and undrawn until the desktop's first inventory", async ({ page }) => {
story("keeps a restored browser tab with no saved page selected and undrawn until the desktop's first inventory", async ({ page }) => {
const root = page.getByTestId("browser-region-fixture")
const tabs = root.getByRole("tab")
await expect(root.getByText("Registrations: 1", { exact: true })).toBeVisible()
await expect(tabs).toHaveText(["alpha.ts"])
// Beta was left on its browser tab, which the desktop has not reported yet.
// Beta was left on its browser tab, which the desktop has not reported yet and no earlier run saved a title for .
await root.getByRole("button", { name: "Beta", exact: true }).click()
await expect(root.getByText("Registrations: 2", { exact: true })).toBeVisible()
await expect(root.getByTestId("selected")).toHaveText(/^browser:tab_/)
Expand All
@@ -709,6 +710,170 @@ story("keeps a restored browser tab selected and undrawn until the desktop's fir
await expect(root.getByRole("tab", { name: "Preview", exact: true })).toHaveAttribute("aria-selected", "true")
})
// What main sends for Beta's two tabs, as production builds it: the inventory `pane-machine.ts` publishes and the page
// details `chromium.ts` reports. `electron-restore.test.ts` reads the titles a restored page publishes in real Electron.
type MainTab = {
id: string
url: string
title: string
loading: boolean
canGoBack: boolean
canGoForward: boolean
generation: number
}
// The fixture reads each one through the pane Ipc's own event schema, so a shape main cannot send fails there.
type MainEvent =
| { type: "state"; state: { tabs: MainTab[]; focusedTabID: string } | null; error?: string }
| { type: "page"; tabID: string; zoom: number; viewport: { mode: "auto" }; icon?: string }
| { type: "embed"; tabID: string; embed: string }
const preview = "tab_33333333-3333-3333-3333-333333333333"
const docs = "tab_66666666-6666-6666-6666-666666666666"
// A page's icon, as the data URL main reports.
const icon = (fill: string) =>
`data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Crect width='16' height='16' fill='${fill}'/%3E%3C/svg%3E`
const previewIcon = icon("teal")
const docsIcon = icon("orange")
const reported = (tab: Pick<MainTab, "id" | "url" | "title"> & Partial<MainTab>): MainTab => ({
loading: false,
canGoBack: false,
canGoForward: false,
generation: 0,
...tab,
})
const inventory = (...tabs: MainTab[]): MainEvent => ({ type: "state", state: { tabs, focusedTabID: preview } })
const details = (tabID: string, icon?: string): MainEvent =>
icon
? { type: "page", tabID, zoom: 1, viewport: { mode: "auto" }, icon }
: { type: "page", tabID, zoom: 1, viewport: { mode: "auto" } }
// The tabs as main restores them: saved by id and address, their pages not loaded, so neither reports a title.
const restoredPreview = reported({ id: preview, url: "http://localhost:4173/", title: "", generation: 1 })
const restoredDocs = reported({ id: docs, url: "https://example.com/docs", title: "", generation: 1 })
const send = async (root: Locator, event: MainEvent) => {
await root.getByRole("textbox", { name: "Main event", exact: true }).fill(JSON.stringify(event))
await root.getByRole("button", { name: "Send main event", exact: true }).dispatchEvent("click")
}
// Each strip tab's box, label and icon, as drawn now.
const drawn = (tabs: Locator) =>
tabs.evaluateAll((nodes) =>
nodes.map((node) => {
const box = node.getBoundingClientRect()
return { x: box.x, width: box.width, text: node.textContent, icon: node.querySelector("img")?.getAttribute("src") ?? "none" }
}),
)
// Beta with two loaded browser tabs beside its file tab, then the app quits and opens again.
const reopen = async (page: Page, quit: () => Promise<void> = async () => {}) => {
const root = page.getByTestId("browser-region-fixture")
const tabs = root.getByRole("tab")
await root.getByRole("button", { name: "Beta", exact: true }).click()
await expect(root.getByText("Registrations: 2", { exact: true })).toBeVisible()
await send(root, inventory(reported({ id: preview, url: "http://localhost:4173/", title: "Preview" }), reported({ id: docs, url: "https://example.com/docs", title: "Docs" })))
await send(root, details(preview, previewIcon))
await send(root, details(docs, docsIcon))
await expect(tabs).toHaveText(["beta.ts", "Preview", "Docs"])
await quit()
await root.getByRole("button", { name: "Quit and reopen", exact: true }).dispatchEvent("click")
await page.evaluate(() => document.fonts.ready.then(() => undefined))
await expect(tabs).toHaveText(["beta.ts", "Preview", "Docs"])
await expect(root.getByRole("tab", { name: "Preview", exact: true })).toHaveAttribute("aria-selected", "true")
await expect(root.getByRole("status", { name: "Loading", exact: true })).toBeVisible()
const first = await drawn(tabs)
const nodes = await tabs.elementHandles()
// The same boxes, labels and icons as the first frame after the reopen, in the same elements: nothing moved.
const stable = async () => {
expect(await drawn(tabs)).toEqual(first)
expect(
await page.evaluate(
([before, after]) => before.length === after.length && before.every((node, index) => node === after[index]),
[nodes, await tabs.elementHandles()],
),
).toBe(true)
}
return { root, first, stable }
}
// After a restart the strip showed no browser tab until the desktop had attached, and then each tab changed its label,
// and so its width and the place of every tab after it, as its page loaded: saved title, address, title again.
story("holds every restored tab's box, label and icon from the reopen until its page has loaded", async ({ page }) => {
// The pane's Ipc is still starting when the window draws its first frame.
const { root, first, stable } = await reopen(page, () => page.getByTestId("browser-region-fixture").getByRole("button", { name: "Pane away", exact: true }).click())
const address = root.getByRole("combobox", { name: "Browser address", exact: true })
await expect(root.getByText("Registrations: 2", { exact: true })).toBeVisible()
await root.getByRole("button", { name: "Pane back", exact: true }).click()
await expect(root.getByText("Registrations: 3", { exact: true })).toBeVisible()
await stable()
// Main attached and restored both tabs. Docs is never selected, so its page never loads and it never reports a title.
await send(root, inventory(restoredPreview, restoredDocs))
await expect(address).toHaveValue("http://localhost:4173/")
await expect(root.getByRole("status", { name: "Loading", exact: true })).toHaveCount(0)
await stable()
// The pane shows Preview, so main creates its page, which starts to load.
await send(root, { type: "embed", tabID: preview, embed: "embed-preview" })
await send(root, inventory({ ...restoredPreview, loading: true }, restoredDocs))
await expect(root.getByRole("button", { name: "Stop", exact: true })).toBeVisible()
await stable()
// The document commits where its address redirected to, with no title and no icon yet.
const committed = { ...restoredPreview, url: "http://localhost:4173/app", loading: true }
await send(root, inventory(committed, restoredDocs))
await send(root, details(preview))
await expect(address).toHaveValue("http://localhost:4173/app")
await stable()
// It names itself, its icon arrives, and it stops loading.
await send(root, inventory({ ...committed, title: "Preview" }, restoredDocs))
await stable()
await send(root, details(preview, previewIcon))
await stable()
await send(root, inventory({ ...committed, title: "Preview", loading: false }, restoredDocs))
await expect(root.getByRole("button", { name: "Reload", exact: true })).toBeVisible()
await stable()
// What held all along is the saved icon of each page, not the globe.
expect(first.map((tab) => tab.icon)).toEqual([expect.any(String), previewIcon, docsIcon])
})
// A server without a browser left its restored tabs on a loader with no end.
story("a restored tab on a server without a browser says that the browser could not open, and keeps its box", async ({ page }) => {
const { root, stable } = await reopen(page)
const failed = root.getByRole("alert").filter({ hasText: "The browser couldn't open" })
const loading = root.getByRole("status", { name: "Loading", exact: true })
await expect(root.getByText("Registrations: 3", { exact: true })).toBeVisible()
// Main closes the binding: the session's server has no browser.
await send(root, { type: "state", state: null, error: "browser.pane.unsupported" })
await expect(failed).toBeVisible()
await expect(loading).toHaveCount(0)
await stable()
// Trying again registers once more and waits for it; the tabs stay where they are, and the browser opens.
await failed.getByRole("button", { name: "Try again", exact: true }).click()
await expect(root.getByText("Registrations: 4", { exact: true })).toBeVisible()
await expect(loading).toBeVisible()
await stable()
await send(root, inventory(restoredPreview, restoredDocs))
await expect(root.getByRole("combobox", { name: "Browser address", exact: true })).toHaveValue("http://localhost:4173/")
await stable()
})
// An agent's tabs.open or tabs.focus shows its tab: it comes to the front over the file the person had selected.
story("an agent show request selects its tab over the selected file, and a plugin open wakes the suspended binding", async ({ page }) => {
const root = page.getByTestId("browser-region-fixture")
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -93,6 +93,8 @@ function fixture(
})
const history = { value: { visits: [] }, set: () => undefined }
// The tabs the last run saved for the strip, which the model writes with every inventory: none here.
const tabs = { value: { sessions: [] }, set: () => undefined }
const fake = {
id: "browser",
Expand All
@@ -102,7 +104,7 @@ function fixture(
screen: { current: () => undefined },
links: { open: () => undefined },
layout: { narrow: () => false, stored: () => [], state: () => "closed", open() {}, close() {}, side: { opened: () => false } },
stores: { history },
stores: { history, tabs },
}
// SAFETY: the model reads only these context fields, and these fields of a session and its server.
Expand Down
Original file line number
Diff line number
Diff line change
@@ -0,0 +1,135 @@
import { createServer } from "node:http"
import electron from "electron"
import type { BuiltinMainStorage } from "@opencode/plugin/gui/builtin"
import type { Embeds } from "@opencode/plugin/gui/main"
import type { Browser as BrowserRpc } from "@opencode/plugin-browser/rpc"
import type { TabActivity } from "./policy"
// The Electron main process of `electron-restore.test.ts`, bundled and run by the pinned Electron. It restores two
// tabs as the pane does when it first shows them (`load` in pane.ts): one whose saved title is known and one saved
// before titles were kept. Their page sends its <title> late, as a slow site does. It prints every tab state the pages
// published, in order, as one JSON line.
const head = `<!doctype html><html><head><meta charset="utf-8">`
const rest = `<title>Real title</title></head><body><p>page</p></body></html>`
// The title arrives after the document committed and started to parse.
const server = createServer((request, response) => {
if (request.url === "/favicon.ico") return void response.writeHead(404).end()
response.writeHead(200, { "content-type": "text/html" })
response.write(head + " ".repeat(2048))
setTimeout(() => response.end(rest), 400)
})
void electron.app.whenReady().then(async () => {
const { Browser } = await import("@opencode/plugin-browser/rpc")
const { createBrowserPage } = await import("./chromium")
const { createHandlePath } = await import("./disk")
const { createSitePermissions } = await import("./site-permissions")
const { createSystemMedia } = await import("./system-media")
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve))
const address = server.address()
const origin = `http://127.0.0.1:${address instanceof Object ? address.port : 0}`
const win = new electron.BrowserWindow({ show: false, width: 800, height: 600 })
const verifier = createHandlePath()
const values = new Map<string, unknown>()
// SAFETY: the site permissions read only `store` and its `value` and `set`.
// oxlint-disable-next-line anti-slop/no-chained-type-assertions -- see SAFETY above
const storage = {
store: (key: string, options: { initial: unknown }) => ({
get value() {
return values.has(key) ? values.get(key) : options.initial
},
// oxlint-disable-next-line anti-slop/no-unknown-parameters -- see SAFETY above
set: (next: unknown) => values.set(key, next),
}),
} as unknown as BuiltinMainStorage
const embeds: Embeds = {
create(view, window) {
window.contentView.addChildView(view)
view.setBounds({ x: 0, y: 0, width: 800, height: 600 })
return {
id: "embed",
show: (visible) => view.setVisible(visible),
on: () => () => undefined,
capture: async () => undefined,
dispose: () => window.contentView.removeChildView(view),
}
},
}
const signal = new AbortController().signal
const refs = { next: 0 }
const sites = createSitePermissions(storage, () => undefined)
const system = createSystemMedia()
// Restores one tab as the pane's `load` does, and returns the states its page published until it stopped loading.
const restore = async (id: BrowserRpc.TabID, path: string, title: string) => {
const activity: TabActivity = { agentRuns: 0 }
const states: { title: string; loading: boolean; url: string }[] = []
const url = origin + path
// The pane takes a page's reports only once it holds the page, which is after its construction.
const held: ReturnType<typeof createBrowserPage>[] = []
const page = createBrowserPage(win, {
id,
toolbar: false,
partition: "restore-fixture",
network: null,
restore: { id, url, title, loading: false, canGoBack: false, canGoForward: false, generation: 1 },
publish: () => {
const tab = held[0]?.state()
const last = states.at(-1)
if (!tab) return
if (last?.title !== tab.title || last.loading !== tab.loading || last.url !== tab.url)
states.push({ title: tab.title, loading: tab.loading, url: tab.url })
},
refused: () => undefined,
fail: () => undefined,
popup: () => {
throw new Error("The fixture page opens no window.")
},
activity,
userInput: () => undefined,
local: true,
signal,
shared: { ref: () => `e${++refs.next}` },
menu: { t: (key) => key, extensions: () => [], navigate: async () => undefined, open: async () => undefined, verifier },
embeds,
sites,
system,
})
held.push(page)
await page.ready
await new Promise<void>((resolve) => {
const settled = () => {
if (page.contents.isLoading() || page.contents.getTitle() !== "Real title") return
page.contents.off("did-stop-loading", settled)
page.contents.off("page-title-updated", settled)
resolve()
}
page.contents.on("did-stop-loading", settled)
page.contents.on("page-title-updated", settled)
settled()
})
const last = page.state()
await page.dispose()
return { url, states, last: { title: last.title, loading: last.loading, url: last.url } }
}
const saved = await restore(Browser.TabID.make("tab_11111111-1111-1111-1111-111111111111"), "/saved", "Saved title")
const untitled = await restore(Browser.TabID.make("tab_22222222-2222-2222-2222-222222222222"), "/untitled", "")
process.stdout.write(`${JSON.stringify({ saved, untitled })}\n`)
server.closeAllConnections()
server.close()
electron.app.quit()
})
Original file line number
Diff line number
Diff line change
@@ -0,0 +1,34 @@
import { expect, test } from "bun:test"
import path from "node:path"
import { runElectronFixture } from "./electron-run"
type Restored = {
readonly url: string
readonly states: readonly { readonly title: string; readonly loading: boolean; readonly url: string }[]
readonly last: { readonly title: string; readonly loading: boolean; readonly url: string }
}
// What a restored tab's strip label draws rests on the titles its page publishes while it loads, and those rest on
// Chromium: it names a document after its URL (`127.0.0.1:1234/saved`) from the commit until the <title> parses. This
// restores two tabs in the pinned Electron against a page whose title arrives late, so a restored page that publishes
// Chromium's name again, or an upgrade that changes when the title arrives, fails here.
test(
"a restored tab publishes its saved title, or none, until its document names itself",
async () => {
const result: { saved: Restored; untitled: Restored } = JSON.parse(
await runElectronFixture({ fixture: path.join(import.meta.dir, "electron-restore.fixture.ts") }),
)
// Each title once, in the order the page published them.
const titles = (tab: Restored) => tab.states.map((state) => state.title).filter((title, index, all) => title !== all[index - 1])
expect(titles(result.saved)).toEqual(["Saved title", "Real title"])
expect(result.saved.states[0]).toEqual({ title: "Saved title", loading: true, url: result.saved.url })
expect(result.saved.last).toEqual({ title: "Real title", loading: false, url: result.saved.url })
// A tab saved before titles were kept has none to hold: it publishes none, never Chromium's name.
expect(titles(result.untitled)).toEqual(["", "Real title"])
expect(result.untitled.last).toEqual({ title: "Real title", loading: false, url: result.untitled.url })
},
// Starting Electron takes seconds on a loaded runner.
60_000,
)
Original file line number
Diff line number
Diff line change
Expand Up
@@ -3,6 +3,7 @@ import { Plugin, Store } from "@opencode/plugin/gui"
import { Schema } from "effect"
import { History } from "./history"
import en from "./i18n/en"
import { SavedTabs } from "./saved-tabs"
/**
* The browser's preferences on this device.
Expand All
@@ -24,6 +25,9 @@ export default Plugin.define({
// session and server, kept on this device.
history: Store.global(History, { visits: [] }),
preferences: Store.global(Preferences, { links: true, welcomed: false }),
// Each session's tabs as the desktop last reported them. A global store is loaded before setup, so the side strip
// draws its stored tabs with these titles from its first render.
tabs: Store.global(SavedTabs, { sessions: [] }),
},
i18n: builtinCatalog({
en,
Expand Down
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.