Skip to content

Commit 63a2f6f

Browse files
agustifivanmilevtues
authored andcommitted
fix: address restart approval review feedback
- Release pending intents: CLI posts cancel on timeout and disconnect so connected TUIs never stay stuck on a dead request. - Resolve only broadcasts on a fresh settlement; late resolvers replay the winner without re-emitting, and nothing pending returns 400. - Subscribe to the resolved event before requesting an intent in both the CLI and the TUI, so a fast decision cannot be missed. - Exclude the requesting session from the idle wait; it blocks on this command and could never drain. - Keep the --force hint out of the non-interactive path so a blocked agent is not handed its own bypass. (cherry picked from commit 80b3628) Co-authored-by: Ivan Milev <ivanmilevtues@gmail.com>
1 parent 8d33e45 commit 63a2f6f

8 files changed

Lines changed: 467 additions & 288 deletions

File tree

‎packages/cli/src/commands/handlers/service/restart.ts‎

Lines changed: 103 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import { select } from "@clack/prompts"
2-
import { EOL } from "os"
2+
import { EOL } from "node:os"
33
import { Effect } from "effect"
44
import { Service } from "@opencode/client/effect/service"
5-
import { OpenCode, type OpenCodeClient } from "@opencode/client/promise"
5+
import { OpenCode, isInvalidRequestError, type OpenCodeClient } from "@opencode/client/promise"
66
import { Commands } from "../../commands"
77
import { Runtime } from "../../../framework/runtime"
88
import { ServiceConfig } from "../../../services/service-config"
@@ -39,16 +39,18 @@ export type RestartApprovalDecision = "now" | "idle" | "cancel"
3939
export type RestartApprovalDeps = {
4040
readonly force: boolean
4141
readonly interactive: boolean
42-
readonly ask: (active: ReadonlyArray<string>) => Effect.Effect<RestartApprovalDecision, unknown>
42+
readonly ask: (active: ReadonlyArray<string>) => Effect.Effect<RestartApprovalDecision, unknown, never>
4343
readonly resolveTimeoutMs: number
4444
readonly idlePollMs: number
4545
readonly onWaiting: (active: ReadonlyArray<string>) => void
4646
}
4747

48-
// Approval gate for restarting a managed server with running sessions. Resolves to the winning
49-
// decision ("now" when nothing needs approval); "cancel" and approval timeouts fail instead of
50-
// restarting. The server counts the first resolve as the winner, so a local pick is adopted
51-
// from the resolve response rather than trusted blindly.
48+
// Approval gate for restarting a managed server with running sessions. The event
49+
// subscription starts before the intent request so a resolution cannot slip
50+
// through between them; only decisions recorded after the request count.
51+
// Resolves to the winning decision ("now" when nothing needs approval); "cancel"
52+
// and approval timeouts fail instead of restarting. A local pick is adopted from
53+
// the resolve response, falling back to the broadcast winner on a lost race.
5254
export const resolveRestartApproval = Effect.fn("cli.service.restart.approval")(function* (
5355
client: OpenCodeClient,
5456
deps: RestartApprovalDeps,
@@ -60,67 +62,94 @@ export const resolveRestartApproval = Effect.fn("cli.service.restart.approval")(
6062
const ids = Object.keys(active)
6163
if (ids.length === 0) return "now"
6264
if (deps.force) return "now"
63-
yield* Effect.tryPromise({
64-
try: () => client.server.restart.request(),
65-
catch: (cause) => new Error("Could not reach server to request restart approval", { cause }),
65+
const watcher = watchResolved(client)
66+
const approval = Effect.gen(function* () {
67+
yield* Effect.tryPromise({
68+
try: () => client.server.restart.request(),
69+
catch: (cause) => new Error("Could not reach server to request restart approval", { cause }),
70+
})
71+
watcher.arm()
72+
const winner = deps.interactive
73+
? yield* resolveInteractive(client, deps, watcher, ids)
74+
: yield* resolveRemote(client, deps, watcher)
75+
if (winner === "cancel") return yield* Effect.fail(restartAborted(ids, deps.interactive))
76+
if (winner === "idle") yield* waitForIdle(client, deps)
77+
return winner
6678
})
67-
const winner = deps.interactive ? yield* resolveInteractive(client, deps, ids) : yield* resolveRemote(client, deps)
68-
if (winner === "cancel") return yield* Effect.fail(restartAborted(ids))
69-
if (winner === "idle") yield* waitForIdle(client, deps, ids)
70-
return winner
79+
return yield* approval.pipe(Effect.ensuring(Effect.sync(() => watcher.dispose())))
7180
})
7281

7382
const resolveInteractive = Effect.fn("cli.service.restart.approval.interactive")(function* (
7483
client: OpenCodeClient,
7584
deps: RestartApprovalDeps,
85+
watcher: ResolvedWatcher,
7686
active: ReadonlyArray<string>,
7787
) {
7888
const picked = yield* deps.ask(active)
79-
const resolved = yield* Effect.tryPromise({
89+
return yield* Effect.tryPromise({
90+
// Pass the rejection through unchanged so catchIf can read its `_tag`.
8091
try: () => client.server.restart.resolve({ decision: picked }),
81-
catch: (cause) => new Error("Could not reach server to resolve restart approval", { cause }),
82-
})
83-
return resolved.decision
92+
catch: (cause) => cause,
93+
}).pipe(
94+
Effect.map((resolved) => resolved.decision),
95+
// Another surface won the race; adopt the broadcast winner instead.
96+
Effect.catchIf(isInvalidRequestError, () => awaitWinner(client, watcher, deps)),
97+
Effect.mapError((cause) => new Error("Could not reach server to resolve restart approval", { cause })),
98+
)
8499
})
85100

86101
const resolveRemote = Effect.fn("cli.service.restart.approval.remote")(function* (
87102
client: OpenCodeClient,
88103
deps: RestartApprovalDeps,
104+
watcher: ResolvedWatcher,
105+
) {
106+
return yield* awaitWinner(client, watcher, deps)
107+
})
108+
109+
const awaitWinner = Effect.fn("cli.service.restart.approval.wait")(function* (
110+
client: OpenCodeClient,
111+
watcher: ResolvedWatcher,
112+
deps: RestartApprovalDeps,
89113
) {
90114
return yield* Effect.tryPromise({
91-
try: () => waitForResolvedEvent(client, deps.resolveTimeoutMs),
115+
try: () => watcher.wait(deps.resolveTimeoutMs),
92116
catch: (cause) =>
93117
cause instanceof RestartApprovalTimeout
94-
? new Error(
95-
"Timed out waiting for restart approval; no connected client approved the restart. Re-run with --force to restart immediately.",
96-
)
118+
? new Error("Timed out waiting for restart approval with sessions still running.")
97119
: new Error("Lost connection to the server while waiting for restart approval", { cause }),
98-
})
120+
}).pipe(
121+
Effect.tapError(() =>
122+
// Release TUIs stuck on our intent; a settled intent replays its winner.
123+
Effect.tryPromise(() => client.server.restart.resolve({ decision: "cancel" })).pipe(Effect.ignore),
124+
),
125+
)
99126
})
100127

128+
// The requesting session blocks on this command, so it can never go idle while
129+
// watched. Exclude it from the drain set; approval itself still required it.
101130
const waitForIdle = Effect.fn("cli.service.restart.approval.idle")(function* (
102131
client: OpenCodeClient,
103132
deps: RestartApprovalDeps,
104-
initial: ReadonlyArray<string>,
105133
) {
106-
deps.onWaiting(initial)
107134
while (true) {
108135
yield* Effect.sleep(deps.idlePollMs)
109136
const active = yield* Effect.tryPromise({
110137
try: () => client.session.active(),
111138
catch: (cause) =>
112139
new Error("Lost connection to the server while waiting for sessions to finish", { cause }),
113140
})
114-
const ids = Object.keys(active)
141+
const ids = Object.keys(active).filter((id) => id !== process.env.OPENCODE_SESSION_ID)
115142
if (ids.length === 0) return
116143
deps.onWaiting(ids)
117144
}
118145
})
119146

120-
function restartAborted(active: ReadonlyArray<string>) {
121-
return new Error(
122-
`Restart cancelled with ${active.length} active session(s); re-run with --force to restart immediately.`,
123-
)
147+
function restartAborted(active: ReadonlyArray<string>, interactive: boolean) {
148+
return interactive
149+
? new Error(
150+
`Restart cancelled with ${active.length} active session(s); re-run with --force to restart immediately.`,
151+
)
152+
: new Error("Restart cancelled with active session(s) still running.")
124153
}
125154

126155
class RestartApprovalTimeout extends Error {
@@ -130,31 +159,58 @@ class RestartApprovalTimeout extends Error {
130159
}
131160
}
132161

133-
function waitForResolvedEvent(client: OpenCodeClient, timeoutMs: number): Promise<RestartApprovalDecision> {
134-
return (async () => {
135-
const controller = new AbortController()
136-
let timedOut = false
137-
const timer = setTimeout(() => {
138-
timedOut = true
139-
controller.abort()
140-
}, timeoutMs)
162+
export type ResolvedWatcher = {
163+
readonly arm: () => void
164+
readonly wait: (timeoutMs: number) => Promise<RestartApprovalDecision>
165+
readonly dispose: () => void
166+
}
167+
168+
export function watchResolved(client: OpenCodeClient): ResolvedWatcher {
169+
const controller = new AbortController()
170+
let armed = false
171+
let pending: RestartApprovalDecision | undefined
172+
let settle: ((decision: RestartApprovalDecision) => void) | undefined
173+
let failure: unknown | undefined
174+
const fail = (cause: unknown) => {
175+
failure ??= cause
176+
settle = undefined
177+
}
178+
void (async () => {
141179
try {
142180
const stream = client.event.subscribe({ signal: controller.signal })[Symbol.asyncIterator]()
143-
while (true) {
181+
for (;;) {
144182
const next = await stream.next()
145183
if (next.done) break
146-
if (next.value.type === "server.restart.resolved") return next.value.data.decision
184+
if (armed && next.value.type === "server.restart.resolved") {
185+
const decision = next.value.data.decision
186+
pending ??= decision
187+
settle?.(decision)
188+
}
147189
}
148-
if (timedOut) throw new RestartApprovalTimeout()
149-
throw new Error("Event stream disconnected while waiting for restart approval")
190+
fail(new Error("Event stream disconnected while waiting for restart approval"))
150191
} catch (cause) {
151-
if (timedOut) throw new RestartApprovalTimeout()
152-
throw cause
153-
} finally {
154-
clearTimeout(timer)
155-
controller.abort()
192+
fail(cause)
156193
}
157194
})()
195+
return {
196+
arm() {
197+
armed = true
198+
},
199+
wait(timeoutMs: number) {
200+
return new Promise<RestartApprovalDecision>((resolve, reject) => {
201+
if (pending !== undefined) return resolve(pending)
202+
if (failure !== undefined) return reject(failure)
203+
const timer = setTimeout(() => reject(new RestartApprovalTimeout()), timeoutMs)
204+
settle = (decision) => {
205+
clearTimeout(timer)
206+
resolve(decision)
207+
}
208+
})
209+
},
210+
dispose() {
211+
controller.abort()
212+
},
213+
}
158214
}
159215

160216
const askRestartDecision = (active: ReadonlyArray<string>) =>

0 commit comments

Comments
 (0)