Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

update.ts

620 lines23.8 KB

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