Skip to content

Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.

TypeScript

feat(byoa): re-detect engines on the heartbeat instead of on re-pair

Xialie Zhuang2b256038c99f
diff --git a/server/src/__tests__/computer-engine-redetect.test.ts b/server/src/__tests__/computer-engine-redetect.test.ts
new file mode 100644
index 0000000..85f699f
--- /dev/null
+++ b/server/src/__tests__/computer-engine-redetect.test.ts
@@ -0,0 +1,75 @@
+/**
+ * Re-detecting a paired computer's engines on the heartbeat.
+ *
+ * `available_engines[0]` is the computer's DEFAULT engine — pairComputer says so
+ * outright ("first = default") and it decides the engine for the starter team
+ * and for any agent assigned without an explicit override. So refreshing the
+ * list from a PATH scan must never reorder it silently, and must never let a
+ * daemon with a broken PATH wipe it.
+ *
+ * Run: node --import tsx --test server/src/__tests__/computer-engine-redetect.test.ts
+ */
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+
+// Same shape as agent-computer-pairing-token.test.ts: pin the HTTP runtime
+// client and import registry dynamically, so the test doesn't drag the in-proc
+// client's dependency graph into a unit run.
+process.env.CUMORA_RUNTIME_CLIENT = 'http'
+
+const { mergeDetectedEngines } = await import('../agents/computer/registry.js')
+
+test('a newly installed engine is appended without re-pairing', () => {
+ // The reported case: the user installs another CLI after pairing.
+ assert.deepEqual(
+ mergeDetectedEngines(['claude', 'codex'], ['claude', 'codex', 'cursor']),
+ ['claude', 'codex', 'cursor'],
+ )
+})
+
+test('the current default stays first even when detection orders it later', () => {
+ // detectEngines returns ENGINE_IDS order, which is NOT the user's choice.
+ // Overwriting with it would silently switch this computer's default engine.
+ assert.deepEqual(
+ mergeDetectedEngines(['codex', 'claude'], ['claude', 'codex', 'grok']),
+ ['codex', 'claude', 'grok'],
+ )
+})
+
+test('an uninstalled engine drops out, and the default moves on', () => {
+ // The default itself is gone — there is nothing to pin, so detection order wins.
+ assert.deepEqual(mergeDetectedEngines(['grok', 'claude'], ['claude', 'codex']), ['claude', 'codex'])
+})
+
+test('an unchanged list writes nothing', () => {
+ // The steady state: every heartbeat reports the same engines. Returning null
+ // keeps the 30s tick from issuing a pointless UPDATE forever.
+ assert.equal(mergeDetectedEngines(['claude', 'codex'], ['claude', 'codex']), null)
+})
+
+test('an empty detection never wipes the stored engines', () => {
+ // A broken PATH or a half-finished CLI upgrade must not un-assign every agent
+ // on the machine.
+ assert.equal(mergeDetectedEngines(['claude'], []), null)
+})
+
+test('a detection of only unknown ids is treated as empty', () => {
+ // A newer daemon reporting an engine this server has no adapter for must not
+ // clear the list either.
+ assert.equal(mergeDetectedEngines(['claude'], ['gemini', 'hermes']), null)
+})
+
+test('unknown ids are filtered out but known ones still apply', () => {
+ assert.deepEqual(
+ mergeDetectedEngines(['claude'], ['claude', 'gemini', 'opencode']),
+ ['claude', 'opencode'],
+ )
+})
+
+test('duplicates in a detection are collapsed', () => {
+ assert.deepEqual(mergeDetectedEngines(['claude'], ['claude', 'claude', 'codex']), ['claude', 'codex'])
+})
+
+test('a computer with no stored engines adopts the detection order', () => {
+ assert.deepEqual(mergeDetectedEngines([], ['claude', 'codex']), ['claude', 'codex'])
+})
diff --git a/server/src/agents/computer/daemon.ts b/server/src/agents/computer/daemon.ts
index f9758f6..1fcc29a 100644
--- a/server/src/agents/computer/daemon.ts
+++ b/server/src/agents/computer/daemon.ts
@@ -59,6 +59,11 @@ const DEFAULT_SERVER = process.env.CUMORA_SERVER_URL || 'https://api.cumora.ai'
const TOKEN_REFRESH_SKEW_MS = 5 * 60 * 1000 // refresh 5min before expiry
const AGENT_POLL_MS = 60_000
const HEARTBEAT_MS = 30_000
+// How often the daemon re-scans PATH for installed engines. Deliberately much
+// slower than the heartbeat: detection spawns a `which`/`where` per engine, and
+// nobody installs a CLI twice a minute. The heartbeat carries the CACHED result,
+// so the report costs nothing on the 30s tick.
+const ENGINE_RESCAN_MS = 5 * 60 * 1000
// While an engine turn is in flight, bump the run's updated_at this often so the
// server's 10-min stale-run sweeper doesn't false-positive a legitimately long
// turn (a multi-hour Bash, a deep task) as "orphaned". 60s = 10× margin under the
@@ -2462,6 +2467,21 @@ async function doRun(serverOverride?: string): Promise<void> {
}
}
+ // Engines this machine can currently run, re-scanned on a slow timer. Reported
+ // on every heartbeat so installing another supported CLI takes effect without
+ // re-pairing — the daemon is already online and can see PATH itself, so there
+ // is no reason to make the user mint a new pairing token for it.
+ let detectedEngines: EngineId[] = await detectEngines()
+ const rescanEngines = async (): Promise<void> => {
+ try {
+ const next = await detectEngines()
+ if (next.length === 0) return // broken PATH / mid-upgrade — keep the last good list
+ const changed = next.length !== detectedEngines.length || next.some((e, i) => e !== detectedEngines[i])
+ if (changed) console.log(`[computer] engines on PATH changed: ${detectedEngines.join(', ') || 'none'} → ${next.join(', ')}`)
+ detectedEngines = next
+ } catch { /* transient — the next tick retries */ }
+ }
+
const heartbeat = async (): Promise<void> => {
try {
await fetch(`${cfg.serverUrl}/api/computers/heartbeat`, {
@@ -2473,7 +2493,7 @@ async function doRun(serverOverride?: string): Promise<void> {
// `supervised` tells the server HOW this daemon runs (service vs. a
// foreground command), so the app's upgrade banner can show the right
// update instructions for this machine.
- body: JSON.stringify({ version: CURRENT_VERSION, supervised: SUPERVISED }),
+ body: JSON.stringify({ version: CURRENT_VERSION, supervised: SUPERVISED, engines: detectedEngines }),
})
} catch { /* transient — next tick retries */ }
}
@@ -2485,6 +2505,8 @@ async function doRun(serverOverride?: string): Promise<void> {
}
const poll = setInterval(() => { void sync() }, AGENT_POLL_MS)
const beat = setInterval(() => { void heartbeat() }, HEARTBEAT_MS)
+ const rescan = setInterval(() => { void rescanEngines() }, ENGINE_RESCAN_MS)
+ rescan.unref?.()
// Keep the service log from filling the disk: rotate at boot, then periodically.
void rotateLogsIfNeeded()
const logrot = setInterval(() => { void rotateLogsIfNeeded() }, LOG_ROTATE_MS)
@@ -2503,7 +2525,7 @@ async function doRun(serverOverride?: string): Promise<void> {
const shutdown = async (why: string): Promise<void> => {
if (shuttingDown) return
shuttingDown = true
- clearInterval(poll); clearInterval(beat); clearInterval(logrot)
+ clearInterval(poll); clearInterval(beat); clearInterval(logrot); clearInterval(rescan)
if (upd) clearInterval(upd)
if (idleWatch) clearInterval(idleWatch)
if (controlWatch) clearInterval(controlWatch)
diff --git a/server/src/agents/computer/registry.ts b/server/src/agents/computer/registry.ts
index f9b02da..085d679 100644
--- a/server/src/agents/computer/registry.ts
+++ b/server/src/agents/computer/registry.ts
@@ -47,6 +47,34 @@ export async function announceComputerOnline(computerId: string, companyId: stri
/** Engines a paired (non-cloud) computer is allowed to advertise. */
const PAIRABLE_ENGINES: ReadonlySet<string> = new Set(['claude', 'codex', 'grok', 'cursor', 'opencode'])
+/** Merge a fresh PATH detection into a computer's advertised engine list.
+ *
+ * `available_engines[0]` is the computer's DEFAULT — pairComputer's comment
+ * puts it plainly: "first = default", and it decides the engine for the starter
+ * team and for any agent assigned without an explicit override. So a re-detect
+ * must never reorder silently: if the current default is still installed it
+ * stays first, and the rest follow detection order. Installing a new CLI adds
+ * it to the tail; uninstalling one drops it.
+ *
+ * Returns null when there is nothing to write — an empty or fully-unknown
+ * detection, or a list identical to what is stored. A daemon that reports no
+ * engines (a broken PATH, a half-finished upgrade) must NOT wipe a computer's
+ * engines and un-assign every agent on it.
+ *
+ * Exported for tests. */
+export function mergeDetectedEngines(current: string[], detected: string[]): string[] | null {
+ const fresh = detected.filter((e) => PAIRABLE_ENGINES.has(e))
+ if (fresh.length === 0) return null
+ const seen = new Set<string>()
+ const next: string[] = []
+ const currentDefault = current[0]
+ // Keep the default pinned to the front while it is still installed.
+ if (currentDefault && fresh.includes(currentDefault)) { next.push(currentDefault); seen.add(currentDefault) }
+ for (const e of fresh) { if (!seen.has(e)) { next.push(e); seen.add(e) } }
+ const same = next.length === current.length && next.every((e, i) => e === current[i])
+ return same ? null : next
+}
+
export interface ComputerRow {
id: string
company_id: string
@@ -275,9 +303,34 @@ export async function pairComputer(args: {
/** Daemon liveness ping. Bumps last_seen_at + the reported version; flips
* offline→online and broadcasts only on the transition (so a steady heartbeat
* is quiet). The version lets the app flag outdated daemons. */
-export async function heartbeatComputer(computerId: string, version?: string, supervised?: boolean): Promise<void> {
+export async function heartbeatComputer(
+ computerId: string,
+ version?: string,
+ supervised?: boolean,
+ detectedEngines?: string[],
+): Promise<void> {
const v = typeof version === 'string' && version ? version.slice(0, 32) : null
const sup = typeof supervised === 'boolean' ? supervised : null
+ // Keep the advertised engine list current WITHOUT a re-pair. The daemon is
+ // already online and re-scans PATH, so installing another supported CLI shows
+ // up here instead of requiring the user to mint a new pairing token. Only for
+ // paired computers: a cloud computer advertises 'managed' and has no PATH.
+ if (detectedEngines && detectedEngines.length > 0) {
+ const { rows } = await pool.query<{ available_engines: string[]; kind: ComputerKind }>(
+ `SELECT available_engines, kind FROM computers WHERE id = $1 AND revoked_at IS NULL`,
+ [computerId],
+ )
+ const row = rows[0]
+ if (row && row.kind !== 'cloud') {
+ const next = mergeDetectedEngines(row.available_engines ?? [], detectedEngines)
+ if (next) {
+ await pool.query(
+ `UPDATE computers SET available_engines = $2::jsonb WHERE id = $1 AND revoked_at IS NULL`,
+ [computerId, JSON.stringify(next)],
+ )
+ }
+ }
+ }
const bumped = await pool.query(
`UPDATE computers SET last_seen_at = NOW(), daemon_version = COALESCE($2, daemon_version),
daemon_supervised = COALESCE($3, daemon_supervised)
diff --git a/server/src/api/router.ts b/server/src/api/router.ts
index 5f07bcb..3783d08 100644
--- a/server/src/api/router.ts
+++ b/server/src/api/router.ts
@@ -1147,7 +1147,12 @@ api.post('/computers/heartbeat', safe(async (req, res) => {
const { computerId } = await requireDevice(req)
const version = typeof req.body?.version === 'string' ? req.body.version : undefined
const supervised = typeof req.body?.supervised === 'boolean' ? req.body.supervised : undefined
- await heartbeatComputer(computerId, version, supervised)
+ // Engines the daemon can currently see on PATH. Optional: an older daemon
+ // sends none and its stored list is left exactly as it was.
+ const engines = Array.isArray(req.body?.engines)
+ ? (req.body.engines as unknown[]).filter((e): e is string => typeof e === 'string')
+ : undefined
+ await heartbeatComputer(computerId, version, supervised, engines)
res.json({ ok: true })
}))