diff --git a/apps/host/server/agent/agent-bridge.mjs b/apps/host/server/agent/agent-bridge.mjs index 4049561f..5239f92d 100644 --- a/apps/host/server/agent/agent-bridge.mjs +++ b/apps/host/server/agent/agent-bridge.mjs @@ -18,7 +18,7 @@ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from ' import { join } from 'node:path'; import { randomUUID } from 'node:crypto'; import { GatewayClient } from './gateway-client.mjs'; -import { HarnessProcess, resolveHarness, redact } from './harness-runtime.mjs'; +import { HarnessProcess, resolveHarness, redact, stopStaleAgent } from './harness-runtime.mjs'; import { buildProfile, routeFor } from './profile.mjs'; import { TurnProjector } from './events.mjs'; @@ -99,11 +99,13 @@ export function createAgentBridge({ dataDir, componentsDir = null, localInstance const h = harnessInfo(); if (!h.ok) throw new AgentUnavailable(h.reason, 'component-missing'); mkdirSync(home, { recursive: true }); + const stale = stopStaleAgent(join(root, 'harness.pid')); + if (stale) log(`agent · stopped a leftover Harness process (pid ${stale}) from an earlier run`); const patchFile = join(root, `profile-${profile.signature}.patch.yml`); writeFileSync(patchFile, profile.patch); const workdir = join(root, 'run'); const hp = new HarnessProcess({ - harness: h, home, patchFile, cwd: workdir, env: profile.env, nodePath, logFile: join(root, 'harness.log'), + harness: h, home, patchFile, cwd: workdir, env: profile.env, nodePath, logFile: join(root, 'harness.log'), pidFile: join(root, 'harness.pid'), onExit: exit => { log(`agent · the Harness process exited (code ${exit.code})`); if (rt?.hp === hp) { lastError = 'The agent process stopped.'; rt = null; } diff --git a/apps/host/server/agent/harness-runtime.mjs b/apps/host/server/agent/harness-runtime.mjs index f9df9ef9..162af9ea 100644 --- a/apps/host/server/agent/harness-runtime.mjs +++ b/apps/host/server/agent/harness-runtime.mjs @@ -10,7 +10,7 @@ * route change while idle), never a way to implement Stop. */ import { spawn, spawnSync } from 'node:child_process'; -import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { join, resolve } from 'node:path'; const URL_PATTERN = /http:\/\/127\.0\.0\.1:(\d+)\/\?token=([A-Za-z0-9_-]+)/; @@ -55,8 +55,8 @@ export class HarnessProcess { exited = null; #onExit; - constructor({ harness, home, patchFile, cwd, env = {}, nodePath = process.execPath, logFile = null, onExit = () => {} }) { - Object.assign(this, { harness, home, patchFile, cwd, extraEnv: env, nodePath, logFile }); + constructor({ harness, home, patchFile, cwd, env = {}, nodePath = process.execPath, logFile = null, pidFile = null, onExit = () => {} }) { + Object.assign(this, { harness, home, patchFile, cwd, extraEnv: env, nodePath, logFile, pidFile }); this.#onExit = onExit; } @@ -94,6 +94,7 @@ export class HarnessProcess { child.on('error', e => { clearTimeout(timer); reject(e); }); }).catch(async error => { await this.stop(); throw error; }); this.info = info; + if (this.pidFile) { try { writeFileSync(this.pidFile, JSON.stringify({ pid: child.pid, at: new Date().toISOString() })); } catch { /* the record is a courtesy */ } } return info; } @@ -110,9 +111,38 @@ export class HarnessProcess { setTimeout(() => { if (!this.exited) child.kill('SIGKILL'); }, graceMs).unref(); } await Promise.race([done, new Promise(r => setTimeout(r, graceMs + 2000))]); + if (this.pidFile) rmSync(this.pidFile, { force: true }); } } +/** The command line of a running process, or null. Used only to confirm a recorded PID is still our agent. */ +function commandLineOf(pid) { + if (!Number.isInteger(pid) || pid <= 0) return null; + if (process.platform === 'win32') { + const r = spawnSync('powershell', ['-NoProfile', '-NonInteractive', '-Command', `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").CommandLine`], { encoding: 'utf8', windowsHide: true, timeout: 15000 }); + return r.status === 0 && r.stdout.trim() ? r.stdout.trim() : null; + } + const r = spawnSync('ps', ['-p', String(pid), '-o', 'args='], { encoding: 'utf8' }); + return r.status === 0 && r.stdout.trim() ? r.stdout.trim() : null; +} + +/** + * A host that died without stopping its agent leaves the agent running, still holding its sessions' + * writer locks, so the next start could not resume a chat. The agent records its PID; at the next start + * a recorded PID is stopped only when it is still a `dsh` web launch (never a reused PID). + */ +export function stopStaleAgent(pidFile) { + if (!existsSync(pidFile)) return null; + let pid = null; + try { pid = Number(JSON.parse(readFileSync(pidFile, 'utf8')).pid); } catch { /* unreadable record */ } + rmSync(pidFile, { force: true }); + const cmd = commandLineOf(pid); + if (!cmd || !/apps[\\/]cli[\\/]lib[\\/]bin\.js/.test(cmd) || !/--profile web/.test(cmd)) return null; + if (process.platform === 'win32') spawnSync('taskkill', ['/PID', String(pid), '/T', '/F'], { windowsHide: true }); + else { try { process.kill(pid, 'SIGTERM'); } catch { /* already gone */ } } + return pid; +} + /** Remove any occurrence of a secret value from text bound for a log. */ export function redact(text, secrets) { let out = String(text); diff --git a/apps/host/tests/agent-bridge.test.mjs b/apps/host/tests/agent-bridge.test.mjs index e2c9605a..494d35ca 100644 --- a/apps/host/tests/agent-bridge.test.mjs +++ b/apps/host/tests/agent-bridge.test.mjs @@ -254,3 +254,32 @@ test('A05c Stop pressed while the agent is still starting cancels the start, and const again = r.run('chat-a05c', 'SCRIPT:echo fine'); await again.promise; assert.equal(text(again.frames), 'fine'); }); + +test('a leftover agent from a host that died is stopped at the next start, and an unrelated PID is never touched', { skip }, async t => { + const { HarnessProcess, stopStaleAgent } = await import('../server/agent/harness-runtime.mjs'); + const { buildProfile } = await import('../server/agent/profile.mjs'); + const { writeFileSync } = await import('node:fs'); + const { spawn } = await import('node:child_process'); + const dir = mkdtempSync(join(tmpdir(), 'strata-stale-')); + t.after(() => cleanup(dir)); + const profile = buildProfile({ local: [{ id: 'x', baseUrl: 'http://127.0.0.1:9/v1', modelId: 'm', context: 8192 }] }); + const patchFile = join(dir, 'p.patch.yml'); writeFileSync(patchFile, profile.patch); + const pidFile = join(dir, 'harness.pid'); + const hp = new HarnessProcess({ harness: resolveHarness({ env: process.env }), home: join(dir, 'home'), patchFile, cwd: join(dir, 'run'), env: profile.env, pidFile }); + await hp.start({ timeoutMs: 90_000 }); + const pid = hp.pid; + assert.ok(existsSync(pidFile), 'the agent records its PID'); + // The host "dies": nothing calls stop(). The next start finds the record. + assert.equal(stopStaleAgent(pidFile), pid); + for (let i = 0; i < 50 && hp.exited === null; i++) await new Promise(x => setTimeout(x, 100)); + assert.notEqual(hp.exited, null, 'the leftover agent was stopped'); + assert.equal(existsSync(pidFile), false); + + // A record that points at some other process must not kill it. + const bystander = spawn(process.execPath, ['-e', 'setTimeout(() => {}, 60000)'], { stdio: 'ignore' }); + t.after(() => bystander.kill()); + writeFileSync(pidFile, JSON.stringify({ pid: bystander.pid })); + assert.equal(stopStaleAgent(pidFile), null); + await new Promise(x => setTimeout(x, 300)); + assert.equal(bystander.exitCode, null, 'an unrelated process is left alone'); +});