Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { expect, it } from "@effect/vitest";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import * as ConfigProvider from "effect/ConfigProvider";
5import * as Duration from "effect/Duration";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Path from "effect/Path";
10import { HttpClient } from "effect/http";
11import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
12
13import * as ProcessRunner from "../processRunner.ts";
14import * as BootService from "./bootService.ts";
15import { pinnedRuntimePaths } from "./pinnedRuntime.ts";
16import {
17 parseServiceState,
18 SERVICE_LAUNCHER_PROTOCOL,
19 SERVICE_RESTART_PENDING_FILE,
20 serviceStateHasPendingUpdate,
21} from "./serviceProtocol.ts";
22
23const linuxRuntime = "/home/theo/.t3/runtime/versions/1.2.3/t3";
24const linuxPlan = {
25 program: [linuxRuntime, "__service-launcher"],
26 baseDir: "/home/theo/.t3",
27 logPath: "/home/theo/.t3/userdata/logs/boot-service.log",
28 unitPath: "/home/theo/.config/systemd/user/t3code.service",
29};
30
31it("runs the pinned runtime's own executable as the systemd launcher", () => {
32 const unit = BootService.renderBootServiceUnit(linuxPlan);
33
34 expect(unit).toContain(`ExecStart=${linuxRuntime} __service-launcher`);
35 expect(unit).toContain("KillMode=mixed");
36 expect(unit).not.toContain("node");
37});
38
39it("reads the served T3 home back out of a rendered unit or plist", () => {
40 const plan = (baseDir: string) => ({
41 program: [`${baseDir}/runtime/versions/1.2.3/t3`, "__service-launcher"],
42 baseDir,
43 logPath: `${baseDir}/userdata/logs/boot-service.log`,
44 unitPath: "/home/theo/.config/systemd/user/t3code.service",
45 });
46
47 expect(
48 BootService.bootServiceBaseDirOf(BootService.renderBootServiceUnit(plan("/home/theo/.t3"))),
49 ).toBe("/home/theo/.t3");
50 // Spaces and specifiers are quoted and escaped on the way in.
51 expect(
52 BootService.bootServiceBaseDirOf(
53 BootService.renderBootServiceUnit(plan("/home/theo/T3 Data/100%")),
54 ),
55 ).toBe("/home/theo/T3 Data/100%");
56 expect(
57 BootService.bootServiceBaseDirOf(
58 BootService.renderBootServicePlist(plan("/Users/theo/a&b"), {
59 homeDir: "/Users/theo",
60 environmentPath: "/usr/bin",
61 }),
62 ),
63 ).toBe("/Users/theo/a&b");
64 expect(BootService.bootServiceBaseDirOf("[Service]\nExecStart=/x\n")).toBeUndefined();
65});
66
67it("survives the kernel OOM-killing a greedy agent child", () => {
68 const unit = BootService.renderBootServiceUnit(linuxPlan);
69
70 expect(unit).toContain("OOMPolicy=continue");
71});
72
73const macRuntime = "/Users/theo/.t3/runtime/versions/1.2.3/t3";
74const macPlan = {
75 program: [macRuntime, "__service-launcher"],
76 baseDir: "/Users/theo/.t3",
77 logPath: "/Users/theo/.t3/userdata/logs/boot-service.log",
78 unitPath: "/Users/theo/Library/LaunchAgents/com.t3tools.t3code.service.plist",
79};
80const macInstallerPath =
81 "/opt/homebrew/bin:/Users/theo/.npm-global/bin:/Users/theo/.nvm/versions/node/v22.16.0/bin:/usr/bin:/bin";
82const macRenderOptions = { homeDir: "/Users/theo", environmentPath: macInstallerPath };
83
84it("runs the pinned runtime's own executable as the launch agent", () => {
85 const plist = BootService.renderBootServicePlist(macPlan, macRenderOptions);
86
87 expect(plist).toContain(
88 ` <array>\n <string>${macRuntime}</string>\n <string>__service-launcher</string>\n </array>`,
89 );
90 expect(plist).not.toContain("node</string>");
91});
92
93it("preserves the installer's provider search path in the launch agent", () => {
94 const plist = BootService.renderBootServicePlist(macPlan, macRenderOptions);
95
96 expect(plist).toContain(` <key>PATH</key>\n <string>${macInstallerPath}</string>`);
97});
98
99it("restarts the launch agent on the systemd cadence", () => {
100 const plist = BootService.renderBootServicePlist(macPlan, macRenderOptions);
101
102 expect(plist).toContain("<key>RunAtLoad</key>\n <true/>");
103 expect(plist).toContain("<key>KeepAlive</key>\n <true/>");
104 expect(plist).toContain("<key>ThrottleInterval</key>\n <integer>5</integer>");
105 expect(plist).toContain("<key>ExitTimeOut</key>\n <integer>90</integer>");
106});
107
108it("appends both stdio streams to the boot service log", () => {
109 const plist = BootService.renderBootServicePlist(macPlan, macRenderOptions);
110
111 expect(plist).toContain(
112 "<key>StandardOutPath</key>\n <string>/Users/theo/.t3/userdata/logs/boot-service.log</string>",
113 );
114 expect(plist).toContain(
115 "<key>StandardErrorPath</key>\n <string>/Users/theo/.t3/userdata/logs/boot-service.log</string>",
116 );
117});
118
119it("escapes XML in host paths", () => {
120 const plist = BootService.renderBootServicePlist(
121 { ...macPlan, baseDir: "/Users/theo/T3 & <Co>" },
122 { homeDir: "/Users/theo", environmentPath: "/Users/theo/Tools & <Scripts>:/usr/bin" },
123 );
124
125 expect(plist).toContain("<string>/Users/theo/T3 & <Co></string>");
126 expect(plist).toContain("<string>/Users/theo/Tools & <Scripts>:/usr/bin</string>");
127});
128
129const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
130 platform: NodeJS.Platform = "linux",
131 installerPath = macInstallerPath,
132) {
133 const fs = yield* FileSystem.FileSystem;
134 const path = yield* Path.Path;
135 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-boot-service-test-" });
136 const baseDir = path.join(home, ".t3");
137 const statePath = path.join(baseDir, "runtime", "service-state.json");
138 // A complete pinned runtime is already present, so install only validates
139 // it and never downloads a release archive.
140 const runtime = pinnedRuntimePaths(path, baseDir, "1.2.3", platform);
141 yield* fs.makeDirectory(path.dirname(runtime.entryPath), { recursive: true });
142 yield* fs.writeFileString(runtime.entryPath, "#!/bin/sh\n");
143 yield* fs.writeFileString(runtime.sentinelPath, "1.2.3\n");
144
145 const commands: string[] = [];
146 const timeouts = new Map<string, unknown>();
147 const control: {
148 failCommand: string | undefined;
149 stateAfterStop?: string;
150 linger: string;
151 enabled: boolean;
152 active: boolean;
153 } = {
154 failCommand: undefined,
155 linger: "yes",
156 enabled: true,
157 active: true,
158 };
159 const runner = ProcessRunner.ProcessRunner.of({
160 run: Effect.fn("test.run_boot_service_command")(function* (
161 input: ProcessRunner.ProcessRunInput,
162 ) {
163 const command = `${input.command} ${input.args.join(" ")}`;
164 commands.push(command);
165 timeouts.set(command, input.timeout);
166 const failed = command === control.failCommand;
167 if (!failed && command === "loginctl enable-linger --no-ask-password 501")
168 control.linger = "yes";
169 if (!failed && command === "systemctl --user enable t3code.service") control.enabled = true;
170 if (!failed && command === "systemctl --user restart t3code.service") control.active = true;
171 // A stop that fails (a timeout, say) has still stopped the service.
172 if (command === "systemctl --user stop t3code.service") control.active = false;
173 if (
174 control.stateAfterStop !== undefined &&
175 (command === "systemctl --user stop t3code.service" ||
176 command.startsWith("launchctl bootout --wait "))
177 ) {
178 yield* fs.writeFileString(statePath, control.stateAfterStop).pipe(Effect.orDie);
179 }
180 return {
181 stdout:
182 input.args[0] === "--version"
183 ? // The runtime under test reports the version of the directory it
184 // was launched from, like the real executable.
185 `t3 v${/versions\/([^/]+)\//.exec(input.command)?.[1] ?? "1.2.3"}\n`
186 : input.command === "loginctl" && input.args[0] === "show-user"
187 ? `${control.linger}\n`
188 : input.args[1] === "is-enabled"
189 ? control.enabled
190 ? "enabled\n"
191 : "disabled\n"
192 : "",
193 stderr: "",
194 code: ChildProcessSpawner.ExitCode(
195 failed ||
196 (input.args[1] === "is-active" && !control.active) ||
197 (input.args[1] === "is-enabled" && !control.enabled)
198 ? 1
199 : 0,
200 ),
201 timedOut: false,
202 stdoutTruncated: false,
203 stderrTruncated: false,
204 stdoutInvalidUtf8: false,
205 stderrInvalidUtf8: false,
206 };
207 }),
208 });
209 const makeService = (
210 environmentPath: string | undefined = installerPath,
211 cliVersion = "1.2.3",
212 serviceBaseDir = baseDir,
213 ) =>
214 Effect.gen(function* () {
215 // Every version the tests install is present and verified on disk, so
216 // install never downloads.
217 const paths = pinnedRuntimePaths(path, serviceBaseDir, cliVersion, platform);
218 yield* fs.makeDirectory(path.dirname(paths.entryPath), { recursive: true });
219 yield* fs.writeFileString(paths.entryPath, "#!/bin/sh\n");
220 yield* fs.writeFileString(paths.sentinelPath, `${cliVersion}\n`);
221 return yield* BootService.make({
222 baseDir: serviceBaseDir,
223 logsDir: path.join(serviceBaseDir, "userdata", "logs"),
224 cliVersion,
225 host: { execPath: "/usr/bin/t3" },
226 });
227 }).pipe(
228 Effect.provideService(ProcessRunner.ProcessRunner, runner),
229 Effect.provide(
230 Layer.mergeAll(
231 Layer.succeed(HostProcess.Platform, platform),
232 Layer.succeed(HostProcess.UserId, 501),
233 Layer.succeed(HostProcess.ExecutablePath, "/usr/bin/t3"),
234 Layer.succeed(
235 HttpClient.HttpClient,
236 HttpClient.make(() => Effect.die("no release download expected")),
237 ),
238 ConfigProvider.layer(
239 ConfigProvider.fromEnv({
240 env: {
241 HOME: home,
242 ...(environmentPath === undefined || environmentPath === ""
243 ? {}
244 : { PATH: environmentPath }),
245 },
246 }),
247 ),
248 ),
249 ),
250 );
251 const service = yield* makeService();
252 return { service, makeService, fs, statePath, commands, timeouts, control, runtime };
253});
254
255it.layer(NodeServices.layer)("boot service install", (it) => {
256 it.effect(
257 "fails before installing files or validating a runtime when lingering needs an administrator",
258 () =>
259 Effect.gen(function* () {
260 const { service, fs, statePath, commands, control, runtime } = yield* makeHarness();
261 const before = yield* service.status;
262 control.linger = "no";
263 control.failCommand = "loginctl enable-linger --no-ask-password 501";
264 yield* fs.remove(runtime.sentinelPath);
265
266 const error = yield* service.install().pipe(Effect.flip);
267
268 expect(error).toMatchObject({
269 _tag: "BootServicePrerequisiteError",
270 problem: "linger-disabled",
271 });
272 expect(error.message).toContain('sudo loginctl enable-linger "$(id -un)"');
273 expect(error.message).toContain("last login session ends");
274 expect(yield* fs.exists(before.unitPath)).toBe(false);
275 expect(yield* fs.exists(statePath)).toBe(false);
276 expect(commands.some((command) => command.includes("--version"))).toBe(false);
277 expect(
278 commands.some(
279 (command) => command.includes("daemon-reload") || command.includes("restart"),
280 ),
281 ).toBe(false);
282 expect(yield* fs.readFileString(before.logPath)).toContain("[linger-disabled]");
283 }),
284 );
285
286 it.effect(
287 "detects a partial install and preserves the running service when repair lacks permission",
288 () =>
289 Effect.gen(function* () {
290 const { service, fs, statePath, commands, control } = yield* makeHarness();
291 const plan = yield* service.install();
292 const before = yield* fs.readFileString(statePath);
293 const unit = yield* fs.readFileString(plan.unitPath);
294 control.linger = "no";
295 control.failCommand = "loginctl enable-linger --no-ask-password 501";
296
297 expect(yield* service.status).toMatchObject({
298 current: false,
299 problems: ["linger-disabled"],
300 });
301 commands.length = 0;
302 expect((yield* service.install().pipe(Effect.flip))._tag).toBe(
303 "BootServicePrerequisiteError",
304 );
305 expect(yield* fs.readFileString(statePath)).toBe(before);
306 expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);
307 expect(commands).not.toContain("systemctl --user stop t3code.service");
308 }),
309 );
310
311 it.effect("enables lingering before installing and repairs stopped or disabled services", () =>
312 Effect.gen(function* () {
313 const { service, commands, control } = yield* makeHarness();
314 control.linger = "no";
315 yield* service.install();
316 expect(control.linger).toBe("yes");
317 expect(commands.indexOf("loginctl enable-linger --no-ask-password 501")).toBeLessThan(
318 commands.indexOf("systemctl --user daemon-reload"),
319 );
320
321 control.enabled = false;
322 control.active = false;
323 expect(yield* service.status).toMatchObject({
324 current: false,
325 problems: ["service-disabled", "service-stopped"],
326 });
327 yield* service.install();
328 expect((yield* service.status).current).toBe(true);
329 }),
330 );
331
332 it.effect.each([
333 { command: "systemctl --user show-environment", problem: "user-manager-unavailable" },
334 { command: "loginctl show-user 501 --property=Linger --value", problem: "linger-unavailable" },
335 ])("reports failed prerequisite probes without installing: $command", ({ command, problem }) =>
336 Effect.gen(function* () {
337 const { service, fs, statePath, control } = yield* makeHarness();
338 control.failCommand = command;
339 expect(yield* service.install().pipe(Effect.flip)).toMatchObject({
340 _tag: "BootServicePrerequisiteError",
341 problem,
342 });
343 expect(yield* fs.exists(statePath)).toBe(false);
344 }),
345 );
346
347 it.effect("installs, reports current state, and uninstalls", () =>
348 Effect.gen(function* () {
349 const { service, fs, statePath, timeouts, runtime } = yield* makeHarness();
350 const plan = yield* service.install();
351
352 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
353 protocol: SERVICE_LAUNCHER_PROTOCOL,
354 activeVersion: "1.2.3",
355 });
356 expect(plan.program).toEqual([runtime.entryPath, "__service-launcher"]);
357 expect(yield* fs.readFileString(plan.unitPath)).toContain(
358 `ExecStart=${runtime.entryPath} __service-launcher`,
359 );
360 expect(yield* service.status).toMatchObject({
361 current: true,
362 installedVersion: "1.2.3",
363 });
364 const pendingState = JSON.stringify({
365 protocol: SERVICE_LAUNCHER_PROTOCOL,
366 activeVersion: "1.2.3",
367 update: {
368 id: "u",
369 fromVersion: "1.2.3",
370 targetVersion: "1.2.4",
371 dbPath: "/tmp/state.sqlite",
372 status: "pending",
373 },
374 });
375 yield* fs.writeFileString(statePath, pendingState);
376 expect((yield* service.status).current).toBe(false);
377 expect(yield* service.uninstall).toBe(true);
378 expect((yield* service.status).installed).toBe(false);
379 // The stop can block up to systemd's 90s TimeoutStopSec; the runner's
380 // 60s default would cancel it mid-shutdown.
381 expect(timeouts.get("systemctl --user disable --now t3code.service")).toEqual(
382 Duration.seconds(120),
383 );
384 }),
385 );
386
387 it.effect.each(["linux", "darwin"] as const)(
388 "reports the installed version across launcher protocols on %s",
389 (platform) =>
390 Effect.gen(function* () {
391 const { service, fs, statePath } = yield* makeHarness(platform);
392 yield* service.install();
393
394 for (const protocol of [SERVICE_LAUNCHER_PROTOCOL - 1, SERVICE_LAUNCHER_PROTOCOL + 1]) {
395 yield* fs.writeFileString(
396 statePath,
397 `{"protocol":${protocol},"activeVersion":"1.2.4-nightly.1","update":{"status":"unknown"}}`,
398 );
399 expect(yield* service.status).toMatchObject({
400 current: false,
401 installedVersion: "1.2.4-nightly.1",
402 });
403 }
404 }),
405 );
406
407 it.effect("reports an unknown version for invalid service state", () =>
408 Effect.gen(function* () {
409 const { service, fs, statePath } = yield* makeHarness();
410 yield* service.install();
411
412 for (const stateText of [
413 "{",
414 '{"activeVersion":"latest"}',
415 '{"activeVersion":"1.2"}',
416 '{"activeVersion":123}',
417 ]) {
418 yield* fs.writeFileString(statePath, stateText);
419 const status = yield* service.status;
420 expect(status.current).toBe(false);
421 expect(status.installedVersion).toBeUndefined();
422 }
423 }),
424 );
425
426 it.effect.each(["linux", "darwin"] as const)(
427 "preserves a newer version that finishes updating during stop on %s",
428 (platform) =>
429 Effect.gen(function* () {
430 const { service, fs, statePath, commands, control } = yield* makeHarness(platform);
431 const plan = yield* service.install();
432 const unit = yield* fs.readFileString(plan.unitPath);
433 control.stateAfterStop = `{"protocol":${SERVICE_LAUNCHER_PROTOCOL + 1},"activeVersion":"1.2.4"}`;
434 commands.length = 0;
435
436 const error = yield* service.install().pipe(Effect.flip);
437
438 expect(error).toMatchObject({
439 _tag: "BootServiceDowngradeRefusedError",
440 installedVersion: "1.2.4",
441 targetVersion: "1.2.3",
442 });
443 expect(yield* fs.readFileString(statePath)).toBe(control.stateAfterStop);
444 expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);
445 expect(
446 commands.filter(
447 (command) =>
448 command.startsWith(platform === "linux" ? "systemctl " : "launchctl ") &&
449 !command.includes("show-environment"),
450 ),
451 ).toEqual(
452 platform === "linux"
453 ? ["systemctl --user stop t3code.service", "systemctl --user restart t3code.service"]
454 : [
455 "launchctl bootout --wait gui/501/com.t3tools.t3code.service",
456 `launchctl bootstrap gui/501 ${plan.unitPath}`,
457 ],
458 );
459 }),
460 );
461
462 it.effect("allows an explicit downgrade", () =>
463 Effect.gen(function* () {
464 const { service, fs, statePath } = yield* makeHarness();
465 yield* service.install();
466 yield* fs.writeFileString(
467 statePath,
468 `{"protocol":${SERVICE_LAUNCHER_PROTOCOL},"activeVersion":"1.2.4"}`,
469 );
470
471 yield* service.install({ allowDowngrade: true });
472
473 expect(parseServiceState(yield* fs.readFileString(statePath))?.activeVersion).toBe("1.2.3");
474 expect((yield* service.status).current).toBe(true);
475 }),
476 );
477
478 it.effect("repairs versions with equal SemVer precedence without an override", () =>
479 Effect.gen(function* () {
480 const { service, fs, statePath } = yield* makeHarness();
481 yield* service.install();
482 yield* fs.writeFileString(
483 statePath,
484 `{"protocol":${SERVICE_LAUNCHER_PROTOCOL},"activeVersion":"1.2.3+previous-build"}`,
485 );
486
487 yield* service.install();
488
489 expect((yield* service.status).current).toBe(true);
490 }),
491 );
492
493 it.effect("install with start=false rewrites the files and marks a restart pending", () =>
494 Effect.gen(function* () {
495 const { service, fs, statePath, commands, makeService } = yield* makeHarness();
496 yield* service.install();
497 commands.length = 0;
498
499 const newer = yield* makeService(undefined, "1.2.4");
500 const plan = yield* newer.install({ start: false });
501
502 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
503 protocol: SERVICE_LAUNCHER_PROTOCOL,
504 activeVersion: "1.2.4",
505 });
506 expect(yield* fs.readFileString(plan.unitPath)).toContain("versions/1.2.4/t3");
507 expect(
508 commands.filter(
509 (command) => command.startsWith("systemctl ") && !command.includes("show-environment"),
510 ),
511 ).toEqual([]);
512 // The files say 1.2.4 but the process is still 1.2.3: not current, and
513 // the reason is named so `t3 service status` can point at restart.
514 const status = yield* newer.status;
515 expect(status.current).toBe(false);
516 expect(status.problems).toContain("restart-pending");
517
518 commands.length = 0;
519 expect(yield* newer.restart).toBe(true);
520 expect((yield* newer.status).problems).not.toContain("restart-pending");
521 expect((yield* newer.status).current).toBe(true);
522 }),
523 );
524
525 it.effect("install with start=false keeps the marker when a later write fails", () =>
526 Effect.gen(function* () {
527 const { service, fs, statePath, makeService } = yield* makeHarness();
528 const path = yield* Path.Path;
529 yield* service.install();
530 const newer = yield* makeService(undefined, "1.2.4");
531 // A non-empty directory in the unit's place: it still counts as an
532 // installed unit, and the rename that writes the new unit fails.
533 const unitPath = (yield* service.status).unitPath;
534 yield* fs.remove(unitPath);
535 yield* fs.makeDirectory(unitPath);
536 yield* fs.writeFileString(path.join(unitPath, "occupied"), "");
537
538 const error = yield* newer.install({ start: false }).pipe(Effect.flip);
539 expect(error._tag).toBe("BootServiceInstallError");
540 expect(
541 yield* fs.exists(path.join(path.dirname(statePath), SERVICE_RESTART_PENDING_FILE)),
542 ).toBe(true);
543 }),
544 );
545
546 it.effect("install with start=false refuses while a remote update is pending", () =>
547 Effect.gen(function* () {
548 const { service, fs, statePath } = yield* makeHarness();
549 yield* service.install();
550 const pendingState = JSON.stringify({
551 protocol: SERVICE_LAUNCHER_PROTOCOL,
552 activeVersion: "1.2.3",
553 update: {
554 id: "u",
555 fromVersion: "1.2.3",
556 targetVersion: "1.2.4",
557 dbPath: "/tmp/state.sqlite",
558 status: "pending",
559 },
560 });
561 yield* fs.writeFileString(statePath, pendingState);
562
563 const error = yield* service.install({ start: false }).pipe(Effect.flip);
564 expect(error._tag).toBe("BootServiceUpdatePendingError");
565 expect(yield* fs.readFileString(statePath)).toBe(pendingState);
566 }),
567 );
568
569 it.effect("pauses only this home's running service for maintenance, even when it fails", () =>
570 Effect.gen(function* () {
571 const { service, commands, control, makeService } = yield* makeHarness();
572 yield* service.install();
573 const failure = yield* service
574 .withStopped(
575 Effect.suspend(() => Effect.fail(control.active ? "running" : "repair failed")),
576 )
577 .pipe(Effect.flip);
578 expect(failure).toBe("repair failed");
579 expect(control.active).toBe(true);
580
581 // A failed stop skips the operation but still starts the service again.
582 control.failCommand = "systemctl --user stop t3code.service";
583 let ran = false;
584 const stopFailure = yield* service
585 .withStopped(
586 Effect.sync(() => {
587 ran = true;
588 }),
589 )
590 .pipe(Effect.flip);
591 expect(stopFailure).toMatchObject({
592 _tag: "BootServiceCommandError",
593 step: "stopping the installed service",
594 });
595 expect(ran).toBe(false);
596 expect(control.active).toBe(true);
597 control.failCommand = undefined;
598
599 // An enabled unit that is not active (crash-looping in auto-restart, say)
600 // is still stopped for the repair and started again afterwards.
601 control.active = false;
602 commands.length = 0;
603 yield* service.withStopped(Effect.sync(() => commands.push("repair")));
604 expect(commands).toEqual([
605 "systemctl --user is-enabled t3code.service",
606 "systemctl --user is-active t3code.service",
607 "systemctl --user stop t3code.service",
608 "repair",
609 "systemctl --user restart t3code.service",
610 ]);
611 expect(control.active).toBe(true);
612 // A running unit the user disabled is started again but stays disabled.
613 control.enabled = false;
614 yield* service.withStopped(Effect.void);
615 expect(control).toMatchObject({ active: true, enabled: false });
616 // A unit that was neither enabled nor active stays stopped.
617 control.active = false;
618 control.enabled = false;
619 commands.length = 0;
620 yield* service.withStopped(Effect.sync(() => commands.push("repair")));
621 expect(commands).toContain("systemctl --user stop t3code.service");
622 expect(commands).not.toContain("systemctl --user restart t3code.service");
623 expect(control.active).toBe(false);
624 control.enabled = true;
625 control.active = true;
626
627 const fs = yield* FileSystem.FileSystem;
628 const otherHome = yield* fs.makeTempDirectoryScoped({ prefix: "t3-doctor-other-" });
629 const other = yield* makeService(undefined, "1.2.3", otherHome);
630 commands.length = 0;
631 expect(yield* other.withStopped(Effect.sync(() => control.active))).toBe(true);
632 expect(commands).toEqual([]);
633 }),
634 );
635
636 it.effect("restart stops and starts an installed service, and is a no-op otherwise", () =>
637 Effect.gen(function* () {
638 const { service, commands } = yield* makeHarness();
639 expect(yield* service.restart).toBe(false);
640 yield* service.install();
641 commands.length = 0;
642
643 expect(yield* service.restart).toBe(true);
644 expect(
645 commands.filter(
646 (command) => command.startsWith("systemctl ") && !command.includes("show-environment"),
647 ),
648 ).toEqual([
649 "systemctl --user stop t3code.service",
650 "systemctl --user daemon-reload",
651 "systemctl --user enable t3code.service",
652 "systemctl --user restart t3code.service",
653 ]);
654 }),
655 );
656
657 it.effect("restart leaves a service that serves another T3 home alone", () =>
658 Effect.gen(function* () {
659 const { service, fs, commands, makeService } = yield* makeHarness();
660 yield* service.install();
661 commands.length = 0;
662 const path = yield* Path.Path;
663 const otherHome = yield* fs.makeTempDirectoryScoped({ prefix: "t3-other-home-" });
664
665 const other = yield* makeService(undefined, "1.2.3", path.join(otherHome, ".t3"));
666 expect(yield* other.restart).toBe(false);
667 expect(commands.filter((command) => command.startsWith("systemctl "))).toEqual([]);
668 }),
669 );
670
671 it.effect("restart brings the service back when activation fails", () =>
672 Effect.gen(function* () {
673 const { service, commands, control } = yield* makeHarness();
674 yield* service.install();
675 commands.length = 0;
676 control.failCommand = "systemctl --user daemon-reload";
677
678 const error = yield* service.restart.pipe(Effect.flip);
679 expect(error._tag).toBe("BootServiceCommandError");
680 expect(
681 commands.filter(
682 (command) => command.startsWith("systemctl ") && !command.includes("show-environment"),
683 ),
684 ).toEqual([
685 "systemctl --user stop t3code.service",
686 "systemctl --user daemon-reload",
687 "systemctl --user restart t3code.service",
688 ]);
689 }),
690 );
691
692 it.effect("restarts an installed service when repair fails", () =>
693 Effect.gen(function* () {
694 const { service, commands, control } = yield* makeHarness();
695 yield* service.install();
696 commands.length = 0;
697 control.failCommand = "systemctl --user daemon-reload";
698
699 const error = yield* service.install().pipe(Effect.flip);
700 expect(error._tag).toBe("BootServiceCommandError");
701 expect(
702 commands.filter(
703 (command) => command.startsWith("systemctl ") && !command.includes("show-environment"),
704 ),
705 ).toEqual([
706 "systemctl --user stop t3code.service",
707 "systemctl --user daemon-reload",
708 "systemctl --user restart t3code.service",
709 ]);
710 }),
711 );
712
713 it.effect("restarts without overwriting a pending remote update", () =>
714 Effect.gen(function* () {
715 const { service, fs, statePath, commands } = yield* makeHarness();
716 yield* service.install();
717 const pendingState = JSON.stringify({
718 protocol: SERVICE_LAUNCHER_PROTOCOL - 1,
719 activeVersion: "1.2.3",
720 update: {
721 id: "remote-update",
722 fromVersion: "1.2.3",
723 targetVersion: "1.2.4",
724 status: "pending",
725 },
726 });
727 yield* fs.writeFileString(statePath, pendingState);
728 for (const allowDowngrade of [false, true]) {
729 commands.length = 0;
730
731 expect((yield* service.install({ allowDowngrade }).pipe(Effect.flip))._tag).toBe(
732 "BootServiceUpdatePendingError",
733 );
734 expect(serviceStateHasPendingUpdate(yield* fs.readFileString(statePath))).toBe(true);
735 expect(
736 commands.filter(
737 (command) => command.startsWith("systemctl ") && !command.includes("show-environment"),
738 ),
739 ).toEqual([
740 "systemctl --user stop t3code.service",
741 "systemctl --user restart t3code.service",
742 ]);
743 }
744 }),
745 );
746
747 it.effect("fails closed on Windows", () =>
748 Effect.gen(function* () {
749 const { service } = yield* makeHarness("win32");
750 expect((yield* service.status).supported).toBe(false);
751 expect((yield* service.install().pipe(Effect.flip))._tag).toBe("BootServiceUnsupportedError");
752 }),
753 );
754
755 it.effect("installs, reports current state, and uninstalls on macOS", () =>
756 Effect.gen(function* () {
757 const { service, fs, statePath, commands, timeouts, runtime } = yield* makeHarness("darwin");
758 const path = yield* Path.Path;
759 const plan = yield* service.install();
760
761 expect(
762 plan.unitPath.endsWith(
763 path.join("Library", "LaunchAgents", "com.t3tools.t3code.service.plist"),
764 ),
765 ).toBe(true);
766 expect(yield* fs.readFileString(plan.unitPath)).toContain(
767 ` <key>PATH</key>\n <string>${macInstallerPath}:/usr/local/bin:/usr/sbin:/sbin</string>`,
768 );
769 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
770 protocol: SERVICE_LAUNCHER_PROTOCOL,
771 activeVersion: "1.2.3",
772 });
773 expect(yield* fs.readFileString(plan.unitPath)).toContain(
774 ` <string>${runtime.entryPath}</string>\n <string>__service-launcher</string>`,
775 );
776 expect(yield* service.status).toMatchObject({
777 current: true,
778 installedVersion: "1.2.3",
779 });
780 expect(yield* service.uninstall).toBe(true);
781 expect((yield* service.status).installed).toBe(false);
782 expect(commands.some((command) => command.startsWith("systemctl "))).toBe(false);
783 // A bootout can block up to the plist's 90s ExitTimeOut; the runner's
784 // 60s default would cancel it and let bootstrap race a loaded job.
785 expect(timeouts.get("launchctl bootout --wait gui/501/com.t3tools.t3code.service")).toEqual(
786 Duration.seconds(120),
787 );
788 }),
789 );
790
791 it.effect("restarts the launch agent when repair fails", () =>
792 Effect.gen(function* () {
793 const { service, commands, control } = yield* makeHarness("darwin");
794 yield* service.install();
795 const plistPath = (yield* service.status).unitPath;
796 commands.length = 0;
797 control.failCommand = `launchctl bootstrap gui/501 ${plistPath}`;
798
799 const error = yield* service.install().pipe(Effect.flip);
800 expect(error._tag).toBe("BootServiceCommandError");
801 expect(commands.filter((command) => command.startsWith("launchctl "))).toEqual([
802 "launchctl bootout --wait gui/501/com.t3tools.t3code.service",
803 "launchctl enable gui/501/com.t3tools.t3code.service",
804 `launchctl bootstrap gui/501 ${plistPath}`,
805 `launchctl bootstrap gui/501 ${plistPath}`,
806 ]);
807 }),
808 );
809
810 it.effect("reconstructs a launch agent search path when the installer has no PATH", () =>
811 Effect.gen(function* () {
812 const { service, fs } = yield* makeHarness("darwin", "");
813 const plan = yield* service.install();
814
815 expect(yield* fs.readFileString(plan.unitPath)).toContain(
816 " <key>PATH</key>\n <string>/usr/bin:/opt/homebrew/bin:/usr/local/bin:/bin:/usr/sbin:/sbin</string>",
817 );
818 expect((yield* service.status).current).toBe(true);
819 }),
820 );
821
822 it.effect("adds missing provider directories to a minimal installer PATH", () =>
823 Effect.gen(function* () {
824 const { service, fs } = yield* makeHarness("darwin", "/usr/bin:/bin");
825 const plan = yield* service.install();
826
827 expect(yield* fs.readFileString(plan.unitPath)).toContain(
828 " <key>PATH</key>\n <string>/usr/bin:/bin:/opt/homebrew/bin:/usr/local/bin:/usr/sbin:/sbin</string>",
829 );
830 expect((yield* service.status).current).toBe(true);
831 }),
832 );
833
834 it.effect("keeps an installed launch agent current when the process PATH changes", () =>
835 Effect.gen(function* () {
836 const { service, makeService } = yield* makeHarness("darwin");
837 yield* service.install();
838
839 const restartedService = yield* makeService("/usr/local/bin:/usr/bin:/bin");
840 expect((yield* restartedService.status).current).toBe(true);
841 }),
842 );
843
844 it.effect("drops PATH directories that cannot be represented in a launch agent plist", () =>
845 Effect.gen(function* () {
846 const { service, fs } = yield* makeHarness(
847 "darwin",
848 "/opt/homebrew/bin:/Users/theo/\u0001invalid:/usr/bin",
849 );
850 const plan = yield* service.install();
851 const plist = yield* fs.readFileString(plan.unitPath);
852
853 expect(plist).toContain(
854 " <key>PATH</key>\n <string>/opt/homebrew/bin:/usr/bin:/usr/local/bin:/bin:/usr/sbin:/sbin</string>",
855 );
856 expect(plist).not.toContain("\u0001");
857 expect((yield* service.status).current).toBe(true);
858 }),
859 );
860
861 it.effect("ignores a bootout for an agent that is not loaded", () =>
862 Effect.gen(function* () {
863 const { service, control } = yield* makeHarness("darwin");
864 yield* service.install();
865 control.failCommand = "launchctl bootout --wait gui/501/com.t3tools.t3code.service";
866
867 yield* service.install();
868 expect((yield* service.status).current).toBe(true);
869 }),
870 );
871
872 it.effect("restarts without overwriting a pending remote update on macOS", () =>
873 Effect.gen(function* () {
874 const { service, fs, statePath, commands } = yield* makeHarness("darwin");
875 yield* service.install();
876 const plistPath = (yield* service.status).unitPath;
877 const pendingState = JSON.stringify({
878 protocol: SERVICE_LAUNCHER_PROTOCOL - 1,
879 activeVersion: "1.2.3",
880 update: {
881 id: "remote-update",
882 fromVersion: "1.2.3",
883 targetVersion: "1.2.4",
884 status: "pending",
885 },
886 });
887 yield* fs.writeFileString(statePath, pendingState);
888 for (const allowDowngrade of [false, true]) {
889 commands.length = 0;
890
891 expect((yield* service.install({ allowDowngrade }).pipe(Effect.flip))._tag).toBe(
892 "BootServiceUpdatePendingError",
893 );
894 expect(serviceStateHasPendingUpdate(yield* fs.readFileString(statePath))).toBe(true);
895 expect(commands.filter((command) => command.startsWith("launchctl "))).toEqual([
896 "launchctl bootout --wait gui/501/com.t3tools.t3code.service",
897 `launchctl bootstrap gui/501 ${plistPath}`,
898 ]);
899 }
900 }),
901 );
902});