fix(browser): reveal only explicit show requests and mark background previews

This commit is contained in:
Luke Parker 2026-11-17 09:35:38 +10:00
parent c0fc1b8ab0
commit f44dc5000f
11 changed files with 97 additions and 69 deletions

View file

@ -63,8 +63,7 @@ export default {
"site.agent.description": "It can read the page, run scripts, and fill in forms.",
"page.add": "Add page to session",
"page.placeholder": "Add context about this page",
"external.open": "Open in system browser",
"external.menu": "Open in browser",
"external.open": "Open in default browser",
"external.unavailable": "This address only works on the server's machine.",
options: "Browser options",
"zoom.in": "Zoom in",
@ -197,10 +196,12 @@ export default {
"menu.forward": "Forward",
"menu.reload": "Reload",
"menu.openLink": "Open link in new tab",
"menu.external": "Open link in system browser",
"menu.external": "Open link in default browser",
"menu.openPage": "Open in default browser",
"menu.pageUnavailable": "Not available in the default browser",
"menu.privateAddress": "This address works only inside this pane.",
"settings.agentPages.title": "Show pages opened by the agent",
"settings.agentPages.description": "Open the pane without moving keyboard focus. If the pane is already open, keep the selected tab.",
"settings.agentPages.description": "Let previews and explicit show requests open a closed pane. Activity marks never switch your selected tab.",
"tab.activity": "Agent activity",
"menu.failed": "Could not open this page in the default browser.",
"menu.copyLink": "Copy link address",

View file

@ -7,6 +7,7 @@ import en from "./i18n/en"
/**
* The browser's preferences on this device.
* - `links`: web links in a session open in the browser pane.
* - `agentPages`: previews and explicit show requests can reveal a closed pane; defaults to true. Activity marks are independent.
* - `welcomed`: the user imported sign-ins or declined the pane's offer, so the pane stops offering.
*/
const Preferences = Schema.Struct({ links: Schema.Boolean, welcomed: Schema.Boolean, agentPages: Schema.optionalKey(Schema.Boolean) })

View file

@ -97,14 +97,17 @@ const types = (effects: readonly MachineEffect[]) => effects.map((effect) => eff
describe("browser pane machine", () => {
const activity = (state: State) => ({ type: "pane.activity" as const, sessionKey: key, attempt: attempt(state),
tabID: tabA, enabled: true, onScreen: true, opened: false, visible: false })
tabID: tabA, reveal: true, room: true, enabled: true, onScreen: true, opened: false, visible: false })
test.each([
["closed pane", {}, "open"],
["another browser tab, Review or Files selected", { opened: true }, "mark"],
["target already visible", { opened: true, visible: true }, "none"],
["session off screen or window hidden", { onScreen: false }, "none"],
["disabled", { enabled: false }, "none"],
["disabled", { enabled: false }, "mark"],
["open pane with setting disabled", { enabled: false, opened: true }, "mark"],
["no room beside the chat", { room: false }, "mark"],
["navigate, popup, focus, implicit open or quiet tab", { reveal: false }, "mark"],
["superseded binding", { attempt: -1 }, "none"],
["since-closed tab", { tabID: tabB }, "none"],
] as const)("agent navigation, preview or new tab: %s", (_label, input, expected) => {
@ -140,6 +143,15 @@ describe("browser pane machine", () => {
expect(revealGuard(elapsed, key, tabA)).toBeUndefined()
})
test("starting with a closed pane does not dismiss the run; file previews use the same rule without replay", () => {
const start = ready()
const observed = transition(start, { type: "side.changed", sessionKey: key, open: false, running: true }).state
const file = { ...activity(observed), type: "pane.file" as const, path: "report.pdf" }
expect(transition(observed, file).effects).toEqual([{ type: "present-file", sessionKey: key, path: file.path, select: true }])
expect(transition(observed, { ...file, opened: true }).effects).toEqual([{ type: "present-file", sessionKey: key, path: file.path, select: false }])
expect(transition(observed, { ...file, onScreen: false })).toEqual({ state: observed, effects: [] })
})
test("a visible restored tab requests its load on acceptance, not before the new registration exists", () => {
const start = ready()
const closed = transition(start, paneState(start, inventory(tab(tabA)), "browser.pane.registration.closed")).state
@ -631,7 +643,8 @@ describe("browser pane machine", () => {
value.phase,
value.embeds,
value.strip,
value.strip.mirrored,
value.strip.mirrored,
value.unseen,
value.addressFocus,
...(value.addressFocus.status === "opening" ? [value.addressFocus.known] : []),
...(value.browser ? [value.browser, value.browser.tabs, ...value.browser.tabs] : []),

View file

@ -90,12 +90,15 @@ export type State =
| { readonly status: "disposed" }
export type Event =
| { readonly type: "pane.file"; readonly sessionKey: string; readonly attempt: number; readonly path: string; readonly enabled: boolean; readonly onScreen: boolean; readonly room: boolean; readonly opened: boolean }
| { readonly type: "side.changed"; readonly sessionKey: string; readonly open: boolean; readonly running: boolean }
| { readonly type: "execution.ended"; readonly sessionKey: string }
| { readonly type: "activity.seen"; readonly sessionKey: string; readonly tabID: Browser.TabID }
| { readonly type: "reveal.elapsed"; readonly sessionKey: string; readonly token: number }
| {
readonly type: "pane.activity"
readonly reveal: boolean
readonly room: boolean
readonly sessionKey: string
readonly attempt: number
readonly tabID: Browser.TabID
@ -175,6 +178,7 @@ export type Event =
}
export type MachineEffect =
| { readonly type: "present-file"; readonly sessionKey: string; readonly path: string; readonly select: boolean }
| {
readonly type: "open-registration"
readonly sessionKey: string
@ -479,14 +483,17 @@ function session(state: Open, key: string, attachment: Attachment, event: Sessio
return attachment.unseen.includes(event.tabID)
? put(state, key, { ...attachment, unseen: attachment.unseen.filter(id => id !== event.tabID) })
: { state, effects: [] }
case "pane.file":
case "pane.activity": {
if (!current(phase, event.attempt) || !event.enabled || !event.onScreen || !attachment.strip.located)
if (!current(phase, event.attempt) || !event.onScreen || !attachment.strip.located)
return { state, effects: [] }
const select = !event.opened && event.room && event.enabled && attachment.side !== "dismissed" && (event.type === "pane.file" || event.reveal)
if (attachment.side === "dismissed" || !attachment.browser?.tabs.some(tab => tab.id === event.tabID))
return { state, effects: [] }
if (event.type === "pane.file") return { state, effects: [{ type: "present-file", sessionKey: key, path: event.path, select }] }
if (!event.opened) {
if (!attachment.browser?.tabs.some(tab => tab.id === event.tabID)) return { state, effects: [] }
if (select) {
const token = state.issued + 1
return put(state, key, { ...attachment, reveal: { token, tabID: event.tabID } }, [

View file

@ -1,4 +1,6 @@
import { FileVerificationError } from "@opencode/util/file-verification"
import { builtinContext } from "@opencode/plugin/gui/builtin"
import { FileSource } from "../file/contract"
import { batch, createRoot, createSignal, getOwner, onCleanup, untrack } from "solid-js"
import { createStore, reconcile, unwrap } from "solid-js/store"
import { makeEventListener } from "@solid-primitives/event-listener"
@ -56,7 +58,6 @@ type Session = Pick<SessionRef, "key">
type Drive = {
ref: SessionRef
/** The agent's previews waiting for the session's screen, which resolves their paths. */
previews: string[]
dispose: () => void
}
@ -100,7 +101,7 @@ export type Model = ReturnType<typeof createModel>
export function createModel(ctx: SetupContext<typeof definition>) {
const sessions = ctx.sessions
const layout = ctx.layout
const links = ctx.links
const filesPanel = ctx.use(FileSource)
// The plugin's own main entry provides the pane. `uses` declares it by reference; its full token, which this chunk
// loads with the protocol schemas, resolves it.
const pane = ctx.use(BrowserPane)
@ -137,6 +138,8 @@ export function createModel(ctx: SetupContext<typeof definition>) {
// Main names why it moved control elsewhere or refused an address; any other failure is a failed request.
const describe = (error: string) => {
if (error === "browser.menu.failed") return ctx.t("menu.failed")
if (error === "browser.pane.replaced") return ctx.t("replaced")
if (error === "browser.address.credentials") return ctx.t("refused.credentials")
@ -170,6 +173,15 @@ export function createModel(ctx: SetupContext<typeof definition>) {
}
const run = (effect: MachineEffect) => {
if (effect.type === "present-file") {
const view = sessions.current()
const files = filesPanel()
if (view?.key === effect.sessionKey && files.status === "active") files.value.open(view, effect.path, effect.select ? "select" : "append")
return
}
if (effect.type === "open-registration") return open(effect)
if (effect.type === "close-registration") {
@ -331,14 +343,14 @@ export function createModel(ctx: SetupContext<typeof definition>) {
if (event.type === "focus") return dispatch({ type: "pane.focus", sessionKey, attempt, tabID: event.tabID })
if (event.type === "activity") return dispatch({
type: "pane.activity", sessionKey, attempt, tabID: event.tabID,
enabled: ctx.stores.preferences.value.agentPages !== false,
onScreen: sessions.current()?.key === sessionKey && !layout.narrow(),
opened: layout.side.opened(drive.ref), visible: layout.state(key(event.tabID), drive.ref) === "visible",
})
if (event.type === "activity" || event.type === "preview") {
const presentation = { sessionKey, attempt, enabled: ctx.stores.preferences.value.agentPages !== false,
onScreen: sessions.current()?.key === sessionKey, room: !layout.narrow() && builtinContext(ctx).layout.fitsSide(), opened: layout.side.opened(drive.ref) }
if (event.type === "preview") return preview(drive, event.path)
if (event.type === "preview") return dispatch({ ...presentation, type: "pane.file", path: event.path })
return dispatch({ ...presentation, type: "pane.activity", tabID: event.tabID, reveal: event.reveal, visible: layout.state(key(event.tabID), drive.ref) === "visible" })
}
if (event.type === "inspect") return inspectors.get(sessionKey)?.forEach((listener) => listener(event))
@ -474,7 +486,7 @@ export function createModel(ctx: SetupContext<typeof definition>) {
const sessionKey = ref.key
if (drives.has(sessionKey)) return
const drive: Drive = { ref, previews: [], dispose: () => undefined }
const drive: Drive = { ref, dispose: () => undefined }
drives.set(sessionKey, drive)
dispatch({ type: "session.attached", sessionKey, serverID: ref.server.id, located: !!ref.location })
@ -491,6 +503,9 @@ export function createModel(ctx: SetupContext<typeof definition>) {
const changed = () => dispatch({type:"session.capability.changed", sessionKey})
onCleanup(data.on("plugin.updated", changed))
onCleanup(data.on("server.connected", changed))
onCleanup(data.on("session.inbox.delivered", event => {
if (event.data.sessionID === ref.id) dispatch({ type: "execution.ended", sessionKey })
}))
onCleanup(data.on("session.deleted", event => {
if (event.data.sessionID === ref.id) dispatch({type:"session.removed", sessionKeys:[sessionKey]})
}))
@ -533,12 +548,6 @@ export function createModel(ctx: SetupContext<typeof definition>) {
{ otherwise: () => dispatch({ type: "session.located", sessionKey, located: false }) },
)
// Previews made while another session was on screen open once the user returns to this one.
createKeyed(
() => sessions.current()?.key === sessionKey && ctx.screen.current(),
() => drive.previews.splice(0).forEach((path) => preview(drive, path)),
)
return dispose
}, owner)
}
@ -610,19 +619,6 @@ export function createModel(ctx: SetupContext<typeof definition>) {
if (current) openURL(session, workspaceFileURL(current.root, path, session.server.builtin ? undefined : session.id))
}
// Main handles browser documents itself. File panel requests wait for the session's file model.
const preview = (drive: Drive, path: string) => {
const view = sessions.current()
if (view?.key === drive.ref.key && ctx.screen.current()) {
links.open({ href: path, session: view, background: true })
return
}
if (!drive.previews.includes(path)) drive.previews.push(path)
}
return {
available,
attached,
@ -631,6 +627,9 @@ export function createModel(ctx: SetupContext<typeof definition>) {
openURL,
async createTab(sessionKey: string, owner: string, url: string) {
if (sessions.current()?.key !== sessionKey) throw new Error("browser.pane.notOnScreen")
const ref = sessions.list().find(item => item.key === sessionKey)
if (ref?.server.compatible) attach(ref)
dispatch({ type: "session.wake", sessionKey })
const target = registrations.get(sessionKey)
@ -692,6 +691,7 @@ export function createModel(ctx: SetupContext<typeof definition>) {
asking: (session: Session, tabID: string) =>
!!state.chrome[session.key]?.[tabID]?.prompt && sessionBrowser(machine(), session.key)?.focusedTabID !== tabID,
unseen: (session: Session, tabID: string) => unseenActivity(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),
revealElapsed: (sessionKey: string, token: number) => dispatch({ type: "reveal.elapsed", sessionKey, token }),
answer(session: Session, tabID: Browser.TabID, id: number, answer: PromptAnswer) {

View file

@ -257,6 +257,7 @@ export default function SessionBrowserPane(props: {
}
const drawn = () => shown() && prompt()?.ask.kind !== "dialog"
createKeyed(() => visible() && state()?.id, id => props.model.seen(props.session, id))
const revealGuard = () => props.model.revealGuard(props.session, props.tab().id)
// Start the guard when this panel would actually show the native view, not while its chunk is still loading.
@ -358,7 +359,7 @@ export default function SessionBrowserPane(props: {
return {
source: source(),
open: !tab?.loadError && externalPage(url, session.server.local),
open: externalPage(url, session.server.local) && (!tab?.loadError || externalAction(url, session.server.local) === "browser"),
reveal: externalAction(url, session.server.local) === "reveal",
openPage() {
if (!id || !current()) return failed()
@ -372,7 +373,6 @@ export default function SessionBrowserPane(props: {
}
const [menuPage, setMenuPage] = createSignal<ReturnType<typeof pageTarget>>()
const toolbarTarget = createMemo(pageTarget)
const closeOverlay = () => dispatchOverlay({ type: "overlay.cancelled" })
const toggleInspect = () => dispatchOverlay({ type: "picker.toggled", context: context() })
@ -409,7 +409,7 @@ export default function SessionBrowserPane(props: {
const copyLink = () => {
const url = address()
if (!url) return
if (!url || serverFile()) return
void system.copy(url).then(
() => showToast({ title: plugin.t("common.copied") }),
() => showToast({ title: plugin.t("common.requestFailed") }),
@ -785,7 +785,7 @@ export default function SessionBrowserPane(props: {
icon={<Icon name="outline-globe-plus" />}
/>
</Tooltip>
<Show keyed when={!serverFile() && toolbarTarget()}>
<Show keyed when={!serverFile() && pageTarget()}>
{(target) => (
<Tooltip placement="top" value={plugin.t(reachable() ? externalLabel() : "external.unavailable")}>
<IconButton
@ -931,16 +931,14 @@ export default function SessionBrowserPane(props: {
</Menu.Item>
</Menu.Group>
<Menu.Separator />
<Menu.Item disabled={!address()} onSelect={copyLink}>
<Menu.Item disabled={!address() || serverFile()} title={serverFile() ? plugin.t("menu.privateAddress") : undefined} onSelect={copyLink}>
{plugin.t("link.copy")}
</Menu.Item>
<Menu.Item disabled={!inspectable()} onSelect={() => find({ type: "open" })}>{plugin.t("find.open")}</Menu.Item>
<Show when={menuPage()?.source}>
{(open) => <Menu.Item onSelect={() => open()()}>{plugin.t("preview.source")}</Menu.Item>}
</Show>
<Show when={menuPage()?.open}>
<Menu.Item onSelect={() => menuPage()?.openPage()}>{plugin.t("menu.openPage")}</Menu.Item>
</Show>
<Menu.Item disabled={!menuPage()?.open} title={!menuPage()?.open ? plugin.t("menu.pageUnavailable") : undefined} onSelect={() => menuPage()?.openPage()}>{plugin.t("menu.openPage")}</Menu.Item>
<Show when={menuPage()?.reveal}>
<Menu.Item onSelect={() => menuPage()?.revealFile()}>
{plugin.t("external.reveal")}

View file

@ -382,6 +382,7 @@ const setup: Plugin.Setup<typeof definition> = (ctx) => {
get entries() {
return [
{ id: "settings-browser-links", title: ctx.t("settings.links.title"), keywords: "links open system browser" },
{ id: "settings-browser-agent-pages", title: ctx.t("settings.agentPages.title"), keywords: "agent preview automatic browser pane" },
{
id: "settings-browser-remote",
title: ctx.t("settings.remote.title"),
@ -429,12 +430,8 @@ const setup: Plugin.Setup<typeof definition> = (ctx) => {
<div class="flex items-center gap-1.5">
<PageIcon icon={icon()} />
<span class="max-w-40 truncate">{text()}</span>
<Show when={model()?.unseen({ key: session }, id)}>
<span role="img" aria-label={ctx.t("tab.activity")} class="size-1.5 shrink-0 rounded-full bg-v2-icon-icon-accent" />
</Show>
{/* A tab behind another waits on the user: a dialog, a sign-in or a site's request. */}
<Show when={model()?.asking({ key: session }, id)}>
<span role="img" aria-label={ctx.t("prompt.tab")} class="size-1.5 shrink-0 rounded-full bg-v2-icon-icon-accent" />
<Show when={model()?.asking({ key: session }, id) ? "prompt.tab" : model()?.unseen({ key: session }, id) && "tab.activity"}>
{(status) => <span role="img" aria-label={ctx.t(status())} class="size-1.5 shrink-0 rounded-full" classList={{ "bg-v2-state-bg-warning": status() === "prompt.tab", "bg-v2-state-bg-info": status() === "tab.activity" }} />}
</Show>
</div>
),

View file

@ -78,16 +78,16 @@ export default function BrowserSettings() {
onChange={(links) => preferences.set({ ...preferences.value, links })}
/>
</ui.SettingsRow>
<ui.SettingsRow
id="settings-browser-agent-pages"
title={ctx.t("settings.agentPages.title")}
description={ctx.t("settings.agentPages.description")}
>
<ui.Switch label={ctx.t("settings.agentPages.title")} hideLabel checked={preferences.value.agentPages !== false}
onChange={agentPages => preferences.update(draft => { draft.agentPages = agentPages })} />
</ui.SettingsRow>
<ui.SettingsRow
id="settings-browser-remote"
<ui.SettingsRow
id="settings-browser-agent-pages"
title={ctx.t("settings.agentPages.title")}
description={ctx.t("settings.agentPages.description")}
>
<ui.Switch label={ctx.t("settings.agentPages.title")} hideLabel checked={preferences.value.agentPages !== false}
onChange={agentPages => preferences.update(draft => { draft.agentPages = agentPages })} />
</ui.SettingsRow>
<ui.SettingsRow
id="settings-browser-remote"
title={ctx.t("settings.remote.title")}
description={ctx.t("settings.remote.description")}
>

View file

@ -2,5 +2,5 @@ import { Contract, type MountedSession } from "@opencode/plugin/gui"
/** Opens a workspace document as selectable source, without following its normal preview route. */
export const FileSource = Contract.define<{
open(session: MountedSession, path: string): void
open(session: MountedSession, path: string, tab?: "select" | "append"): void
}, "file.source">("file.source")

View file

@ -1,4 +1,5 @@
export default {
"tab.activity": "Agent activity",
"tree.all": "All files",
"tab.notFound": "File not found: {{name}}",
"load.failed": "Failed to load file",

View file

@ -150,6 +150,7 @@ const setup: Plugin.Setup<typeof File> = (ctx) => {
const focused = new WeakMap<SessionScreen, string>()
const key = (files: Files, path: string) => `file:${fileTabId(files, path)}`
const [unseen, setUnseen] = createStore<Record<string, boolean | undefined>>({})
const active = (session: MountedSession, id: string) => {
const state = layout.state(`file:${id}`, session)
@ -243,18 +244,20 @@ const setup: Plugin.Setup<typeof File> = (ctx) => {
// Not batched: the mobile tab strip must register the new tab before it leaves the browser, or Kobalte falls back
// to the first tab and reselects it.
layout.open(key(screen.file, path), session, options)
dispatchPicker({ type: "file.opened", sessionKey: session.key })
if (options?.tab !== "append") dispatchPicker({ type: "file.opened", sessionKey: session.key })
void screen.file.sync(path)
}
ctx.provide(FileSource, { open(session, address) {
ctx.provide(FileSource, { open(session, address, tab) {
const files = ctx.screen.current()?.file
const path = files?.resolve(address)
if (!files || !path || files.absolute(path) || path.split(/[\\/]/).includes("..") || sessions.current()?.key !== session.key)
return ctx.toast.show({ variant: "error", title: ctx.t("load.failed") })
openSource(session, address)
if (tab === "append" && layout.state(key(files, address), session) !== "visible") setUnseen(`${session.key}\n${fileTabId(files, address)}`, true)
openSource(session, address, tab ? { tab, background: true } : undefined)
} })
const open = (session: MountedSession, path: string, options?: OpenOptions) => {
@ -434,7 +437,12 @@ const setup: Plugin.Setup<typeof File> = (ctx) => {
return missing() ? ctx.t("tab.notFound", { name }) : name
},
label: (state) => <FileVisual path={path()} temporary={state.preview} notFound={missing()} />,
label: (state) => <>
<FileVisual path={path()} temporary={state.preview} notFound={missing()} />
<Show when={unseen[`${state.session.key}\n${id}`]}>
<span role="img" aria-label={ctx.t("tab.activity")} class="ms-1 size-1.5 shrink-0 rounded-full bg-v2-state-bg-info" />
</Show>
</>,
get missing() {
return missing()
},
@ -483,6 +491,7 @@ const setup: Plugin.Setup<typeof File> = (ctx) => {
})
},
close(input) {
setUnseen(`${input.session.key}\n${input.tab.id}`, undefined)
tabs.get(input.screen)?.delete(input.tab.id)
if (isLauncher(input.tab.id))
@ -492,6 +501,7 @@ const setup: Plugin.Setup<typeof File> = (ctx) => {
},
render: (props) => {
const panel = usePanel()
createKeyed(() => panel.visible() && `${props.session.key}\n${props.tab.id}`, id => setUnseen(id, undefined))
return (
<FileProvider>