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

Multiple Desktop windows share one renderer origin (one localStorage
area) while each window can be connected to a DIFFERENT gateway. The
sidebar pin set (hermes.desktop.pinnedSessions), the manual session
order, and the remembered last-session/route navigation keys were all
persisted under single global (or profile-only) keys, so two windows on
different gateways read and reconciled the same lists: pin-sync's
pullRemotePins() in one window adopted/dropped pins belonging to the
other window's backend, producing the overlapping mixed PINNED/SESSIONS
lists reported after the v0.19.1 update relaunch.

Introduce a connection-scope persistence layer (connectionScopedAtom in
src/lib/connection-scoped.ts): the local connection keeps the bare
legacy key (byte-identical for single-backend users, same contract as
backendScopeKey), while remote connections persist under
`<key>.remote.<encoded baseUrl>.<encoded profile>` — the shape
workspaceCwdKey already established. setConnection() rescopes every
scoped atom when the window's connection changes (null descriptors keep
the current scope, as with syncCronModelImpactConnection), and pin-sync
resets its mirrored/pending/unconfirmed bookkeeping on rescope so a
reconcile never PATCHes one gateway's pins to another.

Legacy globally-keyed values are deliberately not migrated into remote
scopes: ownership of rows accumulated by every window is unknowable
(the #67709 precedent), and backend-mirrored pins self-heal from the
gateway's own `pinned` rows.

Fixes #77318
This commit is contained in:
Teknium
2026-08-16 15:54:43 -07:00
parent d0d605ad0a
commit afe238ac7e
5 changed files with 346 additions and 4 deletions
+161
View File
@@ -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
}
}
}
@@ -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')
})
})
+14 -3
View File
@@ -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[],
@@ -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)
+12 -1
View File
@@ -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())
}