GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat: service restart approval when agents are running by agustif · Pull Request #55967 · anomalyco/opencode

feat: service restart approval when agents are running #55967

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
agustif wants to merge 6 commits into anomalyco:dev from agustif:restart-approval

Uh oh!

There was an error while loading. Please reload this page.

Closed

feat: service restart approval when agents are running #55967

Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
6 commits
Select commit Hold shift + click to select a range
3f47f52
fix(tui): only flag session location missing on LocationNotFoundError
agustif Oct 16, 2026
87a27cf
feat(server): restart approval intent protocol and endpoints
agustif Oct 16, 2026
b68002d
feat(cli): guard service restart with approval
agustif Oct 16, 2026
9152632
feat(tui): restart approval dialog
agustif Oct 16, 2026
80b3628
fix: address restart approval review feedback
agustif Oct 16, 2026
8a5d47c
fix(server): expire unanswered restart requests
agustif Oct 16, 2026
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view
Prev Previous commit
Next Next commit
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.
  • Loading branch information

Uh oh!

There was an error while loading. Please reload this page.

@agustif
agustif committed Oct 16, 2026
commit 80b3628d3904d764f036c523934af0f016f9f994

There are no files selected for viewing

150 changes: 103 additions & 47 deletions 150 packages/cli/src/commands/handlers/service/restart.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { select } from "@clack/prompts"
import { EOL } from "os"
import { EOL } from "node:os"
import { Effect } from "effect"
import { Service } from "@opencode/client/effect/service"
import { OpenCode, type OpenCodeClient } from "@opencode/client/promise"
import { OpenCode, isInvalidRequestError, type OpenCodeClient } from "@opencode/client/promise"
import { Commands } from "../../commands"
import { Runtime } from "../../../framework/runtime"
import { ServiceConfig } from "../../../services/service-config"
Expand Down Expand Up @@ -39,16 +39,18 @@ export type RestartApprovalDecision = "now" | "idle" | "cancel"
export type RestartApprovalDeps = {
readonly force: boolean
readonly interactive: boolean
readonly ask: (active: ReadonlyArray<string>) => Effect.Effect<RestartApprovalDecision, unknown>
readonly ask: (active: ReadonlyArray<string>) => Effect.Effect<RestartApprovalDecision, unknown, never>
readonly resolveTimeoutMs: number
readonly idlePollMs: number
readonly onWaiting: (active: ReadonlyArray<string>) => void
}

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

const resolveInteractive = Effect.fn("cli.service.restart.approval.interactive")(function* (
client: OpenCodeClient,
deps: RestartApprovalDeps,
watcher: ResolvedWatcher,
active: ReadonlyArray<string>,
) {
const picked = yield* deps.ask(active)
const resolved = yield* Effect.tryPromise({
return yield* Effect.tryPromise({
// Pass the rejection through unchanged so catchIf can read its `_tag`.
try: () => client.server.restart.resolve({ decision: picked }),
catch: (cause) => new Error("Could not reach server to resolve restart approval", { cause }),
})
return resolved.decision
catch: (cause) => cause,
}).pipe(
Effect.map((resolved) => resolved.decision),
// Another surface won the race; adopt the broadcast winner instead.
Effect.catchIf(isInvalidRequestError, () => awaitWinner(client, watcher, deps)),
Effect.mapError((cause) => new Error("Could not reach server to resolve restart approval", { cause })),
)
})

const resolveRemote = Effect.fn("cli.service.restart.approval.remote")(function* (
client: OpenCodeClient,
deps: RestartApprovalDeps,
watcher: ResolvedWatcher,
) {
return yield* awaitWinner(client, watcher, deps)
})

const awaitWinner = Effect.fn("cli.service.restart.approval.wait")(function* (
client: OpenCodeClient,
watcher: ResolvedWatcher,
deps: RestartApprovalDeps,
) {
return yield* Effect.tryPromise({
try: () => waitForResolvedEvent(client, deps.resolveTimeoutMs),
try: () => watcher.wait(deps.resolveTimeoutMs),
catch: (cause) =>
cause instanceof RestartApprovalTimeout
? new Error(
"Timed out waiting for restart approval; no connected client approved the restart. Re-run with --force to restart immediately.",
)
? new Error("Timed out waiting for restart approval with sessions still running.")
: new Error("Lost connection to the server while waiting for restart approval", { cause }),
})
}).pipe(
Effect.tapError(() =>
Comment thread Outdated

@opencode-agent opencode-agent Bot Oct 16, 2026

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This releases the request on timeout or a lost connection. It doesn't run when the fiber is interrupted (Ctrl-C) or the process is killed, for example by the agent shell tool's own timeout, which is the agent-invoked case. The request then stays pending forever, the TUI dialogs stay open, and a later "Restart now" there broadcasts a decision nobody acts on. A server-side expiry on the request in RestartIntent (e.g. matching the 120s wait), plus a resolved/expired event so TUIs close the dialog, would cover every way the requester can go away.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@agustif agustif Oct 16, 2026

Copy link
Copy Markdown
Author

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right — the release path only covers unwinding, not interruption or SIGKILL, which is exactly the agent-invoked case. Done in 8a5d47c:

Server owns release. Each server.restart.request now schedules a detached expiry (Effect.forkDetach, so it outlives the request scope) at a 2-minute TTL matching the CLI wait. When it fires and the intent is still pending, it clears it and publishes server.restart.expired. Generation tokens guard the race: expire(generation) is a no-op if a newer request has since been made or the intent already settled, so a stale timer can't free someone else's request.

Approvers dismiss on expiry. The TUI closes the dialog on server.restart.expired, so no dialog is left open for a decision nobody will act on.

One release path. I removed the CLI's own cancel-on-error rather than keeping two mechanisms; the CLI now treats expired as the terminal outcome and fails with the same timeout message. Its local wait is 150s against the server's 120s TTL, so the server always ends an unanswered wait and the local timer only covers a stream that goes silent.

Coverage:

  • packages/server/test/restart-intent.test.ts (6 tests) — expiry releases the current generation; a stale token leaves a newer request pending; expiring a settled intent is a no-op; plus the earlier first-wins/replay cases.
  • CLI "an expired request aborts the wait" and the timeout test now asserts the CLI posts no cancel of its own.
  • TUI "an expired request dismisses the dialog".

All green: server 6, CLI 12, TUI 4; tsgo -b clean in all three packages; oxlint clean.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
// Release TUIs stuck on our intent; a settled intent replays its winner.
Effect.tryPromise(() => client.server.restart.resolve({ decision: "cancel" })).pipe(Effect.ignore),
),
)
})

// The requesting session blocks on this command, so it can never go idle while
// watched. Exclude it from the drain set; approval itself still required it.
const waitForIdle = Effect.fn("cli.service.restart.approval.idle")(function* (
client: OpenCodeClient,
deps: RestartApprovalDeps,
initial: ReadonlyArray<string>,
) {
deps.onWaiting(initial)
while (true) {
yield* Effect.sleep(deps.idlePollMs)
const active = yield* Effect.tryPromise({
try: () => client.session.active(),
catch: (cause) =>
new Error("Lost connection to the server while waiting for sessions to finish", { cause }),
})
const ids = Object.keys(active)
const ids = Object.keys(active).filter((id) => id !== process.env.OPENCODE_SESSION_ID)
if (ids.length === 0) return
deps.onWaiting(ids)
}
})

function restartAborted(active: ReadonlyArray<string>) {
return new Error(
`Restart cancelled with ${active.length} active session(s); re-run with --force to restart immediately.`,
)
function restartAborted(active: ReadonlyArray<string>, interactive: boolean) {
return interactive
? new Error(
`Restart cancelled with ${active.length} active session(s); re-run with --force to restart immediately.`,
)
: new Error("Restart cancelled with active session(s) still running.")
}

class RestartApprovalTimeout extends Error {
Expand All @@ -130,31 +159,58 @@ class RestartApprovalTimeout extends Error {
}
}

function waitForResolvedEvent(client: OpenCodeClient, timeoutMs: number): Promise<RestartApprovalDecision> {
return (async () => {
const controller = new AbortController()
let timedOut = false
const timer = setTimeout(() => {
timedOut = true
controller.abort()
}, timeoutMs)
export type ResolvedWatcher = {
readonly arm: () => void
readonly wait: (timeoutMs: number) => Promise<RestartApprovalDecision>
readonly dispose: () => void
}

export function watchResolved(client: OpenCodeClient): ResolvedWatcher {
const controller = new AbortController()
let armed = false
let pending: RestartApprovalDecision | undefined
let settle: ((decision: RestartApprovalDecision) => void) | undefined
let failure: unknown | undefined
const fail = (cause: unknown) => {
failure ??= cause
settle = undefined
}
void (async () => {
try {
const stream = client.event.subscribe({ signal: controller.signal })[Symbol.asyncIterator]()
while (true) {
for (;;) {
const next = await stream.next()
if (next.done) break
if (next.value.type === "server.restart.resolved") return next.value.data.decision
if (armed && next.value.type === "server.restart.resolved") {
const decision = next.value.data.decision
pending ??= decision
settle?.(decision)
}
}
if (timedOut) throw new RestartApprovalTimeout()
throw new Error("Event stream disconnected while waiting for restart approval")
fail(new Error("Event stream disconnected while waiting for restart approval"))
} catch (cause) {
if (timedOut) throw new RestartApprovalTimeout()
throw cause
} finally {
clearTimeout(timer)
controller.abort()
fail(cause)
}
})()
return {
arm() {
armed = true
},
wait(timeoutMs: number) {
return new Promise<RestartApprovalDecision>((resolve, reject) => {
if (pending !== undefined) return resolve(pending)
if (failure !== undefined) return reject(failure)
const timer = setTimeout(() => reject(new RestartApprovalTimeout()), timeoutMs)
settle = (decision) => {
clearTimeout(timer)
resolve(decision)
}
})
},
dispose() {
controller.abort()
},
}
}

const askRestartDecision = (active: ReadonlyArray<string>) =>
Expand Down
Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.