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
fix(byoa): --stop now kills the daemon started by --pair
zhuangxialie689bd101635c
diff --git a/server/src/__tests__/agents-computer-stop-paired-daemon.test.ts b/server/src/__tests__/agents-computer-stop-paired-daemon.test.tsnew file mode 100644index 0000000..9f3047e--- /dev/null+++ b/server/src/__tests__/agents-computer-stop-paired-daemon.test.ts@@ -0,0 +1,123 @@+import assert from 'node:assert/strict'+import { spawn } from 'node:child_process'+import { mkdtemp, mkdir, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import test from 'node:test'+import { fileURLToPath } from 'node:url'++// `--stop` must kill the daemon the user actually started. The one it kept+// missing is the first-run path: `agent computer --pair <code>` on a machine+// with no service installed pairs and then falls through to `doRun`, so the+// live daemon's own command line carries `--pair` — a one-shot flag. Judged by+// its flags it was spared, while `--stop` still printed "daemon process(es)+// killed"; the daemon kept claiming agent turns until the terminal was closed.+//+// These drive the real `runComputerDaemon(['--stop'])` against real processes,+// because the bug was never in the predicate (which is right, and stays) but in+// what the caller does with it. A pure test of `isStoppableDaemonCommand` still+// passes on the broken code.++const REPO_ROOT = fileURLToPath(new URL('../../..', import.meta.url))+const DAEMON = join(REPO_ROOT, 'server/src/agents/computer/daemon.ts')+const isWindows = process.platform === 'win32'++/** A process whose `ps` command line is exactly what the real CLI produces. */+function spawnDecoy(home: string, flags: string[]): { pid: number; kill: () => void } {+ const child = spawn(+ process.execPath,+ ['-e', 'setInterval(() => {}, 1 << 30)', 'agent', 'computer', ...flags],+ { stdio: 'ignore', env: { ...process.env, HOME: home } },+ )+ assert.ok(child.pid, 'decoy failed to start')+ return { pid: child.pid, kill: () => { try { child.kill('SIGKILL') } catch { /* gone */ } } }+}++function alive(pid: number): boolean {+ try { process.kill(pid, 0); return true } catch { return false }+}++/** Run the real `--stop` in a child, so it reads OUR sandbox HOME rather than+ * the developer's — CONFIG_DIR is resolved once, at module load. */+async function runStop(home: string): Promise<string> {+ const script = `const { runComputerDaemon } = await import(${JSON.stringify(DAEMON)}); await runComputerDaemon(['--stop'])`+ const child = spawn(process.execPath, ['--import', 'tsx', '--input-type=module', '-e', script], {+ cwd: REPO_ROOT,+ env: { ...process.env, HOME: home },+ stdio: ['ignore', 'pipe', 'pipe'],+ })+ let out = ''+ child.stdout.on('data', (c) => { out += String(c) })+ child.stderr.on('data', (c) => { out += String(c) })+ await new Promise((resolve) => child.on('close', resolve))+ return out+}++async function sandbox(): Promise<string> {+ const home = await mkdtemp(join(tmpdir(), 'cumora-stop-'))+ await mkdir(join(home, '.cumora'), { recursive: true })+ return home+}++async function recordRunning(home: string, pid: number): Promise<void> {+ await writeFile(+ join(home, '.cumora', 'running.json'),+ JSON.stringify({ version: '0.0.0-test', pid, startedAt: new Date().toISOString() }),+ 'utf8',+ )+}++/** SIGTERM then SIGKILL, with a grace window matching the daemon's own. */+async function settle(): Promise<void> {+ await new Promise((r) => setTimeout(r, 2500))+}++test('--stop kills the foreground daemon started by --pair', { skip: isWindows }, async () => {+ const home = await sandbox()+ const daemon = spawnDecoy(home, ['--pair', '8lkqelTbO'])+ try {+ // What `doRun` writes about itself once it becomes the daemon.+ await recordRunning(home, daemon.pid)+ const out = await runStop(home)+ await settle()+ assert.equal(alive(daemon.pid), false, `--stop left the paired daemon running. Output:\n${out}`)+ } finally {+ daemon.kill()+ }+})++test('a --pair CLI that never became the daemon is still spared', { skip: isWindows }, async () => {+ const home = await sandbox()+ // Someone re-pairing in another terminal: same command line, but it is NOT the+ // pid in running.json, so it has never declared itself a daemon.+ const oneShot = spawnDecoy(home, ['--pair', '8lkqelTbO'])+ const daemon = spawnDecoy(home, ['--server', 'https://api.cumora.ai'])+ try {+ await recordRunning(home, daemon.pid)+ const out = await runStop(home)+ await settle()+ assert.equal(alive(daemon.pid), false, `the real daemon survived --stop. Output:\n${out}`)+ assert.equal(alive(oneShot.pid), true, `--stop killed a sibling one-shot CLI. Output:\n${out}`)+ } finally {+ oneShot.kill()+ daemon.kill()+ }+})++test('a recycled pid in running.json is not killed', { skip: isWindows }, async () => {+ const home = await sandbox()+ // The pid file is stale and the OS has handed that pid to something else. The+ // recorded pid buys a process out of the flag rule, never out of being ours.+ const stranger = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1 << 30)', 'some-other-tool', 'serve'], {+ stdio: 'ignore', env: { ...process.env, HOME: home },+ })+ assert.ok(stranger.pid)+ try {+ await recordRunning(home, stranger.pid)+ const out = await runStop(home)+ await settle()+ assert.equal(alive(stranger.pid), true, `--stop killed an unrelated process. Output:\n${out}`)+ } finally {+ try { stranger.kill('SIGKILL') } catch { /* gone */ }+ }+})diff --git a/server/src/agents/computer/daemon.ts b/server/src/agents/computer/daemon.tsindex b34d93d..edf780e 100644--- a/server/src/agents/computer/daemon.ts+++ b/server/src/agents/computer/daemon.ts@@ -3929,10 +3929,18 @@ const ONE_SHOT_SUBCOMMAND_RE = /\bagent computer (?:doctor|help)\b/* candidate set. Killing the wrapper's child is what actually stops the daemon,* and the wrapper exits with it. */export function isStoppableDaemonCommand(cmd: string): boolean {- if (!/agent computer/.test(cmd)) return false+ if (!isCumoraAgentCommand(cmd)) return falsereturn !ONE_SHOT_FLAG_RE.test(cmd) && !ONE_SHOT_SUBCOMMAND_RE.test(cmd)}+/** Is this `ps`-reported command line one of ours at all? Weaker than+ * `isStoppableDaemonCommand` on purpose: it says nothing about whether the+ * process is the long-running daemon, only that a pid we already have other+ * evidence for has not been recycled by some unrelated program. */+export function isCumoraAgentCommand(cmd: string): boolean {+ return /agent computer/.test(cmd)+}+async function commandLineForPid(pid: number): Promise<string> {if (process.platform === 'win32') {const command = `(Get-CimInstance Win32_Process -Filter "ProcessId = ${pid}" -ErrorAction SilentlyContinue).CommandLine`@@ -4013,9 +4021,10 @@ async function stopWindowsWatchdog(taskName: string): Promise<void> {* bounded fallback so engine descendants cannot be orphaned. */async function killRunningDaemons(): Promise<void> {const candidates = new Set<number>()+ let recordedPid: number | null = nulltry {const pid = (JSON.parse(await readFile(RUNNING_STATE_PATH, 'utf8')) as { pid?: number }).pid- if (typeof pid === 'number' && pid > 0) candidates.add(pid)+ if (typeof pid === 'number' && pid > 0) { candidates.add(pid); recordedPid = pid }} catch { /* no pid file */ }if (process.platform === 'win32') {for (const item of await windowsDaemonProcesses()) candidates.add(item.ProcessId)@@ -4027,16 +4036,26 @@ async function killRunningDaemons(): Promise<void> {}candidates.delete(process.pid)if (typeof process.ppid === 'number') candidates.delete(process.ppid)++ // running.json is written by `doRun` itself, so a pid recorded there HAS+ // become the long-running daemon whatever its flags say. That matters because+ // one real daemon's command line does carry a one-shot flag: `--pair` on a+ // machine with no service installed pairs and then falls through to `doRun`,+ // which is the whole first-run onboarding path. Judging it by its flags left+ // `--stop` reporting "daemon process(es) killed" while that daemon kept+ // running, kept claiming agent turns, and could only be stopped by closing the+ // terminal. For that pid we only re-confirm it is still one of ours, so a+ // stale file whose pid the OS has recycled cannot make us kill a stranger.+ //+ // Every other candidate comes from a bare pgrep and carries no such evidence,+ // so it keeps the strict rule — a sibling one-shot CLI must never be killed.+ const isVictimCommand = (pid: number, cmd: string): boolean =>+ pid === recordedPid ? isCumoraAgentCommand(cmd) : isStoppableDaemonCommand(cmd)+const victims: number[] = []for (const pid of candidates) {try {- const cmd = await commandLineForPid(pid)- // A genuine long-running daemon: "agent computer" with NO one-shot flag —- // so we never kill a sibling one-shot CLI. (Ourselves and our parent are- // already out of `candidates`.)- if (isStoppableDaemonCommand(cmd)) {- victims.push(pid)- }+ if (isVictimCommand(pid, await commandLineForPid(pid))) victims.push(pid)} catch { /* gone */ }}if (process.platform === 'win32') {@@ -4051,7 +4070,7 @@ async function killRunningDaemons(): Promise<void> {const next: number[] = []for (const pid of survivors) {try {- if (isStoppableDaemonCommand(await commandLineForPid(pid))) next.push(pid)+ if (isVictimCommand(pid, await commandLineForPid(pid))) next.push(pid)} catch { /* exited */ }}survivors = next@@ -4061,14 +4080,14 @@ async function killRunningDaemons(): Promise<void> {}for (const pid of victims) await rm(windowsShutdownRequestPath(pid), { force: true }).catch(() => {})const forceDeadline = Date.now() + 2_000- let remaining = (await windowsDaemonProcesses()).filter((item) =>- item.ProcessId !== process.pid && item.ProcessId !== process.ppid &&- isStoppableDaemonCommand(item.CommandLine))+ const stillRunning = async (): Promise<WindowsProcessInfo[]> =>+ (await windowsDaemonProcesses()).filter((item) =>+ item.ProcessId !== process.pid && item.ProcessId !== process.ppid &&+ isVictimCommand(item.ProcessId, item.CommandLine))+ let remaining = await stillRunning()while (remaining.length > 0 && Date.now() < forceDeadline) {await new Promise((resolve) => setTimeout(resolve, 100))- remaining = (await windowsDaemonProcesses()).filter((item) =>- item.ProcessId !== process.pid && item.ProcessId !== process.ppid &&- isStoppableDaemonCommand(item.CommandLine))+ remaining = await stillRunning()}if (remaining.length > 0) {throw new Error(`Windows daemon process(es) still running: ${remaining.map((item) => item.ProcessId).join(', ')}`)