GeezerVison is showing github.com — fix(cli): wait for background jobs in opencode run · anomalyco/opencode@b706e45
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 +43-6Lines changed: 43 additions & 6 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -158,6 +158,21 @@ export async function runNonInteractivePrompt(input: Input) { | 158 | 158 | return result | 159 | 159 | } | 160 | 160 |
| | 161 | + // Only this session's own jobs hold the run open. A subagent reports back through its job here, so | | 162 | + // work it leaves behind, such as a dev server it tested against, never keeps the run alive. | | 163 | + const pendingBackground = async () => { | | 164 | + if (input.compatibility === "v1" || interrupted || permissionRejected || formCancelled || emittedError) return false | | 165 | + const jobs = await input.client.experimental.job.list({ sessionID: input.sessionID }).catch(() => []) | | 166 | + if (jobs.length > 0) return true | | 167 | + // A finished job wakes this session before its row is removed, so a wake that raced the | | 168 | + // list above shows up as an active session or a queued inbox item. | | 169 | + const [active, inbox] = await Promise.all([ | | 170 | + input.client.session.active().catch(() => ({})), | | 171 | + input.client.session.inbox.list({ sessionID: input.sessionID }).catch(() => []), | | 172 | + ]) | | 173 | + return input.sessionID in active || inbox.length > 0 | | 174 | + } | | 175 | + | 161 | 176 | const replyPermission = async (request: { | 162 | 177 | id: string | 163 | 178 | sessionID: string | @@ -210,13 +225,17 @@ export async function runNonInteractivePrompt(input: Input) { | 210 | 225 | } | 211 | 226 |
| 212 | 227 | const consume = async () => { | | 228 | + const aborted = new Promise<{ done: true; value: undefined }>((resolve) => { | | 229 | + if (controller.signal.aborted) resolve({ done: true, value: undefined }) | | 230 | + else controller.signal.addEventListener("abort", () => resolve({ done: true, value: undefined }), { once: true }) | | 231 | + }) | 213 | 232 | while (!controller.signal.aborted) { | 214 | | - const next = await stream.next().catch((error) => { | 215 | | - if (!emittedError) throw error | | 233 | + const next = await Promise.race([stream.next(), aborted]).catch((error) => { | | 234 | + if (!emittedError && !interrupted) throw error | 216 | 235 | return { done: true as const, value: undefined } | 217 | 236 | }) | 218 | 237 | if (next.done) { | 219 | | - if (emittedError) return | | 238 | + if (emittedError || interrupted) return | 220 | 239 | throw new Error("Event stream disconnected during prompt execution") | 221 | 240 | } | 222 | 241 | const event = next.value | @@ -546,7 +565,10 @@ export async function runNonInteractivePrompt(input: Input) { | 546 | 565 | } | 547 | 566 | return | 548 | 567 | } | 549 | | - if (event.type === "session.execution.succeeded") return | | 568 | + if (event.type === "session.execution.succeeded") { | | 569 | + if (await pendingBackground()) continue | | 570 | + return | | 571 | + } | 550 | 572 | } | 551 | 573 | } | 552 | 574 |
| @@ -711,7 +733,14 @@ export async function runNonInteractivePrompt(input: Input) { | 711 | 733 | interrupted = true | 712 | 734 | process.exitCode = 130 | 713 | 735 | admission?.abort() | 714 | | - void input.client.session.interrupt({ sessionID: input.sessionID }).catch(() => {}) | | 736 | + void input.client.session | | 737 | + .interrupt({ sessionID: input.sessionID }) | | 738 | + .then((result) => { | | 739 | + if (!result.interrupted) controller.abort() | | 740 | + }) | | 741 | + .catch(() => { | | 742 | + controller.abort() | | 743 | + }) | 715 | 744 | } | 716 | 745 | process.on("SIGINT", interrupt) | 717 | 746 |
| @@ -790,7 +819,15 @@ export async function runNonInteractivePrompt(input: Input) { | 790 | 819 | return | 791 | 820 | } | 792 | 821 |
| 793 | | - const waiting = input.client.experimental.session.wait({ sessionID: input.sessionID }) | | 822 | + const waitUntilIdle = async () => { | | 823 | + await input.client.experimental.session.wait({ sessionID: input.sessionID }) | | 824 | + if (!(await pendingBackground())) return | | 825 | + await completed | | 826 | + if (!interrupted && !permissionRejected && !formCancelled && !emittedError) { | | 827 | + await input.client.experimental.session.wait({ sessionID: input.sessionID }) | | 828 | + } | | 829 | + } | | 830 | + const waiting = waitUntilIdle() | 794 | 831 | await Promise.race([waiting, completed.then(() => waiting)]) | 795 | 832 | finalizing = true | 796 | 833 | const projected = await reconcile() | |
Collapse file Copy file name to clipboardExpand all lines: packages/cli/test/run/noninteractive.test.ts +57-2Lines changed: 57 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,7 @@ 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 | 220 | 222 | terminalDelay?: number | 221 | 223 | }) { | 222 | 224 | const sdk = OpenCode.make({ baseUrl: "https://opencode.test" }) | @@ -254,6 +256,9 @@ async function run(input: { | 254 | 256 | spyOn(sdk.session.form, "cancel").mockImplementation((request) => (input.cancel?.(request) ?? ok(undefined)) as never) | 255 | 257 | let promptID = "msg_prompt" | 256 | 258 | spyOn(sdk.experimental.session, "wait").mockImplementation(() => input.wait?.() ?? wait.promise) | | 259 | + spyOn(sdk.experimental.job, "list").mockImplementation(() => ok(input.jobs?.() ?? []) as never) | | 260 | + spyOn(sdk.session, "active").mockImplementation(() => ok({}) as never) | | 261 | + spyOn(sdk.session.inbox, "list").mockImplementation(() => ok([]) as never) | 257 | 262 | spyOn(sdk.message, "list").mockImplementation(() => | 258 | 263 | ok({ | 259 | 264 | data: input.messages?.(promptID) ?? [{ id: promptID, type: "user", text: "hello", time: { created: 1 } }], | @@ -312,6 +317,21 @@ afterEach(() => { | 312 | 317 | process.exitCode = 0 | 313 | 318 | }) | 314 | 319 |
| | 320 | +function shellJob(id: string, command: string): ExperimentalJobListOutput[number] { | | 321 | + return { kind: "shell", id, sessionID: "ses_1", status: "running", shellID: id, command, time: { started: 1 } } | | 322 | +} | | 323 | + | | 324 | +const subagentJob: ExperimentalJobListOutput[number] = { | | 325 | + kind: "subagent", | | 326 | + id: "ses_child", | | 327 | + sessionID: "ses_1", | | 328 | + status: "running", | | 329 | + childSessionID: "ses_child", | | 330 | + agent: "explore", | | 331 | + description: "scan repo", | | 332 | + time: { started: 1 }, | | 333 | +} | | 334 | + | 315 | 335 | describe("runNonInteractivePrompt", () => { | 316 | 336 | test("keeps formatted tool output and compact tool metadata in JSON", async () => { | 317 | 337 | const output = await capture({ format: "json", turn: successfulGrep }) | @@ -474,7 +494,10 @@ describe("runNonInteractivePrompt", () => { | 474 | 494 | } | 475 | 495 | expect(sdk.session.form.cancel).toHaveBeenCalledWith({ sessionID: "global", formID: "frm_live" }, globalOptions) | 476 | 496 | 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) | | 497 | + expect(sdk.session.form.cancel).toHaveBeenCalledWith( | | 498 | + { sessionID: "global", formID: "frm_pending_global" }, | | 499 | + globalOptions, | | 500 | + ) | 478 | 501 | expect(sdk.form.list).toHaveBeenCalledWith({ | 479 | 502 | location: { directory: "/work tree" }, | 480 | 503 | }) | @@ -489,7 +512,10 @@ describe("runNonInteractivePrompt", () => { | 489 | 512 | }) | 490 | 513 | expect(sdk.session.form.cancel).toHaveBeenCalledWith({ sessionID: "ses_1", formID: "frm_pending" }) | 491 | 514 | expect(sdk.form.list).not.toHaveBeenCalled() | 492 | | - expect(sdk.session.form.cancel).not.toHaveBeenCalledWith({ sessionID: "global", formID: "frm_live" }, expect.anything()) | | 515 | + expect(sdk.session.form.cancel).not.toHaveBeenCalledWith( | | 516 | + { sessionID: "global", formID: "frm_live" }, | | 517 | + expect.anything(), | | 518 | + ) | 493 | 519 | expect(sdk.session.form.cancel).not.toHaveBeenCalledWith( | 494 | 520 | { sessionID: "global", formID: "frm_pending_global" }, | 495 | 521 | expect.anything(), | @@ -618,4 +644,33 @@ describe("runNonInteractivePrompt", () => { | 618 | 644 | expect(events[0].part.state.metadata.content).toBeUndefined() | 619 | 645 | expect(output.stderr).toBe("") | 620 | 646 | }) | | 647 | + | | 648 | + test("waits for a background shell and streams the reply it wakes", async () => { | | 649 | + const lists: ExperimentalJobListOutput[] = [[shellJob("sh_train", "python train.py")], []] | | 650 | + const output = await capture({ | | 651 | + format: "json", | | 652 | + jobs: () => lists.shift() ?? [], | | 653 | + turn: (id) => [ | | 654 | + prompted(id), | | 655 | + settled(), | | 656 | + { | | 657 | + id: "evt_text", | | 658 | + created: 2, | | 659 | + type: "session.text.ended", | | 660 | + durable: { aggregateID: "ses_1", seq: 2, version: 1 }, | | 661 | + data: { sessionID: "ses_1", assistantMessageID: "msg_2", ordinal: 0, text: "Training finished." }, | | 662 | + }, | | 663 | + settled(), | | 664 | + ], | | 665 | + }) | | 666 | + expect(output.stdout).toContain("Training finished.") | | 667 | + }) | | 668 | + | | 669 | + test("Ctrl-C while waiting on a background subagent exits with code 130", async () => { | | 670 | + const running = run({ turn: (id) => [prompted(id), settled()], jobs: () => [subagentJob] }) | | 671 | + expect(await Promise.race([running.then(() => "exited"), Bun.sleep(20).then(() => "waiting")])).toBe("waiting") | | 672 | + process.emit("SIGINT") | | 673 | + await running | | 674 | + expect(process.exitCode).toBe(130) | | 675 | + }) | 621 | 676 | }) |
|