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

Closed opened this in answer to
Closed without merging

scout/forge:scout/474-a-finished-run-must-free-its-slot-close → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
6 files changed +151 −6
src/crew/claude.ts +45
@@ -36,8 +36,25 @@ export interface ClaudeInput {
3636 * send after the session ended returns false.
3737 */
3838 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;
3951 }
4052
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
4158 export interface ClaudeOutcome {
4259 /** Whether the run ended with a result rather than an error. */
4360 readonly ok: boolean;
@@ -198,8 +215,33 @@ export async function runClaude(input: ClaudeInput): Promise<ClaudeOutcome> {
198215 let ok = false;
199216 let sawResult = false;
200217
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
201242 const onLine = (line: string): void => {
202243 if (line.trim() === "") return;
244 if (sawResult) watch();
203245 let event: unknown;
204246 try {
205247 event = JSON.parse(line);
@@ -252,6 +294,8 @@ export async function runClaude(input: ClaudeInput): Promise<ClaudeOutcome> {
252294 // said means the session is done, and closing stdin lets it end.
253295 if (pending > 0 && ok) pending--;
254296 else closeInput();
297 if (open === false) input.onFinishing?.();
298 watch();
255299 return;
256300 }
257301 // `user` records are tool results: long and mostly file contents.
@@ -298,6 +342,7 @@ export async function runClaude(input: ClaudeInput): Promise<ClaudeOutcome> {
298342 proc.exited,
299343 ]);
300344 clearTimeout(timer);
345 if (linger !== undefined) clearTimeout(linger);
301346 closeInput();
302347 input.signal.removeEventListener("abort", onAbort);
303348
src/crew/runner.ts +2 −1
@@ -82,7 +82,7 @@ import {
8282 type Pick,
8383 } from "../core/subscriptions.ts";
8484 import { recordUsage, type UsageOutcome } from "../core/usage.ts";
85 import { trackAgentRun, untrackAgentRun } from "./running.ts";
85 import { markFinishing, trackAgentRun, untrackAgentRun } from "./running.ts";
8686 import { sandboxPolicy } from "./sandbox.ts";
8787 import { grantSecrets, parseDeclaration, type Grant } from "./grant.ts";
8888 import { historyHolds, scrubTree } from "./leak.ts";
@@ -716,6 +716,7 @@ async function work(
716716 log: write,
717717 signal,
718718 onSteer: (send) => steering.set(run.id, send),
719 onFinishing: () => markFinishing(run.id),
719720 }),
720721 );
721722 meter.tokensIn += spent.tokensIn;
src/crew/running.ts +11
@@ -16,8 +16,19 @@ export function trackAgentRun(
1616
1717 export function untrackAgentRun(runId: string): void {
1818 running.delete(runId);
19 finishing.delete(runId);
1920 }
2021
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
2132 /** Stop a running agent run. A run not in flight here is left alone. */
2233 export function abortAgentRun(runId: string): boolean {
2334 const controller = running.get(runId);
src/web/pages/runs.ts +4 −3
@@ -11,6 +11,7 @@
1111 * id, so the redirect itself says nothing about what exists.
1212 */
1313
14 import { isFinishing } from "../../crew/running.ts";
1415 import {
1516 cancelRepoRun,
1617 listRepoRuns,
@@ -214,7 +215,7 @@ export function runRow(
214215 title,
215216 titleAttr: title,
216217 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)}`,
218219 });
219220 }
220221
@@ -244,7 +245,7 @@ export function crewActivityCard(ctx: Ctx, repo: Repo, issue: Issue): Html {
244245 meta: html`<span title="${run.summary}"
245246 >${run.summary === "" ? "no summary yet" : run.summary}</span
246247 >`,
247 trail: html`${runStateBadge(run.state, "agent")}${when(
248 trail: html`${runStateBadge(run.state, "agent", isFinishing(run.id))}${when(
248249 run.costUsd > 0,
249250 () =>
250251 html`<span class="num muted small">${costText(run.costUsd)}</span>`,
@@ -378,7 +379,7 @@ export async function runPage(ctx: Ctx): Promise<Response> {
378379 <h1>${title}</h1>
379380 <div class="issue-meta">
380381 <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
382383 >
383384 <span
384385 >${run.kind === "agent"
src/web/ui.ts +8 −2
@@ -263,12 +263,18 @@ export function verdictBadge(
263263 * row wears in a list, and a log page wears in its head. A finished deploy
264264 * "passed" because it is a check; a finished agent run is simply "done".
265265 */
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 {
267271 switch (state) {
268272 case "queued":
269273 return badge("Queued", { icon: "clock", variant: "secondary" });
270274 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" });
272278 case "ok":
273279 return badge(kind === "agent" ? "Done" : "Passed", {
274280 icon: "check",
test/steer.test.ts +81
@@ -204,3 +204,84 @@ fi
204204 }
205205 }, 60_000);
206206 });
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 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs