Skip to content

The agent that grows with you

fix(desktop): rebind Bot Chats after gateway restart

David Dudok de Wit6b4a2eebc859
diff --git a/apps/desktop/src/app/chat/session-tile-actions.test.ts b/apps/desktop/src/app/chat/session-tile-actions.test.ts
index 061c739dcd6..0d0139905da 100644
--- a/apps/desktop/src/app/chat/session-tile-actions.test.ts
+++ b/apps/desktop/src/app/chat/session-tile-actions.test.ts
@@ -6,11 +6,8 @@ import { MAIN_COMPOSER_SCOPE } from './composer/scope'
const requestGatewayMock = vi.hoisted(() => vi.fn())
-vi.mock('@/app/gateway/hooks/use-gateway-request', () => ({
- useGatewayRequest: () => ({ requestGateway: requestGatewayMock })
-}))
-
-const { setSessionTileDelegate } = await import('@/store/session-states')
+const { $activeSessionId } = await import('@/store/session')
+const { $sessionTiles, setSessionTileDelegate } = await import('@/store/session-states')
const { useSessionTileActions } = await import('./session-tile-actions')
const RUNTIME_SESSION_ID = 'rt-tile-current'
@@ -20,6 +17,7 @@ const RECOVERED_SESSION_ID = 'rt-tile-recovered'
function renderTileActions() {
return renderHook(() =>
useSessionTileActions({
+ requestGateway: requestGatewayMock,
runtimeId: RUNTIME_SESSION_ID,
scope: MAIN_COMPOSER_SCOPE,
storedSessionId: STORED_SESSION_ID
@@ -35,6 +33,8 @@ function renderTileActions() {
// primary chat's own reloadFromMessage.
describe('useSessionTileActions sleep/wake session recovery', () => {
beforeEach(() => {
+ $activeSessionId.set('foreground-runtime')
+ $sessionTiles.set([{ runtimeId: RUNTIME_SESSION_ID, storedSessionId: STORED_SESSION_ID }])
setSessionTileDelegate({
archiveSession: vi.fn(async () => undefined),
branchSession: vi.fn(async () => undefined),
@@ -58,6 +58,8 @@ describe('useSessionTileActions sleep/wake session recovery', () => {
})
afterEach(() => {
+ $activeSessionId.set(null)
+ $sessionTiles.set([])
requestGatewayMock.mockReset()
vi.restoreAllMocks()
})
@@ -95,8 +97,9 @@ describe('useSessionTileActions sleep/wake session recovery', () => {
// First interrupt (stale id) → session.resume (stored id) → retry interrupt (fresh id).
expect(calls.map(c => c.method)).toEqual(['session.interrupt', 'session.resume', 'session.interrupt'])
expect(calls[0]?.params).toEqual({ session_id: RUNTIME_SESSION_ID })
- expect(calls[1]?.params).toEqual({ session_id: STORED_SESSION_ID, source: 'desktop', omit_messages: true })
+ expect(calls[1]?.params).toMatchObject({ session_id: STORED_SESSION_ID, source: 'desktop', omit_messages: true })
expect(calls[2]?.params).toEqual({ session_id: RECOVERED_SESSION_ID })
+ expect($sessionTiles.get()[0]?.runtimeId).toBe(RECOVERED_SESSION_ID)
})
it('resumes the stored session and retries once when session.redirect (steer) reports "session not found"', async () => {
@@ -130,5 +133,44 @@ describe('useSessionTileActions sleep/wake session recovery', () => {
expect(ok).toBe(true)
expect(calls.map(c => c.method)).toEqual(['session.redirect', 'session.resume', 'session.redirect'])
expect(calls[2]?.params).toEqual({ session_id: RECOVERED_SESSION_ID, text: 'actually use Postgres' })
+ expect($sessionTiles.get()[0]?.runtimeId).toBe(RECOVERED_SESSION_ID)
+ })
+
+ it('rebinds prompt.submit recovery to the tile without changing the foreground session', async () => {
+ const calls: { method: string; params?: Record<string, unknown> }[] = []
+ let submitAttempts = 0
+
+ requestGatewayMock.mockImplementation(async (method: string, params?: Record<string, unknown>) => {
+ calls.push({ method, params })
+
+ if (method === 'prompt.submit') {
+ submitAttempts += 1
+
+ if (submitAttempts === 1) {
+ throw new Error('session not found')
+ }
+
+ return {}
+ }
+
+ if (method === 'session.resume') {
+ return { session_id: RECOVERED_SESSION_ID }
+ }
+
+ return {}
+ })
+
+ const { result } = renderTileActions()
+
+ await act(async () => {
+ await expect(result.current.submitText('continue the bot chat')).resolves.toBe(true)
+ })
+
+ expect(calls.map(c => c.method)).toEqual(['prompt.submit', 'session.resume', 'prompt.submit'])
+ expect(calls[0]?.params).toMatchObject({ session_id: RUNTIME_SESSION_ID })
+ expect(calls[1]?.params).toMatchObject({ session_id: STORED_SESSION_ID, source: 'desktop', omit_messages: true })
+ expect(calls[2]?.params).toMatchObject({ session_id: RECOVERED_SESSION_ID })
+ expect($sessionTiles.get()[0]?.runtimeId).toBe(RECOVERED_SESSION_ID)
+ expect($activeSessionId.get()).toBe('foreground-runtime')
})
})
diff --git a/apps/desktop/src/app/chat/session-tile-actions.ts b/apps/desktop/src/app/chat/session-tile-actions.ts
index 55419761601..fa8309ebeaa 100644
--- a/apps/desktop/src/app/chat/session-tile-actions.ts
+++ b/apps/desktop/src/app/chat/session-tile-actions.ts
@@ -11,7 +11,6 @@
import type { AppendMessage, ThreadMessage } from '@assistant-ui/react'
import { useCallback, useMemo, useRef } from 'react'
-import { useGatewayRequest } from '@/app/gateway/hooks/use-gateway-request'
import type { ClientSessionState } from '@/app/types'
import { useI18n } from '@/i18n'
import { textPart } from '@/lib/chat-messages'
@@ -24,13 +23,14 @@ import { notifyError } from '@/store/notifications'
import { clearPreviewArtifacts } from '@/store/preview-status'
import { clearAllPrompts } from '@/store/prompts'
import { $connection, $sessions, sessionMatchesStoredId } from '@/store/session'
-import { $sessionStates, sessionTileDelegate } from '@/store/session-states'
+import { $sessionStates, patchSessionTile, sessionTileDelegate } from '@/store/session-states'
import { broadcastSessionsChanged } from '@/store/session-sync'
import { clearSessionSubagents } from '@/store/subagents'
import { clearSessionTodos } from '@/store/todos'
import { setSessionDraftingTool } from '@/store/tool-drafting'
import type { SessionInfo } from '@/types/hermes'
+import type { GatewayRequester } from '../contrib/types'
import { uploadComposerAttachment } from '../session/hooks/use-prompt-actions'
import {
appendMidTurnUserMessage,
@@ -96,15 +96,15 @@ export function listTileSessionRow(deps: {
}
interface SessionTileActionsArgs {
+ requestGateway: GatewayRequester
runtimeId: string
scope: ComposerScope
storedSessionId: string
}
-export function useSessionTileActions({ runtimeId, scope, storedSessionId }: SessionTileActionsArgs) {
+export function useSessionTileActions({ requestGateway, runtimeId, scope, storedSessionId }: SessionTileActionsArgs) {
const { t } = useI18n()
const copy = t.desktop
- const { requestGateway } = useGatewayRequest()
const runtimeIdRef = useRef(runtimeId)
runtimeIdRef.current = runtimeId
@@ -116,6 +116,14 @@ export function useSessionTileActions({ runtimeId, scope, storedSessionId }: Ses
const runtimeIdByStoredSessionIdRef = useRef(new Map([[storedSessionId, runtimeId]]))
runtimeIdByStoredSessionIdRef.current.set(storedSessionId, runtimeId)
+ const bindRecoveredRuntime = useCallback((recoveredId: string) => {
+ const storedId = storedIdRef.current
+
+ runtimeIdRef.current = recoveredId
+ runtimeIdByStoredSessionIdRef.current.set(storedId, recoveredId)
+ patchSessionTile(storedId, { error: undefined, runtimeId: recoveredId })
+ }, [])
+
// Tile busy tracks the SESSION state, never the global $busy — and it must
// read LIVE. A render-time snapshot goes stale (this hook's host doesn't
// re-render on busy edges), and a stale `true` silently blocks every
@@ -177,7 +185,7 @@ export function useSessionTileActions({ runtimeId, scope, storedSessionId }: Ses
// tile's ref rather than the foreground session's.
const onSessionRecovered = (recoveredId: string) => {
liveSessionId = recoveredId
- runtimeIdRef.current = recoveredId
+ bindRecoveredRuntime(recoveredId)
}
for (const attachment of attachments) {
@@ -224,7 +232,7 @@ export function useSessionTileActions({ runtimeId, scope, storedSessionId }: Ses
return { attachments: synced, sessionId: liveSessionId }
},
- [requestGateway, scope.attachments]
+ [bindRecoveredRuntime, readState, requestGateway, scope.attachments]
)
// The REAL submit pipeline with tile seams: session always exists, and the
@@ -239,6 +247,7 @@ export function useSessionTileActions({ runtimeId, scope, storedSessionId }: Ses
// A tile IS its session — no route to abandon, so the create-abort guard's
// token is a stable constant (the guard never trips for a tile).
getRouteToken: () => runtimeId,
+ onRuntimeRecovered: bindRecoveredRuntime,
requestGateway,
runtimeIdByStoredSessionIdRef,
// Tile ids are always bound before this hook mounts, so routed recovery is
@@ -308,15 +317,13 @@ export function useSessionTileActions({ runtimeId, scope, storedSessionId }: Ses
liveId => requestGateway('session.interrupt', { session_id: liveId }),
{
requestGateway,
- onRecovered: recoveredId => {
- runtimeIdRef.current = recoveredId
- }
+ onRecovered: bindRecoveredRuntime
}
)
} catch (err) {
notifyError(err, copy.stopFailed)
}
- }, [copy.stopFailed, requestGateway, update])
+ }, [bindRecoveredRuntime, copy.stopFailed, requestGateway, update])
const steerPrompt = useCallback(
async (rawText: string): Promise<boolean> => {
@@ -369,9 +376,7 @@ export function useSessionTileActions({ runtimeId, scope, storedSessionId }: Ses
liveId => requestGateway<{ status?: string }>('session.redirect', { session_id: liveId, text }),
{
requestGateway,
- onRecovered: recoveredId => {
- runtimeIdRef.current = recoveredId
- }
+ onRecovered: bindRecoveredRuntime
}
)
@@ -398,7 +403,7 @@ export function useSessionTileActions({ runtimeId, scope, storedSessionId }: Ses
return false
},
- [requestGateway]
+ [bindRecoveredRuntime, requestGateway]
)
// Rewind primitive (interrupt-first for live turns, busy-retry) — shared with
@@ -421,14 +426,12 @@ export function useSessionTileActions({ runtimeId, scope, storedSessionId }: Ses
interruptFirst,
{
storedSessionId: storedIdRef.current,
- onSessionRecovered: recoveredId => {
- runtimeIdRef.current = recoveredId
- }
+ onSessionRecovered: bindRecoveredRuntime
},
truncateRowId,
sourceText
),
- [requestGateway]
+ [bindRecoveredRuntime, requestGateway]
)
// After a durable rewind the surviving bubbles' cached rowIds are stale (the
diff --git a/apps/desktop/src/app/chat/session-tile-attachments.test.tsx b/apps/desktop/src/app/chat/session-tile-attachments.test.tsx
index b756f821e4d..162c9dc6110 100644
--- a/apps/desktop/src/app/chat/session-tile-attachments.test.tsx
+++ b/apps/desktop/src/app/chat/session-tile-attachments.test.tsx
@@ -17,10 +17,6 @@ import { deferred } from '../../test/deferred'
const requestGateway = vi.fn()
-vi.mock('@/app/gateway/hooks/use-gateway-request', () => ({
- useGatewayRequest: () => ({ requestGateway })
-}))
-
vi.mock('@/i18n', () => ({
useI18n: () => ({
t: {
@@ -152,7 +148,7 @@ describe('session tile attachment occurrence ownership', () => {
scope.attachments.add(original)
const { result } = renderHook(() =>
- useSessionTileActions({ runtimeId: RUNTIME_ID, scope, storedSessionId: STORED_ID })
+ useSessionTileActions({ requestGateway, runtimeId: RUNTIME_ID, scope, storedSessionId: STORED_ID })
)
let submitted!: Promise<boolean>
@@ -198,7 +194,7 @@ describe('session tile attachment occurrence ownership', () => {
scope.attachments.add(original)
const { result } = renderHook(() =>
- useSessionTileActions({ runtimeId: RUNTIME_ID, scope, storedSessionId: STORED_ID })
+ useSessionTileActions({ requestGateway, runtimeId: RUNTIME_ID, scope, storedSessionId: STORED_ID })
)
let submitted!: Promise<boolean>
@@ -236,7 +232,7 @@ describe('session tile attachment occurrence ownership', () => {
scope.attachments.add(original)
const { result } = renderHook(() =>
- useSessionTileActions({ runtimeId: RUNTIME_ID, scope, storedSessionId: STORED_ID })
+ useSessionTileActions({ requestGateway, runtimeId: RUNTIME_ID, scope, storedSessionId: STORED_ID })
)
let submitted!: Promise<boolean>
@@ -273,7 +269,7 @@ describe('session tile attachment occurrence ownership', () => {
scope.attachments.add(original)
const { result } = renderHook(() =>
- useSessionTileActions({ runtimeId: RUNTIME_ID, scope, storedSessionId: STORED_ID })
+ useSessionTileActions({ requestGateway, runtimeId: RUNTIME_ID, scope, storedSessionId: STORED_ID })
)
let submitted!: Promise<boolean>
@@ -314,7 +310,7 @@ describe('session tile attachment occurrence ownership', () => {
scope.attachments.add(original)
const { result } = renderHook(() =>
- useSessionTileActions({ runtimeId: RUNTIME_ID, scope, storedSessionId: STORED_ID })
+ useSessionTileActions({ requestGateway, runtimeId: RUNTIME_ID, scope, storedSessionId: STORED_ID })
)
await act(async () => {
diff --git a/apps/desktop/src/app/chat/session-tile.tsx b/apps/desktop/src/app/chat/session-tile.tsx
index f0479448c19..125b1cbd345 100644
--- a/apps/desktop/src/app/chat/session-tile.tsx
+++ b/apps/desktop/src/app/chat/session-tile.tsx
@@ -164,7 +164,10 @@ function TileChat({
[attachments, runtimeId, storedSessionId, view.$messages]
)
- const actions = useSessionTileActions({ runtimeId, scope, storedSessionId })
+ // Tile actions must keep the persisted owner route. The ambient gateway hook
+ // follows foreground focus and can point at another backend during restore or
+ // reconnect, which turns a recoverable stale runtime into "session not found".
+ const actions = useSessionTileActions({ requestGateway: requestTileGateway, runtimeId, scope, storedSessionId })
// The same attach/pick/paste/drop pipeline the primary composer uses,
// pointed at this tile's chips + session.
diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.test.tsx b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.test.tsx
index 4b1e214b308..fe3f14343af 100644
--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.test.tsx
+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.test.tsx
@@ -6,9 +6,10 @@ import { closeSecondaryGateways, isActivePrimary } from '@/store/gateway'
import { reconnectGateway } from '@/store/gateway-reconnect'
import { $activeGatewayProfile, $profiles, ensureGatewayProfile } from '@/store/profile'
import { $connection, $currentCwd, $gatewayState } from '@/store/session'
+import { $sessionTiles } from '@/store/session-states'
import { takeGatewaySurvivor } from './gateway-hmr-survivor'
-import { useGatewayBoot } from './use-gateway-boot'
+import { primaryRuntimeConnectionId, useGatewayBoot } from './use-gateway-boot'
// End-to-end-ish repro of the "remote VPS → stuck on CONNECTING, no Settings"
// bug that drives the REAL useGatewayBoot hook + REAL HermesGateway through a
@@ -24,6 +25,20 @@ import { useGatewayBoot } from './use-gateway-boot'
type Listener = (ev: unknown) => void
let connectionApplied: null | (() => void) = null
+describe('primaryRuntimeConnectionId', () => {
+ it('uses the registry identity when the primary connection has one', () => {
+ expect(primaryRuntimeConnectionId({ connectionId: ' tower ', mode: 'remote' })).toBe('tower')
+ })
+
+ it('uses the stable local identity for an app-managed backend', () => {
+ expect(primaryRuntimeConnectionId({ mode: 'local' })).toBe('local')
+ })
+
+ it('preserves legacy remote Bot bindings when the primary identity is unknown', () => {
+ expect(primaryRuntimeConnectionId({ mode: 'remote' })).toBeNull()
+ })
+})
+
// Minimal WebSocket stand-in implementing only what json-rpc-gateway.connect()
// touches: readyState, add/removeEventListener('open'|'error'|'close'), close().
class FakeWebSocket {
@@ -82,6 +97,7 @@ class FakeWebSocket {
const primaryConn = {
authMode: 'token' as const,
baseUrl: 'https://vps.example.com',
+ connectionId: 'primary-vps',
profile: 'default',
token: 't',
wsUrl: 'wss://vps.example.com/api/ws?token=t'
@@ -90,6 +106,7 @@ const primaryConn = {
const coderConn = {
authMode: 'token' as const,
baseUrl: 'https://coder.example.com',
+ connectionId: 'coder-remote',
profile: 'coder',
token: 'c',
wsUrl: 'wss://coder.example.com/api/ws?token=c'
@@ -176,6 +193,7 @@ beforeEach(() => {
$activeGatewayProfile.set('default')
$connection.set(null)
$profiles.set([])
+ $sessionTiles.set([])
vi.useFakeTimers()
FakeWebSocket.mode = 'open'
FakeWebSocket.instances = []
@@ -214,6 +232,7 @@ afterEach(() => {
$activeGatewayProfile.set('default')
$connection.set(null)
$profiles.set([])
+ $sessionTiles.set([])
vi.useRealTimers()
;(globalThis as { WebSocket: unknown }).WebSocket = originalWebSocket
delete (window as { hermesDesktop?: unknown }).hermesDesktop
@@ -408,6 +427,36 @@ describe('useGatewayBoot remote reconnect loop (real hook, fake socket)', () =>
expect($desktopBoot.get().error).toBeNull()
})
+ it('rebinds Bot tabs owned by the restarted primary without touching another gateway', async () => {
+ render(<Harness />)
+ await flushAsync()
+ $sessionTiles.set([
+ {
+ ownerRoute: { connectionId: 'primary-vps', mode: 'remote', profile: 'writer', targetProfile: 'writer' },
+ runtimeId: 'runtime-primary-dead',
+ storedSessionId: 'primary-bot-chat',
+ workspaceMode: 'bots',
+ workspaceOwnerKey: 'primary-vps::writer'
+ },
+ {
+ ownerRoute: { connectionId: 'coder-remote', mode: 'remote', profile: 'coder', targetProfile: 'coder' },
+ runtimeId: 'runtime-secondary-live',
+ storedSessionId: 'secondary-bot-chat',
+ workspaceMode: 'bots',
+ workspaceOwnerKey: 'coder-remote::coder'
+ }
+ ])
+
+ act(() => FakeWebSocket.instances[0].drop())
+ FakeWebSocket.mode = 'open'
+ await advanceBackoff()
+
+ const [primaryBot, secondaryBot] = $sessionTiles.get()
+
+ expect(primaryBot).not.toHaveProperty('runtimeId')
+ expect(secondaryBot).toMatchObject({ runtimeId: 'runtime-secondary-live' })
+ })
+
it('manual reconnect revalidates, re-resolves, re-mints, and re-dials the dropped socket', async () => {
const desktop = fakeDesktop()
diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
index c52cb4040cf..b1eddf11394 100644
--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
@@ -88,6 +88,17 @@ const BOOT_RETRY_MAX_ATTEMPTS = 5
// loop's 300ms: each attempt may rebuild an SSH master + remote dashboard.
const BOOT_RETRY_BASE_DELAY_MS = 2_000
+/** Registry identity whose runtimes died with the primary connection. */
+export function primaryRuntimeConnectionId(connection: Pick<HermesConnection, 'connectionId' | 'mode'>): null | string {
+ const connectionId = connection.connectionId?.trim()
+
+ if (connectionId) {
+ return connectionId
+ }
+
+ return connection.mode === 'local' ? 'local' : null
+}
+
interface GatewayBootOptions {
beforeConnectionSwitch: () => void
handleGatewayEvent: (event: RpcEvent) => void
@@ -253,7 +264,7 @@ export function useGatewayBoot({
reconnectFailingSince = null
// A respawned backend re-mints (recycles) runtime ids, so any tile's
// bound runtime id is now stale — drop them so each tile re-resumes.
- resetTileRuntimeBindings()
+ resetTileRuntimeBindings(primaryRuntimeConnectionId(conn))
// Same staleness, other half: pre-reconnect busy flags are keyed by
// those dead runtime ids and would never receive their terminal
// busy:false — clear them or the sidebar running arc lies forever
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts
index eb22a8d7c97..aa48a36cfd1 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts
@@ -59,6 +59,7 @@ interface SubmitPromptDeps {
getRoutedStoredSessionId: () => null | string
getRuntimeIdForStoredSession: (storedSessionId: string) => null | string
getRouteToken: () => string
+ onRuntimeRecovered?: (runtimeId: string) => void
requestGateway: GatewayRequest
runtimeIdByStoredSessionIdRef: MutableRefObject<Map<string, string>>
resumeStoredSession: (storedSessionId: string) => Promise<void> | void
@@ -105,6 +106,7 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {
getRoutedStoredSessionId,
getRuntimeIdForStoredSession,
getRouteToken,
+ onRuntimeRecovered,
requestGateway,
runtimeIdByStoredSessionIdRef,
resumeStoredSession,
@@ -731,7 +733,9 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {
requestGateway,
driftReason: sessionDriftReason,
onRecovered: recoveredId => {
- if (targetIsCurrentView()) {
+ if (onRuntimeRecovered) {
+ onRuntimeRecovered(recoveredId)
+ } else if (targetIsCurrentView()) {
activeSessionIdRef.current = recoveredId
setActiveSessionId(recoveredId)
}
@@ -829,6 +833,7 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {
getRoutedStoredSessionId,
getRuntimeIdForStoredSession,
getRouteToken,
+ onRuntimeRecovered,
requestGateway,
runtimeIdByStoredSessionIdRef,
resumeStoredSession,
diff --git a/apps/desktop/src/store/gateway-connection-lifecycle.test.ts b/apps/desktop/src/store/gateway-connection-lifecycle.test.ts
index fde23951a0a..eb51610d0c4 100644
--- a/apps/desktop/src/store/gateway-connection-lifecycle.test.ts
+++ b/apps/desktop/src/store/gateway-connection-lifecycle.test.ts
@@ -21,6 +21,11 @@ const gatewayMocks = vi.hoisted(() => {
}
})
+const reconnectStateMocks = vi.hoisted(() => ({
+ reconcileBusyStatesOnReconnect: vi.fn(),
+ resetTileRuntimeBindings: vi.fn()
+}))
+
vi.mock('@/hermes', () => ({
setApiRequestConnection: vi.fn(),
HermesGateway: class {
@@ -44,6 +49,7 @@ vi.mock('@/store/session', () => ({
setGatewayState: vi.fn()
}))
vi.mock('@/store/notify-baseline', () => ({ markNativeNotifyBaseline: vi.fn() }))
+vi.mock('@/store/session-states', () => reconnectStateMocks)
const {
activeGateway,
@@ -173,6 +179,28 @@ describe('disposeSecondariesForConnection', () => {
})
})
+describe('secondary reconnect runtime scope', () => {
+ it('rebinds only Bot runtimes owned by the reconnected profile route', async () => {
+ installDesktop({
+ getConnectionFor: vi.fn(async ({ connectionId, profile }) => descriptorFor(connectionId, profile))
+ })
+
+ await ensureGatewayForAgent('homelab', 'writer')
+ const socket = gatewayMocks.instances[0]
+ socket.connectionState = 'closed'
+
+ reconnectSecondaryGateways()
+
+ await vi.waitFor(() =>
+ expect(reconnectStateMocks.resetTileRuntimeBindings).toHaveBeenCalledWith({
+ connectionId: 'homelab',
+ profile: 'writer'
+ })
+ )
+ expect(reconnectStateMocks.reconcileBusyStatesOnReconnect).toHaveBeenCalledWith('conn:homelab::writer')
+ })
+})
+
describe('retireLocalProfileGateways', () => {
it('retires both local profile scopes without touching the same-named remote agent', async () => {
const getConnection = vi.fn(async (profile: string) => descriptorFor('legacy-local', profile))
diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.ts
index 3ddd8ec19f7..0a36e2cc209 100644
--- a/apps/desktop/src/store/gateway.ts
+++ b/apps/desktop/src/store/gateway.ts
@@ -394,7 +394,13 @@ async function reconnectSecondary(entry: Secondary): Promise<void> {
// fail to load — a skipped reconcile there must not surface as an
// unhandled rejection (the real graph always loads in production).
void import('@/store/session-states')
- .then(({ reconcileBusyStatesOnReconnect }) => reconcileBusyStatesOnReconnect(entry.scope))
+ .then(({ reconcileBusyStatesOnReconnect, resetTileRuntimeBindings }) => {
+ reconcileBusyStatesOnReconnect(entry.scope)
+ resetTileRuntimeBindings({
+ connectionId: entry.connectionId || 'local',
+ profile: entry.profile
+ })
+ })
.catch(() => undefined)
} catch (error) {
// The registry no longer knows this connection (removed while we were
diff --git a/apps/desktop/src/store/session-states.test.ts b/apps/desktop/src/store/session-states.test.ts
index bd1a3cb521f..4f6b15ce289 100644
--- a/apps/desktop/src/store/session-states.test.ts
+++ b/apps/desktop/src/store/session-states.test.ts
@@ -58,7 +58,7 @@ describe('resetTileRuntimeBindings', () => {
expect($sessionTiles.get()[0]?.runtimeId).toBeUndefined()
})
- it('keeps exact-owner Bot runtimes when only the primary gateway reconnects', () => {
+ it('keeps Bot runtimes owned by a different connection', () => {
const invalidateRuntimeBindings = vi.fn()
setSessionTileDelegate({ invalidateRuntimeBindings } as unknown as SessionTileDelegate)
$sessionTiles.set([
@@ -76,11 +76,55 @@ describe('resetTileRuntimeBindings', () => {
}
])
- resetTileRuntimeBindings()
+ resetTileRuntimeBindings('work-vps')
expect($sessionTiles.get()[0]?.runtimeId).toBe('runtime-bot')
expect(invalidateRuntimeBindings).toHaveBeenCalledWith(new Set(['stored-bot']))
})
+
+ it('rebinds only the restarted connection while preserving other Bot gateways', () => {
+ const invalidateRuntimeBindings = vi.fn()
+ setSessionTileDelegate({ invalidateRuntimeBindings } as unknown as SessionTileDelegate)
+ $sessionTiles.set([
+ {
+ ownerRoute: { connectionId: 'barry', mode: 'remote', profile: 'oxcoder', targetProfile: 'oxcoder' },
+ runtimeId: 'runtime-barry-dead',
+ storedSessionId: 'stored-barry-bot',
+ workspaceMode: 'bots',
+ workspaceOwnerKey: 'bot:barry::oxcoder'
+ },
+ {
+ ownerRoute: { connectionId: 'barry', mode: 'remote', profile: 't2oracle', targetProfile: 't2oracle' },
+ runtimeId: 'runtime-barry-sibling-live',
+ storedSessionId: 'stored-barry-sibling-bot',
+ workspaceMode: 'bots',
+ workspaceOwnerKey: 'bot:barry::t2oracle'
+ },
+ {
+ ownerRoute: { connectionId: 'work-vps', mode: 'remote', profile: 'ceo', targetProfile: 'ceo' },
+ runtimeId: 'runtime-work-live',
+ storedSessionId: 'stored-work-bot',
+ workspaceMode: 'bots',
+ workspaceOwnerKey: 'bot:work-vps::ceo'
+ },
+ { runtimeId: 'runtime-session-dead', storedSessionId: 'stored-session' }
+ ])
+
+ resetTileRuntimeBindings({ connectionId: 'barry', profile: 'oxcoder' })
+
+ const [barryBot, barrySibling, workBot, ordinarySession] = $sessionTiles.get()
+
+ expect(barryBot).toMatchObject({ storedSessionId: 'stored-barry-bot' })
+ expect(barryBot).not.toHaveProperty('runtimeId')
+ expect(barrySibling).toMatchObject({
+ runtimeId: 'runtime-barry-sibling-live',
+ storedSessionId: 'stored-barry-sibling-bot'
+ })
+ expect(workBot).toMatchObject({ runtimeId: 'runtime-work-live', storedSessionId: 'stored-work-bot' })
+ expect(ordinarySession).toMatchObject({ storedSessionId: 'stored-session' })
+ expect(ordinarySession).not.toHaveProperty('runtimeId')
+ expect(invalidateRuntimeBindings).toHaveBeenCalledWith(new Set(['stored-barry-sibling-bot', 'stored-work-bot']))
+ })
})
describe('SessionTile workspace scope', () => {
diff --git a/apps/desktop/src/store/session-states.ts b/apps/desktop/src/store/session-states.ts
index 8daefa1b9b6..704927b685f 100644
--- a/apps/desktop/src/store/session-states.ts
+++ b/apps/desktop/src/store/session-states.ts
@@ -800,12 +800,42 @@ export function setSessionTileWorkspaceScope(storedSessionId: string, scope: Ses
* tile atoms left `resumeTile`'s warm path free to re-bind the same dead
* runtime id from the cache, so post-wake tiles repainted empty and never
* actually re-resumed. */
-export function resetTileRuntimeBindings() {
+export interface RuntimeReconnectScope {
+ connectionId: string
+ profile?: null | string
+}
+
+export function resetTileRuntimeBindings(reconnectedScope?: null | string | RuntimeReconnectScope) {
const tiles = $sessionTiles.get()
+ const reconnected =
+ typeof reconnectedScope === 'string'
+ ? { connectionId: reconnectedScope.trim(), profile: null }
+ : reconnectedScope
+ ? {
+ connectionId: reconnectedScope.connectionId.trim(),
+ profile: reconnectedScope.profile?.trim() || null
+ }
+ : null
+
+ const belongsToReconnectedRuntime = (tile: SessionTile): boolean => {
+ const route = tile.ownerRoute
+
+ if (!reconnected?.connectionId || route?.connectionId !== reconnected.connectionId) {
+ return false
+ }
+
+ return !reconnected.profile || (route.targetProfile || route.profile) === reconnected.profile
+ }
+
const preservedStoredIds = new Set(
tiles
- .filter(tile => tile.workspaceMode === 'bots' && Boolean(tile.ownerRoute?.connectionId))
+ .filter(
+ tile =>
+ tile.workspaceMode === 'bots' &&
+ Boolean(tile.ownerRoute?.connectionId) &&
+ (!reconnected || !belongsToReconnectedRuntime(tile))
+ )
.map(tile => tile.storedSessionId)
)