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