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
torque/forge:torque/474-a-finished-run-must-free-its-slot-close → main 4 commits fork
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 | ||
| 602 | 602 | it the same way, as its next turn, rather than queuing a second run behind |
| 603 | 603 | the first; only when nobody is listening does a follow-up run queue, and |
| 604 | 604 | 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. | |
| 605 | 611 | |
| 606 | 612 | Each agent's row on |
| 607 | 613 | the crew page carries the numbers that say how it is doing: runs and how |
forge.json +1 −1
| @@ -6,7 +6,7 @@ | ||
| 6 | 6 | "ready": 90 |
| 7 | 7 | }, |
| 8 | 8 | "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", | |
| 10 | 10 | "timeout": 1800 |
| 11 | 11 | } |
| 12 | 12 | } |
src/actions/runs.ts +12
| @@ -60,6 +60,18 @@ export function announceRun(app: App, run: Run, actorId?: string): void { | ||
| 60 | 60 | }); |
| 61 | 61 | } |
| 62 | 62 | |
| 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 | ||
| 63 | 75 | export function listRepoRuns( |
| 64 | 76 | app: App, |
| 65 | 77 | actor: User | undefined, |
src/core/runs.ts +19
| @@ -77,6 +77,8 @@ export interface Run { | ||
| 77 | 77 | readonly sandboxNote: string; |
| 78 | 78 | /** A failed check's own detail, when its output was recognised; null otherwise. */ |
| 79 | 79 | 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; | |
| 80 | 82 | readonly createdAt: string; |
| 81 | 83 | readonly startedAt: string | null; |
| 82 | 84 | /** When this deploy's environment started serving — set once, at the swap-in. */ |
| @@ -105,6 +107,7 @@ interface RunRow { | ||
| 105 | 107 | sandbox_enforced: number | null; |
| 106 | 108 | sandbox_note: string; |
| 107 | 109 | check_detail: string; |
| 110 | finishing_at: string | null; | |
| 108 | 111 | created_at: string; |
| 109 | 112 | started_at: string | null; |
| 110 | 113 | serving_at: string | null; |
| @@ -133,6 +136,7 @@ const toRun = (r: RunRow): Run => ({ | ||
| 133 | 136 | r.sandbox_enforced === null ? null : r.sandbox_enforced !== 0, |
| 134 | 137 | sandboxNote: r.sandbox_note, |
| 135 | 138 | checkDetail: r.check_detail ? (JSON.parse(r.check_detail) as CheckDetail) : null, |
| 139 | finishingAt: r.finishing_at ?? null, | |
| 136 | 140 | createdAt: r.created_at, |
| 137 | 141 | startedAt: r.started_at, |
| 138 | 142 | servingAt: r.serving_at, |
| @@ -325,6 +329,21 @@ export function noteRunProgress( | ||
| 325 | 329 | ); |
| 326 | 330 | } |
| 327 | 331 | |
| 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 | ||
| 328 | 347 | /** |
| 329 | 348 | * The most recent finished agent run about an issue by one agent — the |
| 330 | 349 | * 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[] = [ | ||
| 1081 | 1081 | PRIMARY KEY (operation_id, position) |
| 1082 | 1082 | ); |
| 1083 | 1083 | `, |
| 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 | `, | |
| 1084 | 1091 | ]; |
src/crew/claude.ts +82 −9
| @@ -36,8 +36,32 @@ 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 | /** | |
| 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; | |
| 39 | 58 | } |
| 40 | 59 | |
| 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 | ||
| 41 | 65 | export interface ClaudeOutcome { |
| 42 | 66 | /** Whether the run ended with a result rather than an error. */ |
| 43 | 67 | readonly ok: boolean; |
| @@ -181,6 +205,10 @@ export async function runClaude(input: ClaudeInput): Promise<ClaudeOutcome> { | ||
| 181 | 205 | // already gone |
| 182 | 206 | } |
| 183 | 207 | }; |
| 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(); | |
| 184 | 212 | say(input.prompt); |
| 185 | 213 | input.onSteer?.((text) => { |
| 186 | 214 | if (!say(text)) return false; |
| @@ -198,8 +226,44 @@ export async function runClaude(input: ClaudeInput): Promise<ClaudeOutcome> { | ||
| 198 | 226 | let ok = false; |
| 199 | 227 | let sawResult = false; |
| 200 | 228 | |
| 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 | ||
| 201 | 264 | const onLine = (line: string): void => { |
| 202 | 265 | if (line.trim() === "") return; |
| 266 | if (sawResult && !finished) armIdle(); | |
| 203 | 267 | let event: unknown; |
| 204 | 268 | try { |
| 205 | 269 | event = JSON.parse(line); |
| @@ -250,8 +314,10 @@ export async function runClaude(input: ClaudeInput): Promise<ClaudeOutcome> { | ||
| 250 | 314 | } |
| 251 | 315 | // A turn is over. Something said meanwhile is the next turn; nothing |
| 252 | 316 | // 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(); | |
| 255 | 321 | return; |
| 256 | 322 | } |
| 257 | 323 | // `user` records are tool results: long and mostly file contents. |
| @@ -274,7 +340,8 @@ export async function runClaude(input: ClaudeInput): Promise<ClaudeOutcome> { | ||
| 274 | 340 | setTimeout(() => { |
| 275 | 341 | if (proc.exitCode === null && proc.signalCode === null) |
| 276 | 342 | signalGroup("SIGKILL"); |
| 277 | }, 5_000); | |
| 343 | stopReading.abort(); | |
| 344 | }, 5_000).unref(); | |
| 278 | 345 | }; |
| 279 | 346 | const timer = setTimeout(() => { |
| 280 | 347 | why = "timeout"; |
| @@ -289,15 +356,21 @@ export async function runClaude(input: ClaudeInput): Promise<ClaudeOutcome> { | ||
| 289 | 356 | |
| 290 | 357 | const stderr: string[] = []; |
| 291 | 358 | 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 | ), | |
| 298 | 369 | proc.exited, |
| 299 | 370 | ]); |
| 300 | 371 | clearTimeout(timer); |
| 372 | clearTimeout(idle); | |
| 373 | clearTimeout(settle); | |
| 301 | 374 | closeInput(); |
| 302 | 375 | input.signal.removeEventListener("abort", onAbort); |
| 303 | 376 |
src/crew/runner.ts +9 −1
| @@ -17,7 +17,7 @@ import type { App } from "../app.ts"; | ||
| 17 | 17 | import { addComment } from "../actions/issues.ts"; |
| 18 | 18 | import { openPull } from "../actions/pulls.ts"; |
| 19 | 19 | import { forkRepo } from "../actions/repos.ts"; |
| 20 | import { announceRun } from "../actions/runs.ts"; | |
| 20 | import { announceFinishing, announceRun } from "../actions/runs.ts"; | |
| 21 | 21 | import { previewEnv } from "../apps/data.ts"; |
| 22 | 22 | import { appsRuntime } from "../apps/runtime.ts"; |
| 23 | 23 | import { crewRole, getAgent, type Agent } from "../core/agents.ts"; |
| @@ -42,7 +42,9 @@ import { | ||
| 42 | 42 | checkSummary, |
| 43 | 43 | claimRun, |
| 44 | 44 | finishRun, |
| 45 | getRun, | |
| 45 | 46 | lastAgentRun, |
| 47 | noteRunFinishing, | |
| 46 | 48 | noteRunProgress, |
| 47 | 49 | type Run, |
| 48 | 50 | } from "../core/runs.ts"; |
| @@ -701,6 +703,7 @@ async function work( | ||
| 701 | 703 | budgetUsd: number, |
| 702 | 704 | resume: string | undefined, |
| 703 | 705 | ): Promise<ClaudeOutcome> => { |
| 706 | noteRunFinishing(app.db, run.id, false); | |
| 704 | 707 | const spent = redactResult( |
| 705 | 708 | await runClaude({ |
| 706 | 709 | binary: options.binary, |
| @@ -716,6 +719,11 @@ async function work( | ||
| 716 | 719 | log: write, |
| 717 | 720 | signal, |
| 718 | 721 | 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 | }, | |
| 719 | 727 | }), |
| 720 | 728 | ); |
| 721 | 729 | meter.tokensIn += spent.tokensIn; |
src/design/activity.ts +4 −1
| @@ -22,7 +22,9 @@ const environment = (env: unknown): string => { | ||
| 22 | 22 | |
| 23 | 23 | /** Moments rather than facts: a feed shows what came of them instead. */ |
| 24 | 24 | 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"; | |
| 26 | 28 | |
| 27 | 29 | export function eventVerb(event: ForgeEvent): string { |
| 28 | 30 | const { kind, payload } = event; |
| @@ -125,6 +127,7 @@ const WORDS: Record<string, string> = { | ||
| 125 | 127 | "origin.needs_reauth": "needs to reconnect an origin", |
| 126 | 128 | "run.queued": "queued a run", |
| 127 | 129 | "run.started": "started a run", |
| 130 | "run.finishing": "is finishing a run", | |
| 128 | 131 | "app.created": "made it an app", |
| 129 | 132 | "app.updated": "changed the app's settings", |
| 130 | 133 | "app.deleted": "stopped serving it as an app", |
src/web/pages/board.ts +9 −2
| @@ -72,10 +72,15 @@ function reasonWords(reason: string): string { | ||
| 72 | 72 | } |
| 73 | 73 | } |
| 74 | 74 | |
| 75 | type StateWord = "queued" | "working" | "paused"; | |
| 75 | type StateWord = "queued" | "working" | "finishing" | "paused"; | |
| 76 | 76 | |
| 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 | */ | |
| 77 | 81 | function stateWord(run: Run): StateWord { |
| 78 | if (run.state === "running") return "working"; | |
| 82 | if (run.state === "running") | |
| 83 | return run.finishingAt === null ? "working" : "finishing"; | |
| 79 | 84 | return run.notBefore === null ? "queued" : "paused"; |
| 80 | 85 | } |
| 81 | 86 | |
| @@ -713,6 +718,8 @@ ${widths} | ||
| 713 | 718 | .board-run[data-state="working"] .board-state { color: var(--accent); } |
| 714 | 719 | .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); } |
| 715 | 720 | .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); } | |
| 716 | 723 | .board-run[data-state="queued"] .board-elapsed { color: var(--muted-fg); } |
| 717 | 724 | .board-run[data-state="paused"] .board-state { color: var(--attn); } |
| 718 | 725 | .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"; | ||
| 19 | 19 | import { recordLook } from "../src/core/looks.ts"; |
| 20 | 20 | import { getPull } from "../src/core/pulls.ts"; |
| 21 | 21 | 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"; | |
| 23 | 28 | import { createUser, getUserByName, type User } from "../src/core/users.ts"; |
| 24 | 29 | import { serve, type Servers } from "../src/http/server.ts"; |
| 25 | 30 | |
| @@ -326,6 +331,28 @@ describe("the board", () => { | ||
| 326 | 331 | const next = await fetch(`${base}/board?wall`, { redirect: "manual" }); |
| 327 | 332 | expect(next.headers.get("location")).toMatch(/^\/signin\?next=/); |
| 328 | 333 | }); |
| 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 | }); | |
| 329 | 356 | }); |
| 330 | 357 | |
| 331 | 358 | 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 | }); |
new above
offline