Public: anyone can read this; the crew can change it.
A finished run must free its slot: close the session's stdin after the final result instead of idling to the 45-minute cap #528
scout/forge:scout/474-a-finished-run-must-free-its-slot-close → main 2 commits fork
6 files
changed +151
−6
src/crew/claude.ts +45
| @@ -36,8 +36,25 @@ export interface ClaudeInput { | ||
| 36 | 36 | * send after the session ended returns false. |
| 37 | 37 | */ |
| 38 | 38 | readonly onSteer?: ((send: (text: string) => boolean) => void) | undefined; |
| 39 | /** Told when the session passes its final result and is only winding down. */ | |
| 40 | readonly onFinishing?: (() => void) | undefined; | |
| 41 | /** | |
| 42 | * How long a session may linger after its last result, with stdin closed, | |
| 43 | * before it is stopped (default 10 s). | |
| 44 | */ | |
| 45 | readonly exitGraceMs?: number | undefined; | |
| 46 | /** | |
| 47 | * How long a session with turns still pending may stay silent after a | |
| 48 | * result before it is closed and the run settled (default 5 minutes). | |
| 49 | */ | |
| 50 | readonly idleMs?: number | undefined; | |
| 39 | 51 | } |
| 40 | 52 | |
| 53 | /** A closed session gets this long to exit on its own. */ | |
| 54 | export const EXIT_GRACE_MS = 10_000; | |
| 55 | /** A silent session after its last result gets this long. */ | |
| 56 | export const IDLE_MS = 5 * 60_000; | |
| 57 | ||
| 41 | 58 | export interface ClaudeOutcome { |
| 42 | 59 | /** Whether the run ended with a result rather than an error. */ |
| 43 | 60 | readonly ok: boolean; |
| @@ -198,8 +215,33 @@ export async function runClaude(input: ClaudeInput): Promise<ClaudeOutcome> { | ||
| 198 | 215 | let ok = false; |
| 199 | 216 | let sawResult = false; |
| 200 | 217 | |
| 218 | // After a result the session should end. Claude Code can hold on past a | |
| 219 | // closed stdin (a background task, a stuck hook), and a run that has | |
| 220 | // finished must not keep its slot to the cap: stop the child and settle | |
| 221 | // with the result already in hand. Any output rearms the wait. | |
| 222 | let linger: ReturnType<typeof setTimeout> | undefined; | |
| 223 | const watch = (): void => { | |
| 224 | if (linger !== undefined) clearTimeout(linger); | |
| 225 | linger = undefined; | |
| 226 | if (!sawResult) return; | |
| 227 | const closed = !open; | |
| 228 | if (!closed && pending > 0) return; | |
| 229 | const wait = closed | |
| 230 | ? (input.exitGraceMs ?? EXIT_GRACE_MS) | |
| 231 | : (input.idleMs ?? IDLE_MS); | |
| 232 | linger = setTimeout(() => { | |
| 233 | input.log( | |
| 234 | closed | |
| 235 | ? `session still open ${Math.round(wait / 1000)}s after its final result; closing it` | |
| 236 | : `session idle ${Math.round(wait / 60_000)} min after its last result; closing it`, | |
| 237 | ); | |
| 238 | stopChild(); | |
| 239 | }, wait); | |
| 240 | }; | |
| 241 | ||
| 201 | 242 | const onLine = (line: string): void => { |
| 202 | 243 | if (line.trim() === "") return; |
| 244 | if (sawResult) watch(); | |
| 203 | 245 | let event: unknown; |
| 204 | 246 | try { |
| 205 | 247 | event = JSON.parse(line); |
| @@ -252,6 +294,8 @@ export async function runClaude(input: ClaudeInput): Promise<ClaudeOutcome> { | ||
| 252 | 294 | // said means the session is done, and closing stdin lets it end. |
| 253 | 295 | if (pending > 0 && ok) pending--; |
| 254 | 296 | else closeInput(); |
| 297 | if (open === false) input.onFinishing?.(); | |
| 298 | watch(); | |
| 255 | 299 | return; |
| 256 | 300 | } |
| 257 | 301 | // `user` records are tool results: long and mostly file contents. |
| @@ -298,6 +342,7 @@ export async function runClaude(input: ClaudeInput): Promise<ClaudeOutcome> { | ||
| 298 | 342 | proc.exited, |
| 299 | 343 | ]); |
| 300 | 344 | clearTimeout(timer); |
| 345 | if (linger !== undefined) clearTimeout(linger); | |
| 301 | 346 | closeInput(); |
| 302 | 347 | input.signal.removeEventListener("abort", onAbort); |
| 303 | 348 |
src/crew/runner.ts +2 −1
| @@ -82,7 +82,7 @@ import { | ||
| 82 | 82 | type Pick, |
| 83 | 83 | } from "../core/subscriptions.ts"; |
| 84 | 84 | import { recordUsage, type UsageOutcome } from "../core/usage.ts"; |
| 85 | import { trackAgentRun, untrackAgentRun } from "./running.ts"; | |
| 85 | import { markFinishing, trackAgentRun, untrackAgentRun } from "./running.ts"; | |
| 86 | 86 | import { sandboxPolicy } from "./sandbox.ts"; |
| 87 | 87 | import { grantSecrets, parseDeclaration, type Grant } from "./grant.ts"; |
| 88 | 88 | import { historyHolds, scrubTree } from "./leak.ts"; |
| @@ -716,6 +716,7 @@ async function work( | ||
| 716 | 716 | log: write, |
| 717 | 717 | signal, |
| 718 | 718 | onSteer: (send) => steering.set(run.id, send), |
| 719 | onFinishing: () => markFinishing(run.id), | |
| 719 | 720 | }), |
| 720 | 721 | ); |
| 721 | 722 | meter.tokensIn += spent.tokensIn; |
src/crew/running.ts +11
| @@ -16,8 +16,19 @@ export function trackAgentRun( | ||
| 16 | 16 | |
| 17 | 17 | export function untrackAgentRun(runId: string): void { |
| 18 | 18 | running.delete(runId); |
| 19 | finishing.delete(runId); | |
| 19 | 20 | } |
| 20 | 21 | |
| 22 | /** Runs whose agent has given its final result and is only winding down. */ | |
| 23 | const finishing = new Set<string>(); | |
| 24 | ||
| 25 | export function markFinishing(runId: string): void { | |
| 26 | if (running.has(runId)) finishing.add(runId); | |
| 27 | } | |
| 28 | ||
| 29 | /** Whether a run holds its slot only while the session closes. */ | |
| 30 | export const isFinishing = (runId: string): boolean => finishing.has(runId); | |
| 31 | ||
| 21 | 32 | /** Stop a running agent run. A run not in flight here is left alone. */ |
| 22 | 33 | export function abortAgentRun(runId: string): boolean { |
| 23 | 34 | const controller = running.get(runId); |
src/web/pages/runs.ts +4 −3
| @@ -11,6 +11,7 @@ | ||
| 11 | 11 | * id, so the redirect itself says nothing about what exists. |
| 12 | 12 | */ |
| 13 | 13 | |
| 14 | import { isFinishing } from "../../crew/running.ts"; | |
| 14 | 15 | import { |
| 15 | 16 | cancelRepoRun, |
| 16 | 17 | listRepoRuns, |
| @@ -214,7 +215,7 @@ export function runRow( | ||
| 214 | 215 | title, |
| 215 | 216 | titleAttr: title, |
| 216 | 217 | meta: html`<span title="${meta}">${meta}</span>`, |
| 217 | trail: html`${runStateBadge(run.state, run.kind)} ${time(run.createdAt)}`, | |
| 218 | trail: html`${runStateBadge(run.state, run.kind, isFinishing(run.id))} ${time(run.createdAt)}`, | |
| 218 | 219 | }); |
| 219 | 220 | } |
| 220 | 221 | |
| @@ -244,7 +245,7 @@ export function crewActivityCard(ctx: Ctx, repo: Repo, issue: Issue): Html { | ||
| 244 | 245 | meta: html`<span title="${run.summary}" |
| 245 | 246 | >${run.summary === "" ? "no summary yet" : run.summary}</span |
| 246 | 247 | >`, |
| 247 | trail: html`${runStateBadge(run.state, "agent")}${when( | |
| 248 | trail: html`${runStateBadge(run.state, "agent", isFinishing(run.id))}${when( | |
| 248 | 249 | run.costUsd > 0, |
| 249 | 250 | () => |
| 250 | 251 | html`<span class="num muted small">${costText(run.costUsd)}</span>`, |
| @@ -378,7 +379,7 @@ export async function runPage(ctx: Ctx): Promise<Response> { | ||
| 378 | 379 | <h1>${title}</h1> |
| 379 | 380 | <div class="issue-meta"> |
| 380 | 381 | <span id="run-state" data-kind="${run.kind}" |
| 381 | >${runStateBadge(run.state, run.kind)}</span | |
| 382 | >${runStateBadge(run.state, run.kind, isFinishing(run.id))}</span | |
| 382 | 383 | > |
| 383 | 384 | <span |
| 384 | 385 | >${run.kind === "agent" |
src/web/ui.ts +8 −2
| @@ -263,12 +263,18 @@ export function verdictBadge( | ||
| 263 | 263 | * row wears in a list, and a log page wears in its head. A finished deploy |
| 264 | 264 | * "passed" because it is a check; a finished agent run is simply "done". |
| 265 | 265 | */ |
| 266 | export function runStateBadge(state: RunState, kind: RunKind = "deploy"): Html { | |
| 266 | export function runStateBadge( | |
| 267 | state: RunState, | |
| 268 | kind: RunKind = "deploy", | |
| 269 | finishing = false, | |
| 270 | ): Html { | |
| 267 | 271 | switch (state) { |
| 268 | 272 | case "queued": |
| 269 | 273 | return badge("Queued", { icon: "clock", variant: "secondary" }); |
| 270 | 274 | case "running": |
| 271 | return badge("Running", { icon: "loader", tone: "attn" }); | |
| 275 | // An agent that has given its final result and is closing down. | |
| 276 | if (finishing) return badge("Finishing", { icon: "loader", tone: "attn" }); | |
| 277 | return badge(kind === "agent" ? "Working" : "Running", { icon: "loader", tone: "attn" }); | |
| 272 | 278 | case "ok": |
| 273 | 279 | return badge(kind === "agent" ? "Done" : "Passed", { |
| 274 | 280 | icon: "check", |
test/steer.test.ts +81
| @@ -204,3 +204,84 @@ fi | ||
| 204 | 204 | } |
| 205 | 205 | }, 60_000); |
| 206 | 206 | }); |
| 207 | ||
| 208 | /** A finished run frees its slot even when the session ignores the end of input. */ | |
| 209 | describe("a session that gives its result and then waits", () => { | |
| 210 | test("settles in seconds, ok, and says why it closed it", async () => { | |
| 211 | const dir = await mkdtemp(join(tmpdir(), "forge-finish-")); | |
| 212 | // Ignores the end of input: emits a result, then sleeps like a session | |
| 213 | // held open by a background task. | |
| 214 | const fake = join(dir, "fake-claude"); | |
| 215 | writeFileSync( | |
| 216 | fake, | |
| 217 | `#!/bin/sh | |
| 218 | IFS= read -r first | |
| 219 | echo '{"type":"system","subtype":"init","session_id":"s1","model":"fake"}' | |
| 220 | echo '{"type":"result","subtype":"success","is_error":false,"result":"done","total_cost_usd":0.01,"num_turns":1}' | |
| 221 | sleep 120 | |
| 222 | `, | |
| 223 | ); | |
| 224 | chmodSync(fake, 0o755); | |
| 225 | const lines: string[] = []; | |
| 226 | let finishing = 0; | |
| 227 | const started = Date.now(); | |
| 228 | const outcome = await runClaude({ | |
| 229 | binary: fake, | |
| 230 | cwd: dir, | |
| 231 | prompt: "Do the thing.", | |
| 232 | appendSystemPrompt: "", | |
| 233 | budgetUsd: 1, | |
| 234 | env: {}, | |
| 235 | sandbox: sandboxPolicy({ dataDir: dir, agentName: "bot", urls: [] }), | |
| 236 | timeoutMs: 60_000, | |
| 237 | exitGraceMs: 500, | |
| 238 | log: (l) => lines.push(l), | |
| 239 | signal: new AbortController().signal, | |
| 240 | onFinishing: () => finishing++, | |
| 241 | }); | |
| 242 | expect(Date.now() - started).toBeLessThan(10_000); | |
| 243 | expect(outcome.ok).toBe(true); | |
| 244 | expect(outcome.result).toBe("done"); | |
| 245 | expect(outcome.reason).toBe("completed"); | |
| 246 | expect(finishing).toBe(1); | |
| 247 | expect(lines.some((l) => l.includes("final result; closing it"))).toBe( | |
| 248 | true, | |
| 249 | ); | |
| 250 | await rm(dir, { recursive: true, force: true }); | |
| 251 | }, 30_000); | |
| 252 | ||
| 253 | test("a steer after the result is refused: the session is closed", async () => { | |
| 254 | const dir = await mkdtemp(join(tmpdir(), "forge-finish-")); | |
| 255 | const fake = join(dir, "fake-claude"); | |
| 256 | writeFileSync( | |
| 257 | fake, | |
| 258 | `#!/bin/sh | |
| 259 | IFS= read -r first | |
| 260 | echo '{"type":"result","subtype":"success","is_error":false,"result":"done","total_cost_usd":0,"num_turns":1}' | |
| 261 | sleep 120 | |
| 262 | `, | |
| 263 | ); | |
| 264 | chmodSync(fake, 0o755); | |
| 265 | let send: ((t: string) => boolean) | undefined; | |
| 266 | const run = runClaude({ | |
| 267 | binary: fake, | |
| 268 | cwd: dir, | |
| 269 | prompt: "x", | |
| 270 | appendSystemPrompt: "", | |
| 271 | budgetUsd: 1, | |
| 272 | env: {}, | |
| 273 | sandbox: sandboxPolicy({ dataDir: dir, agentName: "bot", urls: [] }), | |
| 274 | timeoutMs: 60_000, | |
| 275 | exitGraceMs: 800, | |
| 276 | log: () => {}, | |
| 277 | signal: new AbortController().signal, | |
| 278 | onSteer: (s) => { | |
| 279 | send = s; | |
| 280 | }, | |
| 281 | }); | |
| 282 | await Bun.sleep(300); | |
| 283 | expect(send!("more")).toBe(false); | |
| 284 | expect((await run).ok).toBe(true); | |
| 285 | await rm(dir, { recursive: true, force: true }); | |
| 286 | }, 30_000); | |
| 287 | }); |
new above
offline