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, 03:37 UTC
| 1 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 2 | import { expect, it } from "@effect/vitest"; |
| 3 | import type { ManagedPolicyDocument } from "@t3tools/contracts"; |
| 4 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 5 | import * as Deferred from "effect/Deferred"; |
| 6 | import * as Duration from "effect/Duration"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as FileSystem from "effect/FileSystem"; |
| 9 | import * as Fiber from "effect/Fiber"; |
| 10 | import * as Layer from "effect/Layer"; |
| 11 | import * as Path from "effect/Path"; |
| 12 | import * as Stream from "effect/Stream"; |
| 13 | import * as TestClock from "effect/testing/TestClock"; |
| 14 | import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; |
| 15 | import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; |
| 16 | |
| 17 | import packageJson from "../../package.json" with { type: "json" }; |
| 18 | import * as ServerConfig from "../config.ts"; |
| 19 | import * as DesktopAppUpdate from "../desktopUpdate/DesktopAppUpdate.ts"; |
| 20 | import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; |
| 21 | import * as ProcessRunner from "../processRunner.ts"; |
| 22 | import * as ServiceLauncherClient from "./serviceLauncherClient.ts"; |
| 23 | import { SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts"; |
| 24 | import * as ServerSelfUpdate from "./selfUpdate.ts"; |
| 25 | |
| 26 | interface HarnessOptions { |
| 27 | readonly mode?: "web" | "desktop"; |
| 28 | readonly managed?: boolean; |
| 29 | readonly launcherProtocol?: 3 | typeof SERVICE_LAUNCHER_PROTOCOL; |
| 30 | readonly preflight?: "ready" | "blocked"; |
| 31 | readonly preflightDuration?: Duration.Input; |
| 32 | readonly preflightStarted?: Deferred.Deferred<void>; |
| 33 | readonly beforeDownload?: Effect.Effect<void>; |
| 34 | readonly httpClient?: HttpClient.HttpClient; |
| 35 | readonly requestUpdate?: ServiceLauncherClient.ServiceLauncherClient["Service"]["requestUpdate"]; |
| 36 | readonly desktopAppUpdate?: DesktopAppUpdate.DesktopAppUpdate["Service"]; |
| 37 | readonly policy?: ManagedPolicyDocument; |
| 38 | } |
| 39 | |
| 40 | const archiveBytes = new TextEncoder().encode("not really a tarball"); |
| 41 | const releaseHttpClient = (order: string[], urls: string[], beforeDownload?: Effect.Effect<void>) => |
| 42 | HttpClient.make((request) => |
| 43 | Effect.gen(function* () { |
| 44 | urls.push(request.url); |
| 45 | if (request.url.endsWith("/SHA256SUMS")) { |
| 46 | const digest = yield* Effect.promise(() => crypto.subtle.digest("SHA-256", archiveBytes)); |
| 47 | const hex = Array.from(new Uint8Array(digest), (byte) => |
| 48 | byte.toString(16).padStart(2, "0"), |
| 49 | ).join(""); |
| 50 | return HttpClientResponse.fromWeb( |
| 51 | request, |
| 52 | new Response(`${hex} t3-1.1.0-linux-x64.tar.gz\n`), |
| 53 | ); |
| 54 | } |
| 55 | if (beforeDownload) yield* beforeDownload; |
| 56 | order.push("download"); |
| 57 | return HttpClientResponse.fromWeb(request, new Response(archiveBytes)); |
| 58 | }), |
| 59 | ); |
| 60 | |
| 61 | const makeHarness = Effect.fn("test.make_self_update_harness")(function* ( |
| 62 | options: HarnessOptions = {}, |
| 63 | ) { |
| 64 | const fs = yield* FileSystem.FileSystem; |
| 65 | const path = yield* Path.Path; |
| 66 | const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-self-update-test-" }); |
| 67 | const order: string[] = []; |
| 68 | const urls: string[] = []; |
| 69 | const preflightProtocols: Array<string | undefined> = []; |
| 70 | const runner = ProcessRunner.ProcessRunner.of({ |
| 71 | run: (input) => |
| 72 | Effect.gen(function* () { |
| 73 | if (input.command === "busctl") { |
| 74 | // No user bus: the unit directory falls back to XDG_CONFIG_HOME or ~/.config. |
| 75 | return { |
| 76 | stdout: "", |
| 77 | stderr: "", |
| 78 | code: ChildProcessSpawner.ExitCode(1), |
| 79 | timedOut: false, |
| 80 | stdoutTruncated: false, |
| 81 | stderrTruncated: false, |
| 82 | stdoutInvalidUtf8: false, |
| 83 | stderrInvalidUtf8: false, |
| 84 | }; |
| 85 | } |
| 86 | if (input.command === "tar") { |
| 87 | order.push("extract"); |
| 88 | const stagingDir = input.args[input.args.indexOf("-C") + 1]; |
| 89 | if (stagingDir === undefined) return yield* Effect.die("missing tar target"); |
| 90 | yield* fs.writeFileString(path.join(stagingDir, "t3"), "#!/bin/sh\n").pipe(Effect.orDie); |
| 91 | return { |
| 92 | stdout: "", |
| 93 | stderr: "", |
| 94 | code: ChildProcessSpawner.ExitCode(0), |
| 95 | timedOut: false, |
| 96 | stdoutTruncated: false, |
| 97 | stderrTruncated: false, |
| 98 | stdoutInvalidUtf8: false, |
| 99 | stderrInvalidUtf8: false, |
| 100 | }; |
| 101 | } |
| 102 | if (options.preflightStarted) yield* Deferred.succeed(options.preflightStarted, undefined); |
| 103 | if (options.preflightDuration !== undefined) { |
| 104 | // Like the real runner, fail once the caller's timeout elapses. |
| 105 | const timeout = Duration.fromInputUnsafe(input.timeout ?? "60 seconds"); |
| 106 | const finished = yield* Effect.sleep(options.preflightDuration).pipe( |
| 107 | Effect.timeoutOption(timeout), |
| 108 | ); |
| 109 | if (finished._tag === "None") { |
| 110 | return yield* new ProcessRunner.ProcessTimeoutError({ |
| 111 | command: input.command, |
| 112 | argumentCount: input.args.length, |
| 113 | timeoutMs: Duration.toMillis(timeout), |
| 114 | }); |
| 115 | } |
| 116 | } |
| 117 | order.push("preflight"); |
| 118 | // Like a release, report back the launcher protocol the server named. |
| 119 | const named = input.args[input.args.indexOf("--launcher-protocol") + 1]; |
| 120 | preflightProtocols.push(named); |
| 121 | const result = |
| 122 | options.preflight === "blocked" |
| 123 | ? { status: "blocked", version: "1.1.0", reason: "local update required" } |
| 124 | : { status: "ready", version: "1.1.0", launcherProtocol: Number(named) }; |
| 125 | return { |
| 126 | stdout: JSON.stringify(result), |
| 127 | stderr: "", |
| 128 | code: ChildProcessSpawner.ExitCode(0), |
| 129 | timedOut: false, |
| 130 | stdoutTruncated: false, |
| 131 | stderrTruncated: false, |
| 132 | stdoutInvalidUtf8: false, |
| 133 | stderrInvalidUtf8: false, |
| 134 | }; |
| 135 | }), |
| 136 | }); |
| 137 | const managed = options.managed ?? true; |
| 138 | const launcher = ServiceLauncherClient.ServiceLauncherClient.of({ |
| 139 | managed, |
| 140 | protocol: managed ? (options.launcherProtocol ?? SERVICE_LAUNCHER_PROTOCOL) : undefined, |
| 141 | requestUpdate: |
| 142 | options.requestUpdate ?? |
| 143 | (() => |
| 144 | Effect.sync(() => { |
| 145 | order.push("accept"); |
| 146 | return "launcher-id"; |
| 147 | })), |
| 148 | prepareTrial: () => Effect.undefined, |
| 149 | }); |
| 150 | const config = yield* ServerConfig.ServerConfig.pipe( |
| 151 | Effect.provide(ServerConfig.layerTest(process.cwd(), baseDir)), |
| 152 | ); |
| 153 | const selfUpdate = yield* ServerSelfUpdate.make().pipe( |
| 154 | Effect.provideService(ProcessRunner.ProcessRunner, runner), |
| 155 | Effect.provideService(ServiceLauncherClient.ServiceLauncherClient, launcher), |
| 156 | Effect.provideService( |
| 157 | DesktopAppUpdate.DesktopAppUpdate, |
| 158 | options.desktopAppUpdate ?? { |
| 159 | available: false, |
| 160 | run: () => Effect.die("unexpected desktop app update run"), |
| 161 | }, |
| 162 | ), |
| 163 | Effect.provideService( |
| 164 | HttpClient.HttpClient, |
| 165 | options.httpClient ?? releaseHttpClient(order, urls, options.beforeDownload), |
| 166 | ), |
| 167 | Effect.provideService(HostProcess.Platform, "linux"), |
| 168 | Effect.provideService(HostProcess.Architecture, "x64"), |
| 169 | Effect.provide( |
| 170 | Layer.merge( |
| 171 | ServerConfig.layer({ ...config, mode: options.mode ?? "web" }), |
| 172 | ManagedPolicy.layerTest(options.policy), |
| 173 | ), |
| 174 | ), |
| 175 | ); |
| 176 | return { selfUpdate, order, urls, baseDir, preflightProtocols }; |
| 177 | }); |
| 178 | |
| 179 | it.layer(NodeServices.layer)("server self update", (it) => { |
| 180 | it.effect.each([ |
| 181 | { asset: "checksums", status: 504 }, |
| 182 | { asset: "archive", status: 503 }, |
| 183 | { asset: "checksums", status: 403 }, |
| 184 | ])("reports an HTTP $status downloading $asset and allows retry", ({ asset, status }) => |
| 185 | Effect.gen(function* () { |
| 186 | let failDownload = true; |
| 187 | const downloadFailed = yield* Deferred.make<void>(); |
| 188 | const { selfUpdate, order, baseDir } = yield* makeHarness({ |
| 189 | httpClient: releaseHttpClient([], []).pipe( |
| 190 | HttpClient.transform((response, request) => { |
| 191 | if (!failDownload || request.url.endsWith("/SHA256SUMS") !== (asset === "checksums")) |
| 192 | return response; |
| 193 | Deferred.doneUnsafe(downloadFailed, Effect.void); |
| 194 | return Effect.succeed( |
| 195 | HttpClientResponse.fromWeb( |
| 196 | HttpClientRequest.get("https://user:password@cdn.example/private?token=secret"), |
| 197 | new Response("private response body", { status }), |
| 198 | ), |
| 199 | ); |
| 200 | }), |
| 201 | ), |
| 202 | }); |
| 203 | const failing = yield* selfUpdate |
| 204 | .update({ targetVersion: "1.1.0" }) |
| 205 | .pipe(Effect.flip, Effect.forkScoped); |
| 206 | yield* Deferred.await(downloadFailed); |
| 207 | // A 5xx is retried after 2, 4, then 8 seconds before the update gives up. |
| 208 | yield* TestClock.adjust("14 seconds"); |
| 209 | const error = yield* Fiber.join(failing); |
| 210 | expect(error.reason).toBe( |
| 211 | `Could not prepare t3@1.1.0 while downloading the t3 release ${asset} (HTTP ${status} from cdn.example).`, |
| 212 | ); |
| 213 | expect(order).toEqual([]); |
| 214 | const fs = yield* FileSystem.FileSystem; |
| 215 | const path = yield* Path.Path; |
| 216 | expect(yield* fs.readDirectory(path.join(baseDir, "runtime", "versions"))).toEqual([]); |
| 217 | failDownload = false; |
| 218 | expect((yield* selfUpdate.update({ targetVersion: "1.1.0" })).updateId).toBe("launcher-id"); |
| 219 | expect(order).toEqual(["extract", "preflight", "accept"]); |
| 220 | }), |
| 221 | ); |
| 222 | |
| 223 | // regression: #34502 a remote update never replaces the launcher, so it can be older than the server |
| 224 | it.effect("names its launcher's protocol to the staged preflight, not its own", () => |
| 225 | Effect.gen(function* () { |
| 226 | const { selfUpdate, preflightProtocols, baseDir } = yield* makeHarness({ |
| 227 | launcherProtocol: 3, |
| 228 | }); |
| 229 | yield* TestClock.setTime(5_000); |
| 230 | expect((yield* selfUpdate.update({ targetVersion: "1.1.0" })).updateId).toBe("launcher-id"); |
| 231 | expect(preflightProtocols).toEqual(["3"]); |
| 232 | // That launcher holds no lock between its servers; SSH launches wait on this marker instead. |
| 233 | const fs = yield* FileSystem.FileSystem; |
| 234 | const path = yield* Path.Path; |
| 235 | expect( |
| 236 | JSON.parse( |
| 237 | yield* fs.readFileString(path.join(baseDir, "runtime", "desktop-update-in-progress")), |
| 238 | ), |
| 239 | ).toEqual({ startedAt: 5_000, expiresAt: 65_000 }); |
| 240 | }), |
| 241 | ); |
| 242 | |
| 243 | // regression: #5181 make remote updates rollback-safe |
| 244 | it.effect("rejects invalid versions and desktop-managed servers before staging", () => |
| 245 | Effect.gen(function* () { |
| 246 | const web = yield* makeHarness(); |
| 247 | expect( |
| 248 | (yield* web.selfUpdate.update({ targetVersion: "latest" }).pipe(Effect.flip)).reason, |
| 249 | ).toBe("'latest' is not an exact t3 version."); |
| 250 | const desktop = yield* makeHarness({ mode: "desktop" }); |
| 251 | expect( |
| 252 | (yield* desktop.selfUpdate.update({ targetVersion: "1.1.0" }).pipe(Effect.flip)).reason, |
| 253 | ).toContain("desktop app"); |
| 254 | expect([...web.order, ...desktop.order]).toEqual([]); |
| 255 | }), |
| 256 | ); |
| 257 | |
| 258 | it.effect("refuses every update when the managed policy turns updates off", () => |
| 259 | Effect.gen(function* () { |
| 260 | const policy: ManagedPolicyDocument = { |
| 261 | schemaVersion: 1, |
| 262 | organization: "Example Corp", |
| 263 | limits: { updates: { mode: "off" } }, |
| 264 | }; |
| 265 | const service = yield* makeHarness({ policy }); |
| 266 | const desktop = yield* makeHarness({ |
| 267 | mode: "desktop", |
| 268 | policy, |
| 269 | desktopAppUpdate: { |
| 270 | available: true, |
| 271 | run: () => Effect.die("unexpected desktop app update run"), |
| 272 | commit: () => Effect.never, |
| 273 | }, |
| 274 | }); |
| 275 | for (const harness of [service, desktop]) { |
| 276 | expect( |
| 277 | (yield* harness.selfUpdate.update({ targetVersion: "1.1.0" }).pipe(Effect.flip)).reason, |
| 278 | ).toBe("Example Corp manages T3 Code updates."); |
| 279 | } |
| 280 | expect([...service.order, ...desktop.order]).toEqual([]); |
| 281 | }), |
| 282 | ); |
| 283 | |
| 284 | it.effect("lets a user start an update, but only to stable without nightly", () => |
| 285 | Effect.gen(function* () { |
| 286 | const { selfUpdate, order, urls } = yield* makeHarness({ |
| 287 | policy: { |
| 288 | schemaVersion: 1, |
| 289 | organization: "Example Corp", |
| 290 | limits: { |
| 291 | updates: { |
| 292 | mode: "auto", |
| 293 | allowNightly: false, |
| 294 | feedUrl: "https://updates.example.com/t3code/", |
| 295 | }, |
| 296 | }, |
| 297 | }, |
| 298 | }); |
| 299 | expect( |
| 300 | (yield* selfUpdate.update({ targetVersion: "1.2.0-nightly.20261028.1" }).pipe(Effect.flip)) |
| 301 | .reason, |
| 302 | ).toBe("Example Corp manages T3 Code updates. Only stable releases can be installed."); |
| 303 | expect(order).toEqual([]); |
| 304 | // The mirror lists only 1.1.0's archive. |
| 305 | expect((yield* selfUpdate.update({ targetVersion: "1.2.0" }).pipe(Effect.flip)).reason).toBe( |
| 306 | "Example Corp's update mirror has no t3@1.2.0 for this machine.", |
| 307 | ); |
| 308 | expect((yield* selfUpdate.update({ targetVersion: "1.1.0" })).updateId).toBe("launcher-id"); |
| 309 | // The release comes from the policy's mirror, not GitHub. |
| 310 | expect(urls.length).toBeGreaterThan(0); |
| 311 | for (const url of urls) |
| 312 | expect(url).toMatch(/^https:\/\/updates\.example\.com\/t3code\/v1\.[12]\.0\//); |
| 313 | }), |
| 314 | ); |
| 315 | |
| 316 | it.effect("delegates desktop-managed updates to the desktop app when available", () => |
| 317 | Effect.gen(function* () { |
| 318 | const stages: string[] = []; |
| 319 | const { selfUpdate, order } = yield* makeHarness({ |
| 320 | mode: "desktop", |
| 321 | desktopAppUpdate: { |
| 322 | available: true, |
| 323 | run: (reportProgress) => |
| 324 | reportProgress("downloading").pipe( |
| 325 | Effect.andThen(reportProgress("installing")), |
| 326 | Effect.as({ targetVersion: "1.2.0", method: "desktop-app" as const }), |
| 327 | ), |
| 328 | commit: () => Effect.never, |
| 329 | }, |
| 330 | }); |
| 331 | const result = yield* selfUpdate.update({ targetVersion: "1.1.0" }, (stage) => |
| 332 | Effect.sync(() => void stages.push(stage)), |
| 333 | ); |
| 334 | expect(result).toEqual({ targetVersion: "1.2.0", method: "desktop-app" }); |
| 335 | expect(stages).toEqual(["downloading", "installing"]); |
| 336 | expect(order).toEqual([]); |
| 337 | }), |
| 338 | ); |
| 339 | |
| 340 | it.effect("allows only one update at a time", () => |
| 341 | Effect.gen(function* () { |
| 342 | const requested = yield* Deferred.make<void>(); |
| 343 | const accepted = yield* Deferred.make<string>(); |
| 344 | const { selfUpdate } = yield* makeHarness({ |
| 345 | requestUpdate: () => |
| 346 | Deferred.succeed(requested, undefined).pipe(Effect.andThen(Deferred.await(accepted))), |
| 347 | }); |
| 348 | const first = yield* Effect.forkChild(selfUpdate.update({ targetVersion: "1.1.0" }), { |
| 349 | startImmediately: true, |
| 350 | }); |
| 351 | yield* Deferred.await(requested); |
| 352 | expect((yield* selfUpdate.update({ targetVersion: "1.1.1" }).pipe(Effect.flip)).reason).toBe( |
| 353 | "A server update is already in progress.", |
| 354 | ); |
| 355 | yield* Deferred.succeed(accepted, "launcher-id"); |
| 356 | expect((yield* Fiber.join(first)).updateId).toBe("launcher-id"); |
| 357 | }), |
| 358 | ); |
| 359 | |
| 360 | it.effect("stages the runtime without asking the launcher to restart", () => |
| 361 | Effect.gen(function* () { |
| 362 | const { selfUpdate, order } = yield* makeHarness(); |
| 363 | expect(yield* selfUpdate.update({ targetVersion: "1.1.0", stageOnly: true })).toEqual({ |
| 364 | targetVersion: "1.1.0", |
| 365 | method: "boot-service", |
| 366 | }); |
| 367 | expect(order).toEqual(["download", "extract", "preflight"]); |
| 368 | expect((yield* selfUpdate.update({ targetVersion: "1.1.0" })).updateId).toBe("launcher-id"); |
| 369 | expect(order).toEqual(["download", "extract", "preflight", "preflight", "accept"]); |
| 370 | }), |
| 371 | ); |
| 372 | |
| 373 | // regression: #28198 a slow staged preflight on a loaded host no longer fails the update |
| 374 | it.effect("waits for a staged preflight that takes a minute on a loaded host", () => |
| 375 | Effect.gen(function* () { |
| 376 | const preflightStarted = yield* Deferred.make<void>(); |
| 377 | const { selfUpdate, order } = yield* makeHarness({ |
| 378 | preflightDuration: "60 seconds", |
| 379 | preflightStarted, |
| 380 | }); |
| 381 | const update = yield* Effect.forkChild(selfUpdate.update({ targetVersion: "1.1.0" }), { |
| 382 | startImmediately: true, |
| 383 | }); |
| 384 | yield* Deferred.await(preflightStarted); |
| 385 | yield* TestClock.adjust("60 seconds"); |
| 386 | const exit = yield* Fiber.await(update); |
| 387 | expect(exit._tag === "Failure" ? String(exit.cause) : "launcher handoff").toBe( |
| 388 | "launcher handoff", |
| 389 | ); |
| 390 | expect(order).toEqual(["download", "extract", "preflight", "accept"]); |
| 391 | }), |
| 392 | ); |
| 393 | |
| 394 | it.effect("keeps preparing after the progress stream closes", () => |
| 395 | Effect.gen(function* () { |
| 396 | const releaseDownload = yield* Deferred.make<void>(); |
| 397 | const sawDownloading = yield* Deferred.make<void>(); |
| 398 | const accepted = yield* Deferred.make<void>(); |
| 399 | const { selfUpdate, order } = yield* makeHarness({ |
| 400 | beforeDownload: Deferred.await(releaseDownload), |
| 401 | requestUpdate: () => |
| 402 | Effect.sync(() => { |
| 403 | order.push("accept"); |
| 404 | }).pipe(Effect.andThen(Deferred.succeed(accepted, undefined)), Effect.as("launcher-id")), |
| 405 | }); |
| 406 | |
| 407 | const consumed = yield* ServerSelfUpdate.updateProgressStream(selfUpdate, { |
| 408 | targetVersion: "1.1.0", |
| 409 | }).pipe( |
| 410 | Stream.tap((event) => |
| 411 | event.type === "progress" && event.stage === "downloading" |
| 412 | ? Deferred.succeed(sawDownloading, undefined) |
| 413 | : Effect.void, |
| 414 | ), |
| 415 | Stream.runDrain, |
| 416 | Effect.forkChild, |
| 417 | ); |
| 418 | |
| 419 | yield* Deferred.await(sawDownloading); |
| 420 | yield* Fiber.interrupt(consumed); |
| 421 | expect((yield* selfUpdate.update({ targetVersion: "1.2.0" }).pipe(Effect.flip)).reason).toBe( |
| 422 | "A server update is already in progress.", |
| 423 | ); |
| 424 | |
| 425 | yield* Deferred.succeed(releaseDownload, undefined); |
| 426 | yield* Deferred.await(accepted); |
| 427 | expect(order).toEqual(["download", "extract", "preflight", "accept"]); |
| 428 | expect((yield* selfUpdate.update({ targetVersion: "1.1.0" }).pipe(Effect.flip)).reason).toBe( |
| 429 | "A server update is already in progress.", |
| 430 | ); |
| 431 | }), |
| 432 | ); |
| 433 | }); |
| 434 | |
| 435 | it.layer(NodeServices.layer)("pruning runtimes on start", (it) => { |
| 436 | const staleVersion = "0.0.1"; |
| 437 | const otherProcesses = ProcessRunner.ProcessRunner.of({ |
| 438 | run: () => |
| 439 | Effect.succeed({ |
| 440 | stdout: "p42\nftxt\nn/bin/sh\n", |
| 441 | stderr: "", |
| 442 | code: ChildProcessSpawner.ExitCode(0), |
| 443 | timedOut: false, |
| 444 | stdoutTruncated: false, |
| 445 | stderrTruncated: false, |
| 446 | stdoutInvalidUtf8: false, |
| 447 | stderrInvalidUtf8: false, |
| 448 | }), |
| 449 | }); |
| 450 | |
| 451 | const pruneOnStart = Effect.fn("test.prune_on_start")(function* (input: { |
| 452 | readonly executable: "own runtime" | "elsewhere"; |
| 453 | readonly managed?: boolean; |
| 454 | readonly symlinkedHome?: boolean; |
| 455 | readonly servicePlistStarts?: string; |
| 456 | readonly servicePlistThroughLink?: boolean; |
| 457 | }) { |
| 458 | const fs = yield* FileSystem.FileSystem; |
| 459 | const path = yield* Path.Path; |
| 460 | const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-prune-on-start-" }); |
| 461 | const realHome = path.join(tempDir, "home"); |
| 462 | const baseDir = input.symlinkedHome ? path.join(tempDir, "linked-home") : realHome; |
| 463 | const versionsDir = path.join(baseDir, "runtime", "versions"); |
| 464 | yield* TestClock.setTime(24 * 60 * 60 * 1000); |
| 465 | for (const version of [staleVersion, packageJson.version]) { |
| 466 | const directory = path.join(realHome, "runtime", "versions", version); |
| 467 | yield* fs.makeDirectory(directory, { recursive: true }); |
| 468 | yield* fs.writeFileString(path.join(directory, "t3"), ""); |
| 469 | const sentinel = path.join(directory, ".install-complete"); |
| 470 | yield* fs.writeFileString(sentinel, `${version}\n`); |
| 471 | yield* fs.utimes(sentinel, 0, 0); |
| 472 | } |
| 473 | if (input.symlinkedHome) yield* fs.symlink(realHome, baseDir); |
| 474 | const userHome = path.join(tempDir, "user"); |
| 475 | if (input.servicePlistStarts !== undefined) { |
| 476 | const agentsDir = path.join(userHome, "Library", "LaunchAgents"); |
| 477 | yield* fs.makeDirectory(agentsDir, { recursive: true }); |
| 478 | const programHome = input.servicePlistThroughLink |
| 479 | ? path.join(tempDir, "alias-home") |
| 480 | : baseDir; |
| 481 | if (input.servicePlistThroughLink) yield* fs.symlink(realHome, programHome); |
| 482 | const program = path.join(programHome, "runtime", "versions", input.servicePlistStarts, "t3"); |
| 483 | yield* fs.writeFileString( |
| 484 | path.join(agentsDir, "com.t3tools.t3code.service.plist"), |
| 485 | `<plist><dict>\n<key>ProgramArguments</key>\n<array>\n<string>${program}</string>\n<string>__service-launcher</string>\n</array>\n</dict></plist>\n`, |
| 486 | ); |
| 487 | } |
| 488 | // Like `process.execPath`, the running runtime is reported by its real path. |
| 489 | const executablePath = |
| 490 | input.executable === "own runtime" |
| 491 | ? yield* fs.realPath(path.join(versionsDir, packageJson.version, "t3")) |
| 492 | : "/usr/local/bin/node"; |
| 493 | const removed = yield* ServerSelfUpdate.pruneRuntimesOnStart({ |
| 494 | baseDir, |
| 495 | managed: input.managed ?? false, |
| 496 | }).pipe( |
| 497 | Effect.provideService(HostProcess.ExecutablePath, executablePath), |
| 498 | Effect.provideService(HostProcess.Platform, "darwin"), |
| 499 | Effect.provideService(HostProcess.Environment, {}), |
| 500 | Effect.provideService(HostProcess.HomeDirectory, userHome), |
| 501 | Effect.provideService(ProcessRunner.ProcessRunner, otherProcesses), |
| 502 | ); |
| 503 | return { removed, remaining: (yield* fs.readDirectory(versionsDir)).toSorted() }; |
| 504 | }); |
| 505 | |
| 506 | // The SSH launcher runs `t3 serve` straight from the pinned runtime, with no boot service. |
| 507 | it.effect("prunes for a server started from its home's pinned runtime", () => |
| 508 | Effect.gen(function* () { |
| 509 | const { removed, remaining } = yield* pruneOnStart({ executable: "own runtime" }); |
| 510 | expect(removed).toEqual([staleVersion]); |
| 511 | expect(remaining).toEqual([packageJson.version]); |
| 512 | }), |
| 513 | ); |
| 514 | |
| 515 | it.effect("recognizes its runtime through a symlinked T3 home", () => |
| 516 | Effect.gen(function* () { |
| 517 | const { removed } = yield* pruneOnStart({ executable: "own runtime", symlinkedHome: true }); |
| 518 | expect(removed).toEqual([staleVersion]); |
| 519 | }), |
| 520 | ); |
| 521 | |
| 522 | it.effect("prunes for a boot-service server wherever it runs from", () => |
| 523 | Effect.gen(function* () { |
| 524 | const { removed } = yield* pruneOnStart({ executable: "elsewhere", managed: true }); |
| 525 | expect(removed).toEqual([staleVersion]); |
| 526 | }), |
| 527 | ); |
| 528 | |
| 529 | // In-place updates move the active version but leave the launch agent on the launcher's runtime. |
| 530 | it.effect.each([ |
| 531 | { name: "", throughLink: false }, |
| 532 | { name: " through a symlinked T3 home", throughLink: true }, |
| 533 | ])("keeps the runtime a stopped service's launch agent starts$name", ({ throughLink }) => |
| 534 | Effect.gen(function* () { |
| 535 | const { removed, remaining } = yield* pruneOnStart({ |
| 536 | executable: "own runtime", |
| 537 | servicePlistStarts: staleVersion, |
| 538 | servicePlistThroughLink: throughLink, |
| 539 | }); |
| 540 | expect(removed).toEqual([]); |
| 541 | expect(remaining).toEqual([staleVersion, packageJson.version].toSorted()); |
| 542 | }), |
| 543 | ); |
| 544 | |
| 545 | it.effect("leaves runtimes alone for an unmanaged server started elsewhere", () => |
| 546 | Effect.gen(function* () { |
| 547 | const { removed, remaining } = yield* pruneOnStart({ executable: "elsewhere" }); |
| 548 | expect(removed).toEqual([]); |
| 549 | expect(remaining).toEqual([staleVersion, packageJson.version].toSorted()); |
| 550 | }), |
| 551 | ); |
| 552 | }); |
| 553 | |
| 554 | it("a host crosses tracks only to a release that knows its whole database", () => { |
| 555 | const cross = ( |
| 556 | serverVersion: string, |
| 557 | targetVersion: string, |
| 558 | targetDatabaseMigration: number | undefined, |
| 559 | databaseMigration = 72, |
| 560 | ) => |
| 561 | ServerSelfUpdate.trackSwitchBlockReason({ |
| 562 | serverVersion, |
| 563 | targetVersion, |
| 564 | targetDatabaseMigration, |
| 565 | databaseMigration: () => databaseMigration, |
| 566 | }); |
| 567 | const nightly = "0.1.4-nightly.20261027.3796"; |
| 568 | |
| 569 | expect(cross(nightly, "0.1.4", 72)).toBeNull(); |
| 570 | // Another client moved this host to a newer Nightly after the switch was planned. |
| 571 | expect(cross(nightly, "0.1.4", 72, 73)).toContain("does not support yet"); |
| 572 | expect(cross(nightly, "0.1.4", undefined)).toContain("Cannot confirm"); |
| 573 | // A Stable tag can carry a migration the latest Nightly lacks. |
| 574 | expect(cross("0.1.4", nightly, 72, 73)).toContain("does not support yet"); |
| 575 | expect(cross("0.1.3", "0.1.4", undefined)).toBeNull(); |
| 576 | // A database that exists but cannot be read proves nothing. |
| 577 | expect( |
| 578 | ServerSelfUpdate.trackSwitchBlockReason({ |
| 579 | serverVersion: nightly, |
| 580 | targetVersion: "0.1.4", |
| 581 | targetDatabaseMigration: 72, |
| 582 | databaseMigration: () => undefined, |
| 583 | }), |
| 584 | ).toContain("Cannot confirm"); |
| 585 | }); |