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 #486

Closed opened this in answer to
Closed without merging

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

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
11 files changed +316 −15
docs/APPS.md +6
@@ -602,6 +602,12 @@ comment or review left on the issue or pull while the agent works reaches
602602 it the same way, as its next turn, rather than queuing a second run behind
603603 the first; only when nobody is listening does a follow-up run queue, and
604604 one waiting is enough. _Stop_ sits beside _Send_ while the run goes.
605 Once the agent's final result is in and no word is pending, the forge
606 closes the session and the run is only _finishing_ — the board says so —
607 so words sent from then on go on the conversation too. A process that
608 lingers past five seconds after its result is stopped, and a steered
609 session silent for five minutes after a result is closed and settled as
610 done; the log says which.
605611
606612 Each agent's row on
607613 the crew page carries the numbers that say how it is doing: runs and how
forge.json +1 −1
@@ -6,7 +6,7 @@
66 "ready": 90
77 },
88 "check": {
9 "run": "bun x tsc --noEmit && bun scripts/test-shards.ts --timeout 60000 test/crew.test.ts test/crew-wrapup.test.ts test/crew-limits.test.ts test/crew-sandbox.test.ts test/steer.test.ts test/landing.test.ts test/decide.test.ts test/ledger.test.ts test/checks.test.ts test/dependencies.test.ts test/autonomy.test.ts test/studio.test.ts test/studio-words.test.ts test/forks.test.ts test/fork-flow.test.ts test/cross-repo-pull.test.ts test/pulls.test.ts test/apps.test.ts test/apps-adversarial.test.ts test/apps-busy.test.ts test/apps-token.test.ts test/web.test.ts test/git-trust.test.ts test/helpers.test.ts test/shards.test.ts test/migrate.test.ts test/vitals.test.ts test/asks.test.ts test/feed.test.ts test/feed-page.test.ts test/offline.test.ts test/share.test.ts test/cloud.test.ts test/run-secrets.test.ts test/forge-cloudflare.test.ts test/usage.test.ts test/standing.test.ts test/board-windows.test.ts test/spawn-plan.test.ts test/spawn.test.ts test/web-apps.test.ts test/fleet-ops.test.ts",
9 "run": "bun x tsc --noEmit && bun scripts/test-shards.ts --timeout 60000 test/crew.test.ts test/crew-wrapup.test.ts test/crew-limits.test.ts test/crew-sandbox.test.ts test/steer.test.ts test/session-settle.test.ts test/landing.test.ts test/decide.test.ts test/ledger.test.ts test/checks.test.ts test/dependencies.test.ts test/autonomy.test.ts test/studio.test.ts test/studio-words.test.ts test/forks.test.ts test/fork-flow.test.ts test/cross-repo-pull.test.ts test/pulls.test.ts test/apps.test.ts test/apps-adversarial.test.ts test/apps-busy.test.ts test/apps-token.test.ts test/web.test.ts test/git-trust.test.ts test/helpers.test.ts test/shards.test.ts test/migrate.test.ts test/vitals.test.ts test/asks.test.ts test/feed.test.ts test/feed-page.test.ts test/offline.test.ts test/share.test.ts test/cloud.test.ts test/run-secrets.test.ts test/forge-cloudflare.test.ts test/usage.test.ts test/standing.test.ts test/board-windows.test.ts test/spawn-plan.test.ts test/spawn.test.ts test/web-apps.test.ts test/fleet-ops.test.ts",
1010 "timeout": 1800
1111 }
1212 }
src/actions/runs.ts +12
@@ -60,6 +60,18 @@ export function announceRun(app: App, run: Run, actorId?: string): void {
6060 });
6161 }
6262
63 /**
64 * A running agent run whose agent has given its final result: it is only
65 * finishing now, and the live pages that show it repaint to say so.
66 */
67 export function announceFinishing(app: App, run: Run): void {
68 app.bus.append({
69 kind: "run.finishing",
70 repoId: run.repoId,
71 payload: runPayload(run),
72 });
73 }
74
6375 export function listRepoRuns(
6476 app: App,
6577 actor: User | undefined,
src/core/runs.ts +19
@@ -77,6 +77,8 @@ export interface Run {
7777 readonly sandboxNote: string;
7878 /** A failed check's own detail, when its output was recognised; null otherwise. */
7979 readonly checkDetail: CheckDetail | null;
80 /** For an agent run: when the agent's work ended and the run began finishing; null while it works. */
81 readonly finishingAt: string | null;
8082 readonly createdAt: string;
8183 readonly startedAt: string | null;
8284 /** When this deploy's environment started serving — set once, at the swap-in. */
@@ -105,6 +107,7 @@ interface RunRow {
105107 sandbox_enforced: number | null;
106108 sandbox_note: string;
107109 check_detail: string;
110 finishing_at: string | null;
108111 created_at: string;
109112 started_at: string | null;
110113 serving_at: string | null;
@@ -133,6 +136,7 @@ const toRun = (r: RunRow): Run => ({
133136 r.sandbox_enforced === null ? null : r.sandbox_enforced !== 0,
134137 sandboxNote: r.sandbox_note,
135138 checkDetail: r.check_detail ? (JSON.parse(r.check_detail) as CheckDetail) : null,
139 finishingAt: r.finishing_at ?? null,
136140 createdAt: r.created_at,
137141 startedAt: r.started_at,
138142 servingAt: r.serving_at,
@@ -325,6 +329,21 @@ export function noteRunProgress(
325329 );
326330 }
327331
332 /**
333 * An agent run is finishing (its session's final result is in) or working
334 * again (a wrap-up turn began). Only a running run moves.
335 */
336 export function noteRunFinishing(
337 db: Database,
338 runId: string,
339 finishing: boolean,
340 ): void {
341 db.query(
342 `UPDATE run SET finishing_at = CASE WHEN ?2 THEN strftime('%Y-%m-%dT%H:%M:%fZ','now') END
343 WHERE id = ?1 AND state = 'running'`,
344 ).run(runId, finishing ? 1 : 0);
345 }
346
328347 /**
329348 * The most recent finished agent run about an issue by one agent — the
330349 * session to resume and the moment after which conversation is news.
src/core/schema.ts +7
@@ -1081,4 +1081,11 @@ export const migrations: readonly string[] = [
10811081 PRIMARY KEY (operation_id, position)
10821082 );
10831083 `,
1084 // 41 — when an agent run's work ended: its final result is in and the
1085 // session is closing, so the run is only finishing — landing what it
1086 // made — and the board can tell a held slot from a working one. NULL
1087 // while the agent works.
1088 `
1089 ALTER TABLE run ADD COLUMN finishing_at TEXT;
1090 `,
10841091 ];
src/crew/claude.ts +82 −9
@@ -36,8 +36,32 @@ export interface ClaudeInput {
3636 * send after the session ended returns false.
3737 */
3838 readonly onSteer?: ((send: (text: string) => boolean) => void) | undefined;
39 /**
40 * Called once when the agent's work is over: its final result is in and
41 * the forge has closed the session's input. What is left is the process
42 * going away, which `settleMs` bounds.
43 */
44 readonly onFinishing?: (() => void) | undefined;
45 /**
46 * How long a session may stay silent after a result — no output, no tool
47 * activity — before it is closed and settled as done. Default 5 minutes:
48 * a steer folded into the turn already answered leaves one owed result
49 * that never comes.
50 */
51 readonly idleMs?: number | undefined;
52 /**
53 * How long the process has to exit once its input is closed after the
54 * final result. Past it, the process group is stopped and the run settles
55 * on the result it already gave. Default 5 seconds.
56 */
57 readonly settleMs?: number | undefined;
3958 }
4059
60 /** The idle guard's default: five minutes of silence after a result. */
61 export const IDLE_AFTER_RESULT_MS = 5 * 60_000;
62 /** The grace a finished session has to exit on its own. */
63 export const SETTLE_MS = 5_000;
64
4165 export interface ClaudeOutcome {
4266 /** Whether the run ended with a result rather than an error. */
4367 readonly ok: boolean;
@@ -181,6 +205,10 @@ export async function runClaude(input: ClaudeInput): Promise<ClaudeOutcome> {
181205 // already gone
182206 }
183207 };
208 // The reads stop on their own when the process exits — unless something
209 // it spawned still holds the pipe. Aborting them is how a settled session
210 // stops waiting on a server the agent left running.
211 const stopReading = new AbortController();
184212 say(input.prompt);
185213 input.onSteer?.((text) => {
186214 if (!say(text)) return false;
@@ -198,8 +226,44 @@ export async function runClaude(input: ClaudeInput): Promise<ClaudeOutcome> {
198226 let ok = false;
199227 let sawResult = false;
200228
229 // After a result, the session is either on a steered turn or finished.
230 // Any line it writes is activity and puts the idle guard back; silence
231 // past `idleMs` means the turn it owes is not coming.
232 const idleMs = input.idleMs ?? IDLE_AFTER_RESULT_MS;
233 const settleMs = input.settleMs ?? SETTLE_MS;
234 let idle: ReturnType<typeof setTimeout> | undefined;
235 let settle: ReturnType<typeof setTimeout> | undefined;
236 let finished = false;
237 const armIdle = (): void => {
238 clearTimeout(idle);
239 idle = setTimeout(() => {
240 input.log(
241 `session: no output for ${Math.round(idleMs / 1000)}s after its last result; closing it`,
242 );
243 finish();
244 }, idleMs);
245 };
246 // The work is over: close the input, say so, and give the process
247 // `settleMs` to go. One that lingers is stopped and the result stands.
248 const finish = (): void => {
249 if (finished) return;
250 finished = true;
251 clearTimeout(idle);
252 closeInput();
253 input.onFinishing?.();
254 settle = setTimeout(() => {
255 if (proc.exitCode === null && proc.signalCode === null)
256 input.log(
257 `session: still open ${Math.round(settleMs / 1000)}s after its result; stopping it`,
258 );
259 stopChild();
260 stopReading.abort();
261 }, settleMs);
262 };
263
201264 const onLine = (line: string): void => {
202265 if (line.trim() === "") return;
266 if (sawResult && !finished) armIdle();
203267 let event: unknown;
204268 try {
205269 event = JSON.parse(line);
@@ -250,8 +314,10 @@ export async function runClaude(input: ClaudeInput): Promise<ClaudeOutcome> {
250314 }
251315 // A turn is over. Something said meanwhile is the next turn; nothing
252316 // said means the session is done, and closing stdin lets it end.
253 if (pending > 0 && ok) pending--;
254 else closeInput();
317 if (pending > 0 && ok) {
318 pending--;
319 armIdle();
320 } else finish();
255321 return;
256322 }
257323 // `user` records are tool results: long and mostly file contents.
@@ -274,7 +340,8 @@ export async function runClaude(input: ClaudeInput): Promise<ClaudeOutcome> {
274340 setTimeout(() => {
275341 if (proc.exitCode === null && proc.signalCode === null)
276342 signalGroup("SIGKILL");
277 }, 5_000);
343 stopReading.abort();
344 }, 5_000).unref();
278345 };
279346 const timer = setTimeout(() => {
280347 why = "timeout";
@@ -289,15 +356,21 @@ export async function runClaude(input: ClaudeInput): Promise<ClaudeOutcome> {
289356
290357 const stderr: string[] = [];
291358 const [, , code] = await Promise.all([
292 pump(proc.stdout, onLine),
293 pump(proc.stderr, (line) => {
294 stderr.push(line);
295 if (stderr.length > 50) stderr.shift();
296 input.log(`! ${line}`);
297 }),
359 pump(proc.stdout, onLine, stopReading.signal),
360 pump(
361 proc.stderr,
362 (line) => {
363 stderr.push(line);
364 if (stderr.length > 50) stderr.shift();
365 input.log(`! ${line}`);
366 },
367 stopReading.signal,
368 ),
298369 proc.exited,
299370 ]);
300371 clearTimeout(timer);
372 clearTimeout(idle);
373 clearTimeout(settle);
301374 closeInput();
302375 input.signal.removeEventListener("abort", onAbort);
303376
src/crew/runner.ts +9 −1
@@ -17,7 +17,7 @@ import type { App } from "../app.ts";
1717 import { addComment } from "../actions/issues.ts";
1818 import { openPull } from "../actions/pulls.ts";
1919 import { forkRepo } from "../actions/repos.ts";
20 import { announceRun } from "../actions/runs.ts";
20 import { announceFinishing, announceRun } from "../actions/runs.ts";
2121 import { previewEnv } from "../apps/data.ts";
2222 import { appsRuntime } from "../apps/runtime.ts";
2323 import { crewRole, getAgent, type Agent } from "../core/agents.ts";
@@ -42,7 +42,9 @@ import {
4242 checkSummary,
4343 claimRun,
4444 finishRun,
45 getRun,
4546 lastAgentRun,
47 noteRunFinishing,
4648 noteRunProgress,
4749 type Run,
4850 } from "../core/runs.ts";
@@ -701,6 +703,7 @@ async function work(
701703 budgetUsd: number,
702704 resume: string | undefined,
703705 ): Promise<ClaudeOutcome> => {
706 noteRunFinishing(app.db, run.id, false);
704707 const spent = redactResult(
705708 await runClaude({
706709 binary: options.binary,
@@ -716,6 +719,11 @@ async function work(
716719 log: write,
717720 signal,
718721 onSteer: (send) => steering.set(run.id, send),
722 onFinishing: () => {
723 noteRunFinishing(app.db, run.id, true);
724 const now = getRun(app.db, run.id);
725 if (now?.state === "running") announceFinishing(app, now);
726 },
719727 }),
720728 );
721729 meter.tokensIn += spent.tokensIn;
src/design/activity.ts +4 −1
@@ -22,7 +22,9 @@ const environment = (env: unknown): string => {
2222
2323 /** Moments rather than facts: a feed shows what came of them instead. */
2424 export const isTransientEvent = (kind: string): boolean =>
25 kind === "run.queued" || kind === "run.started";
25 kind === "run.queued" ||
26 kind === "run.started" ||
27 kind === "run.finishing";
2628
2729 export function eventVerb(event: ForgeEvent): string {
2830 const { kind, payload } = event;
@@ -125,6 +127,7 @@ const WORDS: Record<string, string> = {
125127 "origin.needs_reauth": "needs to reconnect an origin",
126128 "run.queued": "queued a run",
127129 "run.started": "started a run",
130 "run.finishing": "is finishing a run",
128131 "app.created": "made it an app",
129132 "app.updated": "changed the app's settings",
130133 "app.deleted": "stopped serving it as an app",
src/web/pages/board.ts +9 −2
@@ -72,10 +72,15 @@ function reasonWords(reason: string): string {
7272 }
7373 }
7474
75 type StateWord = "queued" | "working" | "paused";
75 type StateWord = "queued" | "working" | "finishing" | "paused";
7676
77 /**
78 * A running run whose agent has given its final result is only finishing —
79 * landing what it made — so a slot held past the work shows as such.
80 */
7781 function stateWord(run: Run): StateWord {
78 if (run.state === "running") return "working";
82 if (run.state === "running")
83 return run.finishingAt === null ? "working" : "finishing";
7984 return run.notBefore === null ? "queued" : "paused";
8085 }
8186
@@ -713,6 +718,8 @@ ${widths}
713718 .board-run[data-state="working"] .board-state { color: var(--accent); }
714719 .board-run[data-state="working"] .board-state::before { background: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 22%, transparent); }
715720 .board-run[data-state="working"] .board-elapsed { color: var(--accent); }
721 .board-run[data-state="finishing"] .board-state { color: var(--fg); }
722 .board-run[data-state="finishing"] .board-state::before { background: var(--accent); }
716723 .board-run[data-state="queued"] .board-elapsed { color: var(--muted-fg); }
717724 .board-run[data-state="paused"] .board-state { color: var(--attn); }
718725 .board-run[data-state="paused"] .board-state::before { background: var(--attn); }
test/board.test.ts +28 −1
@@ -19,7 +19,12 @@ import { recordDecision } from "../src/core/decisions.ts";
1919 import { recordLook } from "../src/core/looks.ts";
2020 import { getPull } from "../src/core/pulls.ts";
2121 import { updateRepoSettings, type Repo } from "../src/core/repos.ts";
22 import { claimRun, createRun } from "../src/core/runs.ts";
22 import {
23 cancelRun,
24 claimRun,
25 createRun,
26 noteRunFinishing,
27 } from "../src/core/runs.ts";
2328 import { createUser, getUserByName, type User } from "../src/core/users.ts";
2429 import { serve, type Servers } from "../src/http/server.ts";
2530
@@ -326,6 +331,28 @@ describe("the board", () => {
326331 const next = await fetch(`${base}/board?wall`, { redirect: "manual" });
327332 expect(next.headers.get("location")).toMatch(/^\/signin\?next=/);
328333 });
334
335 test("a run whose agent has given its final result reads finishing, not working", async () => {
336 const run = createRun(app.db, {
337 repoId: shop.id,
338 kind: "agent",
339 reason: "assigned",
340 summary: "landing the cart",
341 });
342 claimRun(app.db, run.id);
343 const card = async (): Promise<string> => {
344 const html = await (await get("/board")).text();
345 const at = html.indexOf(`/alice/shop/runs/${run.id}`);
346 return html.slice(html.lastIndexOf("<a", at), at);
347 };
348 expect(await card()).toContain('data-state="working"');
349 noteRunFinishing(app.db, run.id, true);
350 expect(await card()).toContain('data-state="finishing"');
351 // A wrap-up turn puts it back to work.
352 noteRunFinishing(app.db, run.id, false);
353 expect(await card()).toContain('data-state="working"');
354 cancelRun(app.db, run.id);
355 });
329356 });
330357
331358 describe("the board's forge strip", () => {
test/session-settle.test.ts added +139
@@ -0,0 +1,139 @@
1 /**
2 * A finished run frees its slot. Once the agent's final result is in and
3 * nothing a person said is owed a turn, the session's input closes and the
4 * run settles within seconds — even if the process, or something it left
5 * running, never lets go. A steered turn that never answers is closed by
6 * the idle guard and settled as done.
7 */
8 import { afterAll, describe, expect, test } from "bun:test";
9 import { chmodSync, writeFileSync } from "node:fs";
10 import { mkdtemp, rm } from "node:fs/promises";
11 import { tmpdir } from "node:os";
12 import { join } from "node:path";
13 import { runClaude, type ClaudeInput } from "../src/crew/claude.ts";
14 import { sandboxPolicy } from "../src/crew/sandbox.ts";
15
16 const RESULT =
17 '{"type":"result","subtype":"success","is_error":false,"result":"done","total_cost_usd":0.01,"num_turns":1}';
18
19 const dirs: string[] = [];
20 afterAll(async () => {
21 for (const dir of dirs) await rm(dir, { recursive: true, force: true });
22 });
23
24 async function fakeClaude(script: string): Promise<{
25 common: Omit<ClaudeInput, "prompt">;
26 lines: string[];
27 }> {
28 const dir = await mkdtemp(join(tmpdir(), "forge-settle-"));
29 dirs.push(dir);
30 const fake = join(dir, "fake-claude");
31 writeFileSync(fake, `#!/bin/sh\n${script}`);
32 chmodSync(fake, 0o755);
33 const lines: string[] = [];
34 return {
35 lines,
36 common: {
37 binary: fake,
38 cwd: dir,
39 appendSystemPrompt: "",
40 budgetUsd: 1,
41 env: {},
42 sandbox: sandboxPolicy({ dataDir: dir, agentName: "bot", urls: [] }),
43 // The 45-minute cap stands in at a minute: far past what a settled
44 // run may take.
45 timeoutMs: 60_000,
46 log: (line: string) => lines.push(line),
47 signal: new AbortController().signal,
48 },
49 };
50 }
51
52 describe("a finished session", () => {
53 test("a result, then a process that waits: the run settles in under 10 s, as done", async () => {
54 // Ignores its closed stdin and holds stdout open through a child, the
55 // way a server the agent started in the background would.
56 const { common, lines } = await fakeClaude(`IFS= read -r first
57 echo '{"type":"system","subtype":"init","session_id":"s1","model":"fake"}'
58 echo '${RESULT}'
59 sleep 600 &
60 wait
61 `);
62 let finishing = 0;
63 const started = Date.now();
64 const outcome = await runClaude({
65 ...common,
66 prompt: "Do the thing.",
67 onFinishing: () => finishing++,
68 });
69 expect(Date.now() - started).toBeLessThan(10_000);
70 expect(outcome.ok).toBe(true);
71 expect(outcome.reason).toBe("completed");
72 expect(outcome.result).toBe("done");
73 expect(finishing).toBe(1);
74 expect(lines.some((l) => l.includes("still open"))).toBe(true);
75 }, 20_000);
76
77 test("a process that exits on its own settles without being stopped", async () => {
78 const { common, lines } = await fakeClaude(`IFS= read -r first
79 echo '${RESULT}'
80 `);
81 const started = Date.now();
82 const outcome = await runClaude({ ...common, prompt: "Do the thing." });
83 expect(Date.now() - started).toBeLessThan(3_000);
84 expect(outcome.ok).toBe(true);
85 expect(lines.some((l) => l.startsWith("session:"))).toBe(false);
86 }, 20_000);
87
88 test("a steer after the result finds nobody listening, so it becomes a comment", async () => {
89 const { common } = await fakeClaude(`IFS= read -r first
90 echo '${RESULT}'
91 sleep 600
92 `);
93 let send: ((text: string) => boolean) | undefined;
94 let late: boolean | undefined;
95 const outcome = await runClaude({
96 ...common,
97 prompt: "Do the thing.",
98 settleMs: 1_000,
99 onSteer: (s) => {
100 send = s;
101 },
102 onFinishing: () => {
103 late = send?.("one more thing");
104 },
105 });
106 expect(outcome.ok).toBe(true);
107 expect(late).toBe(false);
108 }, 20_000);
109
110 test("a steered turn that never answers is closed by the idle guard and settled as done", async () => {
111 // Answers the prompt, takes the steer, then goes silent — the owed
112 // result never comes.
113 const { common, lines } = await fakeClaude(`IFS= read -r first
114 echo '{"type":"system","subtype":"init","session_id":"s1","model":"fake"}'
115 sleep 0.4
116 echo '${RESULT}'
117 IFS= read -r second
118 sleep 600
119 `);
120 let send: ((text: string) => boolean) | undefined;
121 const steered = runClaude({
122 ...common,
123 prompt: "Do the thing.",
124 idleMs: 500,
125 settleMs: 500,
126 onSteer: (s) => {
127 send = s;
128 },
129 });
130 await Bun.sleep(150);
131 expect(send!("also add a test")).toBe(true);
132 const started = Date.now();
133 const outcome = await steered;
134 expect(Date.now() - started).toBeLessThan(5_000);
135 expect(outcome.ok).toBe(true);
136 expect(outcome.reason).toBe("completed");
137 expect(lines.some((l) => l.includes("no output for"))).toBe(true);
138 }, 20_000);
139 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs