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

update.ts

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