Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import type { ManagedUpdatesPolicy } from "@t3tools/contracts";
4import * as HostProcess from "@t3tools/shared/HostProcess";
5import * as Duration from "effect/Duration";
6import * as Effect from "effect/Effect";
7import * as Exit from "effect/Exit";
8import * as FileSystem from "effect/FileSystem";
9import * as Layer from "effect/Layer";
10import * as Option from "effect/Option";
11import * as Path from "effect/Path";
12import * as TestClock from "effect/testing/TestClock";
13import * as TestConsole from "effect/testing/TestConsole";
14import { HttpClient, HttpClientResponse } from "effect/http";
15import * as ChildProcess from "effect/process/ChildProcess";
16import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
17import { afterEach, vi } from "vite-plus/test";
18
19import packageJson from "../../package.json" with { type: "json" };
20import * as BootService from "../cloud/bootService.ts";
21import { SERVICE_LAUNCHER_PROTOCOL } from "../cloud/serviceProtocol.ts";
22import {
23 pinnedRuntimePaths,
24 posixLauncherScript,
25 prunePinnedRuntimes,
26 readPosixLauncherTarget,
27 resolveLauncherPath,
28} from "../cloud/pinnedRuntime.ts";
29import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
30import * as ProcessRunner from "../processRunner.ts";
31import {
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.
39const 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
53afterEach(() => vi.restoreAllMocks());
54
55it.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
78it.effect(
79 "uses --github-token to resolve draft preview releases and explains auth when missing",
80 () =>
81 Effect.gen(function* () {
82 const authHeaders: Array<string | undefined> = [];
83 const httpClient = HttpClient.make((request) => {
84 authHeaders.push(request.headers.authorization);
85 const releases =
86 request.headers.authorization === "Bearer cli-token"
87 ? [
88 { tag_name: "v1.2.5", draft: true },
89 { tag_name: "v1.2.5-preview.20261112.4603", draft: true },
90 { tag_name: "v1.2.4" },
91 ]
92 : [{ tag_name: "v1.2.4" }];
93 return Effect.succeed(HttpClientResponse.fromWeb(request, Response.json(releases)));
94 });
95
96 const previewVersion = yield* resolveNewestVersion("preview", "cli-token").pipe(
97 Effect.provideService(HostProcess.Environment, { GH_TOKEN: "env-token" }),
98 Effect.provideService(HttpClient.HttpClient, httpClient),
99 );
100 assert.equal(previewVersion, "1.2.5-preview.20261112.4603");
101 assert.deepStrictEqual(authHeaders, ["Bearer cli-token"]);
102
103 // Stable still ignores draft releases even when authenticated.
104 const stableVersion = yield* resolveNewestVersion("stable", "cli-token").pipe(
105 Effect.provideService(HostProcess.Environment, {}),
106 Effect.provideService(HttpClient.HttpClient, httpClient),
107 );
108 assert.equal(stableVersion, "1.2.4");
109
110 const unauthenticated = yield* resolveNewestVersion("preview").pipe(
111 Effect.flip,
112 Effect.provideService(HostProcess.Environment, {}),
113 Effect.provideService(
114 HttpClient.HttpClient,
115 HttpClient.make((request) =>
116 Effect.succeed(HttpClientResponse.fromWeb(request, Response.json([]))),
117 ),
118 ),
119 );
120 assert.equal(
121 unauthenticated.message,
122 "No published preview release was found. If it's behind auth, run `t3 update --channel preview --github-token $(gh auth token)`.",
123 );
124
125 const rejected = yield* resolveNewestVersion("preview", "bad-token").pipe(
126 Effect.flip,
127 Effect.provideService(HostProcess.Environment, {}),
128 Effect.provideService(
129 HttpClient.HttpClient,
130 HttpClient.make((request) =>
131 Effect.succeed(
132 HttpClientResponse.fromWeb(request, new Response("Unauthorized", { status: 401 })),
133 ),
134 ),
135 ),
136 );
137 assert.include(rejected.message, "GitHub rejected the provided token");
138 }),
139);
140
141it.effect("reads the newest version from the update feed file a mirror publishes", () =>
142 Effect.gen(function* () {
143 const requested: string[] = [];
144 const mirror = {
145 organization: "Example Corp",
146 feedUrl: "https://updates.example.com/t3code/?token=abc",
147 };
148 const resolve = (
149 channel: "stable" | "nightly" | "preview",
150 platform: NodeJS.Platform,
151 arch: string,
152 feed: string,
153 ) =>
154 resolveMirrorVersion(mirror, channel).pipe(
155 Effect.map((version): string => version),
156 Effect.catchTags({ CliUpdateError: (error) => Effect.succeed(`error: ${error.reason}`) }),
157 Effect.provideService(HostProcess.Platform, platform),
158 Effect.provideService(HostProcess.Architecture, arch),
159 Effect.provideService(
160 HttpClient.HttpClient,
161 HttpClient.make((request) => {
162 requested.push(request.url);
163 return Effect.succeed(HttpClientResponse.fromWeb(request, new Response(feed)));
164 }),
165 ),
166 );
167
168 assert.equal(
169 yield* resolve("stable", "darwin", "arm64", "version: 1.4.0\nfiles: []\n"),
170 "1.4.0",
171 );
172 assert.equal(
173 yield* resolve("nightly", "linux", "arm64", "version: '1.5.0-nightly.20261101.2'\n"),
174 "1.5.0-nightly.20261101.2",
175 );
176 assert.deepStrictEqual(requested, [
177 "https://updates.example.com/t3code/latest-mac.yml?token=abc",
178 "https://updates.example.com/t3code/nightly-linux-arm64.yml?token=abc",
179 ]);
180 // A feed for the wrong track is not trusted to mean the requested one.
181 assert.include(
182 yield* resolve("stable", "win32", "x64", "version: 1.5.0-nightly.20261101.2\n"),
183 "Could not read latest.yml from Example Corp's update mirror.",
184 );
185 assert.include(yield* resolve("preview", "win32", "x64", ""), "has no preview builds");
186 }),
187);
188
189it.layer(NodeServices.layer)("t3 update under a managed policy", (it) => {
190 const runWithPolicy = (
191 updates: ManagedUpdatesPolicy,
192 input: { readonly channel?: "stable" | "nightly"; readonly requestedVersion?: string } = {},
193 httpClient = HttpClient.make(() => Effect.die("unexpected release lookup")),
194 ) =>
195 runUpdate({
196 baseDir: "/unused",
197 logsDir: "/unused",
198 databasePath: "/unused",
199 serverRuntimeStatePath: "/unused",
200 channel: input.channel,
201 requestedVersion: input.requestedVersion,
202 allowDowngrade: false,
203 assumeYes: true,
204 }).pipe(
205 Effect.flip,
206 Effect.provide(
207 Layer.mergeAll(
208 ManagedPolicy.layerTest({
209 schemaVersion: 1,
210 organization: "Example Corp",
211 limits: { updates },
212 }),
213 // Refusals happen before the update touches the network, the service, or a process.
214 Layer.mock(BootService.BootService, {}),
215 Layer.mock(ProcessRunner.ProcessRunner, {}),
216 Layer.succeed(HttpClient.HttpClient, httpClient),
217 ),
218 ),
219 );
220
221 it.effect("refuses to update when updates are off", () =>
222 Effect.gen(function* () {
223 const error = yield* runWithPolicy({ mode: "off" });
224 assert.equal(error.message, "Example Corp manages T3 Code updates.");
225 }),
226 );
227
228 it.effect("refuses nightly releases when the policy disallows them", () =>
229 Effect.gen(function* () {
230 const byChannel = yield* runWithPolicy(
231 { mode: "auto", allowNightly: false },
232 { channel: "nightly" },
233 );
234 const byVersion = yield* runWithPolicy(
235 { mode: "auto", allowNightly: false },
236 { channel: "stable", requestedVersion: "1.2.0-nightly.20261028.1" },
237 );
238 for (const error of [byChannel, byVersion]) {
239 assert.equal(
240 error.message,
241 "Example Corp manages T3 Code updates. Only stable releases can be installed.",
242 );
243 }
244 }),
245 );
246
247 it.effect("looks for updates on the policy's mirror, never the public releases", () =>
248 Effect.gen(function* () {
249 const requested: string[] = [];
250 const error = yield* runWithPolicy(
251 { mode: "auto", feedUrl: "https://updates.example.com/t3code" },
252 { channel: "stable" },
253 HttpClient.make((request) => {
254 requested.push(new URL(request.url).origin);
255 return Effect.succeed(
256 HttpClientResponse.fromWeb(request, new Response("", { status: 404 })),
257 );
258 }),
259 );
260 assert.include(error.message, "from Example Corp's update mirror");
261 assert.deepStrictEqual(requested, ["https://updates.example.com"]);
262 }),
263 );
264});
265
266it.layer(NodeServices.layer)("t3 update launcher", (it) => {
267 it.effect("replaces a legacy symlink with a script that execs the new version", () =>
268 Effect.gen(function* () {
269 const fs = yield* FileSystem.FileSystem;
270 const path = yield* Path.Path;
271 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
272 const oldExe = path.join(root, "runtime/versions/1.0.0/t3");
273 const newExe = path.join(root, "runtime/versions/2.0.0/t3");
274 const launcher = path.join(root, "bin/t3");
275 for (const file of [oldExe, newExe]) {
276 yield* fs.makeDirectory(path.dirname(file), { recursive: true });
277 yield* fs.writeFileString(file, "");
278 }
279 yield* fs.makeDirectory(path.dirname(launcher), { recursive: true });
280 yield* fs.symlink(oldExe, launcher);
281
282 const repointed = yield* repointLauncher({
283 launchedAs: launcher,
284 baseDir: root,
285 targetEntryPath: newExe,
286 });
287
288 assert.deepStrictEqual(Option.getOrUndefined(repointed), launcher);
289 assert.equal(yield* fs.readFileString(launcher), posixLauncherScript(newExe));
290 // Replaced, not written through.
291 assert.equal(yield* fs.readFileString(oldExe), "");
292 }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
293 );
294
295 it.effect("repoints a recorded Windows launcher outside PATH", () =>
296 Effect.gen(function* () {
297 const fs = yield* FileSystem.FileSystem;
298 const path = yield* Path.Path;
299 const root = yield* fs.makeTempDirectoryScoped();
300 const baseDir = path.join(root, "home");
301 const runtimeDir = path.join(baseDir, "runtime");
302 const launcher = path.join(root, "custom bin", "t3.cmd");
303 const launchedAs = path.join(runtimeDir, "versions", "1.0.0", "t3.exe");
304 const targetEntryPath = path.join(runtimeDir, "versions", "2.0.0", "t3.exe");
305 yield* fs.makeDirectory(runtimeDir, { recursive: true });
306 yield* fs.makeDirectory(path.dirname(launcher), { recursive: true });
307 yield* fs.writeFileString(launcher, `@echo off\r\n"${launchedAs}" %*`);
308 yield* fs.writeFileString(path.join(runtimeDir, "launchers"), `${launcher}\r\n`);
309
310 const repointed = yield* repointLauncher({ launchedAs, baseDir, targetEntryPath });
311
312 assert.equal(Option.getOrUndefined(repointed), launcher);
313 assert.equal(yield* fs.readFileString(launcher), `@echo off\r\n"${targetEntryPath}" %*`);
314 }).pipe(
315 Effect.scoped,
316 Effect.provideService(HostProcess.Platform, "win32"),
317 Effect.provideService(HostProcess.Environment, { PATH: "" }),
318 ),
319 );
320
321 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
322 "finds the script that ran this executable and rewrites it, keeping aliases and arguments",
323 () =>
324 Effect.gen(function* () {
325 const fs = yield* FileSystem.FileSystem;
326 const path = yield* Path.Path;
327 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
328 const root = yield* fs.realPath(
329 yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" }),
330 );
331 // A quote and a space in the home path exercise the script's quoting.
332 const home = path.join(root, "it's home");
333 const entry = (version: string) => path.join(home, "runtime/versions", version, "t3");
334 for (const version of ["1.0.0", "2.0.0"]) {
335 yield* fs.makeDirectory(path.dirname(entry(version)), { recursive: true });
336 yield* fs.writeFileString(entry(version), '#!/bin/sh\nprintf \'[%s]\\n\' "$0" "$@"\n', {
337 mode: 0o755,
338 });
339 }
340 const launcher = path.join(root, "bin/t3");
341 const alias = path.join(root, "alias/t3");
342 yield* fs.makeDirectory(path.dirname(launcher), { recursive: true });
343 yield* fs.makeDirectory(path.dirname(alias), { recursive: true });
344 yield* fs.writeFileString(launcher, posixLauncherScript(entry("1.0.0")), { mode: 0o755 });
345 yield* fs.symlink(launcher, alias);
346 const repoint = (environment: Record<string, string>) =>
347 repointLauncher({
348 // The script execs by absolute path, so argv0 names the executable.
349 launchedAs: entry("1.0.0"),
350 baseDir: home,
351 targetEntryPath: entry("2.0.0"),
352 }).pipe(Effect.provideService(HostProcess.Environment, environment));
353
354 assert.equal(
355 Option.getOrUndefined(yield* repoint({ PATH: path.dirname(alias) })),
356 launcher,
357 );
358 assert.equal(yield* fs.readLink(alias), launcher);
359 const args = ["two words", "it's quoted", "", "*", "$HOME"];
360 assert.equal(
361 yield* spawner.string(ChildProcess.make(alias, args, { cwd: root })),
362 [entry("2.0.0"), ...args].map((arg) => `[${arg}]\n`).join(""),
363 );
364
365 // Like the shell, a relative PATH entry resolves from the working directory, and a
366 // script nobody can execute is passed over.
367 const unrunnable = path.join(root, "unrunnable/t3");
368 yield* fs.makeDirectory(path.dirname(unrunnable), { recursive: true });
369 yield* fs.writeFileString(unrunnable, posixLauncherScript(entry("2.0.0")), { mode: 0o644 });
370 yield* fs.writeFileString(launcher, posixLauncherScript(entry("2.0.0")), { mode: 0o755 });
371 const relative = yield* repointLauncher({
372 launchedAs: entry("2.0.0"),
373 baseDir: home,
374 targetEntryPath: entry("1.0.0"),
375 }).pipe(
376 Effect.provideService(HostProcess.Environment, {
377 PATH: `${path.dirname(unrunnable)}:bin`,
378 }),
379 Effect.provideService(HostProcess.WorkingDirectory, root),
380 );
381 assert.equal(Option.getOrUndefined(relative), launcher);
382 assert.equal(yield* fs.readFileString(unrunnable), posixLauncherScript(entry("2.0.0")));
383
384 // An edited script is the user's own wrapper now.
385 const edited = `${posixLauncherScript(entry("1.0.0"))}# mine\n`;
386 yield* fs.writeFileString(launcher, edited);
387 assert.isTrue(Option.isNone(yield* repoint({ PATH: path.dirname(launcher) })));
388 assert.equal(yield* fs.readFileString(launcher), edited);
389 }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
390 );
391
392 it.effect.each([
393 { name: "no launcher records", recorded: undefined },
394 { name: "an empty launcher record", recorded: "" },
395 { name: "whole launcher records", recorded: "/opt/t3\n" },
396 { name: "Windows launcher records", recorded: "C:\\t3.cmd\r\n" },
397 // An interrupted append cut this record short.
398 { name: "an unterminated launcher record", recorded: "/opt/t" },
399 // Another process's append is cut short after t3 update reads the records.
400 { name: "a record cut short after the read", recorded: "/opt/t3\n", cut: "/opt/t" },
401 ])("keeps the runtime a repointed launcher off PATH points at with $name", ({ recorded, cut }) =>
402 Effect.gen(function* () {
403 const fs = yield* FileSystem.FileSystem;
404 const path = yield* Path.Path;
405 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
406 yield* TestClock.setTime(Duration.toMillis(Duration.days(1)));
407 for (const version of ["1.0.0", "2.0.0"]) {
408 const directory = path.join(root, "runtime/versions", version);
409 yield* fs.makeDirectory(directory, { recursive: true });
410 yield* fs.writeFileString(path.join(directory, "t3"), "");
411 yield* fs.writeFileString(path.join(directory, ".install-complete"), `${version}\n`);
412 yield* fs.utimes(path.join(directory, ".install-complete"), 0, 0);
413 }
414 if (recorded !== undefined) {
415 yield* fs.writeFileString(path.join(root, "runtime/launchers"), recorded);
416 }
417 // A launcher in the T3 home itself, which neither PATH nor the default bin dir reaches.
418 const launcher = path.join(root, "t3");
419 yield* fs.symlink(path.join(root, "runtime/versions/1.0.0/t3"), launcher);
420
421 const launchersFile = path.join(root, "runtime/launchers");
422 yield* repointLauncher({
423 launchedAs: launcher,
424 baseDir: root,
425 targetEntryPath: path.join(root, "runtime/versions/2.0.0/t3"),
426 }).pipe(
427 Effect.provideService(FileSystem.FileSystem, {
428 ...fs,
429 readFileString: (file, encoding) =>
430 fs
431 .readFileString(file, encoding)
432 .pipe(
433 Effect.tap(() =>
434 cut === undefined || file !== launchersFile
435 ? Effect.void
436 : fs.writeFileString(file, cut, { flag: "a" }),
437 ),
438 ),
439 }),
440 );
441 // A later server start prunes with no idea how this machine launches t3.
442 const removed = yield* prunePinnedRuntimes({ baseDir: root, keep: [] }).pipe(
443 Effect.provideService(ProcessRunner.ProcessRunner, unrelatedLsof),
444 Effect.provideService(HostProcess.Platform, "darwin"),
445 Effect.provideService(HostProcess.Environment, { PATH: "" }),
446 Effect.provideService(HostProcess.HomeDirectory, root),
447 );
448
449 assert.deepStrictEqual(removed, ["1.0.0"]);
450 assert.equal(
451 yield* readPosixLauncherTarget(launcher),
452 path.join(root, "runtime/versions/2.0.0/t3"),
453 );
454 }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
455 );
456
457 const launcherFixture = Effect.fnUntraced(function* () {
458 const fs = yield* FileSystem.FileSystem;
459 const path = yield* Path.Path;
460 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
461 const oldExe = path.join(root, "runtime/versions/1.0.0/t3");
462 const newExe = path.join(root, "runtime/versions/2.0.0/t3");
463 const launcher = path.join(root, "t3");
464 for (const file of [oldExe, newExe]) {
465 yield* fs.makeDirectory(path.dirname(file), { recursive: true });
466 yield* fs.writeFileString(file, "");
467 }
468 yield* fs.symlink(oldExe, launcher);
469 return { root, oldExe, newExe, launcher, launchersFile: path.join(root, "runtime/launchers") };
470 });
471
472 it.effect("records a relative launcher path as absolute", () =>
473 Effect.gen(function* () {
474 const fs = yield* FileSystem.FileSystem;
475 const path = yield* Path.Path;
476 const { root, newExe, launcher, launchersFile } = yield* launcherFixture();
477
478 yield* repointLauncher({
479 launchedAs: path.relative(path.resolve("."), launcher),
480 baseDir: root,
481 targetEntryPath: newExe,
482 });
483
484 assert.equal(yield* fs.readFileString(launchersFile), `\n${launcher}\n`);
485 }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
486 );
487
488 it.effect("fails instead of repointing a launcher it cannot record", () =>
489 Effect.gen(function* () {
490 const fs = yield* FileSystem.FileSystem;
491 const { root, oldExe, newExe, launcher, launchersFile } = yield* launcherFixture();
492 // Appending to a directory fails the way a read-only or full disk would.
493 yield* fs.makeDirectory(launchersFile);
494
495 const result = yield* repointLauncher({
496 launchedAs: launcher,
497 baseDir: root,
498 targetEntryPath: newExe,
499 }).pipe(Effect.exit);
500
501 assert.isTrue(Exit.isFailure(result));
502 assert.equal(yield* fs.readLink(launcher), oldExe);
503 }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
504 );
505
506 it.effect.each(["recording", "repointing"] as const)(
507 "never leaves a repointed launcher unrecorded when t3 update dies while %s",
508 (step) =>
509 Effect.gen(function* () {
510 const fs = yield* FileSystem.FileSystem;
511 const { root, newExe, launcher, launchersFile } = yield* launcherFixture();
512
513 yield* repointLauncher({
514 launchedAs: launcher,
515 baseDir: root,
516 targetEntryPath: newExe,
517 }).pipe(
518 Effect.provideService(FileSystem.FileSystem, {
519 ...fs,
520 writeFileString: (path, data, options) =>
521 step === "recording" && path === launchersFile
522 ? Effect.die("t3 update was killed")
523 : fs.writeFileString(path, data, options),
524 rename: (from, to) =>
525 step === "repointing" && to === launcher
526 ? Effect.die("t3 update was killed")
527 : fs.rename(from, to),
528 }),
529 Effect.exit,
530 );
531
532 const repointed = (yield* readPosixLauncherTarget(launcher)) === newExe;
533 const recorded = (yield* fs
534 .readFileString(launchersFile)
535 .pipe(Effect.orElseSucceed(() => "")))
536 .split("\n")
537 .includes(launcher);
538 assert.isFalse(repointed && !recorded);
539 }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
540 );
541
542 it.effect("leaves a plain copy or a foreign symlink alone", () =>
543 Effect.gen(function* () {
544 const fs = yield* FileSystem.FileSystem;
545 const path = yield* Path.Path;
546 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
547 const newExe = path.join(root, "runtime/versions/2.0.0/t3");
548 const copy = path.join(root, "copy/t3");
549 const foreign = path.join(root, "foreign/t3");
550 const elsewhere = path.join(root, "elsewhere/t3");
551 const otherHome = path.join(root, "other/runtime/versions/1.0.0/t3");
552 const otherLauncher = path.join(root, "other/bin/t3");
553 for (const file of [newExe, copy, elsewhere, otherHome]) {
554 yield* fs.makeDirectory(path.dirname(file), { recursive: true });
555 yield* fs.writeFileString(file, "");
556 }
557 yield* fs.makeDirectory(path.dirname(foreign), { recursive: true });
558 yield* fs.symlink(elsewhere, foreign);
559 yield* fs.makeDirectory(path.dirname(otherLauncher), { recursive: true });
560 yield* fs.symlink(otherHome, otherLauncher);
561
562 for (const launchedAs of [copy, foreign, otherLauncher, undefined]) {
563 const repointed = yield* repointLauncher({
564 launchedAs,
565 baseDir: root,
566 targetEntryPath: newExe,
567 });
568 assert.equal(repointed._tag, "None", launchedAs ?? "undefined");
569 }
570 assert.equal(yield* fs.readLink(foreign), elsewhere);
571 assert.equal(yield* fs.readLink(otherLauncher), otherHome);
572 }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
573 );
574
575 it.effect("finds the launcher a bare command name resolved to on PATH", () =>
576 Effect.gen(function* () {
577 const fs = yield* FileSystem.FileSystem;
578 const path = yield* Path.Path;
579 const delimiter = (yield* HostProcess.Platform) === "win32" ? ";" : ":";
580 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
581 const launcher = path.join(root, "bin/t3");
582 yield* fs.makeDirectory(path.dirname(launcher), { recursive: true });
583 yield* fs.writeFileString(launcher, "", { mode: 0o755 });
584
585 const bare = yield* resolveLauncherPath.pipe(
586 Effect.provideService(HostProcess.InvokedAs, "t3"),
587 Effect.provideService(HostProcess.Environment, {
588 PATH: [path.join(root, "missing"), path.join(root, "bin")].join(delimiter),
589 }),
590 Effect.provideService(HostProcess.WorkingDirectory, root),
591 );
592 const relative = yield* resolveLauncherPath.pipe(
593 Effect.provideService(HostProcess.InvokedAs, "./bin/t3"),
594 Effect.provideService(HostProcess.Environment, { PATH: "" }),
595 Effect.provideService(HostProcess.WorkingDirectory, root),
596 );
597 const absent = yield* resolveLauncherPath.pipe(
598 Effect.provideService(HostProcess.InvokedAs, "t3"),
599 Effect.provideService(HostProcess.Environment, { PATH: path.join(root, "missing") }),
600 Effect.provideService(HostProcess.WorkingDirectory, root),
601 );
602
603 assert.equal(bare, launcher);
604 assert.equal(relative, launcher);
605 assert.equal(absent, undefined);
606 }),
607 );
608});
609
610// Without terminals, update skips its restart prompt whatever runs the test.
611const withoutTerminals = Effect.acquireRelease(
612 Effect.sync(() =>
613 [process.stdin, process.stdout].map((stream) => {
614 const descriptor = Object.getOwnPropertyDescriptor(stream, "isTTY");
615 Object.defineProperty(stream, "isTTY", { configurable: true, value: false });
616 return { stream, descriptor };
617 }),
618 ),
619 (saved) =>
620 Effect.sync(() => {
621 for (const { stream, descriptor } of saved) {
622 if (descriptor === undefined) Reflect.deleteProperty(stream, "isTTY");
623 else Object.defineProperty(stream, "isTTY", descriptor);
624 }
625 }),
626);
627
628it.layer(NodeServices.layer)("t3 update with a background service", (it) => {
629 it.effect("names the version a service with a pending restart still runs", () =>
630 Effect.gen(function* () {
631 yield* withoutTerminals;
632 const fs = yield* FileSystem.FileSystem;
633 const path = yield* Path.Path;
634 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3 update " });
635 const version = packageJson.version;
636 const runtime = pinnedRuntimePaths(path, baseDir, version, "linux");
637 yield* fs.makeDirectory(runtime.versionDir, { recursive: true });
638 yield* fs.writeFileString(runtime.entryPath, "");
639 yield* fs.writeFileString(runtime.sentinelPath, `${version}\n`);
640 const unitPath = path.join(baseDir, "t3code.service");
641 const logPath = path.join(baseDir, "boot-service.log");
642 // An earlier `t3 update` pointed the service at this version without restarting it.
643 const service = Layer.mock(BootService.BootService, {
644 status: Effect.succeed<BootService.BootServiceStatus>({
645 supported: true,
646 installed: true,
647 current: false,
648 installedVersion: version,
649 installedBaseDir: baseDir,
650 problems: ["restart-pending"],
651 unitPath,
652 logPath,
653 }),
654 install: () => Effect.succeed({ program: [runtime.entryPath], baseDir, unitPath, logPath }),
655 });
656 vi.spyOn(BootService, "layer").mockReturnValue(service);
657 const runner = ProcessRunner.ProcessRunner.of({
658 run: (input) =>
659 input.args?.includes("__service-preflight") === true
660 ? unrelatedLsof.run(input).pipe(
661 Effect.map((result) => ({
662 ...result,
663 stdout: JSON.stringify({
664 status: "ready",
665 version,
666 launcherProtocol: SERVICE_LAUNCHER_PROTOCOL,
667 }),
668 })),
669 )
670 : unrelatedLsof.run(input),
671 });
672
673 const output = yield* runUpdate({
674 baseDir,
675 logsDir: baseDir,
676 databasePath: path.join(baseDir, "statev2.sqlite"),
677 serverRuntimeStatePath: path.join(baseDir, "server-runtime.json"),
678 channel: undefined,
679 requestedVersion: version,
680 allowDowngrade: false,
681 assumeYes: false,
682 }).pipe(
683 Effect.andThen(TestConsole.logLines),
684 Effect.map((lines) => lines.join("\n")),
685 Effect.provide(
686 Layer.mergeAll(
687 service,
688 Layer.succeed(ProcessRunner.ProcessRunner, runner),
689 ManagedPolicy.layerTest(),
690 Layer.succeed(
691 HttpClient.HttpClient,
692 HttpClient.make(() => Effect.die("unexpected release lookup")),
693 ),
694 Layer.fresh(TestConsole.layer),
695 ),
696 ),
697 );
698
699 assert.include(
700 output,
701 `Background service still running the version before ${version}. Run \`t3 service restart\` when you are ready to switch it to ${version}.`,
702 );
703 // The home holds a space, so the printed command is quoted to paste into a shell.
704 assert.include(output, ` Run '${runtime.entryPath}'`);
705 }).pipe(
706 Effect.provideService(HostProcess.Platform, "linux"),
707 Effect.provideService(HostProcess.Environment, { PATH: "" }),
708 ),
709 );
710});
711
712it.layer(NodeServices.layer)("t3 update with a service whose home it cannot read", (it) => {
713 it.effect("says the service's home could not be determined, not that it serves another", () =>
714 Effect.gen(function* () {
715 yield* withoutTerminals;
716 const fs = yield* FileSystem.FileSystem;
717 const path = yield* Path.Path;
718 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
719 const targetVersion = "99.0.0";
720 const runtime = pinnedRuntimePaths(path, baseDir, targetVersion, "linux");
721 yield* fs.makeDirectory(runtime.versionDir, { recursive: true });
722 yield* fs.writeFileString(runtime.entryPath, "");
723 yield* fs.writeFileString(runtime.sentinelPath, `${targetVersion}\n`);
724 const unitPath = path.join(baseDir, "t3code.service");
725 // A unit that names no home T3 Code can read, such as a quoted Environment= line.
726 const service = Layer.mock(BootService.BootService, {
727 status: Effect.succeed<BootService.BootServiceStatus>({
728 supported: true,
729 installed: true,
730 current: false,
731 problems: [],
732 unitPath,
733 logPath: path.join(baseDir, "boot-service.log"),
734 }),
735 });
736 const runner = ProcessRunner.ProcessRunner.of({
737 run: (input) =>
738 input.args?.includes("__service-preflight") === true
739 ? unrelatedLsof.run(input).pipe(
740 Effect.map((result) => ({
741 ...result,
742 stdout: JSON.stringify({
743 status: "ready",
744 version: targetVersion,
745 launcherProtocol: SERVICE_LAUNCHER_PROTOCOL,
746 }),
747 })),
748 )
749 : unrelatedLsof.run(input),
750 });
751
752 const output = yield* runUpdate({
753 baseDir,
754 logsDir: baseDir,
755 databasePath: path.join(baseDir, "statev2.sqlite"),
756 serverRuntimeStatePath: path.join(baseDir, "server-runtime.json"),
757 channel: undefined,
758 requestedVersion: targetVersion,
759 allowDowngrade: false,
760 assumeYes: true,
761 }).pipe(
762 Effect.andThen(TestConsole.logLines),
763 Effect.map((lines) => lines.join("\n")),
764 Effect.provide(
765 Layer.mergeAll(
766 service,
767 Layer.succeed(ProcessRunner.ProcessRunner, runner),
768 ManagedPolicy.layerTest(),
769 Layer.succeed(
770 HttpClient.HttpClient,
771 HttpClient.make(() => Effect.die("unexpected release lookup")),
772 ),
773 Layer.fresh(TestConsole.layer),
774 ),
775 ),
776 );
777
778 assert.notInclude(output, "another T3 home");
779 assert.include(
780 output,
781 `A background service definition was found, but its T3 home could not be determined, so it was left unchanged. Check ${unitPath}.`,
782 );
783 }).pipe(
784 Effect.provideService(HostProcess.Platform, "linux"),
785 Effect.provideService(HostProcess.Environment, { PATH: "" }),
786 ),
787 );
788});
789
790it.layer(NodeServices.layer)("t3 update checks the database before switching", (it) => {
791 const preflightOutput = (stdout: string, code = 0) => ({
792 stdout,
793 stderr: code === 0 ? "" : "Unknown command: __service-preflight",
794 code: ChildProcessSpawner.ExitCode(code),
795 timedOut: false,
796 stdoutTruncated: false,
797 stderrTruncated: false,
798 stdoutInvalidUtf8: false,
799 stderrInvalidUtf8: false,
800 });
801 const blockedReason = "This database has migrations that t3@0.1.8 does not know: 79_example.";
802
803 it.effect.each([
804 {
805 name: "installs an older target that accepts this database",
806 targetVersion: "0.1.8",
807 launcherProtocol: 3,
808 preflight: preflightOutput(
809 JSON.stringify({ status: "ready", version: "0.1.8", launcherProtocol: 3 }),
810 ),
811 failure: undefined,
812 },
813 {
814 name: "refuses an older target the database is too new for",
815 targetVersion: "0.1.8",
816 launcherProtocol: 3,
817 preflight: preflightOutput(
818 JSON.stringify({ status: "blocked", version: "0.1.8", reason: blockedReason }),
819 ),
820 failure: blockedReason,
821 },
822 {
823 name: "refuses an older target too old to check the database",
824 targetVersion: "0.1.8",
825 launcherProtocol: 3,
826 preflight: preflightOutput("", 1),
827 failure:
828 "t3@0.1.8 could not confirm it supports this database (its check exited with code 1), so t3 did not switch to it.",
829 },
830 {
831 // Newer builds keep accepting the current launcher protocol, which may drop 3.
832 name: "checks a newer target with the current launcher protocol",
833 targetVersion: "99.0.0",
834 launcherProtocol: SERVICE_LAUNCHER_PROTOCOL,
835 preflight: preflightOutput(
836 JSON.stringify({
837 status: "ready",
838 version: "99.0.0",
839 launcherProtocol: SERVICE_LAUNCHER_PROTOCOL,
840 }),
841 ),
842 failure: undefined,
843 },
844 ])("$name", ({ targetVersion, launcherProtocol, preflight, failure }) =>
845 Effect.gen(function* () {
846 const fs = yield* FileSystem.FileSystem;
847 const path = yield* Path.Path;
848 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
849 const databasePath = path.join(baseDir, "userdata", "statev2.sqlite");
850 const runtime = pinnedRuntimePaths(path, baseDir, targetVersion, "linux");
851 yield* fs.makeDirectory(runtime.versionDir, { recursive: true });
852 yield* fs.writeFileString(runtime.entryPath, "");
853 yield* fs.writeFileString(runtime.sentinelPath, `${targetVersion}\n`);
854 const service = Layer.mock(BootService.BootService, {
855 status: Effect.succeed<BootService.BootServiceStatus>({
856 supported: true,
857 installed: false,
858 current: false,
859 unitPath: path.join(baseDir, "t3code.service"),
860 logPath: path.join(baseDir, "boot-service.log"),
861 }),
862 });
863 const preflightArgs: Array<ReadonlyArray<string>> = [];
864 const runner = ProcessRunner.ProcessRunner.of({
865 run: (input) => {
866 if (input.args?.includes("__service-preflight") === true) {
867 preflightArgs.push(input.args);
868 return Effect.succeed(preflight);
869 }
870 // A target's --version always answers, whatever its database support.
871 return input.args?.includes("--version") === true
872 ? Effect.succeed(preflightOutput(`t3 v${targetVersion}\n`))
873 : unrelatedLsof.run(input);
874 },
875 });
876
877 const exit = yield* runUpdate({
878 baseDir,
879 logsDir: baseDir,
880 databasePath,
881 serverRuntimeStatePath: path.join(baseDir, "server-runtime.json"),
882 channel: undefined,
883 requestedVersion: targetVersion,
884 allowDowngrade: true,
885 assumeYes: true,
886 }).pipe(
887 Effect.exit,
888 Effect.provide(
889 Layer.mergeAll(
890 service,
891 Layer.succeed(ProcessRunner.ProcessRunner, runner),
892 ManagedPolicy.layerTest(),
893 Layer.succeed(
894 HttpClient.HttpClient,
895 HttpClient.make(() => Effect.die("unexpected release lookup")),
896 ),
897 Layer.fresh(TestConsole.layer),
898 ),
899 ),
900 );
901
902 const error = Option.getOrUndefined(Exit.findErrorOption(exit));
903 assert.equal(error?.message, failure);
904 assert.equal(Exit.isSuccess(exit), failure === undefined);
905 assert.deepEqual(preflightArgs, [
906 [
907 "__service-preflight",
908 "--database-path",
909 databasePath,
910 "--launcher-protocol",
911 String(launcherProtocol),
912 ],
913 ]);
914 }).pipe(
915 Effect.provideService(HostProcess.Platform, "linux"),
916 Effect.provideService(HostProcess.Environment, { PATH: "" }),
917 ),
918 );
919
920 it.effect("suggests rerunning with --github-token when an unauthenticated release 404s", () =>
921 Effect.gen(function* () {
922 const fs = yield* FileSystem.FileSystem;
923 const path = yield* Path.Path;
924 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-404-" });
925 const service = Layer.mock(BootService.BootService, {
926 status: Effect.succeed<BootService.BootServiceStatus>({
927 supported: true,
928 installed: false,
929 current: false,
930 unitPath: path.join(baseDir, "t3code.service"),
931 logPath: path.join(baseDir, "boot-service.log"),
932 }),
933 });
934
935 const error = yield* runUpdate({
936 baseDir,
937 logsDir: baseDir,
938 databasePath: path.join(baseDir, "userdata", "statev2.sqlite"),
939 serverRuntimeStatePath: path.join(baseDir, "server-runtime.json"),
940 channel: undefined,
941 requestedVersion: "99.0.0",
942 allowDowngrade: false,
943 assumeYes: true,
944 }).pipe(
945 Effect.flip,
946 Effect.provide(
947 Layer.mergeAll(
948 service,
949 Layer.succeed(ProcessRunner.ProcessRunner, unrelatedLsof),
950 ManagedPolicy.layerTest(),
951 Layer.succeed(
952 HttpClient.HttpClient,
953 HttpClient.make((request) =>
954 Effect.succeed(
955 HttpClientResponse.fromWeb(request, new Response("Not Found", { status: 404 })),
956 ),
957 ),
958 ),
959 Layer.fresh(TestConsole.layer),
960 ),
961 ),
962 );
963
964 assert.equal(
965 error.message,
966 "No release archive was found for t3@99.0.0. If it's behind auth, run `t3 update 99.0.0 --yes --github-token $(gh auth token)`.",
967 );
968 }).pipe(
969 Effect.provideService(HostProcess.Platform, "linux"),
970 Effect.provideService(HostProcess.Architecture, "x64"),
971 Effect.provideService(HostProcess.Environment, { PATH: "" }),
972 ),
973 );
974
975 it.effect("does not blame GH_TOKEN when a custom release base URL answers 401", () =>
976 Effect.gen(function* () {
977 const fs = yield* FileSystem.FileSystem;
978 const path = yield* Path.Path;
979 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-mirror-401-" });
980 const service = Layer.mock(BootService.BootService, {
981 status: Effect.succeed<BootService.BootServiceStatus>({
982 supported: true,
983 installed: false,
984 current: false,
985 unitPath: path.join(baseDir, "t3code.service"),
986 logPath: path.join(baseDir, "boot-service.log"),
987 }),
988 });
989
990 const error = yield* runUpdate({
991 baseDir,
992 logsDir: baseDir,
993 databasePath: path.join(baseDir, "userdata", "statev2.sqlite"),
994 serverRuntimeStatePath: path.join(baseDir, "server-runtime.json"),
995 channel: undefined,
996 requestedVersion: "99.0.0",
997 allowDowngrade: false,
998 assumeYes: true,
999 }).pipe(
1000 Effect.flip,
1001 Effect.provide(
1002 Layer.mergeAll(
1003 service,
1004 Layer.succeed(ProcessRunner.ProcessRunner, unrelatedLsof),
1005 ManagedPolicy.layerTest(),
1006 Layer.succeed(
1007 HttpClient.HttpClient,
1008 HttpClient.make((request) => {
1009 assert.isUndefined(request.headers.authorization);
1010 return Effect.succeed(
1011 HttpClientResponse.fromWeb(
1012 request,
1013 new Response("Unauthorized", { status: 401 }),
1014 ),
1015 );
1016 }),
1017 ),
1018 Layer.fresh(TestConsole.layer),
1019 ),
1020 ),
1021 );
1022
1023 assert.notInclude(error.message, "GitHub rejected");
1024 }).pipe(
1025 Effect.provideService(HostProcess.Platform, "linux"),
1026 Effect.provideService(HostProcess.Architecture, "x64"),
1027 Effect.provideService(HostProcess.Environment, {
1028 PATH: "",
1029 GH_TOKEN: "gh-secret",
1030 T3CODE_RELEASE_BASE_URL: "https://mirror.example.com/t3code",
1031 }),
1032 ),
1033 );
1034});