Open History to see the last commit
1import * as HostProcess from "@t3tools/shared/HostProcess";
2import {
3 CLI_RELEASE_BASE_URL_ENV,
4 CLI_RELEASE_CHANNELS,
5 cliReleaseIndexPageUrl,
6 cliReleaseChannelOf,
7 newestCliReleaseVersion,
8 type CliReleaseChannel,
9} from "@t3tools/shared/cliRelease";
10import * as Console from "effect/Console";
11import * as Duration from "effect/Duration";
12import * as Effect from "effect/Effect";
13import * as FileSystem from "effect/FileSystem";
14import * as Layer from "effect/Layer";
15import * as Option from "effect/Option";
16import * as Path from "effect/Path";
17import * as Schema from "effect/Schema";
18import { Argument, Command, Flag, GlobalFlag, Prompt } from "effect/cli";
19import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
20
21import packageJson from "../../package.json" with { type: "json" };
22import * as BootService from "../cloud/bootService.ts";
23import {
24 ensurePinnedRuntimeInstalled,
25 launcherOwnsVersionsDir,
26 pinnedRuntimeCommand,
27 PinnedRuntimeInstallError,
28 pinnedRuntimePaths,
29 pinnedRuntimeVersionsDir,
30 prunePinnedRuntimes,
31 recordPinnedRuntimeLauncher,
32 windowsShimTarget,
33} from "../cloud/pinnedRuntime.ts";
34import { compareExactServiceVersions, isExactServiceVersion } from "../cloud/serviceProtocol.ts";
35import * as ProcessRunner from "../processRunner.ts";
36import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
37import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
38import { createUpdateProgress } from "./updateProgress.ts";
39import * as CliService from "./service.ts";
40
41export class CliUpdateError extends Schema.TaggedError<CliUpdateError>()("CliUpdateError", {
42 reason: Schema.String,
43}) {
44 override get message(): string {
45 return this.reason;
46 }
47}
48
49const ReleaseIndex = Schema.Array(
50 Schema.Struct({
51 tag_name: Schema.String,
52 draft: Schema.optional(Schema.Boolean),
53 }),
54);
55const decodeReleaseIndex = Schema.decodeUnknownEffect(Schema.fromJsonString(ReleaseIndex));
56
57const RELEASE_INDEX_TIMEOUT = Duration.seconds(30);
58const RELEASE_INDEX_MAX_PAGES = 10;
59
60export const resolveNewestVersion = Effect.fn("cli.update.resolve_newest")(function* (
61 channel: CliReleaseChannel,
62) {
63 const httpClient = yield* HttpClient.HttpClient;
64 const environment = yield* HostProcess.Environment;
65 const githubToken = environment.GH_TOKEN?.trim() || environment.GITHUB_TOKEN?.trim() || undefined;
66 for (let page = 1; page <= RELEASE_INDEX_MAX_PAGES; page += 1) {
67 const request = HttpClientRequest.get(cliReleaseIndexPageUrl(page)).pipe(
68 HttpClientRequest.setHeader("Accept", "application/vnd.github+json"),
69 );
70 const authenticatedRequest =
71 githubToken === undefined
72 ? request
73 : HttpClientRequest.setHeader(request, "Authorization", `Bearer ${githubToken}`);
74 const body = yield* httpClient.execute(authenticatedRequest).pipe(
75 Effect.flatMap(HttpClientResponse.filterStatusOk),
76 Effect.flatMap((response) => response.text),
77 Effect.mapError(() => new CliUpdateError({ reason: "Could not list t3 releases." })),
78 Effect.timeoutOrElse({
79 duration: RELEASE_INDEX_TIMEOUT,
80 orElse: () => Effect.fail(new CliUpdateError({ reason: "Timed out listing t3 releases." })),
81 }),
82 );
83 const releases = yield* decodeReleaseIndex(body).pipe(
84 Effect.mapError(
85 () => new CliUpdateError({ reason: "The t3 release index had an unexpected shape." }),
86 ),
87 );
88 const version = newestCliReleaseVersion(releases, channel);
89 if (version !== undefined) return version;
90 if (releases.length === 0) break;
91 }
92 return yield* new CliUpdateError({ reason: `No published ${channel} release was found.` });
93});
94
95/**
96 * Only a launcher that already points into this home's `runtime/versions` tree is touched; a
97 * plain copy of the executable, or a launcher for some other install, is left alone. It is
98 * recorded before it moves, so prune never meets a repointed launcher it does not know about.
99 */
100export const repointLauncher = Effect.fn("cli.update.repoint_launcher")(function* (input: {
101 readonly launchedAs: string | undefined;
102 readonly baseDir: string;
103 readonly targetEntryPath: string;
104}) {
105 const fs = yield* FileSystem.FileSystem;
106 const path = yield* Path.Path;
107 const platform = yield* HostProcess.Platform;
108 if (input.launchedAs === undefined) return Option.none<string>();
109 const versionsDir = pinnedRuntimeVersionsDir(path, input.baseDir);
110 const ownsTarget = (candidate: string) => launcherOwnsVersionsDir(path, versionsDir, candidate);
111 const remember = (launcher: string) =>
112 recordPinnedRuntimeLauncher({ baseDir: input.baseDir, launcher }).pipe(
113 Effect.mapError(
114 () => new CliUpdateError({ reason: `Could not record the t3 launcher at ${launcher}.` }),
115 ),
116 );
117
118 if (platform === "win32") {
119 const shimPath = yield* findWindowsShim(input.launchedAs);
120 if (shimPath === undefined) return Option.none<string>();
121 const current = yield* fs.readFileString(shimPath).pipe(Effect.option);
122 const quoted = Option.isSome(current) ? windowsShimTarget(current.value) : undefined;
123 if (quoted === undefined || !ownsTarget(quoted)) return Option.none<string>();
124 yield* remember(shimPath);
125 yield* fs
126 .writeFileString(shimPath, `@echo off\r\n"${input.targetEntryPath}" %*`)
127 .pipe(
128 Effect.mapError(
129 () => new CliUpdateError({ reason: `Could not rewrite the t3 launcher at ${shimPath}.` }),
130 ),
131 );
132 return Option.some(shimPath);
133 }
134
135 const linkTarget = yield* fs.readLink(input.launchedAs).pipe(Effect.option);
136 if (Option.isNone(linkTarget)) return Option.none<string>();
137 const resolvedTarget = path.resolve(path.dirname(input.launchedAs), linkTarget.value);
138 if (!ownsTarget(resolvedTarget)) return Option.none<string>();
139 yield* remember(input.launchedAs);
140 const tempLink = `${input.launchedAs}.${process.pid}.tmp`;
141 yield* fs.symlink(input.targetEntryPath, tempLink).pipe(
142 Effect.andThen(fs.rename(tempLink, input.launchedAs)),
143 Effect.mapError(
144 () =>
145 new CliUpdateError({ reason: `Could not repoint the t3 launcher at ${input.launchedAs}.` }),
146 ),
147 );
148 return Option.some(input.launchedAs);
149});
150
151/** Node preserves argv0's spelling; resolve bare names on PATH to find the launcher symlink. */
152export const resolveLauncherPath = Effect.gen(function* () {
153 const path = yield* Path.Path;
154 const fs = yield* FileSystem.FileSystem;
155 const invokedAs = yield* HostProcess.InvokedAs;
156 const cwd = yield* HostProcess.WorkingDirectory;
157 const environment = yield* HostProcess.Environment;
158 const platform = yield* HostProcess.Platform;
159 if (invokedAs.includes("/") || invokedAs.includes("\\")) {
160 return path.resolve(cwd, invokedAs);
161 }
162 const delimiter = platform === "win32" ? ";" : ":";
163 for (const directory of (environment["PATH"] ?? "").split(delimiter)) {
164 if (directory.length === 0) continue;
165 const candidate = path.join(directory, invokedAs);
166 if (yield* fs.exists(candidate).pipe(Effect.orElseSucceed(() => false))) {
167 return candidate;
168 }
169 }
170 return undefined;
171});
172
173/** Windows executables see their own path, so find the installer shim by matching t3.cmd targets on PATH. */
174export const findWindowsShim = Effect.fn("cli.update.find_windows_shim")(function* (
175 executablePath: string,
176) {
177 const fs = yield* FileSystem.FileSystem;
178 const path = yield* Path.Path;
179 const environment = yield* HostProcess.Environment;
180 const candidates = [
181 ...(environment["T3CODE_INSTALL_BIN_DIR"] ? [environment["T3CODE_INSTALL_BIN_DIR"]] : []),
182 ...(environment["PATH"] ?? environment["Path"] ?? "").split(";"),
183 ].filter((entry) => entry.trim().length > 0);
184 for (const directory of candidates) {
185 const shimPath = path.join(directory, "t3.cmd");
186 const contents = yield* fs.readFileString(shimPath).pipe(Effect.option);
187 if (Option.isNone(contents)) continue;
188 const target = windowsShimTarget(contents.value);
189 if (
190 target !== undefined &&
191 path.resolve(target).toLowerCase() === path.resolve(executablePath).toLowerCase()
192 ) {
193 return shimPath;
194 }
195 }
196 return undefined;
197});
198
199const updateFlags = {
200 ...projectLocationFlags,
201 channel: Flag.Literals("channel", CLI_RELEASE_CHANNELS).pipe(
202 Flag.withDescription(
203 "Release channel to follow. Defaults to the channel this t3 was published on.",
204 ),
205 Flag.optional,
206 ),
207 allowDowngrade: Flag.Boolean("allow-downgrade").pipe(
208 Flag.withDescription("Allow moving to an older version than the one running."),
209 Flag.withDefault(false),
210 ),
211 yes: Flag.Boolean("yes").pipe(
212 Flag.withAlias("y"),
213 Flag.withDescription(
214 "Restart the background service without asking. Required to restart it from a script, where there is no prompt.",
215 ),
216 Flag.withDefault(false),
217 ),
218};
219
220const versionArgument = Argument.String("version").pipe(
221 Argument.withDescription(
222 "Exact version to install. Defaults to the newest release on the channel.",
223 ),
224 Argument.optional,
225);
226
227export const updateCommand = Command.make("update", {
228 ...updateFlags,
229 version: versionArgument,
230}).pipe(
231 Command.withDescription(
232 "Download a newer t3 and switch this machine to it, including the background service when one is installed.",
233 ),
234 Command.withHandler((flags) =>
235 Effect.gen(function* () {
236 const logLevel = yield* GlobalFlag.LogLevel;
237 const config = yield* resolveCliAuthConfig(flags, logLevel);
238 return yield* runUpdate({
239 baseDir: config.baseDir,
240 logsDir: config.logsDir,
241 serverRuntimeStatePath: config.serverRuntimeStatePath,
242 channel: Option.getOrUndefined(flags.channel),
243 requestedVersion: Option.getOrUndefined(flags.version),
244 allowDowngrade: flags.allowDowngrade,
245 assumeYes: flags.yes,
246 }).pipe(
247 Effect.provide(
248 Layer.mergeAll(CliService.layer(config), ProcessRunner.layer, FetchHttpClient.layer),
249 ),
250 );
251 }),
252 ),
253);
254
255const findForegroundServer = Effect.fn("cli.update.find_foreground_server")(function* (input: {
256 readonly serverRuntimeStatePath: string;
257 readonly serviceInstalled: boolean;
258}) {
259 const state = yield* readPersistedServerRuntimeState(input.serverRuntimeStatePath);
260 if (Option.isNone(state) || state.value.serviceManaged || !isProcessAlive(state.value.pid)) {
261 return undefined;
262 }
263 if (input.serviceInstalled && (yield* belongsToBootService(state.value.pid))) return undefined;
264 return state.value;
265});
266
267const belongsToBootService = Effect.fn("cli.update.belongs_to_boot_service")(function* (
268 pid: number,
269) {
270 const platform = yield* HostProcess.Platform;
271 const fs = yield* FileSystem.FileSystem;
272 const runner = yield* ProcessRunner.ProcessRunner;
273 if (platform === "linux") {
274 const cgroup = yield* fs.readFileString(`/proc/${pid}/cgroup`).pipe(Effect.option);
275 return Option.isSome(cgroup) && cgroup.value.includes("/t3code.service");
276 }
277 if (platform === "darwin") {
278 const parent = yield* runner
279 .run({
280 command: "ps",
281 args: ["-o", "ppid=", "-p", String(pid)],
282 timeout: Duration.seconds(5),
283 })
284 .pipe(Effect.option);
285 const ppid = Option.isSome(parent) && parent.value.code === 0 ? parent.value.stdout.trim() : "";
286 if (!/^\d+$/.test(ppid)) return false;
287 const command = yield* runner
288 .run({ command: "ps", args: ["-o", "command=", "-p", ppid], timeout: Duration.seconds(5) })
289 .pipe(
290 Effect.map((result) => (result.code === 0 ? result.stdout : "")),
291 Effect.orElseSucceed(() => ""),
292 );
293 return /__service-launcher/.test(command);
294 }
295 return false;
296});
297
298const runUpdate = Effect.fn("cli.update.run")(function* (input: {
299 readonly baseDir: string;
300 readonly logsDir: string;
301 readonly serverRuntimeStatePath: string;
302 readonly channel: CliReleaseChannel | undefined;
303 readonly requestedVersion: string | undefined;
304 readonly allowDowngrade: boolean;
305 readonly assumeYes: boolean;
306}) {
307 const fs = yield* FileSystem.FileSystem;
308 const path = yield* Path.Path;
309 const runner = yield* ProcessRunner.ProcessRunner;
310 const platform = yield* HostProcess.Platform;
311 const arch = yield* HostProcess.Architecture;
312 const environment = yield* HostProcess.Environment;
313 const httpClient = yield* HttpClient.HttpClient;
314 const service = yield* BootService.BootService;
315
316 const currentVersion = packageJson.version;
317 const channel = input.channel ?? cliReleaseChannelOf(currentVersion);
318 if (input.requestedVersion !== undefined && !isExactServiceVersion(input.requestedVersion)) {
319 return yield* new CliUpdateError({
320 reason: `'${input.requestedVersion}' is not an exact t3 version.`,
321 });
322 }
323 const progress = createUpdateProgress();
324 progress.status("Checking for updates...");
325 const targetVersion = yield* (
326 input.requestedVersion === undefined
327 ? resolveNewestVersion(channel)
328 : Effect.succeed(input.requestedVersion)
329 ).pipe(Effect.ensuring(Effect.sync(progress.finish)));
330 const targetChannel = cliReleaseChannelOf(targetVersion);
331
332 const currentChannel = cliReleaseChannelOf(currentVersion);
333 if (targetChannel === "preview" && currentChannel !== "preview") {
334 yield* Console.log(
335 [
336 `t3@${targetVersion} is a preview build.`,
337 " Preview builds are cut by maintainers from unreleased branches to exercise the release",
338 " pipeline. They can be broken, receive no fixes, and are never offered as updates; you",
339 ` will have to switch back to ${currentChannel} yourself with \`t3 update --channel ${currentChannel} --allow-downgrade\`.`,
340 ].join("\n"),
341 );
342 if (!(process.stdin.isTTY && process.stdout.isTTY)) {
343 return yield* new CliUpdateError({
344 reason:
345 "Refusing to install a preview build without confirmation. Run this from a terminal to confirm, or pass --channel preview from an interactive shell.",
346 });
347 }
348 const confirmed = yield* Prompt.run(
349 Prompt.Confirm({ message: "Install the preview build anyway?", initial: false }),
350 ).pipe(Effect.catchTags({ QuitError: () => Effect.succeed(false) }));
351 if (!confirmed) {
352 yield* Console.log("Left as is.");
353 return;
354 }
355 }
356
357 const status = yield* service.status;
358 // Service names are per user, so another home's unit belongs to a different install.
359 const servesThisHome =
360 status.installedBaseDir !== undefined &&
361 path.resolve(status.installedBaseDir) === path.resolve(input.baseDir);
362 const serviceInstalled = status.supported && status.installed && servesThisHome;
363 const foreground = yield* findForegroundServer({
364 serverRuntimeStatePath: input.serverRuntimeStatePath,
365 serviceInstalled,
366 });
367 const serviceVersion = serviceInstalled ? status.installedVersion : undefined;
368 const executableCurrent = targetVersion === currentVersion;
369 const restartPending = status.problems?.includes("restart-pending") === true;
370 const serviceCurrent =
371 !serviceInstalled ||
372 (serviceVersion === targetVersion &&
373 (executableCurrent ? status.current : (status.problems ?? []).length === 0));
374 const newestInstalled =
375 serviceVersion !== undefined && compareExactServiceVersions(serviceVersion, currentVersion) > 0
376 ? serviceVersion
377 : currentVersion;
378
379 if (executableCurrent && serviceCurrent) {
380 yield* Console.log(
381 serviceVersion !== undefined
382 ? `t3 and its background service are already on ${targetVersion} (${targetChannel}).`
383 : `t3 is already on ${targetVersion} (${targetChannel}).`,
384 );
385 return;
386 }
387 if (!input.allowDowngrade && compareExactServiceVersions(targetVersion, newestInstalled) < 0) {
388 return yield* new CliUpdateError({
389 reason: `t3@${targetVersion} is older than the installed ${newestInstalled}. Pass --allow-downgrade to install it anyway.`,
390 });
391 }
392
393 const alreadyOnDisk = yield* fs
394 .readFileString(pinnedRuntimePaths(path, input.baseDir, targetVersion, platform).sentinelPath)
395 .pipe(
396 Effect.map((sentinel) => sentinel.trim() === targetVersion),
397 Effect.orElseSucceed(() => false),
398 );
399
400 progress.heading(
401 executableCurrent && restartPending
402 ? `The background service is still running the version before ${targetVersion} (${targetChannel}).`
403 : executableCurrent
404 ? `Updating the background service ${serviceVersion ?? "(unknown version)"} -> ${targetVersion} (${targetChannel}).`
405 : alreadyOnDisk
406 ? "Switching T3 Code"
407 : "Updating T3 Code",
408 executableCurrent
409 ? ""
410 : `${currentVersion} → ${targetVersion}${targetChannel === "stable" ? "" : ` (${targetChannel})`}`,
411 );
412 let restartService = false;
413 if (serviceInstalled && !serviceCurrent) {
414 yield* Console.log(
415 " A background service is installed for this T3 home. Restarting it interrupts anything running in it: agent turns, terminals, remote clients.",
416 );
417 if (input.assumeYes) {
418 restartService = true;
419 } else if (process.stdin.isTTY && process.stdout.isTTY) {
420 restartService = yield* Prompt.run(
421 Prompt.Confirm({
422 message: "Restart the background service once the download is verified?",
423 initial: true,
424 }),
425 ).pipe(Effect.catchTags({ QuitError: () => Effect.succeed(false) }));
426 } else {
427 yield* Console.log(
428 " Not a terminal, so the service keeps running its current version. Rerun with --yes to restart it now, or run `t3 service restart` later.",
429 );
430 }
431 }
432
433 const runtime = yield* ensurePinnedRuntimeInstalled({
434 onProgress: progress.report,
435 baseDir: input.baseDir,
436 version: targetVersion,
437 fs,
438 path,
439 runner,
440 httpClient,
441 platform,
442 arch,
443 releaseBaseUrl: environment[CLI_RELEASE_BASE_URL_ENV]?.trim() || undefined,
444 validate: (paths) =>
445 runner
446 .run({
447 command: pinnedRuntimeCommand(paths).command,
448 args: [...pinnedRuntimeCommand(paths).args, "--version"],
449 timeout: Duration.seconds(30),
450 })
451 .pipe(
452 Effect.mapError(
453 (cause) =>
454 new PinnedRuntimeInstallError({ step: "verifying the downloaded t3", cause }),
455 ),
456 Effect.flatMap((result) =>
457 result.code === 0 && /\bv(\S+)\s*$/.exec(result.stdout)?.[1] === targetVersion
458 ? Effect.void
459 : Effect.fail(
460 new PinnedRuntimeInstallError({
461 step: "verifying the downloaded t3",
462 exitCode: Number(result.code),
463 }),
464 ),
465 ),
466 ),
467 }).pipe(
468 Effect.ensuring(Effect.sync(progress.finish)),
469 Effect.catchIf(
470 (error): error is PinnedRuntimeInstallError =>
471 error._tag === "PinnedRuntimeInstallError" &&
472 error.step.startsWith("downloading the t3 release checksums") &&
473 String(error.cause).includes("404"),
474 () =>
475 Effect.fail(
476 new CliUpdateError({
477 reason: `No release archive was published for t3@${targetVersion}.`,
478 }),
479 ),
480 ),
481 );
482
483 const launchedAs = (yield* HostProcess.IsExecutable) ? yield* resolveLauncherPath : undefined;
484 const repointed = yield* repointLauncher({
485 launchedAs,
486 baseDir: input.baseDir,
487 targetEntryPath: runtime.entryPath,
488 });
489
490 // Use today's service manager for the target version. Inside the service it hands off to
491 // the target CLI, so stopping this process cannot interrupt the switch.
492 let servicePlan: BootService.BootServicePlan | undefined;
493 if (serviceInstalled && !serviceCurrent) {
494 yield* Console.log(
495 restartService
496 ? "Restarting the background service..."
497 : "Updating the background service...",
498 );
499 servicePlan = yield* BootService.BootService.pipe(
500 Effect.flatMap((target) =>
501 target.install({ allowDowngrade: input.allowDowngrade, start: restartService }),
502 ),
503 Effect.provide(
504 BootService.layer({
505 baseDir: input.baseDir,
506 logsDir: input.logsDir,
507 cliVersion: targetVersion,
508 }),
509 ),
510 Effect.mapError(
511 (error) =>
512 new CliUpdateError({
513 reason: `t3@${targetVersion} is installed but the background service could not be ${restartService ? "updated" : "pointed at it"}: ${error.message}`,
514 }),
515 ),
516 );
517 }
518
519 // A handed-off service install rewrites the unit later, while the old launcher may be stopped.
520 if (servicePlan?.handedOff !== true) {
521 // A stopped service's unit still names the launcher runtime it will start.
522 const unit = yield* fs.readFileString(status.unitPath).pipe(Effect.option);
523 yield* prunePinnedRuntimes({
524 baseDir: input.baseDir,
525 keep: [currentVersion, targetVersion],
526 references: Option.toArray(Option.flatMapNullishOr(unit, BootService.bootServiceProgramOf)),
527 });
528 }
529
530 progress.success(`Installed T3 Code ${targetVersion}`);
531 if (Option.isSome(repointed)) {
532 yield* Console.log(" Run t3 to get started.\n");
533 } else {
534 yield* Console.log(` Run ${runtime.entryPath}\n`);
535 }
536 if (servicePlan?.handedOff === true) {
537 yield* Console.log(
538 ` Background service switching to ${targetVersion} from a separate systemd unit, since this session runs inside it and disconnects when it restarts. Result: ${servicePlan.logPath}`,
539 );
540 } else if (servicePlan !== undefined && restartService) {
541 yield* Console.log(` Background service restarted on ${targetVersion}`);
542 } else if (serviceInstalled && serviceCurrent) {
543 yield* Console.log(` Background service already on ${targetVersion}`);
544 } else if (serviceInstalled) {
545 yield* Console.log(
546 ` Background service still running ${serviceVersion ?? "an unknown version"}. Run \`t3 service restart\` when you are ready to switch it to ${targetVersion}.`,
547 );
548 } else if (status.installed && !servesThisHome) {
549 yield* Console.log(
550 ` The background service serves ${status.installedBaseDir ?? "another T3 home"} and was left unchanged.`,
551 );
552 }
553 if (foreground !== undefined) {
554 yield* Console.log(
555 ` A server started by hand is still running at ${foreground.origin} (pid ${foreground.pid}). Stop it and start it again to pick up ${targetVersion}.`,
556 );
557 }
558});