Skip to content

The agent that grows with you

fix(desktop): restore connection-scoped tabs and chat on backend switch

Teo | Nexcore68f724b3b80f
diff --git a/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.ts b/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.ts
index bf0b8f7538b..3eff587799a 100644
--- a/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.ts
+++ b/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.ts
@@ -12,6 +12,7 @@ import { resolveDeepLinkAction } from '@/lib/deeplink-routes'
import { pathFromHermesDeepLink, resolveHermesOpenPath } from '@/lib/hermes-open-target'
import { storedSessionIdForNotification } from '@/lib/session-ids'
import { announceNewSessionDraftKey } from '@/store/composer'
+import { $activeConnectionId, $connectionContextRestore } from '@/store/connections'
import { requestMcpInstallFromDeepLink } from '@/store/mcp-deeplink-install'
import { startMcpHealthChecker, stopMcpHealthChecker } from '@/store/mcp-health'
import {
@@ -112,6 +113,10 @@ export function useDesktopIntegrations({
}, [])
const restoredRef = useRef(false)
+ const connectionRestoreRequest = useStore($connectionContextRestore)
+ const activeConnectionId = useStore($activeConnectionId)
+ const handledConnectionRestoreRef = useRef(0)
+ const restoreAfterSwitchRef = useRef(false)
const diskPluginsScanPending = useStore($diskPluginsScanPending)
// Wait until boot has adopted the primary profile, then restore that profile's
@@ -120,11 +125,27 @@ export function useDesktopIntegrations({
// This ref is a one-time lifecycle latch, not a mirror of reactive atom state.
// eslint-disable-next-line no-restricted-syntax
useEffect(() => {
+ if (
+ connectionRestoreRequest &&
+ connectionRestoreRequest.sequence > handledConnectionRestoreRef.current &&
+ connectionRestoreRequest.connectionId === activeConnectionId &&
+ connectionRestoreRequest.profile === activeProfile
+ ) {
+ handledConnectionRestoreRef.current = connectionRestoreRequest.sequence
+ restoreAfterSwitchRef.current = true
+ restoredRef.current = false
+ }
+
if (!profileReady || isHudWindow() || isBrowserWindow()) {
return
}
if (!restoredRef.current) {
+ // The switch first clears the outgoing runtime and navigates to a safe
+ // draft. Never interpret its old URL as a route on the new backend.
+ if (restoreAfterSwitchRef.current && locationPathname !== NEW_CHAT_ROUTE) {
+ return
+ }
// Only cold-start navigation at the default route is replaceable; a deep
// link or hidden-then-shown window keeps its explicit destination.
if (locationPathname === NEW_CHAT_ROUTE) {
@@ -132,11 +153,11 @@ export function useDesktopIntegrations({
// record answers, then either restore below or stay on the fresh chat.
// Remembered ids keep being written either way, so flipping the switch
// back on resumes from the very next launch.
- if (resumeLastSession === undefined) {
+ if (resumeLastSession === undefined && !restoreAfterSwitchRef.current) {
return
}
- if (!resumeLastSession) {
+ if (!resumeLastSession && !restoreAfterSwitchRef.current) {
restoredRef.current = true
return
@@ -166,6 +187,7 @@ export function useDesktopIntegrations({
}
restoredRef.current = true
+ restoreAfterSwitchRef.current = false
// A delegate child (source='subagent') is never a restorable
// destination: it is invisible in the sidebar, so resuming one leaves
@@ -268,7 +290,9 @@ export function useDesktopIntegrations({
setRememberedRoute(locationPathname, activeProfile)
}
}, [
+ activeConnectionId,
activeProfile,
+ connectionRestoreRequest,
diskPluginsScanPending,
locationPathname,
navigate,
diff --git a/apps/desktop/src/store/connections.test.ts b/apps/desktop/src/store/connections.test.ts
index 8010b3fa053..e01249b09ca 100644
--- a/apps/desktop/src/store/connections.test.ts
+++ b/apps/desktop/src/store/connections.test.ts
@@ -84,6 +84,7 @@ vi.mock('@/store/profile', () => ({
const {
$activeConnectionId,
+ $connectionContextRestore,
$connectionsRegistry,
$pendingConnectionId,
initializeConnectionsRegistry,
@@ -280,6 +281,7 @@ describe('selectConnection', () => {
expect(api).not.toHaveBeenCalled()
expect(beforeConnectionSwitch).toHaveBeenCalledTimes(1)
expect(requestFreshSession).toHaveBeenCalledTimes(1)
+ expect($connectionContextRestore.get()).toMatchObject({ connectionId: 'homelab', profile: 'default' })
expect(wipeSessionListsForGatewaySwitch).toHaveBeenCalledTimes(1)
expect($newChatProfile.get()).toBe('default')
expect(refreshActiveProfile).toHaveBeenCalledTimes(1)
@@ -409,6 +411,7 @@ describe('selectConnection', () => {
expect($activeSessionId.get()).toBe('a93bb39d')
expect($gatewaySwitching.get()).toBe(false)
expect(requestFreshSession).not.toHaveBeenCalled()
+ expect($connectionContextRestore.get()).toBeNull()
expect($newChatProfile.get()).toBeNull()
expect($pendingConnectionId.get()).toBeNull()
expect(setLastUsed).not.toHaveBeenCalled()
@@ -595,6 +598,7 @@ describe('selectConnection', () => {
expect($connection.get()?.connectionId).toBe('work-vps')
expect(recoverActiveSourceAfterFailedGatewaySwitch).not.toHaveBeenCalled()
expect(requestFreshSession).toHaveBeenCalledTimes(1)
+ expect($connectionContextRestore.get()).toMatchObject({ connectionId: 'work-vps', profile: 'default' })
expect(setLastUsed).toHaveBeenCalledTimes(1)
expect(setLastUsed).toHaveBeenCalledWith('work-vps')
expect($gatewaySwitching.get()).toBe(false)
@@ -897,6 +901,7 @@ describe('selectConnection', () => {
expect(ensureGatewayAgent).not.toHaveBeenCalled()
expect(setLastUsed).toHaveBeenCalledWith('homelab')
expect($showAllProfiles.get()).toBe(true)
+ expect($connectionContextRestore.get()).toBeNull()
})
it('boot restore proceeds after the descriptor wait deadline (bounded wait)', { timeout: 30_000 }, async () => {
diff --git a/apps/desktop/src/store/connections.ts b/apps/desktop/src/store/connections.ts
index 5e72929dc90..b3ba4b7b6d5 100644
--- a/apps/desktop/src/store/connections.ts
+++ b/apps/desktop/src/store/connections.ts
@@ -61,8 +61,16 @@ const $lastProfileByConnection = atom<Record<string, string>>(storedStringRecord
let pendingTarget: null | string = null
let restoreAttempted = false
let switchRevision = 0
+let contextRestoreSequence = 0
export const $pendingConnectionId = atom<null | string>(null)
+/** Winning user-initiated backend switches ask the renderer to restore that
+ * backend's remembered view after its fresh-draft safety barrier lands. */
+export const $connectionContextRestore = atom<null | {
+ connectionId: string
+ profile: string
+ sequence: number
+}>(null)
$lastProfileByConnection.subscribe(value => persistStringRecord(LAST_PROFILE_STORAGE_KEY, value))
@@ -113,7 +121,9 @@ export function _resetConnectionsForTests(): void {
pendingTarget = null
restoreAttempted = false
switchRevision = 0
+ contextRestoreSequence = 0
$pendingConnectionId.set(null)
+ $connectionContextRestore.set(null)
}
export function setConnectionsRegistry(registry: DesktopConnectionsRegistry): void {
@@ -525,6 +535,13 @@ export async function selectConnection(connectionId: string, options: SelectConn
$newChatProfile.set(targetProfile)
captureNewChatSource()
requestFreshSession()
+ if (!restoreOnBoot && currentConnectionId !== null && currentConnectionId !== connectionId) {
+ $connectionContextRestore.set({
+ connectionId,
+ profile: targetProfile,
+ sequence: ++contextRestoreSequence
+ })
+ }
await refreshActiveProfile()
}
} catch (error) {
diff --git a/apps/desktop/src/store/session-states.ts b/apps/desktop/src/store/session-states.ts
index 30c2ae9a955..a564f9646ab 100644
--- a/apps/desktop/src/store/session-states.ts
+++ b/apps/desktop/src/store/session-states.ts
@@ -16,7 +16,7 @@
* itself here as the delegate so tile UI stays dependency-light.
*/
-import { type GatewayEvent, LOCAL_CONNECTION_ID, registryBackendScopeKey } from '@hermes/shared'
+import { backendScopeKey, type GatewayEvent, LOCAL_CONNECTION_ID, registryBackendScopeKey } from '@hermes/shared'
import { atom, computed } from 'nanostores'
import { setSessionOwnerResolver } from '@/api/client'
@@ -1066,12 +1066,9 @@ export interface SessionTileWorkspaceScope {
workspaceTabTitle?: string
}
-// Tiles are persisted PER PROFILE: a session belongs to one profile, and the
-// single live gateway is scoped to one profile at a time, so a tile only makes
-// sense while its profile is active. Switching profiles swaps the visible set
-// (and drops runtime bindings so each tile re-resumes against the now-current
-// gateway — which also settles the "tile resumes against the wrong backend" and
-// "stale runtime after respawn" bugs by construction).
+// Tiles are persisted per connection and profile: same-named profiles on two
+// backends own different sessions. Switching either scope swaps the visible
+// set, with runtime bindings dropped so tiles re-resume on their own gateway.
const TILES_KEY = 'hermes.desktop.sessionTiles.v2'
const LEGACY_TILES_KEY = 'hermes.desktop.sessionTiles.v1'
const TILE_PANE_PREFIX = 'session-tile:'
@@ -1152,20 +1149,37 @@ function parseTileList(value: unknown): StoredTile[] {
}
function loadTilesByProfile(): Record<string, StoredTile[]> {
- const byProfile: Record<string, StoredTile[]> = {}
+ const byProfile: Record<string, StoredTile[]> = Object.create(null)
const parsed = readJson<unknown>(TILES_KEY)
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
for (const [profile, list] of Object.entries(parsed as Record<string, unknown>)) {
const tiles = parseTileList(list)
- const key = profile === BOTS_TILE_BUCKET ? BOTS_TILE_BUCKET : normalizeProfileKey(profile)
+ // Existing profile-only buckets belong to the local connection. New
+ // remote buckets carry the same backend scope key as the socket pool;
+ // never collapse them back into a same-named local profile on reload.
+ const separator = profile.lastIndexOf('::')
+ const isScopedBucket = profile.startsWith('conn:') && separator > 'conn:'.length
+ const key =
+ profile === BOTS_TILE_BUCKET
+ ? BOTS_TILE_BUCKET
+ : isScopedBucket
+ ? backendScopeKey(
+ profile.slice('conn:'.length, separator),
+ normalizeProfileKey(profile.slice(separator + 2))
+ )
+ : normalizeProfileKey(profile)
if (tiles.length > 0) {
const sessionTiles = tiles.filter(tile => tile.workspaceMode !== 'bots')
const botTiles = tiles.filter(tile => tile.workspaceMode === 'bots')
- if (sessionTiles.length > 0) {
- byProfile[key] = [...(byProfile[key] ?? []), ...sessionTiles]
+ for (const tile of sessionTiles) {
+ // Old profile-only buckets can contain remote tiles whose owner was
+ // already recorded. Preserve those tabs on upgrade; unknown owners
+ // stay local rather than being guessed onto another backend.
+ const scope = isScopedBucket ? key : backendScopeKey(tile.ownerRoute?.connectionId, key)
+ byProfile[scope] = [...(byProfile[scope] ?? []), tile]
}
if (botTiles.length > 0) {
@@ -1204,6 +1218,18 @@ const tilesByProfile = loadTilesByProfile()
// window's primary backend and never changes on a rail switch, so keying on
// it left the previous profile's tiles registered (phantom "Session" tabs).
const profileKey = () => normalizeProfileKey($activeGatewayProfile.get())
+const tileConnectionScopeId = (connection: ReturnType<typeof $connection.get>) => {
+ const id = connection?.connectionId?.trim()
+ if (id) {
+ return id
+ }
+ // Older direct remotes have no registry id. Keep them separate from local
+ // and from each other instead of writing into the local profile bucket.
+ return connection?.mode === 'remote' ? `url:${connection.baseUrl || 'remote'}` : null
+}
+let tileConnectionId = tileConnectionScopeId($connection.get())
+const tileScopeKey = () => backendScopeKey(tileConnectionId, profileKey())
+let visibleTileScope = tileScopeKey()
// Runtime ids are process-scoped — never trust a persisted one, so the live
// atom hydrates from the stored (runtime-less) tiles for the active profile.
@@ -1240,7 +1266,7 @@ export function setZoneParkedTiles(zoneKey: string, storedSessionIds: readonly s
export const $sessionTiles = atom<SessionTile[]>(
isSecondaryWindow() || isBrowserWindow()
? []
- : [...(tilesByProfile[profileKey()] ?? []), ...(tilesByProfile[BOTS_TILE_BUCKET] ?? [])]
+ : [...(tilesByProfile[visibleTileScope] ?? []), ...(tilesByProfile[BOTS_TILE_BUCKET] ?? [])]
)
function persistTiles() {
@@ -1259,9 +1285,9 @@ function saveTiles(tiles: SessionTile[]) {
const botTiles = stored.filter(tile => tile.workspaceMode === 'bots')
if (sessionTiles.length > 0) {
- tilesByProfile[profileKey()] = sessionTiles
+ tilesByProfile[visibleTileScope] = sessionTiles
} else {
- delete tilesByProfile[profileKey()]
+ delete tilesByProfile[visibleTileScope]
}
if (botTiles.length > 0) {
@@ -1286,13 +1312,25 @@ function saveTileBucket(bucket: string, tiles: SessionTile[]) {
persistTiles()
}
-// Profile switch: surface the new profile's tiles with runtime ids cleared so
-// they re-resume against the now-current gateway. (Fires immediately on
-// subscribe; harmless — the init value already matches.) A secondary window
-// never carries tiles, so it stays out of this entirely.
+// Profile or connection switch: surface only this backend's stored tiles.
+// Null connection is a reconnect blip, not a switch; keep the last scope.
+// A secondary window never carries tiles, so it stays out entirely.
if (!isSecondaryWindow() && !isBrowserWindow()) {
- $activeGatewayProfile.subscribe(() => {
- $sessionTiles.set([...(tilesByProfile[profileKey()] ?? []), ...(tilesByProfile[BOTS_TILE_BUCKET] ?? [])])
+ const restoreVisibleTiles = () => {
+ const nextScope = tileScopeKey()
+ if (nextScope === visibleTileScope) {
+ return
+ }
+ visibleTileScope = nextScope
+ $sessionTiles.set([...(tilesByProfile[nextScope] ?? []), ...(tilesByProfile[BOTS_TILE_BUCKET] ?? [])])
+ }
+ $activeGatewayProfile.subscribe(restoreVisibleTiles)
+ $connection.subscribe(connection => {
+ if (!connection) {
+ return
+ }
+ tileConnectionId = tileConnectionScopeId(connection)
+ restoreVisibleTiles()
})
}
@@ -2426,7 +2464,7 @@ export function reuseBlankDraftTile(
// tiles themselves, so ⌘⇧T after a profile switch never resurrects the other
// profile's session. The tile's placement is remembered so it returns in place.
const closedTilesByProfile: Record<string, SessionTile[]> = {}
-const closedStack = (): SessionTile[] => (closedTilesByProfile[profileKey()] ??= [])
+const closedStack = (): SessionTile[] => (closedTilesByProfile[visibleTileScope] ??= [])
export function closeSessionTile(storedSessionId: string) {
const tile = $sessionTiles.get().find(t => t.storedSessionId === storedSessionId)
@@ -2533,6 +2571,7 @@ export function dropTilesForProfile(
const routeProfile = route?.profile ? normalizeProfileKey(route.profile) : ''
const routeTarget = route?.targetProfile ? normalizeProfileKey(route.targetProfile) : ''
const routeConnection = String(route?.connectionId ?? '').trim()
+ const removedScope = backendScopeKey(routeConnection, routeProfile || name)
const ownerMatches = (owner: SessionProfileRoute | undefined): boolean => {
if (!owner) {
@@ -2570,7 +2609,8 @@ export function dropTilesForProfile(
// The profile's own sessions bucket (Bot tiles live in the shared bucket
// and are keyed by ownerRoute, not by bucket).
- delete tilesByProfile[name]
+ delete tilesByProfile[removedScope]
+ delete closedTilesByProfile[removedScope]
const botTiles = tilesByProfile[BOTS_TILE_BUCKET]
@@ -2596,7 +2636,7 @@ export function dropTilesForProfile(
? !ownerMatches(tile.ownerRoute)
: // Session tiles map to the owning profile's own bucket: drop only when
// the deleted profile IS the live gateway's profile.
- profileKey() !== name
+ visibleTileScope !== removedScope
)
if (next.length !== live.length) {
diff --git a/apps/desktop/src/store/session-tiles-connection-scope.test.ts b/apps/desktop/src/store/session-tiles-connection-scope.test.ts
new file mode 100644
index 00000000000..ba70c4488ec
--- /dev/null
+++ b/apps/desktop/src/store/session-tiles-connection-scope.test.ts
@@ -0,0 +1,124 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import type { HermesConnection } from '@/global'
+
+import { $activeGatewayProfile } from './profile'
+import { $selectedStoredSessionId, setConnection } from './session'
+import { $sessionTiles, openSessionTile } from './session-states'
+
+const profile = 'connection-scope-regression'
+const local = {
+ baseUrl: 'http://127.0.0.1:8000',
+ connectionId: 'local',
+ mode: 'local',
+ profile
+} as unknown as HermesConnection
+const remote = {
+ baseUrl: 'https://homelab.example:8443',
+ connectionId: 'homelab',
+ mode: 'remote',
+ profile
+} as unknown as HermesConnection
+const otherRemote = {
+ baseUrl: 'https://other.example:8443',
+ connectionId: 'other-remote',
+ mode: 'remote',
+ profile
+} as unknown as HermesConnection
+
+beforeEach(() => {
+ window.localStorage.clear()
+ setConnection(local)
+ $activeGatewayProfile.set(profile)
+ $selectedStoredSessionId.set(null)
+ $sessionTiles.set([])
+})
+
+describe('session tiles across registered backend switches (#120106)', () => {
+ it('keeps each same-named profile on its own connection and restores its tabs on return', async () => {
+ openSessionTile('stored-local', 'right', undefined, undefined, {
+ workspaceMode: 'sessions',
+ ownerRoute: { connectionId: 'local', profile }
+ })
+ expect($sessionTiles.get().map(tile => tile.storedSessionId)).toEqual(['stored-local'])
+
+ setConnection(remote)
+ expect($sessionTiles.get().map(tile => tile.storedSessionId)).toEqual([])
+
+ openSessionTile('stored-remote', 'right', undefined, undefined, {
+ workspaceMode: 'sessions',
+ ownerRoute: { connectionId: 'homelab', profile }
+ })
+ expect($sessionTiles.get().map(tile => tile.storedSessionId)).toEqual(['stored-remote'])
+
+ // A disconnect is not a source change; another remote with the same
+ // profile is a different workspace.
+ setConnection(null)
+ expect($sessionTiles.get().map(tile => tile.storedSessionId)).toEqual(['stored-remote'])
+ setConnection(otherRemote)
+ expect($sessionTiles.get().map(tile => tile.storedSessionId)).toEqual([])
+ setConnection(remote)
+ expect($sessionTiles.get().map(tile => tile.storedSessionId)).toEqual(['stored-remote'])
+
+ setConnection(local)
+ expect($sessionTiles.get().map(tile => tile.storedSessionId)).toEqual(['stored-local'])
+ expect($sessionTiles.get()[0]?.ownerRoute?.connectionId).toBe('local')
+
+ setConnection(remote)
+ expect($sessionTiles.get().map(tile => tile.storedSessionId)).toEqual(['stored-remote'])
+ expect($sessionTiles.get()[0]?.ownerRoute?.connectionId).toBe('homelab')
+
+ // A restart must keep the composite key; profile-only migration would
+ // silently fold remote tabs back into the local bucket.
+ const persisted = JSON.parse(window.localStorage.getItem('hermes.desktop.sessionTiles.v2') || '{}')
+ expect(persisted[profile]?.map((tile: { storedSessionId: string }) => tile.storedSessionId)).toEqual([
+ 'stored-local'
+ ])
+ expect(
+ persisted[`conn:homelab::${profile}`]?.map((tile: { storedSessionId: string }) => tile.storedSessionId)
+ ).toEqual(['stored-remote'])
+
+ vi.resetModules()
+ const reloadedSession = await import('./session')
+ const reloadedProfile = await import('./profile')
+ const reloadedTiles = await import('./session-states')
+ reloadedProfile.$activeGatewayProfile.set(profile)
+ reloadedSession.setConnection(remote)
+ expect(reloadedTiles.$sessionTiles.get().map(tile => tile.storedSessionId)).toEqual(['stored-remote'])
+ reloadedSession.setConnection(local)
+ expect(reloadedTiles.$sessionTiles.get().map(tile => tile.storedSessionId)).toEqual(['stored-local'])
+
+ // A source-scoped deletion must leave the same-named local profile alone.
+ reloadedTiles.dropTilesForProfile(profile, { connectionId: 'homelab', profile })
+ reloadedSession.setConnection(remote)
+ expect(reloadedTiles.$sessionTiles.get()).toEqual([])
+ reloadedSession.setConnection(local)
+ expect(reloadedTiles.$sessionTiles.get().map(tile => tile.storedSessionId)).toEqual(['stored-local'])
+ })
+
+ it('migrates legacy remote-owned tabs out of a profile-only bucket', async () => {
+ window.localStorage.setItem(
+ 'hermes.desktop.sessionTiles.v2',
+ JSON.stringify({
+ [profile]: [
+ { dir: 'right', ownerRoute: { connectionId: 'local', profile }, storedSessionId: 'legacy-local' },
+ { dir: 'right', ownerRoute: { connectionId: 'homelab', profile }, storedSessionId: 'legacy-remote' },
+ { dir: 'right', storedSessionId: 'legacy-unknown-owner' }
+ ]
+ })
+ )
+ vi.resetModules()
+ const session = await import('./session')
+ const gatewayProfile = await import('./profile')
+ const tiles = await import('./session-states')
+ gatewayProfile.$activeGatewayProfile.set(profile)
+
+ session.setConnection(remote)
+ expect(tiles.$sessionTiles.get().map(tile => tile.storedSessionId)).toEqual(['legacy-remote'])
+ session.setConnection(local)
+ expect(tiles.$sessionTiles.get().map(tile => tile.storedSessionId)).toEqual([
+ 'legacy-local',
+ 'legacy-unknown-owner'
+ ])
+ })
+})