Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 13 additions & 29 deletions packages/opencode/src/cli/cmd/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { pathToFileURL } from "url"
import { open } from "node:fs/promises"
import { Effect } from "effect"
import { BackgroundTasks } from "./run/background-tasks"
import { RetryNotice } from "./run/retry-notice"
import { UI } from "../ui"
import { effectCmd } from "../effect-cmd"
import { EOL } from "os"
Expand Down Expand Up @@ -742,8 +743,14 @@ export const RunCommand = effectCmd({
let rootIdle = false
let lastText = ""
let error: string | undefined
// Last announced retry attempt per session (root and owned background children).
const retryNoticed = new Map<string, number>()
// Announces long retry waits of the root and of owned background children (#555).
const retryNotice = RetryNotice.make({
rootSessionID: sessionID,
owns: background.owns,
print: (line) => UI.println(line),
threshold: RUN_RETRY_NOTICE_MS,
json: args.format === "json",
})

for await (const event of events.stream) {
if (
Expand Down Expand Up @@ -783,6 +790,7 @@ export const RunCommand = effectCmd({
? part.state.metadata.runId
: undefined
background.launch({ sessionID: taskID!, parentSessionID: part.sessionID, run, launchID: part.id })
retryNotice.launched()
}
}
if (part.type === "text") {
Expand Down Expand Up @@ -870,34 +878,10 @@ export const RunCommand = effectCmd({
UI.error(err)
}

if (event.type === "session.status" && background.owns(event.properties.sessionID)) {
if (event.type === "session.status") {
const statusSession = event.properties.sessionID
const isRoot = statusSession === sessionID
if (isRoot) rootIdle = event.properties.status.type === "idle"
const status = event.properties.status
// Visibility only: a long provider-requested retry delay used to leave a
// headless run silent until killed (#555). Say that it is waiting, without
// changing the retry policy. Short retries stay silent.
// A later non-retry status (busy again after a successful step) ends the
// wait, so the next wait in the same run is announced too.
if (status.type !== "retry") retryNoticed.delete(statusSession)
if (status.type === "retry" && args.format !== "json") {
const wait = status.next - Date.now()
if (wait > RUN_RETRY_NOTICE_MS && status.attempt !== retryNoticed.get(statusSession)) {
retryNoticed.set(statusSession, status.attempt)
// A fixed category, never the provider's retry message: that text can carry raw
// response bodies, URLs or control characters.
const reason =
status.action?.reason === "free_tier_limit"
? "free usage limit reached"
: status.action?.reason === "account_rate_limit"
? "account rate limit"
: "retrying after a provider error"
UI.println(
`${isRoot ? "" : "subagent "}waiting about ${Math.ceil(wait / 1000)}s before retrying (attempt ${status.attempt}): ${reason}`,
)
}
}
if (statusSession === sessionID) rootIdle = event.properties.status.type === "idle"
retryNotice.status(statusSession, event.properties.status)
}
// A deferred/silent descendant delivery can arrive after the root's
// last idle event. Recheck on every event, not only another root
Expand Down
73 changes: 73 additions & 0 deletions packages/opencode/src/cli/cmd/run/retry-notice.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/** Visibility only (#555): a long provider-requested retry wait used to leave a headless run silent.
* Announces the wait without touching the retry policy. A child can report its wait before its launch
* reaches the run loop, so the latest retry status of a not-yet-owned session is held and announced once
* the launch ties that session to the run.
*/
export type RetryStatus = { type: string; attempt?: number; next?: number; action?: { reason?: string } }

export const make = (input: {
rootSessionID: string
owns: (sessionID: string) => boolean
print: (line: string) => void
threshold: number
json: boolean
now?: () => number
}) => {
const now = input.now ?? Date.now
const noticed = new Map<string, number>()
// Retry statuses of sessions not (yet) owned. Bounded: a run only ever needs the few children whose launch
// is still on its way, so the oldest entries are dropped past the cap and expired waits are pruned.
const held = new Map<string, RetryStatus>()
const HELD_CAP = 32

const notice = (sessionID: string, status: RetryStatus) => {
if (status.type !== "retry") {
noticed.delete(sessionID)
return
}
if (input.json) return
const wait = (status.next ?? 0) - now()
if (wait <= input.threshold || status.attempt === noticed.get(sessionID)) return
noticed.set(sessionID, status.attempt ?? 0)
// A fixed category, never the provider's retry message: that text can carry raw
// response bodies, URLs or control characters.
const reason =
status.action?.reason === "free_tier_limit"
? "free usage limit reached"
: status.action?.reason === "account_rate_limit"
? "account rate limit"
: "retrying after a provider error"
input.print(
`${sessionID === input.rootSessionID ? "" : "subagent "}waiting about ${Math.ceil(wait / 1000)}s before retrying (attempt ${status.attempt}): ${reason}`,
)
}

return {
/** Feed every session.status event. */
status(sessionID: string, status: RetryStatus) {
if (input.owns(sessionID)) {
held.delete(sessionID)
notice(sessionID, status)
} else if (status.type === "retry" && !input.json) {
held.delete(sessionID)
held.set(sessionID, status)
for (const key of held.keys()) {
if (held.size <= HELD_CAP) break
held.delete(key)
}
} else held.delete(sessionID)
},
/** Call after a launch was recorded: announces held waits of sessions that are now owned. */
launched() {
for (const [sessionID, status] of held) {
// An ended wait can never be announced, owned or not.
if ((status.next ?? 0) <= now()) held.delete(sessionID)
if (!input.owns(sessionID)) continue
if (!held.delete(sessionID)) continue
notice(sessionID, status)
}
},
}
}

export * as RetryNotice from "./retry-notice"
89 changes: 89 additions & 0 deletions packages/opencode/test/cli/run/retry-notice.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import { describe, expect, test } from "bun:test"
import { BackgroundTasks } from "../../../src/cli/cmd/run/background-tasks"
import { RetryNotice } from "../../../src/cli/cmd/run/retry-notice"

// #555: a child's retry wait can arrive before the launch that ties the child to the run.
const setup = (json = false) => {
const lines: string[] = []
const background = BackgroundTasks.make("root")
const notice = RetryNotice.make({
rootSessionID: "root",
owns: background.owns,
print: (line) => lines.push(line),
threshold: 10_000,
json,
now: () => 1_000,
})
const retry = (attempt: number, ms = 12_000) => ({
type: "retry",
attempt,
next: 1_000 + ms,
action: { reason: "free_tier_limit" },
})
return { lines, background, notice, retry }
}

describe("retry wait notice ordering (#555)", () => {
test("a child wait seen before its launch is announced once the launch is observed", () => {
const { lines, background, notice, retry } = setup()
notice.status("child", retry(1))
expect(lines).toEqual([])
background.launch({ sessionID: "child", parentSessionID: "root", run: "r1", launchID: "p1" })
notice.launched()
expect(lines).toEqual(["subagent waiting about 12s before retrying (attempt 1): free usage limit reached"])
notice.launched()
expect(lines.length).toBe(1)
})

test("a held wait that ended before the launch is not announced", () => {
const { lines, background, notice, retry } = setup()
notice.status("child", retry(1))
notice.status("child", { type: "busy" })
background.launch({ sessionID: "child", parentSessionID: "root", run: "r1", launchID: "p1" })
notice.launched()
expect(lines).toEqual([])
})

test("only the latest held attempt is announced, and unrelated sessions never are", () => {
const { lines, background, notice, retry } = setup()
notice.status("child", retry(1))
notice.status("child", retry(2))
notice.status("stranger", retry(1))
background.launch({ sessionID: "child", parentSessionID: "root", run: "r1", launchID: "p1" })
notice.launched()
expect(lines).toEqual(["subagent waiting about 12s before retrying (attempt 2): free usage limit reached"])
})

test("short waits, JSON output and the root keep their existing behavior", () => {
const short = setup()
short.notice.status("root", short.retry(1, 5_000))
expect(short.lines).toEqual([])
const json = setup(true)
json.notice.status("root", json.retry(1))
expect(json.lines).toEqual([])
const root = setup()
root.notice.status("root", root.retry(1))
root.notice.status("root", root.retry(1))
expect(root.lines).toEqual(["waiting about 12s before retrying (attempt 1): free usage limit reached"])
})

test("the held map is capped, JSON mode holds nothing, and ended waits are pruned", () => {
const { lines, background, notice, retry } = setup()
for (let i = 0; i < 100; i++) notice.status(`s${i}`, retry(1))
// The oldest entries were dropped; the newest still replays after its launch.
background.launch({ sessionID: "s0", parentSessionID: "root", run: "r0", launchID: "p0" })
background.launch({ sessionID: "s99", parentSessionID: "root", run: "r99", launchID: "p99" })
notice.launched()
expect(lines).toEqual(["subagent waiting about 12s before retrying (attempt 1): free usage limit reached"])
const json = setup(true)
json.notice.status("child", json.retry(1))
json.background.launch({ sessionID: "child", parentSessionID: "root", run: "r1", launchID: "p1" })
json.notice.launched()
expect(json.lines).toEqual([])
const ended = setup()
ended.notice.status("child", ended.retry(1, -1))
ended.background.launch({ sessionID: "child", parentSessionID: "root", run: "r1", launchID: "p1" })
ended.notice.launched()
expect(ended.lines).toEqual([])
})
})
Loading