Skip to content

The agent that grows with you

fix(desktop): a 409 maintenance refusal ends the legacy owner backfill for that scope

teknium1c0e4928ff68a
diff --git a/apps/desktop/electron/local-gateway.test.ts b/apps/desktop/electron/local-gateway.test.ts
index 09e638fb215..052b736ae59 100644
--- a/apps/desktop/electron/local-gateway.test.ts
+++ b/apps/desktop/electron/local-gateway.test.ts
@@ -18,7 +18,9 @@ test.skipIf(process.platform === 'win32')('native HTTP mints fresh purpose-bound
const path = await import('node:path')
const net = await import('node:net')
const { nativeGatewayHttpHeaders } = await import('./local-gateway')
- const home = await fs.mkdtemp(path.join(os.tmpdir(), 'desktop-http-'))
+ // macOS: os.tmpdir() is /var/..., a symlink to /private/var; the gateway canonicalises
+ // profile_id, so the endpoint must carry the realpath or identities never match.
+ const home = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'desktop-http-')))
const endpoint = { profile_id: home, instance_id: 'owner', authority_epoch: 1, runtime_protocol: 1, api_origin: 'http://127.0.0.1:1234', capabilities: ['session-authority-v1'], supervisor: 'none' }
const requests: any[] = []
@@ -113,7 +115,9 @@ test.skipIf(process.platform === 'win32')('a stopped gateway that unlinked its c
const path = await import('node:path')
const net = await import('node:net')
const { mintLocalGatewayTicket, redialLocalGateway } = await import('./local-gateway')
- const home = await fs.mkdtemp(path.join(os.tmpdir(), 'desktop-redial-'))
+ // macOS: os.tmpdir() is /var/..., a symlink to /private/var; the gateway canonicalises
+ // profile_id, so the endpoint must carry the realpath or identities never match.
+ const home = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'desktop-redial-')))
const socketPath = path.join(home, 'gateway.sock')
const endpoint = { profile_id: home, instance_id: 'owner', authority_epoch: 1, runtime_protocol: 1, api_origin: 'http://127.0.0.1:1234', capabilities: ['session-authority-v1'], supervisor: 'none' }
@@ -170,7 +174,9 @@ test.skipIf(process.platform === 'win32')('a group-accessible control socket is
const path = await import('node:path')
const net = await import('node:net')
const { isStaleLocalGatewayError, mintLocalGatewayTicket } = await import('./local-gateway')
- const home = await fs.mkdtemp(path.join(os.tmpdir(), 'desktop-unsafe-'))
+ // macOS: os.tmpdir() is /var/..., a symlink to /private/var; the gateway canonicalises
+ // profile_id, so the endpoint must carry the realpath or identities never match.
+ const home = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'desktop-unsafe-')))
const socketPath = path.join(home, 'gateway.sock')
const endpoint = { profile_id: home, instance_id: 'owner', authority_epoch: 1, runtime_protocol: 1, api_origin: 'http://127.0.0.1:1234', capabilities: ['session-authority-v1'], supervisor: 'none' }
const server = net.createServer(socket => socket.end())
diff --git a/apps/desktop/src/lib/gateway-rpc.test.ts b/apps/desktop/src/lib/gateway-rpc.test.ts
index aa8a1ef9e20..d8f56435003 100644
--- a/apps/desktop/src/lib/gateway-rpc.test.ts
+++ b/apps/desktop/src/lib/gateway-rpc.test.ts
@@ -1,7 +1,7 @@
import { JsonRpcGatewayError } from '@hermes/shared'
import { describe, expect, it } from 'vitest'
-import { isMissingPendingPromptRequest, isMissingRpcMethod } from './gateway-rpc'
+import { isMissingPendingPromptRequest, isMissingRpcMethod, isOfflineMaintenance } from './gateway-rpc'
describe('isMissingRpcMethod', () => {
it('trusts the JSON-RPC code over the message when the frame survived', () => {
@@ -22,6 +22,20 @@ describe('isMissingRpcMethod', () => {
})
})
+describe('isOfflineMaintenance', () => {
+ it('matches only the anchored HTTP 409 status marker, bare or through the IPC bridge', () => {
+ // Real server form (api-transport.ts::httpStatusError) and its IPC-wrapped twin.
+ const detail = '{"detail":"Exclusive maintenance refused: Gateway runtime already owns profile /x. Drain and stop the gateway, then retry."}'
+ expect(isOfflineMaintenance(new Error(`409: ${detail}`))).toBe(true)
+ expect(isOfflineMaintenance(new Error(`Error invoking remote method 'hermes:api': Error: 409: ${detail}`))).toBe(true)
+ // Decoys: a 409 token in a body, a longer number, another status, bare conflict text.
+ expect(isOfflineMaintenance(new Error('500: Query returned 409 rows'))).toBe(false)
+ expect(isOfflineMaintenance(new Error('4096: not a status'))).toBe(false)
+ expect(isOfflineMaintenance(new Error('404: {"detail":"Not Found"}'))).toBe(false)
+ expect(isOfflineMaintenance(new Error('conflict: gateway owns the profile'))).toBe(false)
+ })
+})
+
describe('isMissingPendingPromptRequest', () => {
it('detects stale prompt response errors from the gateway', () => {
expect(isMissingPendingPromptRequest(new Error('no pending password request'), 'password')).toBe(true)
diff --git a/apps/desktop/src/lib/gateway-rpc.ts b/apps/desktop/src/lib/gateway-rpc.ts
index 14c2d8a2dd6..ee00c648c16 100644
--- a/apps/desktop/src/lib/gateway-rpc.ts
+++ b/apps/desktop/src/lib/gateway-rpc.ts
@@ -34,6 +34,20 @@ export function isMissingRestEndpoint(error: unknown): boolean {
)
}
+/** True when the backend refused a request because it owns the profile and the
+ * call is offline-only maintenance (`web_server_sessions.py::_with_session_maintenance`
+ * → HTTP 409 "Exclusive maintenance refused"). The refusal is the steady state
+ * for as long as that gateway runs, so callers treat it as terminal, not
+ * transient. Only the anchored `409: {...}` status marker — bare, or wrapped as
+ * "Error invoking remote method 'hermes:api': Error: 409: …" by the IPC bridge —
+ * counts; a `409` token inside a message body ("Query returned 409 rows", "4096")
+ * never does. */
+export function isOfflineMaintenance(error: unknown): boolean {
+ const message = error instanceof Error ? error.message : String(error)
+
+ return /(?:^\s*|error:\s*)409:/i.test(message)
+}
+
/** True when a prompt response raced a backend-side timeout / completion. */
export function isMissingPendingPromptRequest(error: unknown, key: string): boolean {
const message = error instanceof Error ? error.message : String(error)
diff --git a/apps/desktop/src/lib/legacy-session-owner-backfill.test.ts b/apps/desktop/src/lib/legacy-session-owner-backfill.test.ts
index c6d37fc02cc..18db511e04d 100644
--- a/apps/desktop/src/lib/legacy-session-owner-backfill.test.ts
+++ b/apps/desktop/src/lib/legacy-session-owner-backfill.test.ts
@@ -1,7 +1,52 @@
-import { describe, expect, it } from 'vitest'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
import { resolveLegacyOwnerBackfillScope } from './session-owner-stamp'
+const api = vi.fn<(request: unknown) => Promise<unknown>>()
+
+vi.mock('@/api/client', () => ({
+ getApiRequestConnection: () => 'gw-b',
+ hermesApi: (request: unknown) => api(request)
+}))
+vi.mock('@/store/connection-registry-state', () => ({
+ $connectionsRegistry: { get: () => ({ connections: [{ id: 'local' }, { id: 'gw-b' }] }) },
+ hasRegistryTopology: () => true
+}))
+
+async function enumerateTwice(): Promise<number> {
+ const { maybeBackfillLegacySessionOwners } = await import('./legacy-session-owner-backfill')
+ maybeBackfillLegacySessionOwners()
+ await Promise.resolve()
+ await Promise.resolve()
+ maybeBackfillLegacySessionOwners()
+ await Promise.resolve()
+
+ return api.mock.calls.length
+}
+
+describe('maybeBackfillLegacySessionOwners (one-shot per scope)', () => {
+ beforeEach(async () => {
+ api.mockReset()
+ const { resetLegacyOwnerBackfillAttempts } = await import('./legacy-session-owner-backfill')
+ resetLegacyOwnerBackfillAttempts()
+ })
+
+ it('treats the owning gateway\'s 409 maintenance refusal as terminal, like version skew', async () => {
+ // The gateway answers 409 for as long as it owns the profile: re-arming here is a request
+ // storm the backend will keep refusing. Reported and verified by @ahrazzle (#106742).
+ api.mockRejectedValue(new Error(
+ "Error invoking remote method 'hermes:api': Error: 409: " +
+ '{"detail":"Exclusive maintenance refused: Gateway runtime already owns profile /x"}'
+ ))
+ expect(await enumerateTwice()).toBe(1)
+ })
+
+ it('re-arms the scope after a transient failure so the next enumeration retries', async () => {
+ api.mockRejectedValue(new Error('503: {"detail":"storage_unavailable"}'))
+ expect(await enumerateTwice()).toBe(2)
+ })
+})
+
describe('resolveLegacyOwnerBackfillScope (#94724 single-match owner backfill)', () => {
it('targets the serving registered connection (the backend that serves a page owns its rows)', () => {
const scope = resolveLegacyOwnerBackfillScope({
diff --git a/apps/desktop/src/lib/legacy-session-owner-backfill.ts b/apps/desktop/src/lib/legacy-session-owner-backfill.ts
index c839fd751ee..c15bc31bd6c 100644
--- a/apps/desktop/src/lib/legacy-session-owner-backfill.ts
+++ b/apps/desktop/src/lib/legacy-session-owner-backfill.ts
@@ -20,11 +20,14 @@
* The request is one-shot per (connection, profile) scope per renderer:
* the server side is idempotent and never overwrites a non-NULL owner, so a
* repeat is harmless but pointless. A transport failure re-arms the scope so
- * the next refresh retries; a backend without the endpoint (version skew)
- * stays armed-off for this renderer lifetime.
+ * the next refresh retries; a backend without the endpoint (version skew) or a
+ * backend that refuses offline maintenance because it owns the profile (409,
+ * the steady state while that gateway runs) stays armed-off for this renderer
+ * lifetime — retrying either every enumeration is a request storm the backend
+ * will keep refusing.
*/
import { getApiRequestConnection, hermesApi } from '@/api/client'
-import { isMissingRestEndpoint } from '@/lib/gateway-rpc'
+import { isMissingRestEndpoint, isOfflineMaintenance } from '@/lib/gateway-rpc'
import { resolveLegacyOwnerBackfillScope } from '@/lib/session-owner-stamp'
import { $connectionsRegistry, hasRegistryTopology } from '@/store/connection-registry-state'
@@ -81,9 +84,10 @@ export function maybeBackfillLegacySessionOwners(): void {
}
})
.catch(error => {
- // Version skew: this backend predates the endpoint. Keep the scope
- // marked so we don't re-probe a known-dead route every refresh.
- if (isMissingRestEndpoint(error)) {
+ // Terminal for this scope: version skew (no endpoint) or the owning
+ // gateway's 409 maintenance refusal. Keep the scope marked so we don't
+ // re-probe a route that will answer the same way every refresh.
+ if (isMissingRestEndpoint(error) || isOfflineMaintenance(error)) {
return
}