feat(browser): open a link's new tab beside the tab it came from (#65126)

This commit is contained in:
Luke Parker
2026-11-20 06:33:59 -06:00
committed by GitHub
Unverified
parent bfee96a859
commit 80d7c17d8e
18 changed files with 819 additions and 59 deletions
@@ -24,6 +24,7 @@ const modules = {
settings: source("../src/settings/model.tsx"),
platform: source("../src/runtime/platform/platform.tsx"),
solid: source("./plugin-host.fixture.tsx"),
sessionTabs: source("../src/shell/state/session-tabs.ts"),
}
story.beforeEach(async ({ mount, page }) => {
@@ -45,6 +46,7 @@ story.beforeEach(async ({ mount, page }) => {
solid,
closed,
pluginCommands,
sessionTabs,
] = await Promise.all([
import(modules.fixture),
import(modules.host),
@@ -60,6 +62,7 @@ story.beforeEach(async ({ mount, page }) => {
import(modules.solid),
import(modules.closed),
import(modules.pluginCommands),
import(modules.sessionTabs),
// Load the pane before mounting: Vite must not reload the page to optimize its dependencies mid-fixture.
import(modules.browserPanel),
])
@@ -211,6 +214,7 @@ story.beforeEach(async ({ mount, page }) => {
return null
},
Contribution: renderer.Contribution,
appendTab: sessionTabs.appendSessionTab,
})
}, modules)
})
@@ -724,9 +728,10 @@ type MainTab = {
// The fixture reads each one through the pane Ipc's own event schema, so a shape main cannot send fails there.
type MainEvent =
| { type: "state"; state: { tabs: MainTab[]; focusedTabID: string } | null; error?: string }
| { type: "state"; state: { tabs: MainTab[]; focusedTabID: string } | null; error?: string; unnamed?: string[]; placed?: { tabID: string; after: string } }
| { type: "page"; tabID: string; zoom: number; viewport: { mode: "auto" }; icon?: string }
| { type: "embed"; tabID: string; embed: string }
| { type: "focus"; tabID: string }
const preview = "tab_33333333-3333-3333-3333-333333333333"
@@ -851,6 +856,184 @@ story("holds every restored tab's box, label and icon from the reopen until its
expect(first.map((tab) => tab.icon)).toEqual([expect.any(String), previewIcon, docsIcon])
})
// A tab a link opened was added at the end of the strip, after every other tab, however far from the tab it came from.
// Now it appears at the click, beside that tab, as in Chrome. The strip sizes a tab by its label, so the tabs after it
// move when it appears and when it takes its page's title, and at no other step: it keeps its new-tab label while its
// page loads and has only Chromium's name for it, its address, which would move them a third time.
type Box = Awaited<ReturnType<typeof drawn>>[number]
// `after` is `before` with one tab added at `index`: it takes the place of the tab that stood there, every tab after it
// moves right by its width and the strip's gap, and no other tab moves or changes width, label or icon.
const expectInserted = (before: Box[], after: Box[], index: number) => {
const gap = before[1].x - before[0].x - before[0].width
const added = after[index]
expect(after.length).toBe(before.length + 1)
expect(after.slice(0, index)).toEqual(before.slice(0, index))
expect(added.x).toBeCloseTo(before[index]?.x ?? before[index - 1].x + before[index - 1].width + gap, 3)
after.slice(index + 1).forEach((tab, offset) => {
const earlier = before[index + offset]
expect({ ...tab, x: 0 }).toEqual({ ...earlier, x: 0 })
expect(tab.x).toBeCloseTo(earlier.x + added.width + gap, 3)
})
}
// `after` is `before` with the tab at `index` relabelled `text`: it stays where it stood with another width, every tab
// after it moves by that difference, and no other tab moves or changes width, label or icon.
const expectRenamed = (before: Box[], after: Box[], index: number, text: string) => {
const grown = after[index].width - before[index].width
expect(after.length).toBe(before.length)
expect(after.slice(0, index)).toEqual(before.slice(0, index))
expect(after[index]).toEqual({ ...before[index], text, width: after[index].width })
expect(grown).not.toBe(0)
after.slice(index + 1).forEach((tab, offset) => {
const earlier = before[index + 1 + offset]
expect({ ...tab, x: 0 }).toEqual({ ...earlier, x: 0 })
expect(tab.x).toBeCloseTo(earlier.x + grown, 3)
})
}
// Beta with three loaded browser tabs after its file tab, and Docs, the middle one, in front.
const linkStrip = async (page: Page) => {
const root = page.getByTestId("browser-region-fixture")
const tabs = root.getByRole("tab")
const first = reported({ id: preview, url: "http://localhost:4173/", title: "Preview" })
const middle = reported({ id: docs, url: "https://example.com/docs", title: "Docs" })
const last = reported({ id: "tab_77777777-7777-7777-7777-777777777777", url: "https://example.com/guide", title: "Guide" })
await root.getByRole("button", { name: "Beta", exact: true }).click()
await expect(root.getByText("Registrations: 2", { exact: true })).toBeVisible()
await send(root, inventory(first, middle, last))
await root.getByRole("tab", { name: "Docs", exact: true }).click()
await expect(root.getByTestId("selected")).toHaveText(`browser:${docs}`)
await page.evaluate(() => document.fonts.ready.then(() => undefined))
expect((await drawn(tabs)).map((tab) => tab.text)).toEqual(["beta.ts", "Preview", "Docs", "Guide"])
// Main's inventory with `opened` between Docs and Guide, as it reports it (`publish` in pane-machine.ts).
const listed = (opened: MainTab[], rest: { unnamed?: string[]; placed?: { tabID: string; after: string }; focusedTabID?: string } = {}) => ({
type: "state" as const,
state: { tabs: [first, middle, ...opened, last], focusedTabID: rest.focusedTabID ?? docs },
...(rest.unnamed && { unnamed: rest.unnamed }),
...(rest.placed && { placed: rest.placed }),
})
return { root, tabs, listed, selected: root.getByTestId("selected") }
}
// What a tab a link opened reports, in order, as measured in Electron: blank, its load starts, its document commits
// under Chromium's name for it, the document names itself, and the load ends.
const linkPage = (id: string, path: string, title: string) => {
const blank = reported({ id, url: "about:blank", title: "" })
const committed = { ...blank, url: `https://example.com/${path}`, title: `example.com/${path}`, loading: true, generation: 1 }
return { id, blank, started: { ...blank, loading: true }, committed, named: { ...committed, title }, ended: { ...committed, title, loading: false } }
}
story("a tab a link opens behind appears at once beside the tab it came from, and its page's title is its only other change", async ({ page }) => {
const { root, tabs, listed, selected } = await linkStrip(page)
const one = linkPage("tab_88888888-8888-8888-8888-888888888888", "one", "One")
const two = linkPage("tab_99999999-9999-9999-9999-999999999999", "two", "Second page")
const three = linkPage("tab_aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "three", "Three")
const before = await drawn(tabs)
// The person middle-clicks a link in Docs: the tab appears at once, after Docs, behind it.
await send(root, listed([one.blank], { placed: { tabID: one.id, after: docs }, unnamed: [one.id] }))
await expect(tabs).toHaveText(["beta.ts", "Preview", "Docs", "New tab", "Guide"])
const shown = await drawn(tabs)
expectInserted(before, shown, 3)
// Its load starts and its document commits, with Chromium's name for it: no box moves or changes width or label.
for (const waiting of [one.started, one.committed]) {
await send(root, listed([waiting], { unnamed: [one.id] }))
expect(await drawn(tabs)).toEqual(shown)
}
// Its document names itself: the tab takes that name, where it stands.
await send(root, listed([one.named]))
await expect(tabs).toHaveText(["beta.ts", "Preview", "Docs", "One", "Guide"])
const named = await drawn(tabs)
expectRenamed(shown, named, 3, "One")
// Its icon arrives and its load ends: no box moves or changes width.
await send(root, details(one.id, docsIcon))
await expect(root.getByRole("tab", { name: "One", exact: true }).locator("img")).toHaveAttribute("src", docsIcon)
await send(root, listed([one.ended]))
const loaded = await drawn(tabs)
expect(loaded).toEqual([...named.slice(0, 3), { ...named[3], icon: docsIcon }, named[4]])
await expect(selected).toHaveText(`browser:${docs}`)
// Two more middle-clicks in a row: each appears at its click, in the order they were opened, after One.
await send(root, listed([one.ended, two.blank], { placed: { tabID: two.id, after: one.id }, unnamed: [two.id] }))
await expect(tabs).toHaveText(["beta.ts", "Preview", "Docs", "One", "New tab", "Guide"])
const second = await drawn(tabs)
expectInserted(loaded, second, 4)
await send(root, listed([one.ended, two.started, three.blank], { placed: { tabID: three.id, after: two.id }, unnamed: [two.id, three.id] }))
await expect(tabs).toHaveText(["beta.ts", "Preview", "Docs", "One", "New tab", "New tab", "Guide"])
const third = await drawn(tabs)
expectInserted(second, third, 5)
await send(root, listed([one.ended, two.started, three.started], { unnamed: [two.id, three.id] }))
await send(root, listed([one.ended, two.committed, three.committed], { unnamed: [two.id, three.id] }))
expect(await drawn(tabs)).toEqual(third)
// The second one's page is named first: only it is relabelled, and only Guide moves.
await send(root, listed([one.ended, two.committed, three.named], { unnamed: [two.id] }))
await expect(tabs).toHaveText(["beta.ts", "Preview", "Docs", "One", "New tab", "Three", "Guide"])
const reversed = await drawn(tabs)
expectRenamed(third, reversed, 5, "Three")
// Then the first one's: Three and Guide move once more, for this tab.
await send(root, listed([one.ended, two.named, three.named]))
await expect(tabs).toHaveText(["beta.ts", "Preview", "Docs", "One", "Second page", "Three", "Guide"])
const ordered = await drawn(tabs)
expectRenamed(reversed, ordered, 4, "Second page")
await send(root, listed([one.ended, two.ended, three.ended]))
expect(await drawn(tabs)).toEqual(ordered)
await expect(selected).toHaveText(`browser:${docs}`)
// The app quits and opens again: the strip draws the same order at once, and main's restored tabs move nothing.
await root.getByRole("button", { name: "Quit and reopen", exact: true }).dispatchEvent("click")
await expect(root.getByText("Registrations: 3", { exact: true })).toBeVisible()
await expect(tabs).toHaveText(["beta.ts", "Preview", "Docs", "One", "Second page", "Three", "Guide"])
expect(await drawn(tabs)).toEqual(ordered)
const restored = listed([one.ended, two.ended, three.ended])
await send(root, { ...restored, state: { ...restored.state, tabs: restored.state.tabs.map((tab) => ({ ...tab, title: "", generation: 1 })) } })
await expect(root.getByRole("status", { name: "Loading", exact: true })).toHaveCount(0)
expect(await drawn(tabs)).toEqual(ordered)
await expect(selected).toHaveText(`browser:${docs}`)
})
story("a tab a link opens in front appears at once, selected, beside the tab it came from, and its page's title is its only other change", async ({ page }) => {
const { root, tabs, listed, selected } = await linkStrip(page)
const front = linkPage("tab_88888888-8888-8888-8888-888888888888", "front", "In front")
const address = root.getByRole("combobox", { name: "Browser address", exact: true })
const before = await drawn(tabs)
// The person clicks a `target="_blank"` link in Docs: main lists the tab after Docs and brings it to the front, in
// that order (`tab.opened`, then `tab.focused`, in pane-machine.ts).
await send(root, listed([front.blank], { placed: { tabID: front.id, after: docs }, unnamed: [front.id] }))
await send(root, listed([front.blank], { unnamed: [front.id], focusedTabID: front.id }))
await send(root, { type: "focus", tabID: front.id })
await expect(selected).toHaveText(`browser:${front.id}`)
await expect(tabs).toHaveText(["beta.ts", "Preview", "Docs", "New tab", "Guide"])
const shown = await drawn(tabs)
expectInserted(before, shown, 3)
// Its load starts and its document commits: the pane shows the address, and no box moves or changes width or label.
await send(root, listed([front.started], { unnamed: [front.id], focusedTabID: front.id }))
await expect(root.getByRole("button", { name: "Stop", exact: true })).toBeVisible()
expect(await drawn(tabs)).toEqual(shown)
await send(root, listed([front.committed], { unnamed: [front.id], focusedTabID: front.id }))
await expect(address).toHaveValue("https://example.com/front")
expect(await drawn(tabs)).toEqual(shown)
// Its document names itself: the tab takes that name, where it stands.
await send(root, listed([front.named], { focusedTabID: front.id }))
await expect(tabs).toHaveText(["beta.ts", "Preview", "Docs", "In front", "Guide"])
const named = await drawn(tabs)
expectRenamed(shown, named, 3, "In front")
await send(root, details(front.id, docsIcon))
await expect(root.getByRole("tab", { name: "In front", exact: true }).locator("img")).toHaveAttribute("src", docsIcon)
await send(root, listed([front.ended], { focusedTabID: front.id }))
await expect(root.getByRole("button", { name: "Reload", exact: true })).toBeVisible()
expect(await drawn(tabs)).toEqual([...named.slice(0, 3), { ...named[3], icon: docsIcon }, named[4]])
await expect(selected).toHaveText(`browser:${front.id}`)
})
// A page's icon arrives after its tab is drawn: Chromium lists it once the document's head has parsed, and main loads
// it. The tab draws the globe until then. A site's SVG is drawn as an image, never put in the window as markup.
story("a tab draws its page's icon in the globe's place as an image, and no tab moves", async ({ page }) => {
@@ -25,7 +25,6 @@ import {
type MountedSession,
type NotifyOptions,
type NotifyResult,
type OpenOptions,
type PanelSidebar,
type PanelState,
type ServerRef,
@@ -36,7 +35,7 @@ import {
type StorageScope,
type Tabs,
} from "@opencode/plugin/gui"
import { BuiltinPanel, BuiltinPromptGate, type BuiltinStoreFrom, type BuiltinStoreOptions } from "@opencode/plugin/gui/builtin"
import { BuiltinPanel, BuiltinPromptGate, type BuiltinOpenOptions, type BuiltinStoreFrom, type BuiltinStoreOptions } from "@opencode/plugin/gui/builtin"
import { usePlatform } from "@/runtime/platform/platform"
import { same } from "@/runtime/persistence/equality"
import { Persist, persisted, removePersisted } from "@/runtime/persistence/storage"
@@ -107,7 +106,8 @@ type Attached = {
scope: (server: string) => ServerScope
/** Records a session-scoped store so layout pruning drops it with the session. */
scoped: (name: string) => void
layout: Omit<Layout, "narrow" | "settings" | "project" | "draft" | "command" | "stored" | "side"> & {
layout: Omit<Layout, "narrow" | "settings" | "project" | "draft" | "command" | "stored" | "side" | "open"> & {
open(key: string, session: SessionRef, options?: BuiltinOpenOptions): void
stored(plugin: string, session: SessionRef): readonly string[]
/** `width` and `resize` take the panel's host key, `${plugin}:${panel id}`. */
side: Layout["side"]
@@ -842,7 +842,7 @@ export function createPluginAttachment(apis: HostApis) {
key: string,
session: SessionRef,
value: string,
options: OpenOptions | undefined,
options: BuiltinOpenOptions | undefined,
via: "open" | "toggle",
) => {
const wasOpen = sideOpened(session)
@@ -868,18 +868,18 @@ export function createPluginAttachment(apis: HostApis) {
if (mountedSession(session)) region()?.opening(key)
}
const place = (key: string, session: SessionRef, value: string, options: OpenOptions | undefined) => {
const place = (key: string, session: SessionRef, value: string, options: BuiltinOpenOptions | undefined) => {
const item = provider(key)
const placement = options?.tab ?? "open"
// An append adds the tab quietly: no selection, no region change, no preview replacement.
if (placement === "append") return layout.panel.append(value, key)
if (placement === "append") return layout.panel.append(value, key, options?.after)
// A select keeps the narrow-screen view, as a background open does, and shows the tab's pane too.
if (placement === "select")
return batch(() => {
uncover(session, key)
layout.panel.append(value, key)
layout.panel.append(value, key, options?.after)
layout.panel.focus(value, key)
reveal(session, value, key)
})
@@ -907,7 +907,7 @@ export function createPluginAttachment(apis: HostApis) {
})
}
const open = (key: string, session: SessionRef, options?: OpenOptions) =>
const open = (key: string, session: SessionRef, options?: BuiltinOpenOptions) =>
withLocated(session, (value) => openAt(key, session, value, options, "open"))
const closeAt = (key: string, session: SessionRef, value: string) => {
+5 -4
View File
@@ -16,6 +16,7 @@ import { SessionStateKey } from "@/runtime/server/scope"
import { createSessionKeyReader, ensureSessionKey, pruneSessionKeys } from "./helpers"
import { requireServerKey } from "@/shell/routes/session"
import {
appendSessionTab,
closeSessionTab,
moveSessionTab,
openSessionTab,
@@ -629,12 +630,12 @@ export const { use: useLayout, provider: LayoutProvider } = createSimpleContext(
preview(session: string, tab: string, launchers?: ReadonlySet<string>) {
applyTabs(session, previewSessionTab(tabState(session), tab, launchers))
},
/** Adds a tab at the end of the strip without selecting it or touching the preview. */
append(session: string, tab: string) {
/** Adds a tab without selecting it or touching the preview: after `after` when given and stored, else at the end. */
append(session: string, tab: string, after?: string) {
const current = store.sessionTabs[session] ?? { all: [] }
const next = appendSessionTab(current, tab, after)
if (current.all.includes(tab)) return
writeTabs(session, { ...current, all: [...current.all, tab] })
if (next !== current) writeTabs(session, next)
},
focus(session: string, tab: string) {
writeTabs(session, { ...(store.sessionTabs[session] ?? { all: [] }), active: tab })
@@ -1,5 +1,6 @@
import { expect, test } from "bun:test"
import {
appendSessionTab,
closeSessionTab,
moveSessionTab,
openSessionTab,
@@ -171,3 +172,17 @@ test("closing the selected tab of a pane selects its neighbour in the same pane"
expect(closeSessionTab({ tabs }, T2).tabs.active).toBe(T1)
})
test.each([
{ name: "append adds a tab at the end without selecting it", after: undefined, expected: ["a", "b", "c", "new"] },
{ name: "append places a tab directly after the tab it names", after: "a", expected: ["a", "new", "b", "c"] },
{ name: "append after the last tab is the end", after: "c", expected: ["a", "b", "c", "new"] },
{ name: "append after a tab the strip does not store is the end", after: "gone", expected: ["a", "b", "c", "new"] },
])("$name", ({ after, expected }) => {
expect(appendSessionTab({ all: ["a", "b", "c"], active: "b" }, "new", after)).toEqual({ all: [...expected], active: "b" })
})
test("append leaves a tab the strip stores where it is", () => {
const tabs: SessionTabs = { all: ["a", "b", "c"], active: "b" }
expect(appendSessionTab(tabs, "c", "a")).toBe(tabs)
})
@@ -130,6 +130,18 @@ export function moveSessionTab(current: SessionTabs, tab: string, pane: SessionP
})
}
/**
* Adds `tab` to the strip without selecting it or touching the preview: directly after `after` when the strip stores
* that tab, else at the end. A tab the strip stores already stays where it is.
*/
export function appendSessionTab(current: SessionTabs, tab: string, after?: string): SessionTabs {
if (current.all.includes(tab)) return current
const index = after === undefined ? -1 : current.all.indexOf(after)
const position = index === -1 ? current.all.length : index + 1
return { ...current, all: [...current.all.slice(0, position), tab, ...current.all.slice(position)] }
}
/** The tab a pane shows: the active tab in its pane, else the pane's own selection. */
export function sessionPaneTab(tabs: SessionTabs, pane: SessionPane) {
if (tabs.active !== undefined && sessionTabPane(tabs, tabs.active) === pane) return tabs.active
@@ -4,6 +4,7 @@ import electron from "electron"
import type { BuiltinMainStorage } from "@opencode/plugin/gui/builtin"
import type { Embeds } from "@opencode/plugin/gui/main"
import type { RefusalNotice } from "./ipc"
import type { BindingEvent } from "./pane-machine"
import type { TabActivity } from "./policy"
// The Electron main process of `electron-links.test.ts`, bundled and run by the pinned Electron. It opens one pane page
@@ -33,6 +34,7 @@ const links = `<!doctype html><title>Links</title>
<a href="/to-mail" style="top:350px">Mail redirect</a>
<a href="/to-refused" style="top:400px">Refused redirect</a>
<a href="/then-download" style="top:450px">Page then download</a>
<a href="/slow" style="top:500px">Slow link</a>
<script>
window.presses = 0
window.moves = 0
@@ -108,6 +110,7 @@ void electron.app.whenReady().then(async () => {
const { Browser } = await import("@opencode/plugin-browser/rpc")
const { createBrowserPage } = await import("./chromium")
const { createHandlePath } = await import("./disk")
const { createPaneState, selectBinding, transitionPane } = await import("./pane-machine")
const { activityOwner } = await import("./policy")
const { createSitePermissions } = await import("./site-permissions")
const { createSystemMedia } = await import("./system-media")
@@ -124,6 +127,14 @@ void electron.app.whenReady().then(async () => {
return void held.add(response)
}
// A server that is slow to answer, and a document whose title comes later still, as a real site's does.
if (request.url === "/slow")
return void setTimeout(() => {
response.writeHead(200, { "content-type": "text/html" })
response.write("<!doctype html><meta charset=utf-8>")
setTimeout(() => response.end("<title>Slow</title><p>slow</p>"), 300)
}, 300)
if (request.url === "/to-mail") return void response.writeHead(302, { location: "mailto:someone@example.test" }).end()
// An address with a password, which the pane opens nowhere.
@@ -210,11 +221,66 @@ void electron.app.whenReady().then(async () => {
const made = { count: 0 }
// What the page asked the pane for: each tab with whether it stays behind the current one, and each notice.
type Opened = { readonly background: boolean; readonly owner: string; closed: boolean; readonly notices: RefusalNotice[] }
type Opened = {
readonly background: boolean
readonly owner: string
closed: boolean
readonly notices: RefusalNotice[]
/** Its page in the pane's machine, once it is listed there. */
attempt?: number
/**
* What the pane told the window about this tab, in order, each time it changed: whether the strip keeps its new-tab
* label, its title, whether it loads, its address, and with the report that first lists it, where it stands.
*/
readonly reports: string[]
}
const opened: Opened[] = []
const tabs = new Map<Opened, Page>()
const notices: RefusalNotice[] = []
const listed = new Map<string, Opened>()
// The pane's own machine, which decides what the window's strip is told about each tab from what its page publishes.
const pane = {
state: transitionPane(
transitionPane(createPaneState(), { type: "registered", binding: "links", window: win.id, storageKey: "links", restore: undefined, saved: { tabs: [], focusedTabID: null } }).state,
{ type: "binding", binding: "links", event: { type: "server.attached", fileRoots: [] } },
).state,
}
const dispatch = (event: BindingEvent) => {
const next = transitionPane(pane.state, { type: "binding", binding: "links", event })
pane.state = next.state
for (const effect of next.effects) {
if (effect.type !== "report" || effect.event.type !== "state") continue
const told = effect.event
told.state?.tabs.forEach((tab) => {
const report = [
told.unnamed?.includes(tab.id) ? "new-tab label," : "page's title,",
tab.title.replace(`127.0.0.1:${port}`, "") || "untitled",
tab.loading ? "loading" : "loaded",
tab.url.replace(origin, ""),
...(told.placed?.tabID === tab.id ? [told.placed.after === tabID ? "after the pressed tab" : "after another tab"] : []),
].join(" ")
const reports = listed.get(tab.id)?.reports
if (reports && reports.at(-1) !== report) reports.push(report)
})
}
}
type Opening = Extract<BindingEvent, { readonly type: "tab.opened" }>
// Lists a new page as the pane does (`create` in pane.ts), and says which page of its tab it is.
const list = (tab: Opening["tab"], beside?: Opening["beside"]) => {
const attempt = selectBinding(pane.state, "links")?.nextAttempt ?? 0
dispatch({ type: "tab.opened", tabID: tab.id, attempt, tab, beside })
return attempt
}
// A page as the pane makes it (`create` in pane.ts). One a link or script opened adopts Chromium's new contents, says
// its own notices, and can close itself or hand an address back to the tab that opened it.
@@ -237,14 +303,21 @@ void electron.app.whenReady().then(async () => {
},
refused: popup.refused,
},
publish: () => undefined,
publish: () => {
const tab = popup && tabs.get(popup.tab)?.state()
if (tab && popup.tab.attempt !== undefined) dispatch({ type: "tab.published", tabID: tab.id, attempt: popup.tab.attempt, tab })
},
refused: (notice) => (popup ? popup.tab.notices : notices).push(notice),
fail: () => undefined,
popup: (options, background, child, refused) => {
const tab: Opened = { background, owner: activityOwner(child), closed: false, notices: [] }
const tab: Opened = { background, owner: activityOwner(child), closed: false, notices: [], reports: [] }
const page = make(child, { options, tab, refused })
opened.push(tab)
tabs.set(tab, page)
listed.set(page.state().id, tab)
// The person's tab stands beside the one it came from; the agent's goes to the end.
tab.attempt = list(page.state(), tab.owner === "agent" ? undefined : { tabID: created.state().id, front: !background })
return page.contents
},
@@ -269,6 +342,7 @@ void electron.app.whenReady().then(async () => {
const activity: TabActivity = { agentRuns: 0 }
const page = make(activity)
const tabID = page.state().id
list(page.state())
await page.ready
const turn = () => new Promise<void>((resolve) => setTimeout(resolve, 20))
@@ -425,6 +499,9 @@ void electron.app.whenReady().then(async () => {
return (await count("moves")) > 0
})
const modifier = process.platform === "darwin" ? "meta" : "control"
// First, while the pressed tab is the only other one: a link to a slow page, middle-clicked.
const slow = await press(10, "middle")
const reports = opened[0]?.reports
const middle = await press(0, "middle")
const modified = await press(0, "left", [modifier])
const modifiedShift = await press(0, "left", [modifier, "shift"])
@@ -463,7 +540,7 @@ void electron.app.whenReady().then(async () => {
for (const delay of [50, 500, 2000]) afterwards.push(await pressThenWait(row, kind, delay))
process.stdout.write(
`${JSON.stringify({ platform: process.platform, middle, modified, modifiedShift, middleShift, shift, blank, blankMiddle, mail, mailMiddle, nothing, opener, openerMiddle, key, download, blankDownload, mailRedirect, refusedRedirect, thenDownload: thenDownloaded, agent, agentDownload, reclaimed, synthetic: synthesized, timer, afterPress: afterwards })}\n`,
`${JSON.stringify({ platform: process.platform, slow, reports, middle, modified, modifiedShift, middleShift, shift, blank, blankMiddle, mail, mailMiddle, nothing, opener, openerMiddle, key, download, blankDownload, mailRedirect, refusedRedirect, thenDownload: thenDownloaded, agent, agentDownload, reclaimed, synthetic: synthesized, timer, afterPress: afterwards })}\n`,
)
await page.dispose()
server.closeAllConnections()
@@ -36,13 +36,25 @@ const blocked = (url: string, owner: string): Outcome => ({ tabs: [], notices: [
test(
"the person's middle-click and modified clicks on a link open tabs as in Chrome, a tab left with nothing to show closes, and the agent's and a page's own stay blocked pop-ups, right after a press too",
async () => {
const result: Record<string, Outcome> & { agent: Outcome & { refusal?: string }; platform: string; afterPress: object[] } = JSON.parse(
const result: Record<string, Outcome> & { agent: Outcome & { refusal?: string }; platform: string; afterPress: object[]; reports: string[] } = JSON.parse(
await runElectronFixture({ fixture: path.join(import.meta.dir, "electron-links.fixture.ts") }),
)
// A middle-click, and a Ctrl+click (Cmd+click on macOS): a new tab behind the current one, with no opener and no
// notice. Enter on the focused link with the same modifier is the same.
expect(result.middle).toEqual(behind("/target?plain"))
// A slow page's tab, as the pane's machine reports it to the window from what the page publishes: listed at the
// click, right after the pressed tab, with its new-tab label. It keeps that label while its load starts and its
// document commits under Chromium's name for it (its address), and takes the page's title once, when the document
// names itself. Nothing but `loading` changes after that.
expect(result.slow).toEqual(behind("/slow"))
expect(result.reports).toEqual([
"new-tab label, untitled loaded about:blank after the pressed tab",
"new-tab label, untitled loading about:blank",
"new-tab label, /slow loading /slow",
"page's title, Slow loading /slow",
"page's title, Slow loaded /slow",
])
expect(result.modified).toEqual(behind("/target?plain"))
expect(result.key).toEqual(behind("/target?plain"))
// With Shift as well, the new tab opens in front.
+7
View File
@@ -181,6 +181,13 @@ export const PaneEvent = Schema.Union([
type: Schema.Literal("state"),
state: Schema.NullOr(Browser.State),
error: Schema.optionalKey(Schema.String),
// Tabs a link opened whose first page has no name of its own yet. The strip sizes a tab by its label, so each keeps
// its new-tab label until it leaves this list, and takes its page's title once: never Chromium's name for a
// document that has not named itself, which is its address.
unnamed: Schema.optionalKey(Schema.Array(Browser.TabID)),
// With the inventory that first lists such a tab: the tab it stands after, as in Chrome. The window's strip holds
// other panels' tabs too, so it adds the tab there instead of at its end.
placed: Schema.optionalKey(Schema.Struct({ tabID: Browser.TabID, after: Browser.TabID })),
}),
// A tab's page exists; the renderer lays it out through this host embed.
Schema.Struct({ type: Schema.Literal("embed"), tabID: Browser.TabID, embed: text(256) }),
@@ -16,6 +16,7 @@ import {
sessionSuspended,
sessionTabs,
sessionUnavailable,
tabUnnamed,
transition,
type Attachment,
type Event,
@@ -635,6 +636,30 @@ describe("browser pane machine", () => {
expect(transition(state, { type: "session.retry", sessionKey: key }).state).toBe(state)
})
test("a tab a link opens joins the strip at once, after the tab the desktop names, and keeps its new-tab label until its page is named", () => {
const start = ready()
const placed = { tabID: tabB, after: tabA }
// The inventory as main reports it: with the tab it lists for the first time and where, and the tabs with no name yet.
const report = (state: State, browser: Browser.State, rest: { unnamed?: Browser.TabID[]; placed?: typeof placed }): Event => ({ type: "pane.state", sessionKey: key, attempt: attempt(state), state: browser, error: undefined, ...rest })
const strips = (effects: readonly MachineEffect[]) => effects.filter((effect) => effect.type === "sync-strip")
const labels = (state: State) => [tabA, tabB, tabC].map((tabID) => tabUnnamed(state, key, tabID))
// A link opened B: the strip adds it now, after A.
const opened = transition(start, report(start, inventory(tab(tabA), tab(tabB), tab(tabC)), { placed, unnamed: [tabB] }))
expect(strips(opened.effects)).toEqual([{ type: "sync-strip", sessionKey: key, keep: [tabA, tabB, tabC], open: [tabB, tabC], placed }])
expect(labels(opened.state)).toEqual([false, true, false])
// Its page loads: the strip changes nothing, and the label stays.
const loading = transition(opened.state, report(opened.state, inventory(tab(tabA), { ...tab(tabB), loading: true }, tab(tabC)), { unnamed: [tabB] }))
expect(strips(loading.effects)).toEqual([{ type: "sync-strip", sessionKey: key, keep: [tabA, tabB, tabC], open: [] }])
expect(labels(loading.state)).toEqual([false, true, false])
// Its page named itself: the label is the page's from now on.
const named = transition(loading.state, report(loading.state, inventory(tab(tabA), tab(tabB), tab(tabC)), {}))
expect(strips(named.effects)).toEqual([{ type: "sync-strip", sessionKey: key, keep: [tabA, tabB, tabC], open: [] }])
expect(labels(named.state)).toEqual([false, false, false])
// A tab the strip has already is not placed again: it stays where the person sees it.
const again = transition(named.state, report(named.state, inventory(tab(tabA), tab(tabB)), { placed }))
expect(strips(again.effects)).toEqual([{ type: "sync-strip", sessionKey: key, keep: [tabA, tabB], open: [] }])
})
// A tab drawn from the saved state can be closed or selected before the desktop reports it. With no inventory there
// was no command to send, so the first inventory put a closed tab back in the strip.
test("a saved tab closed or selected before the first inventory is closed or focused on the desktop once it arrives", () => {
+33 -4
View File
@@ -39,6 +39,9 @@ export type Phase =
| { readonly status: "suspended"; readonly reason: "idle" | "ipc" | "unlisted" }
| { readonly status: "blocked"; readonly reason: "replaced" | "missing" | "unsupported" }
/** A tab a page or link opened, and the tab it stands after in the strip, as the desktop reports it once. */
export type Placed = { readonly tabID: Browser.TabID; readonly after: Browser.TabID }
/** How the session's side-panel strip follows the desktop's tab inventory. */
export type Strip = {
/** The session's location is known, so the strip can be written. */
@@ -119,6 +122,11 @@ export type Attachment = {
*/
readonly held?: Held
readonly unseen: readonly Browser.TabID[]
/**
* Tabs a link opened whose first page has no name of its own yet, as the desktop reports them. The strip sizes a tab
* by its label, so each keeps its new-tab label until its page names itself, and is relabelled once.
*/
readonly unnamed: readonly Browser.TabID[]
/** The person's prompts that wait in the session's inbox, by inbox ID, with how each will be delivered. */
readonly prompts: Readonly<Record<string, "steer" | "queue">>
/**
@@ -248,6 +256,10 @@ export type Event =
readonly attempt: number
readonly state: Browser.State | null
readonly error: string | undefined
/** Tabs a link opened whose pages have no name of their own yet (`Attachment.unnamed`). */
readonly unnamed?: readonly Browser.TabID[]
/** The tab this inventory lists for the first time because a page or link opened it, and the tab it stands after. */
readonly placed?: Placed
}
| {
readonly type: "pane.embed"
@@ -313,13 +325,15 @@ export type MachineEffect =
}
/**
* Applies an inventory to the strip: closes stored tabs `keep` lacks (only a native inventory prunes, so the desktop
* decides which tabs exist), then appends `open`, the tabs new since the last mirrored inventory.
* decides which tabs exist), then appends `open`, the tabs new since the last mirrored inventory. The one `placed`
* names is added after the tab it was opened from instead.
*/
| {
readonly type: "sync-strip"
readonly sessionKey: string
readonly keep: readonly Browser.TabID[] | undefined
readonly open: readonly Browser.TabID[]
readonly placed?: Placed
}
| { readonly type: "focus-strip-tab"; readonly sessionKey: string; readonly tabID: Browser.TabID }
/** Records the session's loaded pages in the browser history, and its tabs for the strip of the next launch. */
@@ -464,6 +478,11 @@ export function sessionTab(state: State, sessionKey: string, tabID: string) {
return sessionBrowser(state, sessionKey)?.tabs.find((tab) => tab.id === tabID)
}
/** Whether the tab keeps its new-tab label: a link opened it and its page has no name of its own yet. */
export function tabUnnamed(state: State, sessionKey: string, tabID: string) {
return attachmentOf(state, sessionKey)?.unnamed.some((id) => id === tabID) ?? false
}
export function unseenActivity(state: State, sessionKey: string, tabID: string) {
return attachmentOf(state, sessionKey)?.unseen.some(id => id === tabID) ?? false
}
@@ -594,6 +613,7 @@ function attached(state: Open, event: Extract<Event, { type: "session.attached"
side: "unobserved",
shown: false,
unseen: [],
unnamed: [],
prompts: {},
})
}
@@ -1168,6 +1188,7 @@ function paneState(
{ ...strip, mirrored: [...strip.mirrored, ...dismissed], dismissed: [], selected: undefined },
event.state,
true,
event.placed,
)
// An inventory that repeats the error it reported last is the same failure, not a new one to read again.
@@ -1197,6 +1218,7 @@ function paneState(
phase: { status: "ready", attempt: phase.attempt },
browser: event.state,
unseen: attachment.unseen.filter(id => event.state?.tabs.some(tab => tab.id === id)),
unnamed: sameIDs(attachment.unnamed, event.unnamed ?? []) ? attachment.unnamed : (event.unnamed ?? []),
failure,
strip: mirrored.strip,
addressFocus: follow(attachment.addressFocus, event.state),
@@ -1262,7 +1284,7 @@ function backoff(state: Open, key: string, attachment: Attachment, phase: Bound)
// Mirrors an inventory into the strip. Only tabs new since the last mirrored inventory are added, so a tab the user
// just closed is not reopened before the desktop confirms. Only a native inventory prunes; suspended and restoring
// states keep the tabs they will restore. While the strip cannot be written, the prune waits for the location.
function mirror(key: string, strip: Strip, browser: Browser.State | null, native: boolean) {
function mirror(key: string, strip: Strip, browser: Browser.State | null, native: boolean, placed?: Placed) {
if (!browser) return { strip: { ...noStrip(), located: strip.located }, effects: [] }
const ids = browser.tabs.map((tab) => tab.id)
@@ -1276,7 +1298,7 @@ function mirror(key: string, strip: Strip, browser: Browser.State | null, native
effects: [],
}
return { strip: { ...strip, mirrored: ids }, effects: sync(key, ids, strip.mirrored, native) }
return { strip: { ...strip, mirrored: ids }, effects: sync(key, ids, strip.mirrored, native, placed) }
}
function sync(
@@ -1284,12 +1306,15 @@ function sync(
ids: readonly Browser.TabID[],
mirrored: readonly Browser.TabID[],
prune: boolean,
placed?: Placed,
): MachineEffect[] {
const open = ids.filter((id) => !mirrored.includes(id))
if (!prune && open.length === 0) return []
const effect = { type: "sync-strip" as const, sessionKey: key, keep: prune ? ids : undefined, open }
return [{ type: "sync-strip", sessionKey: key, keep: prune ? ids : undefined, open }]
// Only a tab this inventory adds is placed: one the strip has already stays where the person sees it.
return [placed && open.includes(placed.tabID) ? { ...effect, placed } : effect]
}
// The new tab a user's tabs.open added: blank, it takes the address focus; anything else ends the request. A ready tab
@@ -1369,3 +1394,7 @@ function put(
function listed(sessions: Open["sessions"]) {
return Object.entries(sessions).filter((entry): entry is [string, Attachment] => entry[1] !== undefined)
}
function sameIDs(before: readonly Browser.TabID[], after: readonly Browser.TabID[]) {
return before.length === after.length && before.every((id, index) => id === after[index])
}
+8 -2
View File
@@ -53,6 +53,7 @@ import {
sessionTab,
sessionTabs,
sessionUnavailable,
tabUnnamed,
unseenActivity,
revealGuard,
transition,
@@ -385,7 +386,7 @@ export function createModel(ctx: SetupContext<typeof definition>) {
if (event.error !== undefined) noteFailure(event.error, undefined)
return dispatch({ type: "pane.state", sessionKey, attempt, state: event.state, error: event.error })
return dispatch({ type: "pane.state", sessionKey, attempt, state: event.state, error: event.error, unnamed: event.unnamed, placed: event.placed })
}
if (event.type === "embed")
@@ -476,7 +477,10 @@ export function createModel(ctx: SetupContext<typeof definition>) {
}
effect.open.forEach((tabID) => {
if (layout.state(key(tabID), ref) === "closed") layout.open(key(tabID), ref, { tab: "append" })
if (layout.state(key(tabID), ref) !== "closed") return
// A tab a page or link opened stands after the tab it came from; the strip holds other panels' tabs too.
const after = effect.placed?.tabID === tabID ? key(effect.placed.after) : undefined
builtinContext(ctx).layout.open(key(tabID), ref, { tab: "append", after })
})
})
}
@@ -899,6 +903,8 @@ export function createModel(ctx: SetupContext<typeof definition>) {
return !!ref && !!state.chrome[session.key]?.[tabID]?.prompt && layout.state(key(tabID), ref) !== "visible"
},
unseen: (session: Session, tabID: string) => unseenActivity(machine(), session.key, tabID),
/** The tab keeps its new-tab label until its page names itself. */
unnamed: (session: Session, tabID: string) => tabUnnamed(machine(), session.key, tabID),
seen: (session: Session, tabID: Browser.TabID) => dispatch({ type: "activity.seen", sessionKey: session.key, tabID }),
revealGuard: (session: Session, tabID: string) => revealGuard(machine(), session.key, tabID),
windowShown,
@@ -446,3 +446,226 @@ describe("focus", () => {
expect(orphan.effects.some((effect) => effect.type === "emit")).toBe(false)
})
})
describe("position", () => {
const id = (n: number) => Browser.TabID.make(`tab_00000000-0000-0000-0000-00000000001${n}`)
const [a, b, c, x, y, z] = [1, 2, 3, 4, 5, 6].map(id)
const address = "https://docs.example/guide"
// What a new tab's page reports, in order, as measured in Electron (electron-links.test.ts): its load starts, its
// document commits under Chromium's name for it, the document names itself, and the load ends.
const started = (tabID: Browser.TabID): Browser.Tab => ({ ...tab(tabID, "about:blank"), loading: true })
const committed = (tabID: Browser.TabID): Browser.Tab => ({ ...tab(tabID, address, "docs.example/guide", 1), loading: true })
const titled = (tabID: Browser.TabID): Browser.Tab => ({ ...tab(tabID, address, "Guide", 1), loading: true })
const ended = (tabID: Browser.TabID, title = "Guide"): Browser.Tab => tab(tabID, address, title, 1)
type Step =
/** A tab opens: from `from`'s page or link, behind it or in `front`; with no `from`, by "+" or the agent. */
| { readonly open: Browser.TabID; readonly from?: Browser.TabID; readonly front?: boolean }
/** The tab's page reports itself. */
| { readonly report: Browser.Tab }
/** The person selects a tab in the strip. */
| { readonly select: Browser.TabID }
| { readonly close: Browser.TabID }
/** The person types an address into a tab. */
| { readonly address: Browser.TabID }
// A tab opened from `from`, whose page then loads and names itself.
const named = (tabID: Browser.TabID, from: Browser.TabID, front = false): Step[] => [
{ open: tabID, from, front },
{ report: started(tabID) },
{ report: committed(tabID) },
{ report: titled(tabID) },
]
const event = (state: PaneState, step: Step): BindingEvent => {
if ("report" in step) {
const slot = entry(state).tabs.get(step.report.id)
return { type: "tab.published", tabID: step.report.id, attempt: slot?.status === "live" ? slot.attempt : -1, tab: step.report }
}
if ("select" in step) return { type: "tab.focused", tabID: step.select, fromStrip: true }
if ("close" in step) return { type: "tab.closed", tabID: step.close }
if ("address" in step) return { type: "tab.addressed", tabID: step.address }
return {
type: "tab.opened",
tabID: step.open,
attempt: entry(state).nextAttempt,
tab: tab(step.open, "about:blank"),
beside: step.from ? { tabID: step.from, front: !!step.front } : undefined,
}
}
// Three tabs with B in front, then the steps. `strip`: the tabs in the order the binding lists them. `placed`: each
// tab the strip was told to add beside another, with that other. `unnamed`: which tabs each report said keep their
// new-tab label, one entry per change, so a tab that is relabelled once leaves it once.
const run = (steps: readonly Step[]) => {
const start = attached({ tabs: [a, b, c].map((tabID) => tab(tabID, dashboard)), focusedTabID: b })
const reports: Extract<PaneEffect, { type: "report" }>["event"][] = []
const end = steps.reduce(
(last, step) => {
const opened = transitionPane(last.state, on(event(last.state, step)))
// The pane brings a tab that opened in front to the front itself, right after; that is not the person's selection.
const next = "open" in step && (step.front || !step.from) ? play(opened.state, on({ type: "tab.focused", tabID: step.open })) : { state: opened.state, effects: [] }
return { state: next.state, reports: [...last.reports, ...[...opened.effects, ...next.effects].flatMap((effect) => (effect.type === "report" ? [effect.event] : []))] }
},
{ state: start, reports },
)
return {
strip: Array.from(entry(end.state).tabs.keys()),
placed: end.reports.flatMap((report) => (report.placed ? [[report.placed.tabID, report.placed.after]] : [])),
unnamed: end.reports.map((report) => report.unnamed ?? []).filter((list, index, all) => index === 0 || list.join() !== all[index - 1].join()),
front: entry(end.state).focusedTabID,
}
}
type Row = readonly [name: string, steps: readonly Step[], strip: readonly Browser.TabID[], placed: readonly (readonly Browser.TabID[])[], unnamed: readonly (readonly Browser.TabID[])[], front?: Browser.TabID]
// When the strip shows a tab a link opened, and how long it keeps its new-tab label: until its page names itself.
const shown: readonly Row[] = [
["a tab a link opens behind is listed at once, right after the tab it came from, with its new-tab label", [{ open: x, from: b }], [a, b, x, c], [[x, b]], [[x]]],
[
"it keeps that label while its load starts and its document has only Chromium's name, its address",
[{ open: x, from: b }, { report: started(x) }, { report: committed(x) }],
[a, b, x, c],
[[x, b]],
[[x]],
],
["it takes its page's title once, when its document names itself", named(x, b), [a, b, x, c], [[x, b]], [[x], []]],
["and nothing more as its load ends", [...named(x, b), { report: ended(x) }], [a, b, x, c], [[x, b]], [[x], []]],
[
"a document with no title is named when its load ends, with Chromium's name",
[{ open: x, from: b }, { report: started(x) }, { report: committed(x) }, { report: ended(x, "docs.example/guide") }],
[a, b, x, c],
[[x, b]],
[[x], []],
],
[
"a load that fails keeps the label at its error, which has no name yet",
[{ open: x, from: b }, { report: started(x) }, { report: { ...ended(x, ""), loadError: "ERR_CONNECTION_REFUSED" } }],
[a, b, x, c],
[[x, b]],
[[x]],
],
[
"and is named a moment later, once",
[{ open: x, from: b }, { report: started(x) }, { report: { ...ended(x, ""), loadError: "ERR_CONNECTION_REFUSED" } }, { report: { ...ended(x, "docs.example/guide"), loadError: "ERR_CONNECTION_REFUSED" } }],
[a, b, x, c],
[[x, b]],
[[x], []],
],
[
"a load that ends with no document, as for a refused address, is a new tab that waits for nothing",
[{ open: x, from: b }, { report: started(x) }, { report: tab(x, "about:blank") }],
[a, b, x, c],
[[x, b]],
[[x], []],
],
["a tab that closes before its page has a name leaves no label behind", [{ open: x, from: b }, { report: started(x) }, { close: x }], [a, b, c], [[x, b]], [[x], []]],
["a tab opened in front is listed and takes the pane at once", [{ open: x, from: b, front: true }], [a, b, x, c], [[x, b]], [[x]], x],
["and takes its page's title once, as one opened behind does", named(x, b, true), [a, b, x, c], [[x, b]], [[x], []], x],
[
"two opened behind are listed in the order they were opened, and each is named once, whichever page is named first",
[{ open: x, from: b }, { open: y, from: b }, { report: started(x) }, { report: started(y) }, { report: committed(y) }, { report: titled(y) }, { report: committed(x) }, { report: titled(x) }],
[a, b, x, y, c],
[[x, b], [y, x]],
[[x], [x, y], [x], []],
],
['a tab the person adds with "+", or the agent opens, goes to the end with no label to keep', [{ open: x }, { report: started(x) }, { report: committed(x) }], [a, b, c, x], [], [[]], x],
]
// Where it stands: Chrome's rule (tab-openers.ts). Each tab's page is named before the next step.
const placed: readonly Row[] = [
[
"several opened behind in a row stand in the order they were opened",
[...named(x, b), ...named(y, b), ...named(z, b)],
[a, b, x, y, z, c],
[[x, b], [y, x], [z, y]],
[[x], [], [y], [], [z], []],
],
[
"a tab that opens in front stands right after the tab it came from, before those opened behind",
[...named(x, b), ...named(y, b), ...named(z, b, true)],
[a, b, z, x, y, c],
[[x, b], [y, x], [z, b]],
[[x], [], [y], [], [z], []],
z,
],
[
"a tab opened from a tab that was opened behind joins the same row",
[...named(x, b), { select: x }, ...named(y, x), { select: b }, ...named(z, b)],
[a, b, x, y, z, c],
[[x, b], [y, x], [z, y]],
[[x], [], [y], [], [z], []],
],
[
"looking at an unrelated tab from the opener and coming back keeps the row, as in Chrome",
[...named(x, b), { select: a }, { select: b }, ...named(y, b)],
[a, b, x, y, c],
[[x, b], [y, x]],
[[x], [], [y], []],
],
[
"going from a tab the row opened to an unrelated tab ends the row",
[...named(x, b), { select: x }, { select: a }, { select: b }, ...named(y, b)],
[a, b, y, x, c],
[[x, b], [y, b]],
[[x], [], [y], []],
],
[
"a tab opened in front ends the rows before it",
[...named(x, b), ...named(y, b, true), { select: b }, ...named(z, b)],
[a, b, y, z, x, c],
[[x, b], [y, b], [z, y]],
[[x], [], [y], [], [z], []],
],
[
"what a closed tab opened counts as opened by that tab's own opener",
[...named(x, b), { select: x }, ...named(y, x), { close: x }, { select: b }, ...named(z, b)],
[a, b, y, z, c],
[[x, b], [y, x], [z, y]],
[[x], [], [y], [], [z], []],
],
["a tab whose opener closed meanwhile goes to the end", [{ close: b }, { open: x, from: b }], [a, c, x], [], [[]], a],
[
"an address typed into a tab ends the row",
[...named(x, b), { address: b }, ...named(y, b)],
[a, b, y, x, c],
[[x, b], [y, b]],
[[x], [], [y], []],
],
[
"but not the first address typed into a new tab at the end, a quick look-up",
[...named(x, b), { open: y }, { address: y }, { select: b }, ...named(z, b)],
[a, b, x, z, c, y],
[[x, b], [z, x]],
[[x], [], [z], []],
],
]
test.each([...shown, ...placed])("%s", (_name, steps, strip, placed, unnamed, front = b) => {
expect(run(steps)).toEqual({ strip: [...strip], placed: placed.map((item) => [...item]), unnamed: unnamed.map((item) => [...item]), front })
})
test("a tab opened in front is reported with its place before the window is asked to select it", () => {
const start = attached({ tabs: [a, b, c].map((tabID) => tab(tabID, dashboard)), focusedTabID: b })
const opened = transitionPane(start, on(event(start, { open: x, from: b, front: true })))
const focused = transitionPane(opened.state, on({ type: "tab.focused", tabID: x }))
expect(opened.effects.flatMap((effect) => (effect.type === "report" ? [effect.event.placed] : []))).toEqual([{ tabID: x, after: b }])
expect(focused.effects.at(-1)).toEqual({ type: "emit", binding: "b1", event: { type: "focus", tabID: x } })
})
test("a tab the binding lists already keeps its place when its page loads again", () => {
const start = attached({ tabs: [a, b, c].map((tabID) => tab(tabID, dashboard)), focusedTabID: a })
const loaded = transitionPane(start, on({ type: "tab.opened", tabID: c, attempt: 1, tab: tab(c, dashboard), beside: { tabID: a, front: false } }))
expect(Array.from(entry(loaded.state).tabs.keys())).toEqual([a, b, c])
expect(loaded.effects).toEqual([])
})
})
@@ -1,6 +1,7 @@
import { Browser } from "@opencode/plugin-browser/rpc"
import { Option, Predicate, Schema } from "effect"
import type { PaneCloseReason, PaneEvent } from "./ipc"
import { openersAfterClose, openersAfterOpen, openersAfterSelect, placedAfter, type Openers } from "./tab-openers"
import type { PageEnd } from "./page-log"
/** How long a binding may wait for the server's `attached` handshake before it closes. */
@@ -12,17 +13,27 @@ export const REGISTER_TIMEOUT_MS = 15_000
* - `unloaded`: only the tab's metadata. A restored tab stays here until the pane shows it or an agent command names
* it; a tab whose page crashed returns here, with `loadError`, so it can be loaded again.
* - `live`: a page exists for `attempt`. Results from an earlier page of the same tab carry another attempt.
* `url` is the last address the page reported, kept while a new document has not committed one.
* `url` is the last address the page reported, kept while a new document has not committed one. `unnamed`: a link
* opened the tab and its first page has no name of its own yet (`named`), so the strip keeps its new-tab label.
*/
export type TabSlot =
| { readonly status: "unloaded"; readonly tab: Browser.Tab }
| { readonly status: "live"; readonly attempt: number; readonly tab: Browser.Tab; readonly url: string }
| {
readonly status: "live"
readonly attempt: number
readonly tab: Browser.Tab
readonly url: string
readonly unnamed?: true
}
type Inventory = {
readonly binding: string
readonly window: number
readonly storageKey: string
/** In the order the strip shows them. */
readonly tabs: ReadonlyMap<Browser.TabID, TabSlot>
/** The tab each tab was opened from, which places the next tab a page opens (tab-openers.ts). */
readonly openers: Openers
/** Null or a key of `tabs`. */
readonly focusedTabID: Browser.TabID | null
readonly agentTabID?: Browser.TabID
@@ -93,8 +104,20 @@ export type BindingEvent =
| { readonly type: "request.targeted"; readonly requestID: string; readonly tabID: Browser.TabID }
| { readonly type: "request.cancelled"; readonly requestID: string }
| { readonly type: "request.finished"; readonly requestID: string }
/** A page for `tabID` was created as `attempt`, the binding's `nextAttempt`. */
| { readonly type: "tab.opened"; readonly tabID: Browser.TabID; readonly attempt: number; readonly tab: Browser.Tab }
/**
* A page for `tabID` was created as `attempt`, the binding's `nextAttempt`. `beside`: the tab whose page or link
* opened it, and whether the new tab takes the pane (`front`) or stays behind. A new tab stands next to that tab, as
* in Chrome, and is reported at once; any other new tab goes to the end.
*/
| {
readonly type: "tab.opened"
readonly tabID: Browser.TabID
readonly attempt: number
readonly tab: Browser.Tab
readonly beside?: { readonly tabID: Browser.TabID; readonly front: boolean }
}
/** The person gave the tab an address of their own, typed or picked, as opposed to following a link. */
| { readonly type: "tab.addressed"; readonly tabID: Browser.TabID }
| { readonly type: "restore.refused"; readonly tabID: Browser.TabID; readonly reason: "browser.restore.outside" | "browser.restore.refused" }
| {
readonly type: "tab.published"
@@ -357,7 +380,9 @@ function transitionAttached(state: AttachedBinding, event: BindingEvent): Bindin
if (event.type === "tab.focused") {
if (!state.tabs.has(event.tabID)) return { state, effects: [] }
const next = publish({ ...state, focusedTabID: event.tabID })
// Only the person's own selection is them going elsewhere.
const openers = event.fromStrip ? openersAfterSelect(state.openers, state.focusedTabID, event.tabID) : state.openers
const next = publish({ ...state, focusedTabID: event.tabID, openers })
// The strip already made this selection. Echoing it can reopen a pane the user has since closed.
if (event.fromStrip) return next
@@ -374,20 +399,39 @@ function transitionAttached(state: AttachedBinding, event: BindingEvent): Bindin
if (event.type === "tab.opened") {
if (event.attempt !== state.nextAttempt || state.tabs.get(event.tabID)?.status === "live")
return { state, effects: [] }
const slot = { status: "live" as const, attempt: event.attempt, tab: event.tab, url: event.tab.url }
const beside = event.beside
return {
state: {
// A tab the binding lists already keeps its place, and one that nothing here opened goes to the end.
if (!beside || state.tabs.has(event.tabID) || !state.tabs.has(beside.tabID))
return {
state: { ...state, tabs: new Map(state.tabs).set(event.tabID, slot), nextAttempt: event.attempt + 1 },
effects: [],
}
const after = placedAfter(Array.from(state.tabs.keys()), state.openers, beside.tabID, beside.front)
const entries = Array.from(state.tabs)
const index = entries.findIndex(([tabID]) => tabID === after) + 1
const unnamed: TabSlot = { ...slot, unnamed: true }
// Reported at once, with where it stands: the window's strip holds other tabs too, and only adds this one.
return publish(
{
...state,
tabs: new Map(state.tabs).set(event.tabID, {
status: "live",
attempt: event.attempt,
tab: event.tab,
url: event.tab.url,
}),
tabs: new Map([...entries.slice(0, index), [event.tabID, unnamed], ...entries.slice(index)]),
openers: openersAfterOpen(state.openers, event.tabID, beside.tabID, beside.front),
nextAttempt: event.attempt + 1,
},
effects: [],
}
undefined,
{ tabID: event.tabID, after },
)
}
if (event.type === "tab.addressed") {
// Chrome forgets every opener when a tab is given an address that is no link (`TabNavigating`), except for the
// first one given to a new tab at the end of the strip: a quick look-up that returns to where the person was.
const lookup = state.tabs.get(event.tabID)?.tab.url === "about:blank" && Array.from(state.tabs.keys()).at(-1) === event.tabID
return state.openers.size === 0 || lookup ? { state, effects: [] } : { state: { ...state, openers: new Map() }, effects: [] }
}
if (event.type === "restore.refused") {
@@ -410,7 +454,7 @@ function transitionAttached(state: AttachedBinding, event: BindingEvent): Bindin
// its strip never picks a neighbour for the closed tab.
const opener = front && event.opener !== undefined && tabs.has(event.opener) ? event.opener : undefined
const focusedTabID = front ? (opener ?? tabs.keys().next().value ?? null) : state.focusedTabID
const next = withoutTab({ ...state, tabs, focusedTabID, agentTabID: event.tabID === state.agentTabID ? undefined : state.agentTabID }, event.tabID, closed, undefined)
const next = withoutTab({ ...state, tabs, openers: openersAfterClose(state.openers, event.tabID), focusedTabID, agentTabID: event.tabID === state.agentTabID ? undefined : state.agentTabID }, event.tabID, closed, undefined)
if (!opener) return next
@@ -423,9 +467,11 @@ function transitionAttached(state: AttachedBinding, event: BindingEvent): Bindin
if (slot?.status !== "live" || slot.attempt !== event.attempt) return { state, effects: [] }
if (event.type === "tab.published") {
const tabs = new Map(state.tabs).set(event.tabID, { ...slot, tab: event.tab, url: event.tab.url || slot.url })
const next = { status: "live" as const, attempt: slot.attempt, tab: event.tab, url: event.tab.url || slot.url }
// The strip gives the tab its page's title once, when the page has the name it keeps.
const waiting = slot.unnamed && !named(slot.tab, event.tab)
return publish({ ...state, tabs }, event.error)
return publish({ ...state, tabs: new Map(state.tabs).set(event.tabID, waiting ? { ...next, unnamed: true } : next) }, event.error)
}
// A crashed page keeps its tab, unloaded, so showing it or an agent command on it loads its address again.
@@ -449,6 +495,20 @@ function transitionAttached(state: AttachedBinding, event: BindingEvent): Bindin
return withoutTab({ ...state, tabs }, event.tabID, slot, "page_crashed", event.ended)
}
/**
* Whether a page that reported `before` and now reports `tab` has the name its tab keeps: its document named itself,
* or its load ended (with Chromium's name for a document that has none, an error, or no document at all, as for a
* refused address). Chromium names a document after its URL from the commit until its <title> parses, and a failed
* load reports its name a moment after its error; neither is a name the strip shows.
*/
function named(before: Browser.Tab, tab: Browser.Tab) {
const blank = tab.url === "about:blank"
if (!tab.loading) return (before.loading || before.loadError !== undefined) && (blank || tab.title !== "")
return !blank && tab.generation === before.generation && tab.title !== "" && tab.title !== before.title
}
/** Aborts the requests that target a tab whose page went away, releases that page, and publishes the result. */
function withoutTab(state: AttachedBinding, tabID: Browser.TabID, slot: TabSlot, error: string | undefined, ended?: PageEnd) {
const targeting = Array.from(state.requests).flatMap(([requestID, target]) => (target === tabID ? [requestID] : []))
@@ -464,14 +524,20 @@ function withoutTab(state: AttachedBinding, tabID: Browser.TabID, slot: TabSlot,
return { state: next.state, effects: [...effects, ...next.effects] }
}
/** Saves the tabs for the next launch, and reports the state unless it repeats the last one reported. */
function publish(state: AttachedBinding, error?: string): AttachedTransition {
/**
* Saves the tabs for the next launch, and reports the state unless it repeats the last one reported. `placed` says
* once, with the inventory that first lists a tab a link opened, which tab it stands after.
*/
function publish(state: AttachedBinding, error?: string, placed?: StateEvent["placed"]): AttachedTransition {
const inventory = selectInventory(state)
const unnamed = Array.from(state.tabs).flatMap(([tabID, slot]) => (slot.status === "live" && slot.unnamed ? [tabID] : []))
const event =
error === undefined
? { type: "state" as const, state: inventory }
: { type: "state" as const, state: inventory, error }
const event = {
type: "state" as const,
state: inventory,
...(error !== undefined && { error }),
...(unnamed.length > 0 && { unnamed }),
}
const published = JSON.stringify([event, state.agentTabID])
@@ -491,7 +557,10 @@ function publish(state: AttachedBinding, error?: string): AttachedTransition {
if (published === state.published) return { state, effects: [save] }
return { state: { ...state, published }, effects: [save, { type: "report", binding: state.binding, event }] }
return {
state: { ...state, published },
effects: [save, { type: "report", binding: state.binding, event: placed ? { ...event, placed } : event }],
}
}
function createConnecting(event: Extract<PaneMachineEvent, { readonly type: "registered" }>): ActiveBinding {
@@ -525,6 +594,7 @@ function createConnecting(event: Extract<PaneMachineEvent, { readonly type: "reg
window: event.window,
storageKey: event.storageKey,
tabs,
openers: new Map(),
focusedTabID:
restore.focusedTabID !== null && tabs.has(restore.focusedTabID)
? restore.focusedTabID
+18 -7
View File
@@ -562,6 +562,8 @@ export function createBrowserPane(input: {
if (reason) throw new Error(reason)
if (command.type === "navigate") dispatchBinding(binding, { type: "tab.addressed", tabID: command.tabID })
if ("tabID" in command && command.type !== "tabs.focus") page(binding, command.tabID)?.personCommand()
const closing = command.type === "tabs.close" ? page(binding, command.tabID) : undefined
@@ -807,6 +809,8 @@ export function createBrowserPane(input: {
readonly opener?: Browser.TabID
/** Shows the opener's tab why an address this tab was opened for could not open. */
readonly refused?: (url: string) => void
/** The tab whose page or link opened this one, which it stands next to, and whether it takes the pane. */
readonly beside?: { readonly tabID: Browser.TabID; readonly front: boolean }
} = {},
) {
const entry = selectBinding(machine.state, binding)
@@ -878,7 +882,7 @@ export function createBrowserPane(input: {
if (current()) await execute(binding, { action, files: [] }, handle.abort.signal, "user")
},
open: async (url, background) => { if (current()) await execute(binding, { action: { type: "tabs.open", url, ...(background && { focus: false }) }, files: [] }, handle.abort.signal, "user", "new", childActivity(activity)) },
open: async (url, background) => { if (current()) await execute(binding, { action: { type: "tabs.open", url, ...(background && { focus: false }) }, files: [] }, handle.abort.signal, "user", "new", { activity: childActivity(activity), beside: id }) },
verifier: input.verifier,
},
embeds: input.embeds,
@@ -933,9 +937,11 @@ export function createBrowserPane(input: {
if (handle.shared) input.profile.extensionTabs.hidden(page.contents.id)
},
popup: (popupOptions, background, activity, refused) => {
const popup = create(binding, { initialize: false, popupOptions, activity, opener: id, refused })
const agent = activityOwner(activity) === "agent"
// The person's tab stands beside this one. The agent's goes to the end, as its own tabs do.
const popup = create(binding, { initialize: false, popupOptions, activity, opener: id, refused, beside: agent ? undefined : { tabID: id, front: !background } })
if (activityOwner(activity) === "agent") {
if (agent) {
announce(binding, popup.state().id, "none", !background)
return popup.contents
@@ -968,7 +974,7 @@ export function createBrowserPane(input: {
}))
downloads.set(page.contents.id, page.download)
input.profile.permissions.set(page.contents.id, page.permissions)
dispatchBinding(binding, { type: "tab.opened", tabID: id, attempt, tab: options.restore ?? page.state() })
dispatchBinding(binding, { type: "tab.opened", tabID: id, attempt, tab: options.restore ?? page.state(), beside: options.beside })
// Straight to the window, not through the server report: the embed is local to this desktop.
emit(binding, { type: "embed", tabID: id, embed: page.embed })
// A page that does not become ready reports that itself, through `fail`.
@@ -1015,7 +1021,7 @@ export function createBrowserPane(input: {
new AbortController().signal,
"user",
"new",
page.childActivity(),
{ activity: page.childActivity() },
)
const created = Option.getOrUndefined(Schema.decodeUnknownOption(Schema.Struct({ id: Browser.TabID }))(opened.value))
@@ -1054,7 +1060,7 @@ export function createBrowserPane(input: {
dispatchBinding(binding, { type: "tab.published", tabID, attempt, tab: page.state() })
}
async function execute(binding: string, command: Browser.Command, signal: AbortSignal, origin: "agent" | "user", intent: "present" | "new" = "new", inherited?: TabActivity, created?: (id: Browser.TabID) => void): Promise<Browser.Result> {
async function execute(binding: string, command: Browser.Command, signal: AbortSignal, origin: "agent" | "user", intent: "present" | "new" = "new", from?: { readonly activity: TabActivity; readonly beside?: Browser.TabID }, created?: (id: Browser.TabID) => void): Promise<Browser.Result> {
const action = command.action
const present = (tabID: Browser.TabID, reveal: "none" | "tab" = "none", active = true) => {
@@ -1160,7 +1166,12 @@ export function createBrowserPane(input: {
}
}
const opened = create(binding, { activity: createdActivity(origin, inherited) })
// A tab a page's own link or menu opened stands next to that page's tab; any other goes to the end.
const opened = create(binding, {
activity: createdActivity(origin, from?.activity),
beside: from?.beside === undefined ? undefined : { tabID: from.beside, front: action.focus !== false },
})
const tabID = opened.state().id
const shown = agentTabShow(action)
@@ -1292,6 +1292,8 @@ type RegionHost = {
}>
/** The real host wrapper that renders a plugin in its context. */
Contribution: Component<{ plugin: string; children: () => JSX.Element }>
/** The host's own placement of a tab it adds without selecting it: after `after` when the strip has it, else last. */
appendTab(strip: { all: string[] }, tab: string, after?: string): { all: string[] }
}
type RegionFixtureState = {
@@ -1449,7 +1451,7 @@ export function mountBrowserRegion(input: RegionHost) {
fitsSide: () => true,
ready: () => true,
open(key, session, options) {
if (!strip(session.key).all.includes(key)) setAll(session.key, [...strip(session.key).all, key])
setAll(session.key, input.appendTab({ all: [...strip(session.key).all] }, key, options?.after).all)
if (options?.tab !== "append") setStore("strips", session.key, "active", key)
@@ -526,7 +526,11 @@ const setup: Plugin.Setup<typeof definition> = (ctx) => {
const text = () => {
const tab = page()
return !tab?.url || tab.url === "about:blank" ? ctx.t("tab.new") : tabTitle(tab, saved()) || tab.url
// A tab a link opened keeps this label until its page names itself, so it is relabelled once: never with
// Chromium's name for a document that has not named itself, which is its address.
const unnamed = !tab?.url || tab.url === "about:blank" || model()?.unnamed({ key: session }, id)
return unnamed ? ctx.t("tab.new") : tabTitle(tab, saved()) || tab.url
}
const icon = () => {
@@ -0,0 +1,65 @@
import type { Browser } from "@opencode/plugin-browser/rpc"
/**
* Which tab each tab was opened from, while that still places the next one: Chrome's tab openers
* (`TabStripModel` in chrome/browser/ui/tabs/tab_strip_model.cc). A tab with no entry was opened by nothing, or the
* person has moved on since.
*/
export type Openers = ReadonlyMap<Browser.TabID, Browser.TabID>
/**
* The tab a new tab stands after when `opener` opens it (`DetermineInsertionIndex`). One that takes the pane stands
* right after its opener. One that stays behind stands after the tabs its opener already opened, and those they
* opened, as far as they stand in a row to the opener's right, so several open in the order they were asked for.
*/
export function placedAfter(tabs: readonly Browser.TabID[], openers: Openers, opener: Browser.TabID, front: boolean) {
if (front) return opener
const family = new Set([opener])
const row = tabs.slice(tabs.indexOf(opener) + 1)
const end = row.findIndex((tab) => {
const from = openers.get(tab)
if (!from || !family.has(from)) return true
family.add(tab)
return false
})
return row.slice(0, end === -1 ? row.length : end).at(-1) ?? opener
}
/** The openers once `opener` has opened `tab`. A tab that takes the pane starts over: only it has an opener then. */
export function openersAfterOpen(openers: Openers, tab: Browser.TabID, opener: Browser.TabID, front: boolean): Openers {
return new Map(front ? [] : openers).set(tab, opener)
}
/**
* The openers once the person has selected `to` while `from` was in front (`OnActiveTabChanged`). Moving between a
* tab and the tab that opened it, or between two tabs with the same opener or none, keeps them. Any other move is
* the person going elsewhere, and every opener is forgotten.
*/
export function openersAfterSelect(openers: Openers, from: Browser.TabID | null, to: Browser.TabID): Openers {
if (openers.size === 0 || from === null || from === to) return openers
const next = openers.get(to)
const previous = openers.get(from)
return next === previous || next === from || previous === to ? openers : new Map()
}
/** The openers once `tab` has closed: what it opened counts as opened by its own opener (`FixOpeners`). */
export function openersAfterClose(openers: Openers, tab: Browser.TabID): Openers {
if (openers.size === 0) return openers
const parent = openers.get(tab)
return new Map(
Array.from(openers).flatMap(([child, opener]): [Browser.TabID, Browser.TabID][] => {
if (child === tab) return []
if (opener !== tab) return [[child, opener]]
return parent ? [[child, parent]] : []
}),
)
}
+19 -1
View File
@@ -4,7 +4,7 @@
import type { Schema } from "effect"
import type { Context } from "./context.js"
import { Registry, type Catalog, type Cleanup, type Contract, type Messages, type Persisted, type StoreDeclaration, type StoreFrom } from "./core.js"
import type { Desktop, Layout, Locale, SessionRef, StorageScope, StoreOptions } from "./host-apis.js"
import type { Desktop, Layout, Locale, OpenOptions, SessionRef, StorageScope, StoreOptions } from "./host-apis.js"
import type { MainContext } from "./main.js"
import type { Command, IconName, Panel, PanelTab, SlotMap } from "./registries.js"
import { type JSX } from "solid-js"
@@ -314,8 +314,26 @@ export interface BuiltinDesktop extends Desktop {
forceFocus(enabled: boolean): Promise<void>
}
/** `OpenOptions` with the placement only built-ins use. */
export interface BuiltinOpenOptions extends OpenOptions {
/**
* With `tab: "append"` or `"select"`, the stored tab the new tab lands directly after, as `${plugin}:${tab id}`,
* for a tab that belongs beside the one it came from. Defaults to the end of the strip, which is also where the tab
* lands when the strip does not store that key. A tab the strip stores already does not move.
*/
readonly after?: string
}
/** `Layout` with the abilities only built-ins use. */
export interface BuiltinLayout extends Layout {
/**
* `Layout.open`, which can also place the tab after another one.
*
* @param key - `${plugin}:${tab id}`.
* @param session - The session whose strip changes.
* @param options - How the tab lands; see `BuiltinOpenOptions`.
*/
open(key: string, session: SessionRef, options?: BuiltinOpenOptions): void
/** Whether the current session row can fit a readable conversation beside the minimum side pane. */
fitsSide(): boolean
/**