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@4d3ad3a

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
+107-7Lines changed: 107 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 stops it and exits. 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+
const shellWaitMs = input.backgroundShellWait ?? BACKGROUND_SHELL_WAIT_MS
107+
let shellWait: { timer: ReturnType<typeof setTimeout>; expired: Promise<"expired"> } | undefined
100108
let admission: AbortController | undefined
101109
let pendingStep: { timestamp: number; part: Record<string, unknown>; label: string } | undefined
102110

@@ -158,6 +166,40 @@ 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+
186+
const stopShells = async () => {
187+
const shells = (await input.client.experimental.job.list({ sessionID: input.sessionID }).catch(() => [])).flatMap(
188+
(job) => (job.kind === "shell" && job.status === "running" ? [job.shellID] : []),
189+
)
190+
await Promise.all(
191+
shells.map((id) =>
192+
input.client.shell.remove({ id, location: { directory: input.location.directory } }).catch(() => {}),
193+
),
194+
)
195+
if (shells.length > 0 && input.format !== "json")
196+
UI.println(
197+
UI.Style.TEXT_WARNING_BOLD + "!",
198+
UI.Style.TEXT_NORMAL +
199+
`stopped ${shells.length} background command${shells.length === 1 ? "" : "s"} still running ${Math.round(shellWaitMs / 60_000)} minutes after the last reply`,
200+
)
201+
}
202+
161203
const replyPermission = async (request: {
162204
id: string
163205
sessionID: string
@@ -209,14 +251,32 @@ export async function runNonInteractivePrompt(input: Input) {
209251
if (input.compatibility !== "v1") process.exitCode = 1
210252
}
211253

212-
const consume = async () => {
254+
const consume = () => consumeEvents().finally(() => clearTimeout(shellWait?.timer))
255+
256+
const consumeEvents = async () => {
257+
const aborted = new Promise<{ done: true; value: undefined }>((resolve) => {
258+
if (controller.signal.aborted) resolve({ done: true, value: undefined })
259+
else controller.signal.addEventListener("abort", () => resolve({ done: true, value: undefined }), { once: true })
260+
})
261+
const never = new Promise<never>(() => {})
262+
// Kept across loop turns so an event read while the shell wait expires is not dropped.
263+
let pending: ReturnType<typeof stream.next> | undefined
213264
while (!controller.signal.aborted) {
214-
const next = await stream.next().catch((error) => {
215-
if (!emittedError) throw error
265+
pending ??= stream.next()
266+
const next = await Promise.race([pending, aborted, shellWait?.expired ?? never]).catch((error) => {
267+
if (!emittedError && !interrupted) throw error
216268
return { done: true as const, value: undefined }
217269
})
270+
if (next === "expired") {
271+
shellWait = undefined
272+
const background = await pendingBackground()
273+
if (background === "work") continue
274+
if (background === "shells") await stopShells()
275+
return
276+
}
277+
pending = undefined
218278
if (next.done) {
219-
if (emittedError) return
279+
if (emittedError || interrupted) return
220280
throw new Error("Event stream disconnected during prompt execution")
221281
}
222282
const event = next.value
@@ -546,7 +606,18 @@ export async function runNonInteractivePrompt(input: Input) {
546606
}
547607
return
548608
}
549-
if (event.type === "session.execution.succeeded") return
609+
if (event.type === "session.execution.succeeded") {
610+
const background = await pendingBackground()
611+
if (background === "none") return
612+
// Each reply restarts the wait; subagents and images hold the run until they report.
613+
clearTimeout(shellWait?.timer)
614+
shellWait = undefined
615+
if (background === "shells") {
616+
const { promise, resolve } = Promise.withResolvers<"expired">()
617+
shellWait = { timer: setTimeout(() => resolve("expired"), shellWaitMs), expired: promise }
618+
}
619+
continue
620+
}
550621
}
551622
}
552623

@@ -711,7 +782,28 @@ export async function runNonInteractivePrompt(input: Input) {
711782
interrupted = true
712783
process.exitCode = 130
713784
admission?.abort()
714-
void input.client.session.interrupt({ sessionID: input.sessionID }).catch(() => {})
785+
if (input.compatibility !== "v1") {
786+
void input.client.experimental.job
787+
.list({ sessionID: input.sessionID, descendants: true })
788+
.then((jobs) =>
789+
Promise.all(
790+
jobs.map((job) =>
791+
input.client.session
792+
.interrupt({ sessionID: job.kind === "subagent" ? job.childSessionID : job.sessionID })
793+
.catch(() => {}),
794+
),
795+
),
796+
)
797+
.catch(() => {})
798+
}
799+
void input.client.session
800+
.interrupt({ sessionID: input.sessionID })
801+
.then((result) => {
802+
if (!result.interrupted) controller.abort()
803+
})
804+
.catch(() => {
805+
controller.abort()
806+
})
715807
}
716808
process.on("SIGINT", interrupt)
717809

@@ -790,7 +882,15 @@ export async function runNonInteractivePrompt(input: Input) {
790882
return
791883
}
792884

793-
const waiting = input.client.experimental.session.wait({ sessionID: input.sessionID })
885+
const waitUntilIdle = async () => {
886+
await input.client.experimental.session.wait({ sessionID: input.sessionID })
887+
if ((await pendingBackground()) === "none") return
888+
await completed
889+
if (!interrupted && !permissionRejected && !formCancelled && !emittedError) {
890+
await input.client.experimental.session.wait({ sessionID: input.sessionID })
891+
}
892+
}
893+
const waiting = waitUntilIdle()
794894
await Promise.race([waiting, completed.then(() => waiting)])
795895
finalizing = true
796896
const projected = await reconcile()

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.