The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): keep a hidden session's live Browser mounted across session switches
teknium130b27de069bf
diff --git a/apps/desktop/src/app/chat/pane-mirror.ts b/apps/desktop/src/app/chat/pane-mirror.tsindex 4b95b367ed1..6b7507bc4a9 100644--- a/apps/desktop/src/app/chat/pane-mirror.ts+++ b/apps/desktop/src/app/chat/pane-mirror.ts@@ -9,11 +9,23 @@import type { ReadableAtom } from 'nanostores'import type { ReactElement, ReactNode, PointerEvent as ReactPointerEvent } from 'react'-import { registerPaneCloser, removeTreePane, treePanesWithPrefix } from '@/components/pane-shell/tree/store'+import { setTreePaneParked } from '@/components/pane-shell/tree/parked-panes'+import {+ adoptContributedPanes,+ registerPaneCloser,+ removeTreePane,+ treePanesWithPrefix+} from '@/components/pane-shell/tree/store'import type { MenuKit } from '@/components/ui/actions-menu'import { registry } from '@/contrib/registry'import type { TileDock } from '@/store/session-states'+interface DockHint {+ before: null | string | undefined+ pane: string+ pos: TileDock+}+export interface PaneMirror<T> {/** Reactive source list. */source: ReadableAtom<T[]>@@ -54,41 +66,73 @@ export interface PaneMirror<T> {tabDrag?: (key: string, event: ReactPointerEvent<HTMLElement>, onTap: () => void) => boolean/** Wired as the pane's closer (tab Close). */close: (key: string) => void+ /** A tile that leaves the source but should keep its live body: its pane+ * leaves the tree while its contribution stays registered (see+ * parked-panes.ts), and it re-docks with the same body when it returns.+ * Asked again on every sync, so a tile that stops qualifying is disposed. */+ retain?: (key: string) => boolean+ /** Most retained tiles kept at once; the longest-retained is disposed+ * first. Required with `retain`: every retained body costs memory. */+ retainLimit?: number}/** Build a `watch*` fn: syncs once, then re-syncs on every source/also change.* Module-level state lives in the returned closure, so call it once per app. */export function paneMirror<T>(cfg: PaneMirror<T>): () => void {- const registered = new Map<string, { dispose: () => void; title: string }>()+ const registered = new Map<string, { dispose: () => void; dock: DockHint; title: string }>()+ // Retained tiles, oldest first (Set order = the order they were parked).+ const parked = new Set<string>()const paneId = (key: string) => `${cfg.prefix}:${key}`+ const dockFor = (tile: T): DockHint => ({+ before: cfg.before?.(tile),+ pane: cfg.anchor?.(tile) ?? 'workspace',+ pos: cfg.dir?.(tile) ?? 'right'+ })++ const dispose = (key: string) => {+ registered.get(key)?.dispose()+ registered.delete(key)+ parked.delete(key)+ setTreePaneParked(paneId(key), false)+ removeTreePane(paneId(key))+ }+const sync = () => {const tiles = cfg.source.get()const wanted = new Set(tiles.map(cfg.key))+ let unparked = falsefor (const tile of tiles) {const key = cfg.key(tile)const title = cfg.title(key)const current = registered.get(key)+ // A retained tile coming back keeps its registration — re-registering+ // would remount its body — and re-docks where it fits NOW (its old+ // anchor may have left the tree), before the tiles leaving below go.+ if (current && parked.delete(key)) {+ Object.assign(current.dock, dockFor(tile))+ setTreePaneParked(paneId(key), false)+ unparked = true+ }+// register() replaces same-id in place — safe for live title refreshes.if (current && current.title === title) {continue}- const dispose = registry.register({+ const dock = dockFor(tile)++ const disposeRegistration = registry.register({id: paneId(key),area: 'panes',title,data: {tabLead: cfg.tabLead ? () => cfg.tabLead!(key) : undefined,tabTitle: cfg.tabTitle ? () => cfg.tabTitle!(key) : undefined,- dock: {- before: cfg.before?.(tile),- pane: cfg.anchor?.(tile) ?? 'workspace',- pos: cfg.dir?.(tile) ?? 'right'- },+ dock,lifecycleKeepAlive: cfg.lifecycleKeepAlive?.(key),minWidth: cfg.minWidth,newTab: cfg.newTab?.(key),@@ -105,19 +149,37 @@ export function paneMirror<T>(cfg: PaneMirror<T>): () => void {render: () => cfg.render(key)})- registered.set(key, { dispose, title })+ registered.set(key, { dispose: disposeRegistration, dock, title })if (!current) {registerPaneCloser(paneId(key), () => cfg.close(key))}}- for (const [key, entry] of registered) {- if (!wanted.has(key)) {- entry.dispose()- registered.delete(key)- removeTreePane(paneId(key))+ if (unparked) {+ adoptContributedPanes()+ }++ for (const key of [...registered.keys()]) {+ if (wanted.has(key)) {+ continue}++ if (cfg.retain?.(key)) {+ if (!parked.has(key)) {+ parked.add(key)+ setTreePaneParked(paneId(key), true)+ removeTreePane(paneId(key))+ }++ continue+ }++ dispose(key)+ }++ for (const key of [...parked].slice(0, Math.max(0, parked.size - (cfg.retainLimit ?? 0)))) {+ dispose(key)}// Prune tree panes the SHARED tree persisted for a tile we never registereddiff --git a/apps/desktop/src/app/chat/preview-tile.test.ts b/apps/desktop/src/app/chat/preview-tile.test.tsindex 77ff300287e..5f1359ceb5b 100644--- a/apps/desktop/src/app/chat/preview-tile.test.ts+++ b/apps/desktop/src/app/chat/preview-tile.test.ts@@ -237,6 +237,56 @@ describe('preview tiles mirror the visible session tabs', () => {expect(layout.$rightRailActiveTabId.get()).toBe(bId)})+ const browserTarget = (url: string) => ({ kind: 'url', label: url, source: url, url }) as const++ it("keeps a hidden session's live page mounted and re-docks the same body when it returns", async () => {+ const { preview, session, tree } = await setup()+ const { registry } = await import('@/contrib/registry')+ const contribution = (id: string) => registry.getArea('panes').find(pane => pane.id === `preview-tile:${id}`)++ session.$selectedStoredSessionId.set('sess-1')+ preview.openPreview(browserTarget('https://a.example'))+ const aTab = preview.$previewTabs.get()[0]!.id+ const aBody = contribution(aTab)++ expect(aBody).toBeDefined()++ // Off screen: out of the tree (no tab in B's drawer), body still registered.+ session.$selectedStoredSessionId.set('sess-2')+ preview.openPreview(browserTarget('https://b.example'))+ expect(tree.treePanesWithPrefix('preview-tile:')).toEqual([+ `preview-tile:${preview.$previewTabs.get().find(tab => tab.id !== aTab)!.id}`+ ])+ expect(contribution(aTab)).toBe(aBody)++ // Back on A: the very same registration (a re-register would remount it).+ session.$selectedStoredSessionId.set('sess-1')+ expect(tree.treePanesWithPrefix('preview-tile:')).toEqual([`preview-tile:${aTab}`])+ expect(contribution(aTab)).toBe(aBody)+ })++ it('unmounts only the longest-hidden live page past the cap, and reopens it on return', async () => {+ const { preview, session, tree } = await setup()+ const { registry } = await import('@/contrib/registry')+ const contribution = (id: string) => registry.getArea('panes').find(pane => pane.id === `preview-tile:${id}`)+ const ids: string[] = []++ for (let index = 0; index < 10; index++) {+ session.$selectedStoredSessionId.set(`sess-cap-${index}`)+ preview.openPreview(browserTarget(`https://cap-${index}.example`))+ ids.push(preview.$previewTabs.get().at(-1)!.id)+ }++ // Nine hidden, eight kept: the first session's page was let go.+ expect(contribution(ids[0]!)).toBeUndefined()+ ids.slice(1).forEach(id => expect(contribution(id)).toBeDefined())+ expect(preview.$previewTabs.get()).toHaveLength(10)++ session.$selectedStoredSessionId.set('sess-cap-0')+ expect(contribution(ids[0]!)).toBeDefined()+ expect(tree.treePanesWithPrefix('preview-tile:')).toEqual([`preview-tile:${ids[0]}`])+ })+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.tsxindex 01459c81e65..a8c4fd264e1 100644--- a/apps/desktop/src/app/chat/preview-tile.tsx+++ b/apps/desktop/src/app/chat/preview-tile.tsx@@ -29,6 +29,7 @@ import { $rightRailActiveTabId, type RightRailTabId, selectRightRailTab } from 'import {$browserPages,$dockedVisiblePreviewTabs,+ $poppedBrowserTabIds,$previewTabs,$visiblePreviewTabs,adoptPersistedBrowserTab,@@ -312,12 +313,36 @@ export function watchPreviewTiles(): void {$activeTreeGroup.listen(follow)}+/** Hidden sessions' live pages kept mounted at once. WHY a cap: every kept+ * Browser is a whole renderer process (plus its page's memory) that keeps+ * running while its session is off screen. Eight covers flipping between+ * the handful of chats a user is actually working in; past that the+ * longest-hidden one is unmounted and reloads from its saved address when+ * its session returns (the tab itself is never closed). */+const HIDDEN_LIVE_PREVIEW_LIMIT = 8++/** A page (live Browser guest or rendered HTML) whose body must survive+ * being out of view; a text peek is cheap to re-render. */+function keepsLiveBody(tabId: string): boolean {+ const target = targetFor(tabId)++ return target?.kind === 'url' || target?.previewKind === 'html'+}++/** A tab whose session left the screen keeps its live body when it is a page+ * still open in this profile's rail (`targetFor` reads it) and not popped+ * out (the pop-out window owns that guest). */+const retainHiddenPreview = (tabId: string) => keepsLiveBody(tabId) && !$poppedBrowserTabIds.get().has(tabId)+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). A- // popped-out Browser's pane also leaves the docked tree.+ // Only the FOCUSED session's tabs (plus pins) are in the tree — switching+ // sessions swaps the drawer without closing any tab. A hidden session's+ // live page leaves the tree but stays mounted (hidden, inert) so returning+ // to that session shows the same guest, not a reload; a popped-out+ // Browser's pane leaves the docked tree for good.source: $dockedVisiblePreviewTabs,+ retain: retainHiddenPreview,+ retainLimit: HIDDEN_LIVE_PREVIEW_LIMIT,key: tab => tab.id,prefix: PREVIEW_TILE_PREFIX,// The FIRST preview still opens its own zone docked beside main (identical@@ -338,11 +363,7 @@ const watchPreviewTileMirror = paneMirror<{ id: string }>({// the explicit cross-session workspace, everything else belongs to the// session that opened it (#73890).tabMenuPrefix: previewTabMenuPrefix,- lifecycleKeepAlive: tabId => {- const target = targetFor(tabId)-- return target?.kind === 'url' || target?.previewKind === 'html'- },+ lifecycleKeepAlive: keepsLiveBody,// The body's own Close (an error state's way out) is the tab's ✕, verbatim.render: tabId => <PreviewTilePane onClose={() => closeTabPane(previewPaneId(tabId))} tabId={tabId} />,close: tabId => {diff --git a/apps/desktop/src/components/pane-shell/tree/parked-panes.ts b/apps/desktop/src/components/pane-shell/tree/parked-panes.tsnew file mode 100644index 00000000000..4d624e8c503--- /dev/null+++ b/apps/desktop/src/components/pane-shell/tree/parked-panes.ts@@ -0,0 +1,23 @@+/**+ * PARKED PANES — registered contributions that are deliberately OUT of the+ * layout tree. A parked pane keeps its contribution, so a keep-alive body (a+ * live Browser guest) stays mounted — hidden and inert in its keep-alive host+ * — while adoption must not dock it back. The contribution's owner parks and+ * unparks it: a preview tab whose session is not on screen.+ *+ * Memory-only: after a relaunch there is no live body left to keep.+ */++const parked = new Set<string>()++export function isTreePaneParked(paneId: string): boolean {+ return parked.has(paneId)+}++export function setTreePaneParked(paneId: string, isParked: boolean): void {+ if (isParked) {+ parked.add(paneId)+ } else {+ parked.delete(paneId)+ }+}diff --git a/apps/desktop/src/components/pane-shell/tree/store.ts b/apps/desktop/src/components/pane-shell/tree/store.tsindex d3597386026..0b1a1e8f9a7 100644--- a/apps/desktop/src/components/pane-shell/tree/store.ts+++ b/apps/desktop/src/components/pane-shell/tree/store.ts@@ -44,6 +44,7 @@ import {type SplitNode,type TabStripMode} from './model'+import { isTreePaneParked } from './parked-panes'import { FLOATING_PLACEMENT } from './renderer/floating-rect'import { tabStripVisibleForZone } from './renderer/strip-visibility'@@ -1553,7 +1554,8 @@ export function adoptContributedPanes(): void {// turn it into a track that steals width from a zone, which is the whole// thing floating exists to avoid.const missing = panes.filter(- c => !inTree.has(c.id) && !dismissed.has(c.id) && placementOf(c.id) !== FLOATING_PLACEMENT+ c =>+ !inTree.has(c.id) && !dismissed.has(c.id) && !isTreePaneParked(c.id) && placementOf(c.id) !== FLOATING_PLACEMENT)if (missing.length === 0) {