The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | // @effect-diagnostics nodeBuiltinImport:off |
| 2 | import * as NodeChildProcess from "node:child_process"; |
| 3 | import * as NodeReadline from "node:readline"; |
| 4 | |
| 5 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 6 | import { describe, expect, it } from "@effect/vitest"; |
| 7 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 8 | import * as Deferred from "effect/Deferred"; |
| 9 | import * as Effect from "effect/Effect"; |
| 10 | import * as Exit from "effect/Exit"; |
| 11 | import * as Fiber from "effect/Fiber"; |
| 12 | import * as FileSystem from "effect/FileSystem"; |
| 13 | import * as Layer from "effect/Layer"; |
| 14 | import * as Path from "effect/Path"; |
| 15 | import * as Scope from "effect/Scope"; |
| 16 | import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; |
| 17 | |
| 18 | import * as OpenCodeRuntime from "./OpenCodeRuntime.ts"; |
| 19 | import * as OpenCodeServerLedger from "./OpenCodeServerLedger.ts"; |
| 20 | |
| 21 | const SERVE_ARGS = ["serve", "--hostname=127.0.0.1", "--port=4096"]; |
| 22 | |
| 23 | const groupExists = (pgid: number) => { |
| 24 | try { |
| 25 | process.kill(-pgid, 0); |
| 26 | return true; |
| 27 | } catch { |
| 28 | return false; |
| 29 | } |
| 30 | }; |
| 31 | |
| 32 | // A group of zombies can be reaped between a check and the kill, so ESRCH just means it is gone. |
| 33 | const killGroup = (pgid: number) => |
| 34 | Effect.sync(() => { |
| 35 | try { |
| 36 | process.kill(-pgid, "SIGKILL"); |
| 37 | } catch (cause) { |
| 38 | if (!(cause instanceof Error && "code" in cause && cause.code === "ESRCH")) throw cause; |
| 39 | } |
| 40 | }); |
| 41 | |
| 42 | // libuv ignores a failed setsid(), which happens when the new pid equals the id of a group |
| 43 | // that still has members (such as a sleep orphaned by an earlier test). The child would then |
| 44 | // share the test worker's group, so the script first confirms it leads its own group and exits |
| 45 | // with 97 before starting anything if it does not. |
| 46 | const groupLeaderGuard = `pgid="$(ps -o pgid= -p $$ 2>&1 | tr -d ' ')"; [ "$pgid" = "$$" ] || { echo "ungrouped:$pgid"; exit 97; }; echo grouped; `; |
| 47 | |
| 48 | // Yields the group, or a description of why this shell cannot be used as one. |
| 49 | const spawnGroupLeader = (args: ReadonlyArray<string>, script: string) => |
| 50 | Effect.gen(function* () { |
| 51 | const child = NodeChildProcess.spawn("/bin/sh", ["-c", groupLeaderGuard + script, ...args], { |
| 52 | detached: true, |
| 53 | stdio: ["ignore", "pipe", "ignore"], |
| 54 | }); |
| 55 | const pid = child.pid; |
| 56 | if (pid === undefined) return yield* Effect.die("spawn failed"); |
| 57 | const grouped = yield* Deferred.make<true | string>(); |
| 58 | const exited = yield* Deferred.make<NodeJS.Signals | null>(); |
| 59 | child.once("exit", (_code, signal) => Deferred.doneUnsafe(exited, Effect.succeed(signal))); |
| 60 | // "close" fires after stdout drains, so a guard line always lands first. It only fires before |
| 61 | // "grouped" when the shell died without starting the script, such as from a signal. |
| 62 | child.once("close", (code, signal) => |
| 63 | Deferred.doneUnsafe( |
| 64 | grouped, |
| 65 | Effect.succeed( |
| 66 | `shell ${pid} exited (code ${code}, signal ${signal}) before its group check`, |
| 67 | ), |
| 68 | ), |
| 69 | ); |
| 70 | NodeReadline.createInterface({ input: child.stdout }).on("line", (line) => { |
| 71 | if (line === "grouped") Deferred.doneUnsafe(grouped, Effect.succeed(true)); |
| 72 | if (line.startsWith("ungrouped:")) { |
| 73 | const output = line.slice("ungrouped:".length); |
| 74 | Deferred.doneUnsafe( |
| 75 | grouped, |
| 76 | Effect.succeed(`\`ps -o pgid= -p ${pid}\` printed ${JSON.stringify(output)}`), |
| 77 | ); |
| 78 | } |
| 79 | }); |
| 80 | const result = yield* Deferred.await(grouped); |
| 81 | return result === true ? { pid, exited: Deferred.await(exited) } : result; |
| 82 | }); |
| 83 | |
| 84 | // A pid colliding with a live group id is rare, so a few retries clear it. Repeated failures |
| 85 | // mean the guard itself is broken (for example a missing or BusyBox `ps`). |
| 86 | const GROUP_LEADER_ATTEMPTS = 5; |
| 87 | |
| 88 | const spawnGroup = (args: ReadonlyArray<string>, script = "sleep 600 & wait") => |
| 89 | Effect.acquireRelease( |
| 90 | Effect.gen(function* () { |
| 91 | let failure = ""; |
| 92 | for (let attempt = 0; attempt < GROUP_LEADER_ATTEMPTS; attempt++) { |
| 93 | const group = yield* spawnGroupLeader(args, script); |
| 94 | if (typeof group !== "string") return group; |
| 95 | failure = group; |
| 96 | } |
| 97 | return yield* Effect.die( |
| 98 | `no shell led its own process group after ${GROUP_LEADER_ATTEMPTS} attempts; last: ${failure}`, |
| 99 | ); |
| 100 | }), |
| 101 | ({ pid }) => killGroup(pid), |
| 102 | ); |
| 103 | |
| 104 | const recordFromDeadServer = (stateDir: string, server: { readonly pid: number }) => |
| 105 | Effect.gen(function* () { |
| 106 | const previousServer = yield* spawnGroup([]); |
| 107 | const previousLedger = yield* OpenCodeServerLedger.make({ |
| 108 | stateDir, |
| 109 | ownerPid: previousServer.pid, |
| 110 | }); |
| 111 | yield* Effect.asVoid(previousLedger.track({ pid: server.pid, port: 4096, args: SERVE_ARGS })); |
| 112 | yield* killGroup(previousServer.pid); |
| 113 | yield* previousServer.exited; |
| 114 | }); |
| 115 | |
| 116 | const hostPlatform = HostProcess.Platform.defaultValue(); |
| 117 | // procps accepts the same `ps` flags as macOS, so Linux also covers the macOS path. |
| 118 | const observedPlatforms: ReadonlyArray<NodeJS.Platform> = |
| 119 | hostPlatform === "linux" ? ["linux", "darwin"] : hostPlatform === "darwin" ? ["darwin"] : []; |
| 120 | |
| 121 | describe.each(observedPlatforms)("OpenCodeServerLedger observing as %s", (platform) => { |
| 122 | const provideHost = <A, E, R>(effect: Effect.Effect<A, E, R>) => |
| 123 | effect.pipe( |
| 124 | Effect.provideService(HostProcess.Platform, platform), |
| 125 | Effect.provide(NodeServices.layer), |
| 126 | ); |
| 127 | |
| 128 | it.live("stops an OpenCode server group left by a server that died", () => |
| 129 | Effect.gen(function* () { |
| 130 | const fs = yield* FileSystem.FileSystem; |
| 131 | const path = yield* Path.Path; |
| 132 | const stateDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-opencode-ledger-" }); |
| 133 | const orphan = yield* spawnGroup(SERVE_ARGS); |
| 134 | yield* recordFromDeadServer(stateDir, orphan); |
| 135 | expect(yield* fs.readDirectory(path.join(stateDir, "opencode-servers"))).toHaveLength(1); |
| 136 | |
| 137 | const restarted = yield* OpenCodeServerLedger.make({ stateDir }); |
| 138 | yield* restarted.reapOrphans; |
| 139 | |
| 140 | expect(yield* orphan.exited).toBe("SIGTERM"); |
| 141 | expect(groupExists(orphan.pid)).toBe(false); |
| 142 | expect(yield* fs.readDirectory(path.join(stateDir, "opencode-servers"))).toEqual([]); |
| 143 | }).pipe(provideHost), |
| 144 | ); |
| 145 | |
| 146 | it.live("records a group whose spawned wrapper already exited", () => |
| 147 | Effect.gen(function* () { |
| 148 | const fs = yield* FileSystem.FileSystem; |
| 149 | const path = yield* Path.Path; |
| 150 | const stateDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-opencode-ledger-" }); |
| 151 | const gate = path.join(stateDir, "gate"); |
| 152 | const ready = path.join(stateDir, "ready"); |
| 153 | NodeChildProcess.execFileSync("mkfifo", [gate, ready]); |
| 154 | // The wrapper's child is recorded before it execs and stopped after. |
| 155 | const wrapper = yield* spawnGroup( |
| 156 | SERVE_ARGS, |
| 157 | `(read _ < '${gate}'; exec /bin/sh -c 'echo > "${ready}"; sleep 600 & wait' "$0" "$@") & exit 0`, |
| 158 | ); |
| 159 | yield* wrapper.exited; |
| 160 | expect(groupExists(wrapper.pid)).toBe(true); |
| 161 | |
| 162 | yield* recordFromDeadServer(stateDir, wrapper); |
| 163 | expect(yield* fs.readDirectory(path.join(stateDir, "opencode-servers"))).toHaveLength(1); |
| 164 | yield* fs.writeFileString(gate, "\n"); |
| 165 | yield* fs.readFileString(ready); |
| 166 | |
| 167 | const restarted = yield* OpenCodeServerLedger.make({ stateDir }); |
| 168 | yield* restarted.reapOrphans; |
| 169 | |
| 170 | expect(groupExists(wrapper.pid)).toBe(false); |
| 171 | expect(yield* fs.readDirectory(path.join(stateDir, "opencode-servers"))).toEqual([]); |
| 172 | }).pipe(provideHost), |
| 173 | ); |
| 174 | |
| 175 | it.live("stops a group recorded by an older server without serve arguments", () => |
| 176 | Effect.gen(function* () { |
| 177 | const fs = yield* FileSystem.FileSystem; |
| 178 | const path = yield* Path.Path; |
| 179 | const stateDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-opencode-ledger-" }); |
| 180 | const orphan = yield* spawnGroup(SERVE_ARGS); |
| 181 | yield* recordFromDeadServer(stateDir, orphan); |
| 182 | const entryPath = path.join(stateDir, "opencode-servers", `${orphan.pid}.json`); |
| 183 | const { args: _args, ...legacy } = JSON.parse(yield* fs.readFileString(entryPath)); |
| 184 | yield* fs.writeFileString(entryPath, JSON.stringify(legacy)); |
| 185 | |
| 186 | const restarted = yield* OpenCodeServerLedger.make({ stateDir }); |
| 187 | yield* restarted.reapOrphans; |
| 188 | |
| 189 | expect(groupExists(orphan.pid)).toBe(false); |
| 190 | }).pipe(provideHost), |
| 191 | ); |
| 192 | |
| 193 | it.live("stops a group whose wrapper appends its own options", () => |
| 194 | Effect.gen(function* () { |
| 195 | const fs = yield* FileSystem.FileSystem; |
| 196 | const stateDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-opencode-ledger-" }); |
| 197 | const orphan = yield* spawnGroup([...SERVE_ARGS, "--log-level=ERROR"]); |
| 198 | yield* recordFromDeadServer(stateDir, orphan); |
| 199 | |
| 200 | const restarted = yield* OpenCodeServerLedger.make({ stateDir }); |
| 201 | yield* restarted.reapOrphans; |
| 202 | |
| 203 | expect(groupExists(orphan.pid)).toBe(false); |
| 204 | }).pipe(provideHost), |
| 205 | ); |
| 206 | |
| 207 | it.live("leaves a recycled pid alone when its start time does not match", () => |
| 208 | Effect.gen(function* () { |
| 209 | const fs = yield* FileSystem.FileSystem; |
| 210 | const path = yield* Path.Path; |
| 211 | const stateDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-opencode-ledger-" }); |
| 212 | const unrelated = yield* spawnGroup(SERVE_ARGS); |
| 213 | yield* recordFromDeadServer(stateDir, unrelated); |
| 214 | const entryPath = path.join(stateDir, "opencode-servers", `${unrelated.pid}.json`); |
| 215 | const entry = yield* fs.readFileString(entryPath); |
| 216 | yield* fs.writeFileString(entryPath, entry.replace(/"startTime":"[^"]+"/, '"startTime":"1"')); |
| 217 | |
| 218 | const restarted = yield* OpenCodeServerLedger.make({ stateDir }); |
| 219 | yield* restarted.reapOrphans; |
| 220 | |
| 221 | expect(groupExists(unrelated.pid)).toBe(true); |
| 222 | expect(yield* fs.exists(entryPath)).toBe(false); |
| 223 | }).pipe(provideHost), |
| 224 | ); |
| 225 | |
| 226 | it.live("leaves a serve process on another port alone", () => |
| 227 | Effect.gen(function* () { |
| 228 | const fs = yield* FileSystem.FileSystem; |
| 229 | const path = yield* Path.Path; |
| 230 | const stateDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-opencode-ledger-" }); |
| 231 | const unrelated = yield* spawnGroup(SERVE_ARGS); |
| 232 | yield* recordFromDeadServer(stateDir, unrelated); |
| 233 | const entryPath = path.join(stateDir, "opencode-servers", `${unrelated.pid}.json`); |
| 234 | const entry = yield* fs.readFileString(entryPath); |
| 235 | yield* fs.writeFileString(entryPath, entry.replaceAll("--port=4096", "--port=4097")); |
| 236 | |
| 237 | const restarted = yield* OpenCodeServerLedger.make({ stateDir }); |
| 238 | yield* restarted.reapOrphans; |
| 239 | |
| 240 | expect(groupExists(unrelated.pid)).toBe(true); |
| 241 | expect(yield* fs.exists(entryPath)).toBe(false); |
| 242 | }).pipe(provideHost), |
| 243 | ); |
| 244 | |
| 245 | it.live("leaves the servers of a running T3 server alone", () => |
| 246 | Effect.gen(function* () { |
| 247 | const fs = yield* FileSystem.FileSystem; |
| 248 | const path = yield* Path.Path; |
| 249 | const stateDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-opencode-ledger-" }); |
| 250 | const running = yield* OpenCodeServerLedger.make({ stateDir }); |
| 251 | const server = yield* spawnGroup(SERVE_ARGS); |
| 252 | const forget = yield* running.track({ pid: server.pid, port: 4096, args: SERVE_ARGS }); |
| 253 | |
| 254 | const other = yield* OpenCodeServerLedger.make({ stateDir }); |
| 255 | yield* other.reapOrphans; |
| 256 | expect(groupExists(server.pid)).toBe(true); |
| 257 | |
| 258 | yield* forget; |
| 259 | expect(yield* fs.readDirectory(path.join(stateDir, "opencode-servers"))).toEqual([]); |
| 260 | }).pipe(provideHost), |
| 261 | ); |
| 262 | }); |
| 263 | |
| 264 | describe.skipIf(observedPlatforms.length === 0)("OpenCode server startup", () => { |
| 265 | it.live("stops the group when interrupted while the server is being recorded", () => |
| 266 | Effect.gen(function* () { |
| 267 | const fs = yield* FileSystem.FileSystem; |
| 268 | const path = yield* Path.Path; |
| 269 | const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-opencode-startup-" }); |
| 270 | const binaryPath = path.join(tempDir, "opencode"); |
| 271 | yield* fs.writeFileString(binaryPath, "#!/bin/sh\nsleep 600 &\nexit 0\n"); |
| 272 | yield* fs.chmod(binaryPath, 0o755); |
| 273 | |
| 274 | const spawned = yield* Deferred.make<ChildProcessSpawner.ChildProcessHandle>(); |
| 275 | const recording = yield* Deferred.make<number>(); |
| 276 | const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 277 | const layerRuntime = OpenCodeRuntime.layer.pipe( |
| 278 | Layer.provide( |
| 279 | Layer.succeed( |
| 280 | ChildProcessSpawner.ChildProcessSpawner, |
| 281 | ChildProcessSpawner.make((command) => |
| 282 | spawner |
| 283 | .spawn(command) |
| 284 | .pipe(Effect.tap((handle) => Deferred.succeed(spawned, handle))), |
| 285 | ), |
| 286 | ), |
| 287 | ), |
| 288 | Layer.provide( |
| 289 | Layer.succeed( |
| 290 | OpenCodeServerLedger.OpenCodeServerLedger, |
| 291 | OpenCodeServerLedger.OpenCodeServerLedger.of({ |
| 292 | track: (server) => |
| 293 | Effect.gen(function* () { |
| 294 | yield* (yield* Deferred.await(spawned)).exitCode.pipe(Effect.ignore); |
| 295 | yield* Deferred.succeed(recording, server.pid); |
| 296 | return yield* Effect.never; |
| 297 | }), |
| 298 | }), |
| 299 | ), |
| 300 | ), |
| 301 | ); |
| 302 | |
| 303 | const serverScope = yield* Scope.make(); |
| 304 | const starting = yield* OpenCodeRuntime.OpenCodeRuntime.pipe( |
| 305 | Effect.flatMap((runtime) => |
| 306 | runtime.startOpenCodeServerProcess({ binaryPath, directory: tempDir, port: 4096 }), |
| 307 | ), |
| 308 | Effect.provideService(Scope.Scope, serverScope), |
| 309 | Effect.provide(layerRuntime), |
| 310 | Effect.forkChild, |
| 311 | ); |
| 312 | const pgid = yield* Deferred.await(recording); |
| 313 | yield* Effect.addFinalizer(() => killGroup(pgid)); |
| 314 | expect(groupExists(pgid)).toBe(true); |
| 315 | |
| 316 | yield* Fiber.interrupt(starting); |
| 317 | yield* Scope.close(serverScope, Exit.void); |
| 318 | |
| 319 | expect(groupExists(pgid)).toBe(false); |
| 320 | }).pipe(Effect.provide(NodeServices.layer)), |
| 321 | ); |
| 322 | |
| 323 | // Runs on the test clock, which never advances here: a teardown that sleeps |
| 324 | // out its grace instead of watching the group would never finish. |
| 325 | it.effect("stops a running server as soon as its group exits", () => |
| 326 | Effect.gen(function* () { |
| 327 | const fs = yield* FileSystem.FileSystem; |
| 328 | const path = yield* Path.Path; |
| 329 | const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-opencode-stop-" }); |
| 330 | const binaryPath = path.join(tempDir, "opencode"); |
| 331 | // The background child shares the leader's group. The leader reaps it before exiting, so no |
| 332 | // zombie keeps the group alive under an init that does not reap. The trap is set after the |
| 333 | // fork: a child forked with the trap already set can swallow the signal before it execs. |
| 334 | yield* fs.writeFileString( |
| 335 | binaryPath, |
| 336 | [ |
| 337 | "#!/bin/sh", |
| 338 | "sleep 600 &", |
| 339 | "trap 'wait; exit 0' TERM", |
| 340 | 'echo "opencode server listening on http://127.0.0.1:4096"', |
| 341 | "wait", |
| 342 | "", |
| 343 | ].join("\n"), |
| 344 | ); |
| 345 | yield* fs.chmod(binaryPath, 0o755); |
| 346 | |
| 347 | const tracked = yield* Deferred.make<number>(); |
| 348 | const layerRuntime = OpenCodeRuntime.layer.pipe( |
| 349 | Layer.provide( |
| 350 | Layer.succeed( |
| 351 | OpenCodeServerLedger.OpenCodeServerLedger, |
| 352 | OpenCodeServerLedger.OpenCodeServerLedger.of({ |
| 353 | track: (server) => Deferred.succeed(tracked, server.pid).pipe(Effect.as(Effect.void)), |
| 354 | }), |
| 355 | ), |
| 356 | ), |
| 357 | ); |
| 358 | |
| 359 | const serverScope = yield* Scope.make(); |
| 360 | const server = yield* OpenCodeRuntime.OpenCodeRuntime.pipe( |
| 361 | Effect.flatMap((runtime) => |
| 362 | runtime.startOpenCodeServerProcess({ |
| 363 | binaryPath, |
| 364 | directory: tempDir, |
| 365 | port: 4096, |
| 366 | verify: () => Effect.succeed("1.0.0"), |
| 367 | }), |
| 368 | ), |
| 369 | Effect.provideService(Scope.Scope, serverScope), |
| 370 | Effect.provide(layerRuntime), |
| 371 | ); |
| 372 | const pgid = yield* Deferred.await(tracked); |
| 373 | yield* Effect.addFinalizer(() => killGroup(pgid)); |
| 374 | expect(yield* server.isRunning).toBe(true); |
| 375 | |
| 376 | yield* Scope.close(serverScope, Exit.void); |
| 377 | |
| 378 | expect(groupExists(pgid)).toBe(false); |
| 379 | }).pipe(Effect.provide(NodeServices.layer)), |
| 380 | ); |
| 381 | }); |