Skip to content

The agent that grows with you

feat(desktop): let the in-app browser hold more than one tab

Brooklyn Nicholson8a8f74e789bc
diff --git a/apps/desktop/src/app/chat/pane-mirror.ts b/apps/desktop/src/app/chat/pane-mirror.ts
index 2a2d5dfb489..a2525048b42 100644
--- a/apps/desktop/src/app/chat/pane-mirror.ts
+++ b/apps/desktop/src/app/chat/pane-mirror.ts
@@ -48,6 +48,9 @@ export interface PaneMirror<T> {
* as `tabLead` — a name that moves faster than re-registration (see
* PaneChrome.tabTitle). Falls back to `title`. */
tabTitle?: (key: string) => ReactNode
+ /** Mint another tile of this kind — the strip's "+" (see PaneChrome.newTab).
+ * Per tile so a mirror can offer it for some of its tabs and not others. */
+ newTab?: (key: string) => (() => void) | undefined
render: (key: string) => ReactNode
/** Wrap the tile's TAB (domain context menu — session verbs). */
tabWrap?: (key: string, tab: ReactElement) => ReactNode
@@ -102,6 +105,7 @@ export function paneMirror<T>(cfg: PaneMirror<T>): () => void {
pos: cfg.dir?.(tile) ?? 'right'
},
minWidth: cfg.minWidth,
+ newTab: cfg.newTab?.(key),
// Every mirrored tile is a full workspace surface docked beside main —
// and closeable, which is what keeps its tab when it lands in a zone of
// its own (see strip-visibility.ts).
diff --git a/apps/desktop/src/app/chat/preview-tile.test.ts b/apps/desktop/src/app/chat/preview-tile.test.ts
index 2b77013f7fa..637d71c9adc 100644
--- a/apps/desktop/src/app/chat/preview-tile.test.ts
+++ b/apps/desktop/src/app/chat/preview-tile.test.ts
@@ -12,7 +12,7 @@ import { contributesToWorkspace } from '@/components/pane-shell/workspace-scope'
import { registry } from '@/contrib/registry'
import { closeRightRail, openPreview } from '@/store/preview'
-import { watchPreviewTiles } from './preview-tile'
+import { browserTabLabel, watchPreviewTiles } from './preview-tile'
beforeAll(() => {
watchPreviewTiles()
@@ -22,8 +22,10 @@ afterEach(() => {
closeRightRail()
})
+// By prefix, not by a literal id: a Browser tab's id is minted per tab now
+// that there can be more than one of them.
function browserPane() {
- return registry.getArea('panes').find(entry => entry.id === 'preview-tile:url:browser')
+ return registry.getArea('panes').find(entry => entry.id.startsWith('preview-tile:url:'))
}
describe('preview tiles in Bot Mode', () => {
@@ -42,6 +44,34 @@ describe('preview tiles in Bot Mode', () => {
})
})
+describe('browserTabLabel', () => {
+ const target = { kind: 'url', label: 'Browser', source: 'about:blank', url: 'about:blank' } as const
+
+ it('names the tab after the page', () => {
+ expect(browserTabLabel(target, { title: 'Hacker News', url: 'https://news.ycombinator.com/' })).toBe('Hacker News')
+ })
+
+ // Chromium hands back the address as the title when the page never set one,
+ // which is a worse tab label than the host it came from.
+ it('falls back to the host when the page has no title of its own', () => {
+ expect(browserTabLabel(target, { title: '', url: 'https://www.example.com/a/b' })).toBe('example.com')
+ expect(browserTabLabel(target, { title: 'https://example.com/a', url: 'https://example.com/a' })).toBe(
+ 'example.com'
+ )
+ })
+
+ it('falls back to the surface when there is no page and no host', () => {
+ expect(browserTabLabel(target)).toBe('Browser')
+ expect(browserTabLabel(target, { title: '', url: 'about:blank' })).toBe('Browser')
+ })
+
+ // A tab restored from storage has reported nothing yet, so its target is all
+ // there is to name it by.
+ it('names an unreported tab from its target', () => {
+ expect(browserTabLabel({ ...target, url: 'https://github.com/nous' })).toBe('github.com')
+ })
+})
+
type DockData = { dock?: { pane?: string; pos?: string } } | undefined
function dockOf(paneId: string) {
diff --git a/apps/desktop/src/app/chat/preview-tile.tsx b/apps/desktop/src/app/chat/preview-tile.tsx
index ebae8baa32d..d0dd3fec2b4 100644
--- a/apps/desktop/src/app/chat/preview-tile.tsx
+++ b/apps/desktop/src/app/chat/preview-tile.tsx
@@ -10,12 +10,22 @@
* one bar instead of two.
*/
+import { useStore } from '@nanostores/react'
+
import { findGroup } from '@/components/pane-shell/tree/model'
import { $activeTreeGroup, $layoutTree, revealTreePane, treePanesWithPrefix } from '@/components/pane-shell/tree/store'
import { FileTypeIcon } from '@/components/ui/file-type-icon'
import { ToolIcon } from '@/components/ui/tool-icon'
import { $rightRailActiveTabId, type RightRailTabId, selectRightRailTab } from '@/store/layout'
-import { $previewTabs, closeRightRailTab, type PreviewTarget } from '@/store/preview'
+import {
+ $browserPages,
+ $previewTabs,
+ type BrowserPage,
+ closeRightRailTab,
+ forgetBrowserPage,
+ newBrowserTab,
+ type PreviewTarget
+} from '@/store/preview'
import { paneMirror } from './pane-mirror'
import { PreviewTilePane } from './right-rail/preview'
@@ -26,9 +36,11 @@ function targetFor(tabId: string): PreviewTarget | null {
return $previewTabs.get().find(tab => tab.id === tabId)?.target ?? null
}
-/** Tab title. A URL is a BROWSER — the tab names the surface, not the page, so
- * it doesn't rename itself on every navigation. A file names the file; an
- * artifact is titled rather than located, so its label is the whole name. */
+/** Tab title. A URL tab is titled by the CONTRIBUTION as the surface — see
+ * `BrowserTabLabel` for the live page name the strip actually renders — so
+ * navigating doesn't re-register the pane on every hop. A file names the
+ * file; an artifact is titled rather than located, so its label is the whole
+ * name. */
function previewTitle(tabId: string): string {
const target = targetFor(tabId)
@@ -50,6 +62,40 @@ function previewTitle(tabId: string): string {
return tail || value || 'Preview'
}
+/**
+ * What to call a Browser tab. Its page title, else the host it is on, else
+ * the surface — the ladder every browser walks, and the reason more than one
+ * Browser is usable at all: three tabs reading "Browser" name nothing.
+ *
+ * A page that never set a title reports its own address as one, which is a
+ * worse label than the host it came from, so an address-shaped title falls
+ * through.
+ */
+export function browserTabLabel(target: PreviewTarget, page?: BrowserPage): string {
+ const url = page?.url || target.url
+ const title = page?.title.trim()
+
+ if (title && title !== url) {
+ return title
+ }
+
+ try {
+ return new URL(url).hostname.replace(/^www\./, '') || 'Browser'
+ } catch {
+ // `about:blank` and half-typed addresses have no host to fall back to.
+ return 'Browser'
+ }
+}
+
+/** Live tab label for a Browser: it renames itself as the page navigates,
+ * without the contribution re-registering (see PaneChrome.tabTitle). */
+function BrowserTabLabel({ tabId }: { tabId: string }) {
+ const pages = useStore($browserPages)
+ const target = targetFor(tabId)
+
+ return target ? browserTabLabel(target, pages[tabId]) : null
+}
+
/** The tab's lead glyph — the same file/tool icon family the file tree and code
* fences resolve through, so a `.tsx` peek and its sidebar row agree. */
function PreviewTabLead({ tabId }: { tabId: string }) {
@@ -157,8 +203,13 @@ const watchPreviewTileMirror = paneMirror<{ id: string }>({
minWidth: '22rem',
title: previewTitle,
tabLead: tabId => <PreviewTabLead tabId={tabId} />,
+ tabTitle: tabId => (targetFor(tabId)?.kind === 'url' ? <BrowserTabLabel tabId={tabId} /> : undefined),
+ // A Browser is a vessel, so there can be more of it — a file peek is one of
+ // a kind and leaves the strip's "+" to whatever else the zone holds.
+ newTab: tabId => (targetFor(tabId)?.kind === 'url' ? newBrowserTab : undefined),
render: tabId => <PreviewTilePane tabId={tabId} />,
close: tabId => {
+ forgetBrowserPage(tabId)
forgetPreviewConsole(tabId)
closeRightRailTab(tabId)
}
diff --git a/apps/desktop/src/app/chat/right-rail/preview-pane.tsx b/apps/desktop/src/app/chat/right-rail/preview-pane.tsx
index 817cec638a5..35b19fa4990 100644
--- a/apps/desktop/src/app/chat/right-rail/preview-pane.tsx
+++ b/apps/desktop/src/app/chat/right-rail/preview-pane.tsx
@@ -18,7 +18,12 @@ import { reachablePreviewUrl } from '@/lib/preview-reach'
import { rafCoalesce } from '@/lib/raf-coalesce'
import { cn } from '@/lib/utils'
import { notify, notifyError } from '@/store/notifications'
-import { $previewServerRestart, failPreviewServerRestart, type PreviewTarget } from '@/store/preview'
+import {
+ $previewServerRestart,
+ failPreviewServerRestart,
+ noteBrowserPage,
+ type PreviewTarget
+} from '@/store/preview'
import { ArtifactPreview } from './preview-artifact'
import { PreviewBrowserBar } from './preview-browser-bar'
@@ -746,6 +751,18 @@ export function PreviewPane({ embedded = false, onRestartServer, reloadRequest =
const syncHistory = () =>
setHistory({ back: webview.canGoBack?.() ?? false, forward: webview.canGoForward?.() ?? false })
+ // Tell the strip what this Browser is showing, so its tab renames itself
+ // like a tab anywhere else. Deliberately NOT written back into the tab's
+ // target: the guest is built from `target.url`, so that would rebuild the
+ // webview mid-navigation and throw away the history.
+ const notePage = () => {
+ if (target.kind !== 'url' || !tabId) {
+ return
+ }
+
+ noteBrowserPage(tabId, { title: webview.getTitle?.() ?? '', url: webview.getURL?.() || target.url })
+ }
+
const onNavigate = (event: Event) => {
const detail = event as Event & { url?: string }
@@ -754,6 +771,8 @@ export function PreviewPane({ embedded = false, onRestartServer, reloadRequest =
setCurrentUrl(detail.url)
}
+ notePage()
+
// Ask the webview rather than counting navigations: the guest page can
// move itself (redirects, history.pushState, a link into a new document),
// so it is the only thing that knows what its history holds. Wired to
@@ -794,6 +813,7 @@ export function PreviewPane({ embedded = false, onRestartServer, reloadRequest =
// cancelled navigation) still settles the history — resync so the
// buttons can't be left stale.
syncHistory()
+ notePage()
}
// The WEBVIEW is the source of truth for DevTools, not our click handler:
@@ -885,6 +905,9 @@ export function PreviewPane({ embedded = false, onRestartServer, reloadRequest =
webview.addEventListener('did-navigate-in-page', onNavigate)
webview.addEventListener('did-start-loading', onStart)
webview.addEventListener('did-stop-loading', onStop)
+ // SPAs title themselves long after the load settles, and a route change
+ // renames the page without navigating at all.
+ webview.addEventListener('page-title-updated', notePage)
host.appendChild(webview)
webviewRef.current = webview
@@ -898,9 +921,10 @@ export function PreviewPane({ embedded = false, onRestartServer, reloadRequest =
webview.removeEventListener('did-navigate-in-page', onNavigate)
webview.removeEventListener('did-start-loading', onStart)
webview.removeEventListener('did-stop-loading', onStop)
+ webview.removeEventListener('page-title-updated', notePage)
webview.remove()
}
- }, [appendConsoleEntry, consoleState, copy, isRemoteHtml, isWebPreview, target.url])
+ }, [appendConsoleEntry, consoleState, copy, isRemoteHtml, isWebPreview, tabId, target.kind, target.url])
return (
<aside
diff --git a/apps/desktop/src/components/pane-shell/tree/renderer/track-model.ts b/apps/desktop/src/components/pane-shell/tree/renderer/track-model.ts
index 268dbb4b56e..9d28bb262cb 100644
--- a/apps/desktop/src/components/pane-shell/tree/renderer/track-model.ts
+++ b/apps/desktop/src/components/pane-shell/tree/renderer/track-model.ts
@@ -90,6 +90,11 @@ interface PaneChrome extends PaneSizing {
* the tab and the sidebar row render status/color from the ONE primitive
* (self-subscribing — it updates without the strip re-registering). */
tabLead?: () => React.ReactNode
+ /** Mint another tab of THIS pane's kind — the strip's "+" while this pane is
+ * active. A Browser tab makes another Browser tab; a pane that is one of a
+ * kind (a file peek) leaves it absent and the strip falls back to the chat
+ * "+" if the zone holds session tabs. */
+ newTab?: () => void
/** This pane's TAB LABEL, when it changes faster than the contribution
* should. A session pane whose draft is being typed renames on every
* debounce beat; re-registering `title` that often would re-render the
diff --git a/apps/desktop/src/components/pane-shell/tree/renderer/tree-group.tsx b/apps/desktop/src/components/pane-shell/tree/renderer/tree-group.tsx
index 4e021c58734..dece540d59a 100644
--- a/apps/desktop/src/components/pane-shell/tree/renderer/tree-group.tsx
+++ b/apps/desktop/src/components/pane-shell/tree/renderer/tree-group.tsx
@@ -270,6 +270,25 @@ export function TreeGroup({
const active = paneFor(activeId)
const isEmpty = shown.length === 0
+ // What the strip's "+" makes. The pane you are LOOKING AT answers first (a
+ // Browser tab makes another Browser, even stacked into the chat strip), then
+ // the chat "+" for any zone holding session tabs, then any other tenant that
+ // can mint its own kind — that last rung is what keeps the button from
+ // blinking out when you click a file tab sitting beside a Browser.
+ const ownNewTab = (id: string) => {
+ const mint = paneChrome(paneFor(id)).newTab
+
+ return mint ? { label: t.zones.newTab, onSelect: mint } : null
+ }
+
+ const newTab =
+ ownNewTab(activeId) ??
+ (shown.some(isSessionStripPane) && newSessionTabAction
+ ? { label: t.zones.newSessionTab, onSelect: newSessionTabAction }
+ : null) ??
+ shown.map(ownNewTab).find(Boolean) ??
+ null
+
useEffect(() => {
if (activeId) {
rememberActivePane(memoryKey, activeId)
@@ -594,12 +613,13 @@ export function TreeGroup({
return <Fragment key={paneId}>{chrome.tabWrap ? chrome.tabWrap(tab) : tab}</Fragment>
})}
- {/* Plain "+" after the last tab of a CHAT strip (the workspace
- zone, or any zone holding session tabs) — always shown. Creates
- a new session tab (mirrors ⌘T) via the app-registered action;
- the pointerdown focuses this zone first, so the tab lands in
- THIS strip. Hidden when unwired or the zone is minimized. */}
- {shown.some(isSessionStripPane) && newSessionTabAction && !node.minimized && (
+ {/* Plain "+" after the last tab — it mints another tab of the kind
+ you are LOOKING AT, so a Browser strip makes another Browser
+ and a chat strip makes another session (mirrors ⌘T, via the
+ app-registered action). The pointerdown focuses this zone
+ first, so the tab lands in THIS strip. Hidden when the active
+ pane is one of a kind and the zone holds no session tabs. */}
+ {newTab && !node.minimized && (
<span
// The action docks into the FOCUSED chat zone; clicking a
// background strip's "+" must make THAT zone the focused one
@@ -610,8 +630,8 @@ export function TreeGroup({
>
<PaneStripGlyph
icon={<Codicon name="add" size="0.8125rem" />}
- label={t.zones.newSessionTab}
- onSelect={() => newSessionTabAction()}
+ label={newTab.label}
+ onSelect={newTab.onSelect}
/>
</span>
)}
diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts
index bc039510aad..0c2dc06e8cc 100644
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@ -3072,6 +3072,7 @@ export const en: Translations = {
closeToRight: 'Close to the right',
closeAll: 'Close all',
newSessionTab: 'New session tab',
+ newTab: 'New tab',
pluginDisabled: pluginId => `Plugin "${pluginId}" disabled`,
pluginDisabledBody: 'Re-enable it in Settings → Plugins to bring the pane back.',
missingPane: paneId => `missing pane: ${paneId}`,
diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.ts
index b4d1047d00b..3471bbc8d78 100644
--- a/apps/desktop/src/i18n/ja.ts
+++ b/apps/desktop/src/i18n/ja.ts
@@ -2724,6 +2724,7 @@ export const ja = defineLocale({
closeToRight: '右側を閉じる',
closeAll: 'すべて閉じる',
newSessionTab: '新しいセッションタブ',
+ newTab: '新しいタブ',
pluginDisabled: pluginId => `プラグイン「${pluginId}」を無効化しました`,
pluginDisabledBody: '設定 → プラグイン で再有効化するとペインが戻ります。',
missingPane: paneId => `ペインが見つかりません: ${paneId}`,
diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts
index 534732c3203..6c799c725dc 100644
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@ -2633,6 +2633,7 @@ export interface Translations {
closeToRight: string
closeAll: string
newSessionTab: string
+ newTab: string
pluginDisabled: (pluginId: string) => string
pluginDisabledBody: string
missingPane: (paneId: string) => string
diff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.ts
index c3ab703aea0..0ffb32dc7d0 100644
--- a/apps/desktop/src/i18n/zh-hant.ts
+++ b/apps/desktop/src/i18n/zh-hant.ts
@@ -2632,6 +2632,7 @@ export const zhHant = defineLocale({
closeToRight: '關閉右側',
closeAll: '全部關閉',
newSessionTab: '新增工作階段分頁',
+ newTab: '新增分頁',
pluginDisabled: pluginId => `外掛「${pluginId}」已停用`,
pluginDisabledBody: '在 設定 → 外掛 中重新啟用即可恢復面板。',
missingPane: paneId => `缺少面板:${paneId}`,
diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts
index 9a07fb4e247..eb35364ae72 100644
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@ -3234,6 +3234,7 @@ export const zh: Translations = {
closeToRight: '关闭右侧',
closeAll: '全部关闭',
newSessionTab: '新建会话标签',
+ newTab: '新建标签页',
pluginDisabled: pluginId => `插件“${pluginId}”已禁用`,
pluginDisabledBody: '在 设置 → 插件 中重新启用即可恢复面板。',
missingPane: paneId => `缺少面板:${paneId}`,
diff --git a/apps/desktop/src/store/preview-open-browser.test.ts b/apps/desktop/src/store/preview-open-browser.test.ts
index a2d0a4d6fc2..c7037c7344c 100644
--- a/apps/desktop/src/store/preview-open-browser.test.ts
+++ b/apps/desktop/src/store/preview-open-browser.test.ts
@@ -30,7 +30,8 @@ describe('openBrowserTab', () => {
expect(tabs[0]?.target.url).toBe('https://example.com')
})
- it('reuses the one Browser tab rather than stacking duplicates', () => {
+ // "Show me the browser" is idempotent — the "+" is how you ask for another.
+ it('shows the browser it already has rather than stacking duplicates', () => {
openBrowserTab()
openBrowserTab()
openBrowserTab()
@@ -38,7 +39,6 @@ describe('openBrowserTab', () => {
expect($previewTabs.get()).toHaveLength(1)
})
- // A file tab is keyed by identity; only the web surface is a singleton.
it('leaves other preview tabs alone', () => {
openPreview({ kind: 'file', label: 'notes.md', source: '/work/notes.md', url: 'file:///work/notes.md' })
openBrowserTab()
diff --git a/apps/desktop/src/store/preview.test.ts b/apps/desktop/src/store/preview.test.ts
index 8a04f37f0f8..589367f9575 100644
--- a/apps/desktop/src/store/preview.test.ts
+++ b/apps/desktop/src/store/preview.test.ts
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
-import { $rightRailActiveTabId } from './layout'
+import { $rightRailActiveTabId, selectRightRailTab } from './layout'
import {
$previewServerRestart,
$previewServerRestartStatus,
@@ -11,6 +11,7 @@ import {
closePreviewMatching,
closeRightRail,
closeRightRailTab,
+ newBrowserTab,
openPreview,
previewTabId,
type PreviewTarget,
@@ -69,10 +70,10 @@ describe('preview store', () => {
expect($previewTabs.get().map(tab => tab.target.kind)).toEqual(['file', 'url', 'artifact'])
})
- // The Browser is a SINGLETON: the tab names the surface, not the page, so a
- // second URL navigates the browser it already has instead of stacking a
- // second Browser tab beside the first.
- it('keeps one Browser tab — a second url swaps its target instead of adding a tab', () => {
+ // A Browser tab is a VESSEL, so a link hands its page to the browser you are
+ // already looking at. New tabs are something you ask for (`newBrowserTab`) —
+ // otherwise an agent opening five pages leaves five Browsers behind.
+ it('navigates the open Browser rather than stacking a second one', () => {
openPreview(urlTarget('https://news.ycombinator.com'), 'tool-result')
openPreview(urlTarget('https://www.reddit.com'), 'tool-result')
@@ -83,6 +84,42 @@ describe('preview store', () => {
expect($rightRailActiveTabId.get()).toBe(urlTabs[0].id)
})
+ it('opens more than one Browser on request, each holding its own page', () => {
+ openPreview(urlTarget('https://news.ycombinator.com'), 'tool-result')
+ newBrowserTab()
+ openPreview(urlTarget('https://www.reddit.com'), 'tool-result')
+
+ const urlTabs = $previewTabs.get().filter(tab => tab.target.kind === 'url')
+
+ expect(urlTabs.map(tab => tab.target.url)).toEqual(['https://news.ycombinator.com', 'https://www.reddit.com'])
+ expect(new Set(urlTabs.map(tab => tab.id)).size).toBe(2)
+ })
+
+ // Which Browser a link lands in: the one on screen. Selecting the older tab
+ // must send the next page there, not to whichever was opened most recently.
+ it('navigates the Browser you are looking at', () => {
+ openPreview(urlTarget('https://news.ycombinator.com'), 'tool-result')
+ const first = $previewTabs.get()[0].id
+
+ newBrowserTab()
+ selectRightRailTab(first)
+ openPreview(urlTarget('https://www.reddit.com'), 'tool-result')
+
+ expect($previewTabs.get().find(tab => tab.id === first)?.target.url).toBe('https://www.reddit.com')
+ expect($previewTabs.get()).toHaveLength(2)
+ })
+
+ it('reuses a closed slot instead of counting Browser ids up forever', () => {
+ newBrowserTab()
+ const first = $previewTabs.get()[0].id
+
+ newBrowserTab()
+ closeRightRailTab(first)
+ newBrowserTab()
+
+ expect($previewTabs.get().map(tab => tab.id)).toContain(first)
+ })
+
it('re-fronts an existing tab instead of duplicating it, refreshing its target', () => {
openPreview({ ...fileTarget('/work/demo.html'), label: 'old' }, 'file-browser')
openPreview({ ...fileTarget('/work/demo.html'), label: 'new' }, 'file-browser')
diff --git a/apps/desktop/src/store/preview.ts b/apps/desktop/src/store/preview.ts
index a62f09f5d2f..4d86035f350 100644
--- a/apps/desktop/src/store/preview.ts
+++ b/apps/desktop/src/store/preview.ts
@@ -118,20 +118,11 @@ function isPdfFileTarget(target: PreviewTarget): boolean {
export function decodePreviewTabs(raw: string): PreviewTab[] {
const parsed = JSON.parse(raw) as unknown
- const tabs = (Array.isArray(parsed) ? parsed.filter(isPreviewTab) : []).map(tab =>
+ return (Array.isArray(parsed) ? parsed.filter(isPreviewTab) : []).map(tab =>
isPdfFileTarget(tab.target) && tab.target.previewKind === 'binary'
? { ...tab, target: { ...tab.target, previewKind: 'pdf' as const } }
: tab
)
-
- // One Browser: rekey restored URL tabs onto the singleton id (rows written
- // before the id existed carried one id per address) and keep only the
- // LAST — the most recently opened page is the one the browser shows.
- const lastUrl = tabs.findLast(tab => tab.target.kind === 'url')
-
- return tabs
- .filter(tab => tab.target.kind !== 'url' || tab === lastUrl)
- .map(tab => (tab.target.kind === 'url' ? { ...tab, id: previewTabId(tab.target) } : tab))
}
export const $previewTabs = persistentAtom<PreviewTab[]>(TABS_STORAGE_KEY, [], {
@@ -183,19 +174,78 @@ export const $previewTarget = computed(
* preview open and closed by the target they were handed. */
export const $previewTabSources = computed($previewTabs, tabs => tabs.map(tab => tab.target.source))
+export interface BrowserPage {
+ title: string
+ url: string
+}
+
+/**
+ * What each Browser tab is SHOWING right now, as opposed to the target it was
+ * opened with. Kept out of the target on purpose: the pane builds its guest
+ * from `target.url`, so folding navigation back in would tear the webview down
+ * and lose the history behind it. Memory-only — a restored tab reports again
+ * on its first load.
+ */
+export const $browserPages = atom<Record<string, BrowserPage>>({})
+
+export function noteBrowserPage(tabId: string, page: BrowserPage) {
+ const current = $browserPages.get()[tabId]
+
+ if (current?.title === page.title && current.url === page.url) {
+ return
+ }
+
+ $browserPages.set({ ...$browserPages.get(), [tabId]: page })
+}
+
+export function forgetBrowserPage(tabId: string) {
+ const { [tabId]: gone, ...rest } = $browserPages.get()
+
+ if (gone) {
+ $browserPages.set(rest)
+ }
+}
+
export const $previewReloadRequest = atom(0)
export const $previewServerRestart = atom<PreviewServerRestart | null>(null)
export const $previewServerRestartStatus = computed($previewServerRestart, restart => restart?.status ?? 'idle')
-/** The one Browser tab's id. URL targets all share it: the tab names the
- * SURFACE (Browser), not the page, so opening a second URL navigates the
- * browser it already has — re-front the tab, swap its target, and the pane
- * rebuilds its webview against the new url. Files and artifacts stay keyed
- * by identity; only the web surface is a singleton. */
-const BROWSER_TAB_ID: RightRailTabId = 'url:browser'
-
+/** The tab that owns `target`. Files and artifacts are keyed by IDENTITY —
+ * the same file is always the same tab, reopening it re-fronts the one it
+ * already has. A URL has no identity here: a Browser tab is a vessel you
+ * navigate, so it is picked (`browserTabId`) rather than derived. */
export function previewTabId(target: PreviewTarget): RightRailTabId {
- return target.kind === 'url' ? BROWSER_TAB_ID : `${target.kind}:${target.url}`
+ return `${target.kind}:${target.url}`
+}
+
+const isBrowserTab = (tab: PreviewTab): boolean => tab.target.kind === 'url'
+
+/** The lowest free Browser slot, so ids stay short and readable across a
+ * restore instead of accreting one per page ever opened. */
+function mintBrowserTabId(tabs: PreviewTab[]): RightRailTabId {
+ const used = new Set(tabs.map(tab => tab.id))
+
+ for (let n = 1; ; n += 1) {
+ const id: RightRailTabId = `url:browser-${n}`
+
+ if (!used.has(id)) {
+ return id
+ }
+ }
+}
+
+/** The Browser a URL should open in: the one you're looking at, else the one
+ * you used last. A link from chat navigates the browser you already have
+ * rather than stacking another identical tab — new tabs are something you
+ * ask for (the strip's "+"), the way they are in a real browser. */
+function browserTabId(tabs: PreviewTab[]): RightRailTabId {
+ const active = tabs.find(tab => tab.id === $rightRailActiveTabId.get())
+
+ if (active && isBrowserTab(active)) {
+ return active.id
+ }
+
+ return tabs.findLast(isBrowserTab)?.id ?? mintBrowserTabId(tabs)
}
// Browsing files is "peek at the source"; a tool or an explicit link handing
@@ -217,8 +267,8 @@ function previewTargetForSource(target: PreviewTarget, source: PreviewRecordSour
* only way anything reaches a preview. */
export function openPreview(target: PreviewTarget, source: PreviewRecordSource = 'manual') {
const resolved = previewTargetForSource(target, source)
- const id = previewTabId(resolved)
const current = $previewTabs.get()
+ const id = resolved.kind === 'url' ? browserTabId(current) : previewTabId(resolved)
const index = current.findIndex(tab => tab.id === id)
const tab: PreviewTab = { id, target: resolved }
@@ -226,13 +276,26 @@ export function openPreview(target: PreviewTarget, source: PreviewRecordSource =
selectRightRailTab(id)
}
-/** Open the Browser tab — the surface, not a page. Keeps whatever it was last
- * showing so the hotkey re-fronts your page instead of wiping it; a fresh tab
- * lands on `about:blank`, where the pane's empty state invites an address. */
+const blankPage = (): PreviewTarget => ({ kind: 'url', label: 'Browser', source: 'about:blank', url: 'about:blank' })
+
+/** Show the Browser — the surface, not a page. Keeps whatever it was last
+ * showing so the hotkey re-fronts your page instead of wiping it; with no
+ * browser open it lands on `about:blank`, where the pane's empty state
+ * invites an address. */
export function openBrowserTab() {
- const existing = $previewTabs.get().find(tab => tab.id === BROWSER_TAB_ID)
+ const tabs = $previewTabs.get()
+ const current = tabs.find(tab => tab.id === browserTabId(tabs))
- openPreview(existing?.target ?? { kind: 'url', label: 'Browser', source: 'about:blank', url: 'about:blank' })
+ openPreview(current?.target ?? blankPage())
+}
+
+/** Another Browser, always — the strip's "+". */
+export function newBrowserTab() {
+ const tabs = $previewTabs.get()
+ const id = mintBrowserTabId(tabs)
+
+ $previewTabs.set([...tabs, { id, target: blankPage() }])
+ selectRightRailTab(id)
}
export function closeRightRailTab(tabId: string) {