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 ChildProcessSpawner from "effect/process/ChildProcessSpawner";
16import { afterEach, vi } from "vite-plus/test";
17
18import packageJson from "../../package.json" with { type: "json" };
19import * as BootService from "../cloud/bootService.ts";
20import {
21 pinnedRuntimePaths,
22 prunePinnedRuntimes,
23 resolveLauncherPath,
24} from "../cloud/pinnedRuntime.ts";
25import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
26import * as ProcessRunner from "../processRunner.ts";
27import {
28 repointLauncher,
29 resolveMirrorVersion,
30 resolveNewestVersion,
31 runUpdate,
32} from "./update.ts";
33
34// lsof listing one process, so prune sees a process list in which no runtime is running.
35const unrelatedLsof = ProcessRunner.ProcessRunner.of({
36 run: () =>
37 Effect.succeed({
38 stdout: "p1\nftxt\nn/usr/bin/true\n",
39 stderr: "",
40 code: ChildProcessSpawner.ExitCode(0),
41 timedOut: false,
42 stdoutTruncated: false,
43 stderrTruncated: false,
44 stdoutInvalidUtf8: false,
45 stderrInvalidUtf8: false,
46 }),
47});
48
49afterEach(() => vi.restoreAllMocks());
50
51it.effect("authenticates each release page until the requested channel is found", () =>
52 Effect.gen(function* () {
53 const pages: string[] = [];
54 const httpClient = HttpClient.make((request) => {
55 const url = new URL(request.url);
56 assert.equal(url.origin, "https://api.github.com");
57 assert.equal(url.pathname, "/repos/pingdotgg/t3code/releases");
58 assert.equal(request.headers.accept, "application/vnd.github+json");
59 assert.equal(request.headers.authorization, "Bearer gh-token");
60 const page = url.searchParams.get("page") ?? "";
61 pages.push(page);
62 const tag_name = page === "1" ? "v1.2.4-preview.20260101.1" : "v1.2.3";
63 return Effect.succeed(HttpClientResponse.fromWeb(request, Response.json([{ tag_name }])));
64 });
65 const version = yield* resolveNewestVersion("stable").pipe(
66 Effect.provideService(HostProcess.Environment, { GH_TOKEN: "gh-token" }),
67 Effect.provideService(HttpClient.HttpClient, httpClient),
68 );
69 assert.equal(version, "1.2.3");
70 assert.deepStrictEqual(pages, ["1", "2"]);
71 }),
72);
73
74it.effect("reads the newest version from the update feed file a mirror publishes", () =>
75 Effect.gen(function* () {
76 const requested: string[] = [];
77 const mirror = {
78 organization: "Example Corp",
79 feedUrl: "https://updates.example.com/t3code/?token=abc",
80 };
81 const resolve = (
82 channel: "stable" | "nightly" | "preview",
83 platform: NodeJS.Platform,
84 arch: string,
85 feed: string,
86 ) =>
87 resolveMirrorVersion(mirror, channel).pipe(
88 Effect.map((version): string => version),
89 Effect.catchTags({ CliUpdateError: (error) => Effect.succeed(`error: ${error.reason}`) }),
90 Effect.provideService(HostProcess.Platform, platform),
91 Effect.provideService(HostProcess.Architecture, arch),
92 Effect.provideService(
93 HttpClient.HttpClient,
94 HttpClient.make((request) => {
95 requested.push(request.url);
96 return Effect.succeed(HttpClientResponse.fromWeb(request, new Response(feed)));
97 }),
98 ),
99 );
100
101 assert.equal(
102 yield* resolve("stable", "darwin", "arm64", "version: 1.4.0\nfiles: []\n"),
103 "1.4.0",
104 );
105 assert.equal(
106 yield* resolve("nightly", "linux", "arm64", "version: '1.5.0-nightly.20261101.2'\n"),
107 "1.5.0-nightly.20261101.2",
108 );
109 assert.deepStrictEqual(requested, [
110 "https://updates.example.com/t3code/latest-mac.yml?token=abc",
111 "https://updates.example.com/t3code/nightly-linux-arm64.yml?token=abc",
112 ]);
113 // A feed for the wrong track is not trusted to mean the requested one.
114 assert.include(
115 yield* resolve("stable", "win32", "x64", "version: 1.5.0-nightly.20261101.2\n"),
116 "Could not read latest.yml from Example Corp's update mirror.",
117 );
118 assert.include(yield* resolve("preview", "win32", "x64", ""), "has no preview builds");
119 }),
120);
121
122it.layer(NodeServices.layer)("t3 update under a managed policy", (it) => {
123 const runWithPolicy = (
124 updates: ManagedUpdatesPolicy,
125 input: { readonly channel?: "stable" | "nightly"; readonly requestedVersion?: string } = {},
126 httpClient = HttpClient.make(() => Effect.die("unexpected release lookup")),
127 ) =>
128 runUpdate({
129 baseDir: "/unused",
130 logsDir: "/unused",
131 serverRuntimeStatePath: "/unused",
132 channel: input.channel,
133 requestedVersion: input.requestedVersion,
134 allowDowngrade: false,
135 assumeYes: true,
136 }).pipe(
137 Effect.flip,
138 Effect.provide(
139 Layer.mergeAll(
140 ManagedPolicy.layerTest({
141 schemaVersion: 1,
142 organization: "Example Corp",
143 limits: { updates },
144 }),
145 // Refusals happen before the update touches the network, the service, or a process.
146 Layer.mock(BootService.BootService, {}),
147 Layer.mock(ProcessRunner.ProcessRunner, {}),
148 Layer.succeed(HttpClient.HttpClient, httpClient),
149 ),
150 ),
151 );
152
153 it.effect("refuses to update when updates are off", () =>
154 Effect.gen(function* () {
155 const error = yield* runWithPolicy({ mode: "off" });
156 assert.equal(error.message, "Example Corp manages T3 Code updates.");
157 }),
158 );
159
160 it.effect("refuses nightly releases when the policy disallows them", () =>
161 Effect.gen(function* () {
162 const byChannel = yield* runWithPolicy(
163 { mode: "auto", allowNightly: false },
164 { channel: "nightly" },
165 );
166 const byVersion = yield* runWithPolicy(
167 { mode: "auto", allowNightly: false },
168 { channel: "stable", requestedVersion: "1.2.0-nightly.20261028.1" },
169 );
170 for (const error of [byChannel, byVersion]) {
171 assert.equal(
172 error.message,
173 "Example Corp manages T3 Code updates. Only stable releases can be installed.",
174 );
175 }
176 }),
177 );
178
179 it.effect("looks for updates on the policy's mirror, never the public releases", () =>
180 Effect.gen(function* () {
181 const requested: string[] = [];
182 const error = yield* runWithPolicy(
183 { mode: "auto", feedUrl: "https://updates.example.com/t3code" },
184 { channel: "stable" },
185 HttpClient.make((request) => {
186 requested.push(new URL(request.url).origin);
187 return Effect.succeed(
188 HttpClientResponse.fromWeb(request, new Response("", { status: 404 })),
189 );
190 }),
191 );
192 assert.include(error.message, "from Example Corp's update mirror");
193 assert.deepStrictEqual(requested, ["https://updates.example.com"]);
194 }),
195 );
196});
197
198it.layer(NodeServices.layer)("t3 update launcher", (it) => {
199 it.effect("repoints a symlink that lives in a runtime versions tree", () =>
200 Effect.gen(function* () {
201 const fs = yield* FileSystem.FileSystem;
202 const path = yield* Path.Path;
203 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
204 const oldExe = path.join(root, "runtime/versions/1.0.0/t3");
205 const newExe = path.join(root, "runtime/versions/2.0.0/t3");
206 const launcher = path.join(root, "bin/t3");
207 for (const file of [oldExe, newExe]) {
208 yield* fs.makeDirectory(path.dirname(file), { recursive: true });
209 yield* fs.writeFileString(file, "");
210 }
211 yield* fs.makeDirectory(path.dirname(launcher), { recursive: true });
212 yield* fs.symlink(oldExe, launcher);
213
214 const repointed = yield* repointLauncher({
215 launchedAs: launcher,
216 baseDir: root,
217 targetEntryPath: newExe,
218 });
219
220 assert.deepStrictEqual(Option.getOrUndefined(repointed), launcher);
221 assert.equal(yield* fs.readLink(launcher), newExe);
222 }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
223 );
224
225 it.effect.each([
226 { name: "no launcher records", recorded: undefined },
227 { name: "an empty launcher record", recorded: "" },
228 { name: "whole launcher records", recorded: "/opt/t3\n" },
229 { name: "Windows launcher records", recorded: "C:\\t3.cmd\r\n" },
230 // An interrupted append cut this record short.
231 { name: "an unterminated launcher record", recorded: "/opt/t" },
232 // Another process's append is cut short after t3 update reads the records.
233 { name: "a record cut short after the read", recorded: "/opt/t3\n", cut: "/opt/t" },
234 ])("keeps the runtime a repointed launcher off PATH points at with $name", ({ recorded, cut }) =>
235 Effect.gen(function* () {
236 const fs = yield* FileSystem.FileSystem;
237 const path = yield* Path.Path;
238 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
239 yield* TestClock.setTime(Duration.toMillis(Duration.days(1)));
240 for (const version of ["1.0.0", "2.0.0"]) {
241 const directory = path.join(root, "runtime/versions", version);
242 yield* fs.makeDirectory(directory, { recursive: true });
243 yield* fs.writeFileString(path.join(directory, "t3"), "");
244 yield* fs.writeFileString(path.join(directory, ".install-complete"), `${version}\n`);
245 yield* fs.utimes(path.join(directory, ".install-complete"), 0, 0);
246 }
247 if (recorded !== undefined) {
248 yield* fs.writeFileString(path.join(root, "runtime/launchers"), recorded);
249 }
250 // A launcher in the T3 home itself, which neither PATH nor the default bin dir reaches.
251 const launcher = path.join(root, "t3");
252 yield* fs.symlink(path.join(root, "runtime/versions/1.0.0/t3"), launcher);
253
254 const launchersFile = path.join(root, "runtime/launchers");
255 yield* repointLauncher({
256 launchedAs: launcher,
257 baseDir: root,
258 targetEntryPath: path.join(root, "runtime/versions/2.0.0/t3"),
259 }).pipe(
260 Effect.provideService(FileSystem.FileSystem, {
261 ...fs,
262 readFileString: (file, encoding) =>
263 fs
264 .readFileString(file, encoding)
265 .pipe(
266 Effect.tap(() =>
267 cut === undefined || file !== launchersFile
268 ? Effect.void
269 : fs.writeFileString(file, cut, { flag: "a" }),
270 ),
271 ),
272 }),
273 );
274 // A later server start prunes with no idea how this machine launches t3.
275 const removed = yield* prunePinnedRuntimes({ baseDir: root, keep: [] }).pipe(
276 Effect.provideService(ProcessRunner.ProcessRunner, unrelatedLsof),
277 Effect.provideService(HostProcess.Platform, "darwin"),
278 Effect.provideService(HostProcess.Environment, { PATH: "" }),
279 Effect.provideService(HostProcess.HomeDirectory, root),
280 );
281
282 assert.deepStrictEqual(removed, ["1.0.0"]);
283 // macOS temp dirs sit behind the /var -> /private/var symlink, so compare canonical paths.
284 assert.equal(
285 yield* fs.realPath(launcher),
286 yield* fs.realPath(path.join(root, "runtime/versions/2.0.0/t3")),
287 );
288 }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
289 );
290
291 const launcherFixture = Effect.fnUntraced(function* () {
292 const fs = yield* FileSystem.FileSystem;
293 const path = yield* Path.Path;
294 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
295 const oldExe = path.join(root, "runtime/versions/1.0.0/t3");
296 const newExe = path.join(root, "runtime/versions/2.0.0/t3");
297 const launcher = path.join(root, "t3");
298 for (const file of [oldExe, newExe]) {
299 yield* fs.makeDirectory(path.dirname(file), { recursive: true });
300 yield* fs.writeFileString(file, "");
301 }
302 yield* fs.symlink(oldExe, launcher);
303 return { root, oldExe, newExe, launcher, launchersFile: path.join(root, "runtime/launchers") };
304 });
305
306 it.effect("records a relative launcher path as absolute", () =>
307 Effect.gen(function* () {
308 const fs = yield* FileSystem.FileSystem;
309 const path = yield* Path.Path;
310 const { root, newExe, launcher, launchersFile } = yield* launcherFixture();
311
312 yield* repointLauncher({
313 launchedAs: path.relative(path.resolve("."), launcher),
314 baseDir: root,
315 targetEntryPath: newExe,
316 });
317
318 assert.equal(yield* fs.readFileString(launchersFile), `\n${launcher}\n`);
319 }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
320 );
321
322 it.effect("fails instead of repointing a launcher it cannot record", () =>
323 Effect.gen(function* () {
324 const fs = yield* FileSystem.FileSystem;
325 const { root, oldExe, newExe, launcher, launchersFile } = yield* launcherFixture();
326 // Appending to a directory fails the way a read-only or full disk would.
327 yield* fs.makeDirectory(launchersFile);
328
329 const result = yield* repointLauncher({
330 launchedAs: launcher,
331 baseDir: root,
332 targetEntryPath: newExe,
333 }).pipe(Effect.exit);
334
335 assert.isTrue(Exit.isFailure(result));
336 assert.equal(yield* fs.readLink(launcher), oldExe);
337 }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
338 );
339
340 it.effect.each(["recording", "repointing"] as const)(
341 "never leaves a repointed launcher unrecorded when t3 update dies while %s",
342 (step) =>
343 Effect.gen(function* () {
344 const fs = yield* FileSystem.FileSystem;
345 const { root, newExe, launcher, launchersFile } = yield* launcherFixture();
346
347 yield* repointLauncher({
348 launchedAs: launcher,
349 baseDir: root,
350 targetEntryPath: newExe,
351 }).pipe(
352 Effect.provideService(FileSystem.FileSystem, {
353 ...fs,
354 writeFileString: (path, data, options) =>
355 step === "recording" && path === launchersFile
356 ? Effect.die("t3 update was killed")
357 : fs.writeFileString(path, data, options),
358 rename: (from, to) =>
359 step === "repointing" && to === launcher
360 ? Effect.die("t3 update was killed")
361 : fs.rename(from, to),
362 }),
363 Effect.exit,
364 );
365
366 const repointed = (yield* fs.readLink(launcher)) === newExe;
367 const recorded = (yield* fs
368 .readFileString(launchersFile)
369 .pipe(Effect.orElseSucceed(() => "")))
370 .split("\n")
371 .includes(launcher);
372 assert.isFalse(repointed && !recorded);
373 }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
374 );
375
376 it.effect("leaves a plain copy or a foreign symlink alone", () =>
377 Effect.gen(function* () {
378 const fs = yield* FileSystem.FileSystem;
379 const path = yield* Path.Path;
380 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
381 const newExe = path.join(root, "runtime/versions/2.0.0/t3");
382 const copy = path.join(root, "copy/t3");
383 const foreign = path.join(root, "foreign/t3");
384 const elsewhere = path.join(root, "elsewhere/t3");
385 const otherHome = path.join(root, "other/runtime/versions/1.0.0/t3");
386 const otherLauncher = path.join(root, "other/bin/t3");
387 for (const file of [newExe, copy, elsewhere, otherHome]) {
388 yield* fs.makeDirectory(path.dirname(file), { recursive: true });
389 yield* fs.writeFileString(file, "");
390 }
391 yield* fs.makeDirectory(path.dirname(foreign), { recursive: true });
392 yield* fs.symlink(elsewhere, foreign);
393 yield* fs.makeDirectory(path.dirname(otherLauncher), { recursive: true });
394 yield* fs.symlink(otherHome, otherLauncher);
395
396 for (const launchedAs of [copy, foreign, otherLauncher, undefined]) {
397 const repointed = yield* repointLauncher({
398 launchedAs,
399 baseDir: root,
400 targetEntryPath: newExe,
401 });
402 assert.equal(repointed._tag, "None", launchedAs ?? "undefined");
403 }
404 assert.equal(yield* fs.readLink(foreign), elsewhere);
405 assert.equal(yield* fs.readLink(otherLauncher), otherHome);
406 }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
407 );
408
409 it.effect("finds the launcher a bare command name resolved to on PATH", () =>
410 Effect.gen(function* () {
411 const fs = yield* FileSystem.FileSystem;
412 const path = yield* Path.Path;
413 const delimiter = (yield* HostProcess.Platform) === "win32" ? ";" : ":";
414 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
415 const launcher = path.join(root, "bin/t3");
416 yield* fs.makeDirectory(path.dirname(launcher), { recursive: true });
417 yield* fs.writeFileString(launcher, "", { mode: 0o755 });
418
419 const bare = yield* resolveLauncherPath.pipe(
420 Effect.provideService(HostProcess.InvokedAs, "t3"),
421 Effect.provideService(HostProcess.Environment, {
422 PATH: [path.join(root, "missing"), path.join(root, "bin")].join(delimiter),
423 }),
424 Effect.provideService(HostProcess.WorkingDirectory, root),
425 );
426 const relative = yield* resolveLauncherPath.pipe(
427 Effect.provideService(HostProcess.InvokedAs, "./bin/t3"),
428 Effect.provideService(HostProcess.Environment, { PATH: "" }),
429 Effect.provideService(HostProcess.WorkingDirectory, root),
430 );
431 const absent = yield* resolveLauncherPath.pipe(
432 Effect.provideService(HostProcess.InvokedAs, "t3"),
433 Effect.provideService(HostProcess.Environment, { PATH: path.join(root, "missing") }),
434 Effect.provideService(HostProcess.WorkingDirectory, root),
435 );
436
437 assert.equal(bare, launcher);
438 assert.equal(relative, launcher);
439 assert.equal(absent, undefined);
440 }).pipe(Effect.scoped),
441 );
442});
443
444// Without terminals, update skips its restart prompt whatever runs the test.
445const withoutTerminals = Effect.acquireRelease(
446 Effect.sync(() =>
447 [process.stdin, process.stdout].map((stream) => {
448 const descriptor = Object.getOwnPropertyDescriptor(stream, "isTTY");
449 Object.defineProperty(stream, "isTTY", { configurable: true, value: false });
450 return { stream, descriptor };
451 }),
452 ),
453 (saved) =>
454 Effect.sync(() => {
455 for (const { stream, descriptor } of saved) {
456 if (descriptor === undefined) Reflect.deleteProperty(stream, "isTTY");
457 else Object.defineProperty(stream, "isTTY", descriptor);
458 }
459 }),
460);
461
462it.layer(NodeServices.layer)("t3 update with a background service", (it) => {
463 it.effect("names the version a service with a pending restart still runs", () =>
464 Effect.gen(function* () {
465 yield* withoutTerminals;
466 const fs = yield* FileSystem.FileSystem;
467 const path = yield* Path.Path;
468 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
469 const version = packageJson.version;
470 const runtime = pinnedRuntimePaths(path, baseDir, version, "linux");
471 yield* fs.makeDirectory(runtime.versionDir, { recursive: true });
472 yield* fs.writeFileString(runtime.entryPath, "");
473 yield* fs.writeFileString(runtime.sentinelPath, `${version}\n`);
474 const unitPath = path.join(baseDir, "t3code.service");
475 const logPath = path.join(baseDir, "boot-service.log");
476 // An earlier `t3 update` pointed the service at this version without restarting it.
477 const service = Layer.mock(BootService.BootService, {
478 status: Effect.succeed<BootService.BootServiceStatus>({
479 supported: true,
480 installed: true,
481 current: false,
482 installedVersion: version,
483 installedBaseDir: baseDir,
484 problems: ["restart-pending"],
485 unitPath,
486 logPath,
487 }),
488 install: () => Effect.succeed({ program: [runtime.entryPath], baseDir, unitPath, logPath }),
489 });
490 vi.spyOn(BootService, "layer").mockReturnValue(service);
491 const runner = ProcessRunner.ProcessRunner.of({
492 run: (input) =>
493 input.args?.includes("--version") === true
494 ? unrelatedLsof
495 .run(input)
496 .pipe(Effect.map((result) => ({ ...result, stdout: `t3 v${version}\n` })))
497 : unrelatedLsof.run(input),
498 });
499
500 const output = yield* runUpdate({
501 baseDir,
502 logsDir: baseDir,
503 serverRuntimeStatePath: path.join(baseDir, "server-runtime.json"),
504 channel: undefined,
505 requestedVersion: version,
506 allowDowngrade: false,
507 assumeYes: false,
508 }).pipe(
509 Effect.andThen(TestConsole.logLines),
510 Effect.map((lines) => lines.join("\n")),
511 Effect.provide(
512 Layer.mergeAll(
513 service,
514 Layer.succeed(ProcessRunner.ProcessRunner, runner),
515 ManagedPolicy.layerTest(),
516 Layer.succeed(
517 HttpClient.HttpClient,
518 HttpClient.make(() => Effect.die("unexpected release lookup")),
519 ),
520 Layer.fresh(TestConsole.layer),
521 ),
522 ),
523 );
524
525 assert.include(
526 output,
527 `Background service still running the version before ${version}. Run \`t3 service restart\` when you are ready to switch it to ${version}.`,
528 );
529 }).pipe(
530 Effect.scoped,
531 Effect.provideService(HostProcess.Platform, "linux"),
532 Effect.provideService(HostProcess.Environment, { PATH: "" }),
533 ),
534 );
535});