fix(core): never let persistent PTY handoff break a server restart (#52573)

This commit is contained in:
James Long
2026-10-03 10:23:31 -04:00
committed by GitHub
Unverified
parent d8a3962923
commit 5ad0786536
13 changed files with 329 additions and 120 deletions
+8 -10
View File
@@ -122,7 +122,7 @@
"@clack/core": "1.0.0-alpha.1",
"@clack/prompts": "1.0.0-alpha.1",
"@effect/platform-node": "catalog:",
"@opencode-ai/pty": "0.1.13",
"@opencode-ai/pty": "0.2.0",
"@opencode/client": "workspace:*",
"@opencode/plugin": "workspace:*",
"@opencode/schema": "workspace:*",
@@ -355,7 +355,7 @@
"@lydell/node-pty": "catalog:",
"@modelcontextprotocol/client": "2.0.0",
"@modelcontextprotocol/core": "2.0.0",
"@opencode-ai/pty": "0.1.13",
"@opencode-ai/pty": "0.2.0",
"@opencode/ai": "workspace:*",
"@opencode/codemode": "workspace:*",
"@opencode/plugin": "workspace:*",
@@ -2167,19 +2167,17 @@
"@opencode-ai/protocol": ["@opencode-ai/protocol@0.0.0-beta-18050", "", { "dependencies": { "@opencode-ai/schema": "0.0.0-beta-18050", "effect": "4.0.0-rc.111" } }, "sha512-HDQMnvGp8IU0MdBRbEuydX1WQm09BZ4HJm9iSMQwzweJuQ2HNscgzHJPIH6P02BsbbtfJ8J7sZGPItrz1tWSgw=="],
"@opencode-ai/pty": ["@opencode-ai/pty@0.1.13", "", { "optionalDependencies": { "@opencode-ai/pty-darwin-arm64": "0.1.13", "@opencode-ai/pty-darwin-x64": "0.1.13", "@opencode-ai/pty-linux-arm64-gnu": "0.1.13", "@opencode-ai/pty-linux-arm64-musl": "0.1.13", "@opencode-ai/pty-linux-x64-gnu": "0.1.13", "@opencode-ai/pty-linux-x64-musl": "0.1.13" }, "bin": { "opencode-pty": "bin/opencode-pty.js" } }, "sha512-WPCN8h8HaZhhUcrMG0zu+4D9vco0EZiEg/gCF1K3JPRN6UsHMiXq1HVIy5IlyfcoyjfViRmQmXYE4AuU3laBjA=="],
"@opencode-ai/pty": ["@opencode-ai/pty@0.2.0", "", { "optionalDependencies": { "@opencode-ai/pty-darwin-arm64": "0.2.0", "@opencode-ai/pty-darwin-x64": "0.2.0", "@opencode-ai/pty-linux-arm64-gnu": "0.2.0", "@opencode-ai/pty-linux-arm64-musl": "0.2.0", "@opencode-ai/pty-linux-x64-gnu": "0.2.0", "@opencode-ai/pty-linux-x64-musl": "0.2.0" }, "bin": { "opencode-pty": "bin/opencode-pty.js" } }, "sha512-pV86urAwinpwFXX8AJlOf8S9CVJhGsV+11I/J6TcxMW0c7u6LgeODzdj/BVBC6jUhsG2aKDxg8rACMcDCy3HiA=="],
"@opencode-ai/pty-darwin-arm64": ["@opencode-ai/pty-darwin-arm64@0.1.13", "", { "os": "darwin", "cpu": "arm64" }, "sha512-fVtQZqVLBuJx/aB+5ojfmQifS1KMc9gxlxpFQ6bxEFU8tn8xHQTiFPaNroZgOtaw7I4ceGyx/eXieK1wp68yAA=="],
"@opencode-ai/pty-darwin-arm64": ["@opencode-ai/pty-darwin-arm64@0.2.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-2y6xrktb2J7rRk+mzAJHA8cCbWhC4Lo2zJ66t9ad59qFhL5nzAPfpEOwnyvvFqhxebHNvL08Mp64M9IHnM0aiA=="],
"@opencode-ai/pty-darwin-x64": ["@opencode-ai/pty-darwin-x64@0.1.13", "", { "os": "darwin", "cpu": "x64" }, "sha512-b/tAEm0hCMXraPM9cxR8Rg7X1UBZInRTaxWAS4Ht9eH1nWj1rANOLvHWiWX/vVh5TB0Ubg8bWPu4B0nZkEHROQ=="],
"@opencode-ai/pty-darwin-x64": ["@opencode-ai/pty-darwin-x64@0.2.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-XVQwK9+KgVGYunCYPCCBf1Or0z6zSkzjgfdJd7dEe/LOFg5vmMkOfSB9dCXnoRCWGviWYk7xd07iFIFOgyj5Ig=="],
"@opencode-ai/pty-linux-arm64-gnu": ["@opencode-ai/pty-linux-arm64-gnu@0.1.13", "", { "os": "linux", "cpu": "arm64" }, "sha512-I124aSYBBjpGZnYExHfIajkvVK1FiK+//OJBGdqqFp5pas2Oruq4O8tv+pMoxomZIYh2ce/QhOOYLHRwXsthTg=="],
"@opencode-ai/pty-linux-arm64-gnu": ["@opencode-ai/pty-linux-arm64-gnu@0.2.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-TPVGCQk5E65IY3ipcpd17rwKehdvXcXEYRhhGzok/6Dske69ei2S+ERz7NXZ8cKFAvbiiT771HHM+XyVYAl+7A=="],
"@opencode-ai/pty-linux-arm64-musl": ["@opencode-ai/pty-linux-arm64-musl@0.1.13", "", { "os": "linux", "cpu": "arm64" }, "sha512-feWsfKpaDytGJzutoK43GqQwVghG2vHZt6BE/ydPZNuqIrySQ/6JfliUAMwn5BWs/Ky7ouSwKHCyAVeukusSvg=="],
"@opencode-ai/pty-linux-arm64-musl": ["@opencode-ai/pty-linux-arm64-musl@0.2.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-iH6/liY7xN1OXVD9eGzdH11BVGvnpPsH5Z1Unz0Pn9EzkPFf28oDNKNyeXV0xIAP53oiYp8gpRq2PADNwbVsTg=="],
"@opencode-ai/pty-linux-x64-gnu": ["@opencode-ai/pty-linux-x64-gnu@0.1.13", "", { "os": "linux", "cpu": "x64" }, "sha512-jliNgsevGuxfIeX7eyzjHhrJkF8uEUPnDLbF2v16uv69FhEHrraf7jyWkxazMP6rNvn2CGtwMMc4BXPS5pzjhg=="],
"@opencode-ai/pty-linux-x64-musl": ["@opencode-ai/pty-linux-x64-musl@0.1.13", "", { "os": "linux", "cpu": "x64" }, "sha512-rXDpidW66gz2b2M/NbUN8ZKmAxaJcASnuHATeXevlrFdiPUv8uJwvkRd6Pla1fp01Q65MkBmgRa7Q9c+H1PlzA=="],
"@opencode-ai/pty-linux-x64-gnu": ["@opencode-ai/pty-linux-x64-gnu@0.2.0", "", { "os": "linux", "cpu": "x64" }, "sha512-GhdrmbUzxGHRfWvt1qutgVD4HLb7aSBsgWGjFsc6k8HjO5ZbdaC3ScRyd512YAAG5KAROLKZ6+0SEBsm5xFYlA=="],
"@opencode-ai/schema": ["@opencode-ai/schema@0.0.0-beta-18050", "", { "dependencies": { "@standard-schema/spec": "1.1.0", "effect": "4.0.0-rc.111" } }, "sha512-/D6VXaWlytTXR3IOiMLIKuPcfp7FQNUzRPm9z3K7UBFd1Bw4q/WZksaf5RVcBGz+0YRxYMc1V4D7MFlceSgtyg=="],
+1 -1
View File
@@ -30,7 +30,7 @@
"@effect/platform-node": "catalog:",
"@opencode/client": "workspace:*",
"@opencode/plugin": "workspace:*",
"@opencode-ai/pty": "0.1.13",
"@opencode-ai/pty": "0.2.0",
"@opencode/schema": "workspace:*",
"@opencode/server": "workspace:*",
"@opencode/tui": "workspace:*",
+5 -1
View File
@@ -49,7 +49,11 @@ const processEffect = Effect.fnUntraced(function* (options: Options) {
inherited === undefined
? undefined
: yield* Schema.decodeUnknownEffect(Schema.fromJsonString(PersistentPty.Handoff))(inherited).pipe(
Effect.mapError(() => new Error("Invalid PTY restart handoff")),
Effect.catch(() =>
Effect.logWarning("Ignoring invalid PTY restart handoff; persistent terminals will start fresh").pipe(
Effect.as(undefined),
),
),
)
const global = yield* Global.Service
if (options.mode === "service") yield* Effect.sync(() => process.chdir(global.home))
+8 -5
View File
@@ -145,11 +145,14 @@ export const ensure = Effect.fn("service.ensure")(function* (options: EnsureOpti
/** Stop the registered local service. */
export const stop = Effect.fn("service.stop")(function* (options: StopOptions = {}) {
const info = yield* read(options.file)
if (options.pty === "handoff" && info !== undefined)
yield* Effect.tryPromise(() =>
PtyHandoff.prepare(options.file ?? fallback(), info, defaultEnsureTiming.requestTimeout),
)
else yield* Effect.tryPromise(() => PtyHandoff.clear(options.file ?? fallback()))
// Terminal handoff is best-effort; it must never keep the old service running.
yield* Effect.tryPromise(() =>
options.pty === "handoff" && info !== undefined
? PtyHandoff.prepare(options.file ?? fallback(), info, defaultEnsureTiming.requestTimeout)
: PtyHandoff.clear(options.file ?? fallback()),
).pipe(
Effect.catch((cause) => Effect.logWarning("Failed to prepare persistent terminals for replacement", cause)),
)
if (info !== undefined) yield* terminate(info, options, defaultEnsureTiming)
})
+6 -3
View File
@@ -118,9 +118,12 @@ export async function ensure(options: EnsureOptions = {}): Promise<Endpoint> {
/** Stop the registered local service. */
export async function stop(options: StopOptions = {}) {
const info = await read(options.file)
if (options.pty === "handoff" && info !== undefined)
await PtyHandoff.prepare(options.file ?? fallback(), info, defaultEnsureTiming.requestTimeout)
else await PtyHandoff.clear(options.file ?? fallback())
// Terminal handoff is best-effort; it must never keep the old service running.
await (
options.pty === "handoff" && info !== undefined
? PtyHandoff.prepare(options.file ?? fallback(), info, defaultEnsureTiming.requestTimeout)
: PtyHandoff.clear(options.file ?? fallback())
).catch((cause: unknown) => console.warn("Failed to prepare persistent terminals for replacement", cause))
if (info !== undefined) await terminate(info, options, defaultEnsureTiming)
}
+24 -34
View File
@@ -10,11 +10,14 @@ type Sidecar = {
readonly expiresAt: number
}
/** Publish the ticket before stopping its owner so every replacement contender can adopt it. */
/**
* Publish the ticket before stopping its owner so every replacement contender can adopt it.
* Never throws: terminals are best-effort, so any failure replaces the service without a handoff.
*/
export async function prepare(file: string, info: Info, timeout: number) {
const existing = await read(file)
if (existing !== undefined && existing.expiresAt > Date.now() && same(existing.source, info)) return
const { ClientError, OpenCode } = await import("./promise/index.js")
const { OpenCode } = await import("./promise/index.js")
const client = OpenCode.make({
baseUrl: info.url,
headers:
@@ -22,43 +25,30 @@ export async function prepare(file: string, info: Info, timeout: number) {
? undefined
: { authorization: "Basic " + Buffer.from(`opencode:${info.password}`).toString("base64") },
})
const missing = (error: unknown) =>
error instanceof ClientError &&
error.reason === "UnexpectedStatus" &&
typeof error.cause === "object" &&
error.cause !== null &&
"status" in error.cause &&
error.cause.status === 404
const result = await client.experimental.persistentPty.handoff({ signal: AbortSignal.timeout(timeout) }).then(
(value) => ({ value }),
(cause: unknown) => ({ cause }),
const handoff = await client.experimental.persistentPty
.handoff({ signal: AbortSignal.timeout(timeout) })
.then(parse)
.catch(async (cause: unknown) => {
// Another caller may already have prepared and stopped this server.
const concurrent = await read(file)
if (concurrent !== undefined && concurrent.expiresAt > Date.now() && same(concurrent.source, info)) return
console.warn("Background service cannot hand off persistent terminals; shutting them down before replacement", cause)
await client.experimental.persistentPty.shutdown({ signal: AbortSignal.timeout(timeout) }).catch(() => {})
return null
})
if (handoff === undefined) return
await publish(file, info, handoff).catch((cause: unknown) =>
console.warn("Failed to publish persistent terminal handoff", cause),
)
if ("cause" in result) {
// Another caller may already have prepared and stopped this server.
const concurrent = await read(file)
if (concurrent !== undefined && concurrent.expiresAt > Date.now() && same(concurrent.source, info)) return
if (!missing(result.cause))
throw new Error("Failed to prepare persistent terminals for service replacement", { cause: result.cause })
console.warn("Background service cannot hand off persistent terminals; shutting them down before replacement")
await client.experimental.persistentPty
.shutdown({ signal: AbortSignal.timeout(timeout) })
.catch((cause: unknown) => {
if (missing(cause)) return
throw new Error("Failed to shut down persistent terminals before service replacement", { cause })
})
await publish(file, info, null)
return
}
const body: unknown = result.value
}
function parse(body: unknown) {
if (typeof body !== "object" || body === null || !("handoff" in body))
throw new Error("Invalid persistent terminal handoff response")
if (body.handoff === null) {
await publish(file, info, null)
return
}
if (body.handoff === null) return null
if (!isHandoff(body.handoff) || body.handoff.expiresAt <= Date.now())
throw new Error("Invalid or expired persistent terminal handoff")
await publish(file, info, body.handoff)
return body.handoff
}
async function publish(file: string, info: Info, handoff: PersistentPty.Handoff | null) {
+2
View File
@@ -52,6 +52,8 @@ const server = Bun.serve({
await writeFile(registration + ".prepared", JSON.stringify(handoff))
return Response.json({ handoff })
}
if (pathname === "/api/experimental/persistent-pty/handoff" && mode === "handoff-broken")
return new Response(null, { status: 500 })
if (pathname !== "/api/info") return new Response(null, { status: 404 })
requests += 1
if (mode === "starting") await writeFile(registration + ".status-request", "")
@@ -147,6 +147,19 @@ test("evicts an unresponsive registered service before starting its replacement"
expect(endpoint.url).toBe(replacement.url)
})
test("stops the registered service even when terminal handoff fails", async () => {
await using fixture = await serviceFixture()
const registration = fixture.registration
fixture.spawn("handoff-broken")
await fixture.waitForFile()
await Service.stop({ file: registration, pty: "handoff" })
expect(await Bun.file(registration + ".signal").text()).toBe("SIGTERM")
expect(await Bun.file(registration).exists()).toBe(false)
expect((await Bun.file(registration + ".pty-handoff").json()).handoff).toBeNull()
})
test("signals the registered service process", async () => {
await using fixture = await serviceFixture()
const registration = fixture.registration
+1 -1
View File
@@ -106,7 +106,7 @@
"@lydell/node-pty": "catalog:",
"@modelcontextprotocol/client": "2.0.0",
"@modelcontextprotocol/core": "2.0.0",
"@opencode-ai/pty": "0.1.13",
"@opencode-ai/pty": "0.2.0",
"@opencode/ai": "workspace:*",
"@opencode/codemode": "workspace:*",
"@opencode/plugin": "workspace:*",
+80 -21
View File
@@ -1,8 +1,8 @@
import { spawn } from "node:child_process"
import { readFile } from "node:fs/promises"
import { mkdir, readFile, rename } from "node:fs/promises"
import net from "node:net"
import path from "node:path"
import { Data, Duration, Effect, Schema, Semaphore } from "effect"
import { Cause, Data, Duration, Effect, Schema, Semaphore } from "effect"
import type { Handoff } from "@opencode/schema/persistent-pty"
const ProtocolVersion = 7
@@ -156,11 +156,14 @@ export interface DaemonTransport {
}
export const makeDaemonTransport = Effect.fn("PersistentPty.makeDaemonTransport")(function* (
directory: string,
root: string,
initialID: string,
binary: () => Promise<string> = () => Promise.resolve(process.env.OPENCODE_PTY_BIN || "opencode-pty"),
inherited?: Handoff,
) {
const startup = Semaphore.makeUnsafe(1)
// Each daemon owns the runtime directory `<root>/<id>`.
let id = initialID
let registration: Registration | undefined
let owner: Awaited<ReturnType<typeof openOwner>> | undefined
let closed = false
@@ -195,7 +198,7 @@ export const makeDaemonTransport = Effect.fn("PersistentPty.makeDaemonTransport"
}),
)
const discover = Effect.fn("PersistentPty.daemon.discover")(function* () {
const discover = Effect.fn("PersistentPty.daemon.discover")(function* (directory = path.join(root, id)) {
const value = yield* Effect.tryPromise({
try: () => readFile(path.join(directory, "service.json"), "utf8"),
catch: (cause) => failure("connect", cause),
@@ -222,16 +225,16 @@ export const makeDaemonTransport = Effect.fn("PersistentPty.makeDaemonTransport"
return decoded
})
const start = Effect.fn("PersistentPty.daemon.start")(function* () {
const spawnDaemon = Effect.fn("PersistentPty.daemon.spawn")(function* () {
const executable = yield* Effect.tryPromise({ try: binary, catch: (cause) => failure("spawn", cause) })
const child = yield* Effect.tryPromise({
try: () =>
new Promise<ReturnType<typeof spawn>>((resolve, reject) => {
const child = spawn(executable, ["daemon"], {
detached: true,
stdio: "ignore",
env: { ...process.env, OPENCODE_PTY_RUNTIME_DIR: directory },
})
const child = spawn(
executable,
["daemon", "--runtime-dir", root, "--name", id],
{ detached: true, stdio: "ignore" },
)
child.once("spawn", () => {
child.unref()
resolve(child)
@@ -243,7 +246,7 @@ export const makeDaemonTransport = Effect.fn("PersistentPty.makeDaemonTransport"
return yield* Effect.gen(function* () {
const deadline = Date.now() + 5_000
let last: DaemonError | undefined
while (Date.now() < deadline) {
while (Date.now() < deadline && child.exitCode === null && child.signalCode === null) {
const found = yield* discover().pipe(
Effect.map((value) => ({ value })),
Effect.catch((error) => {
@@ -269,6 +272,25 @@ export const makeDaemonTransport = Effect.fn("PersistentPty.makeDaemonTransport"
)
})
// An unreachable daemon can still hold this directory's lock, so retry once in a fresh directory.
const start = () =>
spawnDaemon().pipe(
Effect.catch((error) =>
Effect.gen(function* () {
yield* Effect.logWarning("Starting opencode-pty in a fresh runtime directory", { cause: error.message })
abandon()
return yield* spawnDaemon()
}),
),
)
const abandon = () => {
owner?.socket.destroy()
owner = undefined
registration = undefined
id = crypto.randomUUID()
}
const connect = Effect.fn("PersistentPty.daemon.connect")(function* (shouldStart: boolean) {
if (closed) return yield* Effect.fail(new DaemonError({ kind: "connect", message: "PTY owner scope is closed" }))
if (registration) return registration
@@ -348,18 +370,23 @@ export const makeDaemonTransport = Effect.fn("PersistentPty.makeDaemonTransport"
)
if (response.type !== "handoff")
return yield* Effect.fail(new DaemonError({ kind: "protocol", message: "Expected PTY handoff ticket" }))
return { directory, instanceID: registered.instance_id, ticket: response.ticket, expiresAt: response.expires_at }
return {
directory: path.join(root, id),
instanceID: registered.instance_id,
ticket: response.ticket,
expiresAt: response.expires_at,
}
}),
)
const subscribe = Effect.fn("PersistentPty.daemon.subscribe")(function* (
id: number,
terminalID: number,
input: Parameters<DaemonTransport["subscribe"]>[1],
) {
const attempt = Effect.gen(function* () {
const current = yield* connect(false)
return yield* Effect.tryPromise({
try: () => subscribePromise(current, id, input),
try: () => subscribePromise(current, terminalID, input),
catch: (cause) => (cause instanceof DaemonError ? cause : failure("connect", cause)),
}).pipe(
Effect.catch((error) => {
@@ -371,19 +398,51 @@ export const makeDaemonTransport = Effect.fn("PersistentPty.makeDaemonTransport"
return yield* attempt.pipe(Effect.catch((error) => (error.kind === "registration" ? attempt : Effect.fail(error))))
})
// A replacement must own its inherited daemon before the server becomes ready.
// A replacement must own its inherited daemon before the server becomes ready. Terminals are
// best-effort: any failure abandons the old daemon so the restart itself always succeeds.
if (inherited) {
if (inherited.expiresAt <= Date.now())
return yield* Effect.fail(new DaemonError({ kind: "registration", message: "PTY restart handoff expired" }))
const current = yield* discover()
if (current.instance_id !== inherited.instanceID)
return yield* Effect.fail(new DaemonError({ kind: "registration", message: "PTY restart daemon changed" }))
yield* claim(current, inherited.ticket)
let found: Registration | undefined
yield* Effect.gen(function* () {
if (inherited.expiresAt <= Date.now())
return yield* Effect.fail(new DaemonError({ kind: "registration", message: "PTY restart handoff expired" }))
// Older releases put the daemon directory outside the root; its directory name is still the ID.
id = path.basename(inherited.directory)
found = yield* discover(inherited.directory)
if (found.instance_id !== inherited.instanceID)
return yield* Effect.fail(new DaemonError({ kind: "registration", message: "PTY restart daemon changed" }))
if (path.resolve(inherited.directory) !== path.resolve(root, id))
yield* migrate(inherited.directory, path.join(root, id))
yield* claim(found, inherited.ticket)
}).pipe(
Effect.catchCause((cause) =>
Effect.gen(function* () {
if (Cause.hasInterruptsOnly(cause)) return yield* Effect.failCause(cause)
yield* Effect.logWarning("Discarding PTY restart handoff; persistent terminals will start fresh", {
cause: Cause.pretty(cause),
})
if (found) yield* oneShot(found, { op: "shutdown" }).pipe(Effect.ignore)
abandon()
}),
),
)
}
return { request, requestIfRunning, shutdown, handoff, subscribe } satisfies DaemonTransport
})
// Older releases kept registrations in purgeable temp directories. Renaming keeps the lock file's
// inode, so the still-running daemon keeps holding its lock in the new location.
const migrate = Effect.fn("PersistentPty.daemon.migrate")(function* (directory: string, target: string) {
yield* Effect.tryPromise({
try: async () => {
await mkdir(target, { recursive: true, mode: 0o700 })
await rename(path.join(directory, "service.lock"), path.join(target, "service.lock"))
await rename(path.join(directory, "service.json"), path.join(target, "service.json"))
},
catch: (cause) => failure("registration", cause),
})
})
async function openOwner(registration: Registration, ticket: string | undefined, signal: AbortSignal) {
const socket = net.createConnection({ path: registration.socket })
const frames = decoder(socket)
+7 -15
View File
@@ -1,6 +1,5 @@
export * as PersistentPty from "./index.js"
import os from "node:os"
import path from "node:path"
import { Context, Effect, Layer, Schema } from "effect"
import { makeGlobalNode } from "@opencode/util/effect/app-node"
@@ -24,7 +23,11 @@ export type { Role, StreamEvent } from "./daemon.js"
export { Handoff } from "@opencode/schema/persistent-pty"
export { available } from "#persistent-pty-binary"
export const Options = Schema.Struct({ handoff: Schema.optional(Handoff) })
export const Options = Schema.Struct({
handoff: Schema.optional(Handoff),
/** Parent of per-server daemon runtime directories; defaults to `<state>/pty`. */
root: Schema.optional(Schema.String),
})
export type Options = typeof Options.Type
export type Info = PersistentPty.Info
@@ -123,7 +126,8 @@ const makeLayer = (options: Options = {}) =>
const runFork = Effect.runForkWith(context)
let binary: Promise<string> | undefined
const daemon = yield* makeDaemonTransport(
options.handoff?.directory ?? runtimeDirectory(),
options.root ?? path.join(global.state, "pty"),
crypto.randomUUID(),
() =>
(binary ??= resolveBinary(global.bin).catch((error) => {
binary = undefined
@@ -383,18 +387,6 @@ const unexpected = (response: WireResponse) =>
const unavailable = (error: unknown) =>
new UnavailableError({ message: error instanceof Error ? error.message : String(error) })
const runtimeDirectory = () => {
const root =
process.env.OPENCODE_PTY_RUNTIME_DIR ??
(process.env.XDG_RUNTIME_DIR
? path.join(process.env.XDG_RUNTIME_DIR, "opencode-pty")
: path.join(
os.tmpdir(),
`opencode-pty-${typeof process.getuid === "function" ? process.getuid() : process.env.USER || "unknown"}`,
))
return path.join(root, crypto.randomUUID())
}
function toInfo(value: WireTerminal): Info {
const status = value.lifecycle.status
return {
@@ -1,6 +1,7 @@
import { expect } from "bun:test"
import { spawn } from "node:child_process"
import { mkdtemp, rm, writeFile } from "node:fs/promises"
import { existsSync } from "node:fs"
import { mkdir, mkdtemp, rm, stat, writeFile } from "node:fs/promises"
import net from "node:net"
import os from "node:os"
import path from "node:path"
@@ -12,7 +13,7 @@ const pong = { type: "pong", instance_id: "test", pid: process.pid, protocol: 7
it.live("rediscovers a same-protocol daemon after its registration rotates", () =>
Effect.gen(function* () {
const directory = yield* temporaryDirectory()
const { root, directory } = yield* temporaryRuntime()
const socketPath = path.join(directory, "daemon.sock")
let token = "old-token"
let instance = "old-instance"
@@ -24,7 +25,7 @@ it.live("rediscovers a same-protocol daemon after its registration rotates", ()
return request.op === "list" ? { type: "terminals", terminals: [] } : { type: "ok" }
})
yield* Effect.promise(() => writeRegistration(directory, socketPath, instance, token))
const daemon = yield* makeDaemonTransport(directory)
const daemon = yield* makeDaemonTransport(root, "daemon")
yield* daemon.request({ op: "list" })
token = "new-token"
@@ -44,7 +45,7 @@ it.live("rediscovers a same-protocol daemon after its registration rotates", ()
it.live("rediscovers a rotated registration when acquiring a subscription", () =>
Effect.gen(function* () {
const directory = yield* temporaryDirectory()
const { root, directory } = yield* temporaryRuntime()
const socketPath = path.join(directory, "daemon.sock")
let token = "old-token"
let instance = "old-instance"
@@ -67,7 +68,7 @@ it.live("rediscovers a rotated registration when acquiring a subscription", () =
}
})
yield* Effect.promise(() => writeRegistration(directory, socketPath, instance, token))
const daemon = yield* makeDaemonTransport(directory)
const daemon = yield* makeDaemonTransport(root, "daemon")
yield* daemon.request({ op: "list" })
token = "new-token"
@@ -89,7 +90,7 @@ it.live("rediscovers a rotated registration when acquiring a subscription", () =
it.live("retries a start-required request when connection fails before dispatch", () =>
Effect.gen(function* () {
const directory = yield* temporaryDirectory()
const { root, directory } = yield* temporaryRuntime()
const firstSocket = path.join(directory, "first.sock")
const secondSocket = path.join(directory, "second.sock")
const first = yield* listen(firstSocket, (_socket, request) => {
@@ -97,7 +98,7 @@ it.live("retries a start-required request when connection fails before dispatch"
return { type: "terminals", terminals: [] }
})
yield* Effect.promise(() => writeRegistration(directory, firstSocket))
const daemon = yield* makeDaemonTransport(directory)
const daemon = yield* makeDaemonTransport(root, "daemon")
yield* daemon.request({ op: "list" })
yield* Effect.promise(first.close)
@@ -115,7 +116,7 @@ it.live("retries a start-required request when connection fails before dispatch"
it.live("does not replay a dispatched mutating request when its response is lost", () =>
Effect.gen(function* () {
const directory = yield* temporaryDirectory()
const { root, directory } = yield* temporaryRuntime()
const socketPath = path.join(directory, "daemon.sock")
let creates = 0
yield* listen(socketPath, (socket, request) => {
@@ -125,7 +126,7 @@ it.live("does not replay a dispatched mutating request when its response is lost
return undefined
})
yield* Effect.promise(() => writeRegistration(directory, socketPath))
const daemon = yield* makeDaemonTransport(directory)
const daemon = yield* makeDaemonTransport(root, "daemon")
const error = yield* Effect.flip(daemon.request({ op: "create" }, true))
expect(error.kind).toBe("response")
@@ -135,7 +136,7 @@ it.live("does not replay a dispatched mutating request when its response is lost
it.live("rejects incompatible daemons without replacing or killing them", () =>
Effect.gen(function* () {
const directory = yield* temporaryDirectory()
const { root, directory } = yield* temporaryRuntime()
const existing = yield* Effect.acquireRelease(
Effect.sync(() => spawn("sleep", ["30"])),
(child) =>
@@ -153,7 +154,7 @@ it.live("rejects incompatible daemons without replacing or killing them", () =>
JSON.stringify({ instance_id: "old", pid: existing.pid, protocol: 6, socket: "/unused", token: "old" }),
),
)
const daemon = yield* makeDaemonTransport(directory, () => Promise.resolve("/missing/opencode-pty"))
const daemon = yield* makeDaemonTransport(root, "daemon", () => Promise.resolve("/missing/opencode-pty"))
const optional = yield* Effect.flip(daemon.requestIfRunning({ op: "list" }))
expect(optional).toMatchObject({
@@ -170,6 +171,84 @@ it.live("rejects incompatible daemons without replacing or killing them", () =>
}),
)
it.live("moves an inherited legacy registration into the runtime root and keeps its lock file", () =>
Effect.gen(function* () {
const base = yield* temporaryDirectory()
const legacy = path.join(base, "legacy", "inherited")
const socketPath = path.join(base, "daemon.sock")
yield* listen(socketPath, (_socket, request) => {
if (request.op === "ping") return pong
return { type: "terminals", terminals: [] }
})
yield* Effect.promise(async () => {
await mkdir(legacy, { recursive: true })
await writeFile(path.join(legacy, "service.lock"), "")
await writeRegistration(legacy, socketPath)
})
const lock = yield* Effect.promise(() => stat(path.join(legacy, "service.lock")))
const daemon = yield* makeDaemonTransport(path.join(base, "root"), "fresh", undefined, {
directory: legacy,
instanceID: "test",
ticket: "ticket",
expiresAt: Date.now() + 60_000,
})
const migrated = path.join(base, "root", "inherited")
expect(existsSync(path.join(legacy, "service.json"))).toBeFalse()
expect((yield* Effect.promise(() => stat(path.join(migrated, "service.lock")))).ino).toBe(lock.ino)
expect(existsSync(path.join(migrated, "service.json"))).toBeTrue()
expect(yield* daemon.request({ op: "list" })).toEqual({ type: "terminals", terminals: [] })
}),
)
it.live("starts fresh instead of failing when an inherited registration is gone or expired", () =>
Effect.gen(function* () {
const base = yield* temporaryDirectory()
const legacy = path.join(base, "legacy")
yield* Effect.promise(() => mkdir(legacy))
for (const expiresAt of [Date.now() + 60_000, Date.now() - 1]) {
const daemon = yield* makeDaemonTransport(path.join(base, "root"), "fresh", undefined, {
directory: legacy,
instanceID: "test",
ticket: "ticket",
expiresAt,
})
expect(yield* daemon.handoff).toBeNull()
expect(yield* daemon.requestIfRunning({ op: "list" })).toBeUndefined()
}
}),
)
it.live("stops a discovered inherited daemon when adoption fails", () =>
Effect.gen(function* () {
const { root, directory } = yield* temporaryRuntime()
const socketPath = path.join(directory, "daemon.sock")
let shutdowns = 0
yield* listen(socketPath, (_socket, request) => {
if (request.op === "ping") return pong
if (request.op === "shutdown") shutdowns++
return { type: "ok" }
})
yield* Effect.promise(() => writeRegistration(directory, socketPath))
yield* makeDaemonTransport(root, "fresh", undefined, {
directory,
instanceID: "replaced",
ticket: "ticket",
expiresAt: Date.now() + 60_000,
})
expect(shutdowns).toBe(1)
}),
)
function temporaryRuntime() {
return Effect.gen(function* () {
const root = yield* temporaryDirectory()
const directory = path.join(root, "daemon")
yield* Effect.promise(() => mkdir(directory))
return { root, directory }
})
}
function temporaryDirectory() {
return Effect.acquireRelease(
Effect.promise(() => mkdtemp(path.join(os.tmpdir(), "opencode-pty-test-"))),
+84 -18
View File
@@ -18,13 +18,14 @@ smoke(
"reads the latest controlled terminal with optional physical line counts through the SDK",
() =>
Effect.gen(function* () {
const fixture = yield* testDirectory("xdg")
const fixture = yield* testDirectory()
const server = yield* ServerProcess.start<never, never>({
hostname: "127.0.0.1",
port: 0,
password: "secret",
app: { version: "test-version" },
database: { path: fixture.database },
pty: { root: fixture.directory },
fs: { filewatcher: false },
})
const base = HttpServer.formatAddress(server.address)
@@ -142,13 +143,14 @@ smoke(
"creates two persistent terminals for one session through the client API",
() =>
Effect.gen(function* () {
const fixture = yield* testDirectory("xdg")
const fixture = yield* testDirectory()
const server = yield* ServerProcess.start<never, never>({
hostname: "127.0.0.1",
port: 0,
password: "secret",
app: { version: "test-version" },
database: { path: fixture.database },
pty: { root: fixture.directory },
fs: { filewatcher: false },
})
const base = HttpServer.formatAddress(server.address)
@@ -315,7 +317,7 @@ smoke(
"isolates servers sharing a database and preserves terminals only through explicit restart handoff",
() =>
Effect.gen(function* () {
const fixture = yield* testDirectory("override")
const fixture = yield* testDirectory()
const scope = yield* Scope.Scope
const originalScope = yield* Scope.fork(scope)
const options = {
@@ -324,6 +326,7 @@ smoke(
password: "secret",
app: { version: "test-version" },
database: { path: fixture.database },
pty: { root: fixture.directory },
fs: { filewatcher: false },
}
const original = yield* ServerProcess.start<never, never>(options).pipe(
@@ -365,7 +368,7 @@ smoke(
expect(process.kill(first.pid, 0)).toBeTrue()
const replacementScope = yield* Scope.fork(scope)
const replacement = yield* ServerProcess.start<never, never>({ ...options, pty: { handoff } }).pipe(
const replacement = yield* ServerProcess.start<never, never>({ ...options, pty: { ...options.pty, handoff } }).pipe(
Effect.provideService(Scope.Scope, replacementScope),
)
const replacementBase = HttpServer.formatAddress(replacement.address)
@@ -385,25 +388,90 @@ smoke(
30_000,
)
function testDirectory(mode: "xdg" | "override") {
smoke(
"migrates a legacy runtime directory on restart and boots fresh when the registration is gone",
() =>
Effect.gen(function* () {
const fixture = yield* testDirectory()
const scope = yield* Scope.Scope
const legacy = path.join(fixture.root, "legacy")
const options = {
hostname: "127.0.0.1",
port: 0,
password: "secret",
app: { version: "test-version" },
database: { path: fixture.database },
fs: { filewatcher: false },
}
const sessionID = Session.ID.make("ses_persistent_pty_migration")
const originalScope = yield* Scope.fork(scope)
const original = yield* ServerProcess.start<never, never>({ ...options, pty: { root: legacy } }).pipe(
Effect.provideService(Scope.Scope, originalScope),
)
const base = HttpServer.formatAddress(original.address)
const first = Schema.decodeUnknownSync(PersistentPty.Info)(
(yield* request(base, "POST", `/api/experimental/session/${sessionID}/terminal`, {
command: "/bin/sh",
args: ["-c", "stty -echo; printf before-migration; exec cat"],
cwd: process.cwd(),
title: "legacy",
env: {},
})).data,
)
expect(yield* waitForText(base, first.id, "before-migration")).toContain("before-migration")
const legacyHandoff = Schema.decodeUnknownSync(PersistentPty.Handoff)(
(yield* request(base, "POST", "/api/experimental/persistent-pty/handoff")).handoff,
)
yield* Scope.close(originalScope, Exit.void)
const migratedScope = yield* Scope.fork(scope)
const migrated = yield* ServerProcess.start<never, never>({
...options,
pty: { root: fixture.directory, handoff: legacyHandoff },
}).pipe(Effect.provideService(Scope.Scope, migratedScope))
const migratedBase = HttpServer.formatAddress(migrated.address)
const directory = path.join(fixture.directory, path.basename(legacyHandoff.directory))
expect(existsSync(path.join(directory, "service.json"))).toBeTrue()
expect(existsSync(path.join(legacyHandoff.directory, "service.json"))).toBeFalse()
expect(
(yield* request(migratedBase, "GET", `/api/experimental/session/${sessionID}/terminal`)).data,
).toMatchObject([{ id: first.id, pid: first.pid }])
const handoff = Schema.decodeUnknownSync(PersistentPty.Handoff)(
(yield* request(migratedBase, "POST", "/api/experimental/persistent-pty/handoff")).handoff,
)
expect(handoff.directory).toBe(directory)
yield* Scope.close(migratedScope, Exit.void)
// Simulate macOS purging the registration while the daemon waits for its successor.
yield* Effect.promise(() => fs.rm(path.join(directory, "service.json")))
const fresh = yield* ServerProcess.start<never, never>({ ...options, pty: { root: fixture.directory, handoff } })
const freshBase = HttpServer.formatAddress(fresh.address)
expect((yield* request(freshBase, "GET", `/api/experimental/session/${sessionID}/terminal`)).data).toEqual([])
const second = Schema.decodeUnknownSync(PersistentPty.Info)(
(yield* request(freshBase, "POST", `/api/experimental/session/${sessionID}/terminal`, {
command: "/bin/sh",
args: ["-c", "printf after-restart; exec cat"],
cwd: process.cwd(),
title: "fresh",
env: {},
})).data,
)
expect(yield* waitForText(freshBase, second.id, "after-restart")).toContain("after-restart")
}),
30_000,
)
function testDirectory() {
return Effect.acquireRelease(
Effect.promise(async () => {
const environment = {
binary: process.env.OPENCODE_PTY_BIN,
runtime: process.env.OPENCODE_PTY_RUNTIME_DIR,
xdg: process.env.XDG_RUNTIME_DIR,
shell: process.env.SHELL,
}
const environment = { binary: process.env.OPENCODE_PTY_BIN, shell: process.env.SHELL }
const root = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-pty-server-test-"))
const runtime = path.join(root, "runtime")
process.env.OPENCODE_PTY_BIN = binary
delete process.env.OPENCODE_PTY_RUNTIME_DIR
process.env.XDG_RUNTIME_DIR = runtime
process.env.SHELL = "/bin/sh"
if (mode === "override") process.env.OPENCODE_PTY_RUNTIME_DIR = runtime
return {
database: path.join(root, "opencode.db"),
directory: mode === "override" ? runtime : path.join(runtime, "opencode-pty"),
directory: path.join(root, "runtime"),
environment,
root,
}
@@ -412,8 +480,6 @@ function testDirectory(mode: "xdg" | "override") {
Effect.promise(async () => {
await fs.rm(fixture.root, { recursive: true, force: true })
restore("OPENCODE_PTY_BIN", fixture.environment.binary)
restore("OPENCODE_PTY_RUNTIME_DIR", fixture.environment.runtime)
restore("XDG_RUNTIME_DIR", fixture.environment.xdg)
restore("SHELL", fixture.environment.shell)
}),
)