Skip to content

The agent that grows with you

fix(desktop): detect attached-backend token drift, not just liveness

chelsealong0029d25f47f4
diff --git a/apps/desktop/electron/dashboard-token.test.ts b/apps/desktop/electron/dashboard-token.test.ts
index 880e3b3a7c1..c7681d84b8d 100644
--- a/apps/desktop/electron/dashboard-token.test.ts
+++ b/apps/desktop/electron/dashboard-token.test.ts
@@ -14,6 +14,7 @@ import {
dashboardIndexUrl,
extractInjectedDashboardToken,
fetchPublicText,
+ isAttachedBackendTokenDrifted,
isForeignBackendToken,
resolveServedDashboardToken
} from './dashboard-token'
@@ -118,6 +119,19 @@ test('adoptServedDashboardToken refuses a foreign token when our child is dead',
)
})
+test('isAttachedBackendTokenDrifted flags a live backend serving a different token', () => {
+ const cases = [
+ [{ servedToken: 'new-token', adoptedToken: 'old-token' }, true],
+ [{ servedToken: 'old-token', adoptedToken: 'old-token' }, false],
+ [{ servedToken: null, adoptedToken: 'old-token' }, false],
+ [{ servedToken: '', adoptedToken: 'old-token' }, false]
+ ]
+
+ for (const [input, expected] of cases) {
+ assert.equal(isAttachedBackendTokenDrifted(input as any), expected, JSON.stringify(input))
+ }
+})
+
test('adoptServedDashboardToken falls back to the spawn token when the fetch fails', async () => {
const logs = []
diff --git a/apps/desktop/electron/dashboard-token.ts b/apps/desktop/electron/dashboard-token.ts
index 42f21485343..0af46904d14 100644
--- a/apps/desktop/electron/dashboard-token.ts
+++ b/apps/desktop/electron/dashboard-token.ts
@@ -101,12 +101,25 @@ async function adoptServedDashboardToken(baseUrl, spawnToken, { childAlive, labe
return servedToken
}
+/**
+ * True when a *live* attached backend is now serving a session token
+ * different from the one we adopted at attach time — a backend recycled by an
+ * external supervisor (e.g. launchd `KeepAlive`) into a new process on the
+ * same port. `/api/health` (and other liveness probes) are public routes that
+ * a recycled backend still answers 200 to, so a plain readiness probe cannot
+ * see this; only re-reading the served token can.
+ */
+function isAttachedBackendTokenDrifted({ servedToken, adoptedToken }) {
+ return Boolean(servedToken) && servedToken !== adoptedToken
+}
+
export {
adoptServedDashboardToken,
dashboardIndexUrl,
DEFAULT_TOKEN_FETCH_TIMEOUT_MS,
extractInjectedDashboardToken,
fetchPublicText,
+ isAttachedBackendTokenDrifted,
isForeignBackendToken,
resolveServedDashboardToken
}
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 653cce749da..1b69e181185 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -203,7 +203,7 @@ import {
import type { RosterProfileMetadata } from './connection-registry'
import { liveWindowState, overlayWindowState } from './connection-window-state'
import { describeCrashReason, installCrashForensics } from './crash-forensics'
-import { adoptServedDashboardToken, resolveServedDashboardToken } from './dashboard-token'
+import { adoptServedDashboardToken, isAttachedBackendTokenDrifted, resolveServedDashboardToken } from './dashboard-token'
import { resolveDesktopHermesHome, resolveDesktopUserData } from './data-paths'
import { loadOrCreateInstallationId, sshOwnershipId } from './desktop-installation'
import { formatDesktopLogLine, formatLogStamp } from './desktop-log-line'
@@ -12798,17 +12798,36 @@ function stopAttachedBackendMonitor() {
* invalidates the connection and hands the respawn to the same supervisor path
* a dead child would (which re-runs discovery and spawns, since the host now
* has no backend).
+ *
+ * A backend recycled by an external supervisor (e.g. launchd `KeepAlive`)
+ * into a new process on the same port passes the readiness probe (it's a
+ * public route) while serving a brand-new session token, so also re-read the
+ * served token on every tick and treat drift the same as "gone" (#121988).
+ *
+ * This teardown is unexpected, not intentional (nobody asked for a re-home),
+ * so it must clear the slot via `backendConnectionState.invalidate()` directly
+ * rather than `invalidatePrimaryConnection()`: the latter also sets
+ * `primaryRecoverySuppressed`, which `scheduleUnexpectedPrimaryRecovery()`
+ * below would then read back as `intentionalTeardown` and refuse to claim,
+ * leaving the app with no backend and no respawn scheduled.
*/
function startAttachedBackendMonitor(attached: AttachedBackend) {
stopAttachedBackendMonitor()
attachedBackendMonitor = setInterval(() => {
- void waitForHermes(attached.baseUrl, attached.token, undefined, 'token', {}, { alreadyBound: true }).catch(() => {
- stopAttachedBackendMonitor()
- rememberLog(`[attach] attached backend on ${attached.baseUrl} (pid ${attached.pid}) is gone; recovering`)
- invalidatePrimaryConnection()
- scheduleUnexpectedPrimaryRecovery({ error: 'The Hermes backend this app attached to exited.', ready: true })
- })
+ void waitForHermes(attached.baseUrl, attached.token, undefined, 'token', {})
+ .then(() => resolveServedDashboardToken(attached.baseUrl, attached.token).catch(() => attached.token))
+ .then(servedToken => {
+ if (isAttachedBackendTokenDrifted({ servedToken, adoptedToken: attached.token })) {
+ throw new Error('attached backend is serving a different session token')
+ }
+ })
+ .catch(() => {
+ stopAttachedBackendMonitor()
+ rememberLog(`[attach] attached backend on ${attached.baseUrl} (pid ${attached.pid}) is gone; recovering`)
+ backendConnectionState.invalidate()
+ scheduleUnexpectedPrimaryRecovery({ error: 'The Hermes backend this app attached to exited.', ready: true })
+ })
}, ATTACHED_LIVENESS_POLL_MS)
attachedBackendMonitor.unref?.()