|
| 1 | +import { select } from "@clack/prompts" |
1 | 2 | import { EOL } from "os" |
2 | 3 | import { Effect } from "effect" |
3 | 4 | import { Service } from "@opencode/client/effect/service" |
| 5 | +import { OpenCode, type OpenCodeClient } from "@opencode/client/promise" |
4 | 6 | import { Commands } from "../../commands" |
5 | 7 | import { Runtime } from "../../../framework/runtime" |
6 | 8 | import { ServiceConfig } from "../../../services/service-config" |
7 | 9 | import { ServerConnection } from "../../../services/server-connection" |
| 10 | +import { prompt } from "../../../ui/prompt" |
8 | 11 |
|
9 | 12 | export default Runtime.handler( |
10 | 13 | 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>) { |
12 | 15 | 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 | + } |
13 | 29 | // Keep this explicit: automatic service replacement must preserve terminals. |
14 | 30 | yield* ServerConnection.shutdownPersistentPty(options).pipe(Effect.ignore) |
15 | 31 | yield* Service.stop(options) |
16 | 32 | const transport = yield* Service.ensure(options) |
17 | 33 | process.stdout.write(transport.url + EOL) |
18 | 34 | }), |
19 | 35 | ) |
| 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