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

bootService.test.ts

980 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(
628 Effect.suspend(() => Effect.fail(control.active ? "running" : "repair failed")),
629 )
630 .pipe(Effect.flip);
631 expect(failure).toBe("repair failed");
632 expect(control.active).toBe(true);
633​
634 control.failCommand = "systemctl --user stop t3code.service";
635 let ran = false;
636 const stopFailure = yield* service
637 .withStopped(
638 Effect.sync(() => {
639 ran = true;
640 }),
641 )
642 .pipe(Effect.flip);
643 expect(stopFailure).toMatchObject({
644 _tag: "BootServiceCommandError",
645 step: "stopping the installed service",
646 });
647 expect(ran).toBe(false);
648 expect(control.active).toBe(true);
649 control.failCommand = undefined;
650​
651 control.active = false;
652 commands.length = 0;
653 yield* service.withStopped(Effect.sync(() => commands.push("repair")));
654 expect(commands).toEqual([
655 "systemctl --user is-enabled t3code.service",
656 "systemctl --user is-active t3code.service",
657 "systemctl --user stop t3code.service",
658 "repair",
659 "systemctl --user restart t3code.service",
660 ]);
661 expect(control.active).toBe(true);
662 control.enabled = false;
663 yield* service.withStopped(Effect.void);
664 expect(control).toMatchObject({ active: true, enabled: false });
665 control.active = false;
666 control.enabled = false;
667 commands.length = 0;
668 yield* service.withStopped(Effect.sync(() => commands.push("repair")));
669 expect(commands).toContain("systemctl --user stop t3code.service");
670 expect(commands).not.toContain("systemctl --user restart t3code.service");
671 expect(control.active).toBe(false);
672 control.enabled = true;
673 control.active = true;
674​
675 const fs = yield* FileSystem.FileSystem;
676 const otherHome = yield* fs.makeTempDirectoryScoped({ prefix: "t3-doctor-other-" });
677 const other = yield* makeService(undefined, "1.2.3", otherHome);
678 commands.length = 0;
679 expect(yield* other.withStopped(Effect.sync(() => control.active))).toBe(true);
680 expect(commands).toEqual([]);
681 }),
682 );
683​
684 it.effect("restart leaves a service that serves another T3 home alone", () =>
685 Effect.gen(function* () {
686 const { service, fs, commands, makeService } = yield* makeHarness();
687 yield* service.install();
688 commands.length = 0;
689 const path = yield* Path.Path;
690 const otherHome = yield* fs.makeTempDirectoryScoped({ prefix: "t3-other-home-" });
691​
692 const other = yield* makeService(undefined, "1.2.3", path.join(otherHome, ".t3"));
693 expect(yield* other.restart).toBe("skipped");
694 expect(commands.filter((command) => command.startsWith("systemctl "))).toEqual([]);
695 }),
696 );
697​
698 it.effect("hands the whole install to systemd without changing the running service", () =>
699 Effect.gen(function* () {
700 const { fs, commands, invocations, control, makeService } = yield* makeHarness();
701 const path = yield* Path.Path;
702 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-handoff-" });
703 const baseDir = path.join(home, "T3 Data 100%", "${UNSET}", "$literal");
704 const outside = yield* makeService(undefined, "1.2.3", baseDir);
705 const plan = yield* outside.install();
706 const statePath = path.join(baseDir, "runtime", "service-state.json");
707 const state = yield* fs.readFileString(statePath);
708 const unit = yield* fs.readFileString(plan.unitPath);
709 const inside = yield* makeService(undefined, "1.2.4", baseDir, true);
710 commands.length = 0;
711 invocations.length = 0;
712​
713 const result = yield* inside.install({ allowDowngrade: true });
714​
715 expect(yield* fs.readFileString(statePath)).toBe(state);
716 expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);
717 expect(commands).not.toContain("systemctl --user stop t3code.service");
718 expect(result).toMatchObject({ handedOff: true, logPath: plan.logPath });
719 const handoffs = invocations.filter(({ command }) => command === "systemd-run");
720 expect(handoffs).toHaveLength(1);
721 expect(handoffs[0]?.args).toEqual([
722 "--user",
723 "--collect",
724 "--quiet",
725 `--property=StandardOutput=append:${plan.logPath}`,
726 `--property=StandardError=append:${plan.logPath}`,
727 "--setenv=T3_BOOT_SERVICE_UNIT=",
728 pinnedRuntimePaths(path, baseDir, "1.2.4", "linux").entryPath,
729 "service",
730 "install",
731 "--base-dir",
732 path.join(home, "T3 Data 100%", "$${UNSET}", "$$literal"),
733 "--allow-downgrade",
734 ]);
735​
736 const handoff = handoffs[0]!;
737 control.failCommand = `${handoff.command} ${handoff.args.join(" ")}`;
738 const error = yield* inside.install({ allowDowngrade: true }).pipe(Effect.flip);
739 expect(error).toMatchObject({ _tag: "BootServiceCommandError", exitCode: 1 });
740 expect(yield* fs.readFileString(statePath)).toBe(state);
741 expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);
742 expect(control.active).toBe(true);
743 expect(commands).not.toContain("systemctl --user stop t3code.service");
744 }),
745 );
746​
747 it.effect(
748 "queues an in-service restart without stopping the caller, even on handoff failure",
749 () =>
750 Effect.gen(function* () {
751 const { service, fs, statePath, commands, control, makeService } = yield* makeHarness();
752 const plan = yield* service.install();
753 const state = yield* fs.readFileString(statePath);
754 const marker = `${plan.baseDir}/runtime/${SERVICE_RESTART_PENDING_FILE}`;
755 yield* fs.writeFileString(marker, "1.2.3\n");
756 const inside = yield* makeService(undefined, "1.2.3", undefined, true);
757 commands.length = 0;
758 control.failCommand = "systemctl --user daemon-reload";
759​
760 const error = yield* inside.restart.pipe(Effect.flip);
761 expect(error).toMatchObject({ _tag: "BootServiceCommandError", exitCode: 1 });
762 expect(commands).toEqual(["systemctl --user daemon-reload"]);
763 expect(control.active).toBe(true);
764​
765 control.failCommand = undefined;
766 commands.length = 0;
767 const outcome = yield* inside.restart;
768 expect(commands).toEqual([
769 "systemctl --user daemon-reload",
770 "systemctl --user enable t3code.service",
771 "systemctl --user restart --no-block t3code.service",
772 ]);
773 expect(outcome).toBe("queued");
774 expect(yield* fs.readFileString(statePath)).toBe(state);
775 expect(yield* fs.readFileString(marker)).toBe("1.2.3\n");
776 }),
777 );
778​
779 it.effect("restarts an installed service when repair fails", () =>
780 Effect.gen(function* () {
781 const { service, commands, control } = yield* makeHarness();
782 yield* service.install();
783 commands.length = 0;
784 control.failCommand = "systemctl --user daemon-reload";
785​
786 const error = yield* service.install().pipe(Effect.flip);
787 expect(error._tag).toBe("BootServiceCommandError");
788 expect(
789 commands.filter(
790 (command) => command.startsWith("systemctl ") && !command.includes("show-environment"),
791 ),
792 ).toEqual([
793 "systemctl --user stop t3code.service",
794 "systemctl --user daemon-reload",
795 "systemctl --user restart t3code.service",
796 ]);
797 }),
798 );
799​
800 it.effect("restarts without overwriting a pending remote update", () =>
801 Effect.gen(function* () {
802 const { service, fs, statePath, commands } = yield* makeHarness();
803 yield* service.install();
804 const pendingState = JSON.stringify({
805 protocol: SERVICE_LAUNCHER_PROTOCOL - 1,
806 activeVersion: "1.2.3",
807 update: {
808 id: "remote-update",
809 fromVersion: "1.2.3",
810 targetVersion: "1.2.4",
811 status: "pending",
812 },
813 });
814 yield* fs.writeFileString(statePath, pendingState);
815 for (const allowDowngrade of [false, true]) {
816 commands.length = 0;
817​
818 expect((yield* service.install({ allowDowngrade }).pipe(Effect.flip))._tag).toBe(
819 "BootServiceUpdatePendingError",
820 );
821 expect(serviceStateHasPendingUpdate(yield* fs.readFileString(statePath))).toBe(true);
822 expect(
823 commands.filter(
824 (command) => command.startsWith("systemctl ") && !command.includes("show-environment"),
825 ),
826 ).toEqual([
827 "systemctl --user stop t3code.service",
828 "systemctl --user restart t3code.service",
829 ]);
830 }
831 }),
832 );
833​
834 it.effect("installs, reports current state, and uninstalls on macOS", () =>
835 Effect.gen(function* () {
836 const { service, fs, statePath, commands, timeouts, runtime } = yield* makeHarness("darwin");
837 const path = yield* Path.Path;
838 const plan = yield* service.install();
839​
840 expect(
841 plan.unitPath.endsWith(
842 path.join("Library", "LaunchAgents", "com.t3tools.t3code.service.plist"),
843 ),
844 ).toBe(true);
845 expect(yield* fs.readFileString(plan.unitPath)).toContain(
846 ` <key>PATH</key>\n <string>${macInstallerPath}:/usr/local/bin:/usr/sbin:/sbin</string>`,
847 );
848 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
849 protocol: SERVICE_LAUNCHER_PROTOCOL,
850 activeVersion: "1.2.3",
851 });
852 expect(yield* fs.readFileString(plan.unitPath)).toContain(
853 ` <string>${runtime.entryPath}</string>\n <string>__service-launcher</string>`,
854 );
855 expect(yield* service.status).toMatchObject({
856 current: true,
857 installedVersion: "1.2.3",
858 });
859 expect(yield* service.uninstall).toBe(true);
860 expect((yield* service.status).installed).toBe(false);
861 expect(commands.some((command) => command.startsWith("systemctl "))).toBe(false);
862 // launchd can take 90s to bootout; the runner's 60s default could let bootstrap race it.
863 expect(timeouts.get("launchctl bootout --wait gui/501/com.t3tools.t3code.service")).toEqual(
864 Duration.seconds(120),
865 );
866 }),
867 );
868​
869 // regression: #8173 keep provider CLIs available in the macOS service
870 it.effect("reconstructs a launch agent search path when the installer has no PATH", () =>
871 Effect.gen(function* () {
872 const { service, fs } = yield* makeHarness("darwin", "");
873 const plan = yield* service.install();
874​
875 expect(yield* fs.readFileString(plan.unitPath)).toContain(
876 " <key>PATH</key>\n <string>/usr/bin:/opt/homebrew/bin:/usr/local/bin:/bin:/usr/sbin:/sbin</string>",
877 );
878 expect((yield* service.status).current).toBe(true);
879 }),
880 );
881​
882 it.effect("adds missing provider directories to a minimal installer PATH", () =>
883 Effect.gen(function* () {
884 const { service, fs } = yield* makeHarness("darwin", "/usr/bin:/bin");
885 const plan = yield* service.install();
886​
887 expect(yield* fs.readFileString(plan.unitPath)).toContain(
888 " <key>PATH</key>\n <string>/usr/bin:/bin:/opt/homebrew/bin:/usr/local/bin:/usr/sbin:/sbin</string>",
889 );
890 expect((yield* service.status).current).toBe(true);
891 }),
892 );
893​
894 it.effect("keeps an installed launch agent current when the process PATH changes", () =>
895 Effect.gen(function* () {
896 const { service, makeService } = yield* makeHarness("darwin");
897 yield* service.install();
898​
899 const restartedService = yield* makeService("/usr/local/bin:/usr/bin:/bin");
900 expect((yield* restartedService.status).current).toBe(true);
901 }),
902 );
903​
904 // regression: #17532
905 it.effect("puts the runtime an update installs on the launch agent PATH", () =>
906 Effect.gen(function* () {
907 const { makeService, fs, baseDir, runtime } = yield* makeHarness("darwin");
908 const path = yield* Path.Path;
909 const previous = runtime.versionDir;
910 const installed = pinnedRuntimePaths(path, baseDir, "1.2.4", "darwin").versionDir;
911 // The 1.2.3 CLI, or the 1.2.3 service's own PATH, installs 1.2.4.
912 const updated = yield* makeService(
913 `/usr/bin:${previous}:/bin`,
914 "1.2.4",
915 undefined,
916 false,
917 runtime.entryPath,
918 );
919 const plan = yield* updated.install();
920​
921 expect(yield* fs.readFileString(plan.unitPath)).toContain(
922 ` <key>PATH</key>\n <string>/usr/bin:${installed}:/bin:/opt/homebrew/bin:/usr/local/bin:/usr/sbin:/sbin</string>`,
923 );
924 }),
925 );
926​
927 it.effect("drops PATH directories that cannot be represented in a launch agent plist", () =>
928 Effect.gen(function* () {
929 const { service, fs } = yield* makeHarness(
930 "darwin",
931 "/opt/homebrew/bin:/Users/theo/\u0001invalid:/usr/bin",
932 );
933 const plan = yield* service.install();
934 const plist = yield* fs.readFileString(plan.unitPath);
935​
936 expect(plist).toContain(
937 " <key>PATH</key>\n <string>/opt/homebrew/bin:/usr/bin:/usr/local/bin:/bin:/usr/sbin:/sbin</string>",
938 );
939 expect(plist).not.toContain("\u0001");
940 expect((yield* service.status).current).toBe(true);
941 }),
942 );
943​
944 it.effect("ignores a bootout for an agent that is not loaded", () =>
945 Effect.gen(function* () {
946 const { service, control } = yield* makeHarness("darwin");
947 yield* service.install();
948 control.failCommand = "launchctl bootout --wait gui/501/com.t3tools.t3code.service";
949​
950 yield* service.install();
951 expect((yield* service.status).current).toBe(true);
952 }),
953 );
954​
955 it.effect("keeps failed launch agent installs pending until activation succeeds", () =>
956 Effect.gen(function* () {
957 const { service, fs, statePath, commands, control } = yield* makeHarness("darwin");
958 const path = yield* Path.Path;
959 const plan = yield* service.install();
960 const markerPath = path.join(path.dirname(statePath), SERVICE_RESTART_PENDING_FILE);
961 const bootstrap = `launchctl bootstrap gui/501 ${plan.unitPath}`;
962 control.failCommand = bootstrap;
963​
964 expect((yield* service.install().pipe(Effect.flip))._tag).toBe("BootServiceCommandError");
965 expect(yield* service.status).toMatchObject({
966 current: false,
967 problems: ["restart-pending"],
968 });
969 expect(yield* fs.readFileString(markerPath)).toBe("1.2.3\n");
970​
971 control.failCommand = undefined;
972 commands.length = 0;
973 yield* service.install();
974​
975 expect(commands).toContain(bootstrap);
976 expect(yield* fs.exists(markerPath)).toBe(false);
977 expect((yield* service.status).current).toBe(true);
978 }),
979 );
980});