feat(browser): import browsing history and complete the address bar from it (#65073)

This commit is contained in:
Luke Parker 2026-11-20 01:24:18 -06:00 • committed by GitHub
parent 92aa3b32e6
commit bf683129fa
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
53 changed files with 3791 additions and 437 deletions

View file

@ -1364,30 +1364,212 @@ story("keeps the current page and restores its URL when an empty address is subm
await expect(root.getByRole("button", { name: "Reload", exact: true })).toBeEnabled()
})
story("suggests visited pages and opens the first one that completes the typed address", async ({ page }) => {
story("lists the typed text with visited pages, and opens the first row: the page the typing completes, else the text", async ({ page }) => {
const root = page.getByTestId("browser-pane-fixture")
await root.getByRole("button", { name: "Seed history", exact: true }).click()
const address = root.getByRole("combobox", { name: "Browser address", exact: true })
await address.click()
await address.pressSequentially("localhost")
const options = page.getByRole("listbox", { name: "Suggestions" }).getByRole("option")
await expect(options).toHaveCount(1)
// The page whose address begins with the text is first and chosen; the search for the text follows it.
await expect(options).toHaveCount(2)
await expect(options.first()).toHaveAttribute("aria-selected", "true")
// Arrow keys that pick IME candidates leave the suggestions alone.
await expect(address).toHaveValue("localhost:5173/settings")
// Arrow keys that pick IME candidates leave the list alone.
await address.dispatchEvent("keydown", { key: "ArrowDown", isComposing: true })
await expect(options.first()).toHaveAttribute("aria-selected", "true")
await address.press("Enter")
await expect(address).toHaveValue("http://localhost:5173/settings")
// A search query also opens the first match; stepping past the list leaves the typed text, which searches.
// Words that only match a page list it below the search for them, which is first and chosen; a step down opens it.
await address.click()
await address.pressSequentially("color format")
await expect(options).toHaveCount(1)
await expect(options).toHaveCount(2)
await expect(options.first()).toHaveAttribute("aria-selected", "true")
await address.press("ArrowDown")
await expect(options.first()).toHaveAttribute("aria-selected", "false")
await expect(options.first()).toHaveText("color format-Google Search")
await address.press("Enter")
await expect(address).toHaveValue("https://www.google.com/search?q=color%20format")
await address.click()
await address.pressSequentially("color format")
await address.press("ArrowDown")
await expect(options.nth(1)).toHaveAttribute("aria-selected", "true")
await address.press("Enter")
await expect(address).toHaveValue("https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Colors/Color_format_converter")
})
story("finds imported pages by their words, completes the site a host begins, and forgets a page on Shift+Delete", async ({ page }) => {
const root = page.getByTestId("browser-pane-fixture")
await root.getByRole("button", { name: "Seed imported history", exact: true }).click()
await expect(root.getByText("Main history: 59", { exact: true })).toBeVisible()
const address = root.getByRole("combobox", { name: "Browser address", exact: true })
const options = page.getByRole("listbox", { name: "Suggestions" }).getByRole("option")
const addresses = () => options.locator('[data-slot="browser-page-row-url"]')
// Main answers after the field shows the text: under the search for it, the list fills with the best matches of 59
// pages, the most visited first, and a word found only inside another ("prune") last.
await address.click()
await address.pressSequentially("rune")
await expect(addresses()).toHaveText([
"Google Search",
"github.com/anomalyco/rune-desktop",
"github.com/anomalyco/rune-desktop/pulls",
"docs.rune.example/guide/getting-started",
"github.com/anomalyco/rune-desktop/issues/128",
"github.com/runelabs/rune-lang",
])
await expect(options.nth(1).locator("mark")).toHaveText(["rune", "Rune", "rune"])
// The search row is the typed text itself, so it draws no match.
await expect(options.first().locator("mark")).toHaveCount(0)
await expect(options.first()).toHaveAttribute("aria-selected", "true")
// Imported pages have no icon of their own: the globe stands in, and none is fetched.
await expect(options.locator("img")).toHaveCount(0)
// Both words, in either order, wherever each starts a part of the address.
await address.fill("")
await address.pressSequentially("desk anom")
await expect(addresses()).toHaveText([
"Google Search",
"github.com/anomalyco/rune-desktop",
"github.com/anomalyco/rune-desktop/pulls",
"github.com/anomalyco/rune-desktop/issues/128",
])
// Shift+Delete forgets the chosen page, in main's history too; on the typed text's row the key is the field's own.
await address.fill("")
await address.pressSequentially("rune")
await expect(options).toHaveCount(6)
await address.press("Shift+Delete")
await expect(root.getByText("Main history: 59", { exact: true })).toBeVisible()
await address.press("ArrowDown")
await address.press("Shift+Delete")
// The row that takes its place is the chosen one, and the field shows its address.
await expect(addresses().nth(1)).toHaveText("github.com/anomalyco/rune-desktop/pulls")
await expect(options.nth(1)).toHaveAttribute("aria-selected", "true")
await expect(address).toHaveValue("https://github.com/anomalyco/rune-desktop/pulls")
await expect(root.getByText("Main history: 58", { exact: true })).toBeVisible()
// Text that begins a host completes its site, which Enter opens.
await address.fill("")
await address.pressSequentially("gith")
await expect(addresses().first()).toHaveText("github.com/")
await expect(options.first()).toHaveAttribute("aria-selected", "true")
await address.press("Enter")
await expect(address).toHaveValue("https://github.com/")
})
story("keeps the first row chosen and moves through the list with Chrome's keys", async ({ page }) => {
const root = page.getByTestId("browser-pane-fixture")
await root.getByRole("button", { name: "Seed imported history", exact: true }).click()
const address = root.getByRole("combobox", { name: "Browser address", exact: true })
const list = page.getByRole("listbox", { name: "Suggestions" })
const options = list.getByRole("option")
const addresses = options.locator('[data-slot="browser-page-row-url"]')
const selection = () => address.evaluate((input: HTMLInputElement) => input.value.slice(input.selectionStart ?? 0, input.selectionEnd ?? 0))
// The places of the chosen rows: always exactly one while the list is open.
const chosen = () => options.evaluateAll((rows) => rows.flatMap((row, place) => (row.getAttribute("aria-selected") === "true" ? [place] : [])))
// The typed text completes to the site: the rest of its address is in the field, selected, and its row is chosen.
await address.click()
await address.pressSequentially("gith")
await expect(address).toHaveValue("github.com")
await expect.poll(selection).toBe("ub.com")
await expect(addresses.first()).toHaveText("github.com/")
await expect(options.nth(1)).toHaveText("gith-Google Search")
await expect(options).toHaveCount(6)
await expect.poll(chosen).toEqual([0])
// Backspace removes the completed part only; deleting never completes, so the typed text is first and chosen.
await address.press("Backspace")
await expect(address).toHaveValue("gith")
await expect(options.first()).toHaveText("gith-Google Search")
await expect(addresses.nth(1)).toHaveText("github.com/")
await expect.poll(chosen).toEqual([0])
// The next character completes again, and typing goes on through the selected part.
await address.pressSequentially("ub")
await expect(address).toHaveValue("github.com")
await expect.poll(selection).toBe(".com")
// Down and Up choose a row and put its text in the field; past either end the choice goes around.
await address.press("ArrowDown")
await expect(address).toHaveValue("github")
await expect.poll(chosen).toEqual([1])
await address.press("ArrowUp")
await expect(address).toHaveValue("https://github.com")
await address.press("ArrowUp")
await expect.poll(chosen).toEqual([5])
await expect(address).toHaveValue(/^https:\/\/github\.com\/.+/)
// Tab moves as Down does while the list is open, and keeps the focus in the field.
await address.press("Tab")
await expect.poll(chosen).toEqual([0])
await address.press("Tab")
await expect.poll(chosen).toEqual([1])
await expect(address).toBeFocused()
// Escape undoes one thing at a time: the row's text, the list, the typed text, then the focus.
await address.press("Escape")
await expect(address).toHaveValue("github.com")
await expect.poll(selection).toBe(".com")
await expect.poll(chosen).toEqual([0])
await address.press("Escape")
await expect(list).toBeHidden()
await expect(address).toHaveValue("github")
await address.press("Escape")
await expect(address).toHaveValue("https://alpha.example/")
await expect.poll(selection).toBe("https://alpha.example/")
await expect(address).toBeFocused()
await address.press("Escape")
await expect(address).not.toBeFocused()
// A caret that leaves the end takes the completed address into the text: the page stays first, and nothing is selected.
await address.focus()
await address.pressSequentially("gith")
await expect.poll(selection).toBe("ub.com")
await address.press("ArrowRight")
await expect(address).toHaveValue("github.com")
await expect.poll(selection).toBe("")
await expect(addresses.first()).toHaveText("github.com/")
await expect(options.nth(1)).toHaveText("github.com-Google Search")
// A click opens the row it is on, chosen or not.
await options.nth(2).click()
await expect(address).toHaveValue(/^https:\/\/github\.com\/.+/)
await expect(address).not.toBeFocused()
})
story("keeps the address bar working, and says so, while main's history cannot be read or cleared", async ({ page }) => {
const root = page.getByTestId("browser-pane-fixture")
await root.getByRole("button", { name: "Seed history", exact: true }).click()
await root.getByRole("button", { name: "Seed imported history", exact: true }).click()
await root.getByRole("button", { name: "History away", exact: true }).click()
const address = root.getByRole("combobox", { name: "Browser address", exact: true })
const options = page.getByRole("listbox", { name: "Suggestions" }).getByRole("option")
// Main rejects every question. The list still has the typed text and the window's own last pages.
await address.click()
await address.pressSequentially("localhost")
await expect(options).toHaveCount(2)
await expect(address).toHaveValue("localhost:5173/settings")
// The imported pages are out of reach, so their words find only the search for them, which Enter opens.
await address.fill("")
await address.pressSequentially("rune")
await expect(options).toHaveText(["rune-Google Search"])
await address.press("Enter")
await expect(address).toHaveValue("https://www.google.com/search?q=rune")
// Clearing empties the window's list at once and says that main's history stayed.
const clear = async () => {
await root.getByRole("button", { name: "Browser options", exact: true }).click()
await page.getByRole("menuitem", { name: "More tools", exact: true }).click()
await page.getByRole("menuitem", { name: "Clear history", exact: true }).click()
}
await clear()
await expect(root.getByText("Couldn't clear the history. Try again.", { exact: true })).toBeVisible()
await expect(root.getByText("Main history: 59", { exact: true })).toBeVisible()
// The item stays although the window's list is empty: main's history is still there to clear once it is back.
await root.getByRole("button", { name: "History away", exact: true }).click()
await clear()
await expect(root.getByText("Main history: 0", { exact: true })).toBeVisible()
})
story("lists recent pages on a blank tab and opens one", async ({ page }) => {
@ -2086,7 +2268,9 @@ story("asks for a site's sign-in with its realm, says the last one failed, and k
story("the options menu lists everyday actions first and the rest under More tools, where each still runs", async ({ page }) => {
const root = page.getByTestId("browser-pane-fixture")
await root.getByRole("button", { name: "Seed history", exact: true }).click()
await root.getByRole("button", { name: "Seed imported history", exact: true }).click()
await expect(root.getByText(/^Visits: \S/)).toBeVisible()
await expect(root.getByText("Main history: 59", { exact: true })).toBeVisible()
await root.getByRole("button", { name: "Browser options", exact: true }).click()
// Find, the zoom row (out, the zoom itself, in), Copy link and Add page; then More tools; then settings.
await expect(page.getByRole("menu").first().getByRole("menuitem")).toHaveText([
@ -2107,8 +2291,10 @@ story("the options menu lists everyday actions first and the rest under More too
/^Reload without saved files/,
"Clear history",
])
// Clearing forgets the window's last pages and main's history, imported pages included.
await page.getByRole("menuitem", { name: "Clear history", exact: true }).click()
await expect(root.getByText("Visits:", { exact: true })).toBeVisible()
await expect(root.getByText("Main history: 0", { exact: true })).toBeVisible()
// The bar keeps only what every browser has there.
await expect(root.getByRole("button", { name: "Add page to session", exact: true })).toHaveCount(0)
await expect(root.getByRole("button", { name: "Comment on part of the page", exact: true })).toHaveCount(0)

View file

@ -10,7 +10,7 @@ const modules = {
// Any story loads the app styles; the fixture mounts the real Settings > Browser page beside it. `target` is the entry
// a settings search or the command palette is revealing.
async function open(page: Page, options?: { target?: string; extensions?: boolean; installed?: boolean }) {
async function open(page: Page, options?: { target?: string; extensions?: boolean; installed?: boolean; historyKept?: boolean }) {
await page.evaluate(
async (input) => {
const [{ mountBrowserSettings }, { ui }] = await Promise.all([import(input.modules.fixture), import(input.modules.ui)])
@ -20,6 +20,7 @@ async function open(page: Page, options?: { target?: string; extensions?: boolea
target: input.options?.target,
extensions: input.options?.extensions,
installed: input.options?.installed,
historyKept: input.options?.historyKept,
})
},
{ modules, options },
@ -57,6 +58,31 @@ story("a search that lands inside Advanced opens it once, and the person's toggl
await expect(view.advanced).toHaveAttribute("aria-expanded", "false")
})
story("no setting decides what an import brings: the import section has its browsers and no note, and Advanced no switch for it", async ({ page }) => {
const view = await open(page, { target: "settings-browser-remote", extensions: true })
const section = view.root.getByRole("region", { name: "Import from another browser", exact: true })
// The section is its title and one row per browser, whose button opens the import dialog with its two boxes.
await expect(section.getByRole("button", { name: "Import…", exact: true })).toHaveCount(2)
await expect(section.locator("p")).toHaveCount(0)
await expect(view.advanced).toHaveAttribute("aria-expanded", "true")
// Advanced holds two switches, neither of them about importing.
await expect(view.root.getByRole("switch")).toHaveCount(3)
await expect(view.root.getByRole("switch", { name: /history/i })).toHaveCount(0)
await expect(view.stored).not.toContainText("importHistory")
})
story("a sign-out that left the history behind says so in its row, and still forgets the window's last pages", async ({ page }) => {
const view = await open(page, { target: "settings-browser-cookies", historyKept: true })
await expect(view.root.getByTestId("browser-settings-visits")).toHaveText("1")
await view.root.getByRole("button", { name: "Sign out everywhere", exact: true }).click()
// The sign-out itself worked, so the row does not call it failed; "everywhere" alone would be a false claim.
await expect(view.root.getByText("Signed out everywhere. The history could not be cleared.", { exact: true })).toBeVisible()
await expect(view.root.getByTestId("browser-settings-visits")).toHaveText("0")
await expect(view.root.getByRole("button", { name: "Sign out everywhere", exact: true })).toBeEnabled()
})
story("Add an extension aligns controls without top clipping and switches cleanly into a confirmation step", async ({ page }) => {
const view = await open(page, { extensions: true })

View file

@ -11,6 +11,7 @@ type SiteScenario = {
empty?: boolean
site?: { name: string; choose: boolean }
reveal?: boolean
pages?: number
}
const source = (path: string) => sourceURL(new URL(path, import.meta.url))
@ -41,8 +42,11 @@ async function open(page: Page, given: SiteScenario, direction: "ltr" | "rtl" =
list: dialog.getByRole("listbox", { name: "Sites" }),
options: dialog.getByRole("option"),
search: dialog.getByRole("searchbox", { name: "Search sites" }),
// "Import all" until the person changes the choice, then how many sites it brings.
importButton: dialog.getByRole("button", { name: /^Import (all|[\d,]+ sites?)$/ }),
// "Import" until the person changes which sites come, then how many sites it brings.
importButton: dialog.getByRole("button", { name: /^Import( [\d,]+ sites?)?$/ }),
// What comes over: two real checkboxes, ticked until the person unticks one.
signins: dialog.getByRole("checkbox", { name: "Sign-ins", exact: true }),
history: dialog.getByRole("checkbox", { name: "Browsing history", exact: true }),
selectNone: dialog.getByRole("button", { name: "Select none", exact: true }),
// The dialog is modal, so the record beside it is hidden from the accessibility tree.
record: page.getByTestId("site-chooser-imports"),
@ -61,13 +65,18 @@ story("lists 5,000 sites in a window of rows, as one keyboard stop with roving f
await expect(view.options.first()).toHaveAttribute("aria-setsize", "5000")
// Every site comes over until the person changes that.
await expect(view.dialog.getByText("5,000 of 5,000 selected")).toBeVisible()
await expect(
view.dialog.getByText("Copies cookies for all 5,000 sites. The other browser keeps its own."),
).toBeVisible()
expect(await view.options.count()).toBeLessThan(45)
await expect(view.importButton).toHaveText("Import all")
await expect(view.importButton).toHaveText("Import")
// Tab goes from the search, past the profile and the selection's one enabled action, to the list, then out of it.
// The two boxes come before the search in reading order. Tab goes from the search, past the profile and the
// selection's one enabled action, to the list, then out of it.
await expect(view.search).toBeFocused()
await page.keyboard.press("Shift+Tab")
await expect(view.history).toBeFocused()
await page.keyboard.press("Shift+Tab")
await expect(view.signins).toBeFocused()
await page.keyboard.press("Tab")
await page.keyboard.press("Tab")
await expect(view.search).toBeFocused()
await page.keyboard.press("Tab")
await expect(view.dialog.getByRole("button", { name: /Browser profile/ })).toBeFocused()
@ -101,7 +110,7 @@ story("lists 5,000 sites in a window of rows, as one keyboard stop with roving f
// Enter imports what is selected; a clean import closes the dialog.
await page.keyboard.press("Enter")
await expect(view.record.locator("li")).toHaveText([JSON.stringify({ source: "chrome", profile: "Default", sites: ["linear.app", "figma.com"] })])
await expect(view.record.locator("li")).toHaveText([JSON.stringify({ source: "chrome", profile: "Default", sites: ["linear.app", "figma.com"], cookies: true, history: true })])
await expect(view.record).toHaveAttribute("data-closed", "true")
await expect(view.record).toHaveAttribute("data-imported", "1")
})
@ -170,16 +179,19 @@ story("switches profiles back to every site chosen, at the top, and reads a prof
await expect(view.record).toHaveAttribute("data-reads", "Default,Profile 1")
})
story("starts from the site a passkey request came from, and stays open to say why an import left cookies behind", async ({ page }) => {
const view = await open(page, { sites: 5, site: { name: "github.com", choose: true }, partial: true })
story("starts from the site a passkey request came from, brings its sign-in alone, and stays open to say that some stayed behind", async ({ page }) => {
const view = await open(page, { sites: 5, site: { name: "github.com", choose: true }, partial: true, pages: 4210 })
await expect(view.options).toHaveCount(1)
await expect(view.options).toHaveAttribute("data-site", "github.com")
// The site the page belongs to is chosen already.
await expect(view.options).toHaveAttribute("aria-selected", "true")
// This dialog is about one site's sign-in: it offers no boxes, and asks main for no history.
await expect(view.dialog.getByRole("checkbox")).toHaveCount(0)
await view.importButton.click()
await expect(view.record.locator("li")).toHaveText([JSON.stringify({ source: "chrome", profile: "Default", sites: ["github.com"], cookies: true, history: false })])
const status = view.dialog.getByRole("status")
await expect(status).toHaveText("Imported 2 cookies. Not imported: 1.")
await expect(status).toHaveText("Imported from Google Chrome. Some sites will ask you to sign in again.")
await expect(view.record).toHaveAttribute("data-closed", "false")
// Status sits in the dialog body (not crammed into the footer), with top clearance and 0px edge drift.
@ -218,8 +230,8 @@ story("opened for a site, moves on to the browser profile that has exactly it, a
await expect(view.options).toHaveCount(2)
await expect(view.dialog.locator('[data-site="google.com"]')).toHaveAttribute("aria-selected", "true")
await expect(view.dialog.locator('[data-site="google.com.au"]')).toHaveAttribute("aria-selected", "false")
// Counts are grouped for the app's language.
await expect(view.dialog.locator('[data-site="google.com"]')).toContainText("120,000 cookies")
// A row is the site's name and nothing else.
await expect(view.dialog.locator('[data-site="google.com"]')).toHaveText("google.com")
})
story("a page's site that only another site contains chooses nothing, and says no sign-in was found", async ({ page }) => {
@ -300,18 +312,111 @@ story("an empty profile says so", async ({ page }) => {
await expect(view.importButton).toBeDisabled()
})
story("opens on one sentence and Import all, which brings every site without the list", async ({ page }) => {
const view = await open(page, { sites: 5, reveal: false })
// Where the two boxes are in the dialog, in CSS pixels: each box's left edge and label against the title's left edge,
// each 28px row's top from the dialog's top, and how far the first box's focus ring (a 2px outline, 2px off the 16px
// box) stays inside what clips the body.
const boxes = (dialog: ReturnType<Page["getByRole"]>) =>
dialog.evaluate((node) => {
const text = (element: Element | null) => {
const range = document.createRange()
await expect(view.dialog.getByText("Copies cookies for all 5 sites. The other browser keeps its own.")).toBeVisible()
if (element) range.selectNodeContents(element)
return range.getBoundingClientRect()
}
const container = (node.closest('[data-slot="dialog-container"]') ?? node).getBoundingClientRect()
const title = text(node.querySelector('[data-slot="dialog-title"]'))
const clip = node.querySelector('[data-slot="dialog-body"] [data-scrollable]')?.getBoundingClientRect()
const kinds = Array.from(node.querySelectorAll('[data-slot="dialog-body"] [data-slot="checkbox-v2"]:not([aria-hidden])'))
const controls = kinds.map((kind) => kind.querySelector('[data-slot="checkbox-v2-control"]')?.getBoundingClientRect())
const first = controls[0]
const last = controls[controls.length - 1]
return {
left: controls.map((control) => Math.round((control?.left ?? -1) - title.left)),
label: kinds.map((kind) => Math.round(text(kind.querySelector('[data-slot="checkbox-v2-label"]')).left - title.left)),
top: kinds.map((kind) => Math.round((kind.parentElement?.getBoundingClientRect().top ?? -1) - container.top)),
height: kinds.map((kind) => kind.parentElement?.getBoundingClientRect().height),
ring: clip && first && last ? [first.left - 4 - clip.left, first.top - 4 - clip.top, clip.bottom - last.bottom - 4].map((value) => Math.round(value)) : [],
}
})
story("opens on two ticked boxes and Import, which brings everything without the list", async ({ page }) => {
const view = await open(page, { sites: 5, reveal: false, pages: 4210 })
// No sentence: the title, the two boxes and the buttons say it.
await expect(view.signins).toBeChecked()
await expect(view.history).toBeChecked()
await expect(view.dialog.locator('[data-slot="dialog-description"]')).toHaveCount(0)
await expect(view.list).toHaveCount(0)
await expect(view.dialog.getByRole("button", { name: "Choose sites" })).toHaveAttribute("aria-expanded", "false")
await expect(view.importButton).toHaveText("Import")
await page.evaluate(() => document.fonts.ready.then(() => undefined))
const collapsed = await boxes(view.dialog)
// Both boxes start on the title's left edge, in 28px rows, with their focus ring inside the body's clip.
expect(collapsed).toMatchObject({ left: [0, 0], label: [24, 24], height: [28, 28] })
expect(Math.min(...collapsed.ring)).toBeGreaterThanOrEqual(0)
// "Choose sites" opens the list under the boxes, which stay where they are.
await view.dialog.getByRole("button", { name: "Choose sites" }).click()
await expect(view.options).toHaveCount(5)
const expanded = await boxes(view.dialog)
expect(expanded).toMatchObject({ left: [0, 0], label: [24, 24], height: [28, 28], top: collapsed.top })
expect(Math.min(...expanded.ring)).toBeGreaterThanOrEqual(0)
await view.dialog.getByRole("button", { name: "Choose sites" }).click()
await expect(view.list).toHaveCount(0)
await view.importButton.click()
// No list of sites: main imports the whole profile.
await expect(view.record.locator("li")).toHaveText([JSON.stringify({ source: "chrome", profile: "Default" })])
// No list of sites: main imports the whole profile, its sign-ins and its history.
await expect(view.record.locator("li")).toHaveText([JSON.stringify({ source: "chrome", profile: "Default", cookies: true, history: true })])
await expect(view.record).toHaveAttribute("data-closed", "true")
})
story("a box the person unticks stays behind, Import needs one of them, and Enter on a box imports", async ({ page }) => {
const view = await open(page, { sites: 5, reveal: false, pages: 4210 })
// The dialog opens with the focus on itself. Tab reaches the boxes in reading order, after Close; Space toggles the
// one that has the focus.
await expect(view.dialog.locator('[data-slot="dialog-content"]').or(view.dialog)).toBeFocused()
await page.keyboard.press("Tab")
await expect(view.dialog.getByRole("button", { name: "Close", exact: true })).toBeFocused()
await page.keyboard.press("Tab")
await expect(view.signins).toBeFocused()
await page.keyboard.press("Space")
await expect(view.signins).not.toBeChecked()
await page.keyboard.press("Tab")
await expect(view.history).toBeFocused()
await page.keyboard.press("Space")
await expect(view.history).not.toBeChecked()
// Nothing is ticked: there is nothing to import, by the button or by Enter.
await expect(view.importButton).toBeDisabled()
await page.keyboard.press("Enter")
await expect(view.record.locator("li")).toHaveCount(0)
// History alone: no cookie is asked for.
await page.keyboard.press("Space")
await expect(view.importButton).toBeEnabled()
await page.keyboard.press("Enter")
await expect(view.record.locator("li")).toHaveText([JSON.stringify({ source: "chrome", profile: "Default", cookies: false, history: true })])
await expect(view.record).toHaveAttribute("data-closed", "true")
})
story("with Browsing history unticked the import brings sign-ins alone, of the chosen sites", async ({ page }) => {
const view = await open(page, { sites: 5 })
// A click on the label unticks its box.
await view.dialog.getByText("Browsing history", { exact: true }).click()
await expect(view.history).not.toBeChecked()
await view.dialog.locator('[data-site="github.com"]').click()
await expect(view.importButton).toHaveText("Import 4 sites")
await view.importButton.click()
const sent = JSON.parse((await view.record.locator("li").textContent()) ?? "{}")
expect(sent).toMatchObject({ cookies: true, history: false })
expect(sent.sites).toHaveLength(4)
})
story("empty fallback uses a compact fit dialog when no browsers are found", async ({ page }) => {
await page.evaluate(
async (input) => {
@ -322,7 +427,7 @@ story("empty fallback uses a compact fit dialog when no browsers are found", asy
{ modules },
)
const dialog = page.getByRole("dialog", { name: "Import sign-ins" })
const dialog = page.getByRole("dialog", { name: "Import from another browser" })
await expect(dialog.getByText("No other browser found on this computer")).toBeVisible()
const box = await page.locator('[data-slot="dialog-container"]').boundingBox()
expect(box && box.width <= 480 && box.height < 250).toBe(true)
@ -336,12 +441,12 @@ story("Choose sites shows the list in place, every site ticked, and the button t
await expect(choose).toHaveAttribute("aria-expanded", "true")
await expect(view.options).toHaveCount(5)
await expect(view.dialog.getByText("5 of 5 selected")).toBeVisible()
await expect(view.importButton).toHaveText("Import all")
await expect(view.importButton).toHaveText("Import")
await view.dialog.locator('[data-site="github.com"]').click()
await expect(view.importButton).toHaveText("Import 4 sites")
// Ticking it again is everything again.
await view.dialog.locator('[data-site="github.com"]').click()
await expect(view.importButton).toHaveText("Import all")
await expect(view.importButton).toHaveText("Import")
await view.dialog.locator('[data-site="github.com"]').click()
await view.importButton.click()
const sent = JSON.parse((await view.record.locator("li").textContent()) ?? "{}")
@ -366,27 +471,81 @@ story("keeps site names left to right in a right-to-left layout, the box at the
const row = view.dialog.locator('[data-site="xn--mnchen-3ya.de"]')
const box = await row.locator('[data-slot="checkbox-v2-control"]').boundingBox()
const name = await row.locator("bdi").first().boundingBox()
const count = await row.getByText("5 cookies").boundingBox()
expect(box && name && count && box.x > name.x && name.x > count.x).toBe(true)
expect(box && name && box.x > name.x).toBe(true)
const long = view.dialog.locator('[data-site$="example.co.uk"]').first().locator("span[title]")
expect(await long.evaluate((element) => [getComputedStyle(element).direction, element.scrollWidth > element.clientWidth])).toEqual(["rtl", true])
})
// The pane's offer, as a bar over a page or a card on the new tab page, with what the faked profile answers an import.
async function offer(page: Page, scenario: SiteScenario, card = false) {
await page.evaluate(
async (input) => {
const [{ mountSiteChooser }, { ui }] = await Promise.all([import(input.modules.fixture), import(input.modules.ui)])
mountSiteChooser({ ui, scenario: input.scenario, offer: true, card: input.card })
},
{ modules, scenario, card },
)
return {
importing: page.getByRole("button", { name: "Import", exact: true }),
confirmation: page.getByRole("status").filter({ hasText: /^Imported/ }),
record: page.getByTestId("site-chooser-imports"),
}
}
story("the sign-in bar names the browser, imports sign-ins and history in one click, and says in words what came", async ({ page }) => {
const bar = await offer(page, { sites: 5, pages: 4210 })
await expect(page.getByText("Bring your sign-ins and history from Google Chrome · Work", { exact: true })).toBeVisible()
await bar.importing.click()
// No dialog and no boxes here: the one click brings both.
await expect(bar.record.locator("li")).toHaveText([JSON.stringify({ source: "chrome", profile: "Default", cookies: true, history: true })])
await expect(bar.confirmation).toHaveText("Imported sign-ins and history from Google Chrome")
await expect(bar.record).toHaveAttribute("data-imported", "1")
})
story("the sign-in bar says that some sites will ask again when sign-ins stayed behind", async ({ page }) => {
const bar = await offer(page, { sites: 5, pages: 4210, protected: 3 })
await bar.importing.click()
await expect(bar.confirmation).toHaveText("Imported from Google Chrome. Some sites will ask you to sign in again.")
})
story("the bar's own dialog brings history alone when Sign-ins is unticked, and the bar says so without loading the page again", async ({ page }) => {
const bar = await offer(page, { sites: 5, pages: 4210 })
await page.getByRole("button", { name: "Import from another browser", exact: true }).click()
await page.getByRole("menuitem", { name: "Choose sites to import", exact: true }).click()
const dialog = page.getByRole("dialog", { name: /^Import from Google Chrome/ })
await dialog.getByText("Sign-ins", { exact: true }).click()
await expect(dialog.getByRole("checkbox", { name: "Sign-ins", exact: true })).not.toBeChecked()
await dialog.getByRole("button", { name: "Import", exact: true }).click()
await expect(bar.record.locator("li")).toHaveText([JSON.stringify({ source: "chrome", profile: "Default", cookies: false, history: true })])
await expect(dialog).toHaveCount(0)
await expect(bar.confirmation).toHaveText("Imported history from Google Chrome")
// No sign-in came, so the page has nothing new to load with.
await expect(bar.record).toHaveAttribute("data-imported", "0")
})
story("the offer card has a title and no paragraph, and its Import brings both", async ({ page }) => {
const card = await offer(page, { sites: 5, pages: 4210 }, true)
const region = page.getByRole("region", { name: "Bring your sign-ins and history", exact: true })
await expect(region.getByText("Bring your sign-ins and history", { exact: true })).toBeVisible()
await expect(region.getByText(/Copy your sign-ins/)).toHaveCount(0)
await region.getByRole("button", { name: "Import", exact: true }).first().click()
await expect(card.record.locator("li")).toHaveText([JSON.stringify({ source: "chrome", profile: "Default", cookies: true, history: true })])
await expect(card.confirmation).toHaveText("Imported sign-ins and history from Google Chrome")
})
// The pane's sign-in bar says what an import brought for a few seconds, then goes by itself; Close ends it sooner.
story("the sign-in bar's import confirmation goes by itself after 5 seconds, and Close ends it sooner", async ({ page }) => {
await page.clock.install()
await page.evaluate(
async (input) => {
const [{ mountSiteChooser }, { ui }] = await Promise.all([import(input.modules.fixture), import(input.modules.ui)])
mountSiteChooser({ ui, scenario: { sites: 5, skipped: 318 }, offer: true })
},
{ modules },
)
const record = page.getByTestId("site-chooser-imports")
const confirmation = page.getByRole("status").filter({ hasText: "Imported 10 cookies from Google Chrome" })
const importing = page.getByRole("button", { name: /^Import from Google Chrome/ })
// No history in this profile: the line names the sign-ins alone.
const { record, confirmation, importing } = await offer(page, { sites: 5, skipped: 318 })
await expect(confirmation).toHaveCount(0)
// Close ends it at once, and only once: the timer it no longer needs does not report a second close.
await importing.click()

View file

@ -3,6 +3,7 @@ import { createRoot, createSignal } from "solid-js"
import type { IpcClient, SessionRef, SetupContext } from "@opencode/plugin/gui"
import { liveAccessor } from "@opencode/plugin/gui/host"
import { Browser } from "../../plugin-browser/src/rpc"
import { BrowserHistory } from "../../gui-plugins/src/browser/history/ipc"
import type definition from "../../gui-plugins/src/browser/index"
import type { BrowserPane, PaneEvent } from "../../gui-plugins/src/browser/ipc"
import { createModel } from "../../gui-plugins/src/browser/model"
@ -93,13 +94,15 @@ function fixture(
})
const history = { value: { visits: [] }, set: () => undefined }
// Main's history of every page is away, as on the web: these cases are about the pane.
const away = liveAccessor(() => ({ status: "inactive" }))
// 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",
t: (key: string, params?: Record<string, string>) => (params ? `${key} ${JSON.stringify(params)}` : key),
use: () => live,
use: (token: { readonly id: string }) => (token.id === BrowserHistory.id ? away : live),
sessions: { current, list: () => refs },
screen: { current: () => undefined },
links: { open: () => undefined },

View file

@ -1,17 +1,23 @@
import { describe, expect, test } from "bun:test"
import { Browser } from "@opencode/plugin-browser/rpc"
import {
addressSuggestions,
addressRows,
addressView,
initialAddressState,
nextAddressEpoch,
transitionAddress,
type AddressEffect,
type AddressEpoch,
type AddressEvent,
type AddressPage,
type AddressRow,
type AddressState,
} from "./address-machine"
import type { Visit } from "./history"
import type { HistoryPage } from "./history/ipc"
import { pageKey, type PageVisit } from "./history/page"
import { createPageIndex, findPages } from "./history/search"
import { HISTORY_ANSWER } from "./history/suggest"
import type { Visit } from "./history/visits"
const tabID = Browser.TabID.make("tab_11111111-1111-1111-1111-111111111111")
@ -25,7 +31,12 @@ const replay = (events: readonly AddressEvent[], state: AddressState = initialAd
events.reduce((current, event) => transitionAddress(current, event).state, state)
const view = (state: AddressState, epoch: AddressEpoch, visits: readonly Visit[] = []) =>
addressView(state, epoch, addressSuggestions(state, visits))
addressView(state, epoch, addressRows(state, visits))
// A row as the tables name it: a page by its address, the typed text by what it does.
const label = (row: AddressRow) => (row.type === "page" ? row.url.replace("https://", "") : `${row.type}: ${row.text}`)
const labels = (state: AddressState, visits: readonly Visit[] = []) => addressRows(state, visits).map(label)
const visits: readonly Visit[] = [
{ url: "https://example.com/", title: "Example" },
@ -48,7 +59,8 @@ describe("a submitted address the browser has not reported yet", () => {
])
const focused = transitionAddress(submitted.state, { type: "focused", epoch })
expect(focused.effects).toEqual([{ type: "select-input" }])
// Focusing also has main read its history, ahead of the first question.
expect(focused.effects).toEqual([{ type: "select-input" }, { type: "prepare" }])
expect(view(focused.state, epoch).field).toBe("https://example.com/")
const left = transitionAddress(focused.state, { type: "blurred", epoch })
@ -69,7 +81,7 @@ describe("a submitted address the browser has not reported yet", () => {
const focused = transitionAddress(submitted, { type: "focused", epoch: moved }).state
expect(view(focused, moved).field).toBe("https://other.example/")
expect(transitionAddress(focused, { type: "blurred", epoch: moved }).state).toEqual({ status: "rest" })
expect(transitionAddress(focused, { type: "blurred", epoch: moved }).state).toMatchObject({ status: "rest" })
})
})
@ -104,7 +116,7 @@ describe("submitting the field", () => {
const editing = replay([
{ type: "focused", epoch },
{ type: "input.changed", value: " ", deleting: false, visits: [] },
{ type: "input.changed", value: " ", completing: true, visits: [] },
])
expect(transitionAddress(editing, { type: "submitted", epoch, visits: [], failed: false }).effects).toEqual([
@ -117,7 +129,7 @@ describe("submitting the field", () => {
const editing = replay([
{ type: "focused", epoch },
{ type: "input.changed", value: "", deleting: true, visits: [] },
{ type: "input.changed", value: "", completing: false, visits: [] },
])
const submitted = transitionAddress(editing, { type: "submitted", epoch, visits: [], failed: true })
@ -126,15 +138,17 @@ describe("submitting the field", () => {
expect(view(submitted.state, epoch).field).toBe("")
})
test("Enter opens the completed suggestion", () => {
test("Enter opens the page whose address the typing completes", () => {
const epoch = reports(blank)
const editing = replay([
{ type: "focused", epoch },
{ type: "input.changed", value: "exa", deleting: false, visits },
{ type: "input.changed", value: "exa", completing: true, visits },
])
expect(view(editing, epoch, visits)).toMatchObject({ listed: true, active: 0, chosen: visits[0] })
// The field shows the rest of the address after the typed text, and the page is the first row.
expect(view(editing, epoch, visits)).toMatchObject({ listed: true, active: 0, field: "example.com", completion: "mple.com" })
expect(labels(editing, visits)).toEqual(["example.com/", "search: exa", "example.org/"])
expect(transitionAddress(editing, { type: "submitted", epoch, visits, failed: false }).effects[0]).toEqual({
type: "navigate",
@ -154,65 +168,416 @@ describe("submitting the field", () => {
describe("editing", () => {
const epoch = reports(blank)
const typed = (value: string, deleting = false) =>
const typed = (value: string, completing = true) =>
replay([
{ type: "focused", epoch },
{ type: "input.changed", value, deleting, visits },
{ type: "input.changed", value, completing, visits },
])
test("deleting never completes a suggestion", () => {
expect(view(typed("exa", true), epoch, visits)).toMatchObject({ listed: true, active: -1, chosen: undefined })
const press = (state: AddressState, key: "ArrowDown" | "ArrowUp" | "Tab" | "Shift+Tab" | "Escape", at = epoch) =>
transitionAddress(state, { type: "key.pressed", key, epoch: at, visits })
const keys = (state: AddressState, ...pressed: ("ArrowDown" | "ArrowUp" | "Tab" | "Shift+Tab")[]) =>
pressed.reduce((current, key) => press(current, key).state, state)
test("deleting never completes: the typed text is the first row, and Enter opens it", () => {
const deleted = typed("exa", false)
expect(view(deleted, epoch, visits)).toMatchObject({ listed: true, active: 0, field: "exa", completion: "" })
expect(labels(deleted, visits)).toEqual(["search: exa", "example.com/", "example.org/"])
expect(transitionAddress(deleted, { type: "submitted", epoch, visits, failed: false }).effects[0]).toMatchObject({
url: "https://www.google.com/search?q=exa",
})
})
test("arrows cycle through the suggestions and the typed text", () => {
const keys = (state: AddressState, ...pressed: ("ArrowDown" | "ArrowUp")[]) =>
pressed.reduce((current, key) => transitionAddress(current, { type: "key.pressed", key, visits }).state, state)
test("arrows and Tab move through the rows, around either end, and the field shows each row's text", () => {
const start = typed("exa", false)
const start = typed("exa", true)
expect(view(keys(start, "ArrowDown"), epoch, visits).active).toBe(0)
expect(view(keys(start, "ArrowDown", "ArrowDown"), epoch, visits).active).toBe(1)
expect(view(keys(start, "ArrowDown", "ArrowDown", "ArrowDown"), epoch, visits).active).toBe(-1)
expect(view(keys(start, "ArrowUp"), epoch, visits).active).toBe(1)
expect(transitionAddress(start, { type: "key.pressed", key: "ArrowDown", visits }).effects).toEqual([
{ type: "prevent-default" },
])
expect(view(keys(start, "ArrowDown"), epoch, visits)).toMatchObject({ active: 1, field: "https://example.com" })
expect(view(keys(start, "ArrowDown", "Tab"), epoch, visits)).toMatchObject({ active: 2, field: "https://example.org" })
expect(view(keys(start, "ArrowDown", "ArrowDown", "ArrowDown"), epoch, visits)).toMatchObject({ active: 0, field: "exa" })
expect(view(keys(start, "ArrowUp"), epoch, visits)).toMatchObject({ active: 2, field: "https://example.org" })
expect(view(keys(start, "Shift+Tab", "Shift+Tab"), epoch, visits)).toMatchObject({ active: 1 })
expect(press(start, "ArrowDown").effects).toEqual([{ type: "prevent-default" }])
})
test("arrows without suggestions leave the key to the input", () => {
test("without a list an arrow in an empty field and Tab are the input's own keys", () => {
const focused = replay([{ type: "focused", epoch }])
expect(transitionAddress(focused, { type: "key.pressed", key: "ArrowDown", visits }).effects).toEqual([])
expect(press(focused, "ArrowDown").effects).toEqual([])
expect(press(focused, "Tab").state).toBe(focused)
expect(press(press(typed("exa"), "Escape").state, "Tab").effects).toEqual([])
})
test("Escape closes the suggestions first, then leaves the field", () => {
const dismissed = transitionAddress(typed("exa"), { type: "key.pressed", key: "Escape", visits })
expect(view(dismissed.state, epoch, visits)).toMatchObject({ listed: false, active: -1 })
expect(dismissed.effects).toEqual([{ type: "prevent-default" }])
test("an arrow opens the list for the address in the field, and chooses its first row", () => {
const page = reports({ ...blank, url: "https://example.org/" })
const opened = press(replay([{ type: "focused", epoch: page }]), "ArrowDown", page)
expect(transitionAddress(dismissed.state, { type: "key.pressed", key: "Escape", visits }).effects).toEqual([
{ type: "prevent-default" },
{ type: "blur-input" },
expect(opened.effects).toEqual([{ type: "prevent-default" }, { type: "ask", attempt: 2, query: "https://example.org/" }])
// The address is a page of the list, so that page is the first row: nothing was typed for an address to complete.
expect(view(opened.state, page, visits)).toMatchObject({ listed: true, active: 0, field: "https://example.org/", completion: "" })
expect(labels(opened.state, visits)).toEqual(["example.org/", "search: https://example.org/"])
})
test("Escape undoes one thing at a time: the row's text, the list, the typed text, then the focus", () => {
const page = reports({ ...blank, url: "https://alpha.example/" })
const stepped = replay([
{ type: "focused", epoch: page },
{ type: "input.changed", value: "exa", completing: true, visits },
{ type: "key.pressed", key: "ArrowDown", epoch: page, visits },
])
expect(view(stepped, page, visits)).toMatchObject({ active: 1, field: "exa" })
const reverted = press(stepped, "Escape", page)
// The typed text is back with the address it completes, selected again, and the list stays open.
expect(view(reverted.state, page, visits)).toMatchObject({ listed: true, active: 0, field: "example.com", completion: "mple.com" })
expect(reverted.effects).toEqual([{ type: "prevent-default" }, { type: "select-completion", start: 3 }])
const closed = press(reverted.state, "Escape", page)
// The list closes and the completed part goes with it; Enter then opens the typed text.
expect(view(closed.state, page, visits)).toMatchObject({ listed: false, active: -1, field: "exa", typed: true })
expect(closed.effects).toEqual([{ type: "prevent-default" }])
expect(transitionAddress(closed.state, { type: "submitted", epoch: page, visits, failed: false }).effects[0]).toMatchObject({
url: "https://www.google.com/search?q=exa",
})
const restored = press(closed.state, "Escape", page)
expect(view(restored.state, page, visits)).toMatchObject({ editing: true, typed: false, field: "https://alpha.example/" })
expect(restored.effects).toEqual([{ type: "prevent-default" }, { type: "select-input" }])
expect(press(restored.state, "Escape", page).effects).toEqual([{ type: "prevent-default" }, { type: "blur-input" }])
})
test("an arrow opens a list Escape closed, without moving", () => {
const closed = press(typed("exa"), "Escape").state
const opened = press(closed, "ArrowDown")
expect(view(opened.state, epoch, visits)).toMatchObject({ listed: true, active: 0, field: "example.com" })
expect(opened.effects).toEqual([
{ type: "prevent-default" },
{ type: "ask", attempt: 3, query: "exa" },
{ type: "select-completion", start: 3 },
])
})
test("a caret that leaves the end takes the completed address into the text", () => {
// The pane reports the field's whole text when the selection is no longer the completed part.
const accepted = transitionAddress(typed("exa"), { type: "input.changed", value: "example.com", completing: false, visits })
expect(view(accepted.state, epoch, visits)).toMatchObject({ field: "example.com", completion: "", active: 0 })
// The text is now the page's whole address, so the page stays the first row.
expect(labels(accepted.state, visits)).toEqual(["example.com/", "search: example.com"])
})
test("input and keys outside an edit change nothing", () => {
const submitted = replay([{ type: "navigated", url: "https://example.com/", epoch }])
for (const state of [initialAddressState, submitted]) {
expect(transitionAddress(state, { type: "input.changed", value: "x", deleting: false, visits }).state).toBe(state)
expect(transitionAddress(state, { type: "key.pressed", key: "Escape", visits }).state).toBe(state)
expect(transitionAddress(state, { type: "input.changed", value: "x", completing: true, visits }).state).toBe(state)
expect(press(state, "Escape").state).toBe(state)
}
})
test("leaving the field drops what the edit typed", () => {
const left = transitionAddress(typed("exa"), { type: "blurred", epoch }).state
expect(left).toEqual({ status: "rest" })
expect(left).toMatchObject({ status: "rest" })
expect(view(left, epoch, visits)).toMatchObject({ field: "", typed: false, listed: false, query: "" })
})
})
describe("main's history answers after the field shows what was typed", () => {
const epoch = reports(blank)
const rune: HistoryPage = { url: "https://github.com/anomalyco/rune-desktop", title: "anomalyco/rune-desktop", score: 5 }
const github: HistoryPage = { url: "https://github.com/", title: "GitHub", score: 17 }
const gitlab: HistoryPage = { url: "https://gitlab.com/", title: "GitLab", score: 2 }
const focused = replay([{ type: "focused", epoch }])
const type = (state: AddressState, value: string, completing = true) =>
transitionAddress(state, { type: "input.changed", value, completing, visits: [] })
const answer = (state: AddressState, attempt: number, pages: readonly HistoryPage[], local: readonly Visit[] = []) =>
transitionAddress(state, { type: "answered", attempt, pages, visits: local })
const asked = (effects: readonly AddressEffect[]) => effects.flatMap((effect) => (effect.type === "ask" ? [effect] : []))
const enter = (state: AddressState, local: readonly Visit[] = []) =>
transitionAddress(state, { type: "submitted", epoch, visits: local, failed: false }).effects[0]
test("each change of the text asks main, without waiting: the field has the text and its own row at once", () => {
const typed = type(focused, "gith")
const [question] = asked(typed.effects)
expect(question).toMatchObject({ type: "ask", query: "gith" })
expect(view(typed.state, epoch)).toMatchObject({ field: "gith", listed: true, active: 0 })
expect(labels(typed.state)).toEqual(["search: gith"])
// Text with nothing to search for asks nothing and lists nothing.
expect(type(focused, " ").effects).toEqual([])
expect(view(type(focused, " ").state, epoch).listed).toBe(false)
expect(type(focused, "https://").effects).toHaveLength(1)
})
test("the answer to the last question joins the list and completes the address it begins", () => {
const typed = type(focused, "gith")
const answered = answer(typed.state, asked(typed.effects)[0]?.attempt ?? -1, [github, rune])
expect(answered.effects).toEqual([{ type: "select-completion", start: 4 }])
expect(view(answered.state, epoch)).toMatchObject({ listed: true, active: 0, field: "github.com", completion: "ub.com" })
expect(labels(answered.state)).toEqual(["github.com/", "search: gith", "github.com/anomalyco/rune-desktop"])
expect(enter(answered.state)).toEqual({ type: "navigate", tabID, url: "https://github.com/" })
})
test("a page that matches without beginning with the text is listed below it and is never the first row", () => {
const typed = type(focused, "rune")
const answered = answer(typed.state, asked(typed.effects)[0]?.attempt ?? -1, [rune])
expect(answered.effects).toEqual([])
expect(view(answered.state, epoch)).toMatchObject({ listed: true, active: 0, field: "rune", completion: "" })
expect(labels(answered.state)).toEqual(["search: rune", "github.com/anomalyco/rune-desktop"])
expect(enter(answered.state)).toEqual({ type: "navigate", tabID, url: "https://www.google.com/search?q=rune" })
// One step down chooses it.
const stepped = transitionAddress(answered.state, { type: "key.pressed", key: "ArrowDown", epoch, visits: [] }).state
expect(enter(stepped)).toMatchObject({ url: rune.url })
})
test("an answer to an earlier text never replaces the answer to a later one", () => {
const first = type(focused, "git")
const second = type(first.state, "gith")
const early = asked(first.effects)[0]?.attempt ?? -1
const late = asked(second.effects)[0]?.attempt ?? -1
expect(late).not.toBe(early)
// The earlier answer arrives after the later question: ignored, as the same state object.
expect(answer(second.state, early, [gitlab]).state).toBe(second.state)
const answered = answer(second.state, late, [github]).state
// And it is ignored when it arrives last, too.
expect(answer(answered, early, [gitlab]).state).toBe(answered)
expect(view(answered, epoch).chosen).toMatchObject({ url: "https://github.com/" })
})
test("an answer that arrives after the edit ended, or in the next edit, is dropped", () => {
const typed = type(focused, "gith")
const attempt = asked(typed.effects)[0]?.attempt ?? -1
const left = transitionAddress(typed.state, { type: "blurred", epoch }).state
expect(answer(left, attempt, [github]).state).toBe(left)
const again = transitionAddress(left, { type: "focused", epoch }).state
expect(answer(again, attempt, [github]).state).toBe(again)
const submitted = transitionAddress(typed.state, { type: "submitted", epoch, visits: [], failed: false }).state
expect(answer(submitted, attempt, [github]).state).toBe(submitted)
})
test("the last answer stays while the next question is out, narrowed to the new text", () => {
const typed = type(focused, "git")
const answered = answer(typed.state, asked(typed.effects)[0]?.attempt ?? -1, [github, gitlab, rune]).state
const more = type(answered, "gith")
// GitLab no longer matches; the others show before main answers "gith", and GitHub's address is completed.
expect(labels(more.state)).toEqual(["github.com/", "search: gith", "github.com/anomalyco/rune-desktop"])
expect(more.effects).toContainEqual({ type: "select-completion", start: 4 })
// Emptying the field drops it: no text has that answer.
expect(labels(type(more.state, "", false).state)).toEqual([])
})
test("deleting never completes, even once the answer comes", () => {
const typed = type(focused, "gith", false)
const answered = answer(typed.state, asked(typed.effects)[0]?.attempt ?? -1, [github])
expect(answered.effects).toEqual([])
expect(view(answered.state, epoch)).toMatchObject({ listed: true, active: 0, field: "gith", chosen: { type: "search" } })
expect(labels(answered.state)).toEqual(["search: gith", "github.com/"])
})
test("a page whose whole address was typed is the first row, deleting or not", () => {
const typed = type(focused, "github.com", false)
const answered = answer(typed.state, asked(typed.effects)[0]?.attempt ?? -1, [github, rune]).state
expect(labels(answered)).toEqual(["github.com/", "search: github.com", "github.com/anomalyco/rune-desktop"])
expect(view(answered, epoch)).toMatchObject({ active: 0, field: "github.com", completion: "" })
})
test("rows the person moved through stay as they were when the answer comes", () => {
const local: Visit[] = [{ url: "https://github.com/sst/opentui", title: "sst/opentui" }]
const typed = transitionAddress(focused, { type: "input.changed", value: "gith", completing: true, visits: local })
// The window's page completes the text; one step down is the search for it.
const stepped = transitionAddress(typed.state, { type: "key.pressed", key: "ArrowDown", epoch, visits: local }).state
expect(view(stepped, epoch, local)).toMatchObject({ active: 1, field: "gith", chosen: { type: "search" } })
// Chrome ends its search at the first step: the answer changes nothing, as the same state object.
expect(answer(stepped, asked(typed.effects)[0]?.attempt ?? -1, [github, rune], local).state).toBe(stepped)
expect(labels(stepped, local)).toEqual(["github.com/sst/opentui", "search: gith"])
// Typing follows the list again, and asks anew.
const more = transitionAddress(stepped, { type: "input.changed", value: "githu", completing: true, visits: local })
expect(asked(more.effects)).toHaveLength(1)
expect(view(more.state, epoch, local)).toMatchObject({ active: 0, field: "github.com/sst/opentui" })
})
test("a question main could not answer leaves what the window knows", () => {
const local: Visit[] = [{ url: "https://github.com/sst/opentui", title: "sst/opentui" }]
const typed = transitionAddress(focused, { type: "input.changed", value: "gith", completing: true, visits: local })
const answered = answer(typed.state, asked(typed.effects)[0]?.attempt ?? -1, [], local).state
expect(view(answered, epoch, local)).toMatchObject({ listed: true, active: 0, chosen: { url: local[0]?.url } })
})
test("Shift+Delete forgets the chosen page at once, and is the field's own key on the typed text's row", () => {
const typed = type(focused, "gith")
const answered = answer(typed.state, asked(typed.effects)[0]?.attempt ?? -1, [github, rune]).state
const forgotten = transitionAddress(answered, { type: "forget.pressed", visits: [] })
expect(forgotten.effects).toEqual([{ type: "prevent-default" }, { type: "forget", url: "https://github.com/" }])
// The next page's address begins with the text too, so it takes the first row and stays chosen.
expect(labels(forgotten.state)).toEqual(["github.com/anomalyco/rune-desktop", "search: gith"])
expect(view(forgotten.state, epoch)).toMatchObject({ listed: true, active: 0, field: "https://github.com/anomalyco/rune-desktop" })
// A later answer that still holds the forgotten page does not bring it back.
expect(answer(forgotten.state, asked(typed.effects)[0]?.attempt ?? -1, [github, rune]).state).toBe(forgotten.state)
const none = transitionAddress(type(focused, "rune").state, { type: "forget.pressed", visits: [] })
expect(none.effects).toEqual([])
expect(transitionAddress(focused, { type: "forget.pressed", visits: [] }).state).toBe(focused)
})
})
// Chrome's address bar, input by input. The pane is played as it runs: each character replaces the completed part of
// the field, as typing over a selection does; Backspace and Delete remove that part first; and every question to
// main is answered by the real search over this history.
describe("the list and its keys are Chrome's", () => {
const now = Date.UTC(2026, 10, 20)
const day = 86_400_000
const epoch = reports({ ...blank, url: "https://start.example/" })
const history: readonly PageVisit[] = [
{ url: "https://github.com/", title: "GitHub", visits: 40, typed: 12, visited: now - day },
{ url: "https://github.com/anomalyco/rune-desktop", title: "anomalyco/rune-desktop", visits: 25, typed: 2, visited: now - day },
{ url: "https://github.com/anomalyco/rune-desktop/pulls", title: "Pull requests", visits: 9, typed: 0, visited: now - 2 * day },
{ url: "https://github.com/sst/opentui", title: "sst/opentui", visits: 5, typed: 0, visited: now - 3 * day },
{ url: "https://github.com/oven-sh/bun", title: "oven-sh/bun", visits: 4, typed: 0, visited: now - 9 * day },
{ url: "https://docs.rune.example/guide", title: "Guide", visits: 6, typed: 0, visited: now - 5 * day },
]
type Outcome = {
readonly rows: readonly string[]
readonly chosen: number
readonly field: string
/** The part of the field the pane selects. */
readonly selected: string
/** What Enter opens next; undefined when it opens nothing. */
readonly enter: string | undefined
}
const keys = ["ArrowDown", "ArrowUp", "Tab", "Shift+Tab", "Escape"] as const
// Plays text and `{keys}` through the machine, answering as main does.
const play = (steps: readonly string[]) => {
const index = createPageIndex()
history.forEach((page, id) => index.set(id, page))
const opened: string[] = []
const left: string[] = []
const run = (state: AddressState, event: AddressEvent): AddressState =>
transitionAddress(state, event).effects.reduce((current, effect) => {
if (effect.type === "navigate") opened.push(effect.url)
if (effect.type === "blur-input") left.push("blur")
if (effect.type === "forget") history.forEach((page, id) => page.url === effect.url && index.remove(id))
if (effect.type !== "ask") return current
const read = { shown: (id: number) => history[id], front: (host: string) => history.find((page) => pageKey(page.url) === host) }
return run(current, { type: "answered", attempt: effect.attempt, pages: findPages(index, effect.query, HISTORY_ANSWER, now, read), visits: [] })
}, transitionAddress(state, event).state)
// What a key leaves of the field's text: a focused address is all selected, as is the completed part.
const typedPart = (state: AddressState) => {
const shown = view(state, epoch)
return shown.typed ? shown.field.slice(0, shown.field.length - shown.completion.length) : ""
}
const state = steps.reduce<AddressState>(
(current, step) => {
if (step === "{Enter}") return run(current, { type: "submitted", epoch, visits: [], failed: false })
if (step === "{Shift+Delete}") return run(current, { type: "forget.pressed", visits: [] })
// The completed part is selected, so either key removes it and nothing else; without it Backspace takes a character.
if (step === "{Backspace}" || step === "{Delete}") {
const completed = view(current, epoch).completion
const value = completed || step === "{Delete}" ? typedPart(current) : typedPart(current).slice(0, -1)
return run(current, { type: "input.changed", value, completing: false, visits: [] })
}
const key = keys.find((name) => step === `{${name}}`)
if (key) return run(current, { type: "key.pressed", key, epoch, visits: [] })
return [...step].reduce((typing, character) => run(typing, { type: "input.changed", value: typedPart(typing) + character, completing: true, visits: [] }), current)
},
run(initialAddressState, { type: "focused", epoch }),
)
const shown = view(state, epoch)
const outcome: Outcome = {
rows: shown.listed ? labels(state) : [],
chosen: shown.active,
field: shown.field,
selected: shown.completion,
enter: transitionAddress(state, { type: "submitted", epoch, visits: [], failed: false }).effects.flatMap((effect) => (effect.type === "navigate" ? [effect.url] : []))[0],
}
return { outcome, opened, left }
}
const google = (text: string) => `https://www.google.com/search?q=${encodeURIComponent(text)}`
const front = "github.com/"
const desktop = "github.com/anomalyco/rune-desktop"
const pulls = "github.com/anomalyco/rune-desktop/pulls"
const guide = "docs.rune.example/guide"
const cases: readonly (readonly [name: string, steps: readonly string[], outcome: Outcome])[] = [
["a word that begins no address searches, with the pages that hold it below", ["rune"], { rows: ["search: rune", desktop, pulls, guide], chosen: 0, field: "rune", selected: "", enter: google("rune") }],
["two words search", ["anom rune"], { rows: ["search: anom rune", desktop, pulls], chosen: 0, field: "anom rune", selected: "", enter: google("anom rune") }],
["a question searches", ["how to center a div"], { rows: ["search: how to center a div"], chosen: 0, field: "how to center a div", selected: "", enter: google("how to center a div") }],
["the start of a host completes to the site", ["gith"], { rows: [front, "search: gith", desktop, pulls, "github.com/sst/opentui", "github.com/oven-sh/bun"], chosen: 0, field: "github.com", selected: "ub.com", enter: "https://github.com/" }],
["the start of a path completes to the page", ["github.com/anom"], { rows: [desktop, "search: github.com/anom", pulls], chosen: 0, field: desktop, selected: "alyco/rune-desktop", enter: `https://${desktop}` }],
["a whole address of the history is its page", [desktop], { rows: [desktop, `search: ${desktop}`, pulls], chosen: 0, field: desktop, selected: "", enter: `https://${desktop}` }],
["an address that is not in the history opens as typed", ["example.org"], { rows: ["address: example.org", "search: example.org"], chosen: 0, field: "example.org", selected: "", enter: "example.org" }],
["a host with a port opens as typed", ["localhost:3000"], { rows: ["address: localhost:3000", "search: localhost:3000"], chosen: 0, field: "localhost:3000", selected: "", enter: "localhost:3000" }],
["Backspace removes the completed part and the typed text is first", ["gith", "{Backspace}"], { rows: ["search: gith", front, desktop, pulls, "github.com/sst/opentui", "github.com/oven-sh/bun"], chosen: 0, field: "gith", selected: "", enter: google("gith") }],
["Delete removes the completed part the same way", ["gith", "{Delete}"], { rows: ["search: gith", front, desktop, pulls, "github.com/sst/opentui", "github.com/oven-sh/bun"], chosen: 0, field: "gith", selected: "", enter: google("gith") }],
["typing after a deletion completes again", ["gith", "{Backspace}", "u"], { rows: [front, "search: githu", desktop, pulls, "github.com/sst/opentui", "github.com/oven-sh/bun"], chosen: 0, field: "github.com", selected: "b.com", enter: "https://github.com/" }],
["Down chooses the next row and shows its address", ["rune", "{ArrowDown}"], { rows: ["search: rune", desktop, pulls, guide], chosen: 1, field: `https://${desktop}`, selected: "", enter: `https://${desktop}` }],
["Up from the first row chooses the last", ["rune", "{ArrowUp}"], { rows: ["search: rune", desktop, pulls, guide], chosen: 3, field: `https://${guide}`, selected: "", enter: `https://${guide}` }],
["Down past the last row is the first again", ["rune", "{ArrowUp}", "{ArrowDown}"], { rows: ["search: rune", desktop, pulls, guide], chosen: 0, field: "rune", selected: "", enter: google("rune") }],
["Tab moves as Down does, Shift+Tab as Up", ["rune", "{Tab}", "{Tab}", "{Shift+Tab}"], { rows: ["search: rune", desktop, pulls, guide], chosen: 1, field: `https://${desktop}`, selected: "", enter: `https://${desktop}` }],
["Down from a completed address is the search for the typed text", ["gith", "{ArrowDown}"], { rows: [front, "search: gith", desktop, pulls, "github.com/sst/opentui", "github.com/oven-sh/bun"], chosen: 1, field: "gith", selected: "", enter: google("gith") }],
["Escape on a row brings back the typed text and the first row", ["rune", "{ArrowDown}", "{Escape}"], { rows: ["search: rune", desktop, pulls, guide], chosen: 0, field: "rune", selected: "", enter: google("rune") }],
["Escape on a row brings back the completed address, too", ["gith", "{ArrowDown}", "{ArrowDown}", "{Escape}"], { rows: [front, "search: gith", desktop, pulls, "github.com/sst/opentui", "github.com/oven-sh/bun"], chosen: 0, field: "github.com", selected: "ub.com", enter: "https://github.com/" }],
["Escape on the first row closes the list and drops the completed part", ["gith", "{Escape}"], { rows: [], chosen: -1, field: "gith", selected: "", enter: google("gith") }],
["Escape again brings back the page's address", ["gith", "{Escape}", "{Escape}"], { rows: [], chosen: -1, field: "https://start.example/", selected: "", enter: "https://start.example/" }],
["Shift+Delete forgets the chosen page; the row that takes its place is chosen", ["rune", "{ArrowDown}", "{Shift+Delete}"], { rows: ["search: rune", pulls, guide], chosen: 1, field: `https://${pulls}`, selected: "", enter: `https://${pulls}` }],
["Shift+Delete on the last row chooses the new last row", ["rune", "{ArrowUp}", "{Shift+Delete}"], { rows: ["search: rune", desktop, pulls], chosen: 2, field: `https://${pulls}`, selected: "", enter: `https://${pulls}` }],
["a forgotten page stays gone when typing asks again", ["rune", "{ArrowDown}", "{Shift+Delete}", "{Escape}", "-"], { rows: ["search: rune-", pulls], chosen: 0, field: "rune-", selected: "", enter: google("rune-") }],
]
test.each(cases)("%s", (_name, steps, outcome) => {
expect(play(steps).outcome).toEqual(outcome)
})
test("Enter opens the chosen row, first or not, and Escape past the page's address leaves the field", () => {
expect(play(["gith", "{Enter}"]).opened).toEqual(["https://github.com/"])
expect(play(["rune", "{Enter}"]).opened).toEqual([google("rune")])
expect(play(["rune", "{ArrowDown}", "{ArrowDown}", "{Enter}"]).opened).toEqual([`https://${pulls}`])
expect(play(["example.org", "{ArrowDown}", "{Enter}"]).opened).toEqual([google("example.org")])
expect(play(["gith", "{Escape}", "{Escape}", "{Escape}"]).left).toEqual(["blur"])
})
})
test("a report that changes nothing keeps the same counts object", () => {
const epoch = reports(blank)

View file

@ -2,15 +2,45 @@
// submitted address stays in the field until the page reports where it went. The page's reports are counted by
// `nextAddressEpoch`, and a submit keeps the counts it saw, so the next URL change, finished load or rejection ends
// the hold, even one that repeats a value, while focusing and leaving the field in between keeps it.
//
// The pages of the list come from two places: the window's own list of the last pages, at once, and main's history,
// which is asked on each change of the text and answers a moment later. The field never waits for it: each question
// takes the next number, and only the answer to the last one is kept.
//
// The list and its keys copy Chrome's address bar (`components/omnibox/browser` in Chromium). Its first row is what
// Enter opens and is always the chosen one: the typed text as a search or an address, or the page whose address the
// typing completes, which the field shows after the typed text, selected. Moving through the list puts each row's
// text in the field and holds the rows as they are.
import type { Browser } from "@opencode/plugin-browser/rpc"
import { resolveAddress, searches } from "./address"
import { completes, suggest, type Visit } from "./history"
import { resolveAddress, searchAddress, searches } from "./address"
import type { HistoryPage } from "./history/ipc"
import { filled, pageKey } from "./history/page"
import { suggestPages, type Suggestion } from "./history/suggest"
import type { Visit } from "./history/visits"
/** Suggestions the address field lists, and pages the new tab page lists. */
/** Pages of the history the address field lists, and pages the new tab page lists. */
export const ADDRESS_SUGGESTIONS = 5
/** Long text scrolls the input, which the inline hint cannot follow, so only a query this short shows it. */
export const ADDRESS_HINT_MAX_LENGTH = 48
/** A row of the address field's list. `url` is what it opens. */
export type AddressRow =
/** A web search for what was typed. */
| { readonly type: "search"; readonly text: string; readonly url: string }
/** What was typed, opened as an address. */
| { readonly type: "address"; readonly text: string; readonly url: string }
/** A page of the history. */
| { readonly type: "page"; readonly page: Suggestion; readonly url: string }
/** The list under the field while the person types. */
export type AddressList =
/** It follows the typing, and its first row is the chosen one. */
| { readonly type: "following" }
/**
* The person moved through it. Its rows stay as they were, whatever main answers later, and the field shows the
* text of the row at `line`.
*/
| { readonly type: "held"; readonly rows: readonly AddressRow[]; readonly line: number }
/** Escape closed it. Typing or an arrow key opens it again. */
| { readonly type: "closed" }
/** What the page reports, read on every change. */
export type AddressPage = {
@ -42,34 +72,60 @@ export type SubmittedHold = {
readonly moved: number
}
export type AddressState =
export type AddressState = {
/** The last question main's history was asked for this field; an answer to any other is stale. */
readonly asked: number
} & (
| { readonly status: "rest" }
| {
readonly status: "editing"
/** What the person typed. The field shows more: a completed address after it, or the text of a row. */
readonly text: string
/** The user typed since focusing; suggestions follow typing, not a focused URL. */
/** The user typed since focusing; the list follows typing, not a focused URL. */
readonly typed: boolean
/** The suggestion Enter opens; -1 opens the typed text. */
readonly active: number
/** Escape closed the suggestions; typing opens them again. */
readonly dismissed: boolean
readonly list: AddressList
/** A submitted address that had not been reported yet when the user focused; leaving the field keeps it. */
readonly hold: SubmittedHold | undefined
/**
* Main's last answer. It stays while the next question is out, matched against the new text, so the list
* narrows at once instead of emptying until the answer comes.
*/
readonly answer: readonly HistoryPage[]
/**
* The last change of the text may complete an address: it typed at the end of the text, and did not delete,
* paste or move the caret.
*/
readonly completing: boolean
}
| { readonly status: "submitted"; readonly hold: SubmittedHold }
)
export type AddressEvent =
| { readonly type: "focused"; readonly epoch: AddressEpoch }
| { readonly type: "blurred"; readonly epoch: AddressEpoch }
/**
* The field's text is `value`: the person typed, deleted or pasted, or moved the caret off a completed address,
* which takes it into the text. `completing` is whether an address may complete it: text typed at its end.
*/
| {
readonly type: "input.changed"
readonly value: string
readonly deleting: boolean
readonly completing: boolean
readonly visits: readonly Visit[]
}
| {
readonly type: "key.pressed"
readonly key: "ArrowDown" | "ArrowUp" | "Escape"
readonly key: "ArrowDown" | "ArrowUp" | "Tab" | "Shift+Tab" | "Escape"
readonly epoch: AddressEpoch
readonly visits: readonly Visit[]
}
/** Shift+Delete: forgets the chosen row's page. */
| { readonly type: "forget.pressed"; readonly visits: readonly Visit[] }
/** Main answered question `attempt`; a question that failed is answered with no pages. */
| {
readonly type: "answered"
readonly attempt: number
readonly pages: readonly HistoryPage[]
readonly visits: readonly Visit[]
}
/** Enter in the field; `failed` is whether the page failed to load, where an empty address opens a blank page. */
@ -79,18 +135,26 @@ export type AddressEvent =
readonly visits: readonly Visit[]
readonly failed: boolean
}
/** A click on a suggestion or a recent page. */
/** A click on a row of the list or a recent page. */
| { readonly type: "navigated"; readonly url: string; readonly epoch: AddressEpoch }
export type AddressEffect =
| { readonly type: "select-input" }
/** Selects the completed address: the field's text from `start`, after what was typed, to its end. */
| { readonly type: "select-completion"; readonly start: number }
| { readonly type: "blur-input" }
| { readonly type: "prevent-default" }
| { readonly type: "navigate"; readonly tabID: Browser.TabID; readonly url: string }
/** The person is about to type: main reads its history into memory, ahead of the first question. */
| { readonly type: "prepare" }
/** Asks main's history for the pages that match `query`; the answer names `attempt`. */
| { readonly type: "ask"; readonly attempt: number; readonly query: string }
/** Forgets a page: in main's history, and in the window's list of the last pages. */
| { readonly type: "forget"; readonly url: string }
export type AddressTransition = { readonly state: AddressState; readonly effects: readonly AddressEffect[] }
export const initialAddressState: AddressState = { status: "rest" }
export const initialAddressState: AddressState = { status: "rest", asked: 0 }
const SELECT: AddressEffect = { type: "select-input" }
@ -98,6 +162,14 @@ const BLUR: AddressEffect = { type: "blur-input" }
const PREVENT: AddressEffect = { type: "prevent-default" }
const PREPARE: AddressEffect = { type: "prepare" }
const FOLLOWING: AddressList = { type: "following" }
const CLOSED: AddressList = { type: "closed" }
type Editing = Extract<AddressState, { status: "editing" }>
export function transitionAddress(state: AddressState, event: AddressEvent): AddressTransition {
switch (event.type) {
case "focused": {
@ -107,13 +179,16 @@ export function transitionAddress(state: AddressState, event: AddressEvent): Add
return {
state: {
status: "editing",
// A new edit: an answer still on its way to the last one is not for this one.
asked: state.asked + 1,
text: hold ? hold.text : event.epoch.url,
typed: false,
active: -1,
dismissed: false,
list: FOLLOWING,
hold,
answer: [],
completing: false,
},
effects: [SELECT],
effects: [SELECT, PREPARE],
}
}
@ -122,52 +197,101 @@ export function transitionAddress(state: AddressState, event: AddressEvent): Add
if (state.status !== "editing") return unchanged(state)
const hold = activeHold(state.hold, event.epoch)
return { state: hold ? { status: "submitted", hold } : initialAddressState, effects: [] }
return { state: hold ? { status: "submitted", asked: state.asked, hold } : { status: "rest", asked: state.asked }, effects: [] }
}
case "input.changed": {
if (state.status !== "editing") return unchanged(state)
const first = suggest(event.visits, event.value, 1)[0]
// Typing completes the first suggestion, as a search would; deleting never does.
const complete = !!first && !event.deleting && (completes(first, event.value) || searches(event.value))
const asked = state.asked + 1
const text = event.value
// Text with nothing to search for asks nothing, and no answer to an earlier text fits it.
const searching = text.trim().length > 0
const next: Editing = { ...state, asked, text, typed: true, list: FOLLOWING, completing: event.completing, answer: searching ? state.answer : [] }
return {
state: { ...state, text: event.value, typed: true, dismissed: false, active: complete ? 0 : -1 },
effects: [],
state: next,
effects: [...(searching ? [{ type: "ask" as const, attempt: asked, query: text }] : []), ...selecting(next, event.visits)],
}
}
case "answered": {
// Rows the person moved through stay as they were: Chrome ends its search at the first step.
if (state.status !== "editing" || event.attempt !== state.asked || state.list.type === "held") return unchanged(state)
const next: Editing = { ...state, answer: event.pages }
// The answer may bring the page whose address the typing completes.
return { state: next, effects: selecting(next, event.visits) }
}
case "forget.pressed": {
if (state.status !== "editing") return unchanged(state)
const rows = addressRows(state, event.visits)
const line = state.list.type === "held" ? state.list.line : 0
const picked = listed(state, rows) ? rows[line] : undefined
// Only a page of the history can be forgotten. On any other row the key is the input's own.
if (picked?.type !== "page") return unchanged(state)
const key = pageKey(picked.url)
const left = listRows(state.text, rows.flatMap((row) => (row.type === "page" && row !== picked ? [row.page] : [])), state.completing)
// The row that takes its place is the chosen one, and the list is held: the page may still be in an answer.
return {
state: {
...state,
answer: state.answer.filter((page) => page.url !== picked.url && (!key || pageKey(page.url) !== key)),
list: { type: "held", rows: left, line: Math.min(line, left.length - 1) },
},
effects: [PREVENT, { type: "forget", url: picked.url }],
}
}
case "key.pressed": {
if (state.status !== "editing") return unchanged(state)
const suggestions = addressSuggestions(state, event.visits)
const rows = addressRows(state, event.visits)
const open = listed(state, rows)
// Escape undoes one thing at a time: the row's text, the list, the typed text, then the focus.
if (event.key === "Escape") {
if (listed(state, suggestions)) return { state: { ...state, dismissed: true, active: -1 }, effects: [PREVENT] }
if (state.list.type === "held") {
const next: Editing = { ...state, list: FOLLOWING }
return { state, effects: [PREVENT, BLUR] }
return { state: next, effects: [PREVENT, ...selecting(next, event.visits)] }
}
if (open) return { state: { ...state, list: CLOSED }, effects: [PREVENT] }
if (!state.typed) return { state, effects: [PREVENT, BLUR] }
const hold = activeHold(state.hold, event.epoch)
return {
state: { ...state, asked: state.asked + 1, text: hold ? hold.text : event.epoch.url, typed: false, list: FOLLOWING, hold, answer: [], completing: false },
effects: [PREVENT, SELECT],
}
}
const count = suggestions.length
if (!open) {
// Without a list Tab leaves the field, and an empty field has nothing to list.
if (event.key === "Tab" || event.key === "Shift+Tab" || !state.text.trim()) return unchanged(state)
const asked = state.asked + 1
// An arrow opens the list for the text in the field. A focused address was not typed, so nothing completes it.
const next: Editing = { ...state, asked, typed: true, list: FOLLOWING, completing: state.typed && state.completing }
if (!count) return unchanged(state)
const by = event.key === "ArrowDown" ? 1 : -1
return {
state: {
...state,
dismissed: false,
active: state.active + by < -1 ? count - 1 : ((state.active + by + 1) % (count + 1)) - 1,
},
effects: [PREVENT],
return { state: next, effects: [PREVENT, { type: "ask", attempt: asked, query: state.text }, ...selecting(next, event.visits)] }
}
const line = state.list.type === "held" ? state.list.line : 0
const by = event.key === "ArrowDown" || event.key === "Tab" ? 1 : -1
// Past either end the choice goes to the other one.
return { state: { ...state, list: { type: "held", rows, line: (line + by + rows.length) % rows.length } }, effects: [PREVENT] }
}
case "submitted": {
const suggestions = addressSuggestions(state, event.visits)
const picked = chosen(state, suggestions)
const rows = addressRows(state, event.visits)
const picked = chosen(state, rows)
if (picked) return navigate(state, picked.url, event.epoch)
const text = field(state, event.epoch).trim()
const text = typedText(state, event.epoch).trim()
if (text || event.failed) return navigate(state, resolveAddress(text), event.epoch)
@ -210,35 +334,76 @@ export function nextAddressEpoch(previous: AddressEpoch | undefined, page: Addre
return { ...page, settled, followed, rejected, moved }
}
/** Suggestions follow what the user typed; a focused address is not a query. */
export function addressSuggestions(state: AddressState, visits: readonly Visit[]): readonly Visit[] {
return state.status === "editing" && state.typed ? suggest(visits, state.text, ADDRESS_SUGGESTIONS) : []
/**
* The rows of the list: they follow what the user typed, and a focused address is not typed. `visits` is the
* window's list of the last pages, which main's answer joins.
*/
export function addressRows(state: AddressState, visits: readonly Visit[]): readonly AddressRow[] {
if (state.status !== "editing" || !state.typed) return []
if (state.list.type === "held") return state.list.rows
return listRows(state.text, suggestPages(state.text, visits, state.answer, ADDRESS_SUGGESTIONS), state.completing)
}
/** What the address field draws. */
export function addressView(state: AddressState, epoch: AddressEpoch, suggestions: readonly Visit[]) {
export function addressView(state: AddressState, epoch: AddressEpoch, rows: readonly AddressRow[]) {
const editing = state.status === "editing"
const shown = listed(state, suggestions)
const active = shown && state.status === "editing" ? state.active : -1
const shown = listed(state, rows)
const picked = chosen(state, rows)
const completed = completion(state, rows)
const hold = state.status === "rest" ? undefined : state.hold
return {
editing,
/** The user's text while editing, a submitted address until the page reports, otherwise the page's URL. */
field: field(state, epoch),
/** What the user typed, which suggestions highlight; empty at rest. */
/**
* The chosen row's text once the person moved through the list; else the user's text while editing, with the
* address it completes after it, a submitted address until the page reports, otherwise the page's URL.
*/
field: state.status === "editing" && state.list.type === "held" && picked ? rowText(picked) : typedText(state, epoch) + completed,
/** What the user typed, whose words the pages of the list highlight; empty at rest. */
query: state.status === "editing" ? state.text : "",
typed: state.status === "editing" && state.typed,
/** The suggestions popover is open. */
/** The list is open. */
listed: shown,
active,
/** The suggestion Enter opens. */
chosen: active >= 0 ? suggestions[active] : undefined,
/** The chosen row's place in the list; -1 without a list. */
active: picked ? rows.indexOf(picked) : -1,
/** The row Enter opens. */
chosen: picked,
/** The end of `field` that completes what was typed, which the field selects; empty when nothing does. */
completion: completed,
/** Typing may complete an address: a caret that leaves the end of the text takes that away. */
completing: state.status === "editing" && state.typed && state.list.type === "following" && state.completing,
/** A submitted navigation the browser has not reported yet; keeps the empty state hidden meanwhile. */
navigating: !!hold && hold.moved === epoch.moved,
}
}
/** What a row puts in the field when the person moves to it: what was typed, or the page's address. */
export function rowText(row: AddressRow) {
return row.type === "page" ? filled(row.url) : row.text
}
/**
* The list for a text, in Chrome's order. The first row is the one Enter opens: the best page when its address is
* the text, or begins with it while typing completes; else the text itself, as a search or as an address. A search
* for the text follows when it is not first, then the pages. A page that only matches is never first.
*/
function listRows(text: string, pages: readonly Suggestion[], completing: boolean): readonly AddressRow[] {
const typed = text.trim()
if (!typed) return []
const search: AddressRow = { type: "search", text: typed, url: searchAddress(typed) }
const rows = pages.map((page): AddressRow => ({ type: "page", page, url: page.url }))
const lead = pages[0]
if (lead && (lead.completion === "" || (completing && lead.completion !== undefined))) return [...rows.slice(0, 1), search, ...rows.slice(1)]
if (searches(typed)) return [search, ...rows]
return [{ type: "address", text: typed, url: resolveAddress(typed) }, search, ...rows]
}
function navigate(state: AddressState, url: string, epoch: AddressEpoch): AddressTransition {
if (!epoch.tabID) return unchanged(state)
@ -246,6 +411,7 @@ function navigate(state: AddressState, url: string, epoch: AddressEpoch): Addres
return {
state: {
status: "submitted",
asked: state.asked,
hold: {
text: url === "about:blank" ? "" : url,
followed: epoch.followed,
@ -257,18 +423,39 @@ function navigate(state: AddressState, url: string, epoch: AddressEpoch): Addres
}
}
function field(state: AddressState, epoch: AddressEpoch) {
/** The user's text while editing, a submitted address until the page reports, otherwise the page's URL. */
function typedText(state: AddressState, epoch: AddressEpoch) {
if (state.status === "editing") return state.text
return state.status === "submitted" && activeHold(state.hold, epoch) ? state.hold.text : epoch.url
}
function listed(state: AddressState, suggestions: readonly Visit[]) {
return state.status === "editing" && suggestions.length > 0 && !state.dismissed
function listed(state: AddressState, rows: readonly AddressRow[]) {
return state.status === "editing" && state.typed && state.list.type !== "closed" && rows.length > 0
}
function chosen(state: AddressState, suggestions: readonly Visit[]) {
return listed(state, suggestions) && state.status === "editing" ? suggestions[state.active] : undefined
/** The row Enter opens: the one the person moved to, else the first. */
function chosen(state: AddressState, rows: readonly AddressRow[]) {
if (state.status !== "editing" || !listed(state, rows)) return undefined
return rows[state.list.type === "held" ? state.list.line : 0]
}
/**
* The rest of the first row's address after the typed text, which the field shows selected: only while the list
* follows the typing and the last change of the text may complete. Deleting never completes.
*/
function completion(state: AddressState, rows: readonly AddressRow[]) {
const first = rows[0]
if (state.status !== "editing" || !state.typed || state.list.type !== "following" || !state.completing || first?.type !== "page") return ""
return first.page.completion ?? ""
}
/** Selects the completed address, when the field now shows one. */
function selecting(state: Editing, visits: readonly Visit[]): readonly AddressEffect[] {
return completion(state, addressRows(state, visits)) ? [{ type: "select-completion", start: state.text.length }] : []
}
/** The hold, while the page has not reported a URL change, a finished load or a rejection since the submit. */

View file

@ -1,6 +1,8 @@
import { expect, test } from "bun:test"
import { addressParts, externalAction, externalPage, pageHandoff, resolveAddress } from "./address"
import { remember, suggest } from "./history"
import { completion, filled } from "./history/page"
import { suggestPages } from "./history/suggest"
import { remember } from "./history/visits"
import { normalizeURL, refusal } from "./policy"
test("typed file paths never become a host or a search query, regardless of the desktop OS", () => {
@ -93,7 +95,7 @@ test("the field draws the whole URL, split around its host, in exactly the input
expect(urls.map((url) => Object.values(addressParts(url)).join(""))).toEqual(urls)
})
test("history keeps one newest-first visit per URL and suggests addresses that complete the query first", () => {
test("the window's list keeps one newest-first visit per URL and, alone, suggests its matches newest first", () => {
const visits = ["https://docs.example/mdn-guide", "https://developer.mozilla.org/", "https://www.mdn.dev/"].reduce(
(list, url) => remember(list, { url, title: url.includes("mozilla") ? "MDN Web Docs" : "Other" }),
remember([], { url: "https://developer.mozilla.org/", title: "Old title" }),
@ -104,13 +106,21 @@ test("history keeps one newest-first visit per URL and suggests addresses that c
["https://developer.mozilla.org/", "MDN Web Docs"],
["https://docs.example/mdn-guide", "Other"],
])
// A leading www. and the scheme are not typed, so mdn completes www.mdn.dev; the others only contain it.
expect(suggest(visits, "MDN", 5).map((visit) => visit.url)).toEqual([
// A leading www. and the scheme are not typed, so mdn completes www.mdn.dev; the others have it as a word of the
// title or a part of the path.
expect(suggestPages("MDN", visits, [], 5).map((visit) => [visit.url, visit.completion])).toEqual([
["https://www.mdn.dev/", ".dev"],
["https://developer.mozilla.org/", undefined],
["https://docs.example/mdn-guide", undefined],
])
// A word found only inside a longer one comes after every word start, however new its page.
expect(suggestPages("ozilla", visits, [], 5).map((visit) => visit.url)).toEqual(["https://developer.mozilla.org/"])
expect(suggestPages("d", visits, [], 5).map((visit) => visit.url)).toEqual([
"https://www.mdn.dev/",
"https://developer.mozilla.org/",
"https://docs.example/mdn-guide",
])
expect(suggest(visits, " ", 5)).toEqual([])
expect(suggestPages(" ", visits, [], 5)).toEqual([])
expect(
Array.from({ length: 40 }, (_, index) => `https://example.com/${index}`).reduce(
(list, url) => remember(list, { url, title: "" }),
@ -119,6 +129,36 @@ test("history keeps one newest-first visit per URL and suggests addresses that c
).toHaveLength(30)
})
test("an address completes the typed text and fills the field as Chrome's address bar does", () => {
const rune = "https://github.com/anomalyco/rune-desktop"
// The text may leave out the scheme and a leading www., in any case; a text that is not the start completes nothing.
const completions: readonly (readonly [text: string, url: string, rest: string | undefined])[] = [
["gith", "https://github.com/", "ub.com"],
["GitH", "https://github.com/", "ub.com"],
["https://gith", "https://github.com/", "ub.com"],
["md", "https://www.mdn.dev/", "n.dev"],
["www.md", "https://www.mdn.dev/", "n.dev"],
["github.com/anom", rune, "alyco/rune-desktop"],
// The whole address, with or without the slash that ends a bare host.
["github.com", "https://github.com/", ""],
["github.com/", "https://github.com/", ""],
["hub", "https://github.com/", undefined],
["gith ", "https://github.com/", undefined],
["", "https://github.com/", undefined],
]
expect(completions.map(([text, url]) => completion(text, url))).toEqual(completions.map(([, , rest]) => rest))
// A row's address in the field: https stays, http and the slash after a bare host go.
expect(["https://github.com/", rune, "http://localhost:3000/", "http://example.com/a/?b#c", "file:///C:/repo/index.html"].map(filled)).toEqual([
"https://github.com",
rune,
"localhost:3000",
"example.com/a/?b#c",
"file:///C:/repo/index.html",
])
})
test("a local preview may be revealed by tab ID but never launched by URL", () => {
for (const suffix of ["html", "exe", "bat", "cmd", "lnk", "ps1", "app"]) {
expect(externalAction(`file:///repo/test.${suffix}`, true)).toBe("reveal")

View file

@ -12,7 +12,12 @@ export function resolveAddress(input: string) {
if (!value || value.toLowerCase() === "about:blank") return "about:blank"
return searches(value) ? `${SEARCH}${encodeURIComponent(value)}` : value
return searches(value) ? searchAddress(value) : value
}
/** The web search for a text, which the address field's list offers for any text, an address too. */
export function searchAddress(text: string) {
return `${SEARCH}${encodeURIComponent(text.trim())}`
}
/**

View file

@ -76,8 +76,7 @@
background-color: transparent;
}
[data-slot="browser-address-display"],
[data-slot="browser-address-hint"] {
[data-slot="browser-address-display"] {
position: absolute;
inset: 0;
display: flex;
@ -87,10 +86,6 @@
pointer-events: none;
}
[data-slot="browser-address-hint"] {
color: var(--v2-text-text-muted);
}
/* One line of the whole URL, ending in an ellipsis where the field ends. The scheme and the path are muted around
the host, and so is the ellipsis, which takes the line's color and almost always cuts the path. An address
without a host, such as a workspace file, keeps its path at full strength. */

View file

@ -0,0 +1,61 @@
import { mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises"
import path from "node:path"
import electron from "electron"
import { runBrowserMain } from "./electron-main"
// The Electron main process of `electron-history.test.ts`, bundled and run by the pinned Electron with every location
// the browser list reads pointed at the test's made-up home. It runs the browser plugin's own main entry and calls the
// two Ipcs it provides, as a window does, while the history store's file is something that cannot be opened: first a
// directory, which cannot be deleted either, then a file that is not a database. It prints one JSON line.
void electron.app.whenReady().then(async () => {
const { Schema } = await import("effect")
const { BrowserProfile } = await import("./profile/ipc")
const file = path.join(electron.app.getPath("userData"), "browser-history", "history.sqlite")
const { profile, history, caller, cookies, outcome, logged, close } = await runBrowserMain()
// Each answer as its Ipc's schema encodes it for the window, which fails on one the contract does not allow.
const methods = BrowserProfile.spec.methods
const importAll = () =>
outcome(async () =>
Schema.encodeSync(methods.importBrowser.output)(
await profile.importBrowser({ source: "firefox", profile: "Profiles/work.default", history: true }, caller),
),
)
const signOut = () => outcome(async () => Schema.encodeSync(methods.clear.output)(await profile.clear(undefined, caller)))
const search = () => outcome(async () => (await history.search({ query: "rune", limit: 5 }, caller)).map((page) => page.url))
// A directory where the store's file belongs: it cannot be opened, and deleting the file does not remove it.
await mkdir(path.join(file, "kept"), { recursive: true })
const blocked = {
imported: await importAll(),
cookies: await cookies(),
search: await search(),
signOut: await signOut(),
cookiesAfter: await cookies(),
clearHistory: await outcome(() => history.clear(undefined, caller)),
kept: await readdir(file),
}
// A file that is not a database: it cannot be opened, and nothing in it can be kept.
await rm(file, { recursive: true })
await writeFile(file, Buffer.alloc(8192, "zebra-marker is not a database. "))
const damaged = {
imported: await importAll(),
cookies: await cookies(),
signOut: await signOut(),
cookiesAfter: await cookies(),
left: (await readFile(file).catch(() => Buffer.alloc(0))).includes("zebra-marker"),
}
// The store that replaced it works as any other.
const replaced = { imported: await importAll(), search: await search(), signOut: await signOut(), searchAfter: await search() }
process.stdout.write(`${JSON.stringify({ blocked, damaged, replaced, logged: logged.filter((message) => message.includes("history")) })}\n`)
await close()
electron.app.quit()
})

View file

@ -0,0 +1,53 @@
import { expect, test } from "bun:test"
import { rm } from "node:fs/promises"
import path from "node:path"
import { runElectronFixture } from "./electron-run"
import { madeUpFirefox } from "./profile/made-up-firefox.fixture"
// The history store is one more thing the browser keeps, and nothing the browser did before may depend on it. This
// runs the plugin's main entry in the pinned Electron and calls its Ipcs as a window does, with a real file in the
// store's place that cannot be opened, against a made-up Firefox profile in a temporary home.
test(
"a history store that cannot open never weakens a sign-out or an import, and a damaged one is cleared by deleting it",
async () => {
const made = await madeUpFirefox()
try {
const result = JSON.parse(await runElectronFixture({ fixture: path.join(import.meta.dir, "electron-history.fixture.ts"), env: made.env }))
const cookies = { type: "imported", imported: 5, skipped: 0, protected: 0, failed: 0 }
// The store's file is a directory. The import still brings every cookie, with no pages and no failure.
expect(result.blocked.imported).toEqual({ value: { ...cookies, pages: 0 } })
expect(result.blocked.cookies).toBe(5)
// The address field's question is refused, which the window answers from its own list.
expect(result.blocked.search).toEqual({ rejected: true })
// The sign-out is whole: every cookie is gone. It says that the history is not, which is still on disk.
expect(result.blocked.signOut).toEqual({ value: { history: false } })
expect(result.blocked.cookiesAfter).toBe(0)
// "Clear history" is refused too, so the window says so, rather than seem to have cleared it.
expect(result.blocked.clearHistory).toEqual({ rejected: true })
expect(result.blocked.kept).toEqual(["kept"])
// The store's file is not a database. The import is as whole, and the sign-out clears the history by deleting
// the file, which leaves nothing of it.
expect(result.damaged.imported).toEqual({ value: { ...cookies, pages: 0 } })
expect(result.damaged.cookies).toBe(5)
expect(result.damaged.signOut).toEqual({ value: { history: true } })
expect(result.damaged.cookiesAfter).toBe(0)
expect(result.damaged.left).toBe(false)
// The store that replaced it takes the profile's three pages, finds one, and a sign-out forgets them.
expect(result.replaced.imported).toEqual({ value: { ...cookies, pages: 3 } })
expect(result.replaced.search).toEqual({ value: ["https://github.com/anomalyco/rune-desktop"] })
expect(result.replaced.signOut).toEqual({ value: { history: true } })
expect(result.replaced.searchAfter).toEqual({ value: [] })
// Each failure is in the desktop log.
expect(result.logged).toContain("another browser's history was not imported")
expect(result.logged).toContain("browser history could not be cleared")
} finally {
await rm(made.home, { recursive: true, force: true }).catch(() => undefined)
}
},
// Starting Electron takes seconds on a loaded runner.
60_000,
)

View file

@ -0,0 +1,58 @@
import { stat, writeFile } from "node:fs/promises"
import path from "node:path"
import electron from "electron"
import { runBrowserMain } from "./electron-main"
// The Electron main process of `electron-import-choice.test.ts`, bundled and run by the pinned Electron with every
// location the browser list reads pointed at the test's made-up home. It runs the browser plugin's own main entry and
// imports through its Ipc, as the import dialog does, what each of the dialog's two boxes stands for: sign-ins only,
// both, both of one chosen site, and history only. It prints one JSON line.
void electron.app.whenReady().then(async () => {
const { Schema } = await import("effect")
const { BrowserProfile } = await import("./profile/ipc")
const store = path.join(electron.app.getPath("userData"), "browser-history", "history.sqlite")
const { profile, history, caller, session, cookies, outcome, close } = await runBrowserMain()
const methods = BrowserProfile.spec.methods
// Each answer as the Ipc's schema encodes it for the window, which fails on one the contract does not allow.
const bring = (what: { readonly cookies?: boolean; readonly history?: boolean; readonly sites?: readonly string[] }) =>
outcome(async () =>
Schema.encodeSync(methods.importBrowser.output)(
await profile.importBrowser({ source: "firefox", profile: "Profiles/work.default", ...what }, caller),
),
)
// The store's file exists once anything opened the store.
const opened = () =>
stat(store).then(
() => true,
() => false,
)
// Every page of the made-up history has a "t" in its address.
const pages = async () => (await history.search({ query: "t", limit: 10 }, caller)).map((page) => page.url).toSorted()
// The browser's cookies and the history go, so each import is counted for itself.
const reset = async () => {
await session.clearStorageData({ storages: ["cookies"] })
await history.clear(undefined, caller)
}
const signins = { result: await bring({ history: false }), cookies: await cookies(), store: await opened() }
await reset()
const both = { result: await bring({ history: true }), cookies: await cookies(), pages: await pages() }
await reset()
const site = { result: await bring({ history: true, sites: ["bank.test"] }), cookies: await cookies(), pages: await pages() }
await reset()
// From here the other browser's cookie database is no database: any read of it fails.
await writeFile(process.env.BROWSER_FIXTURE_COOKIES ?? "", Buffer.alloc(8192, "not a database. "))
const historyOnly = { result: await bring({ cookies: false, history: true }), cookies: await cookies(), pages: await pages() }
await reset()
const historySite = { result: await bring({ cookies: false, history: true, sites: ["bank.test"] }), pages: await pages() }
const read = await bring({ history: false })
process.stdout.write(`${JSON.stringify({ signins, both, site, historyOnly, historySite, read })}\n`)
await close()
electron.app.quit()
})

View file

@ -0,0 +1,39 @@
import { expect, test } from "bun:test"
import { rm } from "node:fs/promises"
import path from "node:path"
import { runElectronFixture } from "./electron-run"
import { madeUpFirefox } from "./profile/made-up-firefox.fixture"
// The import dialog's two boxes, "Sign-ins" and "Browsing history", are two real paths in main. This runs the plugin's
// main entry in the pinned Electron and imports through its Ipc, as the dialog does, from a made-up Firefox profile in
// a temporary home: five cookies of three sites, and three pages of two.
test(
"an import brings what was ticked: sign-ins without opening the history, history without reading a cookie, or both",
async () => {
const made = await madeUpFirefox()
try {
const env = { ...made.env, BROWSER_FIXTURE_COOKIES: path.join(made.profile, "cookies.sqlite") }
const result = JSON.parse(await runElectronFixture({ fixture: path.join(import.meta.dir, "electron-import-choice.fixture.ts"), env }))
const none = { type: "imported", imported: 0, skipped: 0, protected: 0, failed: 0 }
const github = ["https://github.com/", "https://github.com/anomalyco/rune-desktop"]
const bank = "https://www.bank.test/accounts"
// Sign-ins only: every cookie, no count of pages, and the history store was never opened, so it has no file.
expect(result.signins).toEqual({ result: { value: { ...none, imported: 5 } }, cookies: 5, store: false })
// Both: every cookie and every page.
expect(result.both).toEqual({ result: { value: { ...none, imported: 5, pages: 3 } }, cookies: 5, pages: [...github, bank] })
// Chosen sites limit both kinds: the one site's cookie and its one page.
expect(result.site).toEqual({ result: { value: { ...none, imported: 1, pages: 1 } }, cookies: 1, pages: [bank] })
// History only: the pages come and no cookie does. The cookie database cannot be read by then, so an import that
// read it would have failed, as the last one, which asks for the cookies, does.
expect(result.historyOnly).toEqual({ result: { value: { ...none, pages: 3 } }, cookies: 0, pages: [...github, bank] })
expect(result.historySite).toEqual({ result: { value: { ...none, pages: 1 } }, pages: [bank] })
expect(result.read).toEqual({ value: { type: "failed", reason: "read" } })
} finally {
await rm(made.home, { recursive: true, force: true }).catch(() => undefined)
}
},
// Starting Electron takes seconds on a loaded runner.
60_000,
)

View file

@ -0,0 +1,85 @@
import electron from "electron"
import type { Caller, Ipc, IpcImpl, IpcSpec, MainContext } from "@opencode/plugin/gui/main"
/**
* The browser plugin's own main entry, run in the Electron of a real-Electron fixture, and the two Ipcs it provides as
* a window calls them. No pane is registered, so no window, server or page is asked for. `close` ends the plugin.
*/
export async function runBrowserMain() {
const { default: setup } = await import("./main")
const { BrowserHistory } = await import("./history/ipc")
const { BrowserProfile } = await import("./profile/ipc")
const values = new Map<string, unknown>()
const provided = new Map<string, IpcImpl<IpcSpec>>()
const cleanups: (() => void | Promise<void>)[] = []
const logged: string[] = []
const lifetime = new AbortController()
// SAFETY: the main entry and the profile read of the context only what is here: storage as a map of values, the
// log, the Ipcs they provide and their cleanup.
// oxlint-disable-next-line anti-slop/no-chained-type-assertions -- see SAFETY above
const ctx = {
id: "browser",
signal: lifetime.signal,
t: (key: string) => key,
app: { name: "opencode", version: "0.0.0", channel: "local", platform: "desktop", packaged: false },
log: { write: (_level: string, message: string) => void logged.push(message) },
storage: {
store: (key: string, options: { initial: unknown }) => ({
get value() {
return values.has(key) ? values.get(key) : options.initial
},
ready: () => true,
// oxlint-disable-next-line anti-slop/no-unknown-parameters -- see SAFETY above
set: (next: unknown) => void values.set(key, next),
// oxlint-disable-next-line anti-slop/no-unknown-parameters -- see SAFETY above
update(mutate: (draft: unknown) => void) {
const draft = structuredClone(values.has(key) ? values.get(key) : options.initial)
mutate(draft)
values.set(key, draft)
},
}),
remove: (key: string) => void values.delete(key),
},
windows: { get: () => undefined, list: () => [], focused: () => undefined, on: () => () => undefined },
serverEndpoints: { get: () => undefined },
provide: (token: { readonly id: string }, impl: IpcImpl<IpcSpec>) => {
provided.set(token.id, impl)
return { changed: () => undefined, emit: () => undefined }
},
add: () => () => undefined,
onCleanup: (cleanup: () => void | Promise<void>) => void cleanups.push(cleanup),
} as unknown as MainContext
await setup(ctx)
// SAFETY: `provide` above received each Ipc's own implementation from the main entry, whose type the token carries.
const ipc = <S extends IpcSpec>(token: Ipc<S>) => provided.get(token.id) as IpcImpl<S>
const caller: Caller = { window: 1, signal: lifetime.signal }
const session = electron.session.fromPartition("persist:opencode-browser")
return {
profile: ipc(BrowserProfile),
history: ipc(BrowserHistory),
caller,
/** The browser's own cookie store, which an import writes. */
session,
/** How many cookies the browser has. */
cookies: async () => (await session.cookies.get({})).length,
/** What the desktop log received. */
logged,
/** What a window's call comes to: the answer, or the rejection. */
outcome: <A>(call: () => A | Promise<A>) =>
Promise.resolve()
.then(call)
.then(
(value) => ({ value }),
() => ({ rejected: true }),
),
async close() {
lifetime.abort()
await Promise.all(cleanups.map((cleanup) => cleanup()))
},
}
}

View file

@ -32,6 +32,23 @@ try {
}
`
/**
* A file imported with `?raw` is its text, as the app's bundler reads it: the profile ships its page scripts so.
*/
const rawText: Bun.BunPlugin = {
name: "raw-text",
setup(build) {
build.onResolve({ filter: /\?raw$/ }, (args) => ({
path: path.resolve(path.dirname(args.importer), args.path.slice(0, -"?raw".length)),
namespace: "raw-text",
}))
build.onLoad({ filter: /.*/, namespace: "raw-text" }, async (args) => ({
contents: `export default ${JSON.stringify(await readFile(args.path, "utf8"))}`,
loader: "js",
}))
},
}
/** The fixture's one JSON line; otherwise a failure with its exit code, its log and its stderr. */
export async function runElectronFixture(input: {
/** Absolute path to the fixture's source. */
@ -55,6 +72,7 @@ export async function runElectronFixture(input: {
splitting: true,
naming: { entry: "fixture.mjs", chunk: "[name]-[hash].mjs" },
external: ["electron"],
plugins: [rawText],
})
if (!built.success) throw new AggregateError(built.logs, "The Electron fixture did not build.")

View file

@ -0,0 +1,23 @@
import type { BuiltinMainStorage, MainStoreFrom } from "@opencode/plugin/gui/builtin"
import { History } from "./visits"
/**
* Where every window of this desktop app keeps the browser's list of the last pages it showed (the `history` store
* of `index.ts`), and where builds before the plugin rename kept it.
*/
const WINDOW_LISTS: readonly MainStoreFrom[] = [
{ state: ["opencode.global.dat", "plugin.browser.history"] },
{ state: ["opencode.global.dat", "extension.browser.history"] },
]
/**
* The pages the windows listed before the history store existed, newest first, for the store to take over once. Main
* storage reads another home only by importing it into a key of its own, which is deleted again: the list stays the
* windows', who still show it on the new tab page.
*/
export function earlierVisits(storage: BuiltinMainStorage) {
const visits = storage.store("history.earlier", { schema: History, initial: { visits: [] }, from: WINDOW_LISTS }).value.visits
storage.remove("history.earlier")
return visits
}

View file

@ -0,0 +1,5 @@
// What the profile's side of an import uses of the history. Main process only: the store opens SQLite. The window
// imports the modules it needs by name.
export { MAX_PAGES, MAX_URL_LENGTH, webPage, type PageVisit } from "./page"
export { createHistoryStore } from "./store"

View file

@ -0,0 +1,44 @@
import { Schema } from "effect"
import { Ipc } from "@opencode/plugin/gui"
/** An address as a page reports it; the history keeps only web pages of up to `MAX_URL_LENGTH`. */
const address = Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(16_384))
const Page = Schema.Struct({ url: address, title: Schema.String.check(Schema.isMaxLength(2_048)) })
/**
* A page the address field may suggest. `score` is how often and how recently it was visited, which orders pages
* that match equally well.
*/
export const HistoryPage = Schema.Struct({ url: Schema.String, title: Schema.String, score: Schema.Finite })
export type HistoryPage = typeof HistoryPage.Type
/**
* The browsing history of this desktop app: the pages visited here and the pages imported from other browsers, in one
* store in the main process, on this computer only. A window never holds it: it asks for the few pages that match
* what the person typed. Only the windows' address field calls it; no tool of the agent reads or searches it.
*/
export const BrowserHistory = Ipc.define({
id: "browser.history",
methods: {
/** The person focused the address field: main reads the history into memory, so the first search finds it there. */
prepare: {},
/** The `limit` pages that match the typed text best, best first. Text with no word to search for finds none. */
search: {
input: Schema.Struct({
query: Schema.String.check(Schema.isMaxLength(2_048)),
limit: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 20 })),
}),
output: Schema.Array(HistoryPage),
},
/** A page finished loading in a tab: one more visit. A page that is not a web page is ignored. */
visit: { input: Page },
/** A page visited already reported its title. */
retitle: { input: Page },
/** The person removed a suggestion: its page is forgotten. */
remove: { input: Schema.Struct({ url: address }) },
/** Forgets every page, imported ones included. */
clear: {},
},
})

View file

@ -0,0 +1,57 @@
import { expect, test } from "bun:test"
import { markMatches, parseQuery } from "./match"
import { MAX_TITLE_LENGTH, MAX_URL_LENGTH, pageKey, pageTitle } from "./page"
test.each([
// One row per page: the scheme, `www.` and a trailing slash do not make another page.
["http://example.com", "example.com"],
["https://www.example.com/", "example.com"],
["https://EXAMPLE.com/Docs/", "example.com/Docs"],
["https://example.com/docs?page=2#top", "example.com/docs?page=2#top"],
["http://localhost:3000/", "localhost:3000"],
// Never kept: not a web page, credentials in the address, or too long.
["file:///home/me/notes.html", undefined],
["chrome://settings/", undefined],
["about:blank", undefined],
["javascript:alert(1)", undefined],
["workspace://ses_1/index.html", undefined],
["https://me:secret@example.com/", undefined],
["https://me@example.com/", undefined],
["not an address", undefined],
[`https://example.com/${"a".repeat(MAX_URL_LENGTH - "https://example.com/".length)}`, `example.com/${"a".repeat(MAX_URL_LENGTH - "https://example.com/".length)}`],
[`https://example.com/${"a".repeat(MAX_URL_LENGTH)}`, undefined],
])("the page of %p is %p", (url, key) => {
expect(pageKey(url)).toBe(key)
})
test("a title is trimmed and cut without splitting a character", () => {
expect(pageTitle(" Docs \n")).toBe("Docs")
const cut = pageTitle(`${"a".repeat(MAX_TITLE_LENGTH - 1)}😀 tail`)
expect(cut).toBe("a".repeat(MAX_TITLE_LENGTH - 1))
})
test.each([
["rune", ["rune"]],
[" Anom RUNE ", ["anom", "rune"]],
// People paste whole addresses: the scheme and `www.` are not what they search for.
["https://www.GitHub.com/anomalyco", ["github.com/anomalyco"]],
["https://", undefined],
[" ", undefined],
])("the words of %p are %p", (text, words) => {
expect(parseQuery(text)?.words).toEqual(words)
})
test("the matched parts of every word are marked once, in the text's own case", () => {
expect(markMatches("anomalyco/Rune-desktop", parseQuery("rune anom"))).toEqual([
{ text: "anom", match: true },
{ text: "alyco/", match: false },
{ text: "Rune", match: true },
{ text: "-desktop", match: false },
])
// Words that match overlapping text mark it once.
expect(markMatches("github", parseQuery("git thu"))).toEqual([
{ text: "githu", match: true },
{ text: "b", match: false },
])
expect(markMatches("github", undefined)).toEqual([{ text: "github", match: false }])
})

View file

@ -0,0 +1,196 @@
import { bare } from "./page"
/**
* How well a page matches a query.
* - `MISS`: a word of the query is nowhere in the page's address or title.
* - `INSIDE`: every word is there, at least one only inside a longer word.
* - `START`: every word starts a word of the title or a part of the address: the host, a host label or a path
* segment.
*/
export const MISS = 0
export const INSIDE = 1
export const START = 2
/** Stands before every word in a page's search text and in a query's words; no address or title holds it. */
const MARK = "\u0001"
const MARK_CODE = 1
const UTF16 = new TextDecoder("utf-16le")
const DAY = 86_400_000
/** One word of a query, as it is looked for in a page's search text: anywhere, and at the start of a word. */
type Term = {
readonly inside: string
/** Undefined for a word that begins with punctuation, which starts no word. */
readonly start: string | undefined
}
/**
* What the person typed, as the history is searched for it: its words in lower case, each without a web scheme or a
* leading `www.`. `prefix` is the text when it is one word, which an address may begin with.
*/
export type Query = {
readonly words: readonly string[]
readonly terms: readonly Term[]
readonly prefix: string | undefined
}
/** The query a text asks for; undefined when it holds no word to search for, such as a bare `https://`. */
export function parseQuery(text: string): Query | undefined {
const words = text
.trim()
.toLowerCase()
.split(/\s+/)
.map(bare)
.filter((word) => word.length > 0)
const single = words.length === 1 ? words[0] : undefined
if (words.length === 0) return undefined
return {
words,
terms: words.map((word) => {
const marked = mark(word)
return marked.startsWith(MARK) ? { inside: marked.slice(1), start: marked } : { inside: marked, start: undefined }
}),
prefix: single === undefined ? undefined : mark(single),
}
}
/**
* A page's address and title as a search compares them: the address without its scheme or `www.`, then the title, in
* lower case, with a mark before every word. A word begins at a letter or digit that follows none, so each host
* label and path segment is one, as is each part of `rune-desktop`. Finding a query's word then takes one pass over
* the text, and whether it starts a word is whether the mark stands before it.
*/
export function searchText(url: string, title: string) {
return mark(`${bare(url)}\n${title}`.replaceAll(MARK, "").toLowerCase())
}
/** How well a page's `searchText` matches: see `START`, `INSIDE` and `MISS`. */
export function matchQuality(query: Query, text: string) {
// Runs for every page of the history on each keystroke: plain loops, and nothing allocated.
let quality = START
for (const term of query.terms) {
const at = text.indexOf(term.inside)
if (at < 0) return MISS
// The word starts a word where the mark stands before it: at the place found, or at a later one.
if (term.start === undefined || (text.charCodeAt(at - 1) !== MARK_CODE && text.indexOf(term.start, at + 1) < 0)) quality = INSIDE
}
return quality
}
/**
* Whether a page's address begins with what was typed, so Enter may open it in place of the typed text. `text` is the
* page's `searchText`.
*/
export function completes(query: Query, text: string) {
return query.prefix !== undefined && text.startsWith(query.prefix)
}
// Written into 16-bit units and decoded once: a text built from pieces is searched far slower, and this runs for
// every page when the history opens. Every system the app runs on stores those units low byte first.
function mark(text: string) {
const units = new Uint16Array(text.length * 2)
let length = 0
let word = false
for (let at = 0; at < text.length; at++) {
const code = text.charCodeAt(at)
const letter = wordCharacter(code)
if (letter && !word) units[length++] = MARK_CODE
units[length++] = code
word = letter
}
return UTF16.decode(units.subarray(0, length))
}
/** Whether a UTF-16 code unit is part of a word: a letter or a digit of any script. Punctuation and spaces are not. */
function wordCharacter(code: number) {
if (code < 128) return (code >= 97 && code <= 122) || (code >= 48 && code <= 57) || (code >= 65 && code <= 90)
// Half of a character outside the basic plane, such as an emoji or a rarer ideograph.
if (code >= 0xd800 && code <= 0xdfff) return true
return /[\p{L}\p{N}]/u.test(String.fromCharCode(code))
}
/**
* How often and how recently a page was visited, as one number to order pages that match equally well: its
* `frequency` times its `recency`.
*/
export function frecency(visits: number, typed: number, visited: number, now: number) {
return frequency(visits, typed) * recency(visited, now)
}
/**
* How often a page was visited. It grows with the logarithm of the visits, so the hundredth visit adds less than the
* second, and a typed visit counts twice.
*/
export function frequency(visits: number, typed: number) {
return Math.log2(1 + visits + typed)
}
/**
* How recently a page was visited: 1 in the last 4 days, falling to 0.7 at 14 days, 0.5 at 31, 0.3 at 90 and 0.1 from
* a year on.
*/
export function recency(visited: number, now: number) {
const days = (now - visited) / DAY
if (days <= 4) return 1
if (days <= 14) return 0.7 + ((14 - days) * 0.3) / 10
if (days <= 31) return 0.5 + ((31 - days) * 0.2) / 17
if (days <= 90) return 0.3 + ((90 - days) * 0.2) / 59
if (days <= 365) return 0.1 + ((365 - days) * 0.2) / 275
return 0.1
}
/** Splits text around the query's words, case-insensitively, for drawing the matched parts. */
export function markMatches(text: string, query: Query | undefined) {
if (!query) return [{ text, match: false }]
const lower = text.toLowerCase()
const ranges = query.words
.flatMap((word) => {
const found: [number, number][] = []
for (let at = lower.indexOf(word); at >= 0; at = lower.indexOf(word, at + word.length)) found.push([at, at + word.length])
return found
})
.toSorted((a, b) => a[0] - b[0])
// Two words can match overlapping text, which is drawn once.
const merged: [number, number][] = []
ranges.forEach((range) => {
const last = merged.at(-1)
if (!last || range[0] > last[1]) return void merged.push(range)
last[1] = Math.max(last[1], range[1])
})
return [0, ...merged.flat(), text.length].flatMap((start, index, all) => {
const end = all[index + 1]
return end === undefined || end === start ? [] : [{ text: text.slice(start, end), match: index % 2 === 1 }]
})
}

View file

@ -0,0 +1,86 @@
/** Pages the history keeps, and the most one import brings: the most used and most recent. */
export const MAX_PAGES = 50_000
/** A longer address is not one a person returns to by typing; other browsers keep ones of many thousands. */
export const MAX_URL_LENGTH = 2_048
/** What a title is cut to; the drop-down shows far less. */
export const MAX_TITLE_LENGTH = 200
/** A page of the history: one row per page, however often and by which of its addresses it was visited. */
export type PageVisit = {
readonly url: string
readonly title: string
/** Visits in all; at least one. */
readonly visits: number
/** How many of them began in an address bar. */
readonly typed: number
/** The last visit, in Unix milliseconds. */
readonly visited: number
}
/**
* The page an address names and its host. The key is the host without `www.`, the path without a trailing slash, the
* query and the fragment, so `http`, `https`, `www.` and a trailing slash all name one page. Undefined for an
* address the history never keeps: one that is not `http(s)`, that carries a user name or a password, or that is
* longer than `MAX_URL_LENGTH`.
*/
export function webPage(url: string) {
if (url.length > MAX_URL_LENGTH || !URL.canParse(url)) return undefined
const parsed = new URL(url)
if ((parsed.protocol !== "http:" && parsed.protocol !== "https:") || parsed.username || parsed.password) return undefined
return {
key: `${parsed.host.replace(/^www\./, "")}${parsed.pathname.replace(/\/+$/, "")}${parsed.search}${parsed.hash}`,
host: parsed.hostname,
}
}
/** The key of `webPage`; undefined for an address the history never keeps. */
export function pageKey(url: string) {
return webPage(url)?.key
}
/** A title as the history keeps it: trimmed, and cut to `MAX_TITLE_LENGTH` without splitting a character. */
export function pageTitle(title: string) {
const trimmed = title.trim()
return trimmed.length > MAX_TITLE_LENGTH ? trimmed.slice(0, MAX_TITLE_LENGTH).replace(/[\uD800-\uDBFF]$/, "") : trimmed
}
/** The address without its web scheme or a leading `www.`, as people type it. */
export function bare(url: string) {
return url.replace(/^https?:\/\//i, "").replace(/^www\./i, "")
}
/**
* The address a row of the address field's list puts in the field, as Chrome fills it: without `http://` and without
* the slash that ends a bare host. `https://` stays.
*/
export function filled(url: string) {
return hostOnly(url).replace(/^http:\/\//i, "")
}
/**
* The rest of a page's address after `text`, when the address begins with it: `ub.com` for `gith` and
* `https://github.com/`. Empty when the text is the whole address; undefined when the address does not begin with
* it, or the text holds a space. The text may leave out the scheme and a leading `www.`, as people type an address,
* and its case does not count.
*/
export function completion(text: string, url: string) {
if (!text || /\s/.test(text)) return undefined
const typed = text.toLowerCase()
// The slash that ends a bare host is not completed, yet a text that types it is still the whole address.
const shown = [hostOnly(url), url]
.flatMap((whole) => [bare(whole), whole.replace(/^https?:\/\//i, ""), whole])
.find((form) => form.toLowerCase().startsWith(typed))
return shown?.slice(text.length)
}
/** The address without the slash that ends a bare host, which nobody types. */
function hostOnly(url: string) {
return url.replace(/^([a-z][a-z\d+.-]*:\/\/[^/?#]+)\/$/i, "$1")
}

View file

@ -0,0 +1,209 @@
import { completes, frequency, matchQuality, MISS, parseQuery, recency, searchText, START, type Query } from "./match"
import { bare, type PageVisit } from "./page"
/** A page the address field may suggest, as a search returns it. */
export type FoundPage = {
readonly url: string
readonly title: string
/**
* How often and how recently it was visited; see `frecency`. For a site's front page that answers a typed host, the
* sum over the site's pages that begin with what was typed.
*/
readonly score: number
}
/** A page's address and title as they are shown, which the index does not hold. */
type Shown = { readonly url: string; readonly title: string }
export type PageIndex = ReturnType<typeof createPageIndex>
/** A page as a search reads it: its `searchText`, its host and its visits. */
type Entry = {
readonly id: number
readonly text: string
/** The host as the address shows it: in lower case, without `www.`, with its port. */
readonly host: string
/** Its `frequency`, which changes only with a visit. */
readonly frequency: number
readonly visited: number
}
/** A page a search found: how well it matches (see `matchQuality`) and its `frecency`. */
export type Found = { readonly id: number; readonly quality: number; readonly score: number }
/**
* The host a typed text most likely begins: among the hosts with a page whose address begins with it, the one whose
* such pages have the most frecency in sum, which is `score`, and the best of those pages.
*/
export type FoundHost = { readonly host: string; readonly score: number; readonly page: number }
/** A host's sum while a search runs; `best` is the frecency of `page`. */
type HostSum = { host: string; score: number; page: number; best: number }
/**
* Every page of the history in memory, in the form a search compares, so a keystroke costs one pass over them and no
* database read. The store keeps it in step with the database; it holds no address or title as they are shown.
*/
export function createPageIndex() {
const entries: Entry[] = []
// Where each page is in `entries`, by its id.
const slots = new Map<number, number>()
// Each host once, however many pages it has: a host cut from an address would keep that whole address in memory.
const hosts = new Map<string, string>()
const hostOf = (url: string) => {
const address = bare(url).toLowerCase()
const end = address.search(/[/?#]/)
const host = end < 0 ? address : address.slice(0, end)
const known = hosts.get(host)
if (known === undefined) hosts.set(host, host)
return known ?? host
}
const remove = (id: number) => {
const slot = slots.get(id)
const last = entries.pop()
if (slot === undefined || !last) return
slots.delete(id)
// The last page takes the removed one's place, so the list has no holes.
if (last.id === id) return
entries[slot] = last
slots.set(last.id, slot)
}
return {
size: () => entries.length,
set(id: number, page: PageVisit) {
const entry: Entry = {
id,
text: searchText(page.url, page.title),
host: hostOf(page.url),
frequency: frequency(page.visits, page.typed),
visited: page.visited,
}
const slot = slots.get(id)
if (slot !== undefined) return void (entries[slot] = entry)
slots.set(id, entries.length)
entries.push(entry)
},
remove,
clear() {
entries.length = 0
slots.clear()
hosts.clear()
},
/**
* The `limit` pages that match best: by how well they match, then by frecency, then the most recent, then the
* one the history has had longest. When the query may begin a host, also the host it most likely begins.
*/
search(query: Query, limit: number, now: number) {
const top: (Found & { readonly entry: Entry })[] = []
const sums = query.words.length === 1 && !/[/?#]/.test(query.words[0] ?? "") ? new Map<string, HostSum>() : undefined
// Runs on each keystroke over every page: a plain loop, and an allocation only for a page that enters the top.
for (const entry of entries) {
const quality = matchQuality(query, entry.text)
if (quality === MISS) continue
const score = entry.frequency * recency(entry.visited, now)
if (sums && completes(query, entry.text)) {
const known = sums.get(entry.host)
if (!known) sums.set(entry.host, { host: entry.host, score, page: entry.id, best: score })
if (known) {
known.score += score
if (score > known.best) {
known.page = entry.id
known.best = score
}
}
}
const worst = top.length === limit ? top[limit - 1] : undefined
// Most pages that match fall below the top, on these two numbers alone.
if (worst && (quality < worst.quality || (quality === worst.quality && score < worst.score))) continue
if (worst && !before(quality, score, entry, worst)) continue
const at = top.findIndex((item) => before(quality, score, entry, item))
top.splice(at < 0 ? top.length : at, 0, { id: entry.id, quality, score, entry })
if (top.length > limit) top.pop()
}
const host = sums
? [...sums.values()].reduce<HostSum | undefined>((best, item) => (!best || item.score > best.score ? item : best), undefined)
: undefined
return {
pages: top.map((item): Found => ({ id: item.id, quality: item.quality, score: item.score })),
host: host ? ({ host: host.host, score: host.score, page: host.page } satisfies FoundHost) : undefined,
}
},
/** The ids of the pages to drop so that `keep` remain: the ones visited least and longest ago. */
least(keep: number, now: number) {
if (entries.length <= keep) return []
return entries
.map((entry) => ({ id: entry.id, score: entry.frequency * recency(entry.visited, now), visited: entry.visited }))
.toSorted((a, b) => a.score - b.score || a.visited - b.visited)
.slice(0, entries.length - keep)
.map((item) => item.id)
},
}
}
function before(quality: number, score: number, entry: Entry, other: Found & { readonly entry: Entry }) {
if (quality !== other.quality) return quality > other.quality
if (score !== other.score) return score > other.score
if (entry.visited !== other.entry.visited) return entry.visited > other.entry.visited
return entry.id < other.entry.id
}
/**
* The `limit` pages that match what the person typed, best first: see `matchQuality` and `frecency`. Text that
* begins a host also finds that site's front page, whether or not it was ever visited itself, with the frecency of
* all the site's pages that begin so: the address the field completes to when the site is the best match. `shown`
* reads a page's address and title by its id, and `front` the page whose key is a host, if the history has it.
*/
export function findPages(
index: PageIndex,
text: string,
limit: number,
now: number,
read: { readonly shown: (id: number) => Shown | undefined; readonly front: (host: string) => Shown | undefined },
): FoundPage[] {
const query = parseQuery(text)
if (!query) return []
const found = index.search(query, limit, now)
const pages = found.pages.flatMap((item) => {
const page = read.shown(item.id)
return page ? [{ url: page.url, title: page.title, score: item.score, quality: item.quality }] : []
})
const result = (page: FoundPage): FoundPage => ({ url: page.url, title: page.title, score: page.score })
const best = found.host ? read.shown(found.host.page) : undefined
if (!found.host || !best) return pages.map(result)
const front = read.front(found.host.host)
const site = { url: front?.url ?? `${new URL(best.url).origin}/`, title: front?.title ?? "", score: found.host.score, quality: START }
const rest = pages.filter((page) => page.url !== site.url)
const at = rest.findIndex((page) => page.quality < START || page.score <= site.score)
return rest.toSpliced(at < 0 ? rest.length : at, 0, site).slice(0, limit).map(result)
}

View file

@ -0,0 +1,273 @@
import { afterEach, beforeEach, describe, expect, setSystemTime, test } from "bun:test"
import { mkdtemp, readFile, rm } from "node:fs/promises"
import { tmpdir } from "node:os"
import path from "node:path"
import type { BuiltinMainStorage, MainStoreFrom } from "@opencode/plugin/gui/builtin"
import { earlierVisits } from "./earlier"
import { MAX_PAGES, type PageVisit } from "./page"
import { createHistoryStore, type HistoryStore } from "./store"
const NOW = Date.parse("2026-11-20T12:00:00Z")
const DAY = 86_400_000
const page = (url: string, title: string, visits: number, days: number, typed = 0): PageVisit => ({
url,
title,
visits,
typed,
visited: NOW - days * DAY,
})
const rune = "https://github.com/anomalyco/rune-desktop"
const opencode = "https://github.com/anomalyco/opencode"
const opentui = "https://github.com/sst/opentui"
const essence = "https://runescape.wiki/w/Rune_essence"
const pruned = "https://example.com/blog/pruned-trees"
const keynote = "https://www.youtube.com/watch?v=abc"
const dashboard = "http://localhost:3000/dashboard"
const seeded = [
page(rune, "anomalyco/rune-desktop: Rune for the desktop", 40, 1, 2),
page(opencode, "anomalyco/opencode: The open source coding agent", 120, 0, 5),
page(opentui, "sst/opentui", 30, 3),
page(essence, "Rune essence - The RuneScape Wiki", 3, 200),
page(pruned, "Pruned trees", 500, 0),
page("https://gitlab.com/group/project", "Project · GitLab", 4, 20),
page("https://news.ycombinator.com/item?id=1", "Show HN: Anomaly detection in Rust", 60, 1),
page(dashboard, "Dashboard", 10, 0),
page(keynote, "GitHub Universe keynote - YouTube", 25, 2),
]
const opened: { directory: string; store: HistoryStore }[] = []
async function open(directory?: string) {
const store = createHistoryStore({ directory: directory ?? (await mkdtemp(path.join(tmpdir(), "browser-history-"))) })
opened.push({ directory: directory ?? "", store })
return store
}
const addresses = (store: HistoryStore, text: string, limit = 8) => store.search(text, limit).map((found) => found.url)
beforeEach(() => {
setSystemTime(new Date(NOW))
})
afterEach(async () => {
setSystemTime()
opened.forEach((item) => item.store.close())
// Bun's node:sqlite shim can keep the write-ahead log open on Windows after close(); the leftover is only here.
await Promise.all(opened.splice(0).map((item) => (item.directory ? rm(item.directory, { recursive: true, force: true }).catch(() => undefined) : undefined)))
})
describe("what the address field finds", () => {
test.each([
// A word that starts a path segment or a title word comes before one found only inside a longer word, however
// often that page was visited; a host that begins so brings its front page.
["rune", [rune, "https://runescape.wiki/", essence, pruned]],
["anom rune", [rune]],
["rune anom", [rune]],
// The typed text begins a host: its front page leads with the visits of all its pages, then pages by how often
// and how recently they were visited, whether the address or only the title matches.
["gith", ["https://github.com/", opencode, rune, opentui, keynote]],
["GITH", ["https://github.com/", opencode, rune, opentui, keynote]],
["github.com/anomalyco/ru", [rune]],
["https://github.com/sst", [opentui]],
["desktop", [rune]],
// Inside a word only: by visits and recency.
["hub", [opencode, rune, opentui, keynote]],
// The front page keeps the scheme and the port of the pages visited.
["local", ["http://localhost:3000/", dashboard]],
["nothing-like-this", []],
[" ", []],
["https://", []],
])("%p finds %p", async (text, expected) => {
const store = await open()
store.add(seeded)
expect(addresses(store, text)).toEqual(expected)
})
test("a limit keeps the best, and a typed visit counts more than a plain one", async () => {
const store = await open()
store.add([page("https://a.test/docs", "Docs", 3, 0), page("https://b.test/docs", "Docs", 3, 0, 3), page("https://c.test/docs", "Docs", 2, 0)])
expect(addresses(store, "docs", 2)).toEqual(["https://b.test/docs", "https://a.test/docs"])
// A full list still makes way for a better match that was visited less.
store.add([page(pruned, "Pruned trees", 500, 0), page("https://example.com/blog/rune-notes", "Notes", 2, 0)])
expect(addresses(store, "rune", 1)).toEqual(["https://example.com/blog/rune-notes"])
})
test("an old page gives way to one visited as often lately", async () => {
const store = await open()
store.add([page("https://old.test/guide", "Guide", 10, 300), page("https://new.test/guide", "Guide", 10, 2)])
expect(addresses(store, "guide")).toEqual(["https://new.test/guide", "https://old.test/guide"])
})
})
test("the addresses of one page are one row, with the visits of all and the latest address and title", async () => {
const store = await open()
expect(
store.add([
page("http://www.example.org/docs/", "Old docs", 2, 30),
page("https://example.org/docs", "Docs", 5, 1, 1),
page("https://example.org/docs/", "", 1, 0),
page("ftp://example.org/docs", "Not a web page", 9, 0),
page("https://me:secret@example.org/private", "Credentials", 9, 0),
]),
).toBe(1)
expect(store.size()).toBe(1)
expect(store.search("docs", 8)).toEqual([{ url: "https://example.org/docs/", title: "Docs", score: Math.log2(1 + 8 + 1) }])
// Importing the same profile again changes nothing.
store.add([page("https://example.org/docs", "Docs", 5, 1, 1)])
expect(store.search("docs", 8)[0]?.score).toBe(Math.log2(1 + 8 + 1))
})
test("a visit here counts on the page's row, and its title arrives later without counting", async () => {
const store = await open()
store.visit("https://example.org/docs", "")
store.retitle("https://example.org/docs", "Docs")
store.visit("http://www.example.org/docs/", "")
store.visit("file:///home/me/notes.html", "Notes")
store.visit("https://me:secret@example.org/private", "Private")
expect(store.size()).toBe(1)
expect(store.search("docs", 8)).toEqual([{ url: "http://www.example.org/docs/", title: "Docs", score: Math.log2(3) }])
})
test("the pages a window kept before the store existed come over once, web pages only", async () => {
const store = await open()
store.visit("https://kept.test/", "Visited here")
store.adopt(() => [
{ url: "https://newest.test/", title: "Newest" },
{ url: "file:///home/me/notes.html", title: "Notes" },
{ url: "workspace://ses_1/index.html", title: "Preview" },
{ url: "https://kept.test/", title: "From the window" },
{ url: "https://oldest.test/", title: "Oldest" },
])
expect(store.size()).toBe(3)
// The list's order stands in for the visits' times, and a page the store already has keeps its own row.
expect(store.search("test", 8).map((found) => found.title)).toEqual(["Visited here", "Newest", "Oldest"])
store.remove("https://newest.test/")
store.adopt(() => [{ url: "https://newest.test/", title: "Newest" }, { url: "https://later.test/", title: "Later" }])
expect(addresses(store, "test")).toEqual(["https://kept.test/", "https://oldest.test/"])
})
test.each([
["opencode.global.dat\nplugin.browser.history"],
// Where builds before the plugin rename kept the list.
["opencode.global.dat\nextension.browser.history"],
])("the windows' list is read from %p, where every window stores it, and stays theirs", (home) => {
const listed = { visits: [{ url: "https://kept.test/", title: "Kept", icon: "data:image/png;base64,AAAA" }] }
const removed: [string, boolean][] = []
const storage = {
// As main storage answers: the first older home that holds a value, else the initial one.
store: (_key: string, options: { initial: typeof listed; from?: MainStoreFrom | readonly MainStoreFrom[] }) => ({
value: [options.from ?? []].flat().some((from) => "state" in from && from.state.join("\n") === home) ? listed : options.initial,
}),
remove: (key: string, options?: { from?: MainStoreFrom | readonly MainStoreFrom[] }) => void removed.push([key, options?.from !== undefined]),
}
// SAFETY: `earlierVisits` calls only `store`, reading its value, and `remove`, which the object above implements.
// oxlint-disable-next-line anti-slop/no-chained-type-assertions -- see SAFETY above
expect(earlierVisits(storage as unknown as BuiltinMainStorage)).toEqual(listed.visits)
// Main's own copy goes; removing it names no older home, which would delete the windows' list with it.
expect(removed).toEqual([["history.earlier", false]])
})
test("the history is on disk: another start finds the same pages", async () => {
const directory = await mkdtemp(path.join(tmpdir(), "browser-history-"))
const first = await open(directory)
first.add(seeded)
first.adopt(() => [])
const before = first.search("gith", 8)
first.close()
opened.pop()
const second = await open(directory)
expect(second.search("gith", 8)).toEqual(before)
// The window's earlier pages were taken over by the first start.
second.adopt(() => [{ url: "https://late.test/", title: "Late" }])
expect(second.search("late", 8)).toEqual([])
})
test("removing a page forgets it, and clearing forgets every page and leaves none in the file", async () => {
const directory = await mkdtemp(path.join(tmpdir(), "browser-history-"))
const store = await open(directory)
store.add([...seeded, page("https://zebra-marker.test/stripes", "Zebra marker stripes", 4, 0)])
const stored = async () => {
const files = await Promise.all(["history.sqlite", "history.sqlite-wal"].map((name) => readFile(path.join(directory, name)).catch(() => Buffer.alloc(0))))
return Buffer.concat(files).toString("latin1")
}
expect(await stored()).toContain("zebra-marker")
store.remove("http://www.github.com/anomalyco/rune-desktop/")
expect(addresses(store, "rune")).toEqual(["https://runescape.wiki/", essence, pruned])
store.clear()
expect(store.size()).toBe(0)
expect(store.search("zebra", 8)).toEqual([])
const after = await stored()
expect(after).not.toContain("zebra-marker")
expect(after).not.toContain("Zebra marker")
})
test(
"keeps at most 50,000 pages: the ones visited least and longest ago go",
async () => {
const directory = await mkdtemp(path.join(tmpdir(), "browser-history-"))
const store = await open(directory)
const extra = 5
const many = Array.from({ length: MAX_PAGES + extra }, (_, position) =>
page(`https://site-${position}.test/page`, `Page ${position}`, 1, position / 1000),
)
// An old page visited often outlasts newer pages visited once.
expect(store.add([...many, page("https://often.test/", "Often", 400, 300)])).toBe(MAX_PAGES + extra + 1)
expect(store.size()).toBe(MAX_PAGES)
expect(addresses(store, "often.test")).toEqual(["https://often.test/"])
expect(addresses(store, "site-0.test")).toEqual(["https://site-0.test/", "https://site-0.test/page"])
expect(addresses(store, `site-${MAX_PAGES + extra - 1}.test`)).toEqual([])
expect(addresses(store, `site-${MAX_PAGES - 2}.test`)).toEqual([`https://site-${MAX_PAGES - 2}.test/`, `https://site-${MAX_PAGES - 2}.test/page`])
// A visit to a full history makes room and is kept.
store.visit("https://fresh.test/", "Fresh")
expect(store.size()).toBeLessThanOrEqual(MAX_PAGES)
expect(addresses(store, "fresh")).toEqual(["https://fresh.test/"])
store.add(Array.from({ length: 600 }, (_, position) => page(`https://refill-${position}.test/`, "Refill", 2, 0)))
expect(store.size()).toBe(MAX_PAGES)
store.close()
opened.pop()
// After a start, a visit only writes its row: the full history is not read to make room until the address field
// is about to search it.
const again = await open(directory)
again.visit("https://startup.test/", "Startup")
expect(again.size()).toBe(MAX_PAGES + 1)
again.prepare()
expect(again.size()).toBeLessThanOrEqual(MAX_PAGES)
expect(addresses(again, "startup")).toEqual(["https://startup.test/"])
},
// Writes 50,000 rows.
30_000,
)

View file

@ -0,0 +1,272 @@
import { mkdirSync } from "node:fs"
import { rm } from "node:fs/promises"
import path from "node:path"
import { DatabaseSync } from "node:sqlite"
import { MAX_PAGES, pageKey, pageTitle, type PageVisit } from "./page"
import { createPageIndex, findPages, type PageIndex } from "./search"
export type HistoryStore = ReturnType<typeof createHistoryStore>
type Row = { id: number; url: string; title: string; visits: number; typed: number; visited: number }
/** Every page as a search compares it, once the first search or a full store needed it. */
type Loaded = { index?: PageIndex }
/** How many pages a full store drops at once, so that a visit seldom has to make room. */
const ROOM = 500
const FILE = "history.sqlite"
/**
* Deletes a history store's file, with its write-ahead log: what clearing comes to for a store that cannot be opened
* or cleared, as one whose file is damaged. The store must be closed. Rejects while any of the files stays.
*/
export async function removeHistoryStore(directory: string) {
// Windows refuses to delete a file a scanner holds open for a moment, so each is tried once more.
await Promise.all(
["", "-wal", "-shm", "-journal"].map((suffix) => rm(path.join(directory, `${FILE}${suffix}`), { force: true, maxRetries: 1, retryDelay: 200 })),
)
}
/**
* The browsing history on this computer: one row per page (see `pageKey`) in a SQLite file of the app's own data. It
* holds the pages visited here and the pages imported from other browsers, at most `MAX_PAGES`; past that the ones
* visited least and longest ago go. The first search reads every page into memory, in the form a search compares, and
* the store keeps that index in step from then on; a visit before it only writes its row, so a page that loads as the
* app starts costs no read of the history. Nothing here leaves the main process but the few pages a search returns to
* a window.
*/
export function createHistoryStore(input: { readonly directory: string }) {
mkdirSync(input.directory, { recursive: true, mode: 0o700 })
const db = new DatabaseSync(path.join(input.directory, FILE))
// `secure_delete` overwrites what a delete frees, so a cleared history is not left in the file's unused pages.
const schema = `
PRAGMA journal_mode = WAL;
PRAGMA synchronous = NORMAL;
PRAGMA secure_delete = ON;
CREATE TABLE IF NOT EXISTS pages (
id INTEGER PRIMARY KEY,
key TEXT NOT NULL UNIQUE,
url TEXT NOT NULL,
title TEXT NOT NULL,
visits INTEGER NOT NULL,
typed INTEGER NOT NULL,
visited INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL) WITHOUT ROWID;
`
// A file that is not a database fails at its first statement, which has no form that does not throw. The file is
// let go before the failure goes on, so that it can be deleted.
try {
db.exec(schema)
} catch (cause) {
db.close()
throw cause
}
const columns = "id, url, title, visits, typed, visited"
const byID = db.prepare(`SELECT ${columns} FROM pages WHERE id = ?`)
const byKey = db.prepare(`SELECT ${columns} FROM pages WHERE key = ?`)
const drop = db.prepare("DELETE FROM pages WHERE id = ?")
// A visit here: the page's count goes up, and the address and title are the ones just seen.
const visited = db.prepare(`
INSERT INTO pages (key, url, title, visits, typed, visited) VALUES (?, ?, ?, 1, 0, ?)
ON CONFLICT (key) DO UPDATE SET
url = excluded.url,
title = CASE WHEN excluded.title = '' THEN title ELSE excluded.title END,
visits = visits + 1,
visited = excluded.visited
RETURNING ${columns}`)
// A page of another browser: counts are the larger of the two, so importing a profile again adds nothing, and the
// address and title are those of the later visit.
const merged = db.prepare(`
INSERT INTO pages (key, url, title, visits, typed, visited) VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT (key) DO UPDATE SET
url = CASE WHEN excluded.visited >= visited THEN excluded.url ELSE url END,
title = CASE WHEN excluded.title != '' AND (excluded.visited >= visited OR title = '') THEN excluded.title ELSE title END,
visits = max(visits, excluded.visits),
typed = max(typed, excluded.typed),
visited = max(visited, excluded.visited)
RETURNING ${columns}`)
// A page the window kept before this store existed: only where the store has no row for it.
const adopted = db.prepare(`
INSERT INTO pages (key, url, title, visits, typed, visited) VALUES (?, ?, ?, 1, 0, ?)
ON CONFLICT (key) DO NOTHING
RETURNING ${columns}`)
const titled = db.prepare("UPDATE pages SET title = ? WHERE id = ?")
const counted = db.prepare("SELECT count(*) AS pages FROM pages")
const loaded: Loaded = {}
// SAFETY: the statements above name the columns of `pages`, which this module alone creates and writes, in `Row`'s
// types; a statement that returns no row returns undefined.
const row = (value: ReturnType<typeof byID.get>) => value as Row | undefined
const index = () => {
if (loaded.index) return loaded.index
const created = createPageIndex()
// SAFETY: as `row`, for every row of the table.
const stored = db.prepare(`SELECT ${columns} FROM pages`).all() as Row[]
stored.forEach((page) => created.set(page.id, page))
loaded.index = created
return created
}
// SQLite has no transaction that ends by itself: a write that throws must be rolled back, or the next one fails.
const transaction = <T>(run: () => T) => {
db.exec("BEGIN")
try {
const result = run()
db.exec("COMMIT")
return result
} catch (cause) {
db.exec("ROLLBACK")
throw cause
}
}
// Drops the pages visited least and longest ago, so that `room` fewer than the limit remain. Which pages those
// are is the index's to say.
const prune = (room: number) => {
const pages = index()
const least = pages.least(MAX_PAGES - room, Date.now())
if (least.length === 0) return
transaction(() => least.forEach((id) => drop.run(id)))
least.forEach(pages.remove)
}
const keep = (value: ReturnType<typeof byID.get>) => {
const page = row(value)
if (page) loaded.index?.set(page.id, page)
}
// SAFETY: `count(*)` is one row with one integer.
const size = () => loaded.index?.size() ?? (counted.get() as { pages: number }).pages
return {
/** How many pages the history holds. */
size,
/**
* Reads the history into memory, which the first search otherwise does: a tenth of a second for a full history.
* Visits before it wrote their rows without reading the history, so they made no room, and this does.
*/
prepare() {
if (!loaded.index && index().size() > MAX_PAGES) prune(ROOM)
},
/** The `limit` pages that match what the person typed, best first; see `findPages`. */
search(text: string, limit: number) {
if (!loaded.index && index().size() > MAX_PAGES) prune(ROOM)
return findPages(index(), text, limit, Date.now(), { shown: (id) => row(byID.get(id)), front: (host) => row(byKey.get(host)) })
},
/** Records a visit to a page here. An address the history never keeps is ignored. */
visit(url: string, title: string) {
const key = pageKey(url)
if (!key) return
keep(visited.get(key, url, pageTitle(title), Date.now()))
// A full store makes room, once a search has read it; until then a visit only writes its row.
if (loaded.index && loaded.index.size() > MAX_PAGES) prune(ROOM)
},
/** Gives a page its title once the page has reported it; not a visit. */
retitle(url: string, title: string) {
const key = pageKey(url)
const page = key ? row(byKey.get(key)) : undefined
const next = pageTitle(title)
if (!page || !next || next === page.title) return
titled.run(next, page.id)
loaded.index?.set(page.id, { ...page, title: next })
},
/**
* Adds another browser's pages, each merged into the row of the page it names. Returns how many pages came: the
* distinct pages among those the history keeps.
*/
add(pages: readonly PageVisit[]) {
const now = Date.now()
const distinct = new Map<string, PageVisit>()
pages.forEach((page) => {
const key = pageKey(page.url)
if (!key || page.visits < 1) return
const known = distinct.get(key)
const next = { ...page, title: pageTitle(page.title), visited: Math.min(page.visited, now) }
// Two addresses of one page, such as its http and https forms, are one row with the visits of both.
distinct.set(
key,
known
? {
url: next.visited >= known.visited ? next.url : known.url,
title: (next.visited >= known.visited ? next.title : known.title) || known.title || next.title,
visits: known.visits + next.visits,
typed: known.typed + next.typed,
visited: Math.max(known.visited, next.visited),
}
: next,
)
})
transaction(() =>
distinct.forEach((page, key) => keep(merged.get(key, page.url, page.title, page.visits, page.typed, page.visited))),
)
if (size() > MAX_PAGES) prune(0)
return distinct.size
},
/**
* Takes over the pages the windows kept before this store existed, newest first, once: `read` is asked for them
* only the first time, so a page the person removed since does not come back.
*/
adopt(read: () => readonly { readonly url: string; readonly title: string }[]) {
if (db.prepare("SELECT 1 FROM meta WHERE key = 'adopted'").get()) return
const now = Date.now()
transaction(() => {
read().forEach((visit, position) => {
const key = pageKey(visit.url)
// The list has no times: its order stands in for them.
if (key) keep(adopted.get(key, visit.url, pageTitle(visit.title), now - position))
})
db.prepare("INSERT INTO meta (key, value) VALUES ('adopted', '1')").run()
})
if (size() > MAX_PAGES) prune(0)
},
/** Forgets one page. */
remove(url: string) {
const key = pageKey(url)
const page = key ? row(byKey.get(key)) : undefined
if (!page) return
drop.run(page.id)
loaded.index?.remove(page.id)
},
/** Forgets every page, and leaves none of them in the file. */
clear() {
db.exec("DELETE FROM pages")
loaded.index?.clear()
// The rows are overwritten in the file; the write-ahead log still holds them until it is folded in and emptied.
db.exec("VACUUM")
db.exec("PRAGMA wal_checkpoint(TRUNCATE)")
},
close() {
db.close()
},
}
}

View file

@ -0,0 +1,51 @@
import type { HistoryPage } from "./ipc"
import { matchQuality, MISS, parseQuery, searchText } from "./match"
import { completion, pageKey } from "./page"
import type { Visit } from "./visits"
/** How many pages the address field asks main for: a few more than it lists, as the window's own pages join them. */
export const HISTORY_ANSWER = 8
/**
* A page the address field suggests. `completion` is the rest of its address after what was typed: empty when the
* text is the whole address, undefined when the address does not begin with it.
*/
export type Suggestion = Visit & { readonly completion: string | undefined }
/**
* The pages the address field lists for what the person typed, best first: by how well each matches, then by how
* often and how recently it was visited. `answer` is main's last answer, which may be to an earlier text, so each of
* its pages is matched again and narrows at once; `visits` is the window's list of the last pages, newest first,
* which answers before main does, adds what main never keeps (files, previews, artifacts) and gives a page its icon.
*/
export function suggestPages(text: string, visits: readonly Visit[], answer: readonly HistoryPage[], limit: number): Suggestion[] {
const query = parseQuery(text)
if (!query) return []
// A page with no key is one main never keeps, which only its own address names.
const key = (visit: Visit) => pageKey(visit.url) ?? `${visit.url}\n${visit.session ?? ""}`
const listed = new Map(visits.map((visit) => [key(visit), visit]))
const answered = new Set(answer.map((page) => pageKey(page.url)))
const candidates = [
...answer.map((page) => {
const known = listed.get(pageKey(page.url) ?? "")
const visit: Visit = { url: page.url, title: page.title || known?.title || "" }
// An imported page has no icon; one the window showed lately lends its own.
return { visit: known?.icon ? { ...visit, icon: known.icon } : visit, score: page.score }
}),
// A page of the window's list that main did not answer with counts as visited once, the newest the most recent.
...visits.flatMap((visit, position) => (answered.has(pageKey(visit.url) ?? "") ? [] : [{ visit, score: 1 - position / 1000 }])),
]
return candidates
.flatMap((candidate) => {
const quality = matchQuality(query, searchText(candidate.visit.url, candidate.visit.title))
return quality === MISS ? [] : [{ ...candidate, quality }]
})
.toSorted((a, b) => b.quality - a.quality || b.score - a.score)
.slice(0, limit)
.map((found) => ({ ...found.visit, completion: completion(text.trimStart(), found.visit.url) }))
}

View file

@ -1,6 +1,6 @@
import { Schema } from "effect"
/** A page the browser showed, newest first in the history. */
/** A page the browser showed, newest first in the window's list of the last pages. */
export const Visit = Schema.Struct({
url: Schema.String,
title: Schema.String,
@ -16,7 +16,10 @@ export const History = Schema.Struct({ visits: Schema.Array(Visit) })
export type History = typeof History.Type
/** Visits the history keeps; the new tab page shows the first few. */
/**
* Visits the window's list keeps; the new tab page shows the first few, and their icons draw in the address field's
* suggestions. The history itself, with every page and the pages imported from other browsers, is main's (`store.ts`).
*/
const MAX_VISITS = 30
/** Icons larger than this stay out of the stored history; a 32px PNG is a few kilobytes. */
@ -54,55 +57,3 @@ export function withIcon(visits: readonly Visit[], url: string, icon: string) {
function storable(icon: string | undefined) {
return icon && icon.length <= MAX_STORED_ICON ? icon : undefined
}
/**
* Visits whose address or title contains the query, case-insensitively. Addresses that begin with the query come
* first, as the address field completes them; within each group the newest visit leads.
*/
export function suggest(visits: readonly Visit[], query: string, limit: number) {
const needle = query.trim().toLowerCase()
if (!needle) return []
const matches = visits.filter(
(visit) => bare(visit.url).toLowerCase().includes(needle) || visit.title.toLowerCase().includes(needle),
)
return [
...matches.filter((visit) => completes(visit, needle)),
...matches.filter((visit) => !completes(visit, needle)),
].slice(0, limit)
}
/** Whether the visit's address begins with what the user typed, so Enter may open it in place of the typed text. */
export function completes(visit: Visit, query: string) {
const needle = query.trim().toLowerCase()
return !!needle && bare(visit.url).toLowerCase().startsWith(needle)
}
/** Splits text around case-insensitive matches of the query, for drawing the matched parts. */
export function highlight(text: string, query: string) {
const needle = query.trim().toLowerCase()
if (!needle) return [{ text, match: false }]
const lower = text.toLowerCase()
const starts = Array.from(lower.matchAll(new RegExp(escape(needle), "g")), (found) => found.index)
const bounds = starts.flatMap((start) => [start, start + needle.length])
return [0, ...bounds, text.length].flatMap((start, index, all) => {
const end = all[index + 1]
return end === undefined || end === start ? [] : [{ text: text.slice(start, end), match: index % 2 === 1 }]
})
}
/** The address without its web scheme or a leading `www.`, as people type it. */
export function bare(url: string) {
return url.replace(/^https?:\/\//i, "").replace(/^www\./i, "")
}
function escape(text: string) {
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
}

View file

@ -20,6 +20,7 @@ export default {
"tab.new": "New tab",
"address.label": "Browser address",
"address.search": "Search or enter address",
"address.search.web": "Google Search",
"address.suggestions": "Suggestions",
"refused.web": "Only web pages can open here.",
"refused.scheme": "This link opens another app:",
@ -112,6 +113,7 @@ export default {
"viewport.fitFailed": "Couldn’t fit the preview. Use the pane size or try different dimensions.",
"link.copy": "Copy link",
"history.clear": "Clear history",
"history.clear.failed": "Couldn't clear the history. Try again.",
"extensions.menu": "Extensions",
"extensions.manage": "Manage extensions",
"extensions.added": "Added {{name}}.",
@ -146,9 +148,8 @@ export default {
"extensions.failed.manifest": "This is not a supported extension.",
"extensions.failed.download": "The store did not provide this extension. Check the link.",
"extensions.failed.load": "The extension could not load: {{message}}",
"signins.title": "Bring your sign-ins",
"signins.description": "Copy your sign-ins from a browser on this computer, so sites such as GitHub open already signed in.",
"signins.bar": "Already signed in somewhere else? Bring your sign-ins here.",
"signins.title": "Bring your sign-ins and history",
"signins.bar": "Bring your sign-ins and history from {{browser}}",
"signins.import": "Import from {{browser}}",
"signins.action": "Import",
"signins.other": "Import from another browser",
@ -159,16 +160,12 @@ export default {
"signins.imported.other": "Imported {{count}} cookies.",
"signins.imported.incomplete.one": "Imported {{count}} cookie. Not imported: {{omitted}}.",
"signins.imported.incomplete.other": "Imported {{count}} cookies. Not imported: {{omitted}}.",
"signins.imported.from.one": "Imported {{count}} cookie from {{browser}}",
"signins.imported.from.other": "Imported {{count}} cookies from {{browser}}",
"signins.imported.partial.one":
"Imported {{count}} cookie. This browser keeps {{protected}} more locked so that only it can read them. Sign in to those sites here.",
"signins.imported.partial.other":
"Imported {{count}} cookies. This browser keeps {{protected}} more locked so that only it can read them. Sign in to those sites here.",
"signins.imported.partial.named.one":
"Imported {{count}} cookie. {{browser}} keeps {{protected}} more locked so that only it can read them. Sign in to those sites here.",
"signins.imported.partial.named.other":
"Imported {{count}} cookies. {{browser}} keeps {{protected}} more locked so that only it can read them. Sign in to those sites here.",
"signins.imported.from": "Imported sign-ins from {{browser}}",
"signins.imported.history.from": "Imported sign-ins and history from {{browser}}",
"signins.imported.history.only.from": "Imported history from {{browser}}",
"signins.imported.none.from": "Nothing was imported from {{browser}}.",
"signins.imported.partial": "Imported. Some sites will ask you to sign in again.",
"signins.imported.partial.named": "Imported from {{browser}}. Some sites will ask you to sign in again.",
"signins.protected":
"This browser keeps its sign-ins locked so that only it can read them. Sign in to your sites here.",
"signins.protected.named":
@ -198,25 +195,19 @@ export default {
"settings.remote.title": "Share sign-ins with remote servers",
"settings.remote.description":
"Remote servers can use your sign-ins: their pages open signed in to your sites, and those sites can change your sign-ins on this device. Turn this on only for servers you trust.",
"settings.import.title": "Import sign-ins",
"settings.import.note": "Copies cookies only. The other browser keeps its own.",
"settings.import.title": "Import from another browser",
"settings.import.none": "No other browser found on this computer",
"settings.import.choose": "Choose sites",
"sites.description": "Brings the sign-ins of only the sites you select.",
"sites.profile": "Browser profile",
"sites.search": "Search sites",
"sites.list": "Sites",
"sites.selected": "{{selected}} of {{total}} selected",
"sites.selected.shown": "{{shown}} shown, {{selected}} selected",
"sites.order.recent": "The sites used most recently come first.",
"sites.order.name": "The sites are in alphabetical order.",
"sites.missing": "No sign-in for {{site}} was found in {{browser}}.",
"sites.all": "Select all",
"sites.none": "Select none",
"sites.all.shown": "Select {{count}} shown",
"sites.none.shown": "Deselect {{count}} shown",
"sites.cookies.one": "{{number}} cookie",
"sites.cookies.other": "{{number}} cookies",
"sites.loading": "Reading the sites in {{browser}}…",
"sites.empty": "This profile has no sites to import.",
"sites.unmatched": "No site matches your search.",
@ -250,6 +241,7 @@ export default {
"settings.cookies.count.other": "{{count}} cookies. Every session uses the same sign-ins.",
"settings.cookies.clear": "Sign out everywhere",
"settings.cleared": "Signed out everywhere.",
"settings.cleared.history": "Signed out everywhere. The history could not be cleared.",
"menu.back": "Back",
"menu.forward": "Forward",
"menu.reload": "Reload",
@ -431,12 +423,10 @@ export default {
"settings.developers": "For developers",
"site.settings": "Site settings",
"site.back": "Back",
"import.all": "Import all",
"import.signins": "Sign-ins",
"import.history": "Browsing history",
"import.some.one": "Import {{number}} site",
"import.some.other": "Import {{number}} sites",
"import.description.one": "Copies cookies for {{number}} site. The other browser keeps its own.",
"import.description.other": "Copies cookies for all {{number}} sites. The other browser keeps its own.",
"import.description.loading": "Copies cookies only. The other browser keeps its own.",
"settings.import.open": "Import…",
"settings.advanced": "Advanced",
"settings.advanced.summary": "Remote servers, site permissions, sign out, cookie file",

View file

@ -14,12 +14,12 @@ import { SiteChooser } from "./site-chooser"
const CONFIRMATION_MS = 5_000
/**
* The pane's offer to bring sign-ins from the browser the user already uses, until they import or decline once. A
* `bar` sits above a page, where a signed-out site is the reason to import; a `card` sits on the new tab page.
* Nothing shows where no other browser is installed, or while main's profile is away.
* The pane's offer to bring sign-ins, and with them the history, from the browser the user already uses, until they
* import or decline once. A `bar` sits above a page, where a signed-out site is the reason to import; a `card` sits
* on the new tab page. Nothing shows where no other browser is installed, or while main's profile is away.
*
* Once cookies came in it says so, in place of the offer, for `CONFIRMATION_MS` or until the user closes it: a page that
* loads again signed in is the proof, and this names where the sign-ins came from.
* Once an import brought something it says so, in place of the offer, for `CONFIRMATION_MS` or until the user closes
* it: a page that loads again signed in is the proof, and this names where the sign-ins came from.
*
* `imported` runs once cookies came in, for the pane to load its page again with them, and `closed` when the user
* closes the confirmation.
@ -40,23 +40,20 @@ export function SignInOffer(props: { variant: "bar" | "card"; imported: () => vo
const blocked = () => !jobs.available() || jobs.running() !== undefined || jobs.unsaved() !== undefined
const message = () => jobs.unsaved() ?? jobs.notice() ?? jobs.describe(jobs.last())
// The import that brought cookies, with the browser's name, while its confirmation shows.
// The import that brought sign-ins or history, with the browser's name, while its confirmation shows.
const confirmed = createMemo(() => {
const last = jobs.last()
const count = last ? importedCookies(last.outcome) : 0
if (!last || count === 0 || last.job.type !== "import-browser") return undefined
if (!last || last.job.type !== "import-browser" || last.outcome.type !== "imported" || last.outcome.result.type !== "imported") return undefined
const job = last.job
const choice = choices().find((item) => item.source.id === job.source && item.profile.id === job.profile)
const outcome = last.outcome
const partial = outcome.type === "imported" && outcome.result.type === "imported" && importLoss(outcome.result)
const result = last.outcome.result
const loss = importLoss(result)
return {
choice,
text: partial
? (jobs.describe(last)?.text ?? "")
: ctx.plural("signins.imported.from", count, { browser: choice?.source.name ?? "" }),
}
// Nothing came, or only history while the sign-ins could not: the offer says why instead.
if (result.imported === 0 && (loss || !result.pages)) return undefined
const choice = choices().find((item) => item.source.id === job.source && item.profile.id === job.profile)
return { choice, text: loss ? (jobs.describe(last)?.text ?? "") : jobs.imported(result, choice?.source.name ?? "") }
})
// The pane shows the bar over a page and the card on the new tab page, each its own offer: one that goes while it
@ -144,13 +141,8 @@ export function SignInOffer(props: { variant: "bar" | "card"; imported: () => vo
aria-label={ctx.t("signins.title")}
class="mx-auto flex w-full max-w-[608px] flex-col gap-3 px-6 pt-12"
>
<div class="flex flex-col gap-1">
<div class="text-[13px] font-[530] leading-[var(--line-height-compact)] text-v2-text-text-base">
{ctx.t("signins.title")}
</div>
<div class="text-[13px] font-[440] leading-[var(--line-height-base)] text-v2-text-text-muted">
{ctx.t("signins.description")}
</div>
<div class="text-[13px] font-[530] leading-[var(--line-height-compact)] text-v2-text-text-base">
{ctx.t("signins.title")}
</div>
<div class="flex flex-col rounded-[8px] bg-v2-background-bg-layer-01 px-3 shadow-[inset_0_0_0_0.5px_var(--v2-border-border-muted)]">
<For each={choices()}>
@ -202,7 +194,7 @@ export function SignInOffer(props: { variant: "bar" | "card"; imported: () => vo
when={message()}
fallback={
<p class="min-w-0 flex-1 text-[13px] leading-[var(--line-height-compact)] text-v2-text-text-base">
{ctx.t("signins.bar")}
{ctx.t("signins.bar", { browser: choiceLabel(first()) })}
</p>
}
>
@ -224,7 +216,7 @@ export function SignInOffer(props: { variant: "bar" | "card"; imported: () => vo
busy={jobs.importing(first())}
onClick={() => run(first())}
>
{ctx.t("signins.import", { browser: choiceLabel(first()) })}
{ctx.t("signins.action")}
</ui.Button>
<Menu gutter={4} modal={false} placement="bottom-end">
<Tooltip placement="top" value={ctx.t("signins.other")}>

View file

@ -1,7 +1,7 @@
import { builtinCatalog } from "@opencode/plugin/gui/builtin"
import { Plugin, Store } from "@opencode/plugin/gui"
import { Schema } from "effect"
import { History } from "./history"
import { History } from "./history/visits"
import en from "./i18n/en"
import { SavedTabs } from "./saved-tabs"
@ -21,8 +21,8 @@ const Preferences = Schema.Struct({
export default Plugin.define({
stores: {
// Pages the browser showed, for the new tab page and the address field's suggestions. One list for every
// session and server, kept on this device.
// The last pages the browser showed, for the new tab page and their icons. One list for every session and server,
// kept on this device. The history the address field searches, with every page, is main's (`history/store.ts`).
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

View file

@ -95,7 +95,7 @@ test("leaving the surface aborts the running job, and nothing runs after", () =>
const result = replay([
{ type: "started", job: { type: "clear" } },
{ type: "disposed" },
{ type: "finished", attempt: 1, outcome: { type: "cleared" } },
{ type: "finished", attempt: 1, outcome: { type: "cleared", history: true } },
{ type: "started", job: { type: "clear" } },
])

View file

@ -2,8 +2,19 @@ import type { ImportResult, InstallResult } from "./profile/ipc"
/** One thing a surface asks main to do with the browser profile: the settings page, or the pane's import prompt. */
export type Job =
/** Every cookie of a browser profile, or with `sites` only those of the sites the user chose. */
| { readonly type: "import-browser"; readonly source: string; readonly profile: string; readonly sites?: readonly string[] }
/**
* A browser profile's sign-ins and browsing history, or with `sites` only those of the sites the user chose. Both
* come unless the person unticked one in the import dialog: `signins` false leaves the cookies behind, `history`
* false the history.
*/
| {
readonly type: "import-browser"
readonly source: string
readonly profile: string
readonly sites?: readonly string[]
readonly signins?: boolean
readonly history?: boolean
}
| { readonly type: "import-file"; readonly path: string }
| { readonly type: "install-store"; readonly url: string; readonly token?: string }
| { readonly type: "install-folder"; readonly path: string; readonly token?: string }
@ -22,7 +33,8 @@ export type Job =
export type Outcome =
| { readonly type: "imported"; readonly result: ImportResult }
| { readonly type: "installed"; readonly result: InstallResult }
| { readonly type: "cleared" }
/** Signed out everywhere; `history` is whether the browsing history went too. */
| { readonly type: "cleared"; readonly history: boolean }
/** An extension was removed, or turned on or off; the list shows it, so there is nothing to say. */
| { readonly type: "changed" }
/** The call rejected or timed out: main is gone, or the job did not answer in time. */

View file

@ -2,7 +2,7 @@ import { createSignal, onCleanup, untrack } from "solid-js"
import { createKeyed, createLatest, usePlugin, type IpcClient } from "@opencode/plugin/gui"
import type { Choice } from "./choices"
import type definition from "./index"
import { BrowserProfile, type ExtensionCompatibility, type ProfileSource } from "./profile/ipc"
import { BrowserProfile, type ExtensionCompatibility, type ImportResult, type ProfileSource } from "./profile/ipc"
import {
importedCookies,
importLoss,
@ -80,6 +80,10 @@ export function createProfileJobs(
setVersion((value) => value + 1)
input.finished?.(effect.finished)
// Signing out everywhere forgets where the person has been: main's history went with the cookies, and the
// window's list of the last pages goes here.
if (effect.finished.outcome.type === "cleared") ctx.stores.history.set({ visits: [] })
// Cookies came in: the user is signed in, so the pane stops offering the import. Last, as it may unmount the
// surface that runs this.
if (importedCookies(effect.finished.outcome) > 0 && !preferences.value.welcomed)
@ -145,6 +149,18 @@ export function createProfileJobs(
// On macOS a Chromium browser's cookie key is in the login Keychain, and the system asks before handing it over.
const keychain = (job: Job) => mac && source(job)?.engine === "chromium"
/**
* The one line for an import that lost nothing. An import from a browser says what came, in words: sign-ins,
* history, both, or nothing. A cookie file names no browser and brings only cookies, which it counts.
*/
const imported = (result: Extract<ImportResult, { type: "imported" }>, browser?: string) => {
if (!browser) return ctx.plural("signins.imported", result.imported)
if (result.imported > 0) return ctx.t(result.pages ? "signins.imported.history.from" : "signins.imported.from", { browser })
return ctx.t(result.pages ? "signins.imported.history.only.from" : "signins.imported.none.from", { browser })
}
/** What to say about a finished job; undefined for one whose result the surface already shows. */
const describe = (finished: Finished | undefined): JobMessage | undefined => {
if (!finished || finished.outcome.type === "changed") return undefined
@ -161,7 +177,9 @@ export function createProfileJobs(
return { text: ctx.t(type === "import-browser" || type === "import-file" ? "settings.failed.import" : "settings.failed.install"), error: true }
}
if (outcome.type === "cleared") return { text: ctx.t("settings.cleared"), error: false }
// The sign-out worked; history that stayed behind is said, or "everywhere" would be a false claim.
if (outcome.type === "cleared")
return outcome.history ? { text: ctx.t("settings.cleared"), error: false } : { text: ctx.t("settings.cleared.history"), error: true }
if (outcome.type === "installed") {
const result = outcome.result
@ -205,11 +223,10 @@ export function createProfileJobs(
const loss = importLoss(result)
if (loss?.reason === "other")
return {
text: ctx.plural("signins.imported.incomplete", result.imported, { omitted: loss.count }),
error: result.imported === 0,
}
// A cookie file is cookies and says so in counts: how many came, and how many did not. A browser's import counts
// them only when none came.
if (loss?.reason === "other" && (result.imported === 0 || finished.job.type === "import-file"))
return { text: ctx.plural("signins.imported.incomplete", result.imported, { omitted: loss.count }), error: result.imported === 0 }
if (result.imported === 0 && loss)
return {
@ -217,16 +234,14 @@ export function createProfileJobs(
error: true,
}
// Chrome and Edge on Windows mix readable cookies with app-bound ones: say what was left behind and what to do.
// Some sign-ins stayed behind, as Chrome's and Edge's app-bound ones on Windows do: their sites open signed out.
if (loss)
return {
text: browser
? ctx.plural("signins.imported.partial.named", result.imported, { browser, protected: result.protected })
: ctx.plural("signins.imported.partial", result.imported, { protected: result.protected }),
text: browser ? ctx.t("signins.imported.partial.named", { browser }) : ctx.t("signins.imported.partial"),
error: false,
}
return { text: ctx.plural("signins.imported", result.imported), error: result.imported === 0 }
return { text: imported(result, browser), error: result.imported === 0 && !result.pages }
}
return {
@ -245,6 +260,8 @@ export function createProfileJobs(
},
last: () => lastFinished(state()),
describe,
/** The one line that says what a browser's import brought: "Imported sign-ins and history from Helium". */
imported,
/** What to say while a job runs: on macOS, what the Keychain prompt in front of the window asks, and how to answer. */
notice: (): JobMessage | undefined => {
const job = runningJob(state())
@ -284,7 +301,10 @@ async function perform(client: Client, job: Job, signal: AbortSignal): Promise<O
case "import-browser":
return {
type: "imported",
result: await client.importBrowser({ source: job.source, profile: job.profile, sites: job.sites }, { signal }),
result: await client.importBrowser(
{ source: job.source, profile: job.profile, sites: job.sites, cookies: job.signins !== false, history: job.history !== false },
{ signal },
),
}
case "import-file":
return { type: "imported", result: await client.importFile({ path: job.path }, { signal }) }
@ -315,8 +335,6 @@ async function perform(client: Client, job: Job, signal: AbortSignal): Promise<O
return { type: "changed" }
case "clear":
await client.clear({ signal })
return { type: "cleared" }
return { type: "cleared", history: (await client.clear({ signal })).history }
}
}

View file

@ -1,11 +1,14 @@
import path from "node:path"
import { builtinMainContext } from "@opencode/plugin/gui/builtin"
import { MenubarItem, type Plugin } from "@opencode/plugin/gui/main"
import { BrowserHistory } from "./history/ipc"
import type { HistoryStore } from "./history/store"
import type { Pane } from "./pane"
import type { Profile } from "./profile"
import { RefsStore } from "./refs"
import { viewportToolbarAvailable } from "./viewport-toolbar-machine"
import { BrowserPane } from "./ipc"
import { BrowserProfile } from "./profile/ipc"
import { BrowserProfile, type ImportResult } from "./profile/ipc"
import { BrowserSites, createSitePermissions } from "./site-permissions"
import { createSystemMedia } from "./system-media"
import { createHandlePath } from "./disk"
@ -20,6 +23,12 @@ import {
/** The profile's creation while it runs, and the profile once it is created. */
type LoadedProfile = { profile?: Promise<Profile>; value?: Profile }
/** The history store's opening while it runs, and the store once it is open. */
type OpenedHistory = { store?: Promise<HistoryStore> }
/** What an import that leaves the sign-ins behind brought of them: nothing, and nothing was lost. */
const NO_COOKIES: ImportResult = { type: "imported", imported: 0, skipped: 0, protected: 0, failed: 0 }
const setup: Plugin.MainSetup = (ctx) => {
let paneState = createMainPaneState<Pane>()
const loads = new Map<number, ReturnType<typeof Promise.withResolvers<Pane>>>()
@ -70,6 +79,76 @@ const setup: Plugin.MainSetup = (ctx) => {
return pending
}
// The browsing history, opened the first time a window asks it something or an import brings pages: nothing reads
// it at startup. An opening that failed is forgotten, so the next request tries again.
const opened: OpenedHistory = {}
const historyDirectory = async () => {
const { app } = await import("electron")
return path.join(app.getPath("userData"), "browser-history")
}
// With `adopt`, the store takes over the pages the windows listed before it existed: read once, the first time a
// store opens. A store that replaces a deleted one starts empty.
const openHistory = async (adopt: boolean) => {
const { createHistoryStore } = await import("./history/store")
const { earlierVisits } = await import("./history/earlier")
const store = createHistoryStore({ directory: await historyDirectory() })
store.adopt(() => (adopt ? earlierVisits(builtinMainContext(ctx).storage) : []))
return store
}
const opening = (pending: Promise<HistoryStore>) => {
opened.store = pending
pending.catch((cause: unknown) => {
ctx.log.write("warn", "browser history failed to open", { cause: String(cause) })
if (opened.store === pending) opened.store = undefined
})
return pending
}
const history = () => {
if (ctx.signal.aborted) return Promise.reject(new Error("browser.history.unavailable"))
return opened.store ?? opening(openHistory(true))
}
// Forgets every page. A store that cannot be opened or cleared, as one whose file is damaged, is cleared by
// deleting its file: nothing in it can be kept anyway. Rejects only while the pages are still on disk.
const clearHistory = async () => {
const store = await history().catch(() => undefined)
const cleared = store
? await Promise.try(() => store.clear()).then(
() => true,
() => false,
)
: false
if (cleared) return
const { removeHistoryStore } = await import("./history/store")
const directory = await historyDirectory()
// The file is let go before it is deleted. Whoever asks meanwhile waits for the store that replaces it, which
// starts empty: the windows clear their own lists, and those are not taken over a second time.
store?.close()
const removed = removeHistoryStore(directory)
void opening(removed.then(() => openHistory(false)))
await removed
}
// The history of the other browser comes with its sign-ins. It never fails an import that brought cookies: history
// that cannot be read or stored is no pages.
const importHistory = async (current: Profile, source: string, profile: string, sites: readonly string[] | undefined) => {
const pages = await current.readHistory(source, profile, sites)
return pages.length > 0 ? (await history()).add(pages) : 0
}
const dispatch = (event: MainPaneEvent<Pane>) => {
const next = transitionMainPane(paneState, event)
paneState = next.state
@ -204,10 +283,49 @@ const setup: Plugin.MainSetup = (ctx) => {
sources: async () => (await profile()).sources(),
sites: async (input) => (await profile()).sites(input.source, input.profile),
importBrowser: (input) =>
serial(async () => (await profile()).importBrowser(input.source, input.profile, input.sites)),
serial(async () => {
const current = await profile()
// Without sign-ins no cookie is read or written, so the other browser's cookie key is never asked for either:
// no Keychain or key-store prompt. Without history its pages are not read and the history store is not opened.
const result = input.cookies === false ? NO_COOKIES : await current.importBrowser(input.source, input.profile, input.sites)
if (result.type !== "imported" || !input.history) return result
const pages = await importHistory(current, input.source, input.profile, input.sites).catch((cause: unknown) => {
ctx.log.write("warn", "another browser's history was not imported", { source: input.source, cause: String(cause) })
return 0
})
return { ...result, pages }
}),
importFile: (input) => serial(async () => (await profile()).importFile(input.path)),
summary: async () => (await profile()).summary(),
clear: () => serial(async () => (await profile()).clear()),
// Signing out everywhere also forgets where the person has been. The sign-out runs first and is whole whatever
// the history store does, and the history is cleared whether or not the sign-out worked. Neither failure hides
// the other: a sign-out that failed rejects, as it always did, and `history` says whether the history went.
clear: () =>
serial(async () => {
const signedOut = await profile()
.then((current) => current.clear())
.then(
() => undefined,
(cause: unknown) => ({ cause }),
)
const forgotten = await clearHistory().then(
() => true,
(cause: unknown) => {
ctx.log.write("warn", "browser history could not be cleared", { cause: String(cause) })
return false
},
)
if (signedOut) throw signedOut.cause
return { history: forgotten }
}),
browserExtensions: async (input) => (await profile()).browserExtensions(input.source, input.profile),
install: (input) => serial(async () => (await profile()).install(input)),
remove: (input) => serial(async () => (await profile()).remove(input.id)),
@ -241,6 +359,17 @@ const setup: Plugin.MainSetup = (ctx) => {
enable: (input) => serial(async () => (await profile()).enable(input.id, input.enabled)),
})
// Only the windows' address field asks: the pane, which the agent's tools drive, has no way to it.
ctx.provide(BrowserHistory, {
prepare: async () => (await history()).prepare(),
search: async (input) => (await history()).search(input.query, input.limit),
visit: async (input) => (await history()).visit(input.url, input.title),
retitle: async (input) => (await history()).retitle(input.url, input.title),
remove: async (input) => (await history()).remove(input.url),
// Rejects while the pages are still on disk, so the window can say that they are.
clear: () => serial(clearHistory),
})
const sitesIpc = ctx.provide(BrowserSites, {
state: () => ({ decisions: sites.list() }),
set: async (input) => sites.set(input),
@ -255,6 +384,8 @@ const setup: Plugin.MainSetup = (ctx) => {
await disposing
const value = loaded.value ?? (await loaded.profile?.catch(() => undefined))
value?.dispose()
const store = await opened.store?.catch(() => undefined)
store?.close()
await verifier.close()
})
}

View file

@ -20,7 +20,10 @@ import {
type ShortcutEvent,
type Zoom,
} from "./connection"
import { recordable, remember, withIcon } from "./history"
import { BrowserHistory } from "./history/ipc"
import { pageKey } from "./history/page"
import { HISTORY_ANSWER } from "./history/suggest"
import { recordable, remember, withIcon } from "./history/visits"
import { forgetTabs, saveIcon, saveTabs } from "./saved-tabs"
import type definition from "./index"
import { workspaceFileURL } from "./link"
@ -127,6 +130,16 @@ export function createModel(ctx: SetupContext<typeof definition>) {
: { status: current.status }
}
// Main's history of every page, which the address field searches. Away on the web and while main's plugin restarts:
// the window's own list of the last pages then answers alone.
const historyIpc = ctx.use(BrowserHistory)
const historyClient = () => {
const current = historyIpc()
return current.status === "active" ? current.value : undefined
}
const owner = getOwner()
const history = ctx.stores.history
const saved = ctx.stores.tabs
@ -488,7 +501,9 @@ export function createModel(ctx: SetupContext<typeof definition>) {
if (tab.loading || tab.loadError || !attachment.embeds[tab.id] || !recordable(tab.url)) return
const visit = `${tab.url}\n${tab.title}`
if (recorded.get(`${sessionKey}\n${tab.id}`) === visit) return
const previous = recorded.get(`${sessionKey}\n${tab.id}`)
if (previous === visit) return
recorded.set(`${sessionKey}\n${tab.id}`, visit)
history.set({
visits: remember(
@ -497,6 +512,13 @@ export function createModel(ctx: SetupContext<typeof definition>) {
state.pages[sessionKey]?.[tab.id]?.icon,
),
})
// Main's history counts the visit; a page that only reported its title since is the same visit. Main keeps web
// pages alone, and a visit it misses while it is away is one the window's list still has.
const page = { url: tab.url, title: tab.title }
const main = pageKey(tab.url) ? historyClient() : undefined
const sent = previous?.startsWith(`${tab.url}\n`) ? main?.retitle(page, { signal: ctx.signal }) : main?.visit(page, { signal: ctx.signal })
void sent?.catch(() => undefined)
})
}
@ -937,9 +959,42 @@ export function createModel(ctx: SetupContext<typeof definition>) {
return !visit.url.startsWith("workspace:") || (!!session?.id && visit.url.startsWith(workspacePrefix(session.id)))
}),
/**
* Whether there may be history to clear: the window's list has pages, or this is the desktop app, where main's
* history may hold pages the window never listed, as imported ones.
*/
historyClearable: () => history.value.visits.length > 0 || !!ctx.desktop,
/**
* Forgets every page: the window's list, and main's history with the pages imported from other browsers. Answers
* whether main's history went, so the pane never lets the person believe it did: false when main could not clear
* it, or cannot be reached. On the web there is no history but the window's list.
*/
clearHistory: () => {
recorded.clear()
history.set({ visits: [] })
const main = historyClient()
if (!main) return Promise.resolve(!ctx.desktop)
return main.clear({ signal: ctx.signal }).then(
() => true,
() => false,
)
},
/** The person is about to type an address: main reads its history into memory ahead of the first search. */
prepareHistory: () => void historyClient()?.prepare({ signal: ctx.signal }).catch(() => undefined),
/**
* The pages of main's history that match what the person typed in the address field, best first. None while main
* is away, as on the web.
*/
searchHistory: (query: string, signal: AbortSignal) =>
historyClient()?.search({ query, limit: HISTORY_ANSWER }, { signal: AbortSignal.any([ctx.signal, signal]) }) ?? Promise.resolve([]),
/** Forgets one page, as the person asked from the address field's suggestions. */
forgetPage: (url: string) => {
const key = pageKey(url)
history.set({ visits: history.value.visits.filter((visit) => visit.url !== url && (!key || pageKey(visit.url) !== key)) })
void historyClient()?.remove({ url }, { signal: ctx.signal }).catch(() => undefined)
},
pending: (session: SessionRef) => sessionPending(machine(), session),
/** The browser could not open and has no tabs to show: the pane says so and offers `retry`. */

View file

@ -48,7 +48,10 @@ import {
type Workspaces,
} from "@opencode/plugin/gui"
import barStyles from "./bar.css?inline"
import type { History } from "./history"
import { BrowserHistory } from "./history/ipc"
import { pageKey, type PageVisit } from "./history/page"
import { createPageIndex, findPages } from "./history/search"
import type { History } from "./history/visits"
import browserEn from "./i18n/en"
import type definition from "./index"
import { createModel } from "./model"
@ -115,6 +118,12 @@ type PaneFixtureState = {
pages: Record<string, PageDetails | undefined>
/** The browser history store. */
history: History
/** How many pages main's history holds. */
historyPages: number
/** Main's history store cannot open: every call to it rejects, as with a damaged file. */
historyAway: boolean
/** What the pane last said in a toast. */
toast: string
/** URLs the pane opened in the system browser. */
external: string[]
/** Cookies the page's address can read. */
@ -126,7 +135,7 @@ type PaneFixtureState = {
selection: string
}
export type BrowserScenario = "Page" | "Empty" | "Recent" | "Loading" | "Failed" | "Suspended"
export type BrowserScenario = "Page" | "Empty" | "Recent" | "History" | "Loading" | "Failed" | "Suspended"
type ElementRect = Pick<DOMRect, "x" | "y" | "width" | "height">
@ -164,6 +173,56 @@ const visits: History["visits"] = [
{ url: "https://alpha.example/", title: "Alpha" },
]
const DAY = 86_400_000
// A made-up history as an import from another browser leaves it in main: many GitHub repositories, of which a few
// have "rune" in their name or title, and other sites. No page has an icon, as imported pages have none.
const repositories = [
"anomalyco/opencode",
"anomalyco/opentui",
"anomalyco/models.dev",
"sst/sst",
"solidjs/solid",
"oven-sh/bun",
"effect-ts/effect",
"microsoft/typescript",
"vitejs/vite",
"electron/electron",
"nodejs/node",
"denoland/deno",
"rust-lang/rust",
"ziglang/zig",
"neovim/neovim",
"zed-industries/zed",
"withastro/astro",
"sveltejs/svelte",
"tailwindlabs/tailwindcss",
"oxc-project/oxc",
"biomejs/biome",
"microsoft/playwright",
"tanstack/query",
"drizzle-team/drizzle-orm",
"example-org/prune-cli",
]
function importedPages(now: number): PageVisit[] {
const page = (url: string, title: string, visits: number, days: number, typed = 0): PageVisit => ({ url, title, visits, typed, visited: now - days * DAY })
return [
page("https://github.com/anomalyco/rune-desktop", "anomalyco/rune-desktop: Rune for the desktop", 46, 1, 3),
page("https://github.com/anomalyco/rune-desktop/pulls", "Pull requests · anomalyco/rune-desktop", 18, 2),
page("https://github.com/anomalyco/rune-desktop/issues/128", "Rune panel flickers on resize · Issue #128 · anomalyco/rune-desktop", 5, 6),
page("https://github.com/runelabs/rune-lang", "runelabs/rune-lang: A small language for layouts", 7, 40),
page("https://docs.rune.example/guide/getting-started", "Getting started - Rune guide", 9, 12),
page("https://github.com/", "GitHub", 22, 0, 12),
page("https://news.ycombinator.com/", "Hacker News", 140, 0, 30),
page("https://developer.mozilla.org/en-US/docs/Web/API/Popover_API", "Popover API - Web APIs | MDN", 12, 3),
page("http://localhost:5173/", "OpenCode dev", 80, 0, 8),
...repositories.map((name, position) => page(`https://github.com/${name}`, `${name}: ${name.split("/")[1]} on GitHub`, 3 + ((position * 7) % 40), position % 30)),
...repositories.map((name, position) => page(`https://github.com/${name}/issues`, `Issues · ${name}`, 1 + (position % 6), 5 + position)),
]
}
// Component-test fixture: the real pane on the real host embeds, with the desktop faked at its two
// boundaries: the model's main-process pane (tab state, picker events) and the host bridge that shows native views.
export function mountBrowserPane(input: PaneHost) {
@ -224,6 +283,9 @@ export function browserPaneFixture(input: PaneHost | StoryHost) {
comments: [],
pages: {},
history: { visits: scenario === "Recent" ? structuredClone(visits) : [] },
historyPages: 0,
historyAway: false,
toast: "",
external: [],
cookies: 3,
failSite: false,
@ -590,10 +652,74 @@ export function browserPaneFixture(input: PaneHost | StoryHost) {
const live = liveAccessor(() => ({ status: "active", generation: 1, value: pane }))
// Main's history, faked at its Ipc with the real search over an index of its pages: what an import left, and the
// visits the model records.
const index = createPageIndex()
const pages = new Map<number, PageVisit>()
const position = (url: string) => Array.from(pages).find((item) => pageKey(item[1].url) === pageKey(url))?.[0]
const keep = (page: PageVisit, id = pages.size + 1) => {
pages.set(id, page)
index.set(id, page)
setStore("historyPages", pages.size)
}
const seedImported = () => importedPages(Date.now()).forEach((page) => keep(page))
// As main rejects each call while its store cannot open.
const reachable = () => {
if (store.historyAway) throw new Error("unable to open database file")
}
const historyClient = {
prepare: async () => reachable(),
search: async (request: { query: string; limit: number }) => {
reachable()
return findPages(index, request.query, request.limit, Date.now(), {
shown: (id) => pages.get(id),
front: (host) => Array.from(pages.values()).find((page) => pageKey(page.url) === host),
})
},
visit: async (request: { url: string; title: string }) => {
reachable()
const id = position(request.url)
const known = id === undefined ? undefined : pages.get(id)
if (pageKey(request.url)) keep({ ...request, visits: (known?.visits ?? 0) + 1, typed: known?.typed ?? 0, visited: Date.now() }, id)
},
retitle: async () => undefined,
remove: async (request: { url: string }) => {
reachable()
const id = position(request.url)
if (id === undefined) return
pages.delete(id)
index.remove(id)
setStore("historyPages", pages.size)
},
clear: async () => {
reachable()
pages.clear()
index.clear()
setStore("historyPages", 0)
},
}
// SAFETY: the model calls only the six methods above, with the inputs the history's Ipc schemas describe.
// oxlint-disable-next-line anti-slop/no-chained-type-assertions -- see SAFETY above
const historyMain = historyClient as unknown as IpcClient<(typeof BrowserHistory)["spec"]>
const historyLive = liveAccessor(() => ({ status: "active", generation: 1, value: historyMain }))
if (scenario === "History") seedImported()
const fake = {
...base,
app: { name: "opencode", version: "", channel: "dev", platform: "desktop", packaged: false },
use: () => live,
use: (token: { readonly id: string }) => (token.id === BrowserHistory.id ? historyLive : live),
// The plugin instance's lifetime, which the model's calls to main's history end with.
signal: new AbortController().signal,
toast: { show: (shown: { title: string }) => setStore("toast", shown.title) },
sessions: { current: session, list: () => Array.from(views.values()).filter((view) => view.key !== "Empty") },
screen: { current: () => screen },
layout: {
@ -705,6 +831,15 @@ export function browserPaneFixture(input: PaneHost | StoryHost) {
<h1 style={{ "font-size": "24px", "margin-bottom": "16px", display: "flex", "justify-content": "space-between" }}>
Browser pane lifecycle
<span style={{ display: "flex", gap: "8px" }}>
{/* Beside the title too: the pane below is measured where it is. */}
<span style={{ "font-size": "14px", "align-self": "center" }}>Main history: {store.historyPages}</span>
<span style={{ "font-size": "14px", "align-self": "center" }}>{store.toast}</span>
<button style={{ "font-size": "14px" }} onClick={seedImported}>
Seed imported history
</button>
<button style={{ "font-size": "14px" }} onClick={() => setStore("historyAway", (away) => !away)}>
History away
</button>
<button style={{ "font-size": "14px" }} onClick={() => setStore("failCommand", true)}>
Fail next command
</button>

View file

@ -95,7 +95,7 @@ export default {
argTypes: {
scenario: {
control: "select",
options: ["Page", "Empty", "Recent", "Loading", "Failed", "Suspended"] satisfies BrowserScenario[],
options: ["Page", "Empty", "Recent", "History", "Loading", "Failed", "Suspended"] satisfies BrowserScenario[],
},
},
render: (props: { scenario: BrowserScenario }) => <BrowserStory {...props} />,
@ -107,6 +107,9 @@ export const Empty = { args: { scenario: "Empty" } }
export const RecentPages = { args: { scenario: "Recent" } }
// A history as an import from another browser leaves it: type in the address field, for example "rune" or "gith".
export const ImportedHistory = { args: { scenario: "History" } }
export const Loading = { args: { scenario: "Loading" } }
export const LoadFailed = { args: { scenario: "Failed" } }

View file

@ -43,18 +43,20 @@ import { hostDisplay } from "./host-display"
import { FileSource } from "../file/contract"
import { remotePath, workspacePrefix } from "./remote-address"
import {
ADDRESS_HINT_MAX_LENGTH,
addressSuggestions,
addressRows,
addressView,
initialAddressState,
nextAddressEpoch,
transitionAddress,
type AddressEpoch,
type AddressEvent,
type AddressRow,
} from "./address-machine"
import { commentNote, pageNote } from "./comment"
import { Glyph } from "./choices"
import { bare, highlight, type Visit } from "./history"
import type { HistoryPage } from "./history/ipc"
import { markMatches, parseQuery, type Query } from "./history/match"
import { bare } from "./history/page"
import { SignInOffer } from "./import-prompt"
import { SiteChooserDialog } from "./site-chooser"
import type definition from "./index"
@ -223,23 +225,88 @@ export default function SessionBrowserPane(props: {
}),
)
// Suggestions follow what the user typed; a focused address is not a query.
const suggestions = createMemo(() => addressSuggestions(addressState(), props.model.visits()))
const addressBar = createMemo(() => addressView(addressState(), epoch(), suggestions()))
// The list follows what the user typed; a focused address is not a query.
const rows = createMemo(() => addressRows(addressState(), props.model.visits()))
const addressBar = createMemo(() => addressView(addressState(), epoch(), rows()))
// The typed words, whose matches each page of the list draws.
const query = createMemo(() => parseQuery(addressBar().query))
// Ends the questions to main's history that are still out when the pane goes.
const asking = new AbortController()
onCleanup(() => asking.abort())
const dispatchAddress = (event: AddressEvent, domEvent?: Event) => {
const next = transitionAddress(untrack(addressState), event)
setAddressState(next.state)
// The field's text is the machine's. After a key the input holds only what was typed, while the machine may show
// a completed address after it, or a row's text; the same text as before is not written by the binding.
const field = untrack(addressBar).field
if (input && input.value !== field) input.value = field
next.effects.forEach((effect) => {
if (effect.type === "select-input") return input?.select()
// The caret stays after the typed text, as Chrome's does, so the next key replaces the completed part.
if (effect.type === "select-completion") return input?.setSelectionRange(effect.start, input.value.length, "backward")
if (effect.type === "blur-input") return input?.blur()
if (effect.type === "prevent-default") return domEvent?.preventDefault()
if (effect.type === "forget") return props.model.forgetPage(effect.url)
if (effect.type === "prepare") return props.model.prepareHistory()
if (effect.type === "ask") {
// The field already shows what was typed and what the window knows; main's pages join when they come. A
// question main cannot answer, as on the web, is answered with none.
const answer = (pages: readonly HistoryPage[]) => {
if (!asking.signal.aborted) dispatchAddress({ type: "answered", attempt: effect.attempt, pages, visits: props.model.visits() })
}
return void props.model.searchHistory(effect.query, asking.signal).then(answer, () => answer([]))
}
command({ type: "navigate", tabID: effect.tabID, url: effect.url })
})
}
// Editing shows the icon of what Enter would open: the chosen page's once the person typed, else the page's own.
const fieldIcon = () => {
const bar = addressBar()
if (!bar.editing || !bar.field) return undefined
if (!bar.typed) return page()?.icon
return bar.chosen?.type === "page" ? bar.chosen.page.icon : undefined
}
// After a row's title: a page's address, what a search row searches with, or the typed address itself.
const rowDetail = (row: AddressRow) => {
if (row.type === "search") return plugin.t("address.search.web")
return row.type === "page" ? bare(row.url) : row.text
}
// A caret or a selection that leaves the end of the text ends completing, as in Chrome: the completed address
// becomes part of the text, and no later answer completes text the person is working inside.
const caretMoved = () => {
const bar = untrack(addressBar)
if (!input || !bar.completing) return
const end = input.value.length
if (input.selectionStart === bar.field.length - bar.completion.length && input.selectionEnd === end) return
dispatchAddress({
type: "input.changed",
value: input.value,
completing: input.selectionStart === end && input.selectionEnd === end,
visits: props.model.visits(),
})
}
const empty = () => !address() && !state()?.loading && !addressBar().navigating
// The desktop page hides blank and loading documents itself; only hide here
// while the pane shows its own empty or failed state over the embed.
@ -918,21 +985,10 @@ export default function SessionBrowserPane(props: {
dispatchAddress({ type: "submitted", epoch: epoch(), visits: props.model.visits(), failed: failed() })
}}
>
{/* Editing shows the icon of the page Enter would open: the page's own, or the chosen suggestion's. */}
{/* Editing shows the icon of what Enter would open: the page's own, or the chosen row's. */}
<Show
when={site()}
fallback={
<PageIcon
icon={
addressBar().editing && addressBar().field
? addressBar().typed
? addressBar().chosen?.icon
: page()?.icon
: undefined
}
class="text-v2-icon-icon-muted"
/>
}
fallback={<RowIcon search={addressBar().chosen?.type === "search"} icon={fieldIcon()} />}
>
{/* Site information describes one page: another tab or URL closes it, and opening it reads anew. */}
<Show when={`${props.session.key}\n${state()?.id}\n${address()}`} keyed>
@ -962,7 +1018,7 @@ export default function SessionBrowserPane(props: {
ref={input}
data-slot="browser-address-input"
role="combobox"
aria-autocomplete="list"
aria-autocomplete="both"
aria-expanded={addressBar().listed}
aria-controls={addressBar().listed ? "browser-suggestions" : undefined}
aria-activedescendant={addressBar().chosen ? `browser-suggestion-${addressBar().active}` : undefined}
@ -985,18 +1041,33 @@ export default function SessionBrowserPane(props: {
dispatchAddress({
type: "input.changed",
value: event.currentTarget.value,
deleting: event.inputType.startsWith("delete"),
// Only text typed at the end completes an address: not a deletion, a paste or a drop, and not
// text an IME is still composing, which a changed value would break.
completing:
(event.inputType === "insertText" || event.inputType === "insertCompositionText") &&
!event.isComposing &&
event.currentTarget.selectionStart === event.currentTarget.value.length,
visits: props.model.visits(),
})
}
onKeyDown={(event) => {
// Keys during IME composition pick and cancel candidates, not suggestions. Safari can report the
// Keys during IME composition pick and cancel candidates, not rows. Safari can report the
// composition-confirming keydown with isComposing false but keyCode 229.
if (event.isComposing || event.keyCode === 229) return
const modified = event.ctrlKey || event.altKey || event.metaKey
if (event.key === "ArrowDown" || event.key === "ArrowUp" || event.key === "Escape")
dispatchAddress({ type: "key.pressed", key: event.key, visits: props.model.visits() }, event)
// Shift with an arrow selects text, and a modified Tab is a shortcut of the app's.
if (((event.key === "ArrowDown" || event.key === "ArrowUp") && !event.shiftKey && !modified) || event.key === "Escape")
dispatchAddress({ type: "key.pressed", key: event.key, epoch: epoch(), visits: props.model.visits() }, event)
if (event.key === "Tab" && !modified)
dispatchAddress({ type: "key.pressed", key: event.shiftKey ? "Shift+Tab" : "Tab", epoch: epoch(), visits: props.model.visits() }, event)
// Shift+Delete forgets the chosen row's page, as in other browsers; on any other row it is the field's.
if (event.key === "Delete" && event.shiftKey) dispatchAddress({ type: "forget.pressed", visits: props.model.visits() }, event)
}}
onKeyUp={caretMoved}
onPointerUp={caretMoved}
/>
{/* At rest, draw the whole URL over the input's hidden text with its host emphasized. While editing, the
input shows its own text so selection and the caret need no mirror. */}
@ -1009,20 +1080,6 @@ export default function SessionBrowserPane(props: {
</span>
</div>
</Show>
{/* The suggestion Enter opens, after the typed text. Long text scrolls the input, which a mirror cannot
follow, so only a short query shows it. */}
<Show
when={
addressBar().editing && addressBar().query.length <= ADDRESS_HINT_MAX_LENGTH && addressBar().chosen
}
>
{(visit) => (
<div aria-hidden="true" data-slot="browser-address-hint">
<span class="invisible shrink-0">{addressBar().query}</span>
<span class="ms-1.5 min-w-0 truncate">{`- ${bare(visit().url)}`}</span>
</div>
)}
</Show>
</div>
{/* Any zoom but 100% stays in sight, as the system browser shows it; a click resets it. */}
<Show when={zoomed()}>
@ -1046,13 +1103,17 @@ export default function SessionBrowserPane(props: {
onCloseAutoFocus={(event) => event.preventDefault()}
>
<div id="browser-suggestions" role="listbox" aria-label={plugin.t("address.suggestions")}>
<For each={suggestions()}>
{(visit, index) => (
<For each={rows()}>
{(row, index) => (
<PageRow
visit={visit}
query={addressBar().query}
search={row.type === "search"}
icon={row.type === "page" ? row.page.icon : undefined}
title={rowTitle(row)}
detail={rowDetail(row)}
// Only a page draws the typed words: the other rows are the typed text itself.
query={row.type === "page" ? query() : undefined}
option={{ id: `browser-suggestion-${index()}`, selected: index() === addressBar().active }}
onClick={() => go(visit.url)}
onClick={() => go(row.url)}
/>
)}
</For>
@ -1240,7 +1301,15 @@ export default function SessionBrowserPane(props: {
>
{plugin.t("menu.hardReload")}
</Menu.Item>
<Menu.Item disabled={props.model.visits().length === 0} onSelect={() => props.model.clearHistory()}>
<Menu.Item
disabled={!props.model.historyClearable()}
// The list empties at once; a history main could not clear is said, and the item stays to try again.
onSelect={() =>
void props.model.clearHistory().then((cleared) => {
if (!cleared) plugin.toast.show({ variant: "error", title: plugin.t("history.clear.failed") })
})
}
>
{plugin.t("history.clear")}
</Menu.Item>
</Menu.SubContent>
@ -1403,7 +1472,9 @@ export default function SessionBrowserPane(props: {
{plugin.t("home.recent")}
</div>
<div class="flex flex-col gap-2">
<For each={recent()}>{(visit) => <PageRow visit={visit} onClick={() => go(visit.url)} />}</For>
<For each={recent()}>
{(visit) => <PageRow icon={visit.icon} title={visit.title} detail={bare(visit.url)} onClick={() => go(visit.url)} />}
</For>
</div>
</div>
</Show>
@ -1594,26 +1665,48 @@ export default function SessionBrowserPane(props: {
)
}
/** A page in the suggestions or the new tab page: its icon, title and address, with the query's matches drawn. */
/** The title of a row of the address field's list: a page's own, or the text a search row searches for. */
function rowTitle(row: AddressRow) {
if (row.type === "page") return row.page.title
return row.type === "search" ? row.text : ""
}
/** The icon of a row of the address field's list, and of the field while that row is chosen: the search glyph, or a page's own. */
function RowIcon(props: { search: boolean; icon: string | undefined }) {
return (
<Show when={props.search} fallback={<PageIcon icon={props.icon} class="text-v2-icon-icon-muted" />}>
<Icon name="magnifying-glass" class="pointer-events-none size-4 shrink-0 text-v2-icon-icon-muted" />
</Show>
)
}
/**
* A row of the address field's list or of the new tab page: an icon, a title and, after it, a page's address or what
* a search row searches with. A page draws the query's matches.
*/
function PageRow(props: {
visit: Visit
query?: string
/** Set for a suggestion: an option of the address field's list, which keeps keyboard focus in the field. */
search?: boolean
icon: string | undefined
title: string
detail: string
query?: Query
/** Set for a row of the address field's list: an option, which keeps keyboard focus in the field. */
option?: { id: string; selected: boolean }
onClick: () => void
}) {
const body = () => (
<>
<PageIcon icon={props.visit.icon} class="text-v2-icon-icon-muted" />
<RowIcon search={!!props.search} icon={props.icon} />
<span data-slot="browser-page-row-text">
<Show when={props.visit.title}>
<Show when={props.title}>
<span data-slot="browser-page-row-title">
<Marked text={props.visit.title} query={props.query ?? ""} />
<Marked text={props.title} query={props.query} />
</span>
<span>-</span>
</Show>
<span data-slot="browser-page-row-url">
<Marked text={bare(props.visit.url)} query={props.query ?? ""} />
<Marked text={props.detail} query={props.query} />
</span>
</span>
</>
@ -1646,9 +1739,9 @@ function PageRow(props: {
)
}
function Marked(props: { text: string; query: string }) {
function Marked(props: { text: string; query: Query | undefined }) {
return (
<For each={highlight(props.text, props.query)}>
<For each={markMatches(props.text, props.query)}>
{(part) => (
<Show when={part.match} fallback={part.text}>
<mark>{part.text}</mark>

View file

@ -6,8 +6,9 @@ import { DatabaseSync } from "node:sqlite"
const PREFIX = "opencode-browser-import-"
/**
* Where copies of another browser's databases live while they are read: a directory of the app's own data, which only
* the user can read, and the copies being read now. `log` hears a copy that could not be deleted.
* Where copies of another browser's databases, its cookies and its history, live while they are read: a directory of
* the app's own data, which only the user can read, and the copies being read now. `log` hears a copy that could not
* be deleted.
*/
export type SnapshotScratch = {
readonly directory: string
@ -92,7 +93,7 @@ async function remove(directory: string, scratch: SnapshotScratch) {
() => false,
)
if (!removed) scratch.log("a copy of another browser's cookie database could not be deleted", { directory })
if (!removed) scratch.log("a copy of another browser's database could not be deleted", { directory })
}
// A link among the entries is deleted itself, never what it points to, and a directory among them is left, so the
@ -111,5 +112,5 @@ async function removeFlat(directory: string, scratch: SnapshotScratch) {
() => false,
)
if (!removed) scratch.log("a copy of another browser's cookie database could not be deleted", { directory })
if (!removed) scratch.log("a copy of another browser's database could not be deleted", { directory })
}

View file

@ -1,12 +1,14 @@
import path from "node:path"
import electron from "electron"
import { createHistoryStore } from "../history"
import { writeCookies } from "./import"
import { siteFilter } from "./sites"
import { readSource } from "./sources"
import { readSource, readSourceHistory } from "./sources"
// The Electron main process of `electron-import.test.ts`, bundled and run by the pinned Electron with every location
// the browser list reads pointed at the test's made-up home. It imports the chosen sites of a made-up Firefox profile
// into an in-memory session, the way the profile's import does, then another site, and prints one JSON line.
// into an in-memory session, the way the profile's import does, then another site; then the profile's history into a
// history store, which it searches and clears; and prints one JSON line.
void electron.app.whenReady().then(async () => {
const session = electron.session.fromPartition("import-test")
@ -25,6 +27,17 @@ void electron.app.whenReady().then(async () => {
const afterFirst = await cookies()
const second = await chosen(["bank.test"])
const afterSecond = await cookies()
process.stdout.write(`${JSON.stringify({ first, afterFirst, second, afterSecond })}\n`)
// The history, with the pinned Electron's own SQLite: read from the profile's copy, kept, searched and cleared.
const store = createHistoryStore({ directory: path.join(process.env.HOME ?? "", "history") })
const read = await readSourceHistory("firefox", "Profiles/work.default", scratch)
const pages = "failure" in read ? read : store.add(read)
const found = store.search("rune", 5).map((page) => page.url)
const completed = store.search("gith", 5).map((page) => page.url)
store.clear()
const cleared = store.size()
store.close()
process.stdout.write(`${JSON.stringify({ first, afterFirst, second, afterSecond, pages, found, completed, cleared })}\n`)
electron.app.quit()
})

View file

@ -6,9 +6,10 @@ import { madeUpFirefox } from "./made-up-firefox.fixture"
// An import of chosen sites writes only those sites' cookies into Electron's cookie store, keeps domain and host-only
// cookies as they were, and a later import adds a site without removing the first. This runs the real read and the
// profile's writer in the pinned Electron, against a made-up Firefox profile in a temporary home.
// profile's writer in the pinned Electron, against a made-up Firefox profile in a temporary home. The profile's history
// goes through the same Electron's SQLite into the history store.
test(
"the pinned Electron receives only the chosen sites' cookies, and a second import adds to them",
"the pinned Electron receives only the chosen sites' cookies, a second import adds to them, and the history comes too",
async () => {
const made = await madeUpFirefox()
@ -24,6 +25,12 @@ test(
])
expect(result.second).toMatchObject({ type: "imported", imported: 1 })
expect(result.afterSecond).toEqual([...result.afterFirst, [".bank.test", "session", "bank-secret", false]].toSorted())
// The profile's history, through the pinned Electron's SQLite: three visited pages, found by a word of the path
// and completed from the start of a host, and none left after a clear.
expect(result.pages).toBe(3)
expect(result.found).toEqual(["https://github.com/anomalyco/rune-desktop"])
expect(result.completed).toEqual(["https://github.com/", "https://github.com/anomalyco/rune-desktop"])
expect(result.cleared).toBe(0)
} finally {
await rm(made.home, { recursive: true, force: true }).catch(() => undefined)
}

View file

@ -0,0 +1,181 @@
import { afterEach, beforeEach, expect, setSystemTime, test } from "bun:test"
import { mkdtemp, readdir, rm } from "node:fs/promises"
import { tmpdir } from "node:os"
import path from "node:path"
import { DatabaseSync } from "node:sqlite"
import { MAX_PAGES, MAX_URL_LENGTH } from "../history"
import { readChromiumHistory, readSafariHistory } from "./history"
import { madeUpFirefox } from "./made-up-firefox.fixture"
import { siteFilter } from "./sites"
import { readSourceHistory } from "./sources"
const NOW = Date.parse("2026-11-20T12:00:00Z")
const DAY = 86_400_000
// Chromium counts microseconds since 1601, Safari seconds since 2001.
const chromiumTime = (daysAgo: number) => (NOW - daysAgo * DAY + 11_644_473_600_000) * 1000
const safariTime = (daysAgo: number) => (NOW - daysAgo * DAY) / 1000 - 978_307_200
// The `urls` table as Chromium's history database version 70 creates it.
const CHROMIUM_URLS =
"CREATE TABLE urls(id INTEGER PRIMARY KEY AUTOINCREMENT,url LONGVARCHAR,title LONGVARCHAR,visit_count INTEGER DEFAULT 0 NOT NULL,typed_count INTEGER DEFAULT 0 NOT NULL,last_visit_time INTEGER NOT NULL,hidden INTEGER DEFAULT 0 NOT NULL)"
// Safari's two history tables, as macOS 15 creates them.
const SAFARI_TABLES = `
CREATE TABLE history_items (id INTEGER PRIMARY KEY AUTOINCREMENT, url TEXT NOT NULL UNIQUE, domain_expansion TEXT NULL, visit_count INTEGER NOT NULL, daily_visit_counts BLOB NOT NULL, weekly_visit_counts BLOB NULL, autocomplete_triggers BLOB NULL, should_recompute_derived_visit_counts INTEGER NOT NULL, visit_count_score INTEGER NOT NULL);
CREATE TABLE history_visits (id INTEGER PRIMARY KEY AUTOINCREMENT, history_item INTEGER NOT NULL REFERENCES history_items(id) ON DELETE CASCADE, visit_time REAL NOT NULL, title TEXT NULL, load_successful BOOLEAN NOT NULL DEFAULT 1, http_non_get BOOLEAN NOT NULL DEFAULT 0, synthesized BOOLEAN NOT NULL DEFAULT 0, redirect_source INTEGER NULL UNIQUE REFERENCES history_visits(id) ON DELETE CASCADE, redirect_destination INTEGER NULL UNIQUE REFERENCES history_visits(id) ON DELETE CASCADE, origin INTEGER NOT NULL DEFAULT 0, generation INTEGER NOT NULL DEFAULT 0, attributes INTEGER NOT NULL DEFAULT 0, score INTEGER NOT NULL DEFAULT 0);
`
const saved = { ...process.env }
const made: string[] = []
async function database(name: string, fill: (db: DatabaseSync) => void) {
const directory = await mkdtemp(path.join(tmpdir(), "browser-history-read-"))
made.push(directory)
const file = path.join(directory, name)
const db = new DatabaseSync(file)
fill(db)
db.close()
// Copies go under the test's own directory, as the profile puts them under the app's data.
return { file, scratch: { directory: path.join(directory, "copies"), live: new Set<string>(), log: () => undefined } }
}
beforeEach(() => {
setSystemTime(new Date(NOW))
})
afterEach(async () => {
setSystemTime()
Object.keys(process.env)
.filter((key) => !(key in saved))
.forEach((key) => delete process.env[key])
Object.assign(process.env, saved)
await Promise.all(made.splice(0).map((directory) => rm(directory, { recursive: true, force: true }).catch(() => undefined)))
})
test("reads a Chromium history: visited web pages, most used and most recent first, and leaves no copy behind", async () => {
const source = await database("History", (db) => {
db.exec(CHROMIUM_URLS)
const insert = db.prepare("INSERT INTO urls (url, title, visit_count, typed_count, last_visit_time, hidden) VALUES (?, ?, ?, ?, ?, ?)")
insert.run("https://github.com/anomalyco/rune-desktop", "anomalyco/rune-desktop", 40, 2, chromiumTime(1), 0)
insert.run("https://old.test/guide", "Guide", 40, 2, chromiumTime(300), 0)
insert.run("http://localhost:3000/", "Local app", 1, 0, chromiumTime(0), 0)
// What an import never brings: other schemes, credentials, an address too long, a hidden row, no visit.
insert.run("chrome://settings/", "Settings", 9, 0, chromiumTime(0), 0)
insert.run("file:///C:/Users/me/notes.html", "Notes", 9, 0, chromiumTime(0), 0)
insert.run("https://me:secret@private.test/", "Private", 9, 0, chromiumTime(0), 0)
insert.run(`https://long.test/${"a".repeat(MAX_URL_LENGTH)}`, "Long", 9, 0, chromiumTime(0), 0)
insert.run("https://github.com/subframe", "A subframe", 9, 0, chromiumTime(0), 1)
insert.run("https://unvisited.test/", "Never visited", 0, 0, chromiumTime(0), 0)
// Damage: a title that is not text reads as no title, a count that is not a number as no visit.
insert.run("https://damaged.test/title", Buffer.from("blob"), 2, 0, chromiumTime(5), 0)
insert.run("https://damaged.test/count", "Count", "many", 0, chromiumTime(0), 0)
insert.run(Buffer.from("https://damaged.test/url"), "Address", 3, 0, chromiumTime(0), 0)
})
expect(await readChromiumHistory(source.file, source.scratch, { now: NOW })).toEqual([
{ url: "https://github.com/anomalyco/rune-desktop", title: "anomalyco/rune-desktop", visits: 40, typed: 2, visited: NOW - DAY },
{ url: "https://old.test/guide", title: "Guide", visits: 40, typed: 2, visited: NOW - 300 * DAY },
{ url: "https://damaged.test/title", title: "", visits: 2, typed: 0, visited: NOW - 5 * DAY },
{ url: "http://localhost:3000/", title: "Local app", visits: 1, typed: 0, visited: NOW },
])
expect((await readdir(source.scratch.directory)).filter((entry) => entry.startsWith("opencode-browser-import-"))).toEqual([])
})
test("reads a Chromium history that lacks the optional columns, and nothing from one without addresses", async () => {
const bare = await database("History", (db) => {
db.exec("CREATE TABLE urls (id INTEGER PRIMARY KEY, url LONGVARCHAR, last_visit_time INTEGER)")
db.prepare("INSERT INTO urls (url, last_visit_time) VALUES (?, ?)").run("https://example.com/", chromiumTime(2))
})
expect(await readChromiumHistory(bare.file, bare.scratch, { now: NOW })).toEqual([
{ url: "https://example.com/", title: "", visits: 1, typed: 0, visited: NOW - 2 * DAY },
])
const renamed = await database("History", (db) => db.exec("CREATE TABLE urls (id INTEGER PRIMARY KEY, address TEXT)"))
expect(await readChromiumHistory(renamed.file, renamed.scratch, { now: NOW })).toEqual([])
})
test(
"an import brings at most 50,000 pages, the most used and most recent",
async () => {
const source = await database("History", (db) => {
db.exec(CHROMIUM_URLS)
// Ten more than the limit, each visited once a minute apart; the first is the oldest.
db.exec(`
WITH RECURSIVE numbers(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM numbers WHERE n < ${MAX_PAGES + 10})
INSERT INTO urls (url, title, visit_count, typed_count, last_visit_time, hidden)
SELECT 'https://site.test/page/' || n, 'Page ' || n, 1, 0, ${chromiumTime(40)} + n * 60000000, 0 FROM numbers`)
db.prepare("INSERT INTO urls (url, title, visit_count, typed_count, last_visit_time, hidden) VALUES (?, ?, ?, ?, ?, ?)").run(
"https://often.test/",
"Often",
500,
0,
chromiumTime(300),
0,
)
})
const pages = await readChromiumHistory(source.file, source.scratch, { now: NOW })
expect(pages).toHaveLength(MAX_PAGES)
expect(pages[0]?.url).toBe("https://often.test/")
// The eleven oldest single visits stay behind.
expect(pages.some((page) => page.url === "https://site.test/page/11")).toBe(false)
expect(pages.some((page) => page.url === "https://site.test/page/12")).toBe(true)
},
// Writes and reads 50,000 rows.
30_000,
)
test("reads a Safari history: each page with its latest visit's title and time", async () => {
const source = await database("History.db", (db) => {
db.exec(SAFARI_TABLES)
const item = db.prepare("INSERT INTO history_items (id, url, visit_count, daily_visit_counts, should_recompute_derived_visit_counts, visit_count_score) VALUES (?, ?, ?, x'', 0, 0)")
const visit = db.prepare("INSERT INTO history_visits (history_item, visit_time, title) VALUES (?, ?, ?)")
item.run(1, "https://github.com/anomalyco/rune-desktop", 3)
visit.run(1, safariTime(9), "Loading…")
visit.run(1, safariTime(1), "anomalyco/rune-desktop")
visit.run(1, safariTime(4), null)
item.run(2, "https://www.apple.com/", 1)
visit.run(2, safariTime(20), "Apple")
item.run(3, "file:///Users/me/notes.html", 4)
visit.run(3, safariTime(0), "Notes")
// An address with no visit left is not history.
item.run(4, "https://unvisited.test/", 2)
})
expect(await readSafariHistory(source.file, source.scratch, { now: NOW })).toEqual([
{ url: "https://github.com/anomalyco/rune-desktop", title: "anomalyco/rune-desktop", visits: 3, typed: 0, visited: NOW - DAY },
{ url: "https://www.apple.com/", title: "Apple", visits: 1, typed: 0, visited: NOW - 20 * DAY },
])
})
test("a profile's history comes from Firefox's own table, and with chosen sites only theirs", async () => {
const profile = await madeUpFirefox()
made.push(profile.home)
Object.assign(process.env, profile.env)
const scratch = { directory: path.join(profile.home, "copies"), live: new Set<string>(), log: () => undefined }
const all = await readSourceHistory("firefox", "Profiles/work.default", scratch)
if ("failure" in all) throw new Error(`The made-up profile did not read: ${all.failure}`)
// The bookmark never visited and the hidden redirect hop stay behind; a page without a title has none.
expect(all.map((page) => [page.url, page.title, page.visits, page.typed])).toEqual([
["https://github.com/anomalyco/rune-desktop", "anomalyco/rune-desktop", 12, 1],
["https://www.bank.test/accounts", "", 2, 0],
["https://github.com/", "GitHub", 3, 0],
])
expect(Math.abs((all[0]?.visited ?? 0) - (NOW - DAY))).toBeLessThan(1_000)
const chosen = await readSourceHistory("firefox", "Profiles/work.default", scratch, siteFilter(["bank.test"]))
expect("failure" in chosen ? chosen : chosen.map((page) => page.url)).toEqual(["https://www.bank.test/accounts"])
// Safari's history is on macOS only, and a browser that is not installed has none: both answer quietly.
expect(await readSourceHistory("safari", "default", scratch)).toEqual({ failure: "read" })
expect(await readSourceHistory("firefox", "Profiles/missing", scratch)).toEqual({ failure: "read" })
})

View file

@ -0,0 +1,146 @@
import type { DatabaseSync } from "node:sqlite"
import { MAX_PAGES, MAX_URL_LENGTH, webPage, type PageVisit } from "../history"
import { snapshotDatabase, type SnapshotScratch } from "./database"
/** Milliseconds between 1601-01-01 (Chromium's epoch) and 1970-01-01. */
const WINDOWS_EPOCH_MS = 11_644_473_600_000
/** Seconds between 1970-01-01 and 2001-01-01, the epoch of Safari's timestamps. */
const MAC_EPOCH_SECONDS = 978_307_200
/** No browser has counted more visits to a page; a larger count is damage. */
const MOST_VISITS = 10_000_000
/** The year 2100 in Unix milliseconds; a later visit is damage. */
const LATEST_VISIT = 4_102_444_800_000
type Row = { url: string; title: string; visits: number; typed: number; visited: number }
/** What a reader keeps of a history: with `keep`, only the pages of the hosts it keeps. */
type Kept = { readonly keep?: (host: string) => boolean; readonly now: number }
/**
* Reads a Chromium profile's `History`: its `urls` table has one row per address, with its title, how often it was
* visited and typed, and its last visit in microseconds since 1601. Rows Chromium hides from its own address bar
* (subframes and redirect hops) stay behind.
*/
export function readChromiumHistory(database: string, scratch: SnapshotScratch, kept: Kept) {
return snapshotDatabase(database, scratch, (db) => {
const has = columns(db, "urls")
if (!has("url")) return []
return collect(
db,
`SELECT url,
${has("title") ? "title" : "NULL"} AS title,
${has("visit_count") ? "visit_count" : "1"} AS visits,
${has("typed_count") ? "typed_count" : "0"} AS typed,
${has("last_visit_time") ? `last_visit_time / 1000 - ${WINDOWS_EPOCH_MS}` : "0"} AS visited
FROM urls WHERE ${has("hidden") ? "hidden = 0" : "1"}`,
kept,
)
})
}
/**
* Reads a Firefox-family profile's `places.sqlite`: `moz_places` has one row per address, with its title, its visit
* count, whether it was ever typed, and its last visit in microseconds since 1970. Bookmarks never visited and hidden
* places stay behind. Its `frecency` is not read: what it means changed between Firefox versions.
*/
export function readFirefoxHistory(database: string, scratch: SnapshotScratch, kept: Kept) {
return snapshotDatabase(database, scratch, (db) => {
const has = columns(db, "moz_places")
if (!has("url")) return []
return collect(
db,
`SELECT url,
${has("title") ? "title" : "NULL"} AS title,
${has("visit_count") ? "visit_count" : "1"} AS visits,
${has("typed") ? "typed" : "0"} AS typed,
${has("last_visit_date") ? "last_visit_date / 1000" : "0"} AS visited
FROM moz_places WHERE ${has("hidden") ? "hidden = 0" : "1"}`,
kept,
)
})
}
/**
* Reads Safari's `History.db`: `history_items` has one row per address and `history_visits` one per visit, with the
* title the page had then and its time in seconds since 2001. A page's title and time are its latest visit's. Safari
* records no typed visits.
*/
export function readSafariHistory(database: string, scratch: SnapshotScratch, kept: Kept) {
return snapshotDatabase(database, scratch, (db) => {
const item = columns(db, "history_items")
const visit = columns(db, "history_visits")
if (!item("id") || !item("url") || !visit("history_item") || !visit("visit_time")) return []
// SQLite takes a bare column beside `max()` from the row that holds the maximum: the latest visit's title.
return collect(
db,
`SELECT i.url AS url,
${visit("title") ? "v.title" : "NULL"} AS title,
${item("visit_count") ? "i.visit_count" : "count(*)"} AS visits,
0 AS typed,
(max(v.visit_time) + ${MAC_EPOCH_SECONDS}) * 1000 AS visited
FROM history_items i JOIN history_visits v ON v.history_item = i.id GROUP BY i.id`,
kept,
)
})
}
/** Whether a table has a column, so a browser version that lacks or renamed one still imports what it has. */
function columns(db: DatabaseSync, table: string) {
// SAFETY: `table_info` returns one row per column, whose `name` is text.
const names = new Set((db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[]).map((column) => column.name))
return (name: string) => names.has(name)
}
/**
* The pages of one browser's history, from a query that names a row's `url`, `title`, `visits`, `typed` and
* `visited` (Unix milliseconds): web pages visited at least once, the most used and most recent first, until
* `MAX_PAGES` are kept. A value of another type than the browser writes is damage: it reads as no title, no visit
* or no time, and a count or time beyond any real one is cut, so no row fails the read.
*/
function collect(db: DatabaseSync, select: string, kept: Kept) {
// What the order sorts stays in memory, never in a temporary file outside the copy's own directory.
db.exec("PRAGMA temp_store = MEMORY")
const query = db.prepare(`
SELECT url, title, visits, typed, visited FROM (
SELECT url,
CASE WHEN typeof(title) = 'text' THEN title ELSE '' END AS title,
CASE WHEN typeof(visits) = 'integer' THEN min(visits, ${MOST_VISITS}) ELSE 0 END AS visits,
CASE WHEN typeof(typed) = 'integer' THEN max(0, min(typed, ${MOST_VISITS})) ELSE 0 END AS typed,
CASE WHEN typeof(visited) IN ('integer', 'real') THEN CAST(max(0, min(visited, ${LATEST_VISIT})) AS INTEGER) ELSE 0 END AS visited
FROM (${select})
WHERE typeof(url) = 'text' AND length(url) <= ${MAX_URL_LENGTH} AND (url LIKE 'http://%' OR url LIKE 'https://%')
)
WHERE visits > 0
ORDER BY (visits + typed) * CASE
WHEN ? - visited <= 345600000 THEN 100
WHEN ? - visited <= 1209600000 THEN 70
WHEN ? - visited <= 2678400000 THEN 50
WHEN ? - visited <= 7776000000 THEN 30
ELSE 10 END DESC, visited DESC`)
const pages: PageVisit[] = []
// Read row by row, so a history of a million addresses stops at the pages kept.
// SAFETY: the query above gives every row these five columns, each in the type `Row` says.
for (const row of query.iterate(kept.now, kept.now, kept.now, kept.now) as IterableIterator<Row>) {
const page = webPage(row.url)
if (!page || (kept.keep && !kept.keep(page.host))) continue
pages.push({ url: row.url, title: row.title, visits: row.visits, typed: Math.min(row.typed, row.visits), visited: row.visited })
if (pages.length === MAX_PAGES) break
}
return pages
}

View file

@ -40,6 +40,7 @@ import {
listSources,
profileExtensions,
readSource,
readSourceHistory,
readSourceHosts,
windowsIcons,
} from "./sources"
@ -486,6 +487,19 @@ export async function createBrowserProfile(input: {
return importCookies(read, !!sites)
},
/**
* The pages of a browser profile's history for an import, or with `sites` only the chosen sites'. None when the
* history cannot be read, as Safari's without Full Disk Access: the log says why, without any address.
*/
async readHistory(source: string, profile: string, sites?: readonly string[]) {
const keep = sites ? (await import("./sites")).siteFilter(sites) : undefined
const read = await readSourceHistory(source, profile, scratch, keep)
if (!("failure" in read)) return read
input.log.write("warn", "another browser's history could not be read", { source, reason: read.failure })
return []
},
async importFile(file: string): Promise<ImportResult> {
// A cookie export is a few megabytes at most; anything far larger is not one.
const size = await stat(file).then(

View file

@ -124,6 +124,8 @@ export type ProfileSource = typeof ProfileSource.Type
* How a cookie import ended.
* - `imported`: `imported` cookies were written; `skipped` were expired or partitioned, `protected` were encrypted with a
* key only the source browser can use (Chrome and Edge app-bound encryption on Windows), `failed` did not decrypt.
* `pages` is how many pages of the browser's history came too: absent for a cookie file, or when history was not
* asked for. History that could not be read is 0 pages, never a failure.
* - `failed`: nothing was read. `key`: the browser's key was not available, e.g. a denied Keychain prompt. `access`: the
* system denied access, e.g. Safari without Full Disk Access. `locked`: the browser runs and holds its cookies open,
* as Chromium does on Windows. `read`: the profile could not be read. `format`: the
@ -136,6 +138,7 @@ export const ImportResult = Schema.Union([
skipped: Count,
protected: Count,
failed: Count,
pages: Schema.optional(Count),
}),
Schema.Struct({
type: Schema.Literal("failed"),
@ -214,11 +217,20 @@ export const BrowserProfile = Ipc.define({
/** The sites a browser profile has cookies for; see `SiteList`. Only the window's import dialog asks. */
sites: { input: Schema.Struct(SourceProfile), output: SiteList },
/**
* Imports a browser profile's cookies: all of them, or with `sites` only those of the sites `sites` returned that
* the user chose. Cookies already in the profile stay, so a later import adds more sites.
* Imports from a browser profile what the person ticked in the import dialog: its cookies, its browsing history,
* or both; all of each, or with `sites` only those of the sites `sites` returned that the user chose.
* - Cookies come unless `cookies` is false. Cookies already in the profile stay, so a later import adds more
* sites. With `cookies` false none is read or written, and the other browser's cookie key is not asked for.
* - With `history`, the profile's browsing history comes, for the address field to complete from, and the
* result's `pages` counts it. Without it no page is read and the history store is not opened.
*/
importBrowser: {
input: Schema.Struct({ ...SourceProfile, sites: Schema.optional(Schema.Array(text(255)).check(Schema.isMaxLength(100_000))) }),
input: Schema.Struct({
...SourceProfile,
sites: Schema.optional(Schema.Array(text(255)).check(Schema.isMaxLength(100_000))),
history: Schema.optional(Schema.Boolean),
cookies: Schema.optional(Schema.Boolean),
}),
output: ImportResult,
},
/** A Netscape `cookies.txt`, a JSON cookie export or a Playwright storage state. */
@ -231,10 +243,12 @@ export const BrowserProfile = Ipc.define({
/** Turns sharing the profile's sign-ins with remote servers' pages on or off; see the state's `remoteSignIns`. */
shareSignIns: { input: Schema.Struct({ enabled: Schema.Boolean }) },
/**
* Signs out everywhere: deletes every cookie, cache, site's stored data and HTTP sign-in. Extensions and the site
* permissions the user kept stay.
* Signs out everywhere: deletes every cookie, cache, site's stored data and HTTP sign-in, and the browsing history.
* Extensions and the site permissions the user kept stay. The sign-out does not depend on the history: it rejects
* only when the sign-out itself failed, and `history` is false when the history could not be cleared, so the window
* never says that it went.
*/
clear: {},
clear: { output: Schema.Struct({ history: Schema.Boolean }) },
/** The extensions a Chromium profile has installed. */
browserExtensions: {
input: Schema.Struct(SourceProfile),

View file

@ -7,7 +7,8 @@ import { DatabaseSync } from "node:sqlite"
* A made-up Firefox profile where this system's Firefox keeps its profiles, under a new temporary home, and the
* environment that points every location the browser list reads at that home, so no browser on this machine is read.
* Its profile `Profiles/work.default` has cookies of github.com (a domain cookie, a host-only one and a subdomain's, plus
* a partitioned and a container cookie that never import), bank.test and mail.test.
* a partitioned and a container cookie that never import), bank.test and mail.test. Its history, in Firefox's own
* `moz_places` table, has two pages of github.com and one of bank.test, a bookmark never visited and a hidden place.
*/
export async function madeUpFirefox() {
const home = await mkdtemp(path.join(tmpdir(), "browser-sources-"))
@ -45,5 +46,22 @@ export async function madeUpFirefox() {
insert.run("mail.test", "session", "mail-secret", "/", later, 1, 1, 1, "", 0)
db.close()
return { home, env }
const places = new DatabaseSync(path.join(root, "Profiles", "work.default", "places.sqlite"))
// As Firefox 147 creates it.
places.exec(
"CREATE TABLE moz_places (id INTEGER PRIMARY KEY, url LONGVARCHAR, title LONGVARCHAR, rev_host LONGVARCHAR, visit_count INTEGER DEFAULT 0, hidden INTEGER DEFAULT 0 NOT NULL, typed INTEGER DEFAULT 0 NOT NULL, frecency INTEGER DEFAULT -1 NOT NULL, last_visit_date INTEGER, guid TEXT, foreign_count INTEGER DEFAULT 0 NOT NULL, url_hash INTEGER DEFAULT 0 NOT NULL, description TEXT, preview_image_url TEXT, site_name TEXT, origin_id INTEGER, recalc_frecency INTEGER NOT NULL DEFAULT 0, alt_frecency INTEGER, recalc_alt_frecency INTEGER NOT NULL DEFAULT 0)",
)
const place = places.prepare("INSERT INTO moz_places (url, title, visit_count, hidden, typed, last_visit_date) VALUES (?, ?, ?, ?, ?, ?)")
// Firefox counts a visit's time in microseconds.
const visited = (daysAgo: number) => (Date.now() - daysAgo * 86_400_000) * 1000
place.run("https://github.com/anomalyco/rune-desktop", "anomalyco/rune-desktop", 12, 0, 1, visited(1))
place.run("https://github.com/", "GitHub", 3, 0, 0, visited(40))
place.run("https://www.bank.test/accounts", null, 2, 0, 0, visited(2))
place.run("https://bookmarked.test/", "Never visited", 0, 0, 0, null)
place.run("https://github.com/redirect", "A redirect hop", 5, 1, 0, visited(1))
places.close()
return { home, env, profile: path.join(root, "Profiles", "work.default") }
}

View file

@ -7,6 +7,8 @@ import { deriveCbcKey, readChromiumCookies, readChromiumHosts, type ChromiumKey
import type { CookieRead } from "./cookie"
import type { SnapshotScratch } from "./database"
import { firefoxProfiles, readFirefoxCookies, readFirefoxHosts } from "./firefox"
import type { PageVisit } from "../history"
import { readChromiumHistory, readFirefoxHistory, readSafariHistory } from "./history"
import { parseBinaryCookies } from "./safari"
import type { CookieHost } from "./sites"
@ -290,6 +292,31 @@ export async function readSourceHosts(
return readChromiumHosts(located.target.database, scratch).catch(readFailure)
}
/**
* The pages of a profile's browsing history, the most used and most recent first; with `keep`, only those of the
* hosts it keeps. `profile` must be an id `listSources` returned. Safari's history needs Full Disk Access, as its
* cookies do. The other browser's files are only copied, never written or locked.
*/
export async function readSourceHistory(
id: string,
profile: string,
scratch: SnapshotScratch,
keep?: (host: string) => boolean,
): Promise<readonly PageVisit[] | SourceFailure> {
const located = await locateProfile(id, profile)
if (!located) return { failure: "read" }
const kept = { keep, now: Date.now() }
if (located.definition.engine === "firefox")
return readFirefoxHistory(path.join(located.target.directory, "places.sqlite"), scratch, kept).catch(readFailure)
if (located.definition.engine === "safari")
return readSafariHistory(path.join(located.definition.root, "Safari", "History.db"), scratch, kept).catch(readFailure)
return readChromiumHistory(path.join(located.target.directory, "History"), scratch, kept).catch(readFailure)
}
async function locateProfile(id: string, profile: string) {
const definition = definitions().find((item) => item.id === id)
const target = definition ? (await profiles(definition)).find((item) => item.id === profile) : undefined

View file

@ -488,11 +488,11 @@ const setup: Plugin.Setup<typeof definition> = (ctx) => {
title: ctx.t("settings.remote.title"),
keywords: "remote server sign in cookies share",
},
{ id: "settings-browser-cookies", title: ctx.t("settings.cookies.title"), keywords: "cookies sign out" },
{ id: "settings-browser-cookies", title: ctx.t("settings.cookies.title"), keywords: "cookies sign out history clear" },
{
id: "settings-browser-import",
title: ctx.t("settings.import.title"),
keywords: "import cookies chrome edge firefox safari helium arc brave sign in",
keywords: "import cookies history chrome edge firefox safari helium arc brave sign in",
},
{ id: "settings-browser-extensions", title: ctx.t("settings.extensions.title"), keywords: "extensions" },
{

View file

@ -2,7 +2,12 @@
import type { ExtensionCompatibility, InstallResult } from "./profile/ipc"
/** The search entries whose rows are inside Advanced. */
export const ADVANCED_ENTRIES = ["settings-browser-remote", "settings-browser-agent-pages", "settings-browser-sites", "settings-browser-cookies"]
export const ADVANCED_ENTRIES = [
"settings-browser-remote",
"settings-browser-agent-pages",
"settings-browser-sites",
"settings-browser-cookies",
]
/**
* Whether the Advanced section shows open: the person opened it on this device (`stored`), or a settings search is

View file

@ -76,8 +76,9 @@ const sampleExtensionEntries: readonly (readonly [string, readonly SampleExtensi
// Component-test fixture: the real Settings > Browser page with main's browser profile and site decisions faked at
// their Ipcs, and the stored preferences shown beside the page. `target` is the entry a settings search is revealing,
// which stays set for the whole visit, as the host leaves it. With `extensions`, Chromium browsers and their extensions
// are populated so the real Add an extension dialog can be driven end to end.
export function mountBrowserSettings(input: { ui: Ui; target?: string; extensions?: boolean; installed?: boolean }) {
// are populated so the real Add an extension dialog can be driven end to end. `historyKept` is a sign-out that left
// main's history behind: its file could not be removed.
export function mountBrowserSettings(input: { ui: Ui; target?: string; extensions?: boolean; installed?: boolean; historyKept?: boolean }) {
const host = document.createElement("main")
host.dataset.testid = "browser-settings-fixture"
document.body.appendChild(host)
@ -96,6 +97,11 @@ export function mountBrowserSettings(input: { ui: Ui; target?: string; extension
welcomed: true,
})
// The window's list of the last pages, which a sign-out empties.
const [history, setHistory] = createStore<{ visits: readonly { url: string; title: string }[] }>({
visits: [{ url: "https://alpha.example/", title: "Alpha" }],
})
const sampleExtensions = new Map(sampleExtensionEntries)
const installed = new Set<string>()
const staged = new Map<string, SampleExtension>()
@ -120,6 +126,7 @@ export function mountBrowserSettings(input: { ui: Ui; target?: string; extension
on: () => () => undefined,
sources: async () => (input.extensions ? [...sampleSources] : []),
summary: async () => ({ cookies: 0, persistent: true }),
clear: async () => ({ history: !input.historyKept }),
browserExtensions: async (request: { source: string; profile: string }) =>
input.extensions
? (sampleExtensions.get(request.source) ?? []).map((item) => ({
@ -214,6 +221,7 @@ export function mountBrowserSettings(input: { ui: Ui; target?: string; extension
update: (mutate: (draft: typeof preferences) => void) => setPreferences(produce(mutate)),
set: (next: typeof preferences) => setPreferences(next),
},
history: { value: history, ready: () => true, set: (next: typeof history) => setHistory(next) },
},
}
@ -225,6 +233,7 @@ export function mountBrowserSettings(input: { ui: Ui; target?: string; extension
<PluginContext.Provider value={plugin}>
<BrowserSettings target={input.target} />
<output data-testid="browser-settings-stored">{JSON.stringify(preferences)}</output>
<output data-testid="browser-settings-visits">{history.visits.length}</output>
</PluginContext.Provider>
)
}

View file

@ -15,10 +15,10 @@ import { showToast } from "@opencode/ui/toast"
import type { Job } from "./jobs-machine"
/**
* Settings › Browser: importing sign-ins, the extensions the profile runs and whether links open in the pane; then,
* under Advanced, sharing with remote servers, the agent's pages, the cookie-file import, site permissions and stored
* data. Every action goes through the jobs machine, so one runs at a time and each says how it ended beside
* the control that started it.
* Settings › Browser: importing from another browser, the extensions the profile runs and whether links open in the
* pane; then, under Advanced, sharing with remote servers, the agent's pages, the cookie-file import, site permissions
* and stored data. Every action goes through the jobs machine, so one runs at a time and
* each says how it ended beside the control that started it.
*/
export default function BrowserSettings(props: { target?: string }) {
const ctx = usePlugin<typeof definition>()
@ -85,7 +85,7 @@ export default function BrowserSettings(props: { target?: string }) {
// one closed "Advanced" section.
return (
<ui.SettingsLayout title={ctx.t("settings.title")}>
<ui.SettingsSection title={ctx.t("settings.import.title")} footer={<Note>{ctx.t("settings.import.note")}</Note>}>
<ui.SettingsSection title={ctx.t("settings.import.title")}>
<Show when={jobs.unsaved()}>
{(message) => (
<ui.SettingsRow

View file

@ -1,6 +1,6 @@
import { DialogProvider, useDialog } from "@opencode/ui/context/dialog"
import { createStore } from "solid-js/store"
import { For, onMount } from "solid-js"
import { For, onMount, type JSX } from "solid-js"
import { render } from "solid-js/web"
import { liveAccessor, PluginContext } from "@opencode/plugin/gui/host"
import type { Context, IpcClient, SetupContext, Ui } from "@opencode/plugin/gui"
@ -13,6 +13,7 @@ import { SignInOffer } from "./import-prompt"
/**
* What main answers the dialog: how many made-up sites the first profile has (or why it has none), whether the
* listing waits for the test, whether an import brings everything or (`partial`) leaves a cookie behind, and the page's site it opens for (`site`).
* `pages` is how many pages of history an import that asks for history brings.
*/
export type SiteScenario = {
/** The dialog opens with its site list shown, as where the person asked to choose sites. */
@ -24,8 +25,12 @@ export type SiteScenario = {
readonly protected?: number
readonly empty?: boolean
readonly site?: { readonly name: string; readonly choose: boolean }
readonly pages?: number
}
/** The dialog host, once the opener mounts under it: the offer opens its own import dialog there. */
type Hosted = { dialog?: ReturnType<typeof useDialog> }
const sources: ProfileSource[] = [
{
id: "chrome",
@ -56,7 +61,7 @@ function siteList(count: number): SiteList {
// Component-test fixture: the real import dialog, with jobs of its own, in the real dialog host, and main's browser
// profile faked at its Ipc. It records each import main receives and each list it reads in an element beside the
// dialog, so the test reads what would be imported, and whether the dialog closed.
export function mountSiteChooser(input: { ui: Ui; scenario: SiteScenario; direction?: "ltr" | "rtl"; offer?: boolean }) {
export function mountSiteChooser(input: { ui: Ui; scenario: SiteScenario; direction?: "ltr" | "rtl"; offer?: boolean; card?: boolean }) {
const host = document.createElement("main")
host.dataset.testid = "site-chooser-fixture"
host.dir = input.direction ?? "ltr"
@ -74,7 +79,7 @@ export function mountSiteChooser(input: { ui: Ui; scenario: SiteScenario; direct
(messages.get(key) ?? key).replace(/\{\{(\w+)\}\}/g, (_, name: string) => String(params?.[name] ?? ""))
const [store, setStore] = createStore<{
imports: { source: string; profile: string; sites?: readonly string[] }[]
imports: { source: string; profile: string; sites?: readonly string[]; cookies?: boolean; history?: boolean }[]
reads: string[]
closed: boolean
imported: number
@ -82,6 +87,7 @@ export function mountSiteChooser(input: { ui: Ui; scenario: SiteScenario; direct
}>({ imports: [], reads: [], closed: false, imported: 0, closes: 0 })
const held = Promise.withResolvers<void>()
const hosted: Hosted = {}
const client = {
state: () => ({ extensions: [], remoteSignIns: false }),
@ -97,10 +103,10 @@ export function mountSiteChooser(input: { ui: Ui; scenario: SiteScenario; direct
return input.scenario.sites === "locked" ? { type: "failed", reason: "locked" } : siteList(input.scenario.sites)
},
importBrowser: async (request: { source: string; profile: string; sites?: readonly string[] }): Promise<ImportResult> => {
importBrowser: async (request: { source: string; profile: string; sites?: readonly string[]; cookies?: boolean; history?: boolean }): Promise<ImportResult> => {
setStore("imports", (items) => [...items, request])
// Without a list of sites, main imports the whole profile.
const count = (request.sites?.length ?? 5) * 2
// Without a list of sites, main imports the whole profile; without cookies, only its history.
const count = request.cookies === false ? 0 : (request.sites?.length ?? 5) * 2
return {
type: "imported",
@ -108,6 +114,8 @@ export function mountSiteChooser(input: { ui: Ui; scenario: SiteScenario; direct
skipped: input.scenario.skipped ?? 0,
protected: input.scenario.protected ?? 0,
failed: input.scenario.partial ? 1 : 0,
// History comes only when the import asks for it.
pages: request.history ? input.scenario.pages : undefined,
}
},
}
@ -130,7 +138,14 @@ export function mountSiteChooser(input: { ui: Ui; scenario: SiteScenario; direct
desktop: { os: "windows" },
stores: { preferences: { value: { links: true, welcomed: !input.offer }, set() {} } },
layout: { settings() {} },
dialogs: { open: () => ({ close() {} }) },
dialogs: {
open: (content: (handle: { close: () => void }) => JSX.Element) => {
const handle = { close: () => hosted.dialog?.close() }
hosted.dialog?.show(() => <PluginContext.Provider value={plugin}>{content(handle)}</PluginContext.Provider>)
return handle
},
},
}
// SAFETY: the dialog uses only the context properties implemented above.
@ -139,13 +154,17 @@ export function mountSiteChooser(input: { ui: Ui; scenario: SiteScenario; direct
function Opener() {
const dialog = useDialog()
hosted.dialog = dialog
// With `offer`, the pane's sign-in bar instead of the dialog: the bar's import and its confirmation.
if (input.offer)
return (
<PluginContext.Provider value={plugin}>
<SignInOffer variant="bar" imported={() => setStore("imported", (count) => count + 1)} closed={() => setStore("closes", (count) => count + 1)} />
<ol data-testid="site-chooser-imports" data-closes={store.closes} data-imported={store.imported} />
<SignInOffer variant={input.card ? "card" : "bar"} imported={() => setStore("imported", (count) => count + 1)} closed={() => setStore("closes", (count) => count + 1)} />
{/* Out of the layout: the offer is measured and pictured where it is. */}
<ol hidden data-testid="site-chooser-imports" data-closes={store.closes} data-imported={store.imported}>
<For each={store.imports}>{(item) => <li>{JSON.stringify(item)}</li>}</For>
</ol>
</PluginContext.Provider>
)

View file

@ -23,18 +23,20 @@ const ROW_HEIGHT = 32
const TYPE_AHEAD_MS = 700
/**
* The import dialog, "Import from <browser>": one sentence of what comes over, and "Import all". A quiet "Choose
* sites" reveals, in place, the sites the browser profile has cookies for, one row per registrable domain with its
* cookie count, every one ticked until the person changes that; the button then names how many sites it brings. Main
* reads the list from the cookies' hosts alone. Lists stay only while the dialog is open, so switching back to a
* profile does not read it again; neither the lists nor the choice is stored.
* The import dialog, "Import from <browser>": what comes over, as two ticked boxes, "Sign-ins" and "Browsing history",
* and "Import". A quiet "Choose sites" reveals, in place under the boxes, the sites the browser profile has cookies
* for, one row per registrable domain, every one ticked until the person changes that; the button then names how many
* sites it brings. Main reads the list from the cookies' hosts alone. Lists stay only while the dialog is open, so
* switching back to a profile does not read it again; neither the lists nor any choice is stored: an import is a
* one-off, and each starts from everything.
*
* The import runs as a job of `jobs`, the surface that opened the dialog, which reports how it ended in its own place
* (a Settings row, the pane's offer). A clean import closes the dialog; a partial or failed one keeps it open and says
* why. `reveal` opens it with the list shown. `site` opens it with the list shown and searched for a page's
* registrable domain, as a passkey request's, on the first browser profile that lists exactly that site; with
* `choose`, that site alone is chosen there, and without it nothing is. A site that only contains it, such as
* `github.com` for `hub.com`, is shown but never chosen.
* `github.com` for `hub.com`, is shown but never chosen. Opened so, the dialog is about one site's sign-in: it
* shows no boxes and brings sign-ins only.
*/
export function SiteChooser(props: {
choices: readonly Choice[]
@ -75,6 +77,8 @@ export function SiteChooser(props: {
seeking: !!props.site,
revealed: !!props.site || !!props.reveal,
custom: !!props.site,
signins: true,
history: true,
})
// The import this dialog started, compared by identity with the jobs' own, which a store would wrap in a proxy.
@ -160,7 +164,9 @@ export function SiteChooser(props: {
const clean = () => {
const outcome = finished()?.outcome
return !!outcome && importedCookies(outcome) > 0 && outcome.type === "imported" && outcome.result.type === "imported" && !importLoss(outcome.result)
if (outcome?.type !== "imported" || outcome.result.type !== "imported" || importLoss(outcome.result)) return false
return outcome.result.imported > 0 || !!outcome.result.pages
}
// Closes the dialog host's dialog, outside Solid, once the import it started ended cleanly.
@ -221,8 +227,9 @@ export function SiteChooser(props: {
const selectShown = () => choose((next) => shown().forEach((item) => next.add(item.site)))
const clearShown = () => choose((next) => shown().forEach((item) => next.delete(item.site)))
// "Import all" needs no list: it works while the list is still being read, as the one-click import does.
// Importing everything needs no list: it works while the list is still being read, as the one-click import does.
const canImport = () =>
(!!props.site || state.signins || state.history) &&
(state.custom ? sites().size > 0 : result()?.type !== "listed" || all().length > 0) &&
props.jobs.available() &&
!busy() &&
@ -232,14 +239,15 @@ export function SiteChooser(props: {
if (!canImport()) return
const current = choice()
const next: Job = everything()
? { type: "import-browser", source: current.source.id, profile: current.profile.id }
: {
type: "import-browser",
source: current.source.id,
profile: current.profile.id,
sites: all().flatMap((item) => (sites().has(item.site) ? [item.site] : [])),
}
const next: Job = {
type: "import-browser",
source: current.source.id,
profile: current.profile.id,
sites: everything() ? undefined : all().flatMap((item) => (sites().has(item.site) ? [item.site] : [])),
// Opened for a page's site, the import is that site's sign-in and no history.
signins: !!props.site || state.signins,
history: !props.site && state.history,
}
setJob(next)
props.jobs.start(next)
@ -320,11 +328,6 @@ export function SiteChooser(props: {
return (
<ui.Dialog
title={ctx.t("signins.import", { browser: choiceLabel(choice()) })}
description={
result()?.type === "listed"
? ctx.plural("import.description", all().length, { number: number(all().length) })
: ctx.t("import.description.loading")
}
size={state.revealed ? "large" : "fit"}
footer={
<>
@ -337,30 +340,53 @@ export function SiteChooser(props: {
{ctx.t("common.cancel")}
</ui.Button>
<ui.Button variant="contrast" disabled={!canImport()} busy={!!job() && props.jobs.running() === job()} onClick={start}>
{everything() ? ctx.t("import.all") : ctx.plural("import.some", sites().size, { number: number(sites().size) })}
{everything() ? ctx.t("signins.action") : ctx.plural("import.some", sites().size, { number: number(sites().size) })}
</ui.Button>
</>
}
>
<Show
when={state.revealed}
fallback={
<Show when={message()}>
{(current) => (
<p
role={current().error ? "alert" : "status"}
class="py-1 text-[13px] leading-[var(--line-height-base)]"
classList={{ "text-v2-state-fg-danger": current().error, "text-v2-text-text-muted": !current().error }}
>
{current().text}
</p>
)}
</Show>
}
>
{/* The dialog's body scrolls, so it clips at its edges. The search field and the profile select draw their edge and
their focus ring just outside their box: the vertical padding keeps both inside the clip. */}
<div data-component="browser-site-chooser" class="flex h-full min-h-0 flex-col gap-3 py-1">
<div data-component="browser-site-chooser" class="flex h-full min-h-0 flex-col">
{/* What comes over: both, until the person unticks one. The rows are the first thing in the body with or without
the list, so they stay where they are when "Choose sites" opens it. Each box sits 6px inside its 28px row,
which keeps its focus ring inside the body's clip. Enter on a box imports, as it does on the list. */}
<Show when={!props.site}>
<div
class="flex shrink-0 flex-col"
onKeyDown={(event) => {
if (event.key !== "Enter" || event.isComposing) return
event.preventDefault()
start()
}}
>
<div class="flex h-7 items-center">
<Checkbox
appearance="compact"
surface={state.revealed ? "base" : "layer-1"}
checked={state.signins}
disabled={busy()}
onChange={(signins) => setState("signins", signins)}
>
{ctx.t("import.signins")}
</Checkbox>
</div>
<div class="flex h-7 items-center">
<Checkbox
appearance="compact"
surface={state.revealed ? "base" : "layer-1"}
checked={state.history}
disabled={busy()}
onChange={(history) => setState("history", history)}
>
{ctx.t("import.history")}
</Checkbox>
</div>
</div>
</Show>
<Show when={state.revealed}>
{/* The dialog's body scrolls, so it clips at its edges. The search field and the profile select draw their edge
and their focus ring just outside their box, and the list's frame its edge just inside the body's end: the
padding keeps them inside the clip. Under the boxes the search field starts 8px lower. */}
<div class="flex min-h-0 flex-1 flex-col gap-3 pb-1" classList={{ "pt-2": !props.site, "pt-1": !!props.site }}>
<div class="flex items-center gap-2">
<TextInput
appearance="large"
@ -472,7 +498,6 @@ export function SiteChooser(props: {
{(site) => (
<Show when={placed().get(site)}>
{(row) => {
const item = () => shown()[row().index]
const active = () => activeSite() === site
return (
@ -496,18 +521,12 @@ export function SiteChooser(props: {
}}
>
<Checkbox appearance="compact" surface="layer-1" presentation checked={sites().has(site)} />
{/* The name and the smaller count share a baseline. */}
<span class="flex min-w-0 flex-1 items-baseline gap-2">
{/* A long name loses its start, so the registrable domain at its end stays in view. */}
<span
class="min-w-0 flex-1 truncate text-[13px] leading-[var(--line-height-base)] text-v2-text-text-base [direction:rtl] ltr:text-left rtl:text-right"
title={site}
>
<bdi dir="ltr">{site}</bdi>
</span>
<bdi dir="auto" class="shrink-0 text-[12px] leading-[var(--line-height-compact)] tabular-nums text-v2-text-text-muted">
{ctx.plural("sites.cookies", item()?.cookies ?? 0, { number: number(item()?.cookies ?? 0) })}
</bdi>
{/* A long name loses its start, so the registrable domain at its end stays in view. */}
<span
class="min-w-0 flex-1 truncate text-[13px] leading-[var(--line-height-base)] text-v2-text-text-base [direction:rtl] ltr:text-left rtl:text-right"
title={site}
>
<bdi dir="ltr">{site}</bdi>
</span>
</div>
)
@ -542,11 +561,13 @@ export function SiteChooser(props: {
)}
</Show>
</div>
</div>
</Show>
<Show when={message()}>
{(current) => (
<p
role={current().error ? "alert" : "status"}
class="shrink-0 text-[13px] leading-[var(--line-height-base)]"
class="shrink-0 py-1 text-[13px] leading-[var(--line-height-base)]"
classList={{ "text-v2-state-fg-danger": current().error, "text-v2-text-text-muted": !current().error }}
>
{current().text}
@ -554,7 +575,6 @@ export function SiteChooser(props: {
)}
</Show>
</div>
</Show>
</ui.Dialog>
)
}
@ -562,7 +582,7 @@ export function SiteChooser(props: {
/**
* The dialog's state: the profile shown and the search; the chosen sites of one profile, so switching profiles starts
* from none; the active row and whether the list has the keyboard; how often the list was read again; what the
* type-ahead has so far; and whether it still looks for the profile that has the searched site.
* type-ahead has so far; whether it still looks for the profile that has the searched site; and what comes over.
*/
type ChooserState = {
profile: string
@ -577,6 +597,10 @@ type ChooserState = {
revealed: boolean
/** The person changed which sites come over, or the dialog opened for one site; before that, every site does. */
custom: boolean
/** The sign-ins come over; ticked until the person unticks it. */
signins: boolean
/** The browsing history comes over; ticked until the person unticks it. */
history: boolean
}
/** The list's scrolling viewport and the listbox in it, once they mount. */

View file

@ -109,7 +109,7 @@ export function webAuthnGateScript(report: string, answer: string, native: boole
/** Why an agent command stopped: the page it drove asked for a passkey or security key, which was refused. */
export function agentPasskeyRefusal(site: string | undefined) {
return `${site || "The page"} asked for a passkey or security key (WebAuthn). The desktop browser refused it at once with NotAllowedError: agent tools cannot complete a passkey or security-key sign-in. The site may now offer another sign-in method; otherwise ask the user to sign in with their own browser and import the sign-in (Settings > Browser > Import sign-ins). Then continue with browser.snapshot({tabID}).`
return `${site || "The page"} asked for a passkey or security key (WebAuthn). The desktop browser refused it at once with NotAllowedError: agent tools cannot complete a passkey or security-key sign-in. The site may now offer another sign-in method; otherwise ask the user to sign in with their own browser and import the sign-in (Settings > Browser > Import from another browser). Then continue with browser.snapshot({tabID}).`
}
/**