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.

feat(relay): standing listener scheduler and host-token mint for the Server Edition

reviewf80f97ec80c5
diff --git a/src/core/relay/host-token.test.ts b/src/core/relay/host-token.test.ts
new file mode 100644
index 000000000..29cb6b366
--- /dev/null
+++ b/src/core/relay/host-token.test.ts
@@ -0,0 +1,90 @@
+// src/core/relay/host-token.test.ts
+import { describe, it, expect, vi, afterEach } from 'vitest'
+import { mintHostToken, tokenTtlMs } from './host-token'
+
+const res = (status: number, body: unknown, headers: Record<string, string> = {}) =>
+ ({ ok: status >= 200 && status < 300, status, headers: new Headers(headers), json: async () => body, text: async () => JSON.stringify(body) }) as Response
+
+afterEach(() => {
+ vi.useRealTimers()
+})
+
+describe('host token', () => {
+ it('sends deviceId + host key and measures TTL on the server clock', async () => {
+ let sent: unknown
+ const r = await mintHostToken({
+ apiBase: 'https://api', deviceId: 'd', hostPublicKeyB64: 'K',
+ fetch: (async (_u: string, init: RequestInit) => { sent = JSON.parse(String(init.body)); return res(200, { pairingToken: 'T', hostId: 'H', exp: 1_000_120 }, { date: new Date(1_000_000_000).toUTCString() }) }) as typeof fetch,
+ now: () => 999_000_000 // local clock 1000 s behind: must not matter
+ })
+ expect(sent).toEqual({ deviceId: 'd', hostPublicKeyB64: 'K' })
+ expect(r).toEqual({ ok: true, pairingToken: 'T', hostId: 'H', ttlMs: 120_000 })
+ })
+ it('429 carries Retry-After; 402 is refused; network throws are network', async () => {
+ const f = (r: Response) => (async () => r) as unknown as typeof fetch
+ expect(await mintHostToken({ apiBase: 'a', deviceId: 'd', hostPublicKeyB64: 'k', fetch: f(res(429, {}, { 'retry-after': '90' })) }))
+ .toMatchObject({ ok: false, kind: 'rate-limited', retryAfterMs: 90_000 })
+ expect(await mintHostToken({ apiBase: 'a', deviceId: 'd', hostPublicKeyB64: 'k', fetch: f(res(402, { error: 'not_entitled' })) }))
+ .toMatchObject({ ok: false, kind: 'refused', status: 402 })
+ expect(await mintHostToken({ apiBase: 'a', deviceId: 'd', hostPublicKeyB64: 'k', fetch: (async () => { throw new Error('x') }) as unknown as typeof fetch }))
+ .toMatchObject({ ok: false, kind: 'network' })
+ })
+ it('tokenTtlMs falls back to the local clock without a Date header', () => {
+ expect(tokenTtlMs(100, null, 40_000)).toBe(60_000)
+ expect(tokenTtlMs(0, null, 0)).toBe(120_000)
+ })
+
+ it('posts to <apiBase>/v1/relay/host-token, tolerating a trailing slash on the base', async () => {
+ const urls: string[] = []
+ const methods: Array<string | undefined> = []
+ const f = (async (u: string, init: RequestInit) => {
+ urls.push(u)
+ methods.push(init.method)
+ return res(200, { pairingToken: 'T', hostId: 'H', exp: 0 })
+ }) as unknown as typeof fetch
+ await mintHostToken({ apiBase: 'https://api.example/', deviceId: 'd', hostPublicKeyB64: 'k', fetch: f })
+ await mintHostToken({ apiBase: 'https://api.example', deviceId: 'd', hostPublicKeyB64: 'k', fetch: f })
+ expect(urls).toEqual(['https://api.example/v1/relay/host-token', 'https://api.example/v1/relay/host-token'])
+ expect(methods).toEqual(['POST', 'POST'])
+ })
+
+ it('403 is refused; any other non-2xx is network with its status; a 429 without Retry-After has no retryAfterMs', async () => {
+ const f = (r: Response) => (async () => r) as unknown as typeof fetch
+ expect(await mintHostToken({ apiBase: 'a', deviceId: 'd', hostPublicKeyB64: 'k', fetch: f(res(403, {})) }))
+ .toMatchObject({ ok: false, kind: 'refused', status: 403 })
+ expect(await mintHostToken({ apiBase: 'a', deviceId: 'd', hostPublicKeyB64: 'k', fetch: f(res(503, {})) }))
+ .toEqual({ ok: false, kind: 'network', status: 503 })
+ expect(await mintHostToken({ apiBase: 'a', deviceId: 'd', hostPublicKeyB64: 'k', fetch: f(res(429, {})) }))
+ .toEqual({ ok: false, kind: 'rate-limited', status: 429 })
+ })
+
+ it('a 200 without a usable token or with an unparseable body is bad-response', async () => {
+ const f = (r: Response) => (async () => r) as unknown as typeof fetch
+ expect(await mintHostToken({ apiBase: 'a', deviceId: 'd', hostPublicKeyB64: 'k', fetch: f(res(200, { hostId: 'H', exp: 1 })) }))
+ .toEqual({ ok: false, kind: 'bad-response' })
+ expect(await mintHostToken({ apiBase: 'a', deviceId: 'd', hostPublicKeyB64: 'k', fetch: f(res(200, { pairingToken: '' })) }))
+ .toEqual({ ok: false, kind: 'bad-response' })
+ const broken = { ...res(200, null), json: async () => { throw new SyntaxError('Unexpected token <') } } as Response
+ expect(await mintHostToken({ apiBase: 'a', deviceId: 'd', hostPublicKeyB64: 'k', fetch: f(broken) }))
+ .toEqual({ ok: false, kind: 'bad-response' })
+ })
+
+ it('the 8 s timeout also covers a body that stalls after the headers arrived', async () => {
+ // A body read outside the abort window would leave the mint pending forever, and the scheduler
+ // (which runs one mint at a time) would never mint again.
+ vi.useFakeTimers()
+ const f = (async (_u: string, init: RequestInit) => ({
+ ...res(200, null),
+ json: () => new Promise((_resolve, reject) => {
+ init.signal?.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')))
+ })
+ }) as Response) as unknown as typeof fetch
+ const p = mintHostToken({ apiBase: 'a', deviceId: 'd', hostPublicKeyB64: 'k', fetch: f })
+ let settled: unknown = 'pending'
+ void p.then((r) => { settled = r })
+ await vi.advanceTimersByTimeAsync(7_999)
+ expect(settled).toBe('pending')
+ await vi.advanceTimersByTimeAsync(1)
+ expect(settled).toEqual({ ok: false, kind: 'network' })
+ })
+})
diff --git a/src/core/relay/host-token.ts b/src/core/relay/host-token.ts
new file mode 100644
index 000000000..1058b9ca7
--- /dev/null
+++ b/src/core/relay/host-token.ts
@@ -0,0 +1,83 @@
+// Standing-host token mint for the Server Edition's hosted team relay. Mirrors the desktop's
+// `mintHostToken` + `tokenTtlMs` in src/main/remote/standing-host.ts (see that file for the measured
+// incidents: clock skew → 238 mints/hour, refused mints re-minted in a tight loop), minus Electron.
+// It sends deviceId only, never an entitlement: relay access is free (CLAUDE.md, "Remote access …
+// free, not Pro"), and the backend is the gate.
+//
+// Unlike the desktop copy, which collapses every failure to `null`, this one says WHICH failure it
+// was, because the scheduler reacts differently to each: a 429 waits at least a minute, a 402/403
+// stops minting, anything else backs off and retries.
+export type MintResult =
+ | { ok: true; pairingToken: string; hostId: string; ttlMs: number }
+ | { ok: false; kind: 'network' | 'rate-limited' | 'refused' | 'bad-response'; retryAfterMs?: number; status?: number }
+
+const DEFAULT_TTL_MS = 120_000
+const MINT_TIMEOUT_MS = 8000
+
+/**
+ * How long a freshly minted token has left, in ms.
+ *
+ * `exp` is an absolute instant (seconds) on the SERVER's clock. Subtracting the LOCAL clock 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 refresh lead = the 15 s floor, so the host re-mints four times per TTL (relay log,
+ * 2026-09-27: 238 mints/hour against a free limit of 240). The response's own `Date` header is the
+ * server's clock at the instant it computed `exp`, so the difference is clock-independent. The
+ * local clock is the fallback only when the header is missing or unparseable (a proxy stripped 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)
+}
+
+export async function mintHostToken(deps: {
+ apiBase: string
+ deviceId: string
+ hostPublicKeyB64: string
+ fetch?: typeof fetch
+ now?: () => number
+}): Promise<MintResult> {
+ const f = deps.fetch ?? fetch
+ const ctrl = new AbortController()
+ // The timeout covers the BODY read too, not just the headers: a response whose body stalls would
+ // otherwise leave this mint pending forever, and the scheduler runs one mint at a time.
+ const timer = setTimeout(() => ctrl.abort(), MINT_TIMEOUT_MS)
+ try {
+ let res: Response
+ try {
+ res = await f(`${deps.apiBase.replace(/\/+$/, '')}/v1/relay/host-token`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ // EXACTLY these two fields: the production endpoint was verified against this body.
+ body: JSON.stringify({ deviceId: deps.deviceId, hostPublicKeyB64: deps.hostPublicKeyB64 }),
+ signal: ctrl.signal
+ })
+ } catch {
+ return { ok: false, kind: 'network' }
+ }
+ if (res.status === 429) {
+ // Seconds only. An HTTP-date Retry-After (or none) falls to the scheduler's 60 s floor.
+ const ra = Number(res.headers.get('retry-after'))
+ return { ok: false, kind: 'rate-limited', status: 429, ...(ra > 0 ? { retryAfterMs: ra * 1000 } : {}) }
+ }
+ if (res.status === 402 || res.status === 403) return { ok: false, kind: 'refused', status: res.status }
+ if (!res.ok) return { ok: false, kind: 'network', status: res.status }
+ let json: { pairingToken?: unknown; hostId?: unknown; exp?: unknown } | null
+ try {
+ json = (await res.json()) as typeof json
+ } catch {
+ // Aborted mid-body is a timeout (network); a body that is not JSON is the server's fault.
+ return ctrl.signal.aborted ? { ok: false, kind: 'network' } : { ok: false, kind: 'bad-response' }
+ }
+ if (!json || typeof json.pairingToken !== 'string' || !json.pairingToken) return { ok: false, kind: 'bad-response' }
+ const exp = typeof json.exp === 'number' ? json.exp : 0
+ return {
+ ok: true,
+ pairingToken: json.pairingToken,
+ hostId: typeof json.hostId === 'string' ? json.hostId : '',
+ ttlMs: tokenTtlMs(exp, res.headers.get('date'), (deps.now ?? Date.now)())
+ }
+ } finally {
+ clearTimeout(timer)
+ }
+}
diff --git a/src/core/relay/hosted-scheduler.test.ts b/src/core/relay/hosted-scheduler.test.ts
new file mode 100644
index 000000000..6459c09ae
--- /dev/null
+++ b/src/core/relay/hosted-scheduler.test.ts
@@ -0,0 +1,294 @@
+// src/core/relay/hosted-scheduler.test.ts
+import { describe, it, expect } from 'vitest'
+import { createHostedScheduler, type MintResult, type SchedulerStatus } from './hosted-scheduler'
+
+// Flush with macrotask turns, not a fixed count of microtasks: how many awaits an async mint takes
+// is an implementation detail the tests must not pin.
+const flush = async (turns = 5) => {
+ for (let i = 0; i < turns; i++) await new Promise<void>((r) => setImmediate(r))
+}
+
+type Opened = { bridged: boolean; closed: boolean; token: string; ev: { onBridged(): void; onClose(): void }; close(): void }
+
+function harness(mints: Array<MintResult | (() => Promise<MintResult>)>, opts: {
+ open?: (tok: string, ev: { onBridged(): void; onClose(): void }) => Opened
+ onStatus?: (s: SchedulerStatus) => void
+ firstTimerId?: number
+} = {}) {
+ let t = 0
+ const timers: Array<{ at: number; fn: () => void; id: number; ms: number }> = []
+ const delays: number[] = []
+ let seq = (opts.firstTimerId ?? 1) - 1
+ let mintCalls = 0
+ const opened: Opened[] = []
+ const s = createHostedScheduler({
+ mint: async () => {
+ mintCalls++
+ const next = mints.shift()
+ if (typeof next === 'function') return next()
+ return next ?? { ok: false, kind: 'network' }
+ },
+ open: (tok, ev) => {
+ if (opts.open) return opts.open(tok, ev)
+ const l: Opened = { bridged: false, closed: false, token: tok, ev, close() { l.closed = true } }
+ opened.push(l)
+ return l
+ },
+ setTimeout: (fn, ms) => { const id = ++seq; timers.push({ at: t + ms, fn, id, ms }); delays.push(ms); return id },
+ clearTimeout: (id) => { const i = timers.findIndex((x) => x.id === id); if (i >= 0) timers.splice(i, 1) },
+ onStatus: opts.onStatus
+ }, () => t)
+ const advance = async (ms: number) => {
+ const target = t + ms
+ for (;;) {
+ timers.sort((a, b) => a.at - b.at)
+ const due = timers[0]
+ if (!due || due.at > target) break
+ timers.shift()
+ t = due.at
+ due.fn()
+ await flush()
+ }
+ t = target
+ }
+ return { s, opened, advance, timers, delays, mintCalls: () => mintCalls }
+}
+const ok = (ttlMs = 120_000): MintResult => ({ ok: true, pairingToken: 'T', hostId: 'H', ttlMs })
+
+describe('hosted scheduler', () => {
+ it('keeps one idle listener and replaces it before the token expires', async () => {
+ const h = harness([ok(), ok()])
+ h.s.start(); await flush()
+ expect(h.opened).toHaveLength(1)
+ await h.advance(90_000) // 120 s TTL − 30 s lead
+ expect(h.opened[0].closed).toBe(true)
+ expect(h.opened).toHaveLength(2)
+ })
+ it('a bridged listener is never cut for a refresh, and a new idle one is opened', async () => {
+ const h = harness([ok(), ok()])
+ h.s.start(); await flush()
+ h.opened[0].ev.onBridged(); await flush()
+ expect(h.opened).toHaveLength(2)
+ await h.advance(90_000)
+ expect(h.opened[0].closed).toBe(false)
+ })
+ it('a mint success does NOT reset the backoff when sockets keep dying (relay down, API up)', async () => {
+ const h = harness([ok(), ok(), ok(), ok()])
+ h.s.start(); await flush()
+ h.opened[0].ev.onClose(); await flush()
+ await h.advance(1000); h.opened[1].ev.onClose(); await flush()
+ await h.advance(1999)
+ expect(h.opened).toHaveLength(2) // second retry waits the full 2 s
+ await h.advance(1); expect(h.opened).toHaveLength(3)
+ })
+ it('429 waits max(60 s, Retry-After); 402 stops with backend-refused', async () => {
+ const h = harness([{ ok: false, kind: 'rate-limited', retryAfterMs: 90_000 }, ok()])
+ h.s.start(); await flush()
+ await h.advance(89_999); expect(h.opened).toHaveLength(0)
+ await h.advance(1); await flush(); expect(h.opened).toHaveLength(1)
+ const r = harness([{ ok: false, kind: 'refused', status: 402 }])
+ r.s.start(); await flush()
+ expect(r.s.status().state).toBe('backend-refused')
+ expect(r.timers).toHaveLength(0)
+ })
+ it('counts mints in the last hour', async () => {
+ const h = harness([ok(), ok()])
+ h.s.start(); await flush()
+ expect(h.s.status().mintsLastHour).toBe(1)
+ })
+
+ // --- beyond the brief: the rest of the ported rules and the failure modes that would wedge it ---
+
+ it('a 429 without Retry-After still waits the 60 s floor', async () => {
+ const h = harness([{ ok: false, kind: 'rate-limited', status: 429 }, ok()])
+ h.s.start(); await flush()
+ await h.advance(59_999); expect(h.opened).toHaveLength(0)
+ await h.advance(1); expect(h.opened).toHaveLength(1)
+ })
+
+ it('a Retry-After beyond the timer range is clamped, never overflowing into a ~1 ms re-mint loop', async () => {
+ // Node's setTimeout fires after 1 ms for any delay above 2^31-1: an unclamped 30-day wait is
+ // a tight loop against the very API that asked us to back off.
+ const h = harness([{ ok: false, kind: 'rate-limited', status: 429, retryAfterMs: 30 * 24 * 3_600_000 }])
+ h.s.start(); await flush()
+ expect(h.delays).toHaveLength(1)
+ expect(h.delays[0]).toBeGreaterThanOrEqual(60_000)
+ expect(h.delays[0]).toBeLessThanOrEqual(3_600_000)
+ })
+
+ it('a missing, NaN or absurd ttl never arms a refresh below 15 s or beyond the timer range', async () => {
+ const h = harness([ok(Number.NaN), ok(-5_000), ok(1e15)])
+ h.s.start(); await flush()
+ expect(h.delays.at(-1)).toBe(90_000) // NaN → the default 120 s TTL − 30 s lead
+ h.opened[0].ev.onBridged(); await flush()
+ expect(h.delays.at(-1)).toBe(15_000) // already expired → the 15 s floor
+ h.opened[1].ev.onBridged(); await flush()
+ expect(h.delays.at(-1)).toBeLessThanOrEqual(3_600_000)
+ })
+
+ it('a bridged session ending does not advance the backoff (only a relay failure does)', async () => {
+ const h = harness([ok(), ok(), ok()])
+ h.s.start(); await flush()
+ h.opened[0].ev.onBridged(); await flush()
+ expect(h.opened).toHaveLength(2)
+ h.opened[0].ev.onClose(); await flush() // the teammate left: not a relay failure
+ expect(h.opened).toHaveLength(2) // the idle replacement already exists
+ expect(h.timers.filter((x) => x.ms === 1000 || x.ms === 2000)).toHaveLength(0)
+ h.opened[1].ev.onClose(); await flush() // the idle one dies on its own: the FIRST backoff step
+ await h.advance(1000)
+ expect(h.opened).toHaveLength(3)
+ })
+
+ it('a bridged session ending never mints over a pending backoff (a 429 wait stays a wait)', async () => {
+ const h = harness([ok(), { ok: false, kind: 'rate-limited', status: 429, retryAfterMs: 60_000 }, ok()])
+ h.s.start(); await flush()
+ h.opened[0].ev.onBridged(); await flush() // the replacement mint is answered 429
+ expect(h.mintCalls()).toBe(2)
+ h.opened[0].ev.onClose(); await flush() // the teammate leaves while the 429 wait is armed
+ await h.advance(59_999)
+ expect(h.mintCalls()).toBe(2)
+ await h.advance(1)
+ expect(h.mintCalls()).toBe(3)
+ expect(h.opened).toHaveLength(2)
+ })
+
+ it('never runs two mints at once', async () => {
+ const h = harness([ok(), () => new Promise<MintResult>(() => {}) /* replacement mint hangs */])
+ h.s.start(); await flush()
+ h.opened[0].ev.onBridged(); await flush()
+ expect(h.mintCalls()).toBe(2) // the replacement mint is in flight
+ h.opened[0].ev.onBridged(); await flush()
+ h.opened[0].ev.onClose(); await flush()
+ expect(h.mintCalls()).toBe(2)
+ })
+
+ it('onBridged twice (pending, then approved) is one bridge: one replacement, no second proof', async () => {
+ // The hosted service reports a peer on the pending handshake AND again on approval. The second
+ // report is the same peer, not new evidence: it must not open a second replacement, nor wipe a
+ // failure that happened in between (here the replacement mint was answered 503).
+ const h = harness([ok(), { ok: false, kind: 'network', status: 503 }, ok()])
+ h.s.start(); await flush()
+ h.opened[0].ev.onBridged(); await flush()
+ expect(h.s.status().lastError).toBe('network (503)')
+ h.opened[0].ev.onBridged(); await flush()
+ expect(h.s.status().lastError).toBe('network (503)')
+ expect(h.mintCalls()).toBe(2)
+ await h.advance(1000) // the backoff, not the second report, owns the next mint
+ expect(h.opened).toHaveLength(2)
+ expect(h.s.status()).toMatchObject({ idle: 1, bridged: 1 })
+ expect(h.opened[0].bridged).toBe(true)
+ })
+
+ it('an intentional close (refresh / stop) never counts as a relay failure, even if it fires onClose', async () => {
+ const h = harness([ok(), ok(), ok()], {
+ open: (tok, ev) => {
+ const l: Opened = { bridged: false, closed: false, token: tok, ev, close() { l.closed = true; ev.onClose() } }
+ h.opened.push(l)
+ return l
+ }
+ })
+ h.s.start(); await flush()
+ await h.advance(90_000) // refresh: close() fires onClose synchronously
+ expect(h.opened).toHaveLength(2)
+ expect(h.timers.map((x) => x.ms)).toEqual([90_000]) // only the new refresh, no backoff armed
+ })
+
+ it('a mint that THROWS backs off and retries instead of wedging the scheduler', async () => {
+ const h = harness([() => Promise.reject(new Error('host key unreadable')), ok()])
+ h.s.start(); await flush()
+ expect(h.s.status()).toMatchObject({ state: 'running', idle: 0 })
+ expect(h.s.status().lastError).toMatch(/mint/)
+ await h.advance(1000)
+ expect(h.opened).toHaveLength(1)
+ })
+
+ it('an open() that THROWS (bad relay URL) backs off and retries instead of wedging', async () => {
+ let fail = true
+ const h = harness([ok(), ok()], {
+ open: (tok, ev) => {
+ if (fail) { fail = false; throw new SyntaxError('Invalid URL') }
+ const l: Opened = { bridged: false, closed: false, token: tok, ev, close() { l.closed = true } }
+ h.opened.push(l)
+ return l
+ }
+ })
+ h.s.start(); await flush()
+ expect(h.opened).toHaveLength(0)
+ expect(h.s.status().lastError).toMatch(/open/)
+ await h.advance(1000)
+ expect(h.opened).toHaveLength(1)
+ })
+
+ it('an onStatus observer that throws never wedges the lifecycle', async () => {
+ const h = harness([ok(), ok()], { onStatus: () => { throw new Error('observer bug') } })
+ h.s.start(); await flush()
+ expect(h.opened).toHaveLength(1)
+ await h.advance(90_000)
+ expect(h.opened).toHaveLength(2)
+ })
+
+ it('lastError reports a relay that drops idle listeners, and clears only on proof the relay works', async () => {
+ const h = harness([ok(), ok(), ok()]) // the third is the replacement minted after the bridge
+ h.s.start(); await flush()
+ expect(h.s.status().lastError).toBeNull()
+ h.opened[0].ev.onClose(); await flush()
+ expect(h.s.status().lastError).toMatch(/relay/)
+ await h.advance(1000) // a fresh mint succeeds — still not proof the relay leg works
+ expect(h.opened).toHaveLength(2)
+ expect(h.s.status().lastError).toMatch(/relay/)
+ h.opened[1].ev.onBridged(); await flush() // a peer bridged: that IS proof
+ expect(h.s.status().lastError).toBeNull()
+ })
+
+ it('stop() closes every listener, cancels timers, and a mint landing afterwards opens nothing', async () => {
+ let release!: (r: MintResult) => void
+ const h = harness([ok(), () => new Promise<MintResult>((r) => { release = r })])
+ h.s.start(); await flush()
+ h.opened[0].ev.onBridged(); await flush() // replacement mint now in flight
+ h.s.stop()
+ expect(h.opened[0].closed).toBe(true)
+ expect(h.timers).toHaveLength(0)
+ expect(h.s.status()).toMatchObject({ state: 'stopped', idle: 0, bridged: 0 })
+ release(ok()); await flush()
+ expect(h.opened).toHaveLength(1)
+ expect(h.timers).toHaveLength(0)
+ })
+
+ it('stop() then start() while a mint is in flight still ends with one idle listener', async () => {
+ let release!: (r: MintResult) => void
+ const h = harness([() => new Promise<MintResult>((r) => { release = r })])
+ h.s.start(); await flush()
+ h.s.stop()
+ h.s.start(); await flush()
+ release(ok()); await flush()
+ expect(h.opened).toHaveLength(1)
+ expect(h.s.status()).toMatchObject({ state: 'running', idle: 1 })
+ })
+
+ it('a timer handle of 0 is still a timer (stop() clears it, and it still owns the next mint)', async () => {
+ // Browsers number timers from 1, but an injected setTimeout may legitimately hand back 0.
+ const h = harness([{ ok: false, kind: 'network', status: 503 }], { firstTimerId: 0 })
+ h.s.start(); await flush()
+ expect(h.timers.map((x) => x.id)).toEqual([0])
+ h.s.stop()
+ expect(h.timers).toHaveLength(0)
+ })
+
+ it('start() after backend-refused mints again', async () => {
+ const h = harness([{ ok: false, kind: 'refused', status: 402 }, ok()])
+ h.s.start(); await flush()
+ expect(h.s.status().state).toBe('backend-refused')
+ h.s.start(); await flush()
+ expect(h.s.status()).toMatchObject({ state: 'running', idle: 1, lastError: expect.stringContaining('402') })
+ })
+
+ it('mintsLastHour forgets mints older than an hour', async () => {
+ // An idle listener is re-minted every 90 s: mints land at 0, 90 s, …, 3600 s (41 of them).
+ const h = harness(Array.from({ length: 60 }, () => ok()))
+ h.s.start(); await flush()
+ await h.advance(3_600_000)
+ expect(h.s.status().mintsLastHour).toBe(41)
+ await h.advance(1) // the mint at t=0 is now more than an hour old
+ expect(h.s.status().mintsLastHour).toBe(40)
+ })
+})
diff --git a/src/core/relay/hosted-scheduler.ts b/src/core/relay/hosted-scheduler.ts
new file mode 100644
index 000000000..b89d2977c
--- /dev/null
+++ b/src/core/relay/hosted-scheduler.ts
@@ -0,0 +1,252 @@
+// The standing listener lifecycle for a hosted team: keep ONE idle relay listener registered under
+// the host's room, refresh it before its token expires, replace it the moment it bridges a peer,
+// and back off on failure. A port of the desktop's rules in src/main/remote/standing-host.ts, made
+// pure over injected deps so the measured incidents those rules encode are unit-tested here:
+// - the backoff resets only on PROOF THE RELAY LEG WORKS (a listener lives to its refresh, or a
+// peer bridges) — never on a successful mint. When the API is up and the relay is down every mint
+// succeeds and every socket dies at once, and a reset on mint re-minted at round-trip speed until
+// the API's per-IP limit answered 429 (relay log, 2026-09-27);
+// - a 429 waits at least 60 s (longer if Retry-After says so); a 402/403 stops minting;
+// - while a backoff timer is armed it owns the next mint: nothing else may mint early.
+// Everything the injected deps can throw is caught: a scheduler that swallowed an exception would sit
+// in 'running' with no listener and no timer, i.e. hosting silently dead until a restart.
+import type { MintResult } from './host-token'
+export type { MintResult } from './host-token'
+
+const REFRESH_LEAD_MS = 30_000
+// Floored so a bogus or already-expired exp can't spin us.
+const MIN_REFRESH_MS = 15_000
+const DEFAULT_TTL_MS = 120_000
+const BACKOFF_MS = [1000, 2000, 4000, 8000, 15_000]
+const RATE_LIMIT_MIN_MS = 60_000
+const HOUR_MS = 3_600_000
+// Ceiling for every delay we arm. Node's setTimeout fires after ~1 ms for anything above 2^31-1 ms,
+// so an unclamped Retry-After or token lifetime from the server would become a tight re-mint loop.
+const MAX_DELAY_MS = HOUR_MS
+
+export interface Listener {
+ bridged: boolean
+ close(): void
+}
+export interface SchedulerStatus {
+ state: 'stopped' | 'running' | 'backend-refused'
+ /** The most recent failure since the relay leg was last proven to work; null once it has been. */
+ lastError: string | null
+ /** Tokens minted in the last hour (successful mints — what the backend's hourly limit counts). */
+ mintsLastHour: number
+ idle: number
+ bridged: number
+}
+export interface SchedulerDeps {
+ mint(): Promise<MintResult>
+ /**
+ * Open a relay listener with a fresh token. `onBridged` fires when a peer completes the handshake
+ * on it (it may fire more than once); `onClose` when the relay socket drops ON ITS OWN. A listener
+ * the scheduler closes itself (refresh, stop) may or may not fire `onClose` — both are handled.
+ */
+ open(token: string, events: { onBridged(): void; onClose(): void }): Listener
+ setTimeout(fn: () => void, ms: number): unknown
+ clearTimeout(h: unknown): void
+ onStatus?(s: SchedulerStatus): void
+}
+
+interface Entry {
+ listener: Listener | null
+ bridged: boolean
+ /** The refresh timer's handle, or null. Compared with null, never by truthiness: 0 is a handle. */
+ refresh: unknown
+}
+
+const clampDelay = (ms: number): number => Math.min(MAX_DELAY_MS, ms)
+const errorText = (err: unknown): string => (err instanceof Error ? err.message : String(err))
+
+export function createHostedScheduler(deps: SchedulerDeps, now: () => number) {
+ let state: SchedulerStatus['state'] = 'stopped'
+ let lastError: string | null = null
+ let opening = false
+ let attempt = 0
+ let retry: unknown = null
+ const mints: number[] = []
+ const live = new Set<Entry>()
+
+ const status = (): SchedulerStatus => {
+ const cutoff = now() - HOUR_MS
+ while (mints.length && mints[0] < cutoff) mints.shift()
+ let idle = 0
+ let bridged = 0
+ for (const e of live) {
+ if (e.bridged) bridged++
+ else idle++
+ }
+ return { state, lastError, mintsLastHour: mints.length, idle, bridged }
+ }
+ const emit = (): void => {
+ if (!deps.onStatus) return
+ try {
+ deps.onStatus(status())
+ } catch {
+ // An observer's bug must not wedge the lifecycle it is observing.
+ }
+ }
+
+ // The relay leg demonstrably works: the backoff has done its job and the last failure is history.
+ const proven = (): void => {
+ attempt = 0
+ lastError = null
+ }
+
+ const scheduleRetry = (minMs = 0): void => {
+ if (state !== 'running' || retry !== null) return
+ const ms = clampDelay(Math.max(minMs, BACKOFF_MS[Math.min(attempt, BACKOFF_MS.length - 1)]))
+ attempt++
+ retry = deps.setTimeout(() => {
+ retry = null
+ void top()
+ }, ms)
+ }
+
+ const drop = (e: Entry): void => {
+ if (e.refresh !== null) deps.clearTimeout(e.refresh)
+ e.refresh = null
+ live.delete(e)
+ }
+ const closeQuietly = (l: Listener | null): void => {
+ try {
+ l?.close()
+ } catch {
+ // Already dead or half-built: there is nothing left to close.
+ }
+ }
+
+ const armRefresh = (e: Entry, ttlMs: number): void => {
+ if (e.refresh !== null) deps.clearTimeout(e.refresh)
+ const ttl = Number.isFinite(ttlMs) ? ttlMs : DEFAULT_TTL_MS
+ e.refresh = deps.setTimeout(() => {
+ e.refresh = null
+ if (state !== 'running' || !live.has(e)) return
+ // This listener held its relay registration for a whole token lifetime: the relay is reachable.
+ proven()
+ // A listener serving a peer is never cut for a refresh — the relay drops it at TTL and onClose
+ // takes it from there. Only an IDLE listener is swapped for a freshly minted one.
+ if (e.bridged) {
+ armRefresh(e, DEFAULT_TTL_MS)
+ emit()
+ return
+ }
+ drop(e)
+ closeQuietly(e.listener)
+ emit()
+ void top()
+ }, clampDelay(Math.max(MIN_REFRESH_MS, ttl - REFRESH_LEAD_MS)))
+ }
+
+ const idleCount = (): number => {
+ let n = 0
+ for (const e of live) if (!e.bridged) n++
+ return n
+ }
+
+ // Keep one idle listener registered. Never two mints at once, and never ahead of an armed backoff.
+ async function top(): Promise<void> {
+ if (state !== 'running' || opening || retry !== null || idleCount() >= 1) return
+ opening = true
+ let opened = false
+ try {
+ let r: MintResult
+ let threw: string | null = null
+ try {
+ r = await deps.mint()
+ } catch (err) {
+ r = { ok: false, kind: 'network' }
+ threw = `mint failed: ${errorText(err)}`
+ }
+ if (r.ok) mints.push(now()) // counted even if we were stopped meanwhile: the backend counted it
+ if (state !== 'running') return
+ if (!r.ok) {
+ lastError = threw ?? (r.kind + (r.status ? ` (${r.status})` : ''))
+ if (r.kind === 'refused') {
+ state = 'backend-refused'
+ emit()
+ return
+ }
+ scheduleRetry(r.kind === 'rate-limited' ? Math.max(RATE_LIMIT_MIN_MS, r.retryAfterMs ?? 0) : 0)
+ emit()
+ return
+ }
+ // NOT proven() here: a mint proves only that the API answered, and the relay is another host.
+ const e: Entry = { listener: null, bridged: false, refresh: null }
+ live.add(e) // before open(), so an event fired synchronously from inside it is not lost
+ let listener: Listener
+ try {
+ listener = deps.open(r.pairingToken, {
+ onBridged: () => {
+ if (!live.has(e) || e.bridged) return // a stale listener, or the second report of one peer
+ e.bridged = true
+ if (e.listener) e.listener.bridged = true
+ proven() // a completed handshake proves the relay leg end to end
+ emit()
+ void top() // this listener now serves a peer: restore a warm one
+ },
+ onClose: () => {
+ if (!live.has(e)) return // we closed it ourselves (refresh / stop / replaced)
+ drop(e)
+ if (e.bridged) {
+ // A peer's session ended. Its replacement was opened on bridging, so this is normally a
+ // no-op — and a teammate leaving is not a relay failure, so it never advances the backoff.
+ emit()
+ void top()
+ return
+ }
+ // An idle listener dropping on its own is the relay refusing or unreachable.
+ lastError = 'relay closed the idle listener'
+ scheduleRetry()
+ emit()
+ }
+ })
+ } catch (err) {
+ live.delete(e)
+ lastError = `open failed: ${errorText(err)}`
+ scheduleRetry()
+ emit()
+ return
+ }
+ e.listener = listener
+ if (e.bridged) listener.bridged = true
+ if (!live.has(e)) {
+ // It closed (or was stopped) during open(): its onClose already decided what comes next.
+ closeQuietly(listener)
+ return
+ }
+ opened = true
+ armRefresh(e, r.ttlMs)
+ emit()
+ } finally {
+ opening = false
+ // Still short (the new listener bridged during open()): continue, as the desktop does.
+ if (opened && state === 'running' && idleCount() < 1) queueMicrotask(() => void top())
+ }
+ }
+
+ return {
+ start(): void {
+ if (state === 'running') return
+ state = 'running'
+ attempt = 0
+ emit()
+ void top()
+ },
+ stop(): void {
+ state = 'stopped'
+ if (retry !== null) {
+ deps.clearTimeout(retry)
+ retry = null
+ }
+ for (const e of [...live]) {
+ drop(e)
+ closeQuietly(e.listener)
+ }
+ emit()
+ },
+ status
+ }
+}