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

bootService.test.ts

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