Skip to content

Commit 17260d7

Browse files
agustifivanmilevtues
authored andcommitted
feat(cli): guard service restart with approval
(cherry picked from commit b68002d) Co-authored-by: Ivan Milev <ivanmilevtues@gmail.com>
1 parent c8de424 commit 17260d7

3 files changed

Lines changed: 403 additions & 2 deletions

File tree

‎packages/cli/src/commands/commands.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -472,7 +472,15 @@ const Root = Spec.make(typeof OPENCODE_CLI_NAME === "string" ? OPENCODE_CLI_NAME
472472
description: "Manage the background server",
473473
commands: [
474474
Spec.make("start", { description: "Start the background server" }),
475-
Spec.make("restart", { description: "Restart the background server" }),
475+
Spec.make("restart", {
476+
description: "Restart the background server",
477+
params: {
478+
force: Flag.Boolean("force").pipe(
479+
Flag.withDescription("Restart immediately without asking running sessions for approval"),
480+
Flag.withDefault(false),
481+
),
482+
},
483+
}),
476484
Spec.make("status", { description: "Show background server status" }),
477485
Spec.make("stop", { description: "Stop the background server" }),
478486
Spec.make("get", {
Lines changed: 152 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,170 @@
1+
import { select } from "@clack/prompts"
12
import { EOL } from "os"
23
import { Effect } from "effect"
34
import { Service } from "@opencode/client/effect/service"
5+
import { OpenCode, type OpenCodeClient } from "@opencode/client/promise"
46
import { Commands } from "../../commands"
57
import { Runtime } from "../../../framework/runtime"
68
import { ServiceConfig } from "../../../services/service-config"
79
import { ServerConnection } from "../../../services/server-connection"
10+
import { prompt } from "../../../ui/prompt"
811

912
export default Runtime.handler(
1013
Commands.commands.service.commands.restart,
11-
Effect.fn("cli.service.restart")(function* () {
14+
Effect.fn("cli.service.restart")(function* (input: Runtime.Input<typeof Commands.commands.service.commands.restart>) {
1215
const options = yield* ServiceConfig.options()
16+
const endpoint = yield* Service.discover(options)
17+
if (endpoint !== undefined && !input.force) {
18+
const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })
19+
yield* resolveRestartApproval(client, {
20+
force: input.force,
21+
interactive: process.stdin.isTTY === true && process.stdout.isTTY === true,
22+
ask: askRestartDecision,
23+
resolveTimeoutMs: 120_000,
24+
idlePollMs: 2_000,
25+
onWaiting: (active) =>
26+
process.stdout.write(`Waiting for ${active.length} active session(s) to finish...${EOL}`),
27+
})
28+
}
1329
// Keep this explicit: automatic service replacement must preserve terminals.
1430
yield* ServerConnection.shutdownPersistentPty(options).pipe(Effect.ignore)
1531
yield* Service.stop(options)
1632
const transport = yield* Service.ensure(options)
1733
process.stdout.write(transport.url + EOL)
1834
}),
1935
)
36+
37+
export type RestartApprovalDecision = "now" | "idle" | "cancel"
38+
39+
export type RestartApprovalDeps = {
40+
readonly force: boolean
41+
readonly interactive: boolean
42+
readonly ask: (active: ReadonlyArray<string>) => Effect.Effect<RestartApprovalDecision, unknown>
43+
readonly resolveTimeoutMs: number
44+
readonly idlePollMs: number
45+
readonly onWaiting: (active: ReadonlyArray<string>) => void
46+
}
47+
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.
52+
export const resolveRestartApproval = Effect.fn("cli.service.restart.approval")(function* (
53+
client: OpenCodeClient,
54+
deps: RestartApprovalDeps,
55+
) {
56+
const active = yield* Effect.tryPromise({
57+
try: () => client.session.active(),
58+
catch: (cause) => new Error("Could not reach server to check active sessions", { cause }),
59+
})
60+
const ids = Object.keys(active)
61+
if (ids.length === 0) return "now"
62+
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 }),
66+
})
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
71+
})
72+
73+
const resolveInteractive = Effect.fn("cli.service.restart.approval.interactive")(function* (
74+
client: OpenCodeClient,
75+
deps: RestartApprovalDeps,
76+
active: ReadonlyArray<string>,
77+
) {
78+
const picked = yield* deps.ask(active)
79+
const resolved = yield* Effect.tryPromise({
80+
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
84+
})
85+
86+
const resolveRemote = Effect.fn("cli.service.restart.approval.remote")(function* (
87+
client: OpenCodeClient,
88+
deps: RestartApprovalDeps,
89+
) {
90+
return yield* Effect.tryPromise({
91+
try: () => waitForResolvedEvent(client, deps.resolveTimeoutMs),
92+
catch: (cause) =>
93+
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+
)
97+
: new Error("Lost connection to the server while waiting for restart approval", { cause }),
98+
})
99+
})
100+
101+
const waitForIdle = Effect.fn("cli.service.restart.approval.idle")(function* (
102+
client: OpenCodeClient,
103+
deps: RestartApprovalDeps,
104+
initial: ReadonlyArray<string>,
105+
) {
106+
deps.onWaiting(initial)
107+
while (true) {
108+
yield* Effect.sleep(deps.idlePollMs)
109+
const active = yield* Effect.tryPromise({
110+
try: () => client.session.active(),
111+
catch: (cause) =>
112+
new Error("Lost connection to the server while waiting for sessions to finish", { cause }),
113+
})
114+
const ids = Object.keys(active)
115+
if (ids.length === 0) return
116+
deps.onWaiting(ids)
117+
}
118+
})
119+
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+
)
124+
}
125+
126+
class RestartApprovalTimeout extends Error {
127+
constructor() {
128+
super("restart approval timed out")
129+
this.name = "RestartApprovalTimeout"
130+
}
131+
}
132+
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)
141+
try {
142+
const stream = client.event.subscribe({ signal: controller.signal })[Symbol.asyncIterator]()
143+
while (true) {
144+
const next = await stream.next()
145+
if (next.done) break
146+
if (next.value.type === "server.restart.resolved") return next.value.data.decision
147+
}
148+
if (timedOut) throw new RestartApprovalTimeout()
149+
throw new Error("Event stream disconnected while waiting for restart approval")
150+
} catch (cause) {
151+
if (timedOut) throw new RestartApprovalTimeout()
152+
throw cause
153+
} finally {
154+
clearTimeout(timer)
155+
controller.abort()
156+
}
157+
})()
158+
}
159+
160+
const askRestartDecision = (active: ReadonlyArray<string>) =>
161+
prompt<RestartApprovalDecision>(() =>
162+
select<RestartApprovalDecision>({
163+
message: `${active.length} session(s) are still running. Restart the background server?`,
164+
options: [
165+
{ value: "now", label: "Restart now", hint: "Interrupt running sessions" },
166+
{ value: "idle", label: "Wait for idle", hint: "Restart when sessions finish" },
167+
{ value: "cancel", label: "Cancel", hint: "Keep the server running" },
168+
],
169+
}),
170+
)

0 commit comments

Comments
 (0)