GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(cli): wait for background jobs in opencode run · anomalyco/opencode@b706e45

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • packages/cli
    • src/run
      • noninteractive.ts
    • test/run
      • noninteractive.test.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎packages/cli/src/run/noninteractive.ts‎

Copy file name to clipboardExpand all lines: packages/cli/src/run/noninteractive.ts
+43-6Lines changed: 43 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,21 @@ export async function runNonInteractivePrompt(input: Input) {
158158
return result
159159
}
160160

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+
161176
const replyPermission = async (request: {
162177
id: string
163178
sessionID: string
@@ -210,13 +225,17 @@ export async function runNonInteractivePrompt(input: Input) {
210225
}
211226

212227
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+
})
213232
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
216235
return { done: true as const, value: undefined }
217236
})
218237
if (next.done) {
219-
if (emittedError) return
238+
if (emittedError || interrupted) return
220239
throw new Error("Event stream disconnected during prompt execution")
221240
}
222241
const event = next.value
@@ -546,7 +565,10 @@ export async function runNonInteractivePrompt(input: Input) {
546565
}
547566
return
548567
}
549-
if (event.type === "session.execution.succeeded") return
568+
if (event.type === "session.execution.succeeded") {
569+
if (await pendingBackground()) continue
570+
return
571+
}
550572
}
551573
}
552574

@@ -711,7 +733,14 @@ export async function runNonInteractivePrompt(input: Input) {
711733
interrupted = true
712734
process.exitCode = 130
713735
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+
})
715744
}
716745
process.on("SIGINT", interrupt)
717746

@@ -790,7 +819,15 @@ export async function runNonInteractivePrompt(input: Input) {
790819
return
791820
}
792821

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()
794831
await Promise.race([waiting, completed.then(() => waiting)])
795832
finalizing = true
796833
const projected = await reconcile()
Collapse file

‎packages/cli/test/run/noninteractive.test.ts‎

Copy file name to clipboardExpand all lines: packages/cli/test/run/noninteractive.test.ts
+57-2Lines changed: 57 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, mock, spyOn, test } from "bun:test"
22
import {
33
OpenCode,
44
type EventSubscribeOutput,
5+
type ExperimentalJobListOutput,
56
type SessionMessageAssistantTool,
67
type SessionMessageInfo,
78
} from "@opencode/client/promise"
@@ -217,6 +218,7 @@ async function run(input: {
217218
renderToolError?: (part: SessionMessageAssistantTool) => Promise<void>
218219
messages?: (inboxID: string) => SessionMessageInfo[]
219220
wait?: () => Promise<void>
221+
jobs?: () => ExperimentalJobListOutput
220222
terminalDelay?: number
221223
}) {
222224
const sdk = OpenCode.make({ baseUrl: "https://opencode.test" })
@@ -254,6 +256,9 @@ async function run(input: {
254256
spyOn(sdk.session.form, "cancel").mockImplementation((request) => (input.cancel?.(request) ?? ok(undefined)) as never)
255257
let promptID = "msg_prompt"
256258
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)
257262
spyOn(sdk.message, "list").mockImplementation(() =>
258263
ok({
259264
data: input.messages?.(promptID) ?? [{ id: promptID, type: "user", text: "hello", time: { created: 1 } }],
@@ -312,6 +317,21 @@ afterEach(() => {
312317
process.exitCode = 0
313318
})
314319

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+
315335
describe("runNonInteractivePrompt", () => {
316336
test("keeps formatted tool output and compact tool metadata in JSON", async () => {
317337
const output = await capture({ format: "json", turn: successfulGrep })
@@ -474,7 +494,10 @@ describe("runNonInteractivePrompt", () => {
474494
}
475495
expect(sdk.session.form.cancel).toHaveBeenCalledWith({ sessionID: "global", formID: "frm_live" }, globalOptions)
476496
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+
)
478501
expect(sdk.form.list).toHaveBeenCalledWith({
479502
location: { directory: "/work tree" },
480503
})
@@ -489,7 +512,10 @@ describe("runNonInteractivePrompt", () => {
489512
})
490513
expect(sdk.session.form.cancel).toHaveBeenCalledWith({ sessionID: "ses_1", formID: "frm_pending" })
491514
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+
)
493519
expect(sdk.session.form.cancel).not.toHaveBeenCalledWith(
494520
{ sessionID: "global", formID: "frm_pending_global" },
495521
expect.anything(),
@@ -618,4 +644,33 @@ describe("runNonInteractivePrompt", () => {
618644
expect(events[0].part.state.metadata.content).toBeUndefined()
619645
expect(output.stderr).toBe("")
620646
})
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+
})
621676
})

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.