The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): scope the right rail to the chat on screen, not the gateway socket
Codyc996d1c08883
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 70fbac573fb..1c5d4c05253 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -13562,7 +13562,7 @@ function spawnSecondaryWindow({// covers it. ready-to-show fires after the boot-time paint in// themes/context.tsx, so the window appears already themed.show: false,- webPreferences: chatWindowWebPreferences(PRELOAD_PATH)+ webPreferences: chatWindowWebPreferences(PRELOAD_PATH, profile)})// Chat-surface registration: applyWindowTranslucency swaps this window's@@ -13748,7 +13748,7 @@ function createInstanceWindow(...chatWindowSurfaceOptions(),icon,show: false,- webPreferences: chatWindowWebPreferences(PRELOAD_PATH)+ webPreferences: chatWindowWebPreferences(PRELOAD_PATH, route.profile)})instanceWindows.add(win)diff --git a/apps/desktop/electron/session-windows.ts b/apps/desktop/electron/session-windows.tsindex 8785b04d4dc..647b5832ccf 100644--- a/apps/desktop/electron/session-windows.ts+++ b/apps/desktop/electron/session-windows.ts@@ -46,9 +46,44 @@ const SESSION_WINDOW_MIN_HEIGHT = 620// window while its transcript is streaming. Explicit user actions still call// the main-process window focus paths (session re-open, notification/deep-link,// app activation), preserving intentional raises without background focus theft.-function chatWindowWebPreferences(preloadPath: string) {+// Per-profile Electron session partition for chat windows.+//+// WHY: the renderer persists its UI state (right-rail preview tabs, sidebar+// order, workspace layout) in localStorage, which is scoped to the Electron+// session — NOT to the profile the window renders. With no partition every+// window shares one store, so a preview tab opened in one agent's chat appears+// in every other agent's chat, and one profile's layout bleeds into another.+// apps/desktop/AGENTS.md states the rule this violates: "Persisted state must+// declare its scope in its own key... Getting the scope wrong is how one+// profile's setting bleeds into another."+//+// Giving each non-primary profile its own partition scopes that localStorage+// per agent, so each agent keeps its own rail and layout.+//+// Two deliberate constraints:+// - The PRIMARY profile keeps the default session (no partition), so existing+// installs keep their saved layout instead of resetting it once.+// - The name is plain ASCII. AGENTS.md warns that a partition name containing+// a character Electron percent-escapes (e.g. ':') produces a cookie-store+// folder name the OS cannot read, silently breaking persistence — so the+// profile key is sanitized to [a-zA-Z0-9._-] before it is interpolated.+function chatWindowPartition(profileKey?: null | string) {+ const key = typeof profileKey === 'string' ? profileKey.trim() : ''++ if (!key || key === 'default') {+ return undefined+ }++ return `persist:hermes-win-${key.replace(/[^a-zA-Z0-9._-]/g, '-')}`+}++function chatWindowWebPreferences(preloadPath: string, profileKey?: null | string) {+ const partition = chatWindowPartition(profileKey)+return {preload: preloadPath,+ // Absent partition = Electron's default session (the primary profile).+ ...(partition ? { partition } : {}),contextIsolation: true,webviewTag: true,sandbox: true,@@ -201,6 +236,7 @@ function createSessionWindowRegistry() {export {buildInstanceWindowUrl,buildSessionWindowUrl,+ chatWindowPartition,chatWindowWebPreferences,createSessionWindowRegistry,instanceWindowBounds,diff --git a/apps/desktop/src/store/artifacts.test.ts b/apps/desktop/src/store/artifacts.test.tsindex 4a0933086e7..b8724ec1cab 100644--- a/apps/desktop/src/store/artifacts.test.ts+++ b/apps/desktop/src/store/artifacts.test.ts@@ -114,7 +114,9 @@ describe('artifacts store', () => {openArtifact(result.artifactId)- expect(window.localStorage.getItem('hermes.desktop.previewTabs.v2')).toBe('[]')+ // Artifact tabs are never persistable, so the profile's bucket stays empty+ // and the key is removed rather than stored as an empty list.+ expect(window.localStorage.getItem('hermes.desktop.previewTabs.v2')).toBeNull()})it('tracks version selection and snaps back to latest', () => {diff --git a/apps/desktop/src/store/preview-tabs-scope.test.ts b/apps/desktop/src/store/preview-tabs-scope.test.tsnew file mode 100644index 00000000000..dfbdfd67a15--- /dev/null+++ b/apps/desktop/src/store/preview-tabs-scope.test.ts@@ -0,0 +1,104 @@+// Regression: the right rail's tabs were persisted under ONE global key+// (`hermes.desktop.previewTabs.v2` holding a bare array), so a preview opened in+// one agent's chat appeared in every other agent's chat — Tess's model showed up+// in VEXA's rail and vice versa.+//+// Contract under test: the rail follows THE CHAT ON SCREEN. That is deliberately+// NOT the window's gateway socket — a focused tab does not swap the socket, and+// every bot chat is served by one pooled backend, so a socket-keyed rail shows+// one agent's previews in every agent's chat. That is the same trap+// `bot-row.tsx` documents for the roster highlight, and it is why the first cut+// of this fix did not work. `session-states.ts` resolves the focused session's+// owner and pushes it in via `setPreviewScope`.+import { beforeEach, describe, expect, it } from 'vitest'++import { $activeGatewayProfile, normalizeProfileKey } from '@/store/profile'+import {+ $previewTabs,+ migratePreviewTabsForProfile,+ openPreview,+ setPreviewScope,+ type PreviewTarget+} from '@/store/preview'++const TABS_KEY = 'hermes.desktop.previewTabs.v2'++function fileTarget(path: string): PreviewTarget {+ return {+ kind: 'file',+ label: path.split('/').pop() ?? path,+ path,+ source: path,+ url: `file://${path}`+ }+}++const paths = () => $previewTabs.get().map(tab => tab.target.path)++function storedBuckets(): Record<string, { target: { path?: string } }[]> {+ const raw = window.localStorage.getItem(TABS_KEY)++ return raw ? (JSON.parse(raw) as Record<string, { target: { path?: string } }[]>) : {}+}++describe('right rail follows the chat on screen', () => {+ beforeEach(() => {+ window.localStorage.clear()+ $activeGatewayProfile.set('default')+ setPreviewScope('default')+ $previewTabs.set([])+ })++ it('does not show one agent the tabs another agent opened', () => {+ setPreviewScope('tess')+ openPreview(fileTarget('/tmp/tess-model.html'))++ expect(paths()).toEqual(['/tmp/tess-model.html'])++ // Reading another agent's chat re-homes the rail.+ setPreviewScope('default')++ expect($previewTabs.get()).toEqual([])++ // ...and comes back, unchanged, on the way in.+ setPreviewScope('tess')++ expect(paths()).toEqual(['/tmp/tess-model.html'])+ })++ it('keeps each agent in its own persisted bucket', () => {+ setPreviewScope('tess')+ openPreview(fileTarget('/tmp/tess-model.html'))++ setPreviewScope('default')+ openPreview(fileTarget('/tmp/vexa-note.md'))++ const buckets = storedBuckets()++ expect(buckets[normalizeProfileKey('tess')]?.map(tab => tab.target.path)).toEqual(['/tmp/tess-model.html'])+ expect(buckets[normalizeProfileKey('default')]?.map(tab => tab.target.path)).toEqual(['/tmp/vexa-note.md'])+ })++ it('does NOT re-home on a gateway socket change — the bug this guards', () => {+ // A focused tab does not swap the socket, so the socket changing must not+ // move the rail. Keying off it is what put Tess's model in VEXA's chat.+ setPreviewScope('tess')+ openPreview(fileTarget('/tmp/tess-model.html'))++ $activeGatewayProfile.set('default')++ expect(paths()).toEqual(['/tmp/tess-model.html'])+ })++ it('moves the rail with a rename instead of stranding it under the old name', () => {+ setPreviewScope('tess')+ openPreview(fileTarget('/tmp/tess-model.html'))++ migratePreviewTabsForProfile('tess', 'tess-renamed')++ const buckets = storedBuckets()++ expect(buckets[normalizeProfileKey('tess')]).toBeUndefined()+ expect(buckets[normalizeProfileKey('tess-renamed')]?.map(tab => tab.target.path)).toEqual(['/tmp/tess-model.html'])+ })+})diff --git a/apps/desktop/src/store/preview.test.ts b/apps/desktop/src/store/preview.test.tsindex 32d6168153e..b441d80ded0 100644--- a/apps/desktop/src/store/preview.test.ts+++ b/apps/desktop/src/store/preview.test.ts@@ -228,7 +228,9 @@ describe('preview store', () => {it('does not persist remote HTML without its in-memory document', () => {openPreview({ ...fileTarget('/remote/report.html'), dataUrl: 'data:text/html;base64,PGgxPnJlbW90ZTwvaDE+' })- expect(window.localStorage.getItem('hermes.desktop.previewTabs.v2')).toBe('[]')+ // Nothing persistable, so the profile's bucket is empty and the key is+ // removed rather than stored as an empty list (matching the tiles store).+ expect(window.localStorage.getItem('hermes.desktop.previewTabs.v2')).toBeNull()})it('preserves an explicit HTML source fallback', () => {@@ -242,6 +244,8 @@ describe('preview store', () => {openPreview(target, 'tool-result')- expect(window.localStorage.getItem('hermes.desktop.previewTabs.v2')).toBe('[]')+ // Nothing persistable, so the profile's bucket is empty and the key is+ // removed rather than stored as an empty list (matching the tiles store).+ expect(window.localStorage.getItem('hermes.desktop.previewTabs.v2')).toBeNull()})})diff --git a/apps/desktop/src/store/preview.ts b/apps/desktop/src/store/preview.tsindex 6e3e685e68f..8c77e72bed2 100644--- a/apps/desktop/src/store/preview.ts+++ b/apps/desktop/src/store/preview.ts@@ -1,10 +1,10 @@import { atom, computed } from 'nanostores'-import { persistentAtom } from '@/lib/persisted'-import { readKey } from '@/lib/storage'+import { readKey, readJson, writeKey } from '@/lib/storage'import { normalize } from '@/lib/text'import { $rightRailActiveTabId, type RightRailTabId, selectRightRailTab } from './layout'+import { normalizeProfileKey } from './profile'import { canOpenBrowserWindow, openBrowserInNewWindow } from './windows'/**@@ -118,8 +118,10 @@ function isPdfFileTarget(target: PreviewTarget): boolean {* Without this restore-time migration, an already-open PDF keeps taking the* obsolete raw-binary path after Desktop itself has been upgraded. */export function decodePreviewTabs(raw: string): PreviewTab[] {- const parsed = JSON.parse(raw) as unknown+ return parseTabList(JSON.parse(raw) as unknown)+}+function parseTabList(parsed: unknown): PreviewTab[] {return (Array.isArray(parsed) ? parsed.filter(isPreviewTab) : []).map(tab =>isPdfFileTarget(tab.target) && tab.target.previewKind === 'binary'? { ...tab, target: { ...tab.target, previewKind: 'pdf' as const } }@@ -127,22 +129,160 @@ export function decodePreviewTabs(raw: string): PreviewTab[] {)}-export const $previewTabs = persistentAtom<PreviewTab[]>(TABS_STORAGE_KEY, [], {- decode: decodePreviewTabs,- // Inline bytes are not restorable. Strip them from images, and skip remote- // HTML and artifact tabs that cannot render without their in-memory payload.- encode: tabs =>- JSON.stringify(- tabs.filter(- tab =>- tab.target.kind !== 'artifact' &&- !tab.target.transient &&- !(tab.target.previewKind === 'html' && tab.target.dataUrl)- ),- (key, value) => (key === 'dataUrl' ? undefined : value)- )+/** The tabs a profile's rail is showing, keyed by profile. */+type TabsByProfile = Record<string, PreviewTab[]>++/** Read every profile's bucket. A value written by a build that stored ONE+ * global array is held back and adopted by the first scope to arrive rather+ * than dropped — tabs the user can see are the tabs that must survive. */+let pendingLegacyTabs: PreviewTab[] | null = null++function loadTabsByProfile(): TabsByProfile {+ const stored = readJson<unknown>(TABS_STORAGE_KEY)++ if (Array.isArray(stored)) {+ pendingLegacyTabs = parseTabList(stored)++ return {}+ }++ if (!stored || typeof stored !== 'object') {+ return {}+ }++ const byProfile: TabsByProfile = {}++ for (const [key, value] of Object.entries(stored as Record<string, unknown>)) {+ byProfile[normalizeProfileKey(key)] = parseTabList(value)+ }++ return byProfile+}++const tabsByProfile = loadTabsByProfile()++/** Inline bytes are not restorable. Strip them from images, and skip remote+ * HTML and artifact tabs that cannot render without their in-memory payload. */+function persistableTabs(tabs: PreviewTab[]): PreviewTab[] {+ return tabs.filter(+ tab =>+ tab.target.kind !== 'artifact' &&+ !tab.target.transient &&+ !(tab.target.previewKind === 'html' && tab.target.dataUrl)+ )+}++function persistTabs() {+ const buckets: TabsByProfile = {}++ for (const [key, tabs] of Object.entries(tabsByProfile)) {+ const persistable = persistableTabs(tabs)++ if (persistable.length > 0) {+ buckets[key] = persistable+ }+ }++ // `dataUrl` holds inline bytes that cannot be restored; drop the key wherever+ // it survives the filter above (an image tab). An empty map removes the key+ // rather than storing `{}`, matching the tiles store.+ writeKey(+ TABS_STORAGE_KEY,+ Object.keys(buckets).length === 0+ ? null+ : JSON.stringify(buckets, (key, value) => (key === 'dataUrl' ? undefined : value))+ )+}++// Tabs are scoped to THE CHAT ON SCREEN, not to the window's gateway socket.+// `session-states.ts` resolves the focused session's owner and pushes it here+// via `setPreviewScope`; the two must not be conflated, because a focused tab+// does not swap the socket — every bot chat is served by one pooled backend, so+// a socket-keyed rail showed one agent's preview in every agent's chat. That is+// the same trap `bot-row.tsx` documents for the roster highlight. (It also owns+// the resolver, so it pushes rather than having this module reach for it — this+// file is already imported by session-states.ts.)+//+// Which bucket the atom mirrors. A RENAME moves the view without the scope+// changing, so this has to follow the rename or the persist subscriber below+// would resurrect the bucket the rename just deleted.+let viewKey = 'default'++export const $previewTabs = atom<PreviewTab[]>([])++$previewTabs.subscribe(tabs => {+ // `subscribe` hands a readonly view; the bucket is a mutable store of its own.+ tabsByProfile[viewKey] = [...tabs]+ persistTabs()})+/** 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. */+export function setPreviewScope(scope: string) {+ const next = normalizeProfileKey(scope) || 'default'++ if (next === viewKey) {+ return+ }++ if (pendingLegacyTabs) {+ tabsByProfile[next] = [...(tabsByProfile[next] ?? []), ...pendingLegacyTabs]+ pendingLegacyTabs = null+ persistTabs()+ }++ viewKey = next+ $previewTabs.set(tabsByProfile[next] ?? [])+}++/** Drop one profile's rail. Delete counterpart of the tiles store's+ * `dropTilesForProfile`, which profile deletion calls. */+export function dropPreviewTabsForProfile(profile: string) {+ const key = normalizeProfileKey(profile)++ delete tabsByProfile[key]+ persistTabs()++ if (key === viewKey) {+ $previewTabs.set([])+ }+}++/** Move one profile's rail to another. Rename counterpart of the tiles store's+ * `migrateTilesForProfile`: without it a rename strands the tabs under a+ * profile that no longer exists. */+export function migratePreviewTabsForProfile(oldProfile: string, newProfile: string) {+ const from = normalizeProfileKey(oldProfile)+ const to = normalizeProfileKey(newProfile)++ if (from === to) {+ return+ }++ const moved = tabsByProfile[from]++ if (moved) {+ delete tabsByProfile[from]+ tabsByProfile[to] = [...(tabsByProfile[to] ?? []), ...moved]+ }++ // The view belongs to the renamed profile; only its NAME changed. Re-point it+ // BEFORE the atom is set, so the persist subscriber writes the new bucket+ // rather than resurrecting the one just deleted.+ const wasInView = from === viewKey++ if (wasInView) {+ viewKey = to+ }++ persistTabs()++ if (wasInView) {+ $previewTabs.set(tabsByProfile[to] ?? [])+ }+}+if (typeof window !== 'undefined') {try {window.localStorage.removeItem(LEGACY_SESSION_REGISTRY_KEY)diff --git a/apps/desktop/src/store/session-states.ts b/apps/desktop/src/store/session-states.tsindex 7f6ff71adc2..acb55a75814 100644--- a/apps/desktop/src/store/session-states.ts+++ b/apps/desktop/src/store/session-states.ts@@ -37,6 +37,7 @@ import type { SessionInfo } from '@/types/hermes'import { dropPreviewArtifactsForProfile, migratePreviewArtifactsForProfile } from './preview-status'import { $activeGatewayProfile, normalizeProfileKey } from './profile'+import { dropPreviewTabsForProfile, migratePreviewTabsForProfile, setPreviewScope } from './preview'import { clearAllProviderWaits, clearSessionProviderWait } from './provider-wait'import {$activeSessionId,@@ -110,6 +111,9 @@ export function recordSessionEventScope(event: { connectionId?: string; profile?profile: String(event.profile ?? '').trim() || 'default'})+ // An owner resolved after the focus moved must still re-home the rail.+ syncPreviewScope()+return}@@ -121,6 +125,8 @@ export function recordSessionEventScope(event: { connectionId?: string; profile?if (profile) {sessionOwnerByRuntimeId.set(event.session_id, profile)}++ syncPreviewScope()}/** The owner an inbound runtime EVENT proved for `sessionId` (#97511): the@@ -1147,6 +1153,28 @@ export function knownOwnerForSession(sessionId: null | string | undefined): Sessreturn sessionOwnerByRuntimeId.get(sessionId) ?? durable}+/** The profile whose chat is on screen — the rail's scope.+ *+ * NOT `$activeGatewayProfile`: a focused tab does not swap the gateway socket,+ * and every bot chat is served by one pooled backend, so the socket stays on+ * the launch profile while you read another agent's chat. Keying the rail there+ * showed one agent's previews in every agent's chat. `bot-row.tsx` documents+ * the same trap for the roster highlight and resolves it the same way. */+function railScopeForActiveSession(): string {+ const owner = knownOwnerForSession($activeSessionId.get() ?? undefined)+ const profile = typeof owner === 'string' ? owner : owner?.profile++ return normalizeProfileKey(profile || $activeGatewayProfile.get())+}++/** Keep the rail on the chat in view, so switching agents re-homes it. */+function syncPreviewScope() {+ setPreviewScope(railScopeForActiveSession())+}++$activeSessionId.subscribe(syncPreviewScope)+syncPreviewScope()+/*** Whether the connection that OWNS `sessionId` is remote — never the ambient* `$connection`. A session tied to a registered secondary connection (Bot@@ -2053,6 +2081,9 @@ export function dropTilesForProfile(}persistTiles()+ // The rail is a profile-keyed family too: a deleted profile's tabs must not+ // outlive it, or a later profile of the same name inherits them.+ dropPreviewTabsForProfile(name)}/**@@ -2112,6 +2143,9 @@ export function migrateTilesForProfile(oldProfile: string, newProfile: string):migrateRememberedNavigationForProfile(from, to)migrateSessionOwnerHintsForProfile(from, to)migratePreviewArtifactsForProfile(from, to)+ // Sibling family: the rail's profile-keyed buckets move with the rename, or+ // the renamed profile opens with an empty rail and the old name keeps them.+ migratePreviewTabsForProfile(from, to)}/** ⌘⇧T — reopen the most recently closed tab where it was, then focus it.