Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(relay): back off when the relay drops an idle listener; time token refresh on the server clock

review436211d7f4b1
diff --git a/src/main/remote/standing-host.test.ts b/src/main/remote/standing-host.test.ts
index b5a194f07..910c33f0e 100644
--- a/src/main/remote/standing-host.test.ts
+++ b/src/main/remote/standing-host.test.ts
@@ -78,7 +78,7 @@ vi.mock('./host-service', () => ({
}
}))
-import { initStandingHost } from './standing-host'
+import { initStandingHost, tokenTtlMs } from './standing-host'
import { IPC } from '../../shared/ipc'
/** Let the async connectOne() chain (token mint, keypair) settle. */
@@ -317,3 +317,106 @@ describe('standing host: a refused token mint backs off', () => {
host.stop()
})
})
+
+describe('standing host: a listener the relay drops backs off (relay unreachable, API fine)', () => {
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
+ it('re-mints on the backoff, and a successful mint does NOT reset it', async () => {
+ // Relay log, 2026-09-27, a host already on the fixed build: API reachable, relay WS failing for
+ // 2½ minutes. Every mint succeeded (resetting the backoff), every socket died at once, and
+ // onClose re-minted immediately — ~30 mints in 3 s until the API's per-IP limit answered 429.
+ vi.useFakeTimers()
+ const fetchMock = vi.fn(async () => ({
+ ok: true,
+ json: async () => ({ pairingToken: 'tok', hostId: 'host', exp: 0 })
+ }))
+ vi.stubGlobal('fetch', fetchMock)
+ const host = makeHost()
+ host.syncFromSettings()
+ for (let i = 0; i < 10; i++) await settle()
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+
+ const dropNewest = async (): Promise<void> => {
+ sessions.at(-1)!.opts.onClose() // the relay drops the idle listener on its own
+ for (let i = 0; i < 10; i++) await settle()
+ }
+ // Drop #1: nothing immediate, one re-mint after 1 s.
+ await dropNewest()
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ // Drop #2 right after that SUCCESSFUL mint: the delay grew to 2 s — the mint did not reset it.
+ await dropNewest()
+ await vi.advanceTimersByTimeAsync(1999)
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ await vi.advanceTimersByTimeAsync(1)
+ expect(fetchMock).toHaveBeenCalledTimes(3)
+ host.stop()
+ })
+
+ it('a listener that lives to its refresh resets the backoff', async () => {
+ vi.useFakeTimers()
+ const fetchMock = vi.fn(async () => ({
+ ok: true,
+ json: async () => ({ pairingToken: 'tok', hostId: 'host', exp: 0 })
+ }))
+ vi.stubGlobal('fetch', fetchMock)
+ const host = makeHost()
+ host.syncFromSettings()
+ for (let i = 0; i < 10; i++) await settle()
+ // Two early deaths push the backoff to its third step (4 s)…
+ sessions.at(-1)!.opts.onClose()
+ await vi.advanceTimersByTimeAsync(1000)
+ sessions.at(-1)!.opts.onClose()
+ await vi.advanceTimersByTimeAsync(2000)
+ const before = fetchMock.mock.calls.length
+ // …then the listener holds for a full token lifetime (refresh at 120 − 30 = 90 s).
+ await vi.advanceTimersByTimeAsync(90_000)
+ expect(fetchMock.mock.calls.length).toBe(before + 1) // the refresh re-mint
+ // A drop now waits 1 s again, not 4 s.
+ sessions.at(-1)!.opts.onClose()
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(fetchMock.mock.calls.length).toBe(before + 2)
+ host.stop()
+ })
+})
+
+describe('standing host: token refresh is immune to this machine\'s clock error', () => {
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
+ it('tokenTtlMs measures exp against the SERVER clock (Date header), local clock only as fallback', () => {
+ const serverNow = Date.parse('Sun, 27 Sep 2026 08:00:00 GMT')
+ const exp = serverNow / 1000 + 120
+ const fastLocal = serverNow + 75_000 // this machine's clock 75 s ahead
+ expect(tokenTtlMs(exp, 'Sun, 27 Sep 2026 08:00:00 GMT', fastLocal)).toBe(120_000)
+ expect(tokenTtlMs(exp, null, fastLocal)).toBe(45_000) // no header: the old (skewed) answer
+ expect(tokenTtlMs(exp, 'not a date', fastLocal)).toBe(45_000)
+ expect(tokenTtlMs(0, 'Sun, 27 Sep 2026 08:00:00 GMT', fastLocal)).toBe(120_000) // no exp → default TTL
+ })
+
+ it('a host whose clock is 75 s fast refreshes every ~90 s, not at the 15 s floor', async () => {
+ // Relay log, 2026-09-27: a host re-minting every 15 s (238/hour vs a free limit of 240).
+ vi.useFakeTimers()
+ const serverNow = Date.parse('Sun, 27 Sep 2026 08:00:00 GMT')
+ vi.setSystemTime(serverNow + 75_000)
+ const fetchMock = vi.fn(async () => ({
+ ok: true,
+ headers: new Headers({ date: new Date(serverNow).toUTCString() }),
+ json: async () => ({ pairingToken: 'tok', hostId: 'host', exp: serverNow / 1000 + 120 })
+ }))
+ vi.stubGlobal('fetch', fetchMock)
+ const host = makeHost()
+ host.syncFromSettings()
+ for (let i = 0; i < 10; i++) await settle()
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ await vi.advanceTimersByTimeAsync(60_000)
+ expect(fetchMock).toHaveBeenCalledTimes(1) // the old code had re-minted 4 times by now
+ await vi.advanceTimersByTimeAsync(30_000)
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ host.stop()
+ })
+})
diff --git a/src/main/remote/standing-host.ts b/src/main/remote/standing-host.ts
index 6bea3e696..3036ecf4f 100644
--- a/src/main/remote/standing-host.ts
+++ b/src/main/remote/standing-host.ts
@@ -53,6 +53,25 @@ interface HostTokenResponse {
pairingToken: string
hostId: string
exp: number
+ /** How long the token has left, measured on the SERVER's clock at mint time (see tokenTtlMs). */
+ ttlMs: number
+}
+
+/**
+ * How long a freshly minted token has left, in ms.
+ *
+ * `exp` is an absolute instant on the SERVER's clock. Subtracting the LOCAL `Date.now()` from it
+ * folds this machine's clock error into the answer: a clock 75 s fast leaves 120 − 75 = 45 s, minus
+ * the 30 s lead = the 15 s floor, so the host re-mints four times per TTL. Relay log, 2026-09-27: one
+ * host refreshing every 15 s, 238 mints/hour against a free limit of 240 — one stray mint from
+ * locking itself out for the rest of the hour. The response's own `Date` header is the server's
+ * clock at the same instant it computed `exp`, so the difference is clock-independent. It falls
+ * back to the local clock only when the header is missing or unparseable (a proxy that strips it).
+ */
+export function tokenTtlMs(exp: number, serverDate: string | null, localNowMs: number): number {
+ if (!(exp > 0)) return DEFAULT_TTL_MS
+ const serverNowMs = serverDate ? Date.parse(serverDate) : NaN
+ return exp * 1000 - (Number.isFinite(serverNowMs) ? serverNowMs : localNowMs)
}
/**
@@ -79,7 +98,13 @@ async function mintHostToken(
if (!res.ok) return null
const json = (await res.json().catch(() => ({}))) as Partial<HostTokenResponse>
if (!json.pairingToken) return null
- return { pairingToken: json.pairingToken, hostId: json.hostId ?? '', exp: json.exp ?? 0 }
+ const exp = json.exp ?? 0
+ return {
+ pairingToken: json.pairingToken,
+ hostId: json.hostId ?? '',
+ exp,
+ ttlMs: tokenTtlMs(exp, res.headers?.get?.('date') ?? null, Date.now())
+ }
} catch {
return null
} finally {
@@ -208,18 +233,21 @@ export function initStandingHost(
reconnectTimer.unref?.()
}
- function scheduleRefreshFor(p: Pooled, exp: number): void {
+ function scheduleRefreshFor(p: Pooled, ttlMs: number): void {
if (p.refreshTimer) clearTimeout(p.refreshTimer)
- const untilExpMs = exp > 0 ? exp * 1000 - Date.now() : DEFAULT_TTL_MS
- const delay = Math.max(MIN_REFRESH_MS, untilExpMs - REFRESH_LEAD_MS)
+ const delay = Math.max(MIN_REFRESH_MS, ttlMs - REFRESH_LEAD_MS)
p.refreshTimer = setTimeout(() => {
p.refreshTimer = null
if (!running || !pool.has(p)) return
+ // This listener held its relay registration for a whole token lifetime: the relay is
+ // reachable, so the reconnect backoff has done its job. This — not a successful mint — is
+ // what resets it (see connectOne).
+ reconnectAttempt = 0
// A listener serving a client (bridged) is left alone — never cut an active session for a
// token refresh; the relay drops it at TTL and onClose replaces it. Only an IDLE listener is
// re-minted with a fresh token by dropping it and topping the pool back up.
if (p.bridged) {
- scheduleRefreshFor(p, 0)
+ scheduleRefreshFor(p, DEFAULT_TTL_MS)
return
}
removeFromPool(p)
@@ -233,6 +261,7 @@ export function initStandingHost(
async function onPeerReady(pooled: Pooled): Promise<void> {
if (!pooled.bridged) {
pooled.bridged = true
+ reconnectAttempt = 0 // a completed handshake proves the relay leg end to end
// Team presence: a bridged relay client is a peer. It has no mouse, so it stays cursorless
// and appears in the facepile only — see docs/team-presence.md ("Peers may have no cursor").
pooled.presence.join()
@@ -293,7 +322,12 @@ export function initStandingHost(
scheduleReconnect()
return
}
- reconnectAttempt = 0
+ // NOT `reconnectAttempt = 0` here. A mint proves only that the API answered — the relay is a
+ // different host, and when it is unreachable from this machine (relay log, 2026-09-27: a host
+ // on the fixed build, API fine, relay WS failing for 2½ minutes) every mint succeeds, every
+ // socket dies at once, and a reset here made each death re-mint at round-trip speed until the
+ // API's per-IP limit answered 429. The backoff resets on proof the relay leg works instead:
+ // a listener surviving to its refresh, or a completed phone handshake.
const pooled: Pooled = {
session: null as unknown as HostSession,
bridged: false,
@@ -329,12 +363,18 @@ export function initStandingHost(
pooled.refreshTimer = null
}
pool.delete(pooled)
- ensurePool() // a listener/session dropped → top the pool back up
+ // A session a phone was using ended: its replacement listener was already opened in
+ // onPeerReady, so topping up is normally a no-op. An IDLE listener dropping on its own is
+ // different — our refresh closes intentionally (no onClose), so this is the relay
+ // refusing or unreachable, and re-minting at once is the tight loop the backoff exists
+ // to prevent.
+ if (pooled.bridged) ensurePool()
+ else scheduleReconnect()
}
})
pool.add(pooled)
opened = true
- scheduleRefreshFor(pooled, token.exp)
+ scheduleRefreshFor(pooled, token.ttlMs)
// A listener is registered at the relay → advertise the identity for LATE ADOPTION
// (~/.nodeterm/relay.json — see relay-advertise.ts): a phone whose pairing predates the
// toggle reads it over its SSH bootstrap and gains a relay leg without re-pairing.