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

bootService.test.ts

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