Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, expect, it } from "@effect/vitest";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import * as NetService from "@t3tools/shared/Net";
5import * as ConfigProvider from "effect/ConfigProvider";
6import * as Console from "effect/Console";
7import * as Effect from "effect/Effect";
8import * as FileSystem from "effect/FileSystem";
9import * as Layer from "effect/Layer";
10import * as Terminal from "effect/Terminal";
11import { Command } from "effect/cli";
12import { afterEach, vi } from "vite-plus/test";
13
14import packageJson from "../../package.json" with { type: "json" };
15import * as BootService from "../cloud/bootService.ts";
16import {
17 formatServiceStatus,
18 offerServiceDuringOnboarding,
19 reconcileService,
20 recoverServiceOnboardingOffer,
21 serviceCommand,
22} from "./service.ts";
23
24afterEach(() => vi.restoreAllMocks());
25
26const status = {
27 supported: true,
28 installed: true,
29 current: true,
30 unitPath: "/home/me/.config/systemd/user/t3code.service",
31 logPath: "/home/me/.t3/userdata/logs/boot-service.log",
32} as const;
33
34it("reports the installed service version and host paths", () => {
35 assert.equal(
36 formatServiceStatus(status, "0.0.29"),
37 [
38 "T3 Code service",
39 " Status: installed · t3@0.0.29",
40 " Unit: /home/me/.config/systemd/user/t3code.service",
41 " Logs: /home/me/.t3/userdata/logs/boot-service.log",
42 ].join("\n"),
43 );
44});
45
46it("gives a direct repair command for a stale service", () => {
47 assert.include(
48 formatServiceStatus({ ...status, current: false }, "0.0.29"),
49 "Next: Run `t3 service install` to repair it.",
50 );
51});
52
53it("explains an incomplete nightly installation and keeps repair on its installed version", () => {
54 const output = formatServiceStatus(
55 {
56 ...status,
57 current: false,
58 installedVersion: "0.0.32-nightly.1",
59 problems: ["linger-disabled", "service-stopped"],
60 },
61 "0.0.32-nightly.1",
62 );
63
64 expect(output).toContain("[linger-disabled]");
65 expect(output).toContain("last login session ends");
66 expect(output).toContain('sudo loginctl enable-linger "$(id -un)"');
67 expect(output).toContain("[service-stopped]");
68 expect(output).toContain("Run `t3 service install` to repair it.");
69 expect(output).not.toContain("npx");
70});
71
72it("points an older service at a repair, never at npx", () => {
73 const output = formatServiceStatus(
74 { ...status, current: false, installedVersion: "0.0.28" },
75 "0.0.29",
76 );
77 expect(output).toContain("Run `t3 service install` to repair it.");
78 expect(output).not.toContain("npx");
79});
80
81it("explains where the service is supported", () => {
82 assert.include(
83 formatServiceStatus({ ...status, supported: false, installed: false }, "0.0.29"),
84 "Supported on: Linux with systemd, macOS with launchd",
85 );
86});
87
88it("reports a newer installed service and tells the CLI to catch up to it", () => {
89 const output = formatServiceStatus(
90 { ...status, current: false, installedVersion: "0.0.32-nightly.1" },
91 "0.0.31",
92 );
93
94 assert.include(output, "t3@0.0.32-nightly.1 (newer than this t3@0.0.31 CLI)");
95 assert.include(output, "Run `t3 update 0.0.32-nightly.1` to match it");
96 assert.notInclude(output, "npx");
97});
98
99const newerServiceStatus = { ...status, current: false, installedVersion: "999.0.0" };
100
101function makeTestService(
102 serviceStatus: BootService.BootServiceStatus,
103 restartOutcome: "restarted" | "queued" = "restarted",
104) {
105 const installOptions: Array<Parameters<BootService.BootService["Service"]["install"]>[0]> = [];
106 const restarts: Array<true> = [];
107 const service = BootService.BootService.of({
108 status: Effect.succeed(serviceStatus),
109 withStopped: (operation) => operation,
110 restart: Effect.sync(() => {
111 restarts.push(true);
112 return serviceStatus.installed ? restartOutcome : "skipped";
113 }),
114 install: (options) =>
115 Effect.sync(() => {
116 installOptions.push(options);
117 return {
118 program: ["/test/t3/runtime/versions/1.0.0/t3", "__service-launcher"],
119 baseDir: "/test/t3",
120 unitPath: serviceStatus.unitPath,
121 logPath: serviceStatus.logPath,
122 };
123 }),
124 uninstall: Effect.succeed(false),
125 });
126 return { service, installOptions, restarts };
127}
128
129it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("service commands", (it) => {
130 it.effect("restart restarts the installed service", () =>
131 Effect.gen(function* () {
132 const fs = yield* FileSystem.FileSystem;
133 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-cli-test-" });
134 const { service, installOptions, restarts } = makeTestService(status);
135 vi.spyOn(BootService, "layer").mockReturnValue(
136 Layer.succeed(BootService.BootService, service),
137 );
138
139 yield* Command.runWith(serviceCommand, { version: packageJson.version })([
140 "restart",
141 "--base-dir",
142 baseDir,
143 ]).pipe(
144 Effect.provideService(HostProcess.Environment, {}),
145 Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} }))),
146 );
147
148 expect(restarts).toEqual([true]);
149 expect(installOptions).toEqual([]);
150 }),
151 );
152
153 it.effect("restart from inside the service says the restart is only queued", () =>
154 Effect.gen(function* () {
155 const fs = yield* FileSystem.FileSystem;
156 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-cli-test-" });
157 const { service } = makeTestService({ ...status, installedVersion: "0.0.30" }, "queued");
158 vi.spyOn(BootService, "layer").mockReturnValue(
159 Layer.succeed(BootService.BootService, service),
160 );
161 const lines: Array<string> = [];
162 const testConsole = {
163 ...globalThis.console,
164 log: (...args: ReadonlyArray<unknown>) => {
165 lines.push(args.map(String).join(" "));
166 },
167 } satisfies Console.Console;
168
169 yield* Command.runWith(serviceCommand, { version: packageJson.version })([
170 "restart",
171 "--base-dir",
172 baseDir,
173 ]).pipe(
174 Effect.provideService(HostProcess.Environment, {}),
175 Effect.provideService(Console.Console, testConsole),
176 Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} }))),
177 );
178
179 const output = lines.join("\n");
180 expect(output).not.toContain("Restarted");
181 expect(output).toContain("Queued a restart of the T3 Code service on t3@0.0.30");
182 expect(output).toContain(`Logs: ${status.logPath}`);
183 }),
184 );
185
186 it.effect("install reports a handed-off switch as pending", () =>
187 Effect.gen(function* () {
188 const fs = yield* FileSystem.FileSystem;
189 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-cli-test-" });
190 const { service } = makeTestService({ ...status, current: false });
191 vi.spyOn(BootService, "layer").mockReturnValue(
192 Layer.succeed(BootService.BootService, {
193 ...service,
194 install: (options) =>
195 service.install(options).pipe(Effect.map((plan) => ({ ...plan, handedOff: true }))),
196 }),
197 );
198 const lines: string[] = [];
199 yield* Command.runWith(serviceCommand, { version: packageJson.version })([
200 "install",
201 "--base-dir",
202 baseDir,
203 ]).pipe(
204 Effect.provideService(HostProcess.Environment, {}),
205 Effect.provideService(Console.Console, {
206 ...globalThis.console,
207 log: (...args) => {
208 lines.push(args.map(String).join(" "));
209 },
210 }),
211 Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} }))),
212 );
213
214 const output = lines.join("\n");
215 expect(output).not.toMatch(/(?:Installed|Updated) T3 Code service/);
216 expect(output).toContain("separate systemd unit");
217 expect(output).toContain(status.logPath);
218 }),
219 );
220
221 it.effect.each(["install", "update"] as const)(
222 "%s refuses a downgrade before changing the service",
223 (command) =>
224 Effect.gen(function* () {
225 const fs = yield* FileSystem.FileSystem;
226 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-cli-test-" });
227 const { service, installOptions } = makeTestService(newerServiceStatus);
228 vi.spyOn(BootService, "layer").mockReturnValue(
229 Layer.succeed(BootService.BootService, service),
230 );
231
232 const error = yield* Command.runWith(serviceCommand, { version: packageJson.version })([
233 command,
234 "--base-dir",
235 baseDir,
236 ]).pipe(
237 Effect.provideService(HostProcess.Environment, {}),
238 Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} }))),
239 Effect.flip,
240 );
241
242 expect(error).toMatchObject({
243 _tag: "BootServiceDowngradeRefusedError",
244 installedVersion: "999.0.0",
245 targetVersion: packageJson.version,
246 });
247 expect(installOptions).toEqual([]);
248 }),
249 );
250
251 it.effect.each(["install", "update"] as const)("%s allows an explicit downgrade", (command) =>
252 Effect.gen(function* () {
253 const fs = yield* FileSystem.FileSystem;
254 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-cli-test-" });
255 const { service, installOptions } = makeTestService(newerServiceStatus);
256 vi.spyOn(BootService, "layer").mockReturnValue(
257 Layer.succeed(BootService.BootService, service),
258 );
259
260 yield* Command.runWith(serviceCommand, { version: packageJson.version })([
261 command,
262 "--base-dir",
263 baseDir,
264 "--allow-downgrade",
265 ]).pipe(
266 Effect.provideService(HostProcess.Environment, {}),
267 Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} }))),
268 );
269
270 expect(installOptions).toEqual([{ allowDowngrade: true }]);
271 }),
272 );
273});
274
275it.effect.each([
276 { name: "a new service", state: { ...status, installed: false, current: false } },
277 { name: "an older service", state: { ...status, current: false, installedVersion: "0.0.0" } },
278 {
279 name: "the same version",
280 state: { ...status, current: false, installedVersion: packageJson.version },
281 },
282 {
283 name: "an incomplete install of the same version",
284 state: {
285 ...status,
286 current: false,
287 installedVersion: packageJson.version,
288 problems: ["linger-disabled"] as const,
289 },
290 },
291 { name: "an unknown version", state: { ...status, current: false } },
292])("installs or repairs $name without an override", ({ state }) =>
293 Effect.gen(function* () {
294 const { service, installOptions } = makeTestService(state);
295
296 const result = yield* reconcileService().pipe(
297 Effect.provideService(BootService.BootService, service),
298 );
299
300 expect(result.changed).toBe(true);
301 expect(installOptions).toEqual([undefined]);
302 }),
303);
304
305it.effect("leaves a newer service unchanged during onboarding without prompting", () =>
306 Effect.gen(function* () {
307 const { service, installOptions } = makeTestService(newerServiceStatus);
308 const terminal = Terminal.make({
309 columns: Effect.succeed(80),
310 rows: Effect.succeed(24),
311 readInput: Effect.die("Onboarding must not prompt to replace a newer service."),
312 readLine: Effect.die("Onboarding must not prompt to replace a newer service."),
313 display: () => Effect.die("Onboarding must not prompt to replace a newer service."),
314 });
315
316 const ready = yield* offerServiceDuringOnboarding.pipe(
317 Effect.provideService(BootService.BootService, service),
318 Effect.provideService(Terminal.Terminal, terminal),
319 Effect.provide(NodeServices.layer),
320 );
321
322 expect(ready).toBe("skipped");
323 expect(installOptions).toEqual([]);
324 }),
325);
326
327it.effect("keeps onboarding successful when a newer version appears before install", () =>
328 Effect.gen(function* () {
329 const ready = yield* recoverServiceOnboardingOffer(
330 Effect.fail(
331 new BootService.BootServiceDowngradeRefusedError({
332 installedVersion: "999.0.0",
333 targetVersion: packageJson.version,
334 }),
335 ),
336 );
337
338 expect(ready).toBe("skipped");
339 }),
340);
341
342it.effect("keeps the manual-server fallback when background prerequisites fail", () =>
343 Effect.gen(function* () {
344 const ready = yield* recoverServiceOnboardingOffer(
345 Effect.fail(new BootService.BootServicePrerequisiteError({ problem: "linger-disabled" })),
346 );
347 expect(ready).toBe("skipped");
348 }),
349);