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