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

bootService.test.ts

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