feat(core): track planned-shutdown detaching state

This commit is contained in:
James Long
2026-11-05 00:11:05 +00:00
Unverified
parent 203505ac60
commit 8ecfa5caef
5 changed files with 87 additions and 3 deletions
+41
View File
@@ -0,0 +1,41 @@
export * as Detaching from "./detaching.js"
import { Context, Effect, Layer } from "effect"
import { makeGlobalNode } from "@opencode/util/effect/app-node"
/**
* Planned-shutdown state of this server process.
*
* A prepared daemon handoff means a new server will take over the daemon's processes. If this server
* then shuts down, it is detaching: work that can outlive it in the daemon is left running and recorded
* for the new server instead of being stopped. Without a prepared handoff (a normal quit), shutdown
* stops everything as before.
*/
export interface Interface {
/** Records that a daemon handoff was prepared successfully. */
readonly handoffPrepared: Effect.Effect<void>
/** Called once shutdown starts, before any service is torn down. Returns whether this server is detaching. */
readonly begin: Effect.Effect<boolean>
readonly isDetaching: () => boolean
}
export class Service extends Context.Service<Service, Interface>()("@opencode/Detaching") {}
export const make = Effect.sync(() => {
let prepared = false
let detaching = false
return Service.of({
handoffPrepared: Effect.sync(() => {
prepared = true
}),
begin: Effect.sync(() => {
detaching = prepared
return detaching
}),
isDetaching: () => detaching,
})
})
export const layer = Layer.effect(Service, make)
export const node = makeGlobalNode({ service: Service, layer, deps: [] })
+9 -2
View File
@@ -16,6 +16,7 @@ import {
import { Session } from "@opencode/schema/session"
import { SessionEvent } from "@opencode/schema/session-event"
import { Bus } from "../bus.js"
import { Detaching } from "../detaching.js"
import { Pty } from "@opencode/schema/pty"
import { Global } from "@opencode/util/global"
import { ShellSelect } from "../shell/select.js"
@@ -199,6 +200,7 @@ const makeLayer = (options: Options = {}) =>
Effect.gen(function* () {
const bus = yield* Bus.Service
const global = yield* Global.Service
const detaching = yield* Detaching.Service
const context = yield* Effect.context()
const runFork = Effect.runForkWith(context)
let binary: Promise<string> | undefined
@@ -367,7 +369,12 @@ const makeLayer = (options: Options = {}) =>
if (response.type !== "ok") return yield* unexpected(response)
})
const handoff = Effect.fn("PersistentPty.handoff")(() => daemon.handoff.pipe(Effect.mapError(unavailable)))
const handoff = Effect.fn("PersistentPty.handoff")(() =>
daemon.handoff.pipe(
Effect.tap((prepared) => (prepared ? detaching.handoffPrepared : Effect.void)),
Effect.mapError(unavailable),
),
)
const removeVisibleExit = (id: Pty.ID) => {
if (removing.has(id)) return
@@ -528,7 +535,7 @@ export const configured = (options?: Options) =>
makeGlobalNode({
service: Service,
layer: options === undefined ? layer : makeLayer(options),
deps: [Bus.node, Global.node],
deps: [Bus.node, Global.node, Detaching.node],
})
export const node = configured()
+12
View File
@@ -2,6 +2,7 @@ export * as ServerProcess from "./process"
import { NodeHttpServer } from "@effect/platform-node"
import { Bus } from "@opencode/core/bus"
import { Detaching } from "@opencode/core/detaching"
import { SessionRestart } from "@opencode/core/session/execution/restart"
import { Schedule } from "@opencode/core/schedule"
import { InstallationEvent } from "@opencode/schema/installation-event"
@@ -88,6 +89,8 @@ export const start = Effect.fn("ServerProcess.start")(function* <E, R>(
const parentScope = yield* Scope.Scope
const applicationScope = yield* Scope.fork(parentScope)
let detaching: Detaching.Interface | undefined
yield* enterDetachingOnShutdown(() => detaching)
yield* Effect.addFinalizer(() =>
status.beginStopping.pipe(
Effect.andThen(Ref.set(application, Option.none())),
@@ -115,6 +118,7 @@ export const start = Effect.fn("ServerProcess.start")(function* <E, R>(
}
// Schedules fire from any server process (`service`, `opencode serve`, or `--standalone`); the table holds all their state.
yield* Effect.forkIn(Context.get(context, Schedule.Service).run, applicationScope)
detaching = Context.get(context, Detaching.Service)
yield* Ref.set(application, Option.some(Context.get(context, HttpRouter.HttpRouter).asHttpEffect()))
yield* status.ready
const bus = Context.get(context, Bus.Service)
@@ -146,6 +150,14 @@ export const start = Effect.fn("ServerProcess.start")(function* <E, R>(
return yield* Effect.raceFirst(boot, shutdown.await.pipe(Effect.andThen(Effect.interrupt)))
})
/**
* Decides on shutdown whether this server is detaching (a daemon handoff was prepared), before anything
* is torn down. Must be added to the parent scope after the application scope was forked from it:
* finalizers run in reverse order, so it then runs before the application scope closes.
*/
export const enterDetachingOnShutdown = (detaching: () => Detaching.Interface | undefined) =>
Effect.addFinalizer(() => Effect.suspend(() => detaching()?.begin ?? Effect.void))
function listen(options: { readonly hostname: string; readonly port: Option.Option<number> }) {
if (Option.isSome(options.port)) return bind(options.hostname, options.port.value)
const next = (port: number): ReturnType<typeof bind> =>
+2
View File
@@ -20,6 +20,7 @@ import { Instance } from "@opencode/core/instance/service"
import { SessionTransfer } from "@opencode/core/session/transfer"
import { InstructionEntry } from "@opencode/core/session/instruction-entry"
import { ShellSelect } from "@opencode/core/shell/select"
import { Detaching } from "@opencode/core/detaching"
import { Job } from "@opencode/core/job"
import { KV } from "@opencode/core/kv"
import { Mcp } from "@opencode/core/mcp/index"
@@ -62,6 +63,7 @@ const applicationServiceNodes = [
Bus.node,
EventLogger.node,
httpClient,
Detaching.node,
Job.node,
Project.node,
Project.sweepNode,
+23 -1
View File
@@ -1,5 +1,6 @@
import { expect } from "bun:test"
import { Effect } from "effect"
import { Detaching } from "@opencode/core/detaching"
import { Effect, Exit, Scope } from "effect"
import { HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http"
import { it } from "../../core/test/lib/effect"
import { ServerProcess } from "../src/process"
@@ -259,3 +260,24 @@ it.live("server info lists remote URLs alongside local addresses while they are
expect((yield* info()).urls).toEqual([base])
}),
)
it.live("enters detaching on shutdown before the application scope closes", () =>
Effect.gen(function* () {
for (const prepared of [true, false]) {
const detaching = yield* Detaching.make
if (prepared) yield* detaching.handoffPrepared
const parent = yield* Scope.make()
// Same order as ServerProcess.start: fork the application scope, then register the hook.
const application = yield* Scope.fork(parent)
const seen: boolean[] = []
yield* Scope.addFinalizer(
application,
Effect.sync(() => seen.push(detaching.isDetaching())),
)
yield* ServerProcess.enterDetachingOnShutdown(() => detaching).pipe(Scope.provide(parent))
expect(detaching.isDetaching()).toBe(false)
yield* Scope.close(parent, Exit.void)
expect(seen).toEqual([prepared])
}
}),
)