Open History to see the last commit
1import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
2import * as Console from "effect/Console";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Terminal from "effect/Terminal";
6import { Command, Flag, GlobalFlag, Prompt } from "effect/unstable/cli";
7import { FetchHttpClient } from "effect/unstable/http";
8
9import packageJson from "../../package.json" with { type: "json" };
10import * as BootService from "../cloud/bootService.ts";
11import { compareExactServiceVersions } from "../cloud/serviceProtocol.ts";
12import type * as ServerConfig from "../config.ts";
13import * as ProcessRunner from "../processRunner.ts";
14import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
15
16export const bootServiceLayer = (config: ServerConfig.ServerConfig["Service"]) =>
17 BootService.layer({
18 baseDir: config.baseDir,
19 logsDir: config.logsDir,
20 cliVersion: packageJson.version,
21 }).pipe(
22 Layer.provide(ProcessRunner.layer),
23 // Archive-distributed versions download the release archive here.
24 Layer.provide(FetchHttpClient.layer),
25 );
26
27export type ServiceReconcileResult =
28 | {
29 readonly changed: false;
30 readonly status: BootService.BootServiceStatus;
31 }
32 | {
33 readonly changed: true;
34 readonly previouslyInstalled: boolean;
35 readonly plan: BootService.BootServicePlan;
36 };
37
38/** Install, update, or repair the service using the CLI version running this command. */
39export const reconcileService = Effect.fn("cli.service.reconcile")(function* (options?: {
40 readonly allowDowngrade?: boolean;
41}) {
42 const service = yield* BootService.BootService;
43 const status = yield* service.status;
44 if (status.installed && status.current) {
45 return { changed: false, status } satisfies ServiceReconcileResult;
46 }
47 if (
48 status.installedVersion !== undefined &&
49 options?.allowDowngrade !== true &&
50 compareExactServiceVersions(packageJson.version, status.installedVersion) < 0
51 ) {
52 return yield* new BootService.BootServiceDowngradeRefusedError({
53 installedVersion: status.installedVersion,
54 targetVersion: packageJson.version,
55 });
56 }
57 const plan = yield* service.install(options);
58 return {
59 changed: true,
60 previouslyInstalled: status.installed,
61 plan,
62 } satisfies ServiceReconcileResult;
63});
64
65export function formatServiceStatus(
66 status: BootService.BootServiceStatus,
67 cliVersion: string,
68): string {
69 if (!status.supported) {
70 return "T3 Code service\n Status: unavailable on this machine\n Supported on: Linux with systemd, macOS with launchd";
71 }
72 if (!status.installed) {
73 return "T3 Code service\n Status: not installed\n Next: Run `t3 service install`.";
74 }
75 const installedVersion = status.installedVersion ?? cliVersion;
76 const problems = (status.problems ?? []).map(
77 (problem) => ` [${problem}] ${BootService.formatBootServiceProblem(problem)}`,
78 );
79 if (
80 !status.current &&
81 status.installedVersion !== undefined &&
82 compareExactServiceVersions(status.installedVersion, cliVersion) > 0
83 ) {
84 return [
85 "T3 Code service",
86 ` Status: installed · t3@${installedVersion} (newer than this t3@${cliVersion} CLI)`,
87 ` Unit: ${status.unitPath}`,
88 ` Logs: ${status.logPath}`,
89 ...problems,
90 ` Next: Use \`npx t3@${installedVersion} service update\` to repair it, or pass \`--allow-downgrade\` explicitly.`,
91 ].join("\n");
92 }
93 return [
94 "T3 Code service",
95 ` Status: ${status.current ? `installed · t3@${installedVersion}` : "needs an update or repair"}`,
96 ` Unit: ${status.unitPath}`,
97 ` Logs: ${status.logPath}`,
98 ...problems,
99 ...(status.current ? [] : [` Next: Run \`npx t3@${cliVersion} service update\`.`]),
100 ].join("\n");
101}
102
103const runServiceCommand = Effect.fn("cli.service.run")(function* <A, E>(
104 flags: { readonly baseDir: Parameters<typeof resolveCliAuthConfig>[0]["baseDir"] },
105 run: Effect.Effect<A, E, BootService.BootService>,
106) {
107 const logLevel = yield* GlobalFlag.LogLevel;
108 const config = yield* resolveCliAuthConfig(flags, logLevel);
109 return yield* run.pipe(Effect.provide(bootServiceLayer(config)));
110});
111
112const serviceReconcileFlags = {
113 ...projectLocationFlags,
114 allowDowngrade: Flag.boolean("allow-downgrade").pipe(
115 Flag.withDescription("Allow replacing a newer installed service with this older CLI version."),
116 Flag.withDefault(false),
117 ),
118};
119
120const serviceInstallCommand = Command.make("install", serviceReconcileFlags).pipe(
121 Command.withDescription("Install T3 Code as a background service for this user."),
122 Command.withHandler((flags) =>
123 runServiceCommand(
124 flags,
125 Effect.gen(function* () {
126 const result = yield* reconcileService({ allowDowngrade: flags.allowDowngrade });
127 if (!result.changed) {
128 yield* Console.log(
129 `T3 Code service is already installed with t3@${packageJson.version}.`,
130 );
131 return;
132 }
133 yield* Console.log(
134 `${result.previouslyInstalled ? "Updated" : "Installed"} T3 Code service with t3@${packageJson.version}.\nLogs: ${result.plan.logPath}`,
135 );
136 }),
137 ),
138 ),
139);
140
141const serviceUpdateCommand = Command.make("update", serviceReconcileFlags).pipe(
142 Command.withDescription(
143 "Update or repair the background service using this CLI version. Use `t3 update` to move to a newer release first.",
144 ),
145 Command.withHandler((flags) =>
146 runServiceCommand(
147 flags,
148 Effect.gen(function* () {
149 const result = yield* reconcileService({ allowDowngrade: flags.allowDowngrade });
150 if (!result.changed) {
151 yield* Console.log(`T3 Code service is already using t3@${packageJson.version}.`);
152 return;
153 }
154 yield* Console.log(
155 `${result.previouslyInstalled ? "Updated" : "Installed"} T3 Code service with t3@${packageJson.version}.\nLogs: ${result.plan.logPath}`,
156 );
157 }),
158 ),
159 ),
160);
161
162const serviceUninstallCommand = Command.make("uninstall", projectLocationFlags).pipe(
163 Command.withDescription("Stop and remove the T3 Code background service."),
164 Command.withHandler((flags) =>
165 runServiceCommand(
166 flags,
167 Effect.gen(function* () {
168 const service = yield* BootService.BootService;
169 const removed = yield* service.uninstall;
170 yield* Console.log(
171 removed ? "Removed the T3 Code service." : "T3 Code service is not installed.",
172 );
173 }),
174 ),
175 ),
176);
177
178const serviceStatusCommand = Command.make("status", projectLocationFlags).pipe(
179 Command.withDescription("Show whether the T3 Code background service is installed."),
180 Command.withHandler((flags) =>
181 runServiceCommand(
182 flags,
183 Effect.gen(function* () {
184 const service = yield* BootService.BootService;
185 yield* Console.log(formatServiceStatus(yield* service.status, packageJson.version));
186 }),
187 ),
188 ),
189);
190
191export const offerServiceDuringOnboarding = Effect.gen(function* () {
192 const service = yield* BootService.BootService;
193 const status = yield* service.status;
194 const { supported, installed, current } = status;
195 if (!supported) {
196 return false;
197 }
198 if (installed && current) {
199 yield* Console.log("T3 Code is already set up to run in the background on this machine.");
200 return true;
201 }
202 for (const problem of status.problems ?? []) {
203 yield* Console.warn(`[${problem}] ${BootService.formatBootServiceProblem(problem)}`);
204 }
205 if (
206 installed &&
207 status.installedVersion !== undefined &&
208 compareExactServiceVersions(status.installedVersion, packageJson.version) > 0
209 ) {
210 yield* Console.log(
211 `A newer t3@${status.installedVersion} background service is installed. Leaving it unchanged.`,
212 );
213 // This CLI cannot verify the newer service. Keep the manual fallback available.
214 return false;
215 }
216 // A LaunchAgent starts at login and dies at logout; there is no
217 // enable-linger equivalent on macOS. Do not promise more than that.
218 const platform = yield* HostProcessPlatform;
219 const wanted = yield* Prompt.run(
220 Prompt.confirm({
221 message: installed
222 ? "The installed T3 Code service needs an update or repair. Update it now?"
223 : platform === "darwin"
224 ? "Run T3 Code in the background whenever you log in to this Mac? " +
225 "It stays reachable through T3 Connect while you are logged in."
226 : "Run T3 Code in the background whenever this machine boots? " +
227 "It stays reachable through T3 Connect even after you log out.",
228 initial: true,
229 }),
230 );
231 if (!wanted) {
232 return false;
233 }
234 const result = yield* reconcileService();
235 if (result.changed) {
236 yield* Console.log(
237 `Background service ${result.previouslyInstalled ? "updated" : "installed"}. Logs: ${result.plan.logPath}`,
238 );
239 }
240 return true;
241});
242
243export const recoverServiceOnboardingOffer = <R>(
244 offer: Effect.Effect<boolean, BootService.BootServiceError | Terminal.QuitError, R>,
245) =>
246 offer.pipe(
247 Effect.catchTags({
248 QuitError: () => Effect.succeed(false),
249 BootServiceUnsupportedError: (error) =>
250 Console.log(`Skipping background setup: ${error.message}`).pipe(Effect.as(false)),
251 BootServiceCommandError: (error) =>
252 Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
253 BootServiceInstallError: (error) =>
254 Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
255 BootServicePrerequisiteError: (error) =>
256 Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
257 BootServiceUpdatePendingError: (error) =>
258 Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
259 BootServiceDowngradeRefusedError: (error) =>
260 Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
261 }),
262 );
263
264export const serviceCommand = Command.make("service").pipe(
265 Command.withDescription("Manage the T3 Code background service."),
266 Command.withSubcommands([
267 serviceInstallCommand,
268 serviceUninstallCommand,
269 serviceUpdateCommand,
270 serviceStatusCommand,
271 ]),
272);