Skip to content

The agent that grows with you

fix(desktop): keep session-scoped preview tabs owned, restorable and rotation-safe

teknium11cd91c69c57d
diff --git a/apps/desktop/src/app/chat/preview-tile.test.ts b/apps/desktop/src/app/chat/preview-tile.test.ts
index b19fe9c203c..77ff300287e 100644
--- a/apps/desktop/src/app/chat/preview-tile.test.ts
+++ b/apps/desktop/src/app/chat/preview-tile.test.ts
@@ -186,14 +186,15 @@ describe('preview tiles mirror the visible session tabs', () => {
return { model, preview, session, tree }
}
- const htmlTarget = (path: string) => ({
- kind: 'file',
- label: path.split('/').at(-1) ?? path,
- path,
- previewKind: 'html',
- source: path,
- url: `file://${path}`
- }) as const
+ const htmlTarget = (path: string) =>
+ ({
+ kind: 'file',
+ label: path.split('/').at(-1) ?? path,
+ path,
+ previewKind: 'html',
+ source: path,
+ url: `file://${path}`
+ }) as const
it('renders only the focused session previews, pinning spans sessions', async () => {
const { preview, session, tree } = await setup()
@@ -217,6 +218,25 @@ describe('preview tiles mirror the visible session tabs', () => {
expect(tree.treePanesWithPrefix('preview-tile:')).toHaveLength(0)
})
+ it('fronts the tab a session last had in front when switching back to it', async () => {
+ const { preview, session } = await setup()
+ const layout = await import('@/store/layout')
+
+ session.$selectedStoredSessionId.set('sess-1')
+ preview.openPreview(htmlTarget('/work/a.html'))
+ preview.openPreview(htmlTarget('/work/b.html'))
+ const bId = layout.$rightRailActiveTabId.get()
+
+ preview.openPreview(htmlTarget('/work/a.html'))
+ layout.selectRightRailTab(bId)
+
+ session.$selectedStoredSessionId.set('sess-2')
+ preview.openPreview(htmlTarget('/work/c.html'))
+
+ session.$selectedStoredSessionId.set('sess-1')
+ expect(layout.$rightRailActiveTabId.get()).toBe(bId)
+ })
+
it('does not create panes for another session tabs', async () => {
const { preview, session, tree } = await setup()
diff --git a/apps/desktop/src/app/chat/preview-tile.tsx b/apps/desktop/src/app/chat/preview-tile.tsx
index 0c79369d317..e46c755c336 100644
--- a/apps/desktop/src/app/chat/preview-tile.tsx
+++ b/apps/desktop/src/app/chat/preview-tile.tsx
@@ -38,6 +38,7 @@ import {
markBrowserTabPopped,
newBrowserTab,
popOutBrowserTab,
+ preferredVisibleTabId,
type PreviewTarget,
setPreviewTabPinned
} from '@/store/preview'
@@ -253,13 +254,14 @@ export function watchPreviewTiles(): void {
})
// A session switch (or an unpin) can leave the active tab outside the
- // visible set — re-home the selection to the first visible tab so the strip
- // and the pane never point at a hidden preview.
+ // visible set — re-home the selection onto the tab that session last had in
+ // front (else its first) so the strip and the pane never point at a hidden
+ // preview.
const rehome = () => {
- const visible = $visiblePreviewTabs.get()
+ const preferred = preferredVisibleTabId()
- if (!visible.some(tab => tab.id === $rightRailActiveTabId.get())) {
- selectRightRailTab(visible[0]?.id ?? null)
+ if (preferred !== $rightRailActiveTabId.get()) {
+ selectRightRailTab(preferred)
}
}
@@ -304,9 +306,8 @@ export function watchPreviewTiles(): void {
const watchPreviewTileMirror = paneMirror<{ id: string }>({
// Only the FOCUSED session's tabs (plus pins) become panes — switching
// sessions swaps the drawer; a hidden tab's pane leaves the tree without
- // closing the tab (paneMirror's sync disposes, it doesn't call close).
- // Composed with $dockedPreviewTabs so a popped-out Browser pane also
- // leaves the docked tree.
+ // closing the tab (paneMirror's sync disposes, it doesn't call close). A
+ // popped-out Browser's pane also leaves the docked tree.
source: $dockedVisiblePreviewTabs,
key: tab => tab.id,
prefix: PREVIEW_TILE_PREFIX,
diff --git a/apps/desktop/src/app/session/hooks/preview-open.test.tsx b/apps/desktop/src/app/session/hooks/preview-open.test.tsx
index 2cc37d717c5..a4fa5233f2e 100644
--- a/apps/desktop/src/app/session/hooks/preview-open.test.tsx
+++ b/apps/desktop/src/app/session/hooks/preview-open.test.tsx
@@ -151,7 +151,13 @@ describe('preview routing', () => {
try {
await emitPreviewOpen('/tmp/from-tile.html', 'tile-runtime')
- await waitFor(() => expect($previewTarget.get()?.path).toBe('/tmp/from-tile.html'))
+ // Honoured, and owned by the tile's session (#73890): it shows in
+ // that session's drawer, not in whichever one holds focus.
+ await waitFor(() =>
+ expect($previewTabs.get().map(tab => [tab.target.path, tab.sessionId])).toEqual([
+ ['/tmp/from-tile.html', 'stored-tile']
+ ])
+ )
} finally {
$sessionTiles.set(tiles)
}
@@ -284,6 +290,30 @@ describe('preview routing', () => {
}
})
+ it('closes only the tile session tabs when its agent closes without a url', async () => {
+ const { $sessionTiles } = await import('@/store/session-states')
+ const tiles = $sessionTiles.get()
+
+ $selectedStoredSessionId.set('stored-main')
+ $sessionTiles.set([{ dir: 'right', runtimeId: 'tile-runtime', storedSessionId: 'stored-tile' }])
+ render(<Harness />)
+
+ try {
+ await emitPreviewOpen('/tmp/main.html')
+ await emitPreviewOpen('/tmp/from-tile.html', 'tile-runtime')
+ await waitFor(() => expect($previewTabs.get()).toHaveLength(2))
+
+ await emitPreviewClose('', 'tile-runtime')
+
+ expect($previewTabs.get().map(tab => [tab.target.path, tab.sessionId])).toEqual([
+ ['/tmp/main.html', 'stored-main']
+ ])
+ expect($previewTarget.get()?.path).toBe('/tmp/main.html')
+ } finally {
+ $sessionTiles.set(tiles)
+ }
+ })
+
it('ignores a close from a session that is not the one on screen', async () => {
render(<Harness />)
diff --git a/apps/desktop/src/app/session/hooks/use-preview-routing.ts b/apps/desktop/src/app/session/hooks/use-preview-routing.ts
index 9dc369c7465..c4cb767e946 100644
--- a/apps/desktop/src/app/session/hooks/use-preview-routing.ts
+++ b/apps/desktop/src/app/session/hooks/use-preview-routing.ts
@@ -7,9 +7,7 @@ import { reachablePreviewUrl } from '@/lib/preview-reach'
import {
$previewTabs,
beginPreviewServerRestart,
- closeBrowserPreviewMatchingLiveUrl,
- closeDockedPreviewMatching,
- closeRightRail,
+ closeAgentPreview,
completePreviewServerRestart,
openPreview,
progressPreviewServerRestart,
@@ -17,7 +15,12 @@ import {
requestPreviewReload
} from '@/store/preview'
import { $activeSessionId, $currentCwd } from '@/store/session'
-import { $focusedRuntimeId, $sessionTiles } from '@/store/session-states'
+import {
+ $focusedRuntimeId,
+ $focusedStoredSessionId,
+ $sessionTiles,
+ storedSessionIdForRuntimeId
+} from '@/store/session-states'
type EventHandler = (event: GatewayEvent) => void
@@ -39,6 +42,13 @@ function sessionIsOnScreen(sessionId: string): boolean {
)
}
+/** The stored id whose drawer an agent's preview event belongs to: the session
+ * that ran the tool, not whichever one holds focus (#73890). A runtime with no
+ * stored id yet is a fresh draft, whose tabs are ownerless until adopted. */
+function previewOwnerForEvent(sessionId: string | undefined): null | string {
+ return sessionId ? storedSessionIdForRuntimeId(sessionId) : $focusedStoredSessionId.get()
+}
+
export function usePreviewRouting({ baseHandleGatewayEvent, currentCwd, requestGateway }: PreviewRoutingOptions) {
const restartPreviewServer = useCallback(
async (url: string, context?: string) => {
@@ -102,7 +112,10 @@ export function usePreviewRouting({ baseHandleGatewayEvent, currentCwd, requestG
const url = resolved.kind === 'url' ? await reachablePreviewUrl(resolved.url) : resolved.url
const reached = url === resolved.url ? resolved : { ...resolved, label: resolved.label || target, url }
- openPreview(renderedHtmlTarget(trimmedLabel ? { ...reached, label: trimmedLabel } : reached))
+ openPreview(
+ renderedHtmlTarget(trimmedLabel ? { ...reached, label: trimmedLabel } : reached),
+ previewOwnerForEvent(event.session_id)
+ )
}
)
}
@@ -121,8 +134,10 @@ export function usePreviewRouting({ baseHandleGatewayEvent, currentCwd, requestG
return
}
+ const owner = previewOwnerForEvent(event.session_id)
+
if (!target) {
- closeRightRail()
+ closeAgentPreview(owner, [])
return
}
@@ -139,9 +154,7 @@ export function usePreviewRouting({ baseHandleGatewayEvent, currentCwd, requestG
}
}
- if (!closeBrowserPreviewMatchingLiveUrl(...candidates)) {
- closeDockedPreviewMatching(...candidates)
- }
+ closeAgentPreview(owner, candidates)
}
)
diff --git a/apps/desktop/src/app/session/hooks/use-session-state-cache.test.tsx b/apps/desktop/src/app/session/hooks/use-session-state-cache.test.tsx
index 3edb9fc71b9..93f5b847ded 100644
--- a/apps/desktop/src/app/session/hooks/use-session-state-cache.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-session-state-cache.test.tsx
@@ -232,6 +232,34 @@ describe('useSessionStateCache — stored-id rotation provenance', () => {
expect(tiles.find(t => t.storedSessionId === 'stored-A-next')).toBeDefined()
})
+ it('carries the conversation preview tabs onto the new tip when compression rotates it (#73890)', async () => {
+ const { $previewTabs, $visiblePreviewTabs, closeRightRail, openPreview } = await import('@/store/preview')
+ let cache!: Cache
+
+ setActiveSessionId('runtime-A')
+ setSelectedStoredSessionId('stored-A')
+ render(
+ <Harness activeSessionId="runtime-A" onReady={value => (cache = value)} selectedStoredSessionId="stored-A" />
+ )
+
+ try {
+ openPreview({ kind: 'url', label: 'Docs', source: 'https://docs.example', url: 'https://docs.example' })
+
+ act(() => {
+ cache.updateSessionState('runtime-A', state => state, 'stored-A')
+ cache.updateSessionState('runtime-A', state => state, 'stored-A-next')
+ })
+
+ expect($previewTabs.get().map(tab => tab.sessionId)).toEqual(['stored-A-next'])
+ expect($visiblePreviewTabs.get()).toHaveLength(1)
+
+ act(() => setSelectedStoredSessionId('stored-A-next'))
+ expect($visiblePreviewTabs.get()).toHaveLength(1)
+ } finally {
+ closeRightRail()
+ }
+ })
+
it('rekeys the persisted owner profile when its runtime rotates while another profile is visible', () => {
let cache!: Cache
const profileA = 'rotation-profile-a-98622'
diff --git a/apps/desktop/src/app/session/hooks/use-session-state-cache.ts b/apps/desktop/src/app/session/hooks/use-session-state-cache.ts
index 9c5e2e0adb3..60e47c59198 100644
--- a/apps/desktop/src/app/session/hooks/use-session-state-cache.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-state-cache.ts
@@ -7,6 +7,7 @@ import { preserveLocalAssistantErrors } from '@/lib/chat-messages'
import { createClientSessionState } from '@/lib/chat-runtime'
import { migrateInFlightTurnJournal, persistInFlightTurnState } from '@/lib/inflight-turn-journal'
import { setMutableRef } from '@/lib/mutable-ref'
+import { rekeyPreviewTabsSession } from '@/store/preview'
import {
$activeSessionId,
$messages,
@@ -208,6 +209,7 @@ export function useSessionStateCache({
// rekey, which this path can skip when the state updater is a no-op.
if (storedSessionId) {
rekeySessionTile(existing.storedSessionId, storedSessionId, sessionId)
+ rekeyPreviewTabsSession(existing.storedSessionId, storedSessionId)
}
// A rotation event needs a real next id — a null/cleared stored id
diff --git a/apps/desktop/src/store/preview.test.ts b/apps/desktop/src/store/preview.test.ts
index be7a4f5de16..b2e8021898c 100644
--- a/apps/desktop/src/store/preview.test.ts
+++ b/apps/desktop/src/store/preview.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { group } from '@/components/pane-shell/tree/model'
import { $layoutTree, noteActiveTreeGroup } from '@/components/pane-shell/tree/store'
@@ -12,6 +12,7 @@ import {
$previewTarget,
$visiblePreviewTabs,
beginPreviewServerRestart,
+ closeAgentPreview,
closeBrowserPreviewMatchingLiveUrl,
closePreviewForSource,
closePreviewMatching,
@@ -27,6 +28,7 @@ import {
type PreviewTarget,
progressPreviewServerRestart,
prunePreviewTabsForSession,
+ rekeyPreviewTabsSession,
renderedHtmlTarget,
setPreviewRenderMode,
setPreviewTabPinned
@@ -77,7 +79,7 @@ describe('preview store', () => {
it('opens the pane and fronts the new tab', () => {
openPreview(fileTarget('/work/demo.html'))
- expect($rightRailActiveTabId.get()).toBe('file:/work/demo.html')
+ expect($rightRailActiveTabId.get()).toBe('file:file:///work/demo.html')
expect($previewTarget.get()?.path).toBe('/work/demo.html')
})
@@ -397,13 +399,15 @@ describe('preview store', () => {
})
})
-describe('preview session scoping', () => {
+describe('preview session scoping (#73890)', () => {
afterEach(() => {
$selectedStoredSessionId.set(null)
closeRightRail()
window.localStorage.clear()
})
+ const paths = (tabs: readonly { target: PreviewTarget }[]) => tabs.map(tab => tab.target.path ?? tab.target.url)
+
it('stamps the active session on tabs it opens', () => {
$selectedStoredSessionId.set('sess-1')
openPreview(fileTarget('/work/demo.html'))
@@ -411,23 +415,53 @@ describe('preview session scoping', () => {
expect($previewTabs.get()[0]?.sessionId).toBe('sess-1')
})
- it('shows only the active session tabs plus pinned ones', () => {
+ it('shows only the focused session tabs plus pinned ones, keeping hidden tabs alive', () => {
$selectedStoredSessionId.set('sess-1')
openPreview(fileTarget('/work/a.html'))
$selectedStoredSessionId.set('sess-2')
openPreview(fileTarget('/work/b.html'))
- expect($visiblePreviewTabs.get().map(tab => tab.target.path)).toEqual(['/work/b.html'])
+ expect(paths($visiblePreviewTabs.get())).toEqual(['/work/b.html'])
+ expect($previewTabs.get()).toHaveLength(2)
- // Pinning makes the first session's tab visible in every session.
- const aTab = $previewTabs.get().find(tab => tab.target.path === '/work/a.html')
- setPreviewTabPinned(aTab!.id, true)
+ $selectedStoredSessionId.set('sess-1')
+ expect(paths($visiblePreviewTabs.get())).toEqual(['/work/a.html'])
- expect($visiblePreviewTabs.get().map(tab => tab.target.path).sort()).toEqual(['/work/a.html', '/work/b.html'])
+ const aTab = $previewTabs.get().find(tab => tab.target.path === '/work/a.html')!
+ setPreviewTabPinned(aTab.id, true)
+ $selectedStoredSessionId.set('sess-2')
+ expect(paths($visiblePreviewTabs.get()).sort()).toEqual(['/work/a.html', '/work/b.html'])
- // Unpinning hides it from the other session again.
- setPreviewTabPinned(aTab!.id, false)
- expect($visiblePreviewTabs.get().map(tab => tab.target.path)).toEqual(['/work/b.html'])
+ setPreviewTabPinned(aTab.id, false)
+ expect(paths($visiblePreviewTabs.get())).toEqual(['/work/b.html'])
+ })
+
+ it('opens the same file as one tab per session, and re-fronts it within one', () => {
+ $selectedStoredSessionId.set('sess-1')
+ openPreview(fileTarget('/work/demo.html'))
+ openPreview({ ...fileTarget('/work/demo.html'), url: '/work/demo.html', label: 'refreshed' })
+ $selectedStoredSessionId.set('sess-2')
+ openPreview(fileTarget('/work/demo.html'))
+
+ const tabs = $previewTabs.get()
+
+ expect(tabs.map(tab => tab.sessionId)).toEqual(['sess-1', 'sess-2'])
+ expect(new Set(tabs.map(tab => tab.id)).size).toBe(2)
+ expect(tabs[0]?.target.label).toBe('refreshed')
+ })
+
+ it('reuses a pinned file from another session without changing its owner', () => {
+ $selectedStoredSessionId.set('sess-1')
+ openPreview(fileTarget('/work/a.html'))
+ const id = $previewTabs.get()[0]!.id
+ setPreviewTabPinned(id, true)
+
+ $selectedStoredSessionId.set('sess-2')
+ openPreview({ ...fileTarget('/work/a.html'), label: 'refreshed' })
+
+ expect($previewTabs.get()).toHaveLength(1)
+ expect($previewTabs.get()[0]).toMatchObject({ id, pinned: true, sessionId: 'sess-1' })
+ expect($rightRailActiveTabId.get()).toBe(id)
})
it('prunes a deleted session tabs but keeps its pins', () => {
@@ -438,11 +472,10 @@ describe('preview session scoping', () => {
openPreview(fileTarget('/work/b.html'))
prunePreviewTabsForSession('sess-2')
- expect($previewTabs.get().map(tab => tab.target.path)).toEqual(['/work/a.html'])
+ expect(paths($previewTabs.get())).toEqual(['/work/a.html'])
- // Pinned tabs belong to the workspace, not the session that opened them.
prunePreviewTabsForSession('sess-1')
- expect($previewTabs.get().map(tab => tab.target.path)).toEqual(['/work/a.html'])
+ expect(paths($previewTabs.get())).toEqual(['/work/a.html'])
})
it('adopts ownerless draft tabs when a session appears', () => {
@@ -450,103 +483,142 @@ describe('preview session scoping', () => {
expect($previewTabs.get()[0]?.sessionId).toBeUndefined()
$selectedStoredSessionId.set('sess-new')
+
expect($previewTabs.get()[0]?.sessionId).toBe('sess-new')
- // The id is rekeyed onto the session-scoped form so a later open of the
- // same file dedupes instead of stacking.
- expect($previewTabs.get()[0]?.id).toBe('file:sess-new:/work/draft.html')
- expect($visiblePreviewTabs.get().map(tab => tab.target.path)).toEqual(['/work/draft.html'])
+ expect(paths($visiblePreviewTabs.get())).toEqual(['/work/draft.html'])
})
- it('canonicalizes file identities across entry points', () => {
- expect(previewTabId(fileTarget('/work/demo.html'))).toBe('file:/work/demo.html')
+ it('owns a strip "+" Browser by the focused session, never adopting it elsewhere', () => {
+ $selectedStoredSessionId.set('sess-x')
+ newBrowserTab()
+ const id = $previewTabs.get()[0]!.id
+
+ expect($previewTabs.get()[0]?.sessionId).toBe('sess-x')
+ expect($visiblePreviewTabs.get().map(tab => tab.id)).toEqual([id])
- const viaPlainPath = previewTabId({ ...fileTarget('/work/demo.html'), url: '/work/demo.html' })
- expect(viaPlainPath).toBe('file:/work/demo.html')
+ $selectedStoredSessionId.set('sess-y')
+ expect($visiblePreviewTabs.get()).toHaveLength(0)
+ expect($previewTabs.get()[0]?.sessionId).toBe('sess-x')
})
- it('scopes file tab ids to the session, so two sessions can open the same file', () => {
- expect(previewTabId(fileTarget('/work/demo.html'), 'sess-1')).toBe('file:sess-1:/work/demo.html')
- expect(previewTabId(fileTarget('/work/demo.html'), 'sess-2')).toBe('file:sess-2:/work/demo.html')
+ it('never navigates another session Browser for a URL open', () => {
+ $selectedStoredSessionId.set('sess-a')
+ openPreview(urlTarget('https://a.example'))
+ const aBrowser = $previewTabs.get()[0]!
- $selectedStoredSessionId.set('sess-1')
- openPreview(fileTarget('/work/demo.html'))
- $selectedStoredSessionId.set('sess-2')
- openPreview(fileTarget('/work/demo.html'))
+ $selectedStoredSessionId.set('sess-b')
+ openPreview(urlTarget('https://b.example'))
- const tabs = $previewTabs.get()
+ expect($previewTabs.get()).toHaveLength(2)
+ expect($previewTabs.get().find(tab => tab.id === aBrowser.id)).toMatchObject({
+ sessionId: 'sess-a',
+ target: { url: 'https://a.example' }
+ })
- expect(tabs).toHaveLength(2)
- expect(tabs[0]).toMatchObject({ sessionId: 'sess-1', id: 'file:sess-1:/work/demo.html' })
- expect(tabs[1]).toMatchObject({ sessionId: 'sess-2', id: 'file:sess-2:/work/demo.html' })
- expect($visiblePreviewTabs.get()).toHaveLength(1)
+ $selectedStoredSessionId.set('sess-a')
+ expect(paths($visiblePreviewTabs.get())).toEqual(['https://a.example'])
})
- it('re-opening the same file in the same session keeps the tab owner and pin', () => {
- $selectedStoredSessionId.set('sess-1')
- openPreview(fileTarget('/work/demo.html'))
- setPreviewTabPinned($previewTabs.get()[0]!.id, true)
+ it('opens for an explicit owner without touching the focused drawer', () => {
+ $selectedStoredSessionId.set('sess-focused')
+ openPreview(fileTarget('/work/focused.html'))
+ const focusedId = $rightRailActiveTabId.get()
- openPreview({ ...fileTarget('/work/demo.html'), label: 'refreshed' })
+ openPreview(fileTarget('/work/tile.html'), 'sess-tile')
- expect($previewTabs.get()).toHaveLength(1)
- expect($previewTabs.get()[0]).toMatchObject({ sessionId: 'sess-1', pinned: true })
- expect($previewTabs.get()[0]?.target.label).toBe('refreshed')
+ expect($previewTabs.get().find(tab => tab.target.path === '/work/tile.html')?.sessionId).toBe('sess-tile')
+ expect(paths($visiblePreviewTabs.get())).toEqual(['/work/focused.html'])
+ expect($rightRailActiveTabId.get()).toBe(focusedId)
})
- it('unpinning an ownerless tab adopts the current session', () => {
- openPreview(fileTarget('/work/legacy.html'))
+ it('agent close without a url closes only that session own tabs', () => {
+ $selectedStoredSessionId.set('sess-a')
+ openPreview(fileTarget('/work/pinned.html'))
setPreviewTabPinned($previewTabs.get()[0]!.id, true)
+ openPreview(fileTarget('/work/a.html'))
+ $selectedStoredSessionId.set('sess-b')
+ openPreview(fileTarget('/work/b.html'))
- $selectedStoredSessionId.set('sess-1')
- setPreviewTabPinned($previewTabs.get()[0]!.id, false)
+ closeAgentPreview('sess-a', [])
- expect($previewTabs.get()[0]).toMatchObject({ pinned: false, sessionId: 'sess-1' })
- expect($previewTabs.get()[0]?.id).toBe('file:sess-1:/work/legacy.html')
+ expect(paths($previewTabs.get()).sort()).toEqual(['/work/b.html', '/work/pinned.html'])
})
- it('closes by source only within the current session', () => {
- $selectedStoredSessionId.set('sess-1')
- openPreview(fileTarget('/work/a.html'))
- $selectedStoredSessionId.set('sess-2')
- openPreview(fileTarget('/work/a.html'))
+ it('agent close by url reaches only the tabs that session can see', () => {
+ $selectedStoredSessionId.set('sess-a')
+ openPreview(fileTarget('/work/same.html'))
+ $selectedStoredSessionId.set('sess-b')
+ openPreview(fileTarget('/work/same.html'))
- // The hidden session's tab must not be closed by the other session's row.
- expect(closePreviewForSource('/work/a.html')).toBe(true)
- expect($previewTabs.get()).toHaveLength(1)
- expect($previewTabs.get()[0]?.sessionId).toBe('sess-1')
- })
+ closeAgentPreview('sess-a', ['/work/same.html'])
- it('reopens a pinned legacy row instead of stacking a second tab', () => {
- // A migrated legacy row: pinned, unprefixed id, no owner.
- $previewTabs.set([{ id: 'file:/work/a.html', target: fileTarget('/work/a.html'), pinned: true }])
+ expect($previewTabs.get().map(tab => tab.sessionId)).toEqual(['sess-b'])
+ })
- $selectedStoredSessionId.set('sess-1')
+ it('keeps a conversation tabs visible across a compression tip rotation', () => {
+ $selectedStoredSessionId.set('tip-1')
openPreview(fileTarget('/work/a.html'))
+ newBrowserTab()
- expect($previewTabs.get()).toHaveLength(1)
- expect($previewTabs.get()[0]).toMatchObject({ pinned: true, sessionId: 'sess-1' })
- expect($previewTabs.get()[0]?.id).toBe('file:sess-1:/work/a.html')
- expect($visiblePreviewTabs.get()).toHaveLength(1)
+ rekeyPreviewTabsSession('tip-1', 'tip-2')
+
+ // Focus still names the old tip until the route follows; the tabs must
+ // not blink out in between (a hidden Browser loses its page).
+ expect($visiblePreviewTabs.get()).toHaveLength(2)
+
+ $selectedStoredSessionId.set('tip-2')
+ expect($visiblePreviewTabs.get()).toHaveLength(2)
+ expect($previewTabs.get().map(tab => tab.sessionId)).toEqual(['tip-2', 'tip-2'])
})
- it('reusing an owned pinned row from another session keeps the owner id', () => {
+ it('tombstones a missing file by the url the file pane reports', () => {
$selectedStoredSessionId.set('sess-1')
- openPreview(fileTarget('/work/a.html'))
- setPreviewTabPinned($previewTabs.get()[0]!.id, true)
+ openPreview(fileTarget('/work/gone.html'))
- $selectedStoredSessionId.set('sess-2')
- openPreview({ ...fileTarget('/work/a.html'), label: 'refreshed' })
+ markPreviewTabMissing(fileTarget('/work/gone.html').url)
- expect($previewTabs.get()).toHaveLength(1)
- // The row keeps its OWNER's id — never an id/sessionId split (the id
- // would say sess-2 while the owner says sess-1 until the next unpin).
- expect($previewTabs.get()[0]).toMatchObject({
- id: 'file:sess-1:/work/a.html',
- sessionId: 'sess-1',
- pinned: true
- })
- expect($previewTabs.get()[0]?.target.label).toBe('refreshed')
- expect($rightRailActiveTabId.get()).toBe('file:sess-1:/work/a.html')
+ expect($previewTabs.get()[0]?.target.missing).toBe(true)
+ })
+
+ // A relaunch (or a fresh pop-out renderer) reads storage at module load.
+ async function relaunchedPreviewStore() {
+ vi.resetModules()
+
+ return import('./preview')
+ }
+
+ it('restores every Browser tab of every session and every pin on relaunch', async () => {
+ $selectedStoredSessionId.set('sess-a')
+ openPreview(urlTarget('https://a.example'))
+ newBrowserTab()
+ openPreview(urlTarget('https://a2.example'))
+ $selectedStoredSessionId.set('sess-b')
+ openPreview(urlTarget('https://b.example'))
+ setPreviewTabPinned($previewTabs.get()[2]!.id, true)
+ openPreview(fileTarget('/work/b.html'))
+
+ const live = $previewTabs.get().map(tab => [tab.id, tab.sessionId, Boolean(tab.pinned)])
+ const relaunched = await relaunchedPreviewStore()
+
+ expect(relaunched.$previewTabs.get().map(tab => [tab.id, tab.sessionId, Boolean(tab.pinned)])).toEqual(live)
+ })
+
+ it('pops out a Browser tab that is not the last one persisted', async () => {
+ $selectedStoredSessionId.set('sess-a')
+ openPreview(urlTarget('https://first.example'))
+ const first = $previewTabs.get()[0]!.id
+ newBrowserTab()
+ openPreview(urlTarget('https://second.example'))
+
+ // A fresh pop-out renderer: no session focus, its view on the default
+ // bucket, the tab in another profile's bucket — found by id in storage.
+ window.localStorage.setItem('hermes.desktop.previewTabs.v2', JSON.stringify({ work: $previewTabs.get() }))
+ const fresh = await relaunchedPreviewStore()
+
+ expect(fresh.$previewTabs.get()).toHaveLength(0)
+ fresh.adoptPersistedBrowserTab(first)
+
+ expect(fresh.$previewTabs.get().find(tab => tab.id === first)?.target.url).toBe('https://first.example')
})
it('follows the focused session tile over the sidebar selection', () => {
@@ -555,117 +627,35 @@ describe('preview session scoping', () => {
$selectedStoredSessionId.set('sess-2')
openPreview(fileTarget('/work/b.html'))
- expect($visiblePreviewTabs.get().map(tab => tab.target.path)).toEqual(['/work/b.html'])
-
- // A sess-1 session TILE is active in the interacted zone while sess-2 is
- // selected in the sidebar: the drawer belongs to the conversation being
- // typed in, so the visible set follows the FOCUSED session.
const previousTree = $layoutTree.get()
try {
$layoutTree.set(group(['session-tile:sess-1'], { active: 'session-tile:sess-1', id: 'grp-main' }))
noteActiveTreeGroup('grp-main')
- expect($visiblePreviewTabs.get().map(tab => tab.target.path)).toEqual(['/work/a.html'])
+ expect(paths($visiblePreviewTabs.get())).toEqual(['/work/a.html'])
- // Leaving the tile (workspace/route active) falls back to the selection.
noteActiveTreeGroup(null)
- expect($visiblePreviewTabs.get().map(tab => tab.target.path)).toEqual(['/work/b.html'])
+ expect(paths($visiblePreviewTabs.get())).toEqual(['/work/b.html'])
} finally {
- // A failed assertion must not leak the tree/group state into the next
- // test — the focused derivation reads both.
noteActiveTreeGroup(null)
$layoutTree.set(previousTree)
}
})
- it('re-owns the singleton Browser to the session that navigates it', () => {
- $selectedStoredSessionId.set('sess-1')
- openPreview(urlTarget('http://localhost:5174'))
-
- // A second session navigating the Browser takes the surface with it:
- // keeping the original owner would leave the new URL invisible in the
- // session that just opened it.
- $selectedStoredSessionId.set('sess-2')
- openPreview(urlTarget('http://localhost:9999'))
-
- expect($previewTabs.get()).toHaveLength(1)
- // The Browser id is minted (never reused), so assert the stable parts:
- // one surface, re-owned to the navigating session.
- expect($previewTabs.get()[0]?.id).toMatch(/^url:browser-/)
- expect($previewTabs.get()[0]).toMatchObject({ sessionId: 'sess-2' })
- expect($previewTabs.get()[0]?.target.url).toBe('http://localhost:9999')
- expect($visiblePreviewTabs.get()).toHaveLength(1)
-
- // And sess-1 no longer sees the navigated surface — no context leak.
- $selectedStoredSessionId.set('sess-1')
- expect($visiblePreviewTabs.get()).toHaveLength(0)
- })
-
- it('adoption dedupes against an already session-scoped row', () => {
- // Both rows for the same file coexist before the session appears.
- $previewTabs.set([
- { id: 'file:/work/a.html', target: fileTarget('/work/a.html') },
- { id: 'file:sess-1:/work/a.html', target: fileTarget('/work/a.html'), sessionId: 'sess-1' }
- ])
-
- $selectedStoredSessionId.set('sess-1')
-
- expect($previewTabs.get()).toHaveLength(1)
- expect($previewTabs.get()[0]?.id).toBe('file:sess-1:/work/a.html')
- })
-
- it('adoption dedupe keeps the active selection valid', () => {
- // The colliding row is the ACTIVE tab when adoption rekeys the draft
- // onto the same id — the survivor carries that id, so the selection must
- // not dangle.
- $previewTabs.set([
- { id: 'file:/work/a.html', target: fileTarget('/work/a.html') },
- { id: 'file:sess-1:/work/a.html', target: fileTarget('/work/a.html'), sessionId: 'sess-1' }
- ])
- selectRightRailTab('file:sess-1:/work/a.html')
-
- $selectedStoredSessionId.set('sess-1')
-
- expect($previewTabs.get()).toHaveLength(1)
- expect($rightRailActiveTabId.get()).toBe('file:sess-1:/work/a.html')
- })
-
- it('migrates legacy unscoped tabs to pinned and rekeys their ids', () => {
+ it('migrates legacy unscoped tabs to pinned and keeps their ids', () => {
const raw = JSON.stringify([
{ id: 'file:file:///work/a.html', target: fileTarget('/work/a.html') },
- { id: 'file:file:///work/b.html', target: fileTarget('/work/b.html'), sessionId: 'sess-9' }
+ { id: 'file:file:///work/b.html', target: fileTarget('/work/b.html'), sessionId: 'sess-9' },
+ { id: 'file:file:///work/c.html', target: fileTarget('/work/c.html'), sessionId: 'sess-1', pinned: false }
])
const decoded = decodePreviewTabs(raw)
- expect(decoded).toHaveLength(2)
- expect(decoded[0]).toMatchObject({ id: 'file:/work/a.html', pinned: true })
- expect(decoded[1]?.id).toBe('file:sess-9:/work/b.html')
- expect(decoded[1]?.sessionId).toBe('sess-9')
- expect(decoded[1]?.pinned).toBeUndefined()
- })
-
- it('does not re-pin a persisted unpinned row', () => {
- const raw = JSON.stringify([
- { id: 'file:/work/a.html', target: fileTarget('/work/a.html'), sessionId: 'sess-1', pinned: false }
- ])
-
- const decoded = decodePreviewTabs(raw)
-
- expect(decoded[0]?.pinned).toBe(false)
- })
-
- it('dedupes the same file persisted under both old and canonical ids', () => {
- const raw = JSON.stringify([
- { id: 'file:file:///work/a.html', target: fileTarget('/work/a.html') },
- { id: 'file:/work/a.html', target: { ...fileTarget('/work/a.html'), label: 'updated' } }
+ expect(decoded.map(tab => [tab.id, tab.sessionId, tab.pinned])).toEqual([
+ ['file:file:///work/a.html', undefined, true],
+ ['file:file:///work/b.html', 'sess-9', undefined],
+ ['file:file:///work/c.html', 'sess-1', false]
])
-
- const decoded = decodePreviewTabs(raw)
-
- expect(decoded).toHaveLength(1)
- expect(decoded[0]?.id).toBe('file:/work/a.html')
- expect(decoded[0]?.target.label).toBe('updated')
})
})
diff --git a/apps/desktop/src/store/preview.ts b/apps/desktop/src/store/preview.ts
index e3c55b28091..7114f2bb459 100644
--- a/apps/desktop/src/store/preview.ts
+++ b/apps/desktop/src/store/preview.ts
@@ -25,8 +25,9 @@ import { canOpenBrowserWindow, openBrowserInNewWindow } from './windows'
* a tool result, a file-browser click, and an artifact card all travel the
* same road and behave identically once open.
*
- * Tabs are global and outlive the session that created them, like tabs
- * anywhere else — they close when you close them.
+ * Every tab belongs to the session that opened it (#73890): the drawer shows
+ * the focused session's tabs plus the pinned ones, and a hidden session's
+ * tabs stay alive until it comes back. Tabs close when you close them.
*/
/** How an HTML file target shows: the live page, or its source. */
@@ -74,11 +75,14 @@ export interface PreviewServerRestart {
export interface PreviewTab {
id: RightRailTabId
target: PreviewTarget
- /** The session that opened the tab. Absent only on legacy rows written
- * before session scoping (decodePreviewTabs migrates those to pinned). */
+ /** Stored id of the session that owns the tab. Absent on a tab opened in a
+ * fresh draft (adopted when the draft becomes a session) and on legacy rows
+ * written before session scoping (decodePreviewTabs migrates those to
+ * pinned). */
sessionId?: string
/** Pinned tabs render in EVERY session — the explicit cross-session
- * workspace. Everything else is visible only in the session that opened it. */
+ * workspace. Everything else is visible only in the session that owns it.
+ * Always written by this build, so a missing flag marks a legacy row. */
pinned?: boolean
}
@@ -154,34 +158,11 @@ function parseTabList(parsed: unknown): PreviewTab[] {
// Legacy rows (written before session scoping) have no owner and no way to
// recover one — keep them as workspace-pinned rather than dropping them or
- // dumping every stale tab into one chat. Explicit `!== undefined` checks:
- // a persisted `pinned: false` must not be re-pinned.
- const owned = pdfUpgraded.map(tab =>
+ // dumping every stale tab into one chat. Ids are kept verbatim: a Browser's
+ // minted id is how the pop-out window finds its tab (#119850).
+ return pdfUpgraded.map(tab =>
tab.sessionId !== undefined || tab.pinned !== undefined ? tab : { ...tab, pinned: true }
)
-
- // File tab identities are session-scoped: a row written before the scope
- // existed (or by an id-collapsing legacy build) rekeys onto the canonical
- // `file:<session>:<path>` form, deduping the same file persisted under both
- // old and new ids. Browser (URL) rows keep their MINTED id verbatim: ids are
- // never rekeyed (#119850), because the pop-out window hand-off looks tabs up
- // by the persisted id, and reusing a navigated Browser depends on the id
- // surviving restore. Keep only the LAST row per id — the most recently
- // opened wins.
- const lastUrl = owned.findLast(tab => tab.target.kind === 'url')
- const deduped = new Map<string, PreviewTab>()
-
- for (const tab of owned) {
- if (tab.target.kind === 'url' && tab !== lastUrl) {
- continue
- }
-
- const id = tab.target.kind === 'file' ? previewTabId(tab.target, tab.sessionId) : tab.id
-
- deduped.set(id, tab.target.kind === 'file' ? { ...tab, id } : tab)
- }
-
- return [...deduped.values()]
}
/** The tabs a profile's rail is showing, keyed by profile. */
@@ -376,61 +357,135 @@ if (typeof window !== 'undefined') {
}
}
-/** Tabs the ACTIVE session sees: its own tabs plus everything pinned. The
- * layout-tree mirror renders only these, so a session switch swaps the drawer
- * and pinned tabs are the explicit cross-session workspace. While no session
- * exists (a fresh draft), ownerless tabs stay visible. */
+// Auto-compression rotates a conversation's stored id (tip → next tip). The
+// tabs are rekeyed onto the new tip, and the old id stays an alias so the
+// window between the rotation and the focus following it cannot hide them —
+// a hidden Browser's pane leaves the tree and would lose its page.
+const $rotatedSessionIds = atom<ReadonlyMap<string, string>>(new Map())
+
+function latestSessionId(sessionId: null | string | undefined, rotated: ReadonlyMap<string, string>): null | string {
+ let id = sessionId ?? null
+
+ // Tips are fresh ids, so the chain only ever moves forward.
+ while (id && rotated.has(id)) {
+ id = rotated.get(id)!
+ }
+
+ return id
+}
+
+/** True when `sessionId`'s drawer shows `tab`: its own tabs plus every pin.
+ * With no session (a fresh draft) the ownerless tabs are its own. */
+function tabVisibleTo(tab: PreviewTab, sessionId: null | string, rotated: ReadonlyMap<string, string>): boolean {
+ return Boolean(tab.pinned) || latestSessionId(tab.sessionId, rotated) === latestSessionId(sessionId, rotated)
+}
+
+function tabsVisibleTo(tabs: readonly PreviewTab[], sessionId: null | string): PreviewTab[] {
+ const rotated = $rotatedSessionIds.get()
+
+ return tabs.filter(tab => tabVisibleTo(tab, sessionId, rotated))
+}
+
+/** Tabs the FOCUSED session sees. The layout-tree mirror renders only these,
+ * so a session switch swaps the drawer; hidden tabs stay in `$previewTabs`. */
export const $visiblePreviewTabs = computed(
- [$previewTabs, $focusedStoredSessionId],
- (tabs, sessionId) =>
- tabs.filter(
- tab => tab.pinned || tab.sessionId === sessionId || (sessionId == null && tab.sessionId == null)
- )
+ [$previewTabs, $focusedStoredSessionId, $rotatedSessionIds],
+ (tabs, sessionId, rotated) => tabs.filter(tab => tabVisibleTo(tab, sessionId, rotated))
)
-// A fresh draft has no session yet, so tabs opened there are ownerless — adopt
-// them into the session the moment one exists (rekeying file ids onto the
-// session-scoped form, so a later open of the same file dedupes), or the
-// drawer would silently lose them at first send.
-$focusedStoredSessionId.listen(sessionId => {
- if (sessionId == null) {
+// The tab each session last had in front, so switching back to a session
+// fronts what it was showing instead of its first tab. Memory-only.
+const activeTabBySession = new Map<string, RightRailTabId>()
+
+function rememberActiveTab(sessionId: null | string, tabId: RightRailTabId | null): void {
+ const key = latestSessionId(sessionId, $rotatedSessionIds.get())
+
+ if (key && tabId) {
+ activeTabBySession.set(key, tabId)
+ }
+}
+
+/** Rekey a rotated conversation's tabs onto its new stored id. Every profile
+ * bucket, not just the view: a background tile's conversation rotates too. */
+export function rekeyPreviewTabsSession(previousId: string, nextId: string): void {
+ if (!previousId || !nextId || previousId === nextId) {
return
}
- const tabs = $previewTabs.get()
+ $rotatedSessionIds.set(new Map([...$rotatedSessionIds.get(), [previousId, nextId]]))
- if (tabs.some(tab => tab.sessionId == null && !tab.pinned)) {
- const activeId = $rightRailActiveTabId.get()
- let newActiveId = activeId
+ const rekey = (tabs: PreviewTab[]) =>
+ tabs.some(tab => tab.sessionId === previousId)
+ ? tabs.map(tab => (tab.sessionId === previousId ? { ...tab, sessionId: nextId } : tab))
+ : null
- const updated = tabs.map(tab => {
- if (tab.sessionId != null || tab.pinned) {
- return tab
- }
+ let backgroundChanged = false
- const nextId = tab.target.kind === 'file' ? previewTabId(tab.target, sessionId) : tab.id
+ for (const [key, tabs] of Object.entries(tabsByProfile)) {
+ const next = key === viewKey ? null : rekey(tabs)
- if (tab.id === activeId) {
- newActiveId = nextId
- }
+ if (next) {
+ tabsByProfile[key] = next
+ backgroundChanged = true
+ }
+ }
- return { ...tab, id: nextId, sessionId }
- })
+ if (backgroundChanged) {
+ persistTabs()
+ }
- // A rekey can collide with an already session-scoped row of the same file
- // (defensive: adoption runs synchronously with the focus change, so a real
- // open can't interleave — but keep the no-duplicate invariant explicit).
- const deduped = new Map<string, PreviewTab>()
+ const view = rekey($previewTabs.get())
- for (const tab of updated) {
- deduped.set(tab.id, tab)
- }
+ if (view) {
+ $previewTabs.set(view)
+ }
- $previewTabs.set([...deduped.values()])
+ const remembered = activeTabBySession.get(previousId)
- if (newActiveId !== activeId) {
- selectRightRailTab(newActiveId)
- }
+ if (remembered) {
+ activeTabBySession.set(nextId, remembered)
+ }
+}
+
+$rightRailActiveTabId.listen(tabId => {
+ const sessionId = $focusedStoredSessionId.get()
+
+ if (tabId && $visiblePreviewTabs.get().some(tab => tab.id === tabId)) {
+ rememberActiveTab(sessionId, tabId)
+ }
+})
+
+/** The tab the focused session's drawer should front: the current selection
+ * when it is visible, else the one this session last had in front, else its
+ * first tab. */
+export function preferredVisibleTabId(): RightRailTabId | null {
+ const visible = $visiblePreviewTabs.get()
+ const isVisible = (id: null | RightRailTabId | undefined) => Boolean(id && visible.some(tab => tab.id === id))
+ const active = $rightRailActiveTabId.get()
+
+ if (isVisible(active)) {
+ return active
+ }
+
+ const key = latestSessionId($focusedStoredSessionId.get(), $rotatedSessionIds.get())
+ const remembered = key ? activeTabBySession.get(key) : undefined
+
+ return isVisible(remembered) ? remembered! : (visible[0]?.id ?? null)
+}
+
+// A fresh draft has no session yet, so tabs opened there are ownerless — adopt
+// them into the session the moment one exists, or the drawer would silently
+// lose them at first send. Every other open is stamped with its owner, so
+// only a draft's tabs can be ownerless here.
+$focusedStoredSessionId.listen(sessionId => {
+ if (sessionId == null) {
+ return
+ }
+
+ const tabs = $previewTabs.get()
+
+ if (tabs.some(tab => tab.sessionId == null && !tab.pinned)) {
+ $previewTabs.set(tabs.map(tab => (tab.sessionId == null && !tab.pinned ? { ...tab, sessionId } : tab)))
}
})
@@ -441,13 +496,11 @@ function resolveActiveTab(tabs: PreviewTab[], activeTabId: RightRailTabId | null
return tabs.find(tab => tab.id === activeTabId) ?? tabs[0] ?? null
}
-function activePreviewTab(): PreviewTab | null {
- return resolveActiveTab($visiblePreviewTabs.get(), $rightRailActiveTabId.get())
-}
-
// A restored active id whose tab didn't survive validation would leave the rail
-// pointing at nothing.
-selectRightRailTab(activePreviewTab()?.id ?? null)
+// pointing at nothing. Checked against every tab, not the visible ones: at
+// boot no session is focused yet, and re-homing onto the focused session's
+// tabs is the preview tiles' job once one is.
+selectRightRailTab(resolveActiveTab($previewTabs.get(), $rightRailActiveTabId.get())?.id ?? null)
/** The target the rail is currently showing, or null when it has no tabs. */
export const $previewTarget = computed(
@@ -641,11 +694,6 @@ export function markBrowserTabPopped(tabId: string, popped: boolean) {
$poppedBrowserTabIds.set(next)
}
-/** Preview tabs that still belong in the layout tree (not popped out). */
-export const $dockedPreviewTabs = computed([$previewTabs, $poppedBrowserTabIds], (tabs, popped) =>
- popped.size === 0 ? tabs : tabs.filter(tab => !popped.has(tab.id))
-)
-
/** The FOCUSED session's tabs that still belong in the docked layout tree —
* the layout-tree mirror renders only these (#73890): switching sessions
* swaps the drawer, and a popped-out Browser pane stays out. */
@@ -662,21 +710,42 @@ export const $previewServerRestartStatus = computed($previewServerRestart, resta
* already has. A URL has no identity here: a Browser tab is a vessel you
* navigate, so it is picked (`browserTabId`) rather than derived.
*
- * A FILE tab's identity additionally carries the session that opened it —
- * the same file opened in two conversations is two tabs, each owned by its
- * session (the session-scoped rail, #73890). Legacy rows (no session) keep
- * the unprefixed key. The `file://` scheme is stripped so the two entry
- * points (a `file://` URL vs a plain path) resolve to the same key. */
-function canonicalFileKey(target: PreviewTarget): string {
+ * A FILE tab is additionally owned by a session — the same file opened in
+ * two conversations is two tabs (#73890) — so a session-owned file tab's id
+ * carries the owner it was opened by. The id is identity only: lookups match
+ * a file by its canonical path and owner (`fileTabFor`), so an id never needs
+ * rekeying when the owner changes (draft adoption, compression rotation). */
+export function previewTabId(target: PreviewTarget, sessionId?: null | string): RightRailTabId {
+ if (target.kind === 'file' && sessionId) {
+ return `file:${sessionId}:${target.url}`
+ }
+
+ return `${target.kind}:${target.url}`
+}
+
+/** A file's identity independent of entry point: a `file://` URL and a plain
+ * path name the same file. */
+function canonicalFileKey(target: Pick<PreviewTarget, 'path' | 'url'>): string {
return (target.path || target.url).replace(/^file:\/\//, '')
}
-export function previewTabId(target: PreviewTarget, sessionId?: null | string): RightRailTabId {
- if (target.kind === 'file') {
- return `file:${sessionId ? `${sessionId}:` : ''}${canonicalFileKey(target)}`
+/** The tab already showing `target`'s file in `tabs` (a session's visible set). */
+function fileTabFor(tabs: readonly PreviewTab[], target: PreviewTarget): PreviewTab | undefined {
+ const key = canonicalFileKey(target)
+
+ return tabs.find(tab => tab.target.kind === 'file' && canonicalFileKey(tab.target) === key)
+}
+
+/** `base`, suffixed until no tab holds it: a file's owner-derived id can be
+ * taken by a same-path tab whose owner later changed. */
+function unusedTabId(base: RightRailTabId, tabs: readonly PreviewTab[]): RightRailTabId {
+ let id = base
+
+ for (let n = 2; tabs.some(tab => tab.id === id); n++) {
+ id = `${base}#${n}` as RightRailTabId
}
- return `${target.kind}:${target.url}`
+ return id
}
const isBrowserTab = (tab: PreviewTab): boolean => tab.target.kind === 'url'
@@ -695,15 +764,17 @@ function mintBrowserTabId(): RightRailTabId {
/** 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 {
+ * ask for (the strip's "+"), the way they are in a real browser. `tabs` is
+ * the opening session's visible set: another session's Browser is never
+ * taken over. */
+function browserTabFor(tabs: readonly PreviewTab[]): PreviewTab | undefined {
const active = tabs.find(tab => tab.id === $rightRailActiveTabId.get())
- if (active && isBrowserTab(active)) {
- return active.id
- }
+ return active && isBrowserTab(active) ? active : tabs.findLast(isBrowserTab)
+}
- return tabs.findLast(isBrowserTab)?.id ?? mintBrowserTabId()
+function browserTabId(tabs: readonly PreviewTab[]): RightRailTabId {
+ return browserTabFor(tabs)?.id ?? mintBrowserTabId()
}
/** HTML files open rendered unless the caller asks for a mode. A re-open keeps
@@ -741,77 +812,69 @@ export function setPreviewRenderMode(tabId: string, renderMode: PreviewRenderMod
* its target so a stale label/path can't outlive the thing it points at. The
* only way anything reaches a preview.
*
- * The tab belongs to the session that was active when it opened (a re-open
- * of an existing tab keeps the tab's owner and pin state — only the target
- * refreshes). A PINNED row for the same file carries the unprefixed
- * (legacy) id, so a session-scoped open would otherwise stack a second tab
- * for the same file: reuse the pinned row instead — refreshed, still
- * pinned, fronted. Never steal another session's owned tab: that
- * coexistence is the point. */
-export function openPreview(target: PreviewTarget) {
+ * The tab belongs to `owner` — the stored id of the session that asked for
+ * it, the focused one unless the caller knows better (an agent turn in a
+ * side tile). Reuse is decided among the tabs `owner` can see (its own plus
+ * the pinned ones), so one session's open never takes over another
+ * session's tab; a reused tab keeps its owner and pin. Opening for a session
+ * that is not focused does not touch the focused drawer's selection — the
+ * tab is fronted when that session's drawer shows. */
+export function openPreview(target: PreviewTarget, owner: null | string = $focusedStoredSessionId.get()) {
const current = $previewTabs.get()
- const sessionId = $focusedStoredSessionId.get() ?? undefined
- const id = target.kind === 'url' ? browserTabId(current) : previewTabId(target, sessionId)
- const index = current.findIndex(tab => tab.id === id)
+ const visible = tabsVisibleTo(current, owner)
const existing =
- index === -1 && target.kind === 'file'
- ? current.find(
- tab => tab.pinned && tab.target.kind === 'file' && canonicalFileKey(tab.target) === canonicalFileKey(target)
- )
- : current[index]
-
- // Reuse semantics depend on WHY the row was found:
- // - Same-session re-open (any kind): keep the owner and pin state — only
- // the target refreshes.
- // - A PINNED file row reached from ANOTHER session: keep its owner (and
- // therefore its owner-keyed id) — the pin is the explicit cross-session
- // workspace contract, and rekeying to the opening session would leave
- // `id` and `sessionId` disagreeing until the next unpin (which returns
- // the tab to that owner anyway).
- // - The singleton Browser or an artifact reached from another session: the
- // surface NAVIGATES, so it re-owns to the opening session — otherwise the
- // new URL would stay invisible in the session that just opened it.
- // - Ownerless legacy rows: adopted — rekeyed and stamped — into the opening
- // session (see the pinned-legacy test).
- // The id is derived from the FINAL session id so the two can never split.
- const tabSessionId =
- existing?.sessionId == null || existing.pinned || existing.sessionId === sessionId
- ? existing?.sessionId ?? sessionId
- : sessionId
+ target.kind === 'url'
+ ? browserTabFor(visible)
+ : target.kind === 'file'
+ ? fileTabFor(visible, target)
+ : current.find(tab => tab.id === previewTabId(target))
+
+ const id =
+ existing?.id ?? (target.kind === 'url' ? mintBrowserTabId() : unusedTabId(previewTabId(target, owner), current))
const tab: PreviewTab = {
- id: target.kind === 'url' ? id : previewTabId(target, tabSessionId),
- target: withRenderMode(target, existing?.target),
- sessionId: tabSessionId,
- pinned: existing?.pinned
+ id,
+ pinned: Boolean(existing?.pinned),
+ // An artifact is one tab per artifact; opening it from another session
+ // re-owns it, or the session that just asked for it would not see it.
+ sessionId: (existing?.pinned ? existing.sessionId : owner) ?? undefined,
+ target: withRenderMode(target, existing?.target)
}
- const replaceIndex = existing ? current.indexOf(existing) : -1
+ $previewTabs.set(existing ? current.map(item => (item === existing ? tab : item)) : [...current, tab])
+
+ if (!tabVisibleTo(tab, $focusedStoredSessionId.get(), $rotatedSessionIds.get())) {
+ rememberActiveTab(owner, id)
- $previewTabs.set(replaceIndex === -1 ? [...current, tab] : current.map((item, i) => (i === replaceIndex ? tab : item)))
- noteExplicitPreviewOpen(tab.id)
- // Select the row's FINAL id: when a pinned row is reused from another
- // session, the id keeps the owner's session, so the pre-computed id would
- // point at nothing.
- selectRightRailTab(tab.id)
+ return
+ }
+
+ noteExplicitPreviewOpen(id)
+ selectRightRailTab(id)
}
const blankPage = (): PreviewTarget => ({ kind: 'url', label: 'Browser', source: 'about:blank', url: 'about:blank' })
-/** Tombstone the tab for a confirmed-missing file: keep it open this session
- * (the pane shows "file no longer exists"), but flag the target so the next
- * restore drops it instead of re-probing the dead path on every boot. */
-export function markPreviewTabMissing(targetUrl: string) {
+/** Tombstone the tabs for a confirmed-missing file: keep them open this
+ * session (the pane shows "file no longer exists"), but flag the target so
+ * the next restore drops them instead of re-probing the dead path on every
+ * boot. Takes a tab id or the file's url/path; a file that is gone is gone
+ * for every session showing it. */
+export function markPreviewTabMissing(tabIdOrUrl: string) {
const current = $previewTabs.get()
- const id = targetUrl.startsWith('file:') ? targetUrl : `file:${targetUrl}`
- const index = current.findIndex(tab => tab.id === id)
+ const key = canonicalFileKey({ url: tabIdOrUrl.replace(/^file:(?!\/\/)/, '') })
+
+ const hit = (tab: PreviewTab) =>
+ tab.target.kind === 'file' &&
+ !tab.target.missing &&
+ (tab.id === tabIdOrUrl || tab.target.url === tabIdOrUrl || canonicalFileKey(tab.target) === key)
- if (index === -1 || current[index]!.target.missing) {
+ if (!current.some(hit)) {
return
}
- $previewTabs.set(current.map((tab, i) => (i === index ? { ...tab, target: { ...tab.target, missing: true } } : tab)))
+ $previewTabs.set(current.map(tab => (hit(tab) ? { ...tab, target: { ...tab.target, missing: true } } : tab)))
}
/** Show the Browser — the surface, not a page. Keeps whatever it was last
@@ -819,7 +882,7 @@ export function markPreviewTabMissing(targetUrl: string) {
* browser open it lands on `about:blank`, where the pane's empty state
* invites an address. */
export function openBrowserTab() {
- const tabs = $previewTabs.get()
+ const tabs = $visiblePreviewTabs.get()
const current = tabs.find(tab => tab.id === browserTabId(tabs))
recordFeatureUse('browser_pane')
@@ -833,7 +896,7 @@ export function openBrowserTab() {
* preview-tile pane the layout tree keeps is actually visible, i.e. not
* dismissed/hidden/minimized AND holding its zone's active slot. */
export function toggleBrowserTab() {
- const id = browserTabId($previewTabs.get())
+ const id = browserTabId($visiblePreviewTabs.get())
if (isPaneVisible(`${PREVIEW_TILE_PREFIX}:${id}`)) {
dismissTreePane(`${PREVIEW_TILE_PREFIX}:${id}`)
@@ -849,40 +912,27 @@ export function newBrowserTab() {
const id = mintBrowserTabId()
recordFeatureUse('browser_pane')
- $previewTabs.set([...$previewTabs.get(), { id, target: blankPage() }])
+ $previewTabs.set([
+ ...$previewTabs.get(),
+ { id, pinned: false, sessionId: $focusedStoredSessionId.get() ?? undefined, target: blankPage() }
+ ])
noteExplicitPreviewOpen(id)
selectRightRailTab(id)
}
/** Pin or unpin a preview tab. Pinned tabs render in EVERY session — the
* explicit cross-session workspace; unpinning returns it to its session
- * (adopting the current one, and rekeying the file id, when the tab never
- * had an owner). */
+ * (adopting the current one when the tab never had an owner). */
export function setPreviewTabPinned(tabId: string, pinned: boolean): void {
const currentSession = $focusedStoredSessionId.get() ?? undefined
- const activeId = $rightRailActiveTabId.get()
- let newActiveId = activeId
$previewTabs.set(
- $previewTabs.get().map(tab => {
- if (tab.id !== tabId) {
- return tab
- }
-
- const nextSession = tab.sessionId ?? (!pinned ? currentSession : undefined)
- const nextId = tab.target.kind === 'file' ? previewTabId(tab.target, nextSession) : tab.id
-
- if (tab.id === activeId) {
- newActiveId = nextId
- }
-
- return { ...tab, id: nextId, pinned, sessionId: nextSession }
- })
+ $previewTabs
+ .get()
+ .map(tab =>
+ tab.id === tabId ? { ...tab, pinned, sessionId: tab.sessionId ?? (pinned ? undefined : currentSession) } : tab
+ )
)
-
- if (newActiveId !== activeId) {
- selectRightRailTab(newActiveId)
- }
}
/** Drop the tabs a deleted session opened. Pinned tabs survive — they belong
@@ -893,19 +943,23 @@ export function prunePreviewTabsForSession(sessionId: string): void {
export function closeRightRailTab(tabId: string) {
const current = $previewTabs.get()
- const index = current.findIndex(tab => tab.id === tabId)
- if (index === -1) {
+ if (!current.some(tab => tab.id === tabId)) {
return
}
const next = current.filter(tab => tab.id !== tabId)
+ // The neighbour comes from the focused drawer: a hidden session's tab
+ // must not become the selection.
+ const visible = $visiblePreviewTabs.get()
+ const visibleIndex = visible.findIndex(tab => tab.id === tabId)
+ const remaining = visible.filter(tab => tab.id !== tabId)
forgetBrowserPage(tabId)
$previewTabs.set(next)
if ($rightRailActiveTabId.get() === tabId) {
- const nextId = next[Math.min(index, next.length - 1)]?.id ?? null
+ const nextId = remaining[Math.min(Math.max(visibleIndex, 0), remaining.length - 1)]?.id ?? null
if (nextId) {
noteExplicitPreviewOpen(nextId)
@@ -924,21 +978,17 @@ export function closeRightRailTab(tabId: string) {
/** Close the tab showing `source` in the CURRENT session, if one is open.
* Returns whether it closed. */
export function closePreviewForSource(source: string): boolean {
- const tab = $visiblePreviewTabs.get().find(item => item.target.source === source)
-
- if (!tab) {
- return false
- }
-
- closeRightRailTab(tab.id)
-
- return true
+ return closePreviewMatching(source)
}
/** Close the first docked Browser tab whose current page URL matches.
* Browsers keep navigation state outside their persisted target so matching
* only target.url misses redirects and in-page navigation. */
export function closeBrowserPreviewMatchingLiveUrl(...candidates: string[]): boolean {
+ return closeBrowserMatchingLiveUrlIn($visiblePreviewTabs.get(), candidates)
+}
+
+function closeBrowserMatchingLiveUrlIn(tabs: readonly PreviewTab[], candidates: string[]): boolean {
const queries = new Set(
candidates
.map(value => {
@@ -959,7 +1009,6 @@ export function closeBrowserPreviewMatchingLiveUrl(...candidates: string[]): boo
const pages = $browserPages.get()
const popped = $poppedBrowserTabIds.get()
- const tabs = $previewTabs.get()
const activeId = $rightRailActiveTabId.get()
const ordered = [...tabs.filter(tab => tab.id === activeId), ...tabs.filter(tab => tab.id !== activeId)]
@@ -1022,12 +1071,36 @@ export function closePreviewMatching(...candidates: string[]): boolean {
/** Agent-driven close is scoped to the docked rail; an independent Browser
* window owns popped tabs and must not lose its backing state here. */
export function closeDockedPreviewMatching(...candidates: string[]): boolean {
+ return closePreviewMatchingTabs(dockedTabs($visiblePreviewTabs.get()), candidates)
+}
+
+function dockedTabs(tabs: readonly PreviewTab[]): PreviewTab[] {
const popped = $poppedBrowserTabIds.get()
- return closePreviewMatchingTabs(
- $visiblePreviewTabs.get().filter(tab => !popped.has(tab.id)),
- candidates
- )
+ return tabs.filter(tab => !popped.has(tab.id))
+}
+
+/** An agent's `close_preview` for the session that ran it (`owner`, a stored
+ * id). With candidates it closes the first matching tab that session can
+ * see (live Browser page first, then source/url/label); without, it closes
+ * every tab that session owns. Never another session's tabs, never a pin
+ * the agent did not name. */
+export function closeAgentPreview(owner: null | string, candidates: string[]): void {
+ const visible = tabsVisibleTo($previewTabs.get(), owner)
+
+ if (candidates.length > 0) {
+ if (!closeBrowserMatchingLiveUrlIn(visible, candidates)) {
+ closePreviewMatchingTabs(dockedTabs(visible), candidates)
+ }
+
+ return
+ }
+
+ for (const tab of visible) {
+ if (!tab.pinned) {
+ closeRightRailTab(tab.id)
+ }
+ }
}
/** Artifact tabs can't outlive the registry they read from, so clearing it
diff --git a/apps/desktop/src/store/session-states.ts b/apps/desktop/src/store/session-states.ts
index b76dac383b6..bdc8f292140 100644
--- a/apps/desktop/src/store/session-states.ts
+++ b/apps/desktop/src/store/session-states.ts
@@ -44,7 +44,12 @@ import { dropStatusDrawersForProfile, migrateStatusDrawersForProfile } from './c
import { registryConnectionKind } from './connection-registry-state'
import { recordDislike } from './desktop-metrics'
import { dialedGatewayModeFor } from './gateway'
-import { dropPreviewTabsForProfile, migratePreviewTabsForProfile, setPreviewScope } from './preview'
+import {
+ dropPreviewTabsForProfile,
+ migratePreviewTabsForProfile,
+ rekeyPreviewTabsSession,
+ setPreviewScope
+} from './preview'
import { dropPreviewArtifactsForProfile, migratePreviewArtifactsForProfile } from './preview-status'
import { $activeGatewayProfile, normalizeProfileKey } from './profile'
import { clearAllProviderWaits, clearSessionProviderWait } from './provider-wait'
@@ -816,6 +821,8 @@ function handleTransition(previous: ClientSessionState | null, next: ClientSessi
// a background tile's conversation rotates too, and its pane would
// otherwise keep the stale id forever (duplicate/differently-titled tabs).
rekeySessionTile(previous.storedSessionId, next.storedSessionId, runtimeId)
+ // The conversation's preview tabs follow it onto the new tip (#73890).
+ rekeyPreviewTabsSession(previous.storedSessionId, next.storedSessionId)
clearSettled(previous.storedSessionId)
setSessionStalled(previous.storedSessionId, false)