Skip to content

Commit 86379fc

Browse files
authored
Merge pull request #5 from ranxianglei/fix/run-grace-period-multi-bg
fix(run): grace period before exit for multi-background-agent race
2 parents 139f011 + beba94a commit 86379fc

1 file changed

Lines changed: 17 additions & 1 deletion

File tree

  • packages/opencode/src/cli/cmd

packages/opencode/src/cli/cmd/run.ts

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -454,6 +454,7 @@ export const RunCommand = effectCmd({
454454
// background (child) sessions are still running.
455455
const busy = new Set<string>()
456456
let mainIdle = false
457+
let graceTimer: ReturnType<typeof setTimeout> | undefined
457458

458459
for await (const event of events.stream) {
459460
if (
@@ -549,9 +550,23 @@ export const RunCommand = effectCmd({
549550
if (status.type === "idle") {
550551
busy.delete(sid)
551552
if (sid === sessionID) mainIdle = true
552-
if (mainIdle && busy.size === 0) resolveDone()
553553
} else {
554554
busy.add(sid)
555+
if (graceTimer) {
556+
clearTimeout(graceTimer)
557+
graceTimer = undefined
558+
}
559+
}
560+
// Don't resolve immediately when everything looks idle: background
561+
// sessions spawned near the main session's completion emit their
562+
// busy event asynchronously, so busy may be momentarily empty.
563+
// Wait a grace period; any session going busy during it cancels
564+
// the timer above so we keep waiting.
565+
if (mainIdle && busy.size === 0 && !graceTimer) {
566+
graceTimer = setTimeout(() => {
567+
if (mainIdle && busy.size === 0) resolveDone()
568+
}, 3000)
569+
graceTimer.unref?.()
555570
}
556571
}
557572

@@ -579,6 +594,7 @@ export const RunCommand = effectCmd({
579594
}
580595
// Stream closed (e.g. server shutdown) before the exit condition was
581596
// met — unblock execute() so it doesn't hang forever.
597+
if (graceTimer) clearTimeout(graceTimer)
582598
resolveDone()
583599
}
584600

0 commit comments

Comments
 (0)