Skip to content

The agent that grows with you

fix(desktop): drop stale persisted session owner hints on resume

Brooklyn Nicholson430ada18caa6
diff --git a/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.test.tsx b/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.test.tsx
index b986fade191..42a8e0d4c33 100644
--- a/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.test.tsx
+++ b/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.test.tsx
@@ -10,7 +10,12 @@ import { $hubInstalledOverride } from '@/store/hub-actions'
import { requestMcpInstallFromDeepLink } from '@/store/mcp-deeplink-install'
import { requestPluginCatalogInstallFromDeepLink } from '@/store/plugin-catalog-install'
import { openPluginInstallRequest } from '@/store/plugin-install-request'
-import { _resetLegacyDiscardForTests } from '@/store/session'
+import {
+ _resetLegacyDiscardForTests,
+ _resetSessionOwnerHintsForTests,
+ getSessionOwnerHint,
+ setSessionOwnerHint
+} from '@/store/session'
import { dropSessionState, publishSessionState } from '@/store/session-states'
import type * as WindowsStore from '@/store/windows'
import type { SessionInfo } from '@/types/hermes'
@@ -79,6 +84,9 @@ describe('useDesktopIntegrations', () => {
// Every test starts as a main window; only the HUD describe flips this.
hudWindowMock.mockReturnValue(false)
peerWindowMock.mockReturnValue(false)
+ // Isolated owner-hint state per test: persisted hints are global
+ // module state that would otherwise leak between restore cases.
+ _resetSessionOwnerHintsForTests({ storage: true })
// Stub the desktop bridge so the hook's useEffect callbacks don't try to
// reach real Electron IPC. The established desktop-test pattern assigns a
@@ -423,6 +431,22 @@ describe('useDesktopIntegrations', () => {
// The route and session match the active profile — should restore.
expect(navigate).toHaveBeenCalledWith('/ai-session', { replace: true })
})
+
+ it('drops a legacy local owner hint when auto-restoring an untagged row (#97809)', () => {
+ // Older builds persisted a `local` hint for a session whose row carries
+ // no connection tag (the legacy primary-SSH path). At click time
+ // openStoredSession clears it; the boot auto-restore must too, or the
+ // pathname-driven resume routes a remote session to the Mac backend.
+ window.localStorage.setItem('hermes.desktop.lastSessionId.profile.default', 'ssh-session')
+ setSessionOwnerHint('ssh-session', { connectionId: 'local', profile: 'default' })
+
+ const sessions = [session({ id: 'ssh-session', profile: 'default' })]
+
+ render({ activeProfile: 'default', profileReady: true, sessions })
+
+ expect(navigate).toHaveBeenCalledWith('/ssh-session', { replace: true })
+ expect(getSessionOwnerHint('ssh-session')).toBeUndefined()
+ })
})
describe('two profiles with distinct sessions', () => {
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 9237c642d5a..edfc854e2e8 100644
--- a/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.ts
+++ b/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.ts
@@ -27,13 +27,16 @@ import { openPluginInstallRequest } from '@/store/plugin-install-request'
import { openFolderAsProject } from '@/store/projects'
import {
$selectedStoredSessionId,
+ forgetSessionOwnerHintsForSession,
getRememberedRoute,
getRememberedSessionId,
resolveComposerSessionKey,
sessionBelongsToProfile,
sessionMatchesStoredId,
+ sessionOwnerRouteFromRow,
setRememberedRoute,
- setRememberedSessionId
+ setRememberedSessionId,
+ setSessionOwnerHint
} from '@/store/session'
import { $botChatScopes, $sessionTiles, storedSessionIdForRuntimeId } from '@/store/session-states'
import { onSessionsChanged } from '@/store/session-sync'
@@ -183,6 +186,29 @@ export function useDesktopIntegrations({
// synchronous there; an unlisted id resolves by id below.
const rowFor = (id: string) => sessions.find(session => sessionMatchesStoredId(session, id))
+ // The same owner hygiene the click path (openStoredSession) applies to
+ // a list row: an untagged row is owned by the ambient backend, so a
+ // stale explicit hint (older builds persisted `local` for legacy
+ // primary-SSH rows) must not survive into the pathname-driven resume —
+ // it would dial the Mac backend for a remote session and die with
+ // "session not found" (#97809). A connection-tagged row pins its exact
+ // route instead, exactly as a clicked row does.
+ const repairOwnerHintsForRestore = (id: string) => {
+ const row = rowFor(id)
+
+ if (!row) {
+ return
+ }
+
+ const ownerRoute = sessionOwnerRouteFromRow(row)
+
+ if (ownerRoute) {
+ setSessionOwnerHint(id, ownerRoute)
+ } else {
+ forgetSessionOwnerHintsForSession(id)
+ }
+ }
+
const restorableRouteSession = routeSession && rowFor(routeSession)?.source !== 'subagent' ? routeSession : null
if (
@@ -194,6 +220,10 @@ export function useDesktopIntegrations({
// The user may have started typing on the fresh chat while the
// backend was still coming up; the composer moves that draft onto
// the restored session when its scope swaps (#114122).
+ if (routeSession) {
+ repairOwnerHintsForRestore(routeSession)
+ }
+
announceNewSessionDraftKey(routeSession && resolveComposerSessionKey(routeSession, sessions))
navigate(route, { replace: true })
@@ -210,6 +240,7 @@ export function useDesktopIntegrations({
// Fast path: a listed, non-delegate row restores directly, exactly
// as before — no by-id fetch on the common cold start.
if (rowFor(last)?.source !== 'subagent' && sessionBelongsToProfile(sessions, last, activeProfile)) {
+ repairOwnerHintsForRestore(last)
announceNewSessionDraftKey(resolveComposerSessionKey(last, sessions))
navigate(sessionRoute(last), { replace: true })
@@ -229,6 +260,7 @@ export function useDesktopIntegrations({
return
}
+ repairOwnerHintsForRestore(remembered)
announceNewSessionDraftKey(resolveComposerSessionKey(remembered, sessions))
setRememberedSessionId(remembered, activeProfile)
navigate(sessionRoute(remembered), { replace: true })
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx
index 0505f0a0ab7..649fc22ce97 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx
@@ -86,6 +86,7 @@ import {
setNewChatWorkspaceTarget,
setResumeFailedSessionId,
setSelectedStoredSessionId,
+ setSessionOwnerHint,
setSessions,
setSessionStartedAt,
setTurnStartedAt,
@@ -1734,6 +1735,13 @@ describe('resumeSession failure recovery', () => {
$sessionMutationsInFlight.set(new Set())
clearClarifyRequest()
clearSessionTodos('runtime-1')
+ // Persisted owner hints are global module state; the hint-hygiene tests
+ // below write them and must not leak into later describes' resumes.
+ _resetSessionOwnerHintsForTests()
+ // Same for this describe's source-override: mockReset() restores the
+ // default-preserving spy (the real registry read), unlike
+ // restoreAllMocks() below, which is a no-op for factory-created vi.fn().
+ vi.mocked(activeGatewayConnectionId).mockReset()
vi.restoreAllMocks()
})
@@ -2613,6 +2621,73 @@ describe('resumeSession failure recovery', () => {
expect($resumeFailedSessionId.get()).toBe('stored-1')
expect($activeSessionId.get()).toBeNull()
})
+
+ // #97809 remaining edge: older builds persisted a `local` owner hint for
+ // sessions whose rows carry no connection tag (the legacy primary-SSH
+ // path). Clicks repair it (openStoredSession drops the hint for untagged
+ // rows), but every pathname-driven resume (boot auto-restore, reconnect
+ // re-resume, stranded-view self-heal) funnels through here and used to
+ // trust the hint verbatim — dialing the Mac backend for a remote session
+ // and dying with "session not found". A hint naming a connection that is
+ // not this window's live primary is stale by definition and must be
+ // dropped, not honored.
+ it('drops a legacy local owner hint when the window primary is a remote connection (#97809)', async () => {
+ _resetSessionOwnerHintsForTests()
+ setSessionOwnerHint('stored-1', { connectionId: 'local', profile: 'default' })
+ // The window's live primary is the SSH connection, not `local`.
+ vi.mocked(activeGatewayConnectionId).mockReturnValue('ssh-proxmox')
+
+ const requestGateway = vi.fn(async (method: string) => {
+ if (method === 'session.resume') {
+ return {
+ info: {},
+ message_count: 0,
+ messages: [],
+ resumed: 'stored-1',
+ session_id: 'runtime-1',
+ session_key: 'stored-1'
+ } as never
+ }
+
+ return {} as never
+ })
+
+ vi.mocked(getLatestSessionMessages).mockResolvedValue({ messages: [], session_id: 'stored-1' } as never)
+
+ await runResume(requestGateway)
+
+ // The poisoned hint is repaired, not just ignored: a stale route left
+ // in the map re-poisons the next resume and every session-scoped RPC
+ // dispatch that consults the hint rung.
+ expect(getSessionOwnerHint('stored-1')).toBeUndefined()
+ })
+
+ it('keeps a current owner hint that names the live primary connection', async () => {
+ _resetSessionOwnerHintsForTests()
+ setSessionOwnerHint('stored-1', { connectionId: 'ssh-proxmox', profile: 'default' })
+ vi.mocked(activeGatewayConnectionId).mockReturnValue('ssh-proxmox')
+
+ const requestGateway = vi.fn(async (method: string) => {
+ if (method === 'session.resume') {
+ return {
+ info: {},
+ message_count: 0,
+ messages: [],
+ resumed: 'stored-1',
+ session_id: 'runtime-1',
+ session_key: 'stored-1'
+ } as never
+ }
+
+ return {} as never
+ })
+
+ vi.mocked(getLatestSessionMessages).mockResolvedValue({ messages: [], session_id: 'stored-1' } as never)
+
+ await runResume(requestGateway)
+
+ expect(getSessionOwnerHint('stored-1')).toMatchObject({ connectionId: 'ssh-proxmox' })
+ })
})
describe('session.resume turn timer contract', () => {
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
index c69468271ac..bcb8ec5c8c0 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
@@ -39,6 +39,7 @@ import { resetSessionBackground } from '@/store/composer-status'
import { $connectionRequests } from '@/store/connection-request'
import {
$gateway,
+ activeGatewayConnectionId,
isActivePrimary,
openGatewayForAgent,
openGatewayForProfile,
@@ -83,6 +84,7 @@ import {
$newChatWorkspaceTarget,
$sessions,
$yoloActive,
+ forgetSessionOwnerHintsForSession,
getCurrentModelSource,
getSessionOwnerHint,
idsShareLineage,
@@ -1431,7 +1433,38 @@ export function useSessionActions({
// gateway call (no-op when it's already on that profile / single-profile).
// resolveStoredSession finds the row by id (cheap), so an uncached pasted
// id loads as fast as a sidebar click instead of hanging on a list scan.
- const ownerRoute = capturedOwner || getSessionOwnerHint(storedSessionId)
+ //
+ // A persisted owner hint is only trustworthy when the connection it
+ // names is still this window's live primary. Current builds mint hints
+ // from the real registry id at create/resume time, but older builds
+ // persisted `local` for rows that actually live on a remote primary
+ // (the legacy primary-SSH path): an auto-restored resume that trusts
+ // that hint dials the Mac backend and dies with "session not found"
+ // (#97809). The click path (openStoredSession) already drops such hints
+ // for untagged rows; every OTHER pathname-driven resume funnels through
+ // here, so the same hygiene applies at this seam. The hint is repaired,
+ // not just ignored: a stale route left in the map re-poisons the next
+ // resume, the row ladder and every session-scoped RPC dispatch.
+ //
+ // An explicitly captured owner (requestSessionResume with a row route,
+ // a plugin open) is authoritative as given; only the REMEMBERED hint
+ // is validated, never the caller's capture.
+ const rememberedHint = capturedOwner ? undefined : getSessionOwnerHint(storedSessionId)
+
+ const rememberedOwner = rememberedHint
+ ? rememberedHint.connectionId === (activeGatewayConnectionId() ?? 'local')
+ ? rememberedHint
+ : undefined
+ : undefined
+
+ if (rememberedHint && !rememberedOwner) {
+ forgetSessionOwnerHintsForSession(storedSessionId)
+ }
+
+ // An explicit capture outranks the remembered hint; the hint only
+ // fills in when the caller had no route to give.
+ const ownerRoute = capturedOwner || rememberedOwner
+
// A connection switch clears/reloads the session rows before this path
// runs, so an untagged row belongs to the connection that supplied the
// current list. Capture that source before the async metadata lookup. If