The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): keep live session tiles out of saved layout presets
Austin Pickett55507eab9006
diff --git a/apps/desktop/src/components/pane-shell/tree/preset-tree.test.ts b/apps/desktop/src/components/pane-shell/tree/preset-tree.test.tsnew file mode 100644index 00000000000..1c82d185117--- /dev/null+++ b/apps/desktop/src/components/pane-shell/tree/preset-tree.test.ts@@ -0,0 +1,82 @@+import { describe, expect, it } from 'vitest'++import { allPaneIds, group, split } from './model'+import { isPresetExcludedPaneId, PRESET_EXCLUDED_PANE_PREFIXES, stripPresetLivePanes } from './preset-tree'++describe('stripPresetLivePanes', () => {+ it('drops session tiles and keeps the structural rails', () => {+ const tree = split(+ 'row',+ [+ group(['sessions', 'preview'], { active: 'sessions', id: 'grp-sessions' }),+ group(['workspace', 'session-tile:20260823_193634_728a24', 'session-tile:20260823_193532_a7dbd9'], {+ active: 'session-tile:20260823_193634_728a24',+ id: 'grp-main'+ }),+ group(['files'], { active: 'files', id: 'grp-files' })+ ],+ [1, 3.4, 1.25],+ 'spl-root'+ )++ const next = stripPresetLivePanes(tree)++ expect(next).not.toBeNull()+ expect(allPaneIds(next!)).toEqual(['sessions', 'preview', 'workspace', 'files'])+ // Geometry survives: node ids, weights and split shape are untouched.+ expect(next).toMatchObject({+ type: 'split',+ id: 'spl-root',+ weights: [1, 3.4, 1.25],+ children: [+ { id: 'grp-sessions' },+ { id: 'grp-main', active: 'workspace', panes: ['workspace'] },+ { id: 'grp-files' }+ ]+ })+ })++ it('drops preview and route tiles, collapsing the zone they emptied', () => {+ const tree = split('row', [+ group(['workspace'], { active: 'workspace', id: 'grp-main' }),+ group(['preview-tile:undefined', 'route-tile:skills'], {+ active: 'preview-tile:undefined',+ id: 'grp-ghost'+ })+ ])++ const next = stripPresetLivePanes(tree)++ expect(next).toMatchObject({ type: 'group', id: 'grp-main', panes: ['workspace'] })+ expect(allPaneIds(next!)).not.toContain('preview-tile:undefined')+ expect(allPaneIds(next!)).not.toContain('route-tile:skills')+ })++ it('re-points `active` at a surviving tab when the active one is a tile', () => {+ const tree = group(['files', 'session-tile:gone'], { active: 'session-tile:gone', id: 'grp-x' })++ expect(stripPresetLivePanes(tree)).toMatchObject({ active: 'files', panes: ['files'] })+ })++ it('returns the SAME reference when the tree is already clean', () => {+ const tree = group(['workspace', 'files'], { active: 'workspace', id: 'grp-main' })++ expect(stripPresetLivePanes(tree)).toBe(tree)+ })++ it('returns null when the preset was only a snapshot of live tiles', () => {+ const tree = group(['session-tile:abc', 'preview-tile:file:/tmp/x'], { active: 'session-tile:abc', id: 'only' })++ expect(stripPresetLivePanes(tree)).toBeNull()+ })++ it('classifies the prefixes the field report baked into user-jrl', () => {+ expect(PRESET_EXCLUDED_PANE_PREFIXES).toEqual(['session-tile:', 'preview-tile:', 'route-tile:'])+ expect(isPresetExcludedPaneId('session-tile:20260823_193634_728a24')).toBe(true)+ expect(isPresetExcludedPaneId('preview-tile:undefined')).toBe(true)+ expect(isPresetExcludedPaneId('route-tile:page')).toBe(true)+ expect(isPresetExcludedPaneId('workspace')).toBe(false)+ expect(isPresetExcludedPaneId('hermes-bots:pane')).toBe(false)+ expect(isPresetExcludedPaneId('terminal')).toBe(false)+ })+})diff --git a/apps/desktop/src/components/pane-shell/tree/preset-tree.ts b/apps/desktop/src/components/pane-shell/tree/preset-tree.tsnew file mode 100644index 00000000000..f20100306b1--- /dev/null+++ b/apps/desktop/src/components/pane-shell/tree/preset-tree.ts@@ -0,0 +1,81 @@+/**+ * A named layout preset is GEOMETRY (splits, rails, weights, which zones are+ * open) — not a snapshot of the conversations that happened to be on screen+ * when it was saved.+ *+ * `saveCurrentLayoutAs` clones the LIVE tree, which carries+ * `session-tile:<storedSessionId>`, `preview-tile:*` and `route-tile:*` panes.+ * Those ids are not portable: the layout tree and its presets are GLOBAL+ * (`hermes.desktop.layoutTree.v2` / `hermes.desktop.layoutPresets.v2`), while a+ * session tile belongs to the profile that owns the stored session. Re-applying+ * such a preset remounts the baked-in tiles, which fires `session.resume` /+ * agent init across profiles; the tile WebSocket then drops, the gateway+ * `ws_orphan_reap`s the runtime, and the UI keeps RPCing the dead id (#94260).+ *+ * This is deliberately NOT the same path as persisting the live tree across+ * restarts (preview tiles, #92818 / #93179) — those PRs never touch+ * `saveLayoutPresetTree` / `applyLayoutPreset`, and they do not strip+ * `session-tile:` at all. `applyTree` already ADOPTS the panes that are open+ * right now into the new geometry, so stripping here does not lose tabs: it+ * only stops them arriving from a stored snapshot.+ */++import { allPaneIds, type LayoutNode, normalize } from './model'++/** Panes that must never ride along in a named layout preset. */+export const PRESET_EXCLUDED_PANE_PREFIXES = ['session-tile:', 'preview-tile:', 'route-tile:'] as const++/** Is `paneId` a live/ephemeral tile that a preset must not carry? */+export const isPresetExcludedPaneId = (paneId: string): boolean =>+ PRESET_EXCLUDED_PANE_PREFIXES.some(prefix => paneId.startsWith(prefix))++/**+ * A copy of `tree` without live/ephemeral tile panes. Zones left empty collapse+ * through `normalize`, which also unwraps the single-child splits they leave+ * behind. Unchanged subtrees keep their reference, so an already-clean preset+ * comes back as the SAME object.+ *+ * Returns `null` when nothing structural remains — a preset that was only a+ * snapshot of open tabs carries no layout and must not be applied (applying it+ * would hand `applyTree` an empty tree).+ */+export function stripPresetLivePanes(tree: LayoutNode): LayoutNode | null {+ const walk = (node: LayoutNode): LayoutNode => {+ if (node.type === 'group') {+ const panes = node.panes.filter(paneId => !isPresetExcludedPaneId(paneId))++ if (panes.length === node.panes.length) {+ return node+ }++ // The active tab may be one of the stripped panes; fall to the first+ // survivor (an emptied zone keeps `''` and is dropped by normalize).+ return { ...node, panes, active: panes.includes(node.active) ? node.active : (panes[0] ?? '') }+ }++ const children = node.children.map(walk)++ // Reference-preserving: a split whose children all came back untouched is+ // returned as-is, so the clean-preset no-op stays allocation-free.+ if (children.every((child, i) => child === node.children[i])) {+ return node+ }++ return { ...node, children }+ }++ return normalize(walk(tree))+}++/** The `resting` entries that still name a pane the stripped geometry places.+ * A resting record for a live tile names nothing on apply (the pane is gone),+ * and leaving it behind would keep writing tile ids back into the preset. */+export function stripPresetResting(resting: readonly string[] | undefined, tree: LayoutNode): string[] {+ if (!resting) {+ return []+ }++ const placed = new Set(allPaneIds(tree))++ return resting.filter(paneId => placed.has(paneId))+}diff --git a/apps/desktop/src/components/pane-shell/tree/presets.test.ts b/apps/desktop/src/components/pane-shell/tree/presets.test.tsnew file mode 100644index 00000000000..14c1f51ed3b--- /dev/null+++ b/apps/desktop/src/components/pane-shell/tree/presets.test.ts@@ -0,0 +1,120 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { allPaneIds, group, type LayoutNode, split } from './model'+import { applyLayoutPreset, deleteUserPreset, saveLayoutPresetTree } from './presets'+import { $dismissedPanes, $hiddenTreePanes, $layoutTree } from './store'++// #94260: a named layout preset is GEOMETRY. Saving cloned the live tree, so a+// preset carried `session-tile:<storedSessionId>` (from ANY profile — the+// layout tree and its presets are global) and `preview-tile:*` /+// `route-tile:*`. Applying it remounted those conversations (`session.resume` →+// agent init), the tile WS dropped, the gateway `ws_orphan_reap`ed the runtime+// and the UI kept RPCing the dead id. These are the save / apply / load-heal+// paths for that defect.++const USER_KEY = 'hermes.desktop.layoutPresets.v2'++const LIVE_TILE = 'session-tile:20260823_233759_0fc103'+const FOREIGN_TILE = 'session-tile:20260823_193634_728a24'+const OTHER_FOREIGN_TILE = 'session-tile:20260823_193532_a7dbd9'++/** The shape `user-jrl` had in the field report: live tiles cloned into a+ * saved deck, two of them from named profiles. */+function dirtyDeck() {+ return split(+ 'row',+ [+ group(['sessions', 'preview'], { active: 'sessions', id: 'grp-sessions' }),+ group(['workspace', FOREIGN_TILE, OTHER_FOREIGN_TILE], { active: FOREIGN_TILE, id: 'grp-main' }),+ group(['preview-tile:undefined', 'route-tile:skills'], { active: 'preview-tile:undefined', id: 'grp-ghost' })+ ],+ [1, 3.4, 1],+ 'spl-root'+ )+}++const storedPresets = () =>+ JSON.parse(window.localStorage.getItem(USER_KEY) ?? 'null') as Record<string, { resting?: string[]; tree: LayoutNode }>++beforeEach(() => {+ window.localStorage.clear()+ $dismissedPanes.set(new Set())+ $hiddenTreePanes.set(new Set())+})++afterEach(() => {+ deleteUserPreset('user-jrl')+ deleteUserPreset('user-rest')+ vi.resetModules()+})++describe('user layout presets stay geometry-only (#94260)', () => {+ it('saves geometry, not the session tabs open at save time', () => {+ const id = saveLayoutPresetTree('JRL', dirtyDeck())++ expect(id).toBe('user-jrl')++ expect(allPaneIds(storedPresets()['user-jrl'].tree)).toEqual(['sessions', 'preview', 'workspace'])+ })++ it('drops resting records for the live tiles it strips', () => {+ saveLayoutPresetTree('Rest', dirtyDeck(), [FOREIGN_TILE, 'sessions'])++ expect(storedPresets()['user-rest'].resting).toEqual(['sessions'])+ })++ it('applies a dirty snapshot without resurrecting its baked-in tiles', () => {+ $layoutTree.set(group(['workspace', LIVE_TILE], { active: 'workspace', id: 'grp-live' }))++ applyLayoutPreset('user-jrl', dirtyDeck())++ const ids = allPaneIds($layoutTree.get()!)++ // Nothing from the snapshot's tiles comes back…+ expect(ids).not.toContain(FOREIGN_TILE)+ expect(ids).not.toContain(OTHER_FOREIGN_TILE)+ expect(ids).not.toContain('preview-tile:undefined')+ expect(ids).not.toContain('route-tile:skills')+ // …the preset's geometry does…+ expect(ids).toContain('sessions')+ // …and the tile that was ALREADY open is adopted, so no tab is lost.+ expect(ids).toContain(LIVE_TILE)+ })++ it('leaves the live layout alone when a preset is only a tile snapshot', () => {+ const live = group(['workspace'], { active: 'workspace', id: 'grp-live' })++ $layoutTree.set(live)+ applyLayoutPreset('user-tiles-only', group([FOREIGN_TILE, 'preview-tile:undefined'], { id: 'only-tiles' }))++ expect($layoutTree.get()).toBe(live)+ })++ it('heals a preset stored by an older build and rewrites the healed copy', async () => {+ window.localStorage.setItem(USER_KEY, JSON.stringify({ 'user-jrl': { name: 'JRL', tree: dirtyDeck() } }))++ vi.resetModules()++ await import('./presets')++ const healed = storedPresets()['user-jrl'] as { name: string; tree: LayoutNode }++ expect(healed.name).toBe('JRL')+ expect(allPaneIds(healed.tree)).toEqual(['sessions', 'preview', 'workspace'])+ })++ it('drops a stored preset that was nothing but tiles', async () => {+ window.localStorage.setItem(+ USER_KEY,+ JSON.stringify({+ 'user-ghosts': { name: 'Ghosts', tree: group([FOREIGN_TILE, 'preview-tile:undefined'], { id: 'only-tiles' }) }+ })+ )++ vi.resetModules()++ await import('./presets')++ expect(window.localStorage.getItem(USER_KEY)).toBe('{}')+ })+})diff --git a/apps/desktop/src/components/pane-shell/tree/presets.ts b/apps/desktop/src/components/pane-shell/tree/presets.tsindex 9bfad6d5d43..10bcdc2ef49 100644--- a/apps/desktop/src/components/pane-shell/tree/presets.ts+++ b/apps/desktop/src/components/pane-shell/tree/presets.ts@@ -13,6 +13,7 @@ import { readJson, writeJson, writeKey } from '@/lib/storage'import { asLayoutIntent, type Tiered } from '@/store/interface-mode'import { allPaneIds, findGroupOfPane, isLayoutNode, type LayoutNode } from './model'+import { stripPresetLivePanes, stripPresetResting } from './preset-tree'import { $dismissedPanes, $hiddenTreePanes, $layoutTree, applyTree, markActivePreset } from './store'export const LAYOUTS_AREA = 'layouts'@@ -75,12 +76,37 @@ const userDisposers = new Map<string, () => void>()function loadUserPresets(): Record<string, StoredPreset> {const parsed = readJson<Record<string, StoredPreset>>(USER_KEY) ?? {}const out: Record<string, StoredPreset> = {}+ let healed = falsefor (const [id, preset] of Object.entries(parsed)) {- if (preset && typeof preset.name === 'string' && isLayoutNode(preset.tree)) {- out[id] = preset- rememberSpec(id, preset)+ if (!preset || typeof preset.name !== 'string' || !isLayoutNode(preset.tree)) {+ continue}++ // Heal presets written by older builds, which cloned the live tree and so+ // baked in `session-tile:` / `preview-tile:` / `route-tile:` pane ids+ // (#94260). A preset that was ONLY such a snapshot has no geometry left+ // and is dropped.+ const tree = stripPresetLivePanes(preset.tree)++ if (!tree) {+ healed = true++ continue+ }++ const resting = stripPresetResting(preset.resting, tree)++ if (tree !== preset.tree || resting.length !== (preset.resting?.length ?? 0)) {+ healed = true+ }++ out[id] = { name: preset.name, resting, tree }+ rememberSpec(id, out[id])+ }++ if (healed) {+ persistUserPresets(out)}return out@@ -107,7 +133,10 @@ for (const [id, preset] of Object.entries(userPresets)) {/** Save any tree as a named user preset (and make it active). A deck saved* from the live layout remembers which of its panes were closed, so applying- * it later restores what was on screen, not just where things sat. */+ * it later restores what was on screen, not just where things sat —+ * but only for the panes a preset can carry: a live tile (session / preview /+ * route) is a snapshot of conversations open NOW, not layout, and restoring+ * one remounts a foreign-profile session (#94260). */export function saveLayoutPresetTree(name: string, tree: LayoutNode, resting: readonly string[] = []): string | null {const trimmed = name.trim()@@ -115,6 +144,15 @@ export function saveLayoutPresetTree(name: string, tree: LayoutNode, resting: rereturn null}+ // Presets are GEOMETRY. Strip the live tiles before the tree is ever written+ // to `hermes.desktop.layoutPresets.v2`; `applyTree` adopts the tiles that are+ // actually open into this geometry, so no open tab is lost.+ const geometry = stripPresetLivePanes(tree)++ if (!geometry) {+ return null+ }+const id = `user-${trimmed.toLowerCase()@@ -122,7 +160,7 @@ export function saveLayoutPresetTree(name: string, tree: LayoutNode, resting: re.replace(/^-+|-+$/g, '') || Date.now().toString(36)}`- userPresets[id] = { name: trimmed, tree, resting: [...resting] }+ userPresets[id] = { name: trimmed, tree: geometry, resting: stripPresetResting(resting, geometry) }persistUserPresets(userPresets)rememberSpec(id, userPresets[id])registerUserPreset(id, userPresets[id])@@ -163,7 +201,18 @@ export const isUserPreset = (id: string) => id in userPresets/** Apply a preset's tree (deep-cloned so live edits never mutate the preset),* opening what it places and resting what it says to. In Simple the mode* already decides what rests, so the open/close side of a layout pick yields- * to it instead of surfacing shadowed panes for the session. */+ * to it instead of surfacing shadowed panes for the session.+ *+ * Strips live tiles on the way in as well: a preset registered by a plugin —+ * or handed straight to this function before a reload healed the store — must+ * not be able to remount a baked-in session (#94260). `applyTree` adopts the+ * tiles open right now, so the user's tabs stay where they are. */export function applyLayoutPreset(id: string, tree: LayoutNode) {- asLayoutIntent(() => applyTree(structuredClone(tree), id, specs.get(id)?.resting))+ const geometry = stripPresetLivePanes(structuredClone(tree))++ if (!geometry) {+ return+ }++ asLayoutIntent(() => applyTree(geometry, id, specs.get(id)?.resting))}