- src/shutdown.ts: every command's process group is remembered until it is empty; on exit what is left gets TERM, a grace, KILL. Signals of a run: first SIGINT stops the turn and the wait for jobs (exit 130), a second, or SIGTERM/SIGHUP once, ends it now (143/129) with the groups killed. - settleJobs takes a stop signal and says which jobs it stops; a failed or cancelled prompt does not wait for its jobs. - A foreground command that leaves a program in its group says so; the listener on its output is taken off when the call returns. - A spawn error is reported as what it was. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
112 lines
5.0 KiB
TypeScript
112 lines
5.0 KiB
TypeScript
// One way out (src/shutdown.ts): nothing a command started outlives the program, by whatever
|
|
// door it leaves; `lembas run` can be interrupted while it waits for a job.
|
|
import { afterEach, expect, test } from "bun:test"
|
|
import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"
|
|
import { tmpdir } from "node:os"
|
|
import { join } from "node:path"
|
|
import { createApp } from "../src/app.ts"
|
|
import type { AskReply } from "../src/bus/index.ts"
|
|
import { paths } from "../src/config/paths.ts"
|
|
import { settleJobs } from "../src/headless.ts"
|
|
import { groupAlive, killGroupsSync, liveGroups } from "../src/shutdown.ts"
|
|
import { bashTool, LEFT_BEHIND } from "../src/tool/bash.ts"
|
|
import { delta, fakeProvider, toolCall, type Fake } from "./fake-provider.ts"
|
|
|
|
let fake: Fake | undefined
|
|
afterEach(() => {
|
|
fake?.stop()
|
|
killGroupsSync(50)
|
|
})
|
|
|
|
const alive = (pid: number) => {
|
|
try {
|
|
process.kill(pid, 0)
|
|
return true
|
|
} catch {
|
|
return false
|
|
}
|
|
}
|
|
const gone = async (pid: number, ms = 3000) => {
|
|
const until = Date.now() + ms
|
|
while (Date.now() < until && alive(pid)) await Bun.sleep(20)
|
|
return !alive(pid)
|
|
}
|
|
|
|
test("a wait for a background job ends when the run is interrupted, and the job is stopped", async () => {
|
|
fake = fakeProvider([{ chunks: [toolCall(0, "t1", "bash", JSON.stringify({ command: "sleep 60", background: true, description: "server" }))] }, { chunks: [delta({ content: "Running." })] }])
|
|
mkdirSync(paths.config, { recursive: true })
|
|
writeFileSync(join(paths.config, "connections.yaml"), `connections:\n f:\n type: webui\n url: ${fake.url}\n models: { f/m: {} }\n`, { mode: 0o600 })
|
|
writeFileSync(join(paths.config, "config.yaml"), "model: f/m\n")
|
|
const a = createApp({ cwd: mkdtempSync(join(tmpdir(), "ph-sd-")), mode: "auto", store: false, snapshots: false, asker: { ask: async (): Promise<AskReply> => ({ kind: "once" }) } })
|
|
await a.turns.prompt("go")
|
|
const sid = a.jobsSessionId()
|
|
expect(a.registry.running(sid)).toHaveLength(1)
|
|
const stop = new AbortController()
|
|
const said: string[] = []
|
|
const started = Date.now()
|
|
setTimeout(() => stop.abort(), 300)
|
|
await settleJobs(a, true, { stop: stop.signal, say: (t) => said.push(t) })
|
|
expect(Date.now() - started).toBeLessThan(4000)
|
|
expect(said.join("\n")).toContain("stopping 1 background job")
|
|
expect(a.registry.running(sid)).toEqual([])
|
|
})
|
|
|
|
test("a foreground command that leaves a program behind says so, and the program ends with lembas", async () => {
|
|
const root = mkdtempSync(join(tmpdir(), "ph-sd-"))
|
|
const ctx = { root, cwd: root, signal: new AbortController().signal, readFiles: new Set<string>(), fileStamps: new Map(), bashTimeoutMs: 5000 }
|
|
const r = await bashTool.run({ command: "sleep 60 >/dev/null 2>&1 & echo $!", description: "x" }, ctx)
|
|
const pid = Number(/^\d+/.exec(r.output)![0])
|
|
expect(r.output).toContain(LEFT_BEHIND)
|
|
expect(alive(pid)).toBe(true)
|
|
expect(liveGroups().length).toBeGreaterThan(0)
|
|
killGroupsSync(100)
|
|
expect(await gone(pid)).toBe(true)
|
|
})
|
|
|
|
test("a command that ends cleanly is forgotten", async () => {
|
|
const root = mkdtempSync(join(tmpdir(), "ph-sd-"))
|
|
const ctx = { root, cwd: root, signal: new AbortController().signal, readFiles: new Set<string>(), fileStamps: new Map(), bashTimeoutMs: 5000 }
|
|
const r = await bashTool.run({ command: "echo hi", description: "x" }, ctx)
|
|
expect(r.output).not.toContain(LEFT_BEHIND)
|
|
expect(liveGroups()).toEqual([])
|
|
})
|
|
|
|
for (const [sig, code] of [["SIGTERM", 143], ["SIGHUP", 129]] as const)
|
|
test(`${sig} ends the program and what it started (exit ${code})`, async () => {
|
|
const script = `
|
|
import { spawn } from "node:child_process"
|
|
import { onSignals, trackGroup } from ${JSON.stringify(join(import.meta.dir, "..", "src", "shutdown.ts"))}
|
|
const child = spawn("bash", ["-c", "trap '' HUP; sleep 60"], { detached: true, stdio: "ignore" })
|
|
trackGroup(child.pid)
|
|
onSignals({ gentle() {}, last: (n) => console.error("left " + n) })
|
|
console.log(child.pid)
|
|
setInterval(() => {}, 1000)
|
|
`
|
|
const p = Bun.spawn(["bun", "-e", script], { stdout: "pipe", stderr: "pipe" })
|
|
const reader = p.stdout.getReader()
|
|
const pid = Number(new TextDecoder().decode((await reader.read()).value).trim())
|
|
expect(alive(pid)).toBe(true)
|
|
p.kill(sig)
|
|
expect(await p.exited).toBe(code)
|
|
expect(await new Response(p.stderr).text()).toContain("left 1")
|
|
expect(await gone(pid)).toBe(true)
|
|
expect(groupAlive(pid)).toBe(false)
|
|
})
|
|
|
|
test("the first Ctrl+C is gentle, the second ends it", async () => {
|
|
const script = `
|
|
import { onSignals } from ${JSON.stringify(join(import.meta.dir, "..", "src", "shutdown.ts"))}
|
|
onSignals({ gentle: () => console.log("gentle") })
|
|
console.log("ready")
|
|
setInterval(() => {}, 1000)
|
|
`
|
|
const p = Bun.spawn(["bun", "-e", script], { stdout: "pipe", stderr: "pipe" })
|
|
const reader = p.stdout.getReader()
|
|
const dec = new TextDecoder()
|
|
let out = dec.decode((await reader.read()).value)
|
|
p.kill("SIGINT")
|
|
while (!out.includes("gentle")) out += dec.decode((await reader.read()).value)
|
|
p.kill("SIGINT")
|
|
expect(await p.exited).toBe(130)
|
|
})
|