fix(desktop): fail the agent switch closed when its descriptor lookup rejects

Review caught that the agent path fixed the pending-descriptor race but not
the failure path. `resolveConnectionForActiveAgent` caught a
`getConnectionFor` rejection and returned null, so `Promise.all` resolved as
`[null, activate]` and the switch published anyway: the activation thunk ran
and `$activeGatewayProfile` advanced, while only `setConnection` was skipped.

That is the same mixed state this PR exists to remove, except it does not
close on its own. The pending-descriptor window ends when the descriptor
arrives; a failed lookup never arrives, so `$gateway` named the new backend
while `$connection` described the old one until an unrelated reconnect or
switch happened to repair it. Anything branching on connection mode in
between (plugins, `MEDIA:`, `/api/fs/*`, `/api/media`, image attach) saw the
pair disagree.

Let the rejection propagate, matching `resolveConnectionForProfile`, whose
contract is already exactly this: null means "no desktop bridge" and nothing
else, and a bridge rejection aborts the whole switch before anything is
published. Both doors now fail closed identically, and the caller can retry.

The existing "leaves the prior connection intact when the descriptor fetch
fails" test asserted the old best-effort behaviour, so it pinned the defect
rather than a contract worth keeping. Replaced with a rejected-descriptor
test that asserts none of the three atoms moved and the activation thunk was
never called. The pending-descriptor case keeps its own separate test, so the
success and failure contracts are pinned independently.

Also reworded the publication comments: these are sequential atom writes with
no asynchronous gap between them, not a transaction, and describing them as
one "frame" overstated the guarantee.
This commit is contained in:
Jack Lau
2026-08-16 08:13:29 -05:00
committed by Teknium
parent d0e0951cf1
commit 20ccf88acd
2 changed files with 35 additions and 24 deletions
@@ -13,10 +13,15 @@ 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.
// 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.
// 3. A SUCCEEDING activation publishes the gateway, the profile pointer and
// the connection descriptor with no asynchronous gap between them.
// Activating first and awaiting the descriptor after left $gateway on the
// new backend while $connection still described the old one.
// 4. A FAILING descriptor lookup publishes none of the three. Swallowing the
// rejection and publishing anyway produced the same mixed state as (3),
// except permanent: (3) closes when the descriptor arrives, whereas a
// failed lookup never arrives and the split survived until an unrelated
// reconnect or switch repaired it.
//
// Both doors go through the prepare/publish seam (prepareGatewayFor*, which
// dial without publishing and return the activation thunk), so these mocks
@@ -115,14 +120,22 @@ describe('ensureGatewayAgent → $connection / $activeGatewayProfile sync', () =
expect($connection.get()?.profile).toBe('research')
})
it('leaves the prior connection intact when the descriptor fetch fails', async () => {
it('fails the switch closed when the descriptor lookup rejects', async () => {
// Previously this path swallowed the rejection and published anyway, which
// left $gateway and $activeGatewayProfile on the NEW backend while
// $connection still described the old one. Unlike the pending-descriptor
// race below, that state did not close on its own: it survived until some
// later reconnect or switch happened to repair it.
getConnectionFor.mockRejectedValue(new Error('source unreachable'))
await ensureGatewayAgent('homelab', 'research')
await expect(ensureGatewayAgent('homelab', 'research')).rejects.toThrow('source unreachable')
expect($activeGatewayProfile.get()).toBe('research')
// Best-effort: boot/reconnect resyncs later; we must not null it out here.
// Nothing published: all three still describe the previous backend, and the
// caller can retry the switch.
expect(activateAgent).not.toHaveBeenCalled()
expect($activeGatewayProfile.get()).toBe('default')
expect($connection.get()?.mode).toBe('local')
expect($connection.get()?.profile).toBe('default')
})
it('does not republish a registry identity invalidated during activation', async () => {
+14 -16
View File
@@ -372,27 +372,24 @@ 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.
// getConnection (the local pool).
// 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.
// BEFORE the activation frame rather than an await after it.
//
// Null means "no desktop bridge" (plain browser) and nothing else, matching
// resolveConnectionForProfile. A bridge REJECTION propagates so the caller
// aborts the whole switch. Collapsing the two into null instead let a failed
// lookup publish the new gateway and profile while $connection kept describing
// the OLD backend, and unlike the pending-descriptor race that state did not
// close on its own: it survived until some later reconnect or switch happened
// to repair it, which is the same invariant this path exists to establish.
async function resolveConnectionForActiveAgent(
connectionId: string,
profile: string
): Promise<null | HermesConnection> {
const getConnectionFor = window.hermesDesktop?.getConnectionFor
if (!getConnectionFor) {
return null
}
try {
return await getConnectionFor({ connectionId, profile })
} catch {
return null
}
return getConnectionFor ? getConnectionFor({ connectionId, profile }) : null
}
// Activate a connection-scoped agent's gateway — the (connectionId, profile)
@@ -456,8 +453,9 @@ export async function ensureGatewayAgent(connectionId: null | string, profile: s
$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.
// /api/media) follow $connection. Null here is only the no-bridge case,
// so keeping the previous descriptor is correct; a failed lookup
// rejected above and never reached this frame.
if (descriptor) {
setConnection(descriptor)
}