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

bootService.test.ts

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