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