GeezerVison is showing github.com — fix(cli): wait for background jobs in opencode run · anomalyco/opencode@1feba95
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: packages/cli/src/run/noninteractive.ts +64-7Lines changed: 64 additions & 7 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -39,6 +39,8 @@ type Input = { | 39 | 39 | /** True when the client is attached to a shared server rather than an exclusive in-process one. */ | 40 | 40 | attached: boolean | 41 | 41 | compatibility?: "v1" | | 42 | + /** How long running background shells keep the run open after the model's last reply. */ | | 43 | + backgroundShellWait?: number | 42 | 44 | renderTool: (part: SessionMessageAssistantTool) => Promise<void> | 43 | 45 | renderToolError: (part: SessionMessageAssistantTool) => Promise<void> | 44 | 46 | } | @@ -70,6 +72,10 @@ const GLOBAL_FORM_SESSION_ID = "global" | 70 | 72 | const QUESTION_CANCELLED_FEEDBACK = | 71 | 73 | "This non-interactive run cannot ask the user questions, so the question was cancelled. Continue without an answer; make reasonable assumptions and state them." | 72 | 74 |
| | 75 | +// A finishing test or build wakes the model well within this. A server left running on purpose never | | 76 | +// finishes, so after this long the run exits without it. Subagents and images always finish. | | 77 | +const BACKGROUND_SHELL_WAIT_MS = 10 * 60 * 1000 | | 78 | + | 73 | 79 | const PERMISSION_REJECTED_FEEDBACK = | 74 | 80 | "This non-interactive run cannot ask the user for permission, so the request was rejected. Continue without this action." | 75 | 81 |
| @@ -97,6 +103,8 @@ export async function runNonInteractivePrompt(input: Input) { | 97 | 103 | let v1InvalidOutput = false | 98 | 104 | let prePromotionError: { message: string; [key: string]: unknown } | undefined | 99 | 105 | let finalizing = false | | 106 | + let shellWait: ReturnType<typeof setTimeout> | undefined | | 107 | + let shellWaitExpired = false | 100 | 108 | let admission: AbortController | undefined | 101 | 109 | let pendingStep: { timestamp: number; part: Record<string, unknown>; label: string } | undefined | 102 | 110 |
| @@ -158,6 +166,23 @@ export async function runNonInteractivePrompt(input: Input) { | 158 | 166 | return result | 159 | 167 | } | 160 | 168 |
| | 169 | + // Only this session's own jobs hold the run open. A subagent reports back through its job here, so | | 170 | + // work it leaves behind, such as a dev server it tested against, never keeps the run alive. | | 171 | + const pendingBackground = async (): Promise<"none" | "work" | "shells"> => { | | 172 | + if (input.compatibility === "v1" || interrupted || permissionRejected || formCancelled || emittedError) | | 173 | + return "none" | | 174 | + const jobs = await input.client.experimental.job.list({ sessionID: input.sessionID }).catch(() => []) | | 175 | + if (jobs.length > 0) | | 176 | + return jobs.every((job) => job.kind === "shell" && job.status === "running") ? "shells" : "work" | | 177 | + // A finished job wakes this session before its row is removed, so a wake that raced the | | 178 | + // list above shows up as an active session or a queued inbox item. | | 179 | + const [active, inbox] = await Promise.all([ | | 180 | + input.client.session.active().catch(() => ({})), | | 181 | + input.client.session.inbox.list({ sessionID: input.sessionID }).catch(() => []), | | 182 | + ]) | | 183 | + return input.sessionID in active || inbox.length > 0 ? "work" : "none" | | 184 | + } | | 185 | + | 161 | 186 | const replyPermission = async (request: { | 162 | 187 | id: string | 163 | 188 | sessionID: string | @@ -209,14 +234,20 @@ export async function runNonInteractivePrompt(input: Input) { | 209 | 234 | if (input.compatibility !== "v1") process.exitCode = 1 | 210 | 235 | } | 211 | 236 |
| 212 | | - const consume = async () => { | | 237 | + const consume = () => consumeEvents().finally(() => clearTimeout(shellWait)) | | 238 | + | | 239 | + const consumeEvents = async () => { | | 240 | + const aborted = new Promise<{ done: true; value: undefined }>((resolve) => { | | 241 | + if (controller.signal.aborted) resolve({ done: true, value: undefined }) | | 242 | + else controller.signal.addEventListener("abort", () => resolve({ done: true, value: undefined }), { once: true }) | | 243 | + }) | 213 | 244 | while (!controller.signal.aborted) { | 214 | | - const next = await stream.next().catch((error) => { | 215 | | - if (!emittedError) throw error | | 245 | + const next = await Promise.race([stream.next(), aborted]).catch((error) => { | | 246 | + if (!emittedError && !interrupted) throw error | 216 | 247 | return { done: true as const, value: undefined } | 217 | 248 | }) | 218 | 249 | if (next.done) { | 219 | | - if (emittedError) return | | 250 | + if (emittedError || interrupted || shellWaitExpired) return | 220 | 251 | throw new Error("Event stream disconnected during prompt execution") | 221 | 252 | } | 222 | 253 | const event = next.value | @@ -546,7 +577,18 @@ export async function runNonInteractivePrompt(input: Input) { | 546 | 577 | } | 547 | 578 | return | 548 | 579 | } | 549 | | - if (event.type === "session.execution.succeeded") return | | 580 | + if (event.type === "session.execution.succeeded") { | | 581 | + // Each reply restarts the wait; subagents and images hold the run until they report. | | 582 | + clearTimeout(shellWait) | | 583 | + const background = await pendingBackground() | | 584 | + if (background === "none") return | | 585 | + if (background === "shells") | | 586 | + shellWait = setTimeout(() => { | | 587 | + shellWaitExpired = true | | 588 | + controller.abort() | | 589 | + }, input.backgroundShellWait ?? BACKGROUND_SHELL_WAIT_MS) | | 590 | + continue | | 591 | + } | 550 | 592 | } | 551 | 593 | } | 552 | 594 |
| @@ -711,7 +753,14 @@ export async function runNonInteractivePrompt(input: Input) { | 711 | 753 | interrupted = true | 712 | 754 | process.exitCode = 130 | 713 | 755 | admission?.abort() | 714 | | - void input.client.session.interrupt({ sessionID: input.sessionID }).catch(() => {}) | | 756 | + void input.client.session | | 757 | + .interrupt({ sessionID: input.sessionID }) | | 758 | + .then((result) => { | | 759 | + if (!result.interrupted) controller.abort() | | 760 | + }) | | 761 | + .catch(() => { | | 762 | + controller.abort() | | 763 | + }) | 715 | 764 | } | 716 | 765 | process.on("SIGINT", interrupt) | 717 | 766 |
| @@ -790,7 +839,15 @@ export async function runNonInteractivePrompt(input: Input) { | 790 | 839 | return | 791 | 840 | } | 792 | 841 |
| 793 | | - const waiting = input.client.experimental.session.wait({ sessionID: input.sessionID }) | | 842 | + const waitUntilIdle = async () => { | | 843 | + await input.client.experimental.session.wait({ sessionID: input.sessionID }) | | 844 | + if ((await pendingBackground()) === "none") return | | 845 | + await completed | | 846 | + if (!interrupted && !permissionRejected && !formCancelled && !emittedError) { | | 847 | + await input.client.experimental.session.wait({ sessionID: input.sessionID }) | | 848 | + } | | 849 | + } | | 850 | + const waiting = waitUntilIdle() | 794 | 851 | await Promise.race([waiting, completed.then(() => waiting)]) | 795 | 852 | finalizing = true | 796 | 853 | const projected = await reconcile() | |
Collapse file Copy file name to clipboardExpand all lines: packages/cli/test/run/noninteractive.test.ts +68-2Lines changed: 68 additions & 2 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, mock, spyOn, test } from "bun:test" | 2 | 2 | import { | 3 | 3 | OpenCode, | 4 | 4 | type EventSubscribeOutput, | | 5 | + type ExperimentalJobListOutput, | 5 | 6 | type SessionMessageAssistantTool, | 6 | 7 | type SessionMessageInfo, | 7 | 8 | } from "@opencode/client/promise" | @@ -217,6 +218,8 @@ async function run(input: { | 217 | 218 | renderToolError?: (part: SessionMessageAssistantTool) => Promise<void> | 218 | 219 | messages?: (inboxID: string) => SessionMessageInfo[] | 219 | 220 | wait?: () => Promise<void> | | 221 | + jobs?: () => ExperimentalJobListOutput | | 222 | + backgroundShellWait?: number | 220 | 223 | terminalDelay?: number | 221 | 224 | }) { | 222 | 225 | const sdk = OpenCode.make({ baseUrl: "https://opencode.test" }) | @@ -254,6 +257,9 @@ async function run(input: { | 254 | 257 | spyOn(sdk.session.form, "cancel").mockImplementation((request) => (input.cancel?.(request) ?? ok(undefined)) as never) | 255 | 258 | let promptID = "msg_prompt" | 256 | 259 | spyOn(sdk.experimental.session, "wait").mockImplementation(() => input.wait?.() ?? wait.promise) | | 260 | + spyOn(sdk.experimental.job, "list").mockImplementation(() => ok(input.jobs?.() ?? []) as never) | | 261 | + spyOn(sdk.session, "active").mockImplementation(() => ok({}) as never) | | 262 | + spyOn(sdk.session.inbox, "list").mockImplementation(() => ok([]) as never) | 257 | 263 | spyOn(sdk.message, "list").mockImplementation(() => | 258 | 264 | ok({ | 259 | 265 | data: input.messages?.(promptID) ?? [{ id: promptID, type: "user", text: "hello", time: { created: 1 } }], | @@ -279,6 +285,7 @@ async function run(input: { | 279 | 285 | auto: false, | 280 | 286 | attached: input.attached ?? false, | 281 | 287 | compatibility: input.compatibility, | | 288 | + backgroundShellWait: input.backgroundShellWait, | 282 | 289 | renderTool: input.renderTool ?? (() => Promise.resolve()), | 283 | 290 | renderToolError: input.renderToolError ?? (() => Promise.resolve()), | 284 | 291 | }) | @@ -312,6 +319,21 @@ afterEach(() => { | 312 | 319 | process.exitCode = 0 | 313 | 320 | }) | 314 | 321 |
| | 322 | +function shellJob(id: string, command: string): ExperimentalJobListOutput[number] { | | 323 | + return { kind: "shell", id, sessionID: "ses_1", status: "running", shellID: id, command, time: { started: 1 } } | | 324 | +} | | 325 | + | | 326 | +const subagentJob: ExperimentalJobListOutput[number] = { | | 327 | + kind: "subagent", | | 328 | + id: "ses_child", | | 329 | + sessionID: "ses_1", | | 330 | + status: "running", | | 331 | + childSessionID: "ses_child", | | 332 | + agent: "explore", | | 333 | + description: "scan repo", | | 334 | + time: { started: 1 }, | | 335 | +} | | 336 | + | 315 | 337 | describe("runNonInteractivePrompt", () => { | 316 | 338 | test("keeps formatted tool output and compact tool metadata in JSON", async () => { | 317 | 339 | const output = await capture({ format: "json", turn: successfulGrep }) | @@ -474,7 +496,10 @@ describe("runNonInteractivePrompt", () => { | 474 | 496 | } | 475 | 497 | expect(sdk.session.form.cancel).toHaveBeenCalledWith({ sessionID: "global", formID: "frm_live" }, globalOptions) | 476 | 498 | expect(sdk.session.form.cancel).toHaveBeenCalledWith({ sessionID: "ses_1", formID: "frm_pending" }) | 477 | | - expect(sdk.session.form.cancel).toHaveBeenCalledWith({ sessionID: "global", formID: "frm_pending_global" }, globalOptions) | | 499 | + expect(sdk.session.form.cancel).toHaveBeenCalledWith( | | 500 | + { sessionID: "global", formID: "frm_pending_global" }, | | 501 | + globalOptions, | | 502 | + ) | 478 | 503 | expect(sdk.form.list).toHaveBeenCalledWith({ | 479 | 504 | location: { directory: "/work tree" }, | 480 | 505 | }) | @@ -489,7 +514,10 @@ describe("runNonInteractivePrompt", () => { | 489 | 514 | }) | 490 | 515 | expect(sdk.session.form.cancel).toHaveBeenCalledWith({ sessionID: "ses_1", formID: "frm_pending" }) | 491 | 516 | expect(sdk.form.list).not.toHaveBeenCalled() | 492 | | - expect(sdk.session.form.cancel).not.toHaveBeenCalledWith({ sessionID: "global", formID: "frm_live" }, expect.anything()) | | 517 | + expect(sdk.session.form.cancel).not.toHaveBeenCalledWith( | | 518 | + { sessionID: "global", formID: "frm_live" }, | | 519 | + expect.anything(), | | 520 | + ) | 493 | 521 | expect(sdk.session.form.cancel).not.toHaveBeenCalledWith( | 494 | 522 | { sessionID: "global", formID: "frm_pending_global" }, | 495 | 523 | expect.anything(), | @@ -618,4 +646,42 @@ describe("runNonInteractivePrompt", () => { | 618 | 646 | expect(events[0].part.state.metadata.content).toBeUndefined() | 619 | 647 | expect(output.stderr).toBe("") | 620 | 648 | }) | | 649 | + | | 650 | + test("waits for a background shell and streams the reply it wakes", async () => { | | 651 | + const lists: ExperimentalJobListOutput[] = [[shellJob("sh_train", "python train.py")], []] | | 652 | + const output = await capture({ | | 653 | + format: "json", | | 654 | + jobs: () => lists.shift() ?? [], | | 655 | + turn: (id) => [ | | 656 | + prompted(id), | | 657 | + settled(), | | 658 | + { | | 659 | + id: "evt_text", | | 660 | + created: 2, | | 661 | + type: "session.text.ended", | | 662 | + durable: { aggregateID: "ses_1", seq: 2, version: 1 }, | | 663 | + data: { sessionID: "ses_1", assistantMessageID: "msg_2", ordinal: 0, text: "Training finished." }, | | 664 | + }, | | 665 | + settled(), | | 666 | + ], | | 667 | + }) | | 668 | + expect(output.stdout).toContain("Training finished.") | | 669 | + }) | | 670 | + | | 671 | + test("exits when only shells are left after the wait", async () => { | | 672 | + const sdk = await run({ | | 673 | + turn: (id) => [prompted(id), settled()], | | 674 | + jobs: () => [shellJob("sh_dev", "bun dev")], | | 675 | + backgroundShellWait: 0, | | 676 | + }) | | 677 | + expect(sdk.experimental.job.list).toHaveBeenCalledWith({ sessionID: "ses_1" }) | | 678 | + }) | | 679 | + | | 680 | + test("waits for background subagents without the shell wait", async () => { | | 681 | + const running = run({ turn: (id) => [prompted(id), settled()], jobs: () => [subagentJob], backgroundShellWait: 0 }) | | 682 | + expect(await Promise.race([running.then(() => "exited"), Bun.sleep(20).then(() => "waiting")])).toBe("waiting") | | 683 | + process.emit("SIGINT") | | 684 | + await running | | 685 | + expect(process.exitCode).toBe(130) | | 686 | + }) | 621 | 687 | }) |
|