Skip to content

The agent that grows with you

fix(desktop): scope session/pin lists per connection across windows

Tekniumafe238ac7e3c
diff --git a/apps/desktop/src/lib/connection-scoped.ts b/apps/desktop/src/lib/connection-scoped.ts
new file mode 100644
index 00000000000..a9b4542b629
--- /dev/null
+++ b/apps/desktop/src/lib/connection-scoped.ts
@@ -0,0 +1,161 @@
+import { atom, type WritableAtom } from 'nanostores'
+
+import { type Codec, Codecs } from './persisted'
+import { readKey, writeKey } from './storage'
+
+// ── Connection-scoped persistence ───────────────────────────────────────────
+// Multiple Desktop windows share one renderer origin — and therefore one
+// localStorage area — while each window can be connected to a DIFFERENT
+// gateway (primary vs per-session secondaries, local vs remote registry
+// connections). Any gateway-bound list persisted under a single global key is
+// silently shared between those windows, and per-window reconciliation (pin
+// sync, session ordering) then bleeds one backend's state into another's
+// sidebar (#77318).
+//
+// Persisted state must declare its scope in its own key. This module owns the
+// CONNECTION scope: a `connectionScopedAtom` behaves like `persistentAtom`,
+// but its storage key follows the active connection. The local connection
+// keeps the BARE key — byte-identical behavior for single-backend users, the
+// same contract as `backendScopeKey` in @hermes/shared — while a remote
+// connection gets `<key>.remote.<encoded baseUrl>.<encoded profile>`, the
+// shape `workspaceCwdKey` already established.
+//
+// Legacy globally-keyed values are deliberately NOT migrated into remote
+// scopes: those keys accumulated writes from every window, so ownership of
+// any given row is unknowable — adopting them wholesale is exactly the
+// cross-connection bleed this scope prevents (see the #67709 precedent for
+// profile keys). Backend-mirrored lists (pins) self-heal from the gateway's
+// own rows instead.
+
+/** Minimal slice of HermesConnection this module keys on. */
+export interface ConnectionScopeDescriptor {
+ baseUrl?: string
+ mode?: 'local' | 'remote'
+ profile?: null | string
+}
+
+/** The storage-key suffix for a connection. Local (and unknown) connections
+ * map to the bare key; remote connections get their own namespace. */
+export function connectionScopeSuffix(connection: ConnectionScopeDescriptor | null | undefined): string {
+ if (connection?.mode !== 'remote') {
+ return ''
+ }
+
+ const base = encodeURIComponent(connection.baseUrl || 'remote')
+ const profile = encodeURIComponent(connection.profile || 'default')
+
+ return `.remote.${base}.${profile}`
+}
+
+interface ScopedEntry<T> {
+ $value: WritableAtom<T>
+ codec: Codec<T>
+ fallback: T
+ key: string
+ /** True while a rescope is applying a loaded value — the persistence
+ * subscriber must not echo that read back into storage. */
+ applying: boolean
+}
+
+let activeSuffix = ''
+
+const registry: ScopedEntry<any>[] = []
+const scopeListeners = new Set<() => void>()
+
+/** The suffix for the connection the window is currently on. */
+export function activeConnectionScopeSuffix(): string {
+ return activeSuffix
+}
+
+/** Observe scope changes (fires BEFORE the scoped atoms repaint, so
+ * per-connection bookkeeping can reset ahead of the reload). */
+export function onConnectionScopeChange(listener: () => void): () => void {
+ scopeListeners.add(listener)
+
+ return () => void scopeListeners.delete(listener)
+}
+
+function loadEntry<T>(entry: ScopedEntry<T>): T {
+ const raw = readKey(entry.key + activeSuffix)
+
+ if (raw === null) {
+ return entry.fallback
+ }
+
+ try {
+ return entry.codec.decode(raw)
+ } catch {
+ return entry.fallback
+ }
+}
+
+/**
+ * A `persistentAtom` whose storage key carries the active connection scope.
+ * Reads seed from the current scope's key; writes land under it. When the
+ * window's connection changes, every scoped atom reloads from the new scope.
+ */
+export function connectionScopedAtom<T>(key: string, fallback: T, codec: Codec<T> = Codecs.json<T>()): WritableAtom<T> {
+ const entry: ScopedEntry<T> = { $value: atom<T>(fallback), applying: false, codec, fallback, key }
+ entry.$value.set(loadEntry(entry))
+ registry.push(entry)
+
+ // Persist CHANGES only — same creation-emission and rescope suppression
+ // rationale as persistentAtom: echoing a just-read value back out can
+ // clobber a storage snapshot another window is about to read.
+ let creationEmission = true
+
+ entry.$value.subscribe(value => {
+ if (creationEmission) {
+ creationEmission = false
+
+ return
+ }
+
+ if (entry.applying) {
+ return
+ }
+
+ writeKey(entry.key + activeSuffix, entry.codec.encode(value))
+ })
+
+ return entry.$value
+}
+
+/**
+ * Point every connection-scoped atom at `connection`'s storage scope.
+ *
+ * Called whenever the window's connection descriptor is published. A null
+ * descriptor is an ordinary disconnect/reconnect state — not evidence the
+ * user selected another backend — so it keeps the current scope (the same
+ * contract as syncCronModelImpactConnection).
+ */
+export function rescopeConnectionScopedStores(connection: ConnectionScopeDescriptor | null | undefined): void {
+ if (!connection) {
+ return
+ }
+
+ const next = connectionScopeSuffix(connection)
+
+ if (next === activeSuffix) {
+ return
+ }
+
+ activeSuffix = next
+
+ // Bookkeeping listeners first: pin-sync's mirrored/pending sets describe
+ // the PREVIOUS backend and must be gone before the reload below triggers
+ // their reconcile against the new scope's lists.
+ for (const listener of scopeListeners) {
+ listener()
+ }
+
+ for (const entry of registry) {
+ entry.applying = true
+
+ try {
+ entry.$value.set(loadEntry(entry))
+ } finally {
+ entry.applying = false
+ }
+ }
+}
diff --git a/apps/desktop/src/store/layout-connection-scope.test.ts b/apps/desktop/src/store/layout-connection-scope.test.ts
new file mode 100644
index 00000000000..2c4ee0ac30f
--- /dev/null
+++ b/apps/desktop/src/store/layout-connection-scope.test.ts
@@ -0,0 +1,154 @@
+import { beforeEach, describe, expect, it } from 'vitest'
+
+import type { HermesConnection } from '@/global'
+import { readKey } from '@/lib/storage'
+
+import { $pinnedSessionIds, $sidebarSessionOrderIds, $sidebarSessionOrderManual, pinSession } from './layout'
+import { getRememberedSessionId, setConnection, setRememberedSessionId } from './session'
+
+// Two Desktop windows share one renderer origin (and therefore one
+// localStorage area) while each can be connected to a DIFFERENT gateway.
+// Session/pin lists reconcile against each gateway's own state.db, so any of
+// these lists persisted under a single global key bleeds between windows on
+// different backends (#77318). These tests pin the scope contract: the
+// gateway-bound sidebar lists must be keyed per connection.
+
+const localConn = {
+ baseUrl: 'http://127.0.0.1:8000',
+ mode: 'local',
+ profile: 'default'
+} as unknown as HermesConnection
+
+const remoteA = {
+ baseUrl: 'https://vps-a.example:8443',
+ mode: 'remote',
+ profile: 'default'
+} as unknown as HermesConnection
+
+const remoteB = {
+ baseUrl: 'https://vps-b.example:8443',
+ mode: 'remote',
+ profile: 'default'
+} as unknown as HermesConnection
+
+beforeEach(() => {
+ window.localStorage.clear()
+ // Return to the local scope and empty every list under it.
+ setConnection(localConn)
+ $pinnedSessionIds.set([])
+ $sidebarSessionOrderIds.set([])
+ $sidebarSessionOrderManual.set(false)
+})
+
+describe('connection-scoped sidebar lists (#77318)', () => {
+ it('does not leak the local pin set into a remote connection', () => {
+ pinSession('local-1')
+ pinSession('local-2')
+
+ setConnection(remoteA)
+
+ // The remote gateway has its own state.db; its pin list starts from its
+ // own scope (empty here), never from the local window's pins.
+ expect($pinnedSessionIds.get()).toEqual([])
+ })
+
+ it('keeps pin sets isolated between two different remote gateways', () => {
+ setConnection(remoteA)
+ pinSession('a-1')
+
+ setConnection(remoteB)
+ expect($pinnedSessionIds.get()).toEqual([])
+ pinSession('b-1')
+
+ // Each scope round-trips its own set.
+ setConnection(remoteA)
+ expect($pinnedSessionIds.get()).toEqual(['a-1'])
+
+ setConnection(remoteB)
+ expect($pinnedSessionIds.get()).toEqual(['b-1'])
+ })
+
+ it('restores the local pin set when returning to the local connection', () => {
+ pinSession('local-1')
+
+ setConnection(remoteA)
+ pinSession('a-1')
+
+ setConnection(localConn)
+ expect($pinnedSessionIds.get()).toEqual(['local-1'])
+ })
+
+ it('writes remote pins to a connection-scoped key, leaving the legacy key intact', () => {
+ pinSession('local-1')
+
+ setConnection(remoteA)
+ pinSession('a-1')
+
+ // The bare key still belongs to the local connection.
+ expect(readKey('hermes.desktop.pinnedSessions')).toBe(JSON.stringify(['local-1']))
+
+ // The remote pin landed under its own scope, not the shared key.
+ const scoped = readKey(
+ `hermes.desktop.pinnedSessions.remote.${encodeURIComponent('https://vps-a.example:8443')}.default`
+ )
+
+ expect(scoped).toBe(JSON.stringify(['a-1']))
+ })
+
+ it('never adopts legacy globally-keyed pins into a remote scope', () => {
+ // Pre-fix installs persisted every window's pins under the one global
+ // key. Ownership of those rows is unknowable, so a remote scope must
+ // start empty (the gateway's own `pinned` rows re-adopt what belongs
+ // there) rather than inherit the mixed set wholesale.
+ pinSession('mixed-1')
+ pinSession('mixed-2')
+
+ setConnection(remoteA)
+ expect($pinnedSessionIds.get()).toEqual([])
+ })
+
+ it('a null connection (reconnect blip) keeps the current scope', () => {
+ setConnection(remoteA)
+ pinSession('a-1')
+
+ // Disconnects publish null; that is a connectivity state, not a switch —
+ // the remote window must not repaint the local scope's lists.
+ setConnection(null)
+ expect($pinnedSessionIds.get()).toEqual(['a-1'])
+ })
+
+ it('scopes the manual session order and its flag per connection', () => {
+ $sidebarSessionOrderIds.set(['s1', 's2'])
+ $sidebarSessionOrderManual.set(true)
+
+ setConnection(remoteA)
+ expect($sidebarSessionOrderIds.get()).toEqual([])
+ expect($sidebarSessionOrderManual.get()).toBe(false)
+
+ $sidebarSessionOrderIds.set(['r1'])
+ $sidebarSessionOrderManual.set(true)
+
+ setConnection(localConn)
+ expect($sidebarSessionOrderIds.get()).toEqual(['s1', 's2'])
+ expect($sidebarSessionOrderManual.get()).toBe(true)
+
+ setConnection(remoteA)
+ expect($sidebarSessionOrderIds.get()).toEqual(['r1'])
+ })
+
+ it('scopes remembered session navigation per connection, not just per profile', () => {
+ setRememberedSessionId('local-session', 'default')
+
+ setConnection(remoteA)
+ // Same profile name on another gateway is a different backend: restoring
+ // the local window's session id here would navigate to a session this
+ // gateway has never seen.
+ expect(getRememberedSessionId('default')).toBeNull()
+
+ setRememberedSessionId('remote-session', 'default')
+ expect(getRememberedSessionId('default')).toBe('remote-session')
+
+ setConnection(localConn)
+ expect(getRememberedSessionId('default')).toBe('local-session')
+ })
+})
diff --git a/apps/desktop/src/store/layout.ts b/apps/desktop/src/store/layout.ts
index 6bac6980e98..5369912c33d 100644
--- a/apps/desktop/src/store/layout.ts
+++ b/apps/desktop/src/store/layout.ts
@@ -4,6 +4,7 @@ import { SIDEBAR_COLLAPSE_MEDIA_QUERY } from '@/app/layout-constants'
import { PANE_TOGGLE_REVEAL_EVENT } from '@/components/pane-shell'
import { isPaneVisible, revealTreePane } from '@/components/pane-shell/tree/store'
import { matchesQuery } from '@/hooks/use-media-query'
+import { connectionScopedAtom } from '@/lib/connection-scoped'
import { type Codec, Codecs, persistentAtom } from '@/lib/persisted'
import { arraysEqual, insertUniqueId, readKey } from '@/lib/storage'
@@ -90,13 +91,23 @@ export const $sidebarWidth: ReadableAtom<number> = computed($paneStates, states
return typeof override === 'number' ? override : SIDEBAR_DEFAULT_WIDTH
})
-export const $pinnedSessionIds = persistentAtom(SIDEBAR_PINNED_STORAGE_KEY, [] as string[], Codecs.stringArray)
-export const $sidebarSessionOrderIds = persistentAtom(
+// Pins and the manual session order are CONNECTION-scoped, not global: they
+// are lists of session ids owned by one gateway's state.db, and multiple
+// windows in this app can be connected to different gateways while sharing
+// one localStorage area. A global key here is how one gateway's pins bleed
+// into another window's sidebar (#77318). The local connection keeps the
+// bare legacy key; remote connections get their own namespaced keys.
+export const $pinnedSessionIds = connectionScopedAtom(SIDEBAR_PINNED_STORAGE_KEY, [] as string[], Codecs.stringArray)
+export const $sidebarSessionOrderIds = connectionScopedAtom(
SIDEBAR_SESSION_ORDER_STORAGE_KEY,
[] as string[],
Codecs.stringArray
)
-export const $sidebarSessionOrderManual = persistentAtom(SIDEBAR_SESSION_ORDER_MANUAL_STORAGE_KEY, false, Codecs.bool)
+export const $sidebarSessionOrderManual = connectionScopedAtom(
+ SIDEBAR_SESSION_ORDER_MANUAL_STORAGE_KEY,
+ false,
+ Codecs.bool
+)
export const $sidebarWorkspaceOrderIds = persistentAtom(
SIDEBAR_WORKSPACE_ORDER_STORAGE_KEY,
[] as string[],
diff --git a/apps/desktop/src/store/session-pin-sync.ts b/apps/desktop/src/store/session-pin-sync.ts
index dddbe741d00..e22bf9433dc 100644
--- a/apps/desktop/src/store/session-pin-sync.ts
+++ b/apps/desktop/src/store/session-pin-sync.ts
@@ -22,6 +22,7 @@
*/
import { setSessionPinnedRemote } from '@/hermes'
+import { onConnectionScopeChange } from '@/lib/connection-scoped'
import { $pinnedSessionIds, pinSession, unpinSession } from '@/store/layout'
import { $sessions, sessionMatchesStoredId, sessionPinId } from '@/store/session'
@@ -179,6 +180,10 @@ function reconcile(): void {
// Sync once, then re-sync on pin-set and session-list changes. Call once per app.
export function watchSessionPins(): void {
+ // A connection rescope repaints $pinnedSessionIds from the new backend's
+ // storage scope; the mirrored/pending/unconfirmed bookkeeping describes
+ // the PREVIOUS backend and must reset before that reload reconciles.
+ onConnectionScopeChange(resetSessionPinMirror)
reconcile()
$pinnedSessionIds.listen(reconcile)
$sessions.listen(reconcile)
diff --git a/apps/desktop/src/store/session.ts b/apps/desktop/src/store/session.ts
index 5b06249951b..5d638b44c2f 100644
--- a/apps/desktop/src/store/session.ts
+++ b/apps/desktop/src/store/session.ts
@@ -5,6 +5,7 @@ import { lastVisibleMessageIsUser } from '@/app/chat/thread-loading'
import type { ContextSuggestion } from '@/app/types'
import type { HermesConnection } from '@/global'
import type { ChatMessage } from '@/lib/chat-messages'
+import { activeConnectionScopeSuffix, rescopeConnectionScopedStores } from '@/lib/connection-scoped'
import { persistBoolean, persistString, storedBoolean, storedString } from '@/lib/storage'
import { syncCronModelImpactConnection } from '@/store/cron-model-impact-scope'
import type { SessionInfo, UsageStats } from '@/types/hermes'
@@ -42,7 +43,12 @@ const LAST_ROUTE_KEY = 'hermes.desktop.lastRoute'
function profileNavigationKey(base: string, profile: string): string {
const key = profile.trim() || 'default'
- return `${base}.profile.${encodeURIComponent(key)}`
+ // Also carries the CONNECTION scope: the same profile name on a different
+ // gateway is a different backend with its own sessions, and windows on
+ // different gateways share this localStorage area — restoring one
+ // gateway's remembered session under another navigates to a session that
+ // backend has never seen (#77318).
+ return `${base}.profile.${encodeURIComponent(key)}${activeConnectionScopeSuffix()}`
}
// Discard legacy global keys once per tick. A module-level flag avoids
@@ -660,6 +666,11 @@ export const $sessionPickerOpen = atom(false)
export const setConnection = (next: Updater<HermesConnection | null>) => {
updateAtom($connection, next)
+ // Repoint connection-scoped persistence (pins, manual session order,
+ // remembered navigation) at the new backend's storage scope before any
+ // consumer reconciles against it. A null descriptor (reconnect blip)
+ // keeps the current scope.
+ rescopeConnectionScopedStores($connection.get())
syncCronModelImpactConnection($connection.get())
}