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

bootService.test.ts

860 lines33.1 KB

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