Skip to content

The agent that grows with you

fix(desktop): keep-connected pin never blocks a gateway edit; review fixes

Teknium4841ace95384
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 1b595dfd0ce..90cacc9a372 100644
--- a/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.ts
+++ b/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.ts
@@ -14,7 +14,7 @@ import { pathFromHermesDeepLink, resolveHermesOpenPath } from '@/lib/hermes-open
import { storedSessionIdForNotification } from '@/lib/session-ids'
import { announceNewSessionDraftKey } from '@/store/composer'
import { recordAction } from '@/store/desktop-metrics'
-import { onKeptGatewayConnected } from '@/store/gateway-persistence'
+import { onKeptRouteOpened } from '@/store/gateway-kept-routes'
import { requestMcpInstallFromDeepLink } from '@/store/mcp-deeplink-install'
import { startMcpHealthChecker, stopMcpHealthChecker } from '@/store/mcp-health'
import {
@@ -564,5 +564,5 @@ export function useDesktopIntegrations({
}, [refreshSessions])
// A gateway that connects after the list was drawn adds its rows to it.
- useEffect(() => onKeptGatewayConnected(() => void refreshSessions()), [refreshSessions])
+ useEffect(() => onKeptRouteOpened(() => void refreshSessions()), [refreshSessions])
}
diff --git a/apps/desktop/src/store/connections.test.ts b/apps/desktop/src/store/connections.test.ts
index 11cca2ec21a..5b6efb87ec2 100644
--- a/apps/desktop/src/store/connections.test.ts
+++ b/apps/desktop/src/store/connections.test.ts
@@ -347,6 +347,57 @@ describe('selectConnection', () => {
expect($connection.get()?.connectionId).toBe('local')
})
+ it.each(['remote', 'cloud'] as const)(
+ 'requires protected REST auth on a warm %s socket before replacing the current chat',
+ async kind => {
+ const oauthRegistry: DesktopConnectionsRegistry = {
+ ...registry,
+ connections: registry.connections.map(connection =>
+ connection.id === 'homelab' ? { ...connection, kind, authMode: 'oauth' } : connection
+ )
+ }
+
+ setConnectionsRegistry(oauthRegistry)
+ const source = { connectionId: 'work-vps', mode: 'remote' as const, profile: 'research', registryScoped: true }
+ $connection.set(source)
+ $activeGatewayProfile.set('research')
+ $activeSessionId.set('source-runtime')
+ $newChatProfile.set('research')
+ setApiRequestConnection('work-vps')
+ setApiRequestProfile('research')
+ setLastUsed.mockImplementationOnce(async id => ({ ok: true, registry: { ...oauthRegistry, lastUsed: id } }))
+
+ // A kept socket already passed its handshake; opening it succeeds even
+ // though fresh REST requests no longer authenticate.
+ const expired = new Error(kind === 'remote' ? '401 Unauthorized: no_cookie' : '403 Forbidden: session expired')
+ api.mockRejectedValueOnce(expired)
+
+ await expect(selectConnection('homelab', { profile: 'scout' })).rejects.toBe(expired)
+ expect($connection.get()).toBe(source)
+ expect($activeSessionId.get()).toBe('source-runtime')
+ expect($newChatProfile.get()).toBe('research')
+ expect(ensureGatewayAgent).not.toHaveBeenCalled()
+ expect(requestFreshSession).not.toHaveBeenCalled()
+ expect(exitProjectScope).not.toHaveBeenCalled()
+ expect(setLastUsed).not.toHaveBeenCalled()
+
+ // Auth refreshed externally: the next click proves the read again and lands.
+ await selectConnection('homelab', { profile: 'scout' })
+ expect(api).toHaveBeenCalledTimes(2)
+ expect($activeConnectionId.get()).toBe('homelab')
+ expect($activeSessionId.get()).toBeNull()
+ }
+ )
+
+ it("leaves the old gateway's project before the fresh draft is requested", async () => {
+ setConnectionsRegistry(registry)
+ $connection.set({ connectionId: 'local', mode: 'local' })
+
+ await selectConnection('homelab')
+
+ expect(exitProjectScope.mock.invocationCallOrder[0]).toBeLessThan(requestFreshSession.mock.invocationCallOrder[0])
+ })
+
it("#93937: the previous gateway's runtime is unbound BEFORE the picked gateway is published", async () => {
setConnectionsRegistry(registry)
$connection.set({ connectionId: 'local', mode: 'local' })
diff --git a/apps/desktop/src/store/connections.ts b/apps/desktop/src/store/connections.ts
index e54c4c1eb07..c3f024a246a 100644
--- a/apps/desktop/src/store/connections.ts
+++ b/apps/desktop/src/store/connections.ts
@@ -1,5 +1,6 @@
import { atom, computed } from 'nanostores'
+import { getProfiles } from '@/api/profiles'
import type { DesktopConnectionsRegistry } from '@/global'
import { traceIdentityChange } from '@/lib/identity-trace'
import { invalidateProfileScopedQueries } from '@/lib/query-client'
@@ -462,6 +463,12 @@ export async function selectConnection(connectionId: string, options: SelectConn
$showAllProfiles.set(false)
}
+ // Project ids name rows in one backend's projects.db; leave before the
+ // fresh draft copies the project's folder into its cwd.
+ if (currentConnectionId !== connectionId) {
+ exitProjectScope()
+ }
+
if (currentNewChatIntent() === draftIntent) {
// The open runtime belongs to the gateway being left; unbind it now, not
// when the fresh draft renders, so nothing pairs it with the target.
@@ -485,6 +492,24 @@ export async function selectConnection(connectionId: string, options: SelectConn
return
}
+ // A kept socket can outlive cookie/native OAuth REST auth. Prove the
+ // cheapest protected read before the draft is replaced; the exact failure
+ // reaches the caller (network failures are not sign-in errors).
+ if (
+ targetConnection.authMode === 'oauth' &&
+ (targetConnection.kind === 'remote' || targetConnection.kind === 'cloud')
+ ) {
+ await withTimeout(
+ getProfiles({ connectionId, profile: targetProfile }),
+ SOURCE_SWITCH_DIAL_TIMEOUT_MS,
+ timeoutMessage
+ )
+
+ if (revision !== switchRevision) {
+ return
+ }
+ }
+
try {
await withTimeout(
ensureGatewayAgent(connectionId, targetProfile, { beforeActivate, signal: activation.signal }),
@@ -507,11 +532,6 @@ export async function selectConnection(connectionId: string, options: SelectConn
throw new Error(`Connection "${targetConnection.label}" did not become active.`)
}
- // Project ids name rows in one backend's projects.db.
- if (currentConnectionId !== connectionId) {
- exitProjectScope()
- }
-
await rememberConnection(connectionId)
if (revision === switchRevision) {
diff --git a/apps/desktop/src/store/gateway-kept-routes.test.ts b/apps/desktop/src/store/gateway-kept-routes.test.ts
new file mode 100644
index 00000000000..8793a4e1928
--- /dev/null
+++ b/apps/desktop/src/store/gateway-kept-routes.test.ts
@@ -0,0 +1,95 @@
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+
+const gatewayMocks = vi.hoisted(() => ({
+ connect: vi.fn(async (_wsUrl: string): Promise<void> => undefined)
+}))
+
+vi.mock('@/hermes', () => ({
+ setApiRequestConnection: vi.fn(),
+ HermesGateway: class {
+ connectionState = 'closed'
+ connect = async (wsUrl: string): Promise<void> => {
+ await gatewayMocks.connect(wsUrl)
+ this.connectionState = 'open'
+ }
+ close = (): void => {
+ this.connectionState = 'closed'
+ }
+ request = async (): Promise<unknown> => ({})
+ onEvent = vi.fn(() => () => {})
+ onState = vi.fn(() => () => {})
+ }
+}))
+vi.mock('@/store/session', () => ({ setConnection: vi.fn(), setGatewayState: vi.fn() }))
+vi.mock('@/store/notify-baseline', () => ({ markNativeNotifyBaseline: vi.fn() }))
+
+const {
+ closeSecondaryGateways,
+ configureGatewayRegistry,
+ disposeSecondariesForConnection,
+ openGatewayForAgent,
+ pruneSecondaryGateways,
+ setPrimaryGateway
+} = await import('./gateway')
+
+const { keepRoute, onKeptRouteOpened } = await import('./gateway-kept-routes')
+
+let endpoint = 'wss://homelab.invalid/api/ws?token=old'
+
+/** Idle long enough that the pruner's young-socket grace no longer applies. */
+function pastMinLifetime(): void {
+ const later = Date.now() + 10 * 60_000
+ vi.spyOn(Date, 'now').mockReturnValue(later)
+}
+
+beforeEach(() => {
+ endpoint = 'wss://homelab.invalid/api/ws?token=old'
+ configureGatewayRegistry({ onEvent: vi.fn() })
+ setPrimaryGateway({ connectionState: 'open' } as never, 'default')
+ ;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = {
+ getConnection: vi.fn(async () => ({ mode: 'remote', wsUrl: endpoint })),
+ getConnectionFor: vi.fn(async () => ({ mode: 'remote', wsUrl: endpoint }))
+ }
+})
+
+afterEach(() => {
+ closeSecondaryGateways()
+ vi.restoreAllMocks()
+ vi.clearAllMocks()
+ delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop
+})
+
+it('a kept gateway survives idle pruning, yet an edit to it redials onto the new endpoint at once', async () => {
+ const release = keepRoute('homelab', 'default')
+ const opened = vi.fn()
+ const off = onKeptRouteOpened(opened)
+
+ await openGatewayForAgent('homelab', 'default')
+ pastMinLifetime()
+ pruneSecondaryGateways(new Set())
+ expect(gatewayMocks.connect).toHaveBeenCalledTimes(1)
+
+ // The user edits the gateway's token: the keep pin must not hold the old socket.
+ endpoint = 'wss://homelab.invalid/api/ws?token=new'
+ disposeSecondariesForConnection('homelab', { redial: true })
+ await vi.waitFor(() => expect(gatewayMocks.connect).toHaveBeenLastCalledWith(endpoint))
+
+ // Both opens (first dial and the redial) announce themselves, so lists re-pull.
+ expect(opened).toHaveBeenCalledTimes(2)
+ off()
+ release()
+})
+
+it('an unkept route is still pruned when idle and announces nothing', async () => {
+ const opened = vi.fn()
+ const off = onKeptRouteOpened(opened)
+
+ await openGatewayForAgent('homelab', 'research')
+ pastMinLifetime()
+ pruneSecondaryGateways(new Set())
+ await openGatewayForAgent('homelab', 'research')
+
+ expect(gatewayMocks.connect).toHaveBeenCalledTimes(2)
+ expect(opened).not.toHaveBeenCalled()
+ off()
+})
diff --git a/apps/desktop/src/store/gateway-kept-routes.ts b/apps/desktop/src/store/gateway-kept-routes.ts
new file mode 100644
index 00000000000..4172ca2411e
--- /dev/null
+++ b/apps/desktop/src/store/gateway-kept-routes.ts
@@ -0,0 +1,31 @@
+// Routes Desktop keeps connected for the window's lifetime (store/gateway-persistence).
+// A leaf module, so store/gateway can consult it without importing its consumer.
+const kept = new Set<string>()
+const openedListeners = new Set<() => void>()
+
+const routeKey = (connectionId: null | string, profile: string) => `${connectionId ?? ''}\u0000${profile}`
+
+/** Keep one route's socket open against every idle-dispose path. Returns the release. */
+export function keepRoute(connectionId: string, profile: string): () => void {
+ const key = routeKey(connectionId, profile)
+ kept.add(key)
+
+ return () => kept.delete(key)
+}
+
+export function isKeptRoute(connectionId: null | string, profile: string): boolean {
+ return kept.has(routeKey(connectionId, profile))
+}
+
+/** Fires each time a kept route's socket opens, first dial or automatic reconnect alike. */
+export function onKeptRouteOpened(handler: () => void): () => void {
+ openedListeners.add(handler)
+
+ return () => openedListeners.delete(handler)
+}
+
+export function keptRouteOpened(connectionId: null | string, profile: string): void {
+ if (isKeptRoute(connectionId, profile)) {
+ openedListeners.forEach(handler => handler())
+ }
+}
diff --git a/apps/desktop/src/store/gateway-persistence.test.ts b/apps/desktop/src/store/gateway-persistence.test.ts
index 2f43f6c7c39..0a0027e529b 100644
--- a/apps/desktop/src/store/gateway-persistence.test.ts
+++ b/apps/desktop/src/store/gateway-persistence.test.ts
@@ -3,15 +3,15 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import type { DesktopConnectionsRegistry } from '@/global'
const released: string[] = []
-const retainGatewayForRelay = vi.fn((connectionId: string) => () => released.push(connectionId))
+const keepRoute = vi.fn((connectionId: string, _profile: string) => () => released.push(connectionId))
const openGatewayForAgent = vi.fn(async (_connectionId: string, _profile: string) => undefined)
const live = new Set<string>()
vi.mock('@/store/gateway', () => ({
liveSecondaryConnectionIds: () => new Set(live),
- openGatewayForAgent,
- retainGatewayForRelay
+ openGatewayForAgent
}))
+vi.mock('@/store/gateway-kept-routes', () => ({ keepRoute }))
const { $connectionsRegistry } = await import('@/store/connection-registry-state')
const { $primaryGatewayRoute } = await import('@/store/gateway-primary-route')
@@ -32,11 +32,17 @@ const registry = (ids: string[]): DesktopConnectionsRegistry => ({
let stop: () => void = () => undefined
+function installProbe(bootstrapNeeded: boolean): void {
+ ;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = {
+ probeLocalBackend: vi.fn(async () => ({ bootstrapNeeded }))
+ }
+}
+
beforeEach(() => {
vi.useFakeTimers()
released.length = 0
live.clear()
- retainGatewayForRelay.mockClear()
+ keepRoute.mockClear()
openGatewayForAgent.mockClear()
$primaryGatewayRoute.set({ connectionId: 'local', mode: 'local' })
$connectionsRegistry.set(registry(['local', 'homelab', 'vps']))
@@ -45,12 +51,16 @@ beforeEach(() => {
afterEach(() => {
stop()
vi.useRealTimers()
+ delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop
})
it('keeps every registered gateway the primary socket does not serve connected, and lets a removed one go', () => {
stop = startPersistentGateways()
- expect(retainGatewayForRelay.mock.calls.map(call => call[0])).toEqual(['homelab', 'vps'])
+ expect(keepRoute.mock.calls).toEqual([
+ ['homelab', 'default'],
+ ['vps', 'default']
+ ])
expect(openGatewayForAgent.mock.calls).toEqual([
['homelab', 'default'],
['vps', 'default']
@@ -64,15 +74,25 @@ it('keeps every registered gateway the primary socket does not serve connected,
$connectionsRegistry.set(registry(['local', 'homelab']))
expect(released).toEqual(['vps'])
- expect(retainGatewayForRelay).toHaveBeenCalledTimes(2)
+ expect(keepRoute).toHaveBeenCalledTimes(2)
})
-it('pins This device on its own socket when a remote gateway is the primary', () => {
+it('with a remote primary, keeps This device only where Hermes is installed (never starts the installer)', async () => {
$primaryGatewayRoute.set({ connectionId: 'homelab', mode: 'remote' })
+ installProbe(true)
stop = startPersistentGateways()
+ await vi.advanceTimersByTimeAsync(0)
+
+ expect(openGatewayForAgent.mock.calls).toEqual([['vps', 'default']])
- expect(retainGatewayForRelay.mock.calls).toEqual([
- ['local', 'default', { includeLocal: true }],
- ['vps', 'default', { includeLocal: true }]
+ stop()
+ openGatewayForAgent.mockClear()
+ installProbe(false)
+ stop = startPersistentGateways()
+ await vi.advanceTimersByTimeAsync(0)
+
+ expect(openGatewayForAgent.mock.calls).toEqual([
+ ['vps', 'default'],
+ ['local', 'default']
])
})
diff --git a/apps/desktop/src/store/gateway-persistence.ts b/apps/desktop/src/store/gateway-persistence.ts
index 8b4148788ea..3bc67b4aaf0 100644
--- a/apps/desktop/src/store/gateway-persistence.ts
+++ b/apps/desktop/src/store/gateway-persistence.ts
@@ -2,11 +2,12 @@ import { LOCAL_CONNECTION_ID } from '@hermes/shared'
import type { DesktopConnectionsRegistry, DesktopRegistryConnection } from '@/global'
import { $connectionsRegistry } from '@/store/connection-registry-state'
-import { liveSecondaryConnectionIds, openGatewayForAgent, retainGatewayForRelay } from '@/store/gateway'
+import { liveSecondaryConnectionIds, openGatewayForAgent } from '@/store/gateway'
+import { keepRoute } from '@/store/gateway-kept-routes'
import { $primaryGatewayRoute, type PrimaryGatewayRoute } from '@/store/gateway-primary-route'
// Every registered gateway stays connected for as long as the window lives: its
-// home socket is dialed at startup, pinned against the idle pruner, and redialed
+// home socket is dialed at startup, kept against the idle pruner, and redialed
// when it drops. Picking a gateway or opening one of its sessions then costs no
// dial, and the unified Sessions list (Electron splices every pooled backend's
// rows) shows every gateway at once instead of only the one in front.
@@ -23,7 +24,7 @@ function servedByPrimary(connection: DesktopRegistryConnection, primary: Primary
return connection.id === LOCAL_CONNECTION_ID && primary.mode !== 'remote'
}
-/** The registry connections that need their own pinned socket. */
+/** The registry connections that need their own kept socket. */
export function persistentGatewayIds(
registry: DesktopConnectionsRegistry | null,
primary: PrimaryGatewayRoute
@@ -31,23 +32,22 @@ export function persistentGatewayIds(
return (registry?.connections ?? []).filter(connection => !servedByPrimary(connection, primary)).map(c => c.id)
}
-const connectedListeners = new Set<() => void>()
+/** Dialing This device where Hermes is not installed would start the installer
+ * unseen; only a confirmed click may do that. A missing probe fails closed. */
+async function localInstalled(): Promise<boolean> {
+ const probe = window.hermesDesktop?.probeLocalBackend
-/** Fires each time a kept gateway (re)connects, so lists drawn before it was
- * reachable re-pull its rows. Returns the unsubscribe. */
-export function onKeptGatewayConnected(handler: () => void): () => void {
- connectedListeners.add(handler)
-
- return () => connectedListeners.delete(handler)
+ return probe ? (await probe()).bootstrapNeeded !== true : false
}
-function dial(connectionId: string): void {
+async function dial(connectionId: string): Promise<void> {
+ if (connectionId === LOCAL_CONNECTION_ID && !(await localInstalled())) {
+ return
+ }
+
// Background priority: a gateway that is down or needs sign-in fails fast and
// stays throttled; the next tick (or a focus/online nudge) tries again.
- void openGatewayForAgent(connectionId, HOME_PROFILE).then(
- () => connectedListeners.forEach(handler => handler()),
- () => undefined
- )
+ await openGatewayForAgent(connectionId, HOME_PROFILE)
}
/** Start keeping every registered gateway connected. Returns the teardown. */
@@ -68,11 +68,11 @@ export function startPersistentGateways(): () => void {
for (const connectionId of wanted) {
if (!pins.has(connectionId)) {
- pins.set(connectionId, retainGatewayForRelay(connectionId, HOME_PROFILE, { includeLocal: true }))
+ pins.set(connectionId, keepRoute(connectionId, HOME_PROFILE))
}
if (!live.has(connectionId)) {
- dial(connectionId)
+ void dial(connectionId).catch(() => undefined)
}
}
}
diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.ts
index e03c59a7d28..3a3856238d5 100644
--- a/apps/desktop/src/store/gateway.ts
+++ b/apps/desktop/src/store/gateway.ts
@@ -32,6 +32,7 @@ import {
} from '@/lib/with-timeout'
import { $gatewayActivationEpoch } from '@/store/gateway-activation-epoch'
import { isMissingConnectionError, isMissingProfileError } from '@/store/gateway-dial-failures'
+import { isKeptRoute, keptRouteOpened } from '@/store/gateway-kept-routes'
import { $primaryGatewayRoute } from '@/store/gateway-primary-route'
import {
isPrimaryRider,
@@ -831,6 +832,7 @@ async function openSecondary(entry: Secondary): Promise<void> {
entry.livenessProbeFailures = 0
clearSecondaryLivenessReprobe(entry)
openedScopes.add(entry.scope)
+ keptRouteOpened(entry.connectionId, entry.profile)
try {
reconcileBusyAfterOpen?.()
@@ -1368,22 +1370,20 @@ function foregroundPinned(entry: Secondary): boolean {
return scopes.has(entry.scope) || (!entry.connectionId && scopes.has(entry.profile))
}
-/** True when the bot relay currently pins this entry open. Number guard:
- * dev-HMR entries predate the field. */
+/** Pinned open: the bot relay holds it, or it is kept connected (gateway-kept-routes). */
function relayRetained(entry: Secondary): boolean {
- return Number.isFinite(entry.relayRetainCount) && entry.relayRetainCount > 0
+ return entry.relayRetainCount > 0 || isKeptRoute(entry.connectionId, entry.profile)
}
/**
- * Finish a material-edit redial once no request, relay, or foreground surface
- * still owns the old socket. Removal deliberately bypasses this drain: a
- * deleted source can never become valid again and must fail-stop immediately.
+ * Finish a material-edit redial once no request, relay lease or foreground surface owns the old socket (a keep
+ * pin never defers it). Removal bypasses this drain: a deleted source must fail-stop immediately.
*/
function drainPendingConnectionRedial(entry: Secondary): boolean {
if (
entry.pendingConnectionRedial !== true ||
entry.activeRequests > 0 ||
- relayRetained(entry) ||
+ entry.relayRetainCount > 0 ||
foregroundPinned(entry) ||
g.secondaries.get(entry.scope) !== entry
) {
@@ -1424,19 +1424,19 @@ function reopenAfterRedial(entry: Secondary, wasActive: boolean): void {
}
/**
- * Pin one route's socket open across drain ticks (bot relay; each gateway's home socket, gateway-persistence).
- * Returns a once-only release. Null, and `local` unless `includeLocal`, get a no-op: a relay pin would outlive
- * retireLocalProfileGateways' drop, and local relay traffic never floods reconnects.
+ * Pin the pooled socket for one relay route open across drain ticks. Returns
+ * a once-only release. Local routes (null/empty or explicit `local` source)
+ * are deliberately EXEMPT and get a no-op release: a relay pin would keep a
+ * local socket open past the point where retireLocalProfileGateways means to
+ * drop it (see that note). Local relay traffic is
+ * either the primary socket (no churn) or a short-lived local dial — never
+ * the remote reconnect flood this retention exists to stop.
*/
-export function retainGatewayForRelay(
- connectionId: null | string,
- profile: string,
- { includeLocal = false }: { includeLocal?: boolean } = {}
-): () => void {
+export function retainGatewayForRelay(connectionId: null | string, profile: string): () => void {
const key = normKey(profile)
const connection = String(connectionId ?? '').trim()
- if (!connection || (connection === 'local' && !includeLocal)) {
+ if (!connection || connection === 'local') {
return () => undefined
}
@@ -1465,7 +1465,7 @@ export function retainGatewayForRelay(
if (
!drainPendingConnectionRedial(entry) &&
- entry.relayRetainCount === 0 &&
+ !relayRetained(entry) &&
entry.activeRequests === 0 &&
!entry.retained &&
!foregroundPinned(entry) &&
@@ -2438,7 +2438,7 @@ export function disposeSecondariesForConnection(connectionId: string, opts: { re
const wasActive = key === g.activeKey
activeInvalidated ||= wasActive
- if (opts.redial && (entry.activeRequests > 0 || relayRetained(entry) || foregroundPinned(entry))) {
+ if (opts.redial && (entry.activeRequests > 0 || entry.relayRetainCount > 0 || foregroundPinned(entry))) {
entry.pendingConnectionRedial = true
continue