Skip to content

The agent that grows with you

fix(desktop): publish the agent activation atomically too

Jack Laud0e0951cf1db
diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.ts
index c01269867b4..570ccec6456 100644
--- a/apps/desktop/src/store/gateway.ts
+++ b/apps/desktop/src/store/gateway.ts
@@ -667,13 +667,30 @@ export async function openGatewayForAgent(connectionId: null | string, profile:
}
}
-export async function ensureGatewayForAgent(connectionId: null | string, profile: string): Promise<boolean> {
+// The agent-scoped analogue of prepareGatewayForProfile, and the same
+// publication seam: dial the agent's socket without publishing anything, and
+// hand back the synchronous activation thunk. A local/null connection falls
+// through to the profile seam, so both doors into an activation share one
+// atomicity contract instead of drifting apart.
+//
+// The thunk reports whether it actually published, preserving the `activated`
+// contract callers rely on: a source edit/remove can dispose this entry while
+// its dial is in flight, and a caller must be able to tell "switched" from
+// "the target stopped existing" rather than assume the former.
+export async function prepareGatewayForAgent(
+ connectionId: null | string,
+ profile: string
+): Promise<() => boolean> {
const scope = registryBackendScopeKey(connectionId, profile)
if (scope === normKey(profile)) {
- await ensureGatewayForProfile(profile)
+ const activate = await prepareGatewayForProfile(profile)
+
+ return () => {
+ activate()
- return true
+ return true
+ }
}
if (!window.hermesDesktop?.getConnectionFor) {
@@ -702,19 +719,28 @@ export async function ensureGatewayForAgent(connectionId: null | string, profile
}
}
- // A source edit/remove may dispose this entry while its dial is still in
- // flight. Only the still-registered, still-owned activation may publish.
- const activated =
- entry.wantOpen &&
- g.secondaries.get(scope) === entry &&
- Boolean(entry.connection) &&
- applyActive(scope, activationEpoch)
+ // Bind the entry this dial settled on; see prepareGatewayForProfile.
+ const prepared = entry
- if (activated && entry.connection) {
- publishActiveConnection(entry.connection)
+ return () => {
+ // A source edit/remove may dispose this entry while its dial is still in
+ // flight. Only the still-registered, still-owned activation may publish.
+ const activated =
+ prepared.wantOpen &&
+ g.secondaries.get(scope) === prepared &&
+ Boolean(prepared.connection) &&
+ applyActive(scope, activationEpoch)
+
+ if (activated && prepared.connection) {
+ publishActiveConnection(prepared.connection)
+ }
+
+ return activated
}
+}
- return activated
+export async function ensureGatewayForAgent(connectionId: null | string, profile: string): Promise<boolean> {
+ return (await prepareGatewayForAgent(connectionId, profile))()
}
// Open `profile`'s socket if needed and hand back a synchronous activation
diff --git a/apps/desktop/src/store/profile-agent-activation.test.ts b/apps/desktop/src/store/profile-agent-activation.test.ts
index 9e410562927..528a5d8e1aa 100644
--- a/apps/desktop/src/store/profile-agent-activation.test.ts
+++ b/apps/desktop/src/store/profile-agent-activation.test.ts
@@ -13,18 +13,40 @@ import type { HermesConnection } from '@/global'
// 2. Agent activations share the gatewaySwitch mutex with profile switches —
// without it, two rapid activations could complete out of order and the
// EARLIER setActive() landed last.
-
-const ensureGatewayForAgent = vi.fn(async (_connectionId: null | string, _profile: string) => true)
-const ensureGatewayForProfile = vi.fn(async (_profile: string) => undefined)
+// 3. An activation publishes the gateway, the profile pointer and the
+// connection descriptor in ONE synchronous frame. Activating first and
+// awaiting the descriptor after left $gateway on the new backend while
+// $connection still described the old one.
+//
+// Both doors go through the prepare/publish seam (prepareGatewayFor*, which
+// dial without publishing and return the activation thunk), so these mocks
+// hand back a spy thunk instead of activating on call.
+
+// Distinct gateway identities so a listener can tell WHICH backend it was
+// handed. A bare vi.fn() thunk never touches $gateway, which would let an
+// out-of-order publication pass unnoticed.
+const INITIAL_GATEWAY = { id: 'live-socket' }
+const AGENT_GATEWAY = { id: 'agent-socket' }
+const PROFILE_GATEWAY = { id: 'profile-socket' }
+const activateAgent = vi.fn(() => {
+ $gateway.set(AGENT_GATEWAY)
+
+ return true
+})
+const activateProfile = vi.fn(() => {
+ $gateway.set(PROFILE_GATEWAY)
+})
+const prepareGatewayForAgent = vi.fn(async (_connectionId: null | string, _profile: string) => activateAgent)
+const prepareGatewayForProfile = vi.fn(async (_profile: string) => activateProfile)
const openGatewayForProfile = vi.fn(async (_profile: string) => undefined)
-const $gateway = atom<unknown>({ id: 'live-socket' })
+const $gateway = atom<unknown>(INITIAL_GATEWAY)
const resetStarmapGraph = vi.fn()
vi.mock('@/store/gateway', () => ({
$gateway,
- ensureGatewayForAgent,
- ensureGatewayForProfile,
- openGatewayForProfile
+ openGatewayForProfile,
+ prepareGatewayForAgent,
+ prepareGatewayForProfile
}))
vi.mock('@/hermes', () => ({
getProfiles: vi.fn(async () => ({ profiles: [] })),
@@ -60,8 +82,12 @@ function deferred(): { promise: Promise<void>; resolve: () => void } {
beforeEach(() => {
getConnection.mockReset()
getConnectionFor.mockReset()
- ensureGatewayForAgent.mockClear()
- ensureGatewayForProfile.mockClear()
+ prepareGatewayForAgent.mockReset()
+ prepareGatewayForAgent.mockResolvedValue(activateAgent)
+ prepareGatewayForProfile.mockReset()
+ prepareGatewayForProfile.mockResolvedValue(activateProfile)
+ activateAgent.mockClear()
+ activateProfile.mockClear()
$gateway.set({ id: 'live-socket' })
$activeGatewayProfile.set('default')
$connection.set(localConn())
@@ -81,7 +107,8 @@ describe('ensureGatewayAgent → $connection / $activeGatewayProfile sync', () =
await ensureGatewayAgent('homelab', 'research')
- expect(ensureGatewayForAgent).toHaveBeenCalledWith('homelab', 'research')
+ expect(prepareGatewayForAgent).toHaveBeenCalledWith('homelab', 'research')
+ expect(activateAgent).toHaveBeenCalledTimes(1)
expect(getConnectionFor).toHaveBeenCalledWith({ connectionId: 'homelab', profile: 'research' })
expect($activeGatewayProfile.get()).toBe('research')
expect($connection.get()?.mode).toBe('remote')
@@ -113,8 +140,8 @@ describe('ensureGatewayAgent → $connection / $activeGatewayProfile sync', () =
await ensureGatewayAgent(null, 'research')
- expect(ensureGatewayForProfile).toHaveBeenCalledWith('research')
- expect(ensureGatewayForAgent).not.toHaveBeenCalled()
+ expect(prepareGatewayForProfile).toHaveBeenCalledWith('research')
+ expect(prepareGatewayForAgent).not.toHaveBeenCalled()
expect(getConnectionFor).not.toHaveBeenCalled()
})
@@ -123,10 +150,40 @@ describe('ensureGatewayAgent → $connection / $activeGatewayProfile sync', () =
await ensureGatewayAgent('local', 'research')
- expect(ensureGatewayForAgent).toHaveBeenCalledWith('local', 'research')
- expect(ensureGatewayForProfile).not.toHaveBeenCalled()
+ expect(prepareGatewayForAgent).toHaveBeenCalledWith('local', 'research')
+ expect(prepareGatewayForProfile).not.toHaveBeenCalled()
expect(getConnectionFor).toHaveBeenCalledWith({ connectionId: 'local', profile: 'research' })
})
+
+ it('never publishes the agent gateway before its connection descriptor', async () => {
+ // The same mixed-state window the profile path closes, through the door
+ // added for the SDK's ensureAgent. A slow getConnectionFor must not leave
+ // $gateway/$activeGatewayProfile on the agent's backend while $connection
+ // still describes the previous one — anything requesting in that window
+ // announces the WRONG mode to the new backend.
+ let resolveDescriptor: (conn: HermesConnection) => void = () => undefined
+ getConnectionFor.mockReturnValue(
+ new Promise<HermesConnection>(resolve => {
+ resolveDescriptor = resolve
+ })
+ )
+
+ const switching = ensureGatewayAgent('homelab', 'research')
+ // Let the socket-dial half settle; the descriptor is still pending.
+ await Promise.resolve()
+ await Promise.resolve()
+
+ expect(activateAgent).not.toHaveBeenCalled()
+ expect($activeGatewayProfile.get()).toBe('default')
+ expect($connection.get()?.mode).toBe('local')
+
+ resolveDescriptor(agentConn())
+ await switching
+
+ expect(activateAgent).toHaveBeenCalledTimes(1)
+ expect($activeGatewayProfile.get()).toBe('research')
+ expect($connection.get()?.mode).toBe('remote')
+ })
})
describe('ensureGatewayAgent shares the gatewaySwitch mutex with profile switches', () => {
@@ -134,14 +191,16 @@ describe('ensureGatewayAgent shares the gatewaySwitch mutex with profile switche
const profileGate = deferred()
const order: string[] = []
- ensureGatewayForProfile.mockImplementation(async (profile: string) => {
+ prepareGatewayForProfile.mockImplementation(async (profile: string) => {
order.push(`profile:${profile}`)
await profileGate.promise
+
+ return activateProfile
})
- ensureGatewayForAgent.mockImplementation(async (_connectionId, profile) => {
+ prepareGatewayForAgent.mockImplementation(async (_connectionId, profile) => {
order.push(`agent:${profile}`)
- return true
+ return activateAgent
})
getConnection.mockResolvedValue(localConn({ profile: 'worker' }))
getConnectionFor.mockResolvedValue(agentConn())
@@ -170,14 +229,16 @@ describe('ensureGatewayAgent shares the gatewaySwitch mutex with profile switche
const agentGate = deferred()
const order: string[] = []
- ensureGatewayForAgent.mockImplementation(async (_connectionId, profile) => {
+ prepareGatewayForAgent.mockImplementation(async (_connectionId, profile) => {
order.push(`agent:${profile}`)
await agentGate.promise
- return true
+ return activateAgent
})
- ensureGatewayForProfile.mockImplementation(async (profile: string) => {
+ prepareGatewayForProfile.mockImplementation(async (profile: string) => {
order.push(`profile:${profile}`)
+
+ return activateProfile
})
getConnection.mockResolvedValue(localConn({ profile: 'worker' }))
getConnectionFor.mockResolvedValue(agentConn())
diff --git a/apps/desktop/src/store/profile.test.ts b/apps/desktop/src/store/profile.test.ts
index 95b9f6957f4..1732e0e726c 100644
--- a/apps/desktop/src/store/profile.test.ts
+++ b/apps/desktop/src/store/profile.test.ts
@@ -8,7 +8,7 @@ import type { ProfileInfo } from '@/types/hermes'
// the REST query client must not run for real in a unit test.
const activateGateway = vi.fn()
const ensureGatewayForProfile = vi.fn(async () => undefined)
-const ensureGatewayForAgent = vi.fn(async () => undefined)
+const prepareGatewayForAgent = vi.fn(async (_connectionId: null | string, _profile: string) => activateGateway)
const prepareGatewayForProfile = vi.fn(async (_profile: string) => activateGateway)
const openGatewayForProfile = vi.fn(async (_profile: string) => undefined)
const $gateway = atom<unknown>({ id: 'live-socket' })
@@ -16,9 +16,9 @@ const resetStarmapGraph = vi.fn()
vi.mock('@/store/gateway', () => ({
$gateway,
- ensureGatewayForAgent,
ensureGatewayForProfile,
openGatewayForProfile,
+ prepareGatewayForAgent,
prepareGatewayForProfile
}))
vi.mock('@/hermes', () => ({
diff --git a/apps/desktop/src/store/profile.ts b/apps/desktop/src/store/profile.ts
index f1b7c0ad390..4adcd7c5b96 100644
--- a/apps/desktop/src/store/profile.ts
+++ b/apps/desktop/src/store/profile.ts
@@ -1,5 +1,6 @@
-import { atom, computed } from 'nanostores'
+import { atom, batch, computed } from 'nanostores'
+import type { HermesConnection } from '@/global'
import { getProfiles, setApiRequestProfile, STARTUP_REQUEST_TIMEOUT_MS } from '@/hermes'
import { invalidateProfileScopedQueries } from '@/lib/query-client'
import {
@@ -14,8 +15,8 @@ import {
import { invalidateCronModelImpactScopeState } from '@/store/cron-model-impact-scope'
import {
$gateway,
- ensureGatewayForAgent,
openGatewayForProfile,
+ prepareGatewayForAgent,
prepareGatewayForProfile
} from '@/store/gateway'
import { setConnection } from '@/store/session'
@@ -342,14 +343,19 @@ export async function ensureGatewayProfile(profile: string | null | undefined):
prepareGatewayForProfile(target)
])
- // One synchronous publication frame — no awaits from here down, so the
- // active gateway, $activeGatewayProfile, and $connection flip together.
- activate()
- $activeGatewayProfile.set(target)
-
- if (connection) {
- setConnection(connection)
- }
+ // ONE publication. batch() defers Nanostores' notifications to the end of
+ // the callback, so the active gateway, $activeGatewayProfile and
+ // $connection become visible together. Without it these are sequential
+ // .set() calls that each drain their listeners synchronously, and a
+ // $gateway listener runs while the other two still name the old backend.
+ batch(() => {
+ activate()
+ $activeGatewayProfile.set(target)
+
+ if (connection) {
+ setConnection(connection)
+ }
+ })
})().catch(() => {
// Descriptor lookup failed: the switch fails as a unit. Nothing was
// published, so every atom still consistently describes the previous
@@ -367,24 +373,32 @@ export async function ensureGatewayProfile(profile: string | null | undefined):
// Registry-aware sibling of syncConnectionToActiveProfile: a connection-scoped
// agent's descriptor comes from getConnectionFor (its SOURCE connection), not
// getConnection (the local pool). Same best-effort contract.
-async function syncConnectionToActiveAgent(connectionId: string, profile: string): Promise<void> {
+// Resolve only — publication is the caller's, so the descriptor can be in hand
+// BEFORE the activation frame rather than an await after it. Null means "no
+// descriptor to publish" (no desktop bridge, or the lookup failed): the caller
+// leaves the prior connection in place and boot/reconnect resyncs it later,
+// which is this path's established best-effort contract.
+async function resolveConnectionForActiveAgent(
+ connectionId: string,
+ profile: string
+): Promise<null | HermesConnection> {
const getConnectionFor = window.hermesDesktop?.getConnectionFor
if (!getConnectionFor) {
- return
+ return null
}
try {
- setConnection(await getConnectionFor({ connectionId, profile }))
+ return await getConnectionFor({ connectionId, profile })
} catch {
- // Leave the prior connection in place; boot/reconnect resyncs it later.
+ return null
}
}
// Activate a connection-scoped agent's gateway — the (connectionId, profile)
// analogue of ensureGatewayProfile, and the door the SDK's ensureAgent goes
-// through. Two invariants the raw store call (ensureGatewayForAgent) does not
-// provide on its own:
+// through. Three invariants the raw store call (ensureGatewayForAgent) does
+// not provide on its own:
// - Every activation moves $activeGatewayProfile and resyncs $connection,
// exactly like the profile path — otherwise activating an ALREADY-OPEN
// registry agent left both describing the previous backend, routing
@@ -393,6 +407,11 @@ async function syncConnectionToActiveAgent(connectionId: string, profile: string
// - Activations share the gatewaySwitch mutex with profile switches, so a
// rapid agent↔profile (or agent↔agent) interleave can't finish out of
// order and leave the EARLIER setActive() as the last write.
+// - The gateway, the profile pointer and the connection descriptor publish in
+// ONE synchronous frame, via the same prepare/publish seam the profile path
+// uses, so no subscriber sees the new backend paired with the old
+// descriptor.
+// A local/null connectionId falls through to the profile path verbatim.
// Only a null connectionId falls through to the legacy profile path. Explicit
// `local` is a registry identity and must use the genuinely-local route.
export async function ensureGatewayAgent(connectionId: null | string, profile: string): Promise<void> {
@@ -410,16 +429,39 @@ export async function ensureGatewayAgent(connectionId: null | string, profile: s
$gatewaySwapTarget.set(target)
gatewaySwitch = (async () => {
- const activated = await ensureGatewayForAgent(connection, target)
-
- if (!activated) {
- return
- }
+ // Dial the agent's socket and resolve its descriptor without publishing
+ // either, exactly like the profile path above. Activating first and then
+ // awaiting the descriptor left $gateway on the new backend while
+ // $connection still described the old one, so anything requesting during
+ // that window announced the WRONG mode to the new backend.
+ const [descriptor, activate] = await Promise.all([
+ resolveConnectionForActiveAgent(connection, target),
+ prepareGatewayForAgent(connection, target)
+ ])
- $activeGatewayProfile.set(target)
- // The active backend just changed; resync $connection so remote-aware
- // paths (image.attach_bytes vs image.attach, /api/fs/*, /api/media) follow.
- await syncConnectionToActiveAgent(connection, target)
+ // ONE publication. batch() defers Nanostores' notifications to the end of
+ // the callback, so a $gateway listener cannot run while the profile
+ // pointer and the connection descriptor still name the previous backend.
+ // Without it these are three sequential .set() calls, each draining its
+ // listeners synchronously, and the first listener observes exactly the
+ // mismatch this seam exists to prevent.
+ batch(() => {
+ // A disposed target (source edited/removed mid-dial) publishes nothing
+ // at all, rather than moving the profile pointer to a backend that no
+ // longer has a socket.
+ if (!activate()) {
+ return
+ }
+
+ $activeGatewayProfile.set(target)
+
+ // Remote-aware paths (image.attach_bytes vs image.attach, /api/fs/*,
+ // /api/media) follow $connection. A null descriptor keeps the previous
+ // one rather than clearing it, per resolveConnectionForActiveAgent.
+ if (descriptor) {
+ setConnection(descriptor)
+ }
+ })
})()
try {