GeezerVison is showing github.com — fix(core): remove a session's terminals when it is deleted (#60322) · jonBoone/opencode@06bf854
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: packages/core/src/persistent-pty/index.ts +34-1Lines changed: 34 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -2,10 +2,11 @@ export * as PersistentPty from "./index.js" | 2 | 2 |
| 3 | 3 | import { stat } from "node:fs/promises" | 4 | 4 | import path from "node:path" | 5 | | -import { Context, Effect, Layer, Schema } from "effect" | | 5 | +import { Context, Effect, Layer, Schema, Stream } from "effect" | 6 | 6 | import { makeGlobalNode } from "@opencode/util/effect/app-node" | 7 | 7 | import { Added, Handoff, PersistentPty, ReadLines, Removed, type ReadResult } from "@opencode/schema/persistent-pty" | 8 | 8 | import { Session } from "@opencode/schema/session" | | 9 | +import { SessionEvent } from "@opencode/schema/session-event" | 9 | 10 | import { Bus } from "../bus.js" | 10 | 11 | import { Pty } from "@opencode/schema/pty" | 11 | 12 | import { Global } from "@opencode/util/global" | @@ -338,6 +339,38 @@ const makeLayer = (options: Options = {}) => | 338 | 339 | ) | 339 | 340 | } | 340 | 341 |
| | 342 | + const removeSession = (sessionID: Session.ID) => | | 343 | + list(sessionID).pipe( | | 344 | + Effect.flatMap((terminals) => | | 345 | + Effect.forEach( | | 346 | + terminals, | | 347 | + (terminal) => | | 348 | + remove(terminal.id).pipe( | | 349 | + Effect.catchTags({ | | 350 | + "PersistentPty.NotFoundError": () => Effect.void, | | 351 | + "PersistentPty.UnavailableError": (error) => | | 352 | + Effect.logWarning("failed to remove deleted session's terminal", { | | 353 | + sessionID, | | 354 | + id: terminal.id, | | 355 | + error: error.message, | | 356 | + }), | | 357 | + }), | | 358 | + ), | | 359 | + { discard: true }, | | 360 | + ), | | 361 | + ), | | 362 | + Effect.catchTag("PersistentPty.UnavailableError", (error) => | | 363 | + Effect.logWarning("failed to list deleted session's terminals", { sessionID, error: error.message }), | | 364 | + ), | | 365 | + Effect.ensuring(Effect.sync(() => current.delete(sessionID))), | | 366 | + ) | | 367 | + | | 368 | + // Errors are handled per event so one failed cleanup does not end the subscription. | | 369 | + yield* bus.subscribe(SessionEvent.Deleted).pipe( | | 370 | + Stream.runForEach((event) => removeSession(event.data.sessionID)), | | 371 | + Effect.forkScoped({ startImmediately: true }), | | 372 | + ) | | 373 | + | 341 | 374 | const attach = Effect.fn("PersistentPty.attach")(function* ( | 342 | 375 | id: Pty.ID, | 343 | 376 | input: Parameters<Interface["attach"]>[1], | |
Collapse file Copy file name to clipboard +123Lines changed: 123 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +import { mkdtemp, rm, writeFile } from "node:fs/promises" | | 2 | +import net from "node:net" | | 3 | +import os from "node:os" | | 4 | +import path from "node:path" | | 5 | +import { Effect } from "effect" | | 6 | + | | 7 | +export const pong = { type: "pong", instance_id: "test", pid: process.pid, protocol: 7 } | | 8 | + | | 9 | +export function temporaryDirectory() { | | 10 | + return Effect.acquireRelease( | | 11 | + Effect.promise(() => mkdtemp(path.join(os.tmpdir(), "opencode-pty-test-"))), | | 12 | + (directory) => Effect.promise(() => rm(directory, { recursive: true, force: true })), | | 13 | + ) | | 14 | +} | | 15 | + | | 16 | +export function listen( | | 17 | + socketPath: string, | | 18 | + handle: (socket: net.Socket, request: Record<string, unknown>, token: string) => object | undefined, | | 19 | +) { | | 20 | + return Effect.acquireRelease( | | 21 | + Effect.promise(async () => { | | 22 | + const sockets = new Set<net.Socket>() | | 23 | + const server = net.createServer((socket) => { | | 24 | + sockets.add(socket) | | 25 | + socket.once("close", () => sockets.delete(socket)) | | 26 | + void readRequest(socket) | | 27 | + .then((envelope) => { | | 28 | + const response = | | 29 | + envelope.request.op === "own" ? { type: "owned" } : handle(socket, envelope.request, envelope.token) | | 30 | + if (response) socket.write(frame(response)) | | 31 | + }) | | 32 | + .catch(() => socket.destroy()) | | 33 | + }) | | 34 | + await new Promise<void>((resolve, reject) => { | | 35 | + server.once("error", reject) | | 36 | + server.listen(socketPath, resolve) | | 37 | + }) | | 38 | + return { | | 39 | + close: () => { | | 40 | + sockets.forEach((socket) => socket.destroy()) | | 41 | + return close(server) | | 42 | + }, | | 43 | + } | | 44 | + }), | | 45 | + (server) => Effect.promise(server.close), | | 46 | + ) | | 47 | +} | | 48 | + | | 49 | +function readRequest(socket: net.Socket) { | | 50 | + return new Promise<Buffer>((resolve, reject) => { | | 51 | + let pending = Buffer.alloc(0) | | 52 | + const cleanup = () => { | | 53 | + socket.off("data", onData) | | 54 | + socket.off("end", onEnd) | | 55 | + socket.off("error", onError) | | 56 | + } | | 57 | + const onData = (value: Buffer) => { | | 58 | + pending = Buffer.concat([pending, value]) | | 59 | + if (pending.length < 4) return | | 60 | + const length = pending.readUInt32BE(0) | | 61 | + if (pending.length < length + 4) return | | 62 | + cleanup() | | 63 | + resolve(pending.subarray(4, length + 4)) | | 64 | + } | | 65 | + const onEnd = () => { | | 66 | + cleanup() | | 67 | + reject(new Error("connection closed before request")) | | 68 | + } | | 69 | + const onError = (error: Error) => { | | 70 | + cleanup() | | 71 | + reject(error) | | 72 | + } | | 73 | + socket.on("data", onData) | | 74 | + socket.on("end", onEnd) | | 75 | + socket.on("error", onError) | | 76 | + }).then((payload) => { | | 77 | + const envelope: unknown = JSON.parse(payload.toString("utf8")) | | 78 | + if (!isRecord(envelope) || typeof envelope.token !== "string" || !isRecord(envelope.request)) | | 79 | + throw new Error("Invalid test daemon envelope") | | 80 | + return { token: envelope.token, request: envelope.request } | | 81 | + }) | | 82 | +} | | 83 | + | | 84 | +function frame(value: object) { | | 85 | + const payload = Buffer.from(JSON.stringify(value)) | | 86 | + const output = Buffer.allocUnsafe(payload.length + 4) | | 87 | + output.writeUInt32BE(payload.length) | | 88 | + payload.copy(output, 4) | | 89 | + return output | | 90 | +} | | 91 | + | | 92 | +export function writeRegistration(directory: string, socket: string, instance = "test", token = "test") { | | 93 | + return writeFile( | | 94 | + path.join(directory, "service.json"), | | 95 | + JSON.stringify({ instance_id: instance, pid: process.pid, protocol: 7, socket, token }), | | 96 | + ) | | 97 | +} | | 98 | + | | 99 | +export function terminal(id: number, groupID = "ses_test") { | | 100 | + return { | | 101 | + id, | | 102 | + pid: null, | | 103 | + title: "test", | | 104 | + foreground_process: null, | | 105 | + group_id: groupID, | | 106 | + command: ["test"], | | 107 | + cwd: "/tmp", | | 108 | + cols: 80, | | 109 | + rows: 24, | | 110 | + lifecycle: { status: "running" }, | | 111 | + output_head: 0, | | 112 | + output_tail: 0, | | 113 | + } | | 114 | +} | | 115 | + | | 116 | +function close(server: net.Server) { | | 117 | + if (!server.listening) return Promise.resolve() | | 118 | + return new Promise<void>((resolve, reject) => server.close((error) => (error ? reject(error) : resolve()))) | | 119 | +} | | 120 | + | | 121 | +function isRecord(value: unknown): value is Record<string, unknown> { | | 122 | + return typeof value === "object" && value !== null && !Array.isArray(value) | | 123 | +} |
Collapse file Copy file name to clipboardExpand all lines: packages/core/test/persistent-pty-daemon.test.ts +2-121Lines changed: 2 additions & 121 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 1 | 1 | import { expect } from "bun:test" | 2 | 2 | import { spawn } from "node:child_process" | 3 | 3 | import { existsSync } from "node:fs" | 4 | | -import { mkdir, mkdtemp, rm, stat, writeFile } from "node:fs/promises" | 5 | | -import net from "node:net" | 6 | | -import os from "node:os" | | 4 | +import { mkdir, stat, writeFile } from "node:fs/promises" | 7 | 5 | import path from "node:path" | 8 | 6 | import { Effect } from "effect" | 9 | 7 | import { makeDaemonTransport } from "../src/persistent-pty/daemon" | | 8 | +import { listen, pong, temporaryDirectory, terminal, writeRegistration } from "./fixture/persistent-pty-daemon" | 10 | 9 | import { it } from "./lib/effect" | 11 | 10 |
| 12 | | -const pong = { type: "pong", instance_id: "test", pid: process.pid, protocol: 7 } | 13 | | - | 14 | 11 | it.live("rediscovers a same-protocol daemon after its registration rotates", () => | 15 | 12 | Effect.gen(function* () { | 16 | 13 | const { root, directory } = yield* temporaryRuntime() | @@ -248,119 +245,3 @@ function temporaryRuntime() { | 248 | 245 | return { root, directory } | 249 | 246 | }) | 250 | 247 | } | 251 | | - | 252 | | -function temporaryDirectory() { | 253 | | - return Effect.acquireRelease( | 254 | | - Effect.promise(() => mkdtemp(path.join(os.tmpdir(), "opencode-pty-test-"))), | 255 | | - (directory) => Effect.promise(() => rm(directory, { recursive: true, force: true })), | 256 | | - ) | 257 | | -} | 258 | | - | 259 | | -function listen( | 260 | | - socketPath: string, | 261 | | - handle: (socket: net.Socket, request: Record<string, unknown>, token: string) => object | undefined, | 262 | | -) { | 263 | | - return Effect.acquireRelease( | 264 | | - Effect.promise(async () => { | 265 | | - const sockets = new Set<net.Socket>() | 266 | | - const server = net.createServer((socket) => { | 267 | | - sockets.add(socket) | 268 | | - socket.once("close", () => sockets.delete(socket)) | 269 | | - void readRequest(socket) | 270 | | - .then((envelope) => { | 271 | | - const response = | 272 | | - envelope.request.op === "own" ? { type: "owned" } : handle(socket, envelope.request, envelope.token) | 273 | | - if (response) socket.write(frame(response)) | 274 | | - }) | 275 | | - .catch(() => socket.destroy()) | 276 | | - }) | 277 | | - await new Promise<void>((resolve, reject) => { | 278 | | - server.once("error", reject) | 279 | | - server.listen(socketPath, resolve) | 280 | | - }) | 281 | | - return { | 282 | | - close: () => { | 283 | | - sockets.forEach((socket) => socket.destroy()) | 284 | | - return close(server) | 285 | | - }, | 286 | | - } | 287 | | - }), | 288 | | - (server) => Effect.promise(server.close), | 289 | | - ) | 290 | | -} | 291 | | - | 292 | | -function readRequest(socket: net.Socket) { | 293 | | - return new Promise<Buffer>((resolve, reject) => { | 294 | | - let pending = Buffer.alloc(0) | 295 | | - const cleanup = () => { | 296 | | - socket.off("data", onData) | 297 | | - socket.off("end", onEnd) | 298 | | - socket.off("error", onError) | 299 | | - } | 300 | | - const onData = (value: Buffer) => { | 301 | | - pending = Buffer.concat([pending, value]) | 302 | | - if (pending.length < 4) return | 303 | | - const length = pending.readUInt32BE(0) | 304 | | - if (pending.length < length + 4) return | 305 | | - cleanup() | 306 | | - resolve(pending.subarray(4, length + 4)) | 307 | | - } | 308 | | - const onEnd = () => { | 309 | | - cleanup() | 310 | | - reject(new Error("connection closed before request")) | 311 | | - } | 312 | | - const onError = (error: Error) => { | 313 | | - cleanup() | 314 | | - reject(error) | 315 | | - } | 316 | | - socket.on("data", onData) | 317 | | - socket.on("end", onEnd) | 318 | | - socket.on("error", onError) | 319 | | - }).then((payload) => { | 320 | | - const envelope: unknown = JSON.parse(payload.toString("utf8")) | 321 | | - if (!isRecord(envelope) || typeof envelope.token !== "string" || !isRecord(envelope.request)) | 322 | | - throw new Error("Invalid test daemon envelope") | 323 | | - return { token: envelope.token, request: envelope.request } | 324 | | - }) | 325 | | -} | 326 | | - | 327 | | -function frame(value: object) { | 328 | | - const payload = Buffer.from(JSON.stringify(value)) | 329 | | - const output = Buffer.allocUnsafe(payload.length + 4) | 330 | | - output.writeUInt32BE(payload.length) | 331 | | - payload.copy(output, 4) | 332 | | - return output | 333 | | -} | 334 | | - | 335 | | -function writeRegistration(directory: string, socket: string, instance = "test", token = "test") { | 336 | | - return writeFile( | 337 | | - path.join(directory, "service.json"), | 338 | | - JSON.stringify({ instance_id: instance, pid: process.pid, protocol: 7, socket, token }), | 339 | | - ) | 340 | | -} | 341 | | - | 342 | | -function terminal(id: number) { | 343 | | - return { | 344 | | - id, | 345 | | - pid: null, | 346 | | - title: "test", | 347 | | - foreground_process: null, | 348 | | - group_id: "ses_test", | 349 | | - command: ["test"], | 350 | | - cwd: "/tmp", | 351 | | - cols: 80, | 352 | | - rows: 24, | 353 | | - lifecycle: { status: "running" }, | 354 | | - output_head: 0, | 355 | | - output_tail: 0, | 356 | | - } | 357 | | -} | 358 | | - | 359 | | -function close(server: net.Server) { | 360 | | - if (!server.listening) return Promise.resolve() | 361 | | - return new Promise<void>((resolve, reject) => server.close((error) => (error ? reject(error) : resolve()))) | 362 | | -} | 363 | | - | 364 | | -function isRecord(value: unknown): value is Record<string, unknown> { | 365 | | - return typeof value === "object" && value !== null && !Array.isArray(value) | 366 | | -} |
|