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@1feba95

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
+64-7Lines changed: 64 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@ type Input = {
3939
/** True when the client is attached to a shared server rather than an exclusive in-process one. */
4040
attached: boolean
4141
compatibility?: "v1"
42+
/** How long running background shells keep the run open after the model's last reply. */
43+
backgroundShellWait?: number
4244
renderTool: (part: SessionMessageAssistantTool) => Promise<void>
4345
renderToolError: (part: SessionMessageAssistantTool) => Promise<void>
4446
}
@@ -70,6 +72,10 @@ const GLOBAL_FORM_SESSION_ID = "global"
7072
const QUESTION_CANCELLED_FEEDBACK =
7173
"This non-interactive run cannot ask the user questions, so the question was cancelled. Continue without an answer; make reasonable assumptions and state them."
7274

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+
7379
const PERMISSION_REJECTED_FEEDBACK =
7480
"This non-interactive run cannot ask the user for permission, so the request was rejected. Continue without this action."
7581

@@ -97,6 +103,8 @@ export async function runNonInteractivePrompt(input: Input) {
97103
let v1InvalidOutput = false
98104
let prePromotionError: { message: string; [key: string]: unknown } | undefined
99105
let finalizing = false
106+
let shellWait: ReturnType<typeof setTimeout> | undefined
107+
let shellWaitExpired = false
100108
let admission: AbortController | undefined
101109
let pendingStep: { timestamp: number; part: Record<string, unknown>; label: string } | undefined
102110

@@ -158,6 +166,23 @@ export async function runNonInteractivePrompt(input: Input) {
158166
return result
159167
}
160168

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+
161186
const replyPermission = async (request: {
162187
id: string
163188
sessionID: string
@@ -209,14 +234,20 @@ export async function runNonInteractivePrompt(input: Input) {
209234
if (input.compatibility !== "v1") process.exitCode = 1
210235
}
211236

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+
})
213244
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
216247
return { done: true as const, value: undefined }
217248
})
218249
if (next.done) {
219-
if (emittedError) return
250+
if (emittedError || interrupted || shellWaitExpired) return
220251
throw new Error("Event stream disconnected during prompt execution")
221252
}
222253
const event = next.value
@@ -546,7 +577,18 @@ export async function runNonInteractivePrompt(input: Input) {
546577
}
547578
return
548579
}
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+
}
550592
}
551593
}
552594

@@ -711,7 +753,14 @@ export async function runNonInteractivePrompt(input: Input) {
711753
interrupted = true
712754
process.exitCode = 130
713755
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+
})
715764
}
716765
process.on("SIGINT", interrupt)
717766

@@ -790,7 +839,15 @@ export async function runNonInteractivePrompt(input: Input) {
790839
return
791840
}
792841

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()
794851
await Promise.race([waiting, completed.then(() => waiting)])
795852
finalizing = true
796853
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
+68-2Lines changed: 68 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,8 @@ async function run(input: {
217218
renderToolError?: (part: SessionMessageAssistantTool) => Promise<void>
218219
messages?: (inboxID: string) => SessionMessageInfo[]
219220
wait?: () => Promise<void>
221+
jobs?: () => ExperimentalJobListOutput
222+
backgroundShellWait?: number
220223
terminalDelay?: number
221224
}) {
222225
const sdk = OpenCode.make({ baseUrl: "https://opencode.test" })
@@ -254,6 +257,9 @@ async function run(input: {
254257
spyOn(sdk.session.form, "cancel").mockImplementation((request) => (input.cancel?.(request) ?? ok(undefined)) as never)
255258
let promptID = "msg_prompt"
256259
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)
257263
spyOn(sdk.message, "list").mockImplementation(() =>
258264
ok({
259265
data: input.messages?.(promptID) ?? [{ id: promptID, type: "user", text: "hello", time: { created: 1 } }],
@@ -279,6 +285,7 @@ async function run(input: {
279285
auto: false,
280286
attached: input.attached ?? false,
281287
compatibility: input.compatibility,
288+
backgroundShellWait: input.backgroundShellWait,
282289
renderTool: input.renderTool ?? (() => Promise.resolve()),
283290
renderToolError: input.renderToolError ?? (() => Promise.resolve()),
284291
})
@@ -312,6 +319,21 @@ afterEach(() => {
312319
process.exitCode = 0
313320
})
314321

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+
315337
describe("runNonInteractivePrompt", () => {
316338
test("keeps formatted tool output and compact tool metadata in JSON", async () => {
317339
const output = await capture({ format: "json", turn: successfulGrep })
@@ -474,7 +496,10 @@ describe("runNonInteractivePrompt", () => {
474496
}
475497
expect(sdk.session.form.cancel).toHaveBeenCalledWith({ sessionID: "global", formID: "frm_live" }, globalOptions)
476498
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+
)
478503
expect(sdk.form.list).toHaveBeenCalledWith({
479504
location: { directory: "/work tree" },
480505
})
@@ -489,7 +514,10 @@ describe("runNonInteractivePrompt", () => {
489514
})
490515
expect(sdk.session.form.cancel).toHaveBeenCalledWith({ sessionID: "ses_1", formID: "frm_pending" })
491516
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+
)
493521
expect(sdk.session.form.cancel).not.toHaveBeenCalledWith(
494522
{ sessionID: "global", formID: "frm_pending_global" },
495523
expect.anything(),
@@ -618,4 +646,42 @@ describe("runNonInteractivePrompt", () => {
618646
expect(events[0].part.state.metadata.content).toBeUndefined()
619647
expect(output.stderr).toBe("")
620648
})
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+
})
621687
})

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.