@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

main
ts 750 lines 30.1 KB
Raw
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { assert, it } from "@effect/vitest";
3 import type { ManagedUpdatesPolicy } from "@t3tools/contracts";
4 import * as HostProcess from "@t3tools/shared/HostProcess";
5 import * as Duration from "effect/Duration";
6 import * as Effect from "effect/Effect";
7 import * as Exit from "effect/Exit";
8 import * as FileSystem from "effect/FileSystem";
9 import * as Layer from "effect/Layer";
10 import * as Option from "effect/Option";
11 import * as Path from "effect/Path";
12 import * as TestClock from "effect/testing/TestClock";
13 import * as TestConsole from "effect/testing/TestConsole";
14 import { HttpClient, HttpClientResponse } from "effect/http";
15 import * as ChildProcess from "effect/process/ChildProcess";
16 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
17 import { afterEach, vi } from "vite-plus/test";
18
19 import packageJson from "../../package.json" with { type: "json" };
20 import * as BootService from "../cloud/bootService.ts";
21 import { SERVICE_LAUNCHER_PROTOCOL } from "../cloud/serviceProtocol.ts";
22 import {
23 pinnedRuntimePaths,
24 posixLauncherScript,
25 prunePinnedRuntimes,
26 readPosixLauncherTarget,
27 resolveLauncherPath,
28 } from "../cloud/pinnedRuntime.ts";
29 import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
30 import * as ProcessRunner from "../processRunner.ts";
31 import {
32 repointLauncher,
33 resolveMirrorVersion,
34 resolveNewestVersion,
35 runUpdate,
36 } from "./update.ts";
37
38 // lsof listing one process, so prune sees a process list in which no runtime is running.
39 const unrelatedLsof = ProcessRunner.ProcessRunner.of({
40 run: () =>
41 Effect.succeed({
42 stdout: "p1\nftxt\nn/usr/bin/true\n",
43 stderr: "",
44 code: ChildProcessSpawner.ExitCode(0),
45 timedOut: false,
46 stdoutTruncated: false,
47 stderrTruncated: false,
48 stdoutInvalidUtf8: false,
49 stderrInvalidUtf8: false,
50 }),
51 });
52
53 afterEach(() => vi.restoreAllMocks());
54
55 it.effect("authenticates each release page until the requested channel is found", () =>
56 Effect.gen(function* () {
57 const pages: string[] = [];
58 const httpClient = HttpClient.make((request) => {
59 const url = new URL(request.url);
60 assert.equal(url.origin, "https://api.github.com");
61 assert.equal(url.pathname, "/repos/pingdotgg/t3code/releases");
62 assert.equal(request.headers.accept, "application/vnd.github+json");
63 assert.equal(request.headers.authorization, "Bearer gh-token");
64 const page = url.searchParams.get("page") ?? "";
65 pages.push(page);
66 const tag_name = page === "1" ? "v1.2.4-preview.20260101.1" : "v1.2.3";
67 return Effect.succeed(HttpClientResponse.fromWeb(request, Response.json([{ tag_name }])));
68 });
69 const version = yield* resolveNewestVersion("stable").pipe(
70 Effect.provideService(HostProcess.Environment, { GH_TOKEN: "gh-token" }),
71 Effect.provideService(HttpClient.HttpClient, httpClient),
72 );
73 assert.equal(version, "1.2.3");
74 assert.deepStrictEqual(pages, ["1", "2"]);
75 }),
76 );
77
78 it.effect("reads the newest version from the update feed file a mirror publishes", () =>
79 Effect.gen(function* () {
80 const requested: string[] = [];
81 const mirror = {
82 organization: "Example Corp",
83 feedUrl: "https://updates.example.com/t3code/?token=abc",
84 };
85 const resolve = (
86 channel: "stable" | "nightly" | "preview",
87 platform: NodeJS.Platform,
88 arch: string,
89 feed: string,
90 ) =>
91 resolveMirrorVersion(mirror, channel).pipe(
92 Effect.map((version): string => version),
93 Effect.catchTags({ CliUpdateError: (error) => Effect.succeed(`error: ${error.reason}`) }),
94 Effect.provideService(HostProcess.Platform, platform),
95 Effect.provideService(HostProcess.Architecture, arch),
96 Effect.provideService(
97 HttpClient.HttpClient,
98 HttpClient.make((request) => {
99 requested.push(request.url);
100 return Effect.succeed(HttpClientResponse.fromWeb(request, new Response(feed)));
101 }),
102 ),
103 );
104
105 assert.equal(
106 yield* resolve("stable", "darwin", "arm64", "version: 1.4.0\nfiles: []\n"),
107 "1.4.0",
108 );
109 assert.equal(
110 yield* resolve("nightly", "linux", "arm64", "version: '1.5.0-nightly.20261101.2'\n"),
111 "1.5.0-nightly.20261101.2",
112 );
113 assert.deepStrictEqual(requested, [
114 "https://updates.example.com/t3code/latest-mac.yml?token=abc",
115 "https://updates.example.com/t3code/nightly-linux-arm64.yml?token=abc",
116 ]);
117 // A feed for the wrong track is not trusted to mean the requested one.
118 assert.include(
119 yield* resolve("stable", "win32", "x64", "version: 1.5.0-nightly.20261101.2\n"),
120 "Could not read latest.yml from Example Corp's update mirror.",
121 );
122 assert.include(yield* resolve("preview", "win32", "x64", ""), "has no preview builds");
123 }),
124 );
125
126 it.layer(NodeServices.layer)("t3 update under a managed policy", (it) => {
127 const runWithPolicy = (
128 updates: ManagedUpdatesPolicy,
129 input: { readonly channel?: "stable" | "nightly"; readonly requestedVersion?: string } = {},
130 httpClient = HttpClient.make(() => Effect.die("unexpected release lookup")),
131 ) =>
132 runUpdate({
133 baseDir: "/unused",
134 logsDir: "/unused",
135 databasePath: "/unused",
136 serverRuntimeStatePath: "/unused",
137 channel: input.channel,
138 requestedVersion: input.requestedVersion,
139 allowDowngrade: false,
140 assumeYes: true,
141 }).pipe(
142 Effect.flip,
143 Effect.provide(
144 Layer.mergeAll(
145 ManagedPolicy.layerTest({
146 schemaVersion: 1,
147 organization: "Example Corp",
148 limits: { updates },
149 }),
150 // Refusals happen before the update touches the network, the service, or a process.
151 Layer.mock(BootService.BootService, {}),
152 Layer.mock(ProcessRunner.ProcessRunner, {}),
153 Layer.succeed(HttpClient.HttpClient, httpClient),
154 ),
155 ),
156 );
157
158 it.effect("refuses to update when updates are off", () =>
159 Effect.gen(function* () {
160 const error = yield* runWithPolicy({ mode: "off" });
161 assert.equal(error.message, "Example Corp manages T3 Code updates.");
162 }),
163 );
164
165 it.effect("refuses nightly releases when the policy disallows them", () =>
166 Effect.gen(function* () {
167 const byChannel = yield* runWithPolicy(
168 { mode: "auto", allowNightly: false },
169 { channel: "nightly" },
170 );
171 const byVersion = yield* runWithPolicy(
172 { mode: "auto", allowNightly: false },
173 { channel: "stable", requestedVersion: "1.2.0-nightly.20261028.1" },
174 );
175 for (const error of [byChannel, byVersion]) {
176 assert.equal(
177 error.message,
178 "Example Corp manages T3 Code updates. Only stable releases can be installed.",
179 );
180 }
181 }),
182 );
183
184 it.effect("looks for updates on the policy's mirror, never the public releases", () =>
185 Effect.gen(function* () {
186 const requested: string[] = [];
187 const error = yield* runWithPolicy(
188 { mode: "auto", feedUrl: "https://updates.example.com/t3code" },
189 { channel: "stable" },
190 HttpClient.make((request) => {
191 requested.push(new URL(request.url).origin);
192 return Effect.succeed(
193 HttpClientResponse.fromWeb(request, new Response("", { status: 404 })),
194 );
195 }),
196 );
197 assert.include(error.message, "from Example Corp's update mirror");
198 assert.deepStrictEqual(requested, ["https://updates.example.com"]);
199 }),
200 );
201 });
202
203 it.layer(NodeServices.layer)("t3 update launcher", (it) => {
204 it.effect("replaces a legacy symlink with a script that execs the new version", () =>
205 Effect.gen(function* () {
206 const fs = yield* FileSystem.FileSystem;
207 const path = yield* Path.Path;
208 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
209 const oldExe = path.join(root, "runtime/versions/1.0.0/t3");
210 const newExe = path.join(root, "runtime/versions/2.0.0/t3");
211 const launcher = path.join(root, "bin/t3");
212 for (const file of [oldExe, newExe]) {
213 yield* fs.makeDirectory(path.dirname(file), { recursive: true });
214 yield* fs.writeFileString(file, "");
215 }
216 yield* fs.makeDirectory(path.dirname(launcher), { recursive: true });
217 yield* fs.symlink(oldExe, launcher);
218
219 const repointed = yield* repointLauncher({
220 launchedAs: launcher,
221 baseDir: root,
222 targetEntryPath: newExe,
223 });
224
225 assert.deepStrictEqual(Option.getOrUndefined(repointed), launcher);
226 assert.equal(yield* fs.readFileString(launcher), posixLauncherScript(newExe));
227 // Replaced, not written through.
228 assert.equal(yield* fs.readFileString(oldExe), "");
229 }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
230 );
231
232 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
233 "finds the script that ran this executable and rewrites it, keeping aliases and arguments",
234 () =>
235 Effect.gen(function* () {
236 const fs = yield* FileSystem.FileSystem;
237 const path = yield* Path.Path;
238 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
239 const root = yield* fs.realPath(
240 yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" }),
241 );
242 // A quote and a space in the home path exercise the script's quoting.
243 const home = path.join(root, "it's home");
244 const entry = (version: string) => path.join(home, "runtime/versions", version, "t3");
245 for (const version of ["1.0.0", "2.0.0"]) {
246 yield* fs.makeDirectory(path.dirname(entry(version)), { recursive: true });
247 yield* fs.writeFileString(entry(version), '#!/bin/sh\nprintf \'[%s]\\n\' "$0" "$@"\n', {
248 mode: 0o755,
249 });
250 }
251 const launcher = path.join(root, "bin/t3");
252 const alias = path.join(root, "alias/t3");
253 yield* fs.makeDirectory(path.dirname(launcher), { recursive: true });
254 yield* fs.makeDirectory(path.dirname(alias), { recursive: true });
255 yield* fs.writeFileString(launcher, posixLauncherScript(entry("1.0.0")), { mode: 0o755 });
256 yield* fs.symlink(launcher, alias);
257 const repoint = (environment: Record<string, string>) =>
258 repointLauncher({
259 // The script execs by absolute path, so argv0 names the executable.
260 launchedAs: entry("1.0.0"),
261 baseDir: home,
262 targetEntryPath: entry("2.0.0"),
263 }).pipe(Effect.provideService(HostProcess.Environment, environment));
264
265 assert.equal(
266 Option.getOrUndefined(yield* repoint({ PATH: path.dirname(alias) })),
267 launcher,
268 );
269 assert.equal(yield* fs.readLink(alias), launcher);
270 const args = ["two words", "it's quoted", "", "*", "$HOME"];
271 assert.equal(
272 yield* spawner.string(ChildProcess.make(alias, args, { cwd: root })),
273 [entry("2.0.0"), ...args].map((arg) => `[${arg}]\n`).join(""),
274 );
275
276 // Like the shell, a relative PATH entry resolves from the working directory, and a
277 // script nobody can execute is passed over.
278 const unrunnable = path.join(root, "unrunnable/t3");
279 yield* fs.makeDirectory(path.dirname(unrunnable), { recursive: true });
280 yield* fs.writeFileString(unrunnable, posixLauncherScript(entry("2.0.0")), { mode: 0o644 });
281 yield* fs.writeFileString(launcher, posixLauncherScript(entry("2.0.0")), { mode: 0o755 });
282 const relative = yield* repointLauncher({
283 launchedAs: entry("2.0.0"),
284 baseDir: home,
285 targetEntryPath: entry("1.0.0"),
286 }).pipe(
287 Effect.provideService(HostProcess.Environment, {
288 PATH: `${path.dirname(unrunnable)}:bin`,
289 }),
290 Effect.provideService(HostProcess.WorkingDirectory, root),
291 );
292 assert.equal(Option.getOrUndefined(relative), launcher);
293 assert.equal(yield* fs.readFileString(unrunnable), posixLauncherScript(entry("2.0.0")));
294
295 // An edited script is the user's own wrapper now.
296 const edited = `${posixLauncherScript(entry("1.0.0"))}# mine\n`;
297 yield* fs.writeFileString(launcher, edited);
298 assert.isTrue(Option.isNone(yield* repoint({ PATH: path.dirname(launcher) })));
299 assert.equal(yield* fs.readFileString(launcher), edited);
300 }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
301 );
302
303 it.effect.each([
304 { name: "no launcher records", recorded: undefined },
305 { name: "an empty launcher record", recorded: "" },
306 { name: "whole launcher records", recorded: "/opt/t3\n" },
307 { name: "Windows launcher records", recorded: "C:\\t3.cmd\r\n" },
308 // An interrupted append cut this record short.
309 { name: "an unterminated launcher record", recorded: "/opt/t" },
310 // Another process's append is cut short after t3 update reads the records.
311 { name: "a record cut short after the read", recorded: "/opt/t3\n", cut: "/opt/t" },
312 ])("keeps the runtime a repointed launcher off PATH points at with $name", ({ recorded, cut }) =>
313 Effect.gen(function* () {
314 const fs = yield* FileSystem.FileSystem;
315 const path = yield* Path.Path;
316 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
317 yield* TestClock.setTime(Duration.toMillis(Duration.days(1)));
318 for (const version of ["1.0.0", "2.0.0"]) {
319 const directory = path.join(root, "runtime/versions", version);
320 yield* fs.makeDirectory(directory, { recursive: true });
321 yield* fs.writeFileString(path.join(directory, "t3"), "");
322 yield* fs.writeFileString(path.join(directory, ".install-complete"), `${version}\n`);
323 yield* fs.utimes(path.join(directory, ".install-complete"), 0, 0);
324 }
325 if (recorded !== undefined) {
326 yield* fs.writeFileString(path.join(root, "runtime/launchers"), recorded);
327 }
328 // A launcher in the T3 home itself, which neither PATH nor the default bin dir reaches.
329 const launcher = path.join(root, "t3");
330 yield* fs.symlink(path.join(root, "runtime/versions/1.0.0/t3"), launcher);
331
332 const launchersFile = path.join(root, "runtime/launchers");
333 yield* repointLauncher({
334 launchedAs: launcher,
335 baseDir: root,
336 targetEntryPath: path.join(root, "runtime/versions/2.0.0/t3"),
337 }).pipe(
338 Effect.provideService(FileSystem.FileSystem, {
339 ...fs,
340 readFileString: (file, encoding) =>
341 fs
342 .readFileString(file, encoding)
343 .pipe(
344 Effect.tap(() =>
345 cut === undefined || file !== launchersFile
346 ? Effect.void
347 : fs.writeFileString(file, cut, { flag: "a" }),
348 ),
349 ),
350 }),
351 );
352 // A later server start prunes with no idea how this machine launches t3.
353 const removed = yield* prunePinnedRuntimes({ baseDir: root, keep: [] }).pipe(
354 Effect.provideService(ProcessRunner.ProcessRunner, unrelatedLsof),
355 Effect.provideService(HostProcess.Platform, "darwin"),
356 Effect.provideService(HostProcess.Environment, { PATH: "" }),
357 Effect.provideService(HostProcess.HomeDirectory, root),
358 );
359
360 assert.deepStrictEqual(removed, ["1.0.0"]);
361 assert.equal(
362 yield* readPosixLauncherTarget(launcher),
363 path.join(root, "runtime/versions/2.0.0/t3"),
364 );
365 }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
366 );
367
368 const launcherFixture = Effect.fnUntraced(function* () {
369 const fs = yield* FileSystem.FileSystem;
370 const path = yield* Path.Path;
371 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
372 const oldExe = path.join(root, "runtime/versions/1.0.0/t3");
373 const newExe = path.join(root, "runtime/versions/2.0.0/t3");
374 const launcher = path.join(root, "t3");
375 for (const file of [oldExe, newExe]) {
376 yield* fs.makeDirectory(path.dirname(file), { recursive: true });
377 yield* fs.writeFileString(file, "");
378 }
379 yield* fs.symlink(oldExe, launcher);
380 return { root, oldExe, newExe, launcher, launchersFile: path.join(root, "runtime/launchers") };
381 });
382
383 it.effect("records a relative launcher path as absolute", () =>
384 Effect.gen(function* () {
385 const fs = yield* FileSystem.FileSystem;
386 const path = yield* Path.Path;
387 const { root, newExe, launcher, launchersFile } = yield* launcherFixture();
388
389 yield* repointLauncher({
390 launchedAs: path.relative(path.resolve("."), launcher),
391 baseDir: root,
392 targetEntryPath: newExe,
393 });
394
395 assert.equal(yield* fs.readFileString(launchersFile), `\n${launcher}\n`);
396 }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
397 );
398
399 it.effect("fails instead of repointing a launcher it cannot record", () =>
400 Effect.gen(function* () {
401 const fs = yield* FileSystem.FileSystem;
402 const { root, oldExe, newExe, launcher, launchersFile } = yield* launcherFixture();
403 // Appending to a directory fails the way a read-only or full disk would.
404 yield* fs.makeDirectory(launchersFile);
405
406 const result = yield* repointLauncher({
407 launchedAs: launcher,
408 baseDir: root,
409 targetEntryPath: newExe,
410 }).pipe(Effect.exit);
411
412 assert.isTrue(Exit.isFailure(result));
413 assert.equal(yield* fs.readLink(launcher), oldExe);
414 }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
415 );
416
417 it.effect.each(["recording", "repointing"] as const)(
418 "never leaves a repointed launcher unrecorded when t3 update dies while %s",
419 (step) =>
420 Effect.gen(function* () {
421 const fs = yield* FileSystem.FileSystem;
422 const { root, newExe, launcher, launchersFile } = yield* launcherFixture();
423
424 yield* repointLauncher({
425 launchedAs: launcher,
426 baseDir: root,
427 targetEntryPath: newExe,
428 }).pipe(
429 Effect.provideService(FileSystem.FileSystem, {
430 ...fs,
431 writeFileString: (path, data, options) =>
432 step === "recording" && path === launchersFile
433 ? Effect.die("t3 update was killed")
434 : fs.writeFileString(path, data, options),
435 rename: (from, to) =>
436 step === "repointing" && to === launcher
437 ? Effect.die("t3 update was killed")
438 : fs.rename(from, to),
439 }),
440 Effect.exit,
441 );
442
443 const repointed = (yield* readPosixLauncherTarget(launcher)) === newExe;
444 const recorded = (yield* fs
445 .readFileString(launchersFile)
446 .pipe(Effect.orElseSucceed(() => "")))
447 .split("\n")
448 .includes(launcher);
449 assert.isFalse(repointed && !recorded);
450 }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
451 );
452
453 it.effect("leaves a plain copy or a foreign symlink alone", () =>
454 Effect.gen(function* () {
455 const fs = yield* FileSystem.FileSystem;
456 const path = yield* Path.Path;
457 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
458 const newExe = path.join(root, "runtime/versions/2.0.0/t3");
459 const copy = path.join(root, "copy/t3");
460 const foreign = path.join(root, "foreign/t3");
461 const elsewhere = path.join(root, "elsewhere/t3");
462 const otherHome = path.join(root, "other/runtime/versions/1.0.0/t3");
463 const otherLauncher = path.join(root, "other/bin/t3");
464 for (const file of [newExe, copy, elsewhere, otherHome]) {
465 yield* fs.makeDirectory(path.dirname(file), { recursive: true });
466 yield* fs.writeFileString(file, "");
467 }
468 yield* fs.makeDirectory(path.dirname(foreign), { recursive: true });
469 yield* fs.symlink(elsewhere, foreign);
470 yield* fs.makeDirectory(path.dirname(otherLauncher), { recursive: true });
471 yield* fs.symlink(otherHome, otherLauncher);
472
473 for (const launchedAs of [copy, foreign, otherLauncher, undefined]) {
474 const repointed = yield* repointLauncher({
475 launchedAs,
476 baseDir: root,
477 targetEntryPath: newExe,
478 });
479 assert.equal(repointed._tag, "None", launchedAs ?? "undefined");
480 }
481 assert.equal(yield* fs.readLink(foreign), elsewhere);
482 assert.equal(yield* fs.readLink(otherLauncher), otherHome);
483 }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
484 );
485
486 it.effect("finds the launcher a bare command name resolved to on PATH", () =>
487 Effect.gen(function* () {
488 const fs = yield* FileSystem.FileSystem;
489 const path = yield* Path.Path;
490 const delimiter = (yield* HostProcess.Platform) === "win32" ? ";" : ":";
491 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
492 const launcher = path.join(root, "bin/t3");
493 yield* fs.makeDirectory(path.dirname(launcher), { recursive: true });
494 yield* fs.writeFileString(launcher, "", { mode: 0o755 });
495
496 const bare = yield* resolveLauncherPath.pipe(
497 Effect.provideService(HostProcess.InvokedAs, "t3"),
498 Effect.provideService(HostProcess.Environment, {
499 PATH: [path.join(root, "missing"), path.join(root, "bin")].join(delimiter),
500 }),
501 Effect.provideService(HostProcess.WorkingDirectory, root),
502 );
503 const relative = yield* resolveLauncherPath.pipe(
504 Effect.provideService(HostProcess.InvokedAs, "./bin/t3"),
505 Effect.provideService(HostProcess.Environment, { PATH: "" }),
506 Effect.provideService(HostProcess.WorkingDirectory, root),
507 );
508 const absent = yield* resolveLauncherPath.pipe(
509 Effect.provideService(HostProcess.InvokedAs, "t3"),
510 Effect.provideService(HostProcess.Environment, { PATH: path.join(root, "missing") }),
511 Effect.provideService(HostProcess.WorkingDirectory, root),
512 );
513
514 assert.equal(bare, launcher);
515 assert.equal(relative, launcher);
516 assert.equal(absent, undefined);
517 }),
518 );
519 });
520
521 // Without terminals, update skips its restart prompt whatever runs the test.
522 const withoutTerminals = Effect.acquireRelease(
523 Effect.sync(() =>
524 [process.stdin, process.stdout].map((stream) => {
525 const descriptor = Object.getOwnPropertyDescriptor(stream, "isTTY");
526 Object.defineProperty(stream, "isTTY", { configurable: true, value: false });
527 return { stream, descriptor };
528 }),
529 ),
530 (saved) =>
531 Effect.sync(() => {
532 for (const { stream, descriptor } of saved) {
533 if (descriptor === undefined) Reflect.deleteProperty(stream, "isTTY");
534 else Object.defineProperty(stream, "isTTY", descriptor);
535 }
536 }),
537 );
538
539 it.layer(NodeServices.layer)("t3 update with a background service", (it) => {
540 it.effect("names the version a service with a pending restart still runs", () =>
541 Effect.gen(function* () {
542 yield* withoutTerminals;
543 const fs = yield* FileSystem.FileSystem;
544 const path = yield* Path.Path;
545 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
546 const version = packageJson.version;
547 const runtime = pinnedRuntimePaths(path, baseDir, version, "linux");
548 yield* fs.makeDirectory(runtime.versionDir, { recursive: true });
549 yield* fs.writeFileString(runtime.entryPath, "");
550 yield* fs.writeFileString(runtime.sentinelPath, `${version}\n`);
551 const unitPath = path.join(baseDir, "t3code.service");
552 const logPath = path.join(baseDir, "boot-service.log");
553 // An earlier `t3 update` pointed the service at this version without restarting it.
554 const service = Layer.mock(BootService.BootService, {
555 status: Effect.succeed<BootService.BootServiceStatus>({
556 supported: true,
557 installed: true,
558 current: false,
559 installedVersion: version,
560 installedBaseDir: baseDir,
561 problems: ["restart-pending"],
562 unitPath,
563 logPath,
564 }),
565 install: () => Effect.succeed({ program: [runtime.entryPath], baseDir, unitPath, logPath }),
566 });
567 vi.spyOn(BootService, "layer").mockReturnValue(service);
568 const runner = ProcessRunner.ProcessRunner.of({
569 run: (input) =>
570 input.args?.includes("__service-preflight") === true
571 ? unrelatedLsof.run(input).pipe(
572 Effect.map((result) => ({
573 ...result,
574 stdout: JSON.stringify({
575 status: "ready",
576 version,
577 launcherProtocol: SERVICE_LAUNCHER_PROTOCOL,
578 }),
579 })),
580 )
581 : unrelatedLsof.run(input),
582 });
583
584 const output = yield* runUpdate({
585 baseDir,
586 logsDir: baseDir,
587 databasePath: path.join(baseDir, "statev2.sqlite"),
588 serverRuntimeStatePath: path.join(baseDir, "server-runtime.json"),
589 channel: undefined,
590 requestedVersion: version,
591 allowDowngrade: false,
592 assumeYes: false,
593 }).pipe(
594 Effect.andThen(TestConsole.logLines),
595 Effect.map((lines) => lines.join("\n")),
596 Effect.provide(
597 Layer.mergeAll(
598 service,
599 Layer.succeed(ProcessRunner.ProcessRunner, runner),
600 ManagedPolicy.layerTest(),
601 Layer.succeed(
602 HttpClient.HttpClient,
603 HttpClient.make(() => Effect.die("unexpected release lookup")),
604 ),
605 Layer.fresh(TestConsole.layer),
606 ),
607 ),
608 );
609
610 assert.include(
611 output,
612 `Background service still running the version before ${version}. Run \`t3 service restart\` when you are ready to switch it to ${version}.`,
613 );
614 }).pipe(
615 Effect.provideService(HostProcess.Platform, "linux"),
616 Effect.provideService(HostProcess.Environment, { PATH: "" }),
617 ),
618 );
619 });
620
621 it.layer(NodeServices.layer)("t3 update checks the database before switching", (it) => {
622 const preflightOutput = (stdout: string, code = 0) => ({
623 stdout,
624 stderr: code === 0 ? "" : "Unknown command: __service-preflight",
625 code: ChildProcessSpawner.ExitCode(code),
626 timedOut: false,
627 stdoutTruncated: false,
628 stderrTruncated: false,
629 stdoutInvalidUtf8: false,
630 stderrInvalidUtf8: false,
631 });
632 const blockedReason = "This database has migrations that t3@0.1.8 does not know: 79_example.";
633
634 it.effect.each([
635 {
636 name: "installs an older target that accepts this database",
637 targetVersion: "0.1.8",
638 launcherProtocol: 3,
639 preflight: preflightOutput(
640 JSON.stringify({ status: "ready", version: "0.1.8", launcherProtocol: 3 }),
641 ),
642 failure: undefined,
643 },
644 {
645 name: "refuses an older target the database is too new for",
646 targetVersion: "0.1.8",
647 launcherProtocol: 3,
648 preflight: preflightOutput(
649 JSON.stringify({ status: "blocked", version: "0.1.8", reason: blockedReason }),
650 ),
651 failure: blockedReason,
652 },
653 {
654 name: "refuses an older target too old to check the database",
655 targetVersion: "0.1.8",
656 launcherProtocol: 3,
657 preflight: preflightOutput("", 1),
658 failure:
659 "t3@0.1.8 could not confirm it supports this database (its check exited with code 1), so t3 did not switch to it.",
660 },
661 {
662 // Newer builds keep accepting the current launcher protocol, which may drop 3.
663 name: "checks a newer target with the current launcher protocol",
664 targetVersion: "99.0.0",
665 launcherProtocol: SERVICE_LAUNCHER_PROTOCOL,
666 preflight: preflightOutput(
667 JSON.stringify({
668 status: "ready",
669 version: "99.0.0",
670 launcherProtocol: SERVICE_LAUNCHER_PROTOCOL,
671 }),
672 ),
673 failure: undefined,
674 },
675 ])("$name", ({ targetVersion, launcherProtocol, preflight, failure }) =>
676 Effect.gen(function* () {
677 const fs = yield* FileSystem.FileSystem;
678 const path = yield* Path.Path;
679 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
680 const databasePath = path.join(baseDir, "userdata", "statev2.sqlite");
681 const runtime = pinnedRuntimePaths(path, baseDir, targetVersion, "linux");
682 yield* fs.makeDirectory(runtime.versionDir, { recursive: true });
683 yield* fs.writeFileString(runtime.entryPath, "");
684 yield* fs.writeFileString(runtime.sentinelPath, `${targetVersion}\n`);
685 const service = Layer.mock(BootService.BootService, {
686 status: Effect.succeed<BootService.BootServiceStatus>({
687 supported: true,
688 installed: false,
689 current: false,
690 unitPath: path.join(baseDir, "t3code.service"),
691 logPath: path.join(baseDir, "boot-service.log"),
692 }),
693 });
694 const preflightArgs: Array<ReadonlyArray<string>> = [];
695 const runner = ProcessRunner.ProcessRunner.of({
696 run: (input) => {
697 if (input.args?.includes("__service-preflight") === true) {
698 preflightArgs.push(input.args);
699 return Effect.succeed(preflight);
700 }
701 // A target's --version always answers, whatever its database support.
702 return input.args?.includes("--version") === true
703 ? Effect.succeed(preflightOutput(`t3 v${targetVersion}\n`))
704 : unrelatedLsof.run(input);
705 },
706 });
707
708 const exit = yield* runUpdate({
709 baseDir,
710 logsDir: baseDir,
711 databasePath,
712 serverRuntimeStatePath: path.join(baseDir, "server-runtime.json"),
713 channel: undefined,
714 requestedVersion: targetVersion,
715 allowDowngrade: true,
716 assumeYes: true,
717 }).pipe(
718 Effect.exit,
719 Effect.provide(
720 Layer.mergeAll(
721 service,
722 Layer.succeed(ProcessRunner.ProcessRunner, runner),
723 ManagedPolicy.layerTest(),
724 Layer.succeed(
725 HttpClient.HttpClient,
726 HttpClient.make(() => Effect.die("unexpected release lookup")),
727 ),
728 Layer.fresh(TestConsole.layer),
729 ),
730 ),
731 );
732
733 const error = Option.getOrUndefined(Exit.findErrorOption(exit));
734 assert.equal(error?.message, failure);
735 assert.equal(Exit.isSuccess(exit), failure === undefined);
736 assert.deepEqual(preflightArgs, [
737 [
738 "__service-preflight",
739 "--database-path",
740 databasePath,
741 "--launcher-protocol",
742 String(launcherProtocol),
743 ],
744 ]);
745 }).pipe(
746 Effect.provideService(HostProcess.Platform, "linux"),
747 Effect.provideService(HostProcess.Environment, { PATH: "" }),
748 ),
749 );
750 });