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

bootService.test.ts

1,045 lines40.3 KB

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