Skip to content

The agent that grows with you

fix(desktop): re-check primary ownership after the reconnect ticket mint

teknium1cd6d6086e6b3
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 4da1e247f73..b8746037932 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
@@ -2858,6 +2858,63 @@ describe('useGatewayBoot remote reconnect loop (real hook, fake socket)', () =>
expect(FakeWebSocket.instances.at(-1)?.url).toBe(newPrimary.wsUrl)
expect($connection.get()?.connectionId).toBe(newPrimary.connectionId)
})
+
+ it('a reconnect ticket minted after a connection apply never dials the old primary', async () => {
+ const oldPrimary = { ...remotePrimaryConn, registryScoped: true }
+ const newPrimary = { ...coderConn, mode: 'remote' as const, profile: 'default', registryScoped: true }
+ const heldOldMint = deferred<string>()
+ let applied = false
+ let oldMints = 0
+
+ const desktop = {
+ ...fakeDesktop(),
+ getConnection: vi.fn(async () => (applied ? newPrimary : oldPrimary)),
+ getConnectionFor: vi.fn(async ({ connectionId }: { connectionId: string; profile: string }) =>
+ connectionId === newPrimary.connectionId ? newPrimary : oldPrimary
+ ),
+ // The boot mint resolves at once; the reconnect's re-mint parks.
+ getGatewayWsUrlFor: vi.fn(({ connectionId }: { connectionId: string; profile: string }) => {
+ if (connectionId === newPrimary.connectionId) {
+ return Promise.resolve(newPrimary.wsUrl)
+ }
+
+ oldMints += 1
+
+ return oldMints === 1 ? Promise.resolve(oldPrimary.wsUrl) : heldOldMint.promise
+ })
+ }
+
+ ;(window as { hermesDesktop?: unknown }).hermesDesktop = desktop
+ render(<Harness />)
+ await flushAsync()
+ expect(FakeWebSocket.instances[0].url).toBe(oldPrimary.wsUrl)
+
+ act(() => FakeWebSocket.instances[0].drop())
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1_000)
+ })
+ expect(oldMints).toBe(2)
+
+ applied = true
+ act(() => connectionApplied?.())
+ await flushAsync()
+ expect(FakeWebSocket.instances.at(-1)?.url).toBe(newPrimary.wsUrl)
+
+ // The applied socket drops while the stale mint is still parked, so
+ // connect() is no longer a no-op on an open socket.
+ act(() => FakeWebSocket.instances.at(-1)!.drop())
+ const sockets = FakeWebSocket.instances.length
+
+ await act(async () => {
+ heldOldMint.resolve(oldPrimary.wsUrl)
+ await vi.advanceTimersByTimeAsync(0)
+ })
+ expect(FakeWebSocket.instances.slice(sockets).map(s => s.url)).not.toContain(oldPrimary.wsUrl)
+
+ await advanceBackoff()
+ expect(FakeWebSocket.instances.at(-1)?.url).toBe(newPrimary.wsUrl)
+ expect($connection.get()?.connectionId).toBe(newPrimary.connectionId)
+ })
})
describe('window-state IPC before the first connection publishes (#108641)', () => {
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 63ae00eb9c7..e9ddcef5adb 100644
--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
@@ -493,6 +493,7 @@ export function useGatewayBoot({
}
recordPrimaryConnection(conn)
+ const dialRevision = primaryRouteRevision
// Only publish the primary descriptor when the primary is active.
// Otherwise a background-profile view would inherit the primary's
@@ -515,6 +516,12 @@ export function useGatewayBoot({
'Timed out re-minting the gateway WebSocket URL'
)
+ // Same fence after the mint: an apply that landed while the ticket was
+ // in flight owns the socket, and its socket may already have dropped.
+ if (cancelled || dialRevision !== primaryRouteRevision) {
+ return
+ }
+
await gateway.connect(wsUrl)
if (cancelled) {
diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-request.test.ts b/apps/desktop/src/app/gateway/hooks/use-gateway-request.test.ts
index 3411b7ff733..08c5b2997a0 100644
--- a/apps/desktop/src/app/gateway/hooks/use-gateway-request.test.ts
+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-request.test.ts
@@ -425,6 +425,36 @@ describe('useGatewayRequest', () => {
}
)
+ it('does not dial the primary when the foreground moves while its ticket is minted', async () => {
+ const desktop = installRemoteDesktop()
+ const primary = makePrimaryGateway()
+ const failure = new Error('connection closed')
+ primary.connectionState = 'closed'
+ primary.request.mockRejectedValueOnce(failure)
+ let releaseMint!: () => void
+ desktop.getGatewayWsUrl.mockImplementationOnce(
+ () =>
+ new Promise(resolve => {
+ releaseMint = () => resolve({ ok: true as const, wsUrl: 'ws://127.0.0.1:5151/api/ws?token=fresh-local' })
+ })
+ )
+ setPrimaryGateway(primary as unknown as HermesGateway, 'default')
+ $gateway.set(primary as unknown as HermesGateway)
+ $gatewayState.set('closed')
+ const { result } = renderHook(() => useGatewayRequest())
+ const pending = result.current.requestGateway('prompt.submit', { text: 'local-only' }).catch(error => error)
+ await vi.waitFor(() => expect(desktop.getGatewayWsUrl).toHaveBeenCalledTimes(1))
+ await act(async () => {
+ await ensureGatewayForAgent('home', 'default')
+ })
+ await act(async () => {
+ releaseMint()
+ })
+
+ expect(await pending).toBe(failure)
+ expect(primary.connect).not.toHaveBeenCalled()
+ })
+
it('does not reconnect for a non-transport request failure', async () => {
const { desktop, gateway } = await activateRemoteGateway()
const failure = Object.assign(new Error('request rejected'), { code: 'EVALIDATION' })
diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-request.ts b/apps/desktop/src/app/gateway/hooks/use-gateway-request.ts
index 2d5a503ef6d..8b8d425550e 100644
--- a/apps/desktop/src/app/gateway/hooks/use-gateway-request.ts
+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-request.ts
@@ -130,6 +130,10 @@ export function useGatewayRequest() {
'Timed out re-minting the gateway WebSocket URL'
)
+ if (!ownsForeground()) {
+ return null
+ }
+
await existing.connect(wsUrl)
return existing