Skip to content

The agent that grows with you

fix(desktop): guard the profile publication on its activation result too

Jack Lau4e520f0850d1
diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.ts
index 8a354a1423c..5d4de94fb94 100644
--- a/apps/desktop/src/store/gateway.ts
+++ b/apps/desktop/src/store/gateway.ts
@@ -680,14 +680,12 @@ export async function openGatewayForAgent(connectionId: null | string, profile:
export async function prepareGatewayForAgent(connectionId: null | string, profile: string): Promise<() => boolean> {
const scope = registryBackendScopeKey(connectionId, profile)
+ // Genuinely-local scope: the profile door owns this route, so hand back ITS
+ // thunk unchanged. Wrapping it to return an unconditional `true` would have
+ // reported a rejected activation as a successful one and let the agent
+ // caller publish companion state for a switch that never happened.
if (scope === normKey(profile)) {
- const activate = await prepareGatewayForProfile(profile)
-
- return () => {
- activate()
-
- return true
- }
+ return prepareGatewayForProfile(profile)
}
if (!window.hermesDesktop?.getConnectionFor) {
@@ -746,14 +744,12 @@ export async function ensureGatewayForAgent(connectionId: null | string, profile
// pointer, connection descriptor), so no subscriber can observe the active
// gateway pointing at one backend while companion state still describes
// another. Nothing is published until the thunk runs.
-export async function prepareGatewayForProfile(profile: string): Promise<() => void> {
+export async function prepareGatewayForProfile(profile: string): Promise<() => boolean> {
const key = normKey(profile)
const activationEpoch = beginGatewayActivation()
if (key === g.primaryProfile) {
- return () => {
- applyActive(key, activationEpoch)
- }
+ return () => applyActive(key, activationEpoch)
}
// Global-remote share (routing case 3): one remote host serves every
@@ -765,9 +761,7 @@ export async function prepareGatewayForProfile(profile: string): Promise<() => v
// entry, and returned as a thunk like every other path here so this
// switch publishes as atomically as a dedicated-socket one.
if (await sharedPrimaryRoute(key)) {
- return () => {
- applyActive(g.primaryProfile, activationEpoch)
- }
+ return () => applyActive(g.primaryProfile, activationEpoch)
}
let entry = g.secondaries.get(key)
@@ -797,15 +791,20 @@ export async function prepareGatewayForProfile(profile: string): Promise<() => v
// compares against this exact entry.
const prepared = entry
+ // Reports whether the ACTIVATION was accepted, which is a different question
+ // from whether a descriptor was published: an accepted activation with no
+ // cached connection still moved the gateway, so the caller must still move
+ // its companion state. Only a rejected activation (disposed entry, or an
+ // epoch superseded by a newer switch while this one was dialing) must leave
+ // every companion store alone.
return () => {
- if (
- prepared.wantOpen &&
- g.secondaries.get(key) === prepared &&
- applyActive(key, activationEpoch) &&
- prepared.connection
- ) {
+ const activated = prepared.wantOpen && g.secondaries.get(key) === prepared && applyActive(key, activationEpoch)
+
+ if (activated && prepared.connection) {
publishActiveConnection(prepared.connection)
}
+
+ return activated
}
}
diff --git a/apps/desktop/src/store/profile-agent-activation.test.ts b/apps/desktop/src/store/profile-agent-activation.test.ts
index b5738b0174b..124da3010ea 100644
--- a/apps/desktop/src/store/profile-agent-activation.test.ts
+++ b/apps/desktop/src/store/profile-agent-activation.test.ts
@@ -42,6 +42,8 @@ const activateAgent = vi.fn(() => {
const activateProfile = vi.fn(() => {
$gateway.set(PROFILE_GATEWAY)
+
+ return true
})
// Annotated with the SEAM's thunk types, not the spies' own. Inferred, the
@@ -51,7 +53,7 @@ const prepareGatewayForAgent = vi.fn(
async (_connectionId: null | string, _profile: string): Promise<() => boolean> => activateAgent
)
-const prepareGatewayForProfile = vi.fn(async (_profile: string): Promise<() => void> => activateProfile)
+const prepareGatewayForProfile = vi.fn(async (_profile: string): Promise<() => boolean> => activateProfile)
const openGatewayForProfile = vi.fn(async (_profile: string) => undefined)
const $gateway = atom<unknown>(INITIAL_GATEWAY)
const resetStarmapGraph = vi.fn()
@@ -252,6 +254,55 @@ describe('ensureGatewayAgent → $connection / $activeGatewayProfile sync', () =
})
})
+describe('ensureGatewayProfile publishes under the same activation guard', () => {
+ it('publishes nothing when the profile activation is superseded', async () => {
+ // The profile-door mirror of "does not republish a registry identity
+ // invalidated during activation". applyActive() returns false when its
+ // captured epoch has been superseded — a newer switch or a teardown
+ // landed while this preparation was awaiting its route or socket.
+ //
+ // Discarding that boolean does not produce a torn publication; batch()
+ // makes the writes observer-atomic either way. It produces something
+ // subtler and worse: ONE complete, internally inconsistent tuple, the
+ // CURRENT gateway paired with the stale target's profile pointer and
+ // descriptor. Atomicity cannot make a rejected activation correct, so the
+ // caller has to decline to publish at all.
+ getConnection.mockResolvedValue(localConn({ profile: 'worker' }))
+ prepareGatewayForProfile.mockResolvedValueOnce(() => false)
+
+ const seen: unknown[] = []
+ const stop = $gateway.listen(gateway => seen.push(gateway))
+
+ try {
+ await ensureGatewayProfile('worker')
+ } finally {
+ stop()
+ }
+
+ // All three still describe the complete route that was already active.
+ expect($gateway.get()).toBe(INITIAL_GATEWAY)
+ expect($activeGatewayProfile.get()).toBe('default')
+ expect($connection.get()?.profile).toBe('default')
+ expect($connection.get()?.mode).toBe('local')
+ // And no subscriber was handed a tuple to disagree about.
+ expect(seen).toEqual([])
+ })
+
+ it('publishes the companions when the profile activation is accepted', async () => {
+ // The other half: the guard must not swallow a legitimate switch. Without
+ // this, returning a constant false from every thunk would pass the test
+ // above and break the feature.
+ getConnection.mockResolvedValue(localConn({ profile: 'worker' }))
+
+ await ensureGatewayProfile('worker')
+
+ expect(activateProfile).toHaveBeenCalledTimes(1)
+ expect($gateway.get()).toBe(PROFILE_GATEWAY)
+ expect($activeGatewayProfile.get()).toBe('worker')
+ expect($connection.get()?.profile).toBe('worker')
+ })
+})
+
describe('ensureGatewayAgent shares the gatewaySwitch mutex with profile switches', () => {
it('serializes an agent activation behind an in-flight profile switch', async () => {
const profileGate = deferred()
diff --git a/apps/desktop/src/store/profile.test.ts b/apps/desktop/src/store/profile.test.ts
index 1732e0e726c..7ac9dbb6bc8 100644
--- a/apps/desktop/src/store/profile.test.ts
+++ b/apps/desktop/src/store/profile.test.ts
@@ -6,7 +6,11 @@ import type { ProfileInfo } from '@/types/hermes'
// Keep profile.ts's side-effecting imports inert: the gateway socket layer and
// the REST query client must not run for real in a unit test.
-const activateGateway = vi.fn()
+// Returns true: both prepare seams hand back a thunk reporting whether the
+// activation was ACCEPTED, and a caller publishes its companion state only on
+// true. A bare vi.fn() returns undefined, which now reads as "superseded" and
+// would silently suppress every publication these tests assert on.
+const activateGateway = vi.fn(() => true)
const ensureGatewayForProfile = vi.fn(async () => undefined)
const prepareGatewayForAgent = vi.fn(async (_connectionId: null | string, _profile: string) => activateGateway)
const prepareGatewayForProfile = vi.fn(async (_profile: string) => activateGateway)
diff --git a/apps/desktop/src/store/profile.ts b/apps/desktop/src/store/profile.ts
index 83cbb30274e..6c406854849 100644
--- a/apps/desktop/src/store/profile.ts
+++ b/apps/desktop/src/store/profile.ts
@@ -344,7 +344,17 @@ export async function ensureGatewayProfile(profile: string | null | undefined):
// .set() calls that each drain their listeners synchronously, and a
// $gateway listener runs while the other two still name the old backend.
batch(() => {
- activate()
+ // A rejected activation publishes NOTHING, exactly like the agent path.
+ // applyActive() returns false when its captured epoch was superseded --
+ // a newer switch (or a teardown) landed while this one was awaiting its
+ // route or socket. Publishing the companions anyway would leave the
+ // CURRENT gateway paired with the stale profile pointer and descriptor,
+ // and batch() cannot rescue that: it would make the mismatched tuple
+ // atomically observable rather than prevent it.
+ if (!activate()) {
+ return
+ }
+
$activeGatewayProfile.set(target)
if (connection) {