Skip to content

The agent that grows with you

fix(desktop): hand the popped-out Browser its tab from shared storage (#119850)

finn76371b79122cac7
diff --git a/apps/desktop/src/app/chat/browser-popout-handoff.test.tsx b/apps/desktop/src/app/chat/browser-popout-handoff.test.tsx
new file mode 100644
index 00000000000..e1d63cc2abc
--- /dev/null
+++ b/apps/desktop/src/app/chat/browser-popout-handoff.test.tsx
@@ -0,0 +1,144 @@
+import { act, cleanup, render, waitFor } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+// The consent dialog has its own test file and needs a QueryClientProvider;
+// this test exercises the pop-out content handoff, not the prompt.
+vi.mock('./right-rail/real-profile-consent-dialog', () => ({
+ RealProfileConsentDialog: () => null
+}))
+
+// A popped-out Browser window is a FRESH renderer: no in-memory atoms cross
+// the window boundary, and no session ever pushes a rail scope there. All it
+// knows arrives via shared persisted tabs plus `?win=browser&tab=` in its own
+// URL. Each test therefore resets the module registry (fresh atoms, cold
+// caches — exactly what a new renderer process boots with), seeds storage the
+// way the main window left it, sets the pop-out query string, and only then
+// imports the shell. Regression tests for the black pop-out window (shell
+// spawns, no URL bar, content never paints — #119850).
+const TABS_KEY = 'hermes.desktop.previewTabs.v2'
+
+// Cold module graph, not test logic: the shell pulls in the whole app.
+vi.setConfig({ testTimeout: 90000 })
+
+function tabRow(id: string, url: string) {
+ return { id, target: { kind: 'url', label: 'kanban', source: url, url } }
+}
+
+function storedBuckets(): Record<string, { id: string }[]> {
+ const raw = window.localStorage.getItem(TABS_KEY)
+
+ return raw ? (JSON.parse(raw) as Record<string, { id: string }[]>) : {}
+}
+
+beforeEach(() => {
+ vi.resetModules()
+ window.localStorage.clear()
+})
+
+afterEach(() => {
+ cleanup()
+ window.localStorage.clear()
+ window.history.replaceState({}, '', '/')
+})
+
+async function renderFreshPopout(tabId: string) {
+ window.history.replaceState({}, '', `/?win=browser&tab=${encodeURIComponent(tabId)}#/`)
+ const { BrowserPopoutShell } = await import('./browser-popout-shell')
+
+ let rendered!: ReturnType<typeof render>
+ await act(async () => {
+ rendered = render(<BrowserPopoutShell />)
+ })
+
+ return rendered
+}
+
+async function expectGuestWithUrl(rendered: ReturnType<typeof render>, url: string) {
+ // The tab arrives via a store update after mount; wait for the re-render.
+ // Generous timeout: the first test in this file pays the cold module-graph
+ // import and every poll must survive it.
+ await waitFor(
+ () => {
+ expect(rendered.container.querySelector('webview')?.getAttribute('src')).toBe(url)
+ },
+ { timeout: 30000 }
+ )
+
+ // Identity: the pop-out bar offers pop-in for this tab (icon-only glyph with
+ // an accessible name, so assert the aria-label, not text content).
+ expect(rendered.container.querySelector('[aria-label="Pop in"]')).not.toBeNull()
+
+ // Address bar tracks the handed-off URL.
+ expect((rendered.container.querySelector('input') as HTMLInputElement | null)?.value).toContain(
+ '127.0.0.1'
+ )
+}
+
+describe('browser pop-out content handoff', () => {
+ it('hands the persisted tab URL to a guest (pre-scoping single-array storage)', async () => {
+ const id = 'url:browser-legacy-1'
+ const url = 'http://127.0.0.1:9119/kanban'
+ window.localStorage.setItem(TABS_KEY, JSON.stringify([tabRow(id, url)]))
+
+ const rendered = await renderFreshPopout(id)
+ await expectGuestWithUrl(rendered, url)
+ })
+
+ it('hands the persisted tab URL to a guest (profile-bucketed storage)', async () => {
+ const id = 'url:browser-bucket-1'
+ const url = 'http://127.0.0.1:9119/kanban'
+ window.localStorage.setItem(TABS_KEY, JSON.stringify({ local: [tabRow(id, url)] }))
+
+ const rendered = await renderFreshPopout(id)
+ await expectGuestWithUrl(rendered, url)
+ })
+
+ it('re-homes onto the owning bucket without duplicating the tab elsewhere', async () => {
+ // The popped tab belongs to a secondary profile. Adoption must move the
+ // VIEW onto that profile's bucket — not splice the tab into the 'default'
+ // bucket the renderer booted on, which would resurrect it in the primary
+ // profile's rail.
+ const id = 'url:browser-owned-1'
+ const url = 'http://127.0.0.1:9119/kanban'
+ window.localStorage.setItem(TABS_KEY, JSON.stringify({ local: [tabRow(id, url)] }))
+
+ const rendered = await renderFreshPopout(id)
+ await expectGuestWithUrl(rendered, url)
+
+ expect(Object.keys(storedBuckets())).toEqual(['local'])
+ })
+
+ it('leaves an unknown tab blank rather than adopting a stranger', async () => {
+ const url = 'http://127.0.0.1:9119/kanban'
+ window.localStorage.setItem(TABS_KEY, JSON.stringify({ local: [tabRow('url:browser-known-1', url)] }))
+
+ const rendered = await renderFreshPopout('url:browser-nope')
+
+ expect(rendered.container.querySelector('webview')).toBeNull()
+ expect(rendered.container.textContent).not.toContain('Pop in')
+ })
+})
+
+describe('a fresh renderer adopts stored tabs without clobbering them', () => {
+ // Same bug family, store half: the scoped-tabs subscribe fires on module
+ // init, and echoing the just-read (empty) view back over storage wiped the
+ // record before any adoption could read it.
+ it('seeds the default bucket into the view at boot', async () => {
+ window.localStorage.setItem(TABS_KEY, JSON.stringify({ default: [tabRow('url:boot-1', 'http://127.0.0.1:9119/kanban')] }))
+
+ const { $previewTabs } = await import('@/store/preview')
+
+ expect($previewTabs.get().map(tab => tab.id)).toEqual(['url:boot-1'])
+ expect(window.localStorage.getItem(TABS_KEY)).not.toBeNull()
+ })
+
+ it('does not wipe a legacy single-array store at boot', async () => {
+ window.localStorage.setItem(TABS_KEY, JSON.stringify([tabRow('url:boot-legacy-1', 'http://127.0.0.1:9119/kanban')]))
+
+ const { adoptPersistedBrowserTab, $previewTabs } = await import('@/store/preview')
+ adoptPersistedBrowserTab('url:boot-legacy-1')
+
+ expect($previewTabs.get().map(tab => tab.id)).toEqual(['url:boot-legacy-1'])
+ expect(storedBuckets().default?.map(tab => tab.id)).toEqual(['url:boot-legacy-1'])
+ })
+})
diff --git a/apps/desktop/src/app/chat/right-rail/preview.tsx b/apps/desktop/src/app/chat/right-rail/preview.tsx
index d831bcbb846..545de50cddc 100644
--- a/apps/desktop/src/app/chat/right-rail/preview.tsx
+++ b/apps/desktop/src/app/chat/right-rail/preview.tsx
@@ -1,7 +1,9 @@
import { useStore } from '@nanostores/react'
+import { useEffect } from 'react'
import { $restartPreviewServer } from '@/app/contrib/panes'
-import { $previewReloadRequest, $previewTabs } from '@/store/preview'
+import { $previewReloadRequest, $previewTabs, adoptPersistedBrowserTab } from '@/store/preview'
+import { isBrowserWindow } from '@/store/windows'
import { PreviewPane } from './preview-pane'
@@ -26,6 +28,17 @@ export function PreviewTilePane({ onClose, tabId }: PreviewTilePaneProps) {
const previewReloadRequest = useStore($previewReloadRequest)
const previewTabs = useStore($previewTabs)
const restartPreviewServer = useStore($restartPreviewServer)
+
+ // A popped-out Browser is a fresh renderer: no session ever pushes a scope
+ // there, so its scoped view may start empty. Pull this window's tab in from
+ // shared storage; the docked mirror never runs this (it is not a browser
+ // window), so a closed tab stays closed there.
+ useEffect(() => {
+ if (isBrowserWindow() && tabId && !previewTabs.some(tab => tab.id === tabId)) {
+ adoptPersistedBrowserTab(tabId)
+ }
+ }, [previewTabs, tabId])
+
const target = previewTabs.find(tab => tab.id === tabId)?.target
// The tab closed while this pane was still mounted (the mirror disposes it a
diff --git a/apps/desktop/src/store/preview.ts b/apps/desktop/src/store/preview.ts
index 810d47483a2..f3d05c537b5 100644
--- a/apps/desktop/src/store/preview.ts
+++ b/apps/desktop/src/store/preview.ts
@@ -1,6 +1,6 @@
import { atom, computed } from 'nanostores'
-import { readJson, readKey, writeKey } from '@/lib/storage'
+import { readJson, writeKey } from '@/lib/storage'
import { normalize } from '@/lib/text'
import { $rightRailActiveTabId, type RightRailTabId, selectRightRailTab } from './layout'
@@ -209,12 +209,33 @@ let viewKey = 'default'
export const $previewTabs = atom<PreviewTab[]>([])
+// Adoption phase: emissions that carry storage THIS MODULE JUST READ, not a
+// change. nanostores' subscribe fires immediately, and writing what was just
+// read back is a data-loss clobber: every renderer boots against storage it
+// has not adopted yet, and echoing the empty view back overwrites the real
+// record before adoption can read it. A legacy single-array store is wiped
+// this way before `pendingLegacyTabs` is ever adopted; a bucket store loses
+// its `default` bucket the same way.
+let adoptingStoredTabs = true
+
$previewTabs.subscribe(tabs => {
+ if (adoptingStoredTabs) {
+ return
+ }
+
// `subscribe` hands a readonly view; the bucket is a mutable store of its own.
tabsByProfile[viewKey] = [...tabs]
persistTabs()
})
+// Seed the view with this renderer's own bucket. Without it the primary
+// profile's rail never restores: `viewKey` already IS 'default', so
+// `setPreviewScope` early-returns and nothing else moves the bucket into the
+// atom. Suppressed like the creation emission above — a persist here would
+// echo the just-read record back out (wiping a legacy store before adoption).
+$previewTabs.set(tabsByProfile[viewKey] ?? [])
+adoptingStoredTabs = false
+
/** Re-home the rail onto the profile that owns the chat on screen. Called by
* `session-states.ts` whenever the focused session (or its resolved owner)
* changes; the previous agent's tabs must not leak into the next one. */
@@ -225,6 +246,15 @@ export function setPreviewScope(scope: string) {
return
}
+ applyPreviewScope(next)
+}
+
+/** Swap the view onto `next`'s bucket (legacy tabs ride along into it). Split
+ * from `setPreviewScope` so `adoptPersistedBrowserTab` can force a re-home
+ * onto the bucket a persisted tab lives in — the same-key early return above
+ * would skip exactly that case (a fresh pop-out renderer starts on 'default'
+ * while the popped tab belongs to another profile). */
+function applyPreviewScope(next: string) {
if (pendingLegacyTabs) {
tabsByProfile[next] = [...(tabsByProfile[next] ?? []), ...pendingLegacyTabs]
pendingLegacyTabs = null
@@ -387,27 +417,56 @@ export function commitBrowserTabLocation(tabId: string, url: string, title?: str
)
}
-/** Pull one tab from storage into this renderer's atom. A sibling window
- * (the pop-out) may have committed a newer URL that we never saw. */
+/** Pull one tab out of shared storage into this renderer's view. Two callers,
+ * two shapes (#119850):
+ *
+ * - The docked mirror when a pop-out closes (`onBrowserPopoutClosed`): the
+ * tab is already in this view, so adopt the newer URL/label the sibling
+ * window committed — every bucket is fair game, because the sibling writes
+ * through its own scoped view, which is not necessarily this one.
+ * - A fresh pop-out renderer (`PreviewTilePane` in `?win=browser`): no
+ * session ever pushes a scope there, so the scoped view starts empty. Find
+ * the bucket that owns the tab and re-home the view onto it. Re-homing
+ * rather than splicing the tab into the current bucket keeps this window's
+ * later writes (address-bar navigation) in the OWNER's bucket — a splice
+ * would duplicate the tab into the primary profile's rail.
+ *
+ * Reads every profile bucket plus the pre-scoping single-array shape. */
export function adoptPersistedBrowserTab(tabId: string) {
if (!tabId) {
return
}
try {
- const raw = readKey(TABS_STORAGE_KEY)
+ const stored = readJson<unknown>(TABS_STORAGE_KEY)
- if (!raw) {
+ if (!stored) {
return
}
- const persisted = decodePreviewTabs(raw).find(tab => tab.id === tabId)
+ const buckets: Array<[string, PreviewTab[]]> = Array.isArray(stored)
+ ? [['default', parseTabList(stored)]]
+ : Object.entries(stored as Record<string, unknown>).map(
+ ([key, value]) => [normalizeProfileKey(key), parseTabList(value)] as [string, PreviewTab[]]
+ )
+
+ if ($previewTabs.get().some(tab => tab.id === tabId)) {
+ const persisted = buckets.flatMap(([, tabs]) => tabs).find(tab => tab.id === tabId)
+
+ if (persisted?.target.kind === 'url') {
+ commitBrowserTabLocation(tabId, persisted.target.url, persisted.target.label)
+ }
- if (!persisted || persisted.target.kind !== 'url') {
return
}
- commitBrowserTabLocation(tabId, persisted.target.url, persisted.target.label)
+ for (const [key, tabs] of buckets) {
+ if (tabs.some(tab => tab.id === tabId)) {
+ applyPreviewScope(key || 'default')
+
+ return
+ }
+ }
} catch {
// Storage can throw; the in-memory tab stays as it was.
}