Skip to content

The agent that grows with you

fix(desktop): boot the registry primary after an update (#99395)

brooklyn!cd2915ac6c86
diff --git a/apps/desktop/electron/desktop-remote-route.test.ts b/apps/desktop/electron/desktop-remote-route.test.ts
index b2f35ae8853..b22fed51473 100644
--- a/apps/desktop/electron/desktop-remote-route.test.ts
+++ b/apps/desktop/electron/desktop-remote-route.test.ts
@@ -4,7 +4,7 @@ import { test } from 'vitest'
import { normalizeRegistry, REGISTRY_VERSION } from './connection-registry'
import { backendScopeKey } from './connection-registry'
-import { resolveDesktopRemoteRoute, v1SshTerminalPoolKey } from './desktop-remote-route'
+import { resolveDesktopRemoteRoute, registryPrimaryBootRoute, v1SshTerminalPoolKey } from './desktop-remote-route'
const tokenA = { encoding: 'plain', value: 'token-a' }
const tokenB = { encoding: 'plain', value: 'token-b' }
@@ -433,3 +433,31 @@ test('the v1 global remote still outranks the registry primary', () => {
assert.equal(route?.source, 'settings')
assert.equal((route as any)?.url, 'https://global.test')
})
+
+test('launchMode=primary selects the registry SSH primary and ignores a local v1 mode', () => {
+ const route = registryPrimaryBootRoute(
+ registry('spark', [
+ { id: 'spark', kind: 'ssh', label: 'Spark', host: 'spark1', user: 'tek', port: 2222, token: tokenA }
+ ])
+ )
+
+ assert.equal(route?.kind, 'ssh')
+ assert.equal(route?.source, 'registry')
+ assert.equal(route?.connectionId, 'spark')
+})
+
+test('launchMode=last-used does not force the registry primary before a local spawn', () => {
+ const route = registryPrimaryBootRoute(
+ normalizeRegistry({
+ version: REGISTRY_VERSION,
+ primary: 'spark',
+ launchMode: 'last-used',
+ connections: [
+ { id: 'local', kind: 'local', label: 'This device' },
+ { id: 'spark', kind: 'ssh', label: 'Spark', host: 'spark1', user: 'tek', port: 2222, token: tokenA }
+ ]
+ })
+ )
+
+ assert.equal(route, null)
+})
diff --git a/apps/desktop/electron/desktop-remote-route.ts b/apps/desktop/electron/desktop-remote-route.ts
index 56ca6b74a88..f54299c6d1f 100644
--- a/apps/desktop/electron/desktop-remote-route.ts
+++ b/apps/desktop/electron/desktop-remote-route.ts
@@ -226,3 +226,16 @@ function resolveRegistryPrimaryRoute(registry: ConnectionRegistry): DesktopRemot
url
}
}
+
+/**
+ * Boot target when the user asked to launch the registry primary. Returns null
+ * for last-used mode and for a local primary — those keep the local spawn.
+ * Ignores legacy connection.json mode, which must not override this choice.
+ */
+export function registryPrimaryBootRoute(registry: ConnectionRegistry): DesktopRemoteRoute | null {
+ if (registry?.launchMode !== 'primary') {
+ return null
+ }
+
+ return resolveRegistryPrimaryRoute(registry)
+}
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 56fe2a551b1..4f6c5dd6515 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -198,7 +198,7 @@ import {
resolveDesktopConnectionRequest,
resolveDesktopWindowLaunch
} from './desktop-profile'
-import { resolveDesktopRemoteRoute, v1SshTerminalPoolKey } from './desktop-remote-route'
+import { resolveDesktopRemoteRoute, registryPrimaryBootRoute, v1SshTerminalPoolKey } from './desktop-remote-route'
import {
buildPosixCleanupScript,
buildWindowsCleanupScript,
@@ -9885,7 +9885,7 @@ function persistSshConnectionToken(profile, source, token, registryConnectionId
// 3. global remote (connection.json `mode: 'remote'`)
// A null/empty profile resolves the env/global remote, so legacy callers and
// the connection test (which pass no profile) are unchanged.
-async function resolveRemoteBackend(profile, options: { poolKey?: string; primary?: boolean } = {}) {
+async function resolveRemoteBackend(profile, options: { forceRegistryPrimary?: boolean; poolKey?: string; primary?: boolean } = {}) {
const profileKey = String(profile || '').trim() || 'default'
const managedPrimary = options.primary
@@ -9937,16 +9937,19 @@ async function resolveRemoteBackend(profile, options: { poolKey?: string; primar
}
const config = readDesktopConnectionConfig()
+ const registry = readDesktopConnectionsRegistry()
- const route = resolveDesktopRemoteRoute({
- config,
- env: {
- token: process.env.HERMES_DESKTOP_REMOTE_TOKEN,
- url: process.env.HERMES_DESKTOP_REMOTE_URL
- },
- profile,
- registry: readDesktopConnectionsRegistry()
- })
+ const route = options.forceRegistryPrimary
+ ? registryPrimaryBootRoute(registry)
+ : resolveDesktopRemoteRoute({
+ config,
+ env: {
+ token: process.env.HERMES_DESKTOP_REMOTE_TOKEN,
+ url: process.env.HERMES_DESKTOP_REMOTE_URL
+ },
+ profile,
+ registry
+ })
if (!route) {
return null
@@ -12482,6 +12485,16 @@ async function runHermesStart({ supervisorRecovery = false }: { supervisorRecove
return resolveRemoteBackend(primaryProfile, { primary: true })
},
+ selectRegistryPrimary: async () => {
+ // The pre-update resolve can miss a registry primary (stale cache, v1
+ // mode=local winning the first read). Re-read after the update gate
+ // and select launchMode=primary before any local attach or spawn.
+ connectionRegistryCache = null
+ connectionRegistryCacheMtime = null
+ attemptedRemote = true
+
+ return resolveRemoteBackend(primaryProfile, { primary: true, forceRegistryPrimary: true })
+ },
waitForDecision: waitForFirstRunSetupChoice,
// Mutual exclusion with an in-app update (#50238). Remote connections
// return before this waiter; local starts park until the updater exits.
diff --git a/apps/desktop/electron/primary-backend-startup.test.ts b/apps/desktop/electron/primary-backend-startup.test.ts
index dc5f2082458..dab35a0f208 100644
--- a/apps/desktop/electron/primary-backend-startup.test.ts
+++ b/apps/desktop/electron/primary-backend-startup.test.ts
@@ -166,6 +166,43 @@ test('remote apply fails clearly when no saved remote can be resolved', async ()
assert.equal(options.ensureLocalRuntime.mock.calls.length, 0)
})
+test('after update clearance, a registry primary is selected before any local spawn', async () => {
+ const sshPrimary = { baseUrl: 'http://127.0.0.1:54414', connectionId: '100-106-105-2' }
+ let updateCleared = false
+
+ const options = startupOptions({
+ resolveRemote: vi.fn(async () => null),
+ selectRegistryPrimary: vi.fn(async () => {
+ assert.equal(updateCleared, true)
+
+ return sshPrimary
+ }),
+ waitForLocalStart: vi.fn(async () => {
+ updateCleared = true
+ }),
+ attachHostBackend: vi.fn(async () => ({ baseUrl: 'http://127.0.0.1:49900', mode: 'local' as const }))
+ })
+
+ assert.deepEqual(await runPrimaryBackendStartup(options), {
+ kind: 'remote',
+ connection: { baseUrl: sshPrimary.baseUrl, mode: 'remote' }
+ })
+ assert.equal(options.prepareLocalBackend.mock.calls.length, 0)
+ assert.equal(options.ensureLocalRuntime.mock.calls.length, 0)
+ assert.equal(options.attachHostBackend.mock.calls.length, 0)
+})
+
+test('a null post-update primary still spawns local exactly once', async () => {
+ const options = startupOptions({
+ resolveRemote: vi.fn(async () => null),
+ selectRegistryPrimary: vi.fn(async () => null)
+ })
+
+ assert.equal((await runPrimaryBackendStartup(options)).kind, 'local')
+ assert.equal(options.selectRegistryPrimary.mock.calls.length, 1)
+ assert.equal(options.ensureLocalRuntime.mock.calls.length, 1)
+})
+
test('continue local waits for update exclusion and ensures the prepared runtime exactly once', async () => {
const gate = createFirstRunSetupGate({ stuckAfterMs: 0 })
const runtimeBackend = { ...bootstrapBackend, command: 'hermes' }
diff --git a/apps/desktop/electron/primary-backend-startup.ts b/apps/desktop/electron/primary-backend-startup.ts
index 6f57d819bd9..2a79fc8f346 100644
--- a/apps/desktop/electron/primary-backend-startup.ts
+++ b/apps/desktop/electron/primary-backend-startup.ts
@@ -13,6 +13,12 @@ export interface PrimaryBackendStartupOptions<Backend, RuntimeBackend, Remote, C
ensureLocalRuntime: (backend: Backend) => Promise<RuntimeBackend>
prepareLocalBackend: () => Backend | Promise<Backend>
resolveRemote: () => Promise<Remote | null>
+ /**
+ * After update clearance and before any local attach/spawn. When launchMode
+ * is primary and the registry primary is non-local, this returns that
+ * remote so a stale pre-update resolve cannot boot an empty local backend.
+ */
+ selectRegistryPrimary?: () => Promise<Remote | null>
waitForDecision: (backend: Backend) => Promise<FirstRunSetupDecision>
waitForLocalStart: () => Promise<unknown>
}
@@ -95,6 +101,7 @@ export async function runPrimaryBackendStartup<Backend, RuntimeBackend, Remote,
ensureLocalRuntime,
prepareLocalBackend,
resolveRemote,
+ selectRegistryPrimary,
waitForDecision,
waitForLocalStart,
signal
@@ -116,6 +123,17 @@ export async function runPrimaryBackendStartup<Backend, RuntimeBackend, Remote,
await step(waitForLocalStart)
+ // Update clearance can land after the first resolve saw a stale local route
+ // (legacy connection.json, a mid-update registry read). Re-select the
+ // registry primary before attaching to or spawning a local backend.
+ if (selectRegistryPrimary) {
+ const registryPrimary = await step(selectRegistryPrimary)
+
+ if (registryPrimary) {
+ return { kind: 'remote', connection: await step(() => connectRemote(registryPrimary)) }
+ }
+ }
+
// Multiplex-only: one backend per HOST. Attach before resolving a runtime or
// entering the first-run gate — a machine with a live backend is, by
// definition, already set up, and the runtime resolve is only needed to spawn.
diff --git a/apps/desktop/src/app/chat/session-tile.test.ts b/apps/desktop/src/app/chat/session-tile.test.ts
index 70f3bdea854..cc39d0a3130 100644
--- a/apps/desktop/src/app/chat/session-tile.test.ts
+++ b/apps/desktop/src/app/chat/session-tile.test.ts
@@ -1,9 +1,16 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
-import { $gatewayState, $sessions, setSessions } from '@/store/session'
+import { $connection, $gatewayState, $sessions, setSessions } from '@/store/session'
import { $sessionTiles } from '@/store/session-states'
-import { sessionTileResumeFailure, shouldResumeSessionTile, startUnrestoredTileTitleBackfill } from './session-tile'
+import {
+ sessionTileResumeFailure,
+ shouldResumeSessionTile,
+ startTileBackendIdentityGuard,
+ startUnrestoredTileTitleBackfill,
+ unbindTilesForBackendIdentityChange,
+ WRONG_BACKEND_TILE_ERROR
+} from './session-tile'
describe('shouldResumeSessionTile', () => {
const live = {
@@ -47,6 +54,59 @@ describe('sessionTileResumeFailure', () => {
it('does not overwrite a tile that rebound while the lookup was pending', () => {
expect(sessionTileResumeFailure('session not found', true, false)).toBeUndefined()
})
+
+ it('unbinds onto a wrong-backend error when the active backend identity changed', () => {
+ expect(sessionTileResumeFailure('session not found', true, true, true)).toBe(
+ 'Wrong backend — this session lives on another connection. Reconnect to that backend to open it.'
+ )
+ expect(sessionTileResumeFailure('404', true, true, true)).not.toMatch(/still available/i)
+ })
+})
+
+describe('unbindTilesForBackendIdentityChange', () => {
+ it('clears a runtime binding and latches the wrong-backend error when the active backend is not the tile owner', () => {
+ const tiles = unbindTilesForBackendIdentityChange(
+ [
+ { ownerRoute: { connectionId: '100-106-105-2' }, runtimeId: 'rt-ssh', storedSessionId: 'ssh-chat' },
+ { ownerRoute: { connectionId: 'local' }, runtimeId: 'rt-local', storedSessionId: 'local-chat' }
+ ],
+ { mode: 'local' }
+ )
+
+ expect(tiles[0]).toEqual({
+ error: WRONG_BACKEND_TILE_ERROR,
+ ownerRoute: { connectionId: '100-106-105-2' },
+ storedSessionId: 'ssh-chat'
+ })
+ expect(tiles[1]?.runtimeId).toBe('rt-local')
+ expect(tiles[1]?.error).toBeUndefined()
+ })
+
+ it('leaves a durable same-backend miss retryable', () => {
+ const tiles = [{ ownerRoute: { connectionId: 'local' }, storedSessionId: 'local-chat' }]
+
+ expect(unbindTilesForBackendIdentityChange(tiles, { connectionId: 'local', mode: 'local' })).toBe(tiles)
+ })
+})
+
+describe('startTileBackendIdentityGuard', () => {
+ afterEach(() => {
+ $connection.set(null)
+ $sessionTiles.set([])
+ })
+
+ it('unbinds persisted tiles when an unqualified local boot replaces their owner', () => {
+ $sessionTiles.set([
+ { ownerRoute: { connectionId: '100-106-105-2' }, runtimeId: 'rt-ssh', storedSessionId: 'ssh-chat' }
+ ])
+
+ const stop = startTileBackendIdentityGuard()
+ $connection.set({ mode: 'local' })
+
+ expect($sessionTiles.get()[0]?.error).toBe(WRONG_BACKEND_TILE_ERROR)
+ expect($sessionTiles.get()[0]?.runtimeId).toBeUndefined()
+ stop()
+ })
})
describe('startUnrestoredTileTitleBackfill (#94167)', () => {
diff --git a/apps/desktop/src/app/chat/session-tile.tsx b/apps/desktop/src/app/chat/session-tile.tsx
index 02de6f7ca35..99ca5f4b51c 100644
--- a/apps/desktop/src/app/chat/session-tile.tsx
+++ b/apps/desktop/src/app/chat/session-tile.tsx
@@ -43,6 +43,7 @@ import { $activeGatewayProfile } from '@/store/profile'
import { $projectTree } from '@/store/projects'
import { sessionAwaitingInput } from '@/store/prompts'
import {
+ $connection,
$cronSessions,
$gatewayState,
$messagingSessions,
@@ -81,10 +82,14 @@ import { ChatView } from '.'
const NO_MESSAGES: ChatMessage[] = []
+export const WRONG_BACKEND_TILE_ERROR =
+ 'Wrong backend — this session lives on another connection. Reconnect to that backend to open it.'
+
export function sessionTileResumeFailure(
message: string,
durableSessionFound: boolean | undefined,
- tileStillUnbound: boolean
+ tileStillUnbound: boolean,
+ backendIdentityChanged = false
): string | undefined {
if (!tileStillUnbound) {
return undefined
@@ -94,6 +99,10 @@ export function sessionTileResumeFailure(
return message
}
+ if (backendIdentityChanged) {
+ return WRONG_BACKEND_TILE_ERROR
+ }
+
if (durableSessionFound) {
return 'Session is still available — retry resuming it.'
}
@@ -101,6 +110,49 @@ export function sessionTileResumeFailure(
return 'Session unavailable — you can retry resuming it.'
}
+/** True when a persisted tile's owner is a different backend than the one that
+ * just became active. An unqualified local boot (no connectionId, mode local)
+ * counts as the local identity — that is the post-update empty backend. */
+export function tileBackendIdentityChanged(
+ ownerConnectionId: string | null | undefined,
+ activeConnection: { connectionId?: string | null; mode?: string | null } | null | undefined
+): boolean {
+ const owner = String(ownerConnectionId || '').trim()
+
+ if (!owner || !activeConnection) {
+ return false
+ }
+
+ const active =
+ String(activeConnection.connectionId || '').trim() || (activeConnection.mode === 'local' ? 'local' : '')
+
+ return Boolean(active) && owner !== active
+}
+
+export function unbindTilesForBackendIdentityChange<
+ T extends { error?: string; ownerRoute?: { connectionId?: string }; runtimeId?: string }
+>(tiles: readonly T[], activeConnection: { connectionId?: string | null; mode?: string | null } | null | undefined): T[] {
+ let changed = false
+
+ const next = tiles.map(tile => {
+ if (!tileBackendIdentityChanged(tile.ownerRoute?.connectionId, activeConnection)) {
+ return tile
+ }
+
+ if (!tile.runtimeId && tile.error === WRONG_BACKEND_TILE_ERROR) {
+ return tile
+ }
+
+ changed = true
+ const unbound = { ...tile, error: WRONG_BACKEND_TILE_ERROR }
+ delete unbound.runtimeId
+
+ return unbound
+ })
+
+ return changed ? next : (tiles as T[])
+}
+
/** Should this tile dispatch a `session.resume`?
*
* - The gateway must be OPEN: persisted tiles mount at boot while it is still
@@ -473,7 +525,13 @@ export function SessionTilePane({ storedSessionId }: { storedSessionId: string }
// reconnect-time lookup.
const durableSession = await resolveStoredSession(storedSessionId, ownerRoute).catch(() => undefined)
const current = $sessionTiles.get().find(candidate => candidate.storedSessionId === storedSessionId)
- const error = sessionTileResumeFailure(message, Boolean(durableSession), Boolean(current && !current.runtimeId))
+ const identityChanged = tileBackendIdentityChanged(ownerRoute?.connectionId, $connection.get())
+ const error = sessionTileResumeFailure(
+ message,
+ Boolean(durableSession),
+ Boolean(current && !current.runtimeId),
+ identityChanged
+ )
if (error) {
patchSessionTile(storedSessionId, { error })
@@ -489,7 +547,7 @@ export function SessionTilePane({ storedSessionId }: { storedSessionId: string }
// retriggers the resume effect: one bounded auto-retry per (re)connect,
// mirroring the primary path's became-open resync.
useEffect(() => {
- if (gatewayOpen && tile?.error) {
+ if (gatewayOpen && tile?.error && tile.error !== WRONG_BACKEND_TILE_ERROR) {
patchSessionTile(storedSessionId, { error: undefined })
}
// eslint-disable-next-line react-hooks/exhaustive-deps
@@ -570,6 +628,26 @@ export function startUnrestoredTileTitleBackfill(lookup = resolveStoredSession):
return off
}
+/** Drop persisted tile bindings that belong to a different backend than the
+ * one that just became active, and latch the wrong-backend error so a later
+ * resume cannot turn a cross-backend 404 into the durable-session retry copy. */
+export function startTileBackendIdentityGuard(activeConnection = () => $connection.get()): () => void {
+ const run = () => {
+ const connection = activeConnection()
+ const tiles = $sessionTiles.get()
+ const next = unbindTilesForBackendIdentityChange(tiles, connection)
+
+ if (next !== tiles) {
+ $sessionTiles.set(next)
+ }
+ }
+
+ const off = $connection.listen(run)
+ run()
+
+ return off
+}
+
/** The tab's REGISTERED name. Deliberately the bare placeholder for a draft
* rather than its live composer title (`tabTitle` renders that): re-registering
* per keystroke would re-render the strip, and holding the draft's text here
diff --git a/apps/desktop/src/app/contrib/controller.tsx b/apps/desktop/src/app/contrib/controller.tsx
index 0dafa7bc94c..63515cfded8 100644
--- a/apps/desktop/src/app/contrib/controller.tsx
+++ b/apps/desktop/src/app/contrib/controller.tsx
@@ -98,6 +98,7 @@ import { startSessionDrag } from '../chat/session-drag'
import {
SessionTileCloseConfirm,
stackSessionTilesIntoMain,
+ startTileBackendIdentityGuard,
startUnrestoredTileTitleBackfill,
watchSessionTiles,
WorkspaceTabMenu
@@ -468,6 +469,7 @@ hydrateContributedPanes()
if (!isBrowserWindow() && !isHudWindow()) {
watchSessionTiles()
startUnrestoredTileTitleBackfill()
+ startTileBackendIdentityGuard()
watchRouteTiles()
watchPreviewTiles()
}
diff --git a/apps/desktop/src/store/connections.test.ts b/apps/desktop/src/store/connections.test.ts
index 16ed26ccda1..d5c3be5e96e 100644
--- a/apps/desktop/src/store/connections.test.ts
+++ b/apps/desktop/src/store/connections.test.ts
@@ -207,6 +207,24 @@ describe('connection registry cache', () => {
expect(ensureGatewayAgent).not.toHaveBeenCalled()
})
+ it('selects the registry primary on boot when an update left an unqualified local descriptor', async () => {
+ // Post-update boot can publish a local descriptor with no registry id
+ // while connections.json still says launchMode=primary and the primary is
+ // SSH. That live local must not block selecting the registered primary.
+ list.mockResolvedValueOnce({
+ ...registry,
+ lastUsed: 'local',
+ launchMode: 'primary',
+ primary: 'homelab'
+ })
+ $connection.set({ mode: 'local' })
+
+ await initializeConnectionsRegistry()
+
+ expect(ensureGatewayAgent).toHaveBeenCalledTimes(1)
+ expect(ensureGatewayAgent).toHaveBeenCalledWith('homelab', 'default', expect.anything())
+ })
+
it('restores a remote registry primary through its exact connection id', async () => {
list.mockResolvedValueOnce({ ...registry, primary: 'homelab', launchMode: 'primary' })
$connection.set({ connectionId: 'local', mode: 'local' })
diff --git a/apps/desktop/src/store/connections.ts b/apps/desktop/src/store/connections.ts
index 1313754631d..5e72929dc90 100644
--- a/apps/desktop/src/store/connections.ts
+++ b/apps/desktop/src/store/connections.ts
@@ -262,22 +262,26 @@ export async function initializeConnectionsRegistry(): Promise<DesktopConnection
return $connectionsRegistry.get() ?? registry
}
- // Residual drift: a window can be live on a source the registry cannot name
- // (a v1-configured remote that reconciliation has not repaired yet, e.g. a
- // read-only userData that rejected the healed write). $activeConnectionId is
- // null there, so the preferred-id guard below would miss and "restore" the
- // registry primary over a connection that is already up and painting —
- // re-homing the user onto a different backend seconds after boot. The
- // registry has no claim on a source it does not know; leave the live one be.
- if ($connection.get() && $activeConnectionId.get() === null) {
- return registry
- }
-
const lastUsed = registry.connections.some(connection => connection.id === registry.lastUsed)
? registry.lastUsed
: registry.primary
const preferredId = registry.launchMode === 'last-used' ? lastUsed : registry.primary
+ const preferred = registry.connections.find(connection => connection.id === preferredId)
+ const live = $connection.get()
+
+ // An unqualified local descriptor is the post-update empty-backend boot, not
+ // a v1 remote the registry cannot name. launchMode=primary must still select
+ // the registered SSH/remote primary instead of staying on that local spawn.
+ const replaceUnqualifiedLocal =
+ live?.mode === 'local' &&
+ $activeConnectionId.get() === null &&
+ registry.launchMode !== 'last-used' &&
+ Boolean(preferred && preferred.kind !== 'local')
+
+ if (live && $activeConnectionId.get() === null && !replaceUnqualifiedLocal) {
+ return registry
+ }
if (!preferredId) {
return registry