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