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

update.ts

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