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

update.ts

599 lines23.9 KB

1import {
2 HostProcessArchitecture,
3 HostProcessEnvironment,
4 HostProcessInvokedAs,
5 HostProcessIsExecutable,
6 HostProcessPlatform,
7 HostProcessWorkingDirectory,
8} from "@t3tools/shared/hostProcess";
9import {
10 CLI_RELEASE_BASE_URL_ENV,
11 CLI_RELEASE_CHANNELS,
12 cliReleaseIndexPageUrl,
13 cliReleaseChannelOf,
14 newestCliReleaseVersion,
15 type CliReleaseChannel,
16} from "@t3tools/shared/cliRelease";
17import * as Console from "effect/Console";
18import * as Duration from "effect/Duration";
19import * as Effect from "effect/Effect";
20import * as FileSystem from "effect/FileSystem";
21import * as Layer from "effect/Layer";
22import * as Option from "effect/Option";
23import * as Path from "effect/Path";
24import * as Schema from "effect/Schema";
25import { Argument, Command, Flag, GlobalFlag, Prompt } from "effect/cli";
26import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
27​
28import packageJson from "../../package.json" with { type: "json" };
29import * as BootService from "../cloud/bootService.ts";
30import {
31 ensurePinnedRuntimeInstalled,
32 pinnedRuntimeCommand,
33 PinnedRuntimeInstallError,
34 pinnedRuntimePaths,
35} from "../cloud/pinnedRuntime.ts";
36import { compareExactServiceVersions, isExactServiceVersion } from "../cloud/serviceProtocol.ts";
37import * as ProcessRunner from "../processRunner.ts";
38import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
39import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
40import { createUpdateProgress } from "./updateProgress.ts";
41import * as CliService from "./service.ts";
42​
43export class CliUpdateError extends Schema.TaggedError<CliUpdateError>()("CliUpdateError", {
44 reason: Schema.String,
45}) {
46 override get message(): string {
47 return this.reason;
48 }
50​
51const ReleaseIndex = Schema.Array(
52 Schema.Struct({
53 tag_name: Schema.String,
54 draft: Schema.optional(Schema.Boolean),
55 }),
56);
57const decodeReleaseIndex = Schema.decodeUnknownEffect(Schema.fromJsonString(ReleaseIndex));
58​
59const RELEASE_INDEX_TIMEOUT = Duration.seconds(30);
60// Enough to walk past a long run of nightlies without hammering the API when
61// a channel genuinely has nothing published.
62const RELEASE_INDEX_MAX_PAGES = 10;
63​
64/** Asks GitHub for the newest published version on a channel, page by page. */
65const resolveNewestVersion = Effect.fn("cli.update.resolve_newest")(function* (
66 channel: CliReleaseChannel,
67) {
68 const httpClient = yield* HttpClient.HttpClient;
69 for (let page = 1; page <= RELEASE_INDEX_MAX_PAGES; page += 1) {
70 const body = yield* httpClient
71 .execute(
72 HttpClientRequest.get(cliReleaseIndexPageUrl(page)).pipe(
73 HttpClientRequest.setHeader("Accept", "application/vnd.github+json"),
74 ),
75 )
76 .pipe(
77 Effect.flatMap(HttpClientResponse.filterStatusOk),
78 Effect.flatMap((response) => response.text),
79 Effect.mapError(() => new CliUpdateError({ reason: "Could not list t3 releases." })),
80 Effect.timeoutOrElse({
81 duration: RELEASE_INDEX_TIMEOUT,
82 orElse: () =>
83 Effect.fail(new CliUpdateError({ reason: "Timed out listing t3 releases." })),
84 }),
85 );
86 const releases = yield* decodeReleaseIndex(body).pipe(
87 Effect.mapError(
88 () => new CliUpdateError({ reason: "The t3 release index had an unexpected shape." }),
89 ),
90 );
91 const version = newestCliReleaseVersion(releases, channel);
92 if (version !== undefined) return version;
93 if (releases.length === 0) break;
94 }
95 return yield* new CliUpdateError({ reason: `No published ${channel} release was found.` });
96});
97​
98/** Whether a launcher target lives inside `<baseDir>/runtime/versions`. */
99export function launcherOwnsVersionsDir(
100 path: Path.Path,
101 versionsDir: string,
102 candidate: string,
103): boolean {
104 const relative = path.relative(versionsDir, path.resolve(candidate));
105 return relative.length > 0 && !relative.startsWith("..") && !path.isAbsolute(relative);
107​
108/**
109 * The launcher the install scripts leave behind: a symlink at `<bin>/t3` on
110 * POSIX, a `t3.cmd` shim on Windows. `t3 update` repoints it so the next `t3`
111 * invocation is the new version. Only a launcher that already points into
112 * this home's `runtime/versions` tree is touched; a plain copy of the
113 * executable, or a launcher for some other install, is left alone.
114 */
115export const repointLauncher = Effect.fn("cli.update.repoint_launcher")(function* (input: {
116 /** Path the current process was started through, if known. */
117 readonly launchedAs: string | undefined;
118 /** `<baseDir>/runtime/versions` of the home being updated. */
119 readonly versionsDir: string;
120 readonly targetEntryPath: string;
121}) {
122 const fs = yield* FileSystem.FileSystem;
123 const path = yield* Path.Path;
124 const platform = yield* HostProcessPlatform;
125 if (input.launchedAs === undefined) return Option.none<string>();
126 const ownsTarget = (candidate: string) =>
127 launcherOwnsVersionsDir(path, input.versionsDir, candidate);
128​
129 if (platform === "win32") {
130 // The shim runs the executable by absolute path, so the executable sees
131 // itself as argv0; the shim is the `t3.cmd` next to it only when launched
132 // from an install script's bin directory. Find it by searching the
133 // directories that would resolve `t3` on this shell's PATH.
134 const shimPath = yield* findWindowsShim(input.launchedAs);
135 if (shimPath === undefined) return Option.none<string>();
136 const current = yield* fs.readFileString(shimPath).pipe(Effect.option);
137 const quoted = Option.isSome(current) ? /^"([^"]+)"/m.exec(current.value)?.[1] : undefined;
138 if (quoted === undefined || !ownsTarget(quoted)) return Option.none<string>();
139 yield* fs
140 .writeFileString(shimPath, `@echo off\r\n"${input.targetEntryPath}" %*`)
141 .pipe(
142 Effect.mapError(
143 () => new CliUpdateError({ reason: `Could not rewrite the t3 launcher at ${shimPath}.` }),
144 ),
145 );
146 return Option.some(shimPath);
147 }
148​
149 const linkTarget = yield* fs.readLink(input.launchedAs).pipe(Effect.option);
150 if (Option.isNone(linkTarget)) return Option.none<string>();
151 const resolvedTarget = path.resolve(path.dirname(input.launchedAs), linkTarget.value);
152 if (!ownsTarget(resolvedTarget)) return Option.none<string>();
153 const tempLink = `${input.launchedAs}.${process.pid}.tmp`;
154 yield* fs.symlink(input.targetEntryPath, tempLink).pipe(
155 Effect.andThen(fs.rename(tempLink, input.launchedAs)),
156 Effect.mapError(
157 () =>
158 new CliUpdateError({ reason: `Could not repoint the t3 launcher at ${input.launchedAs}.` }),
159 ),
160 );
161 return Option.some(input.launchedAs);
162});
163​
164/**
165 * The path the executable was started through. Node keeps the shell's
166 * spelling in argv0: a launcher symlink or `./t3` resolves against the
167 * working directory, while a bare `t3` was found on PATH and has to be
168 * looked up there again, or the launcher symlink is never seen.
169 */
170export const resolveLauncherPath = Effect.gen(function* () {
171 const path = yield* Path.Path;
172 const fs = yield* FileSystem.FileSystem;
173 const invokedAs = yield* HostProcessInvokedAs;
174 const cwd = yield* HostProcessWorkingDirectory;
175 const environment = yield* HostProcessEnvironment;
176 const platform = yield* HostProcessPlatform;
177 if (invokedAs.includes("/") || invokedAs.includes("\\")) {
178 return path.resolve(cwd, invokedAs);
179 }
180 const delimiter = platform === "win32" ? ";" : ":";
181 for (const directory of (environment["PATH"] ?? "").split(delimiter)) {
182 if (directory.length === 0) continue;
183 const candidate = path.join(directory, invokedAs);
184 if (yield* fs.exists(candidate).pipe(Effect.orElseSucceed(() => false))) {
185 return candidate;
186 }
187 }
188 return undefined;
189});
190​
191/**
192 * On Windows a `.cmd` shim is what PATH resolves, but the executable it runs
193 * only ever sees its own path. Walk PATH for a `t3.cmd` whose target is the
194 * running executable; that is the launcher the install script wrote.
195 */
196export const findWindowsShim = Effect.fn("cli.update.find_windows_shim")(function* (
197 executablePath: string,
198) {
199 const fs = yield* FileSystem.FileSystem;
200 const path = yield* Path.Path;
201 const environment = yield* HostProcessEnvironment;
202 const candidates = [
203 ...(environment["T3CODE_INSTALL_BIN_DIR"] ? [environment["T3CODE_INSTALL_BIN_DIR"]] : []),
204 ...(environment["PATH"] ?? environment["Path"] ?? "").split(";"),
205 ].filter((entry) => entry.trim().length > 0);
206 for (const directory of candidates) {
207 const shimPath = path.join(directory, "t3.cmd");
208 const contents = yield* fs.readFileString(shimPath).pipe(Effect.option);
209 if (Option.isNone(contents)) continue;
210 const target = /^"([^"]+)"/m.exec(contents.value)?.[1];
211 if (
212 target !== undefined &&
213 path.resolve(target).toLowerCase() === path.resolve(executablePath).toLowerCase()
214 ) {
215 return shimPath;
216 }
217 }
218 return undefined;
219});
220​
221const updateFlags = {
222 ...projectLocationFlags,
223 channel: Flag.Literals("channel", CLI_RELEASE_CHANNELS).pipe(
224 Flag.withDescription(
225 "Release channel to follow. Defaults to the channel this t3 was published on.",
226 ),
227 Flag.optional,
228 ),
229 allowDowngrade: Flag.Boolean("allow-downgrade").pipe(
230 Flag.withDescription("Allow moving to an older version than the one running."),
231 Flag.withDefault(false),
232 ),
233 yes: Flag.Boolean("yes").pipe(
234 Flag.withAlias("y"),
235 Flag.withDescription(
236 "Restart the background service without asking. Required to restart it from a script, where there is no prompt.",
237 ),
238 Flag.withDefault(false),
239 ),
240};
241​
242const versionArgument = Argument.String("version").pipe(
243 Argument.withDescription(
244 "Exact version to install. Defaults to the newest release on the channel.",
245 ),
246 Argument.optional,
247);
248​
249export const updateCommand = Command.make("update", {
250 ...updateFlags,
251 version: versionArgument,
252}).pipe(
253 Command.withDescription(
254 "Download a newer t3 and switch this machine to it, including the background service when one is installed.",
255 ),
256 Command.withHandler((flags) =>
257 Effect.gen(function* () {
258 const logLevel = yield* GlobalFlag.LogLevel;
259 const config = yield* resolveCliAuthConfig(flags, logLevel);
260 return yield* runUpdate({
261 baseDir: config.baseDir,
262 logsDir: config.logsDir,
263 serverRuntimeStatePath: config.serverRuntimeStatePath,
264 channel: Option.getOrUndefined(flags.channel),
265 requestedVersion: Option.getOrUndefined(flags.version),
266 allowDowngrade: flags.allowDowngrade,
267 assumeYes: flags.yes,
268 }).pipe(
269 Effect.provide(
270 Layer.mergeAll(CliService.layer(config), ProcessRunner.layer, FetchHttpClient.layer),
271 ),
272 );
273 }),
274 ),
275);
276​
277/**
278 * A `t3 serve` or `t3` someone started by hand, as opposed to the one the
279 * background service supervises. The server records its pid on startup; a
280 * stale file from a crashed server is ignored by checking the pid is alive.
281 *
282 * Servers from before `serviceManaged` was recorded cannot be told apart by
283 * the file alone, so the launcher-supervised case is also recognised by
284 * lineage: a service server's parent is the launcher, and on Linux that
285 * launcher runs inside the unit's cgroup.
286 */
287const findForegroundServer = Effect.fn("cli.update.find_foreground_server")(function* (input: {
288 readonly serverRuntimeStatePath: string;
289 readonly serviceInstalled: boolean;
290}) {
291 const state = yield* readPersistedServerRuntimeState(input.serverRuntimeStatePath);
292 if (Option.isNone(state) || state.value.serviceManaged || !isProcessAlive(state.value.pid)) {
293 return undefined;
294 }
295 if (input.serviceInstalled && (yield* belongsToBootService(state.value.pid))) return undefined;
296 return state.value;
297});
298​
299const belongsToBootService = Effect.fn("cli.update.belongs_to_boot_service")(function* (
300 pid: number,
301) {
302 const platform = yield* HostProcessPlatform;
303 const fs = yield* FileSystem.FileSystem;
304 const runner = yield* ProcessRunner.ProcessRunner;
305 if (platform === "linux") {
306 const cgroup = yield* fs.readFileString(`/proc/${pid}/cgroup`).pipe(Effect.option);
307 return Option.isSome(cgroup) && cgroup.value.includes("/t3code.service");
308 }
309 if (platform === "darwin") {
310 // The service server's parent is the launcher process.
311 const parent = yield* runner
312 .run({
313 command: "ps",
314 args: ["-o", "ppid=", "-p", String(pid)],
315 timeout: Duration.seconds(5),
316 })
317 .pipe(Effect.option);
318 const ppid = Option.isSome(parent) && parent.value.code === 0 ? parent.value.stdout.trim() : "";
319 if (!/^\d+$/.test(ppid)) return false;
320 const command = yield* runner
321 .run({ command: "ps", args: ["-o", "command=", "-p", ppid], timeout: Duration.seconds(5) })
322 .pipe(
323 Effect.map((result) => (result.code === 0 ? result.stdout : "")),
324 Effect.orElseSucceed(() => ""),
325 );
326 return /__service-launcher/.test(command);
327 }
328 return false;
329});
330​
331const runUpdate = Effect.fn("cli.update.run")(function* (input: {
332 readonly baseDir: string;
333 readonly logsDir: string;
334 readonly serverRuntimeStatePath: string;
335 readonly channel: CliReleaseChannel | undefined;
336 readonly requestedVersion: string | undefined;
337 readonly allowDowngrade: boolean;
338 readonly assumeYes: boolean;
339}) {
340 const fs = yield* FileSystem.FileSystem;
341 const path = yield* Path.Path;
342 const runner = yield* ProcessRunner.ProcessRunner;
343 const platform = yield* HostProcessPlatform;
344 const arch = yield* HostProcessArchitecture;
345 const environment = yield* HostProcessEnvironment;
346 const httpClient = yield* HttpClient.HttpClient;
347 const service = yield* BootService.BootService;
348​
349 const currentVersion = packageJson.version;
350 const channel = input.channel ?? cliReleaseChannelOf(currentVersion);
351 if (input.requestedVersion !== undefined && !isExactServiceVersion(input.requestedVersion)) {
352 return yield* new CliUpdateError({
353 reason: `'${input.requestedVersion}' is not an exact t3 version.`,
354 });
355 }
356 const progress = createUpdateProgress();
357 progress.status("Checking for updates...");
358 const targetVersion = yield* (
359 input.requestedVersion === undefined
360 ? resolveNewestVersion(channel)
361 : Effect.succeed(input.requestedVersion)
362 ).pipe(Effect.ensuring(Effect.sync(progress.finish)));
363 const targetChannel = cliReleaseChannelOf(targetVersion);
364​
365 // Preview is a maintainers' dogfooding train: it is cut by hand from
366 // unmerged branches, receives no fixes, and is never offered to anyone.
367 // Reaching it from stable or nightly takes an explicit ask and an explicit
368 // acknowledgement; the flag alone is not enough from a script.
369 const currentChannel = cliReleaseChannelOf(currentVersion);
370 if (targetChannel === "preview" && currentChannel !== "preview") {
371 yield* Console.log(
372 [
373 `t3@${targetVersion} is a preview build.`,
374 " Preview builds are cut by maintainers from unreleased branches to exercise the release",
375 " pipeline. They can be broken, receive no fixes, and are never offered as updates; you",
376 ` will have to switch back to ${currentChannel} yourself with \`t3 update --channel ${currentChannel} --allow-downgrade\`.`,
377 ].join("\n"),
378 );
379 if (!(process.stdin.isTTY && process.stdout.isTTY)) {
380 return yield* new CliUpdateError({
381 reason:
382 "Refusing to install a preview build without confirmation. Run this from a terminal to confirm, or pass --channel preview from an interactive shell.",
383 });
384 }
385 const confirmed = yield* Prompt.run(
386 Prompt.Confirm({ message: "Install the preview build anyway?", initial: false }),
387 ).pipe(Effect.catchTags({ QuitError: () => Effect.succeed(false) }));
388 if (!confirmed) {
389 yield* Console.log("Left as is.");
390 return;
391 }
392 }
393​
394 // Work out everything that will be touched before touching anything, so the
395 // user sees one plan and one question rather than a surprise restart.
396 const status = yield* service.status;
397 // The unit name is per user, not per T3 home. Only touch the service when it
398 // serves the home this update targets; otherwise it belongs to another
399 // install on this machine and restarting it would take that server down.
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 // What this machine runs is the executable behind the launcher and, when a
409 // service is installed for this home, the version that service runs. Either
410 // being stale is an update to do, and the newest of the two is what the
411 // downgrade check protects.
412 const serviceVersion = serviceInstalled ? status.installedVersion : undefined;
413 const executableCurrent = targetVersion === currentVersion;
414 // A service whose recorded version is missing or unreadable is not known
415 // to be current, so it gets the update rather than being skipped. Nor is
416 // one on the right version that is stopped, disabled, or still running the
417 // version before it (an earlier update where the restart was declined):
418 // `status.current` covers all of that when the target is this executable,
419 // and the problem list is what can be judged for any other target.
420 const restartPending = status.problems?.includes("restart-pending") === true;
421 const serviceCurrent =
422 !serviceInstalled ||
423 (serviceVersion === targetVersion &&
424 (executableCurrent ? status.current : (status.problems ?? []).length === 0));
425 const newestInstalled =
426 serviceVersion !== undefined && compareExactServiceVersions(serviceVersion, currentVersion) > 0
427 ? serviceVersion
428 : currentVersion;
429​
430 if (executableCurrent && serviceCurrent) {
431 yield* Console.log(
432 serviceVersion !== undefined
433 ? `t3 and its background service are already on ${targetVersion} (${targetChannel}).`
434 : `t3 is already on ${targetVersion} (${targetChannel}).`,
435 );
436 return;
437 }
438 if (!input.allowDowngrade && compareExactServiceVersions(targetVersion, newestInstalled) < 0) {
439 return yield* new CliUpdateError({
440 reason: `t3@${targetVersion} is older than the installed ${newestInstalled}. Pass --allow-downgrade to install it anyway.`,
441 });
442 }
443​
444 const alreadyOnDisk = yield* fs
445 .readFileString(pinnedRuntimePaths(path, input.baseDir, targetVersion, platform).sentinelPath)
446 .pipe(
447 Effect.map((sentinel) => sentinel.trim() === targetVersion),
448 Effect.orElseSucceed(() => false),
449 );
450​
451 progress.heading(
452 executableCurrent && restartPending
453 ? `The background service is still running the version before ${targetVersion} (${targetChannel}).`
454 : executableCurrent
455 ? `Updating the background service ${serviceVersion ?? "(unknown version)"} -> ${targetVersion} (${targetChannel}).`
456 : alreadyOnDisk
457 ? "Switching T3 Code"
458 : "Updating T3 Code",
459 executableCurrent
460 ? ""
461 : `${currentVersion} → ${targetVersion}${targetChannel === "stable" ? "" : ` (${targetChannel})`}`,
462 );
463 let restartService = false;
464 if (serviceInstalled && !serviceCurrent) {
465 yield* Console.log(
466 " A background service is installed for this T3 home. Restarting it interrupts anything running in it: agent turns, terminals, remote clients.",
467 );
468 if (input.assumeYes) {
469 restartService = true;
470 } else if (process.stdin.isTTY && process.stdout.isTTY) {
471 restartService = yield* Prompt.run(
472 Prompt.Confirm({
473 message: "Restart the background service once the download is verified?",
474 initial: true,
475 }),
476 ).pipe(Effect.catchTags({ QuitError: () => Effect.succeed(false) }));
477 } else {
478 yield* Console.log(
479 " Not a terminal, so the service keeps running its current version. Rerun with --yes to restart it now, or run `t3 service restart` later.",
480 );
481 }
482 }
483​
484 const runtime = yield* ensurePinnedRuntimeInstalled({
485 onProgress: progress.report,
486 baseDir: input.baseDir,
487 version: targetVersion,
488 fs,
489 path,
490 runner,
491 httpClient,
492 platform,
493 arch,
494 releaseBaseUrl: environment[CLI_RELEASE_BASE_URL_ENV]?.trim() || undefined,
495 validate: (paths) =>
496 runner
497 .run({
498 command: pinnedRuntimeCommand(paths).command,
499 args: [...pinnedRuntimeCommand(paths).args, "--version"],
500 timeout: Duration.seconds(30),
501 })
502 .pipe(
503 Effect.mapError(
504 (cause) =>
505 new PinnedRuntimeInstallError({ step: "verifying the downloaded t3", cause }),
506 ),
507 Effect.flatMap((result) =>
508 result.code === 0 && /\bv(\S+)\s*$/.exec(result.stdout)?.[1] === targetVersion
509 ? Effect.void
510 : Effect.fail(
511 new PinnedRuntimeInstallError({
512 step: "verifying the downloaded t3",
513 exitCode: Number(result.code),
514 }),
515 ),
516 ),
517 ),
518 }).pipe(
519 Effect.ensuring(Effect.sync(progress.finish)),
520 Effect.catchIf(
521 (error): error is PinnedRuntimeInstallError =>
522 error._tag === "PinnedRuntimeInstallError" &&
523 error.step.startsWith("downloading the t3 release checksums") &&
524 String(error.cause).includes("404"),
525 () =>
526 Effect.fail(
527 new CliUpdateError({
528 reason: `No release archive was published for t3@${targetVersion}.`,
529 }),
530 ),
531 ),
532 );
533​
534 const launchedAs = (yield* HostProcessIsExecutable) ? yield* resolveLauncherPath : undefined;
535 const repointed = yield* repointLauncher({
536 launchedAs,
537 versionsDir: path.dirname(runtime.versionDir),
538 targetEntryPath: runtime.entryPath,
539 });
540​
541 // The service switch runs in this process against the target version: the
542 // downloaded runtime has already proven it runs (the `--version` check
543 // above), and doing it here rather than through the target's own CLI means
544 // a downgrade to a version without today's commands still works. The unit
545 // is rewritten either way so a later `t3 service restart` lands on the new
546 // version; only the restart itself waits for the user's answer.
547 let serviceUpdated = false;
548 if (serviceInstalled && !serviceCurrent) {
549 yield* Console.log(
550 restartService
551 ? "Restarting the background service..."
552 : "Updating the background service...",
553 );
554 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 serviceUpdated = restartService;
573 }
574​
575 progress.success(`Installed T3 Code ${targetVersion}`);
576 if (Option.isSome(repointed)) {
577 yield* Console.log(" Run t3 to get started.\n");
578 } else {
579 yield* Console.log(` Run ${runtime.entryPath}\n`);
580 }
581 if (serviceUpdated) {
582 yield* Console.log(` Background service restarted on ${targetVersion}`);
583 } else if (serviceInstalled && serviceCurrent) {
584 yield* Console.log(` Background service already on ${targetVersion}`);
585 } else if (serviceInstalled) {
586 yield* Console.log(
587 ` Background service still running ${serviceVersion ?? "an unknown version"}. Run \`t3 service restart\` when you are ready to switch it to ${targetVersion}.`,
588 );
589 } else if (status.installed && !servesThisHome) {
590 yield* Console.log(
591 ` The background service serves ${status.installedBaseDir ?? "another T3 home"} and was left unchanged.`,
592 );
593 }
594 if (foreground !== undefined) {
595 yield* Console.log(
596 ` A server started by hand is still running at ${foreground.origin} (pid ${foreground.pid}). Stop it and start it again to pick up ${targetVersion}.`,
597 );
598 }
599});