The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): trim connection-scoped tile salvage to the tab-persistence invariants (#120106, salvage #121983)
teknium13df15fd727ed
diff --git a/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.ts b/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.tsindex 3eff587799a..bf0b8f7538b 100644--- a/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.ts+++ b/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.ts@@ -12,7 +12,6 @@ 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 {@@ -113,10 +112,6 @@ 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@@ -125,27 +120,11 @@ export function useDesktopIntegrations({// This ref is a one-time lifecycle latch, not a mirror of reactive atom state.// eslint-disable-next-line no-restricted-syntaxuseEffect(() => {- 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) {@@ -153,11 +132,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 && !restoreAfterSwitchRef.current) {+ if (resumeLastSession === undefined) {return}- if (!resumeLastSession && !restoreAfterSwitchRef.current) {+ if (!resumeLastSession) {restoredRef.current = truereturn@@ -187,7 +166,6 @@ 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@@ -290,9 +268,7 @@ 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.tsindex e01249b09ca..8010b3fa053 100644--- a/apps/desktop/src/store/connections.test.ts+++ b/apps/desktop/src/store/connections.test.ts@@ -84,7 +84,6 @@ vi.mock('@/store/profile', () => ({const {$activeConnectionId,- $connectionContextRestore,$connectionsRegistry,$pendingConnectionId,initializeConnectionsRegistry,@@ -281,7 +280,6 @@ 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)@@ -411,7 +409,6 @@ 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()@@ -598,7 +595,6 @@ 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)@@ -901,7 +897,6 @@ 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.tsindex b3ba4b7b6d5..5e72929dc90 100644--- a/apps/desktop/src/store/connections.ts+++ b/apps/desktop/src/store/connections.ts@@ -61,16 +61,8 @@ const $lastProfileByConnection = atom<Record<string, string>>(storedStringRecordlet pendingTarget: null | string = nulllet restoreAttempted = falselet switchRevision = 0-let contextRestoreSequence = 0export 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))@@ -121,9 +113,7 @@ export function _resetConnectionsForTests(): void {pendingTarget = nullrestoreAttempted = falseswitchRevision = 0- contextRestoreSequence = 0$pendingConnectionId.set(null)- $connectionContextRestore.set(null)}export function setConnectionsRegistry(registry: DesktopConnectionsRegistry): void {@@ -535,13 +525,6 @@ 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.tsindex 9276117824c..d1b9f2f0af6 100644--- a/apps/desktop/src/store/session-states.ts+++ b/apps/desktop/src/store/session-states.ts@@ -1160,6 +1160,7 @@ function loadTilesByProfile(): Record<string, StoredTile[]> {// 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@@ -1218,15 +1219,19 @@ 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()@@ -1318,17 +1323,21 @@ function saveTileBucket(bucket: string, tiles: SessionTile[]) {if (!isSecondaryWindow() && !isBrowserWindow()) {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()})diff --git a/apps/desktop/src/store/session-tiles-connection-scope.test.ts b/apps/desktop/src/store/session-tiles-connection-scope.test.tsindex ba93924395a..815d9d4b33a 100644--- a/apps/desktop/src/store/session-tiles-connection-scope.test.ts+++ b/apps/desktop/src/store/session-tiles-connection-scope.test.ts@@ -4,27 +4,24 @@ import type { HermesConnection } from '@/global'import { $activeGatewayProfile } from './profile'import { $selectedStoredSessionId, setConnection } from './session'-import {- $sessionTiles,- closeSessionTile,- dropTilesForProfile,- openSessionTile,- reopenLastClosedTile-} from './session-states'+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',@@ -127,66 +124,4 @@ describe('session tiles across registered backend switches (#120106)', () => {'legacy-unknown-owner'])})-- it('drops an id-less remote profile without deleting same-named local tabs', () => {- const name = 'direct-remote-delete-regression'- const localProfile = { ...local, profile: name } as HermesConnection- const directRemote = {- baseUrl: 'https://legacy.example:8443',- mode: 'remote',- profile: name- } as HermesConnection- $activeGatewayProfile.set(name)- setConnection(localProfile)- openSessionTile('local-keep', 'right')- openSessionTile('local-bot', 'right', undefined, undefined, {- workspaceMode: 'bots',- workspaceOwnerKey: `local::${name}`,- ownerRoute: { connectionId: 'local', profile: name }- })-- setConnection(directRemote)- openSessionTile('remote-closed', 'right')- closeSessionTile('remote-closed')- openSessionTile('remote-open', 'right')-- dropTilesForProfile(name)- expect($sessionTiles.get().map(tile => tile.storedSessionId)).toEqual(['local-bot'])- reopenLastClosedTile()- expect($sessionTiles.get().map(tile => tile.storedSessionId)).toEqual(['local-bot'])- const persisted = JSON.parse(window.localStorage.getItem('hermes.desktop.sessionTiles.v2') || '{}')- expect(persisted[`conn:url:${directRemote.baseUrl}::${name}`]).toBeUndefined()- expect(persisted[name]?.map((tile: { storedSessionId: string }) => tile.storedSessionId)).toEqual(['local-keep'])- expect(persisted.__bots_workspace__?.map((tile: { storedSessionId: string }) => tile.storedSessionId)).toEqual([- 'local-bot'- ])-- setConnection(localProfile)- expect($sessionTiles.get().map(tile => tile.storedSessionId)).toEqual(['local-keep', 'local-bot'])- })-- it('drops ambient registered-remote tabs and bots without touching local ones', () => {- const name = 'ambient-remote-delete-regression'- $activeGatewayProfile.set(name)- setConnection({ ...local, profile: name } as HermesConnection)- openSessionTile('local-keep', 'right')- openSessionTile('local-bot', 'right', undefined, undefined, {- workspaceMode: 'bots',- workspaceOwnerKey: `local::${name}`,- ownerRoute: { connectionId: 'local', profile: name }- })-- setConnection({ ...remote, profile: name } as HermesConnection)- openSessionTile('remote-open', 'right')- openSessionTile('remote-bot', 'right', undefined, undefined, {- workspaceMode: 'bots',- workspaceOwnerKey: `homelab::${name}`,- ownerRoute: { connectionId: 'homelab', profile: name }- })-- dropTilesForProfile(name)- expect($sessionTiles.get().map(tile => tile.storedSessionId)).toEqual(['local-bot'])- setConnection({ ...local, profile: name } as HermesConnection)- expect($sessionTiles.get().map(tile => tile.storedSessionId)).toEqual(['local-keep', 'local-bot'])- })})