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