@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

main
ts 1,791 lines 70.9 KB
Raw
1 import { DESKTOP_UPDATE_RESTART_MARKER_FILE } from "@t3tools/contracts";
2 // @effect-diagnostics-next-line nodeBuiltinImport:off -- Cross-process launcher contention uses real filesystem leases and IPC barriers.
3 import * as NodeChildProcess from "node:child_process";
4 import * as NodeSqlite from "node:sqlite";
5 import * as NodeServices from "@effect/platform-node/NodeServices";
6 import { expect, it } from "@effect/vitest";
7 import * as HostProcess from "@t3tools/shared/HostProcess";
8 import * as Clock from "effect/Clock";
9 import * as ConfigProvider from "effect/ConfigProvider";
10 import * as Duration from "effect/Duration";
11 import * as Effect from "effect/Effect";
12 import * as FileSystem from "effect/FileSystem";
13 import * as Fiber from "effect/Fiber";
14 import * as Layer from "effect/Layer";
15 import * as Path from "effect/Path";
16 import { CliError } from "effect/cli";
17 import { HttpClient } from "effect/http";
18 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
19 import { vi } from "vite-plus/test";
20
21 import * as ProcessRunner from "../processRunner.ts";
22 import { serviceLauncherLockPath } from "../serviceLauncher.ts";
23 import * as BootService from "./bootService.ts";
24 import { pinnedRuntimePaths } from "./pinnedRuntime.ts";
25 import {
26 decodeServiceUnit,
27 disabledServiceTask,
28 parseServiceState,
29 serviceTaskIsDisabled,
30 SERVICE_ENV_FILE,
31 SERVICE_LAUNCHER_PROTOCOL,
32 SERVICE_RESTART_PENDING_FILE,
33 serviceStateHasPendingUpdate,
34 serviceUnitLogPathOf,
35 } from "./serviceProtocol.ts";
36
37 const leaseObserver = vi.hoisted(() => ({ contended: (_destination: string) => {} }));
38 vi.mock("node:fs", async (importOriginal) => {
39 const actual = await importOriginal<typeof import("node:fs")>();
40 return {
41 ...actual,
42 renameSync: (...args: Parameters<typeof actual.renameSync>) => {
43 try {
44 return actual.renameSync(...args);
45 } catch (error) {
46 if (["EEXIST", "ENOTEMPTY"].includes((error as NodeJS.ErrnoException).code ?? "")) {
47 leaseObserver.contended(String(args[1]));
48 }
49 throw error;
50 }
51 },
52 };
53 });
54
55 const windowsTaskOptions = {
56 userId: "PC\\theo",
57 homeDir: "C:\\Users\\theo",
58 conhostPath: "C:\\Windows\\System32\\conhost.exe",
59 };
60
61 it("reads the served T3 home and log back out of a rendered unit, plist, or task", () => {
62 const plan = (baseDir: string) => ({
63 program: [`${baseDir}/runtime/versions/1.2.3/t3`, "__service-launcher"],
64 baseDir,
65 logPath: `${baseDir}/userdata/logs/boot-service.log`,
66 unitPath: "/home/theo/.config/systemd/user/t3code.service",
67 });
68
69 expect(
70 BootService.bootServiceBaseDirOf(BootService.renderBootServiceUnit(plan("/home/theo/.t3"))),
71 ).toBe("/home/theo/.t3");
72 expect(
73 BootService.bootServiceBaseDirOf(
74 BootService.renderBootServiceUnit(plan("/home/theo/T3 Data/100%")),
75 ),
76 ).toBe("/home/theo/T3 Data/100%");
77 expect(
78 serviceUnitLogPathOf(BootService.renderBootServiceUnit(plan("/home/theo/T3 Data/100%"))),
79 ).toBe("/home/theo/T3 Data/100%/userdata/logs/boot-service.log");
80 expect(
81 serviceUnitLogPathOf(
82 BootService.renderBootServicePlist(plan("/Users/theo/a&b"), {
83 homeDir: "/Users/theo",
84 environmentPath: "/usr/bin",
85 }),
86 ),
87 ).toBe("/Users/theo/a&b/userdata/logs/boot-service.log");
88 expect(
89 BootService.bootServiceBaseDirOf(
90 BootService.renderBootServicePlist(plan("/Users/theo/a&b"), {
91 homeDir: "/Users/theo",
92 environmentPath: "/usr/bin",
93 }),
94 ),
95 ).toBe("/Users/theo/a&b");
96 expect(
97 BootService.bootServiceBaseDirOf(
98 BootService.renderBootServiceTask(plan("C:\\Users\\theo\\T3 a&b\\"), windowsTaskOptions),
99 ),
100 ).toBe("C:\\Users\\theo\\T3 a&b\\");
101 expect(BootService.bootServiceBaseDirOf("[Service]\nExecStart=/x\n")).toBeUndefined();
102 });
103
104 it("protects the server unit from agents under CPU and memory pressure", () => {
105 const unit = BootService.renderBootServiceUnit({
106 program: ["/home/theo/.t3/runtime/versions/1.2.3/t3", "__service-launcher"],
107 baseDir: "/home/theo/.t3",
108 logPath: "/home/theo/.t3/userdata/logs/boot-service.log",
109 unitPath: "/home/theo/.config/systemd/user/t3code.service",
110 });
111 const service = unit.slice(unit.indexOf("[Service]"), unit.indexOf("[Install]"));
112 for (const line of [
113 "CPUWeight=1000",
114 "IOWeight=1000",
115 "MemoryLow=1536M",
116 "OOMScoreAdjust=100",
117 "OOMPolicy=continue",
118 ]) {
119 expect(service.split("\n")).toContain(line);
120 }
121 });
122
123 it.each([
124 ["a unit", "/home/theo/T3 Data/100%$x", BootService.renderBootServiceUnit],
125 [
126 "a plist",
127 "/Users/theo/a&b <c>",
128 (plan: BootService.BootServicePlan) =>
129 BootService.renderBootServicePlist(plan, { homeDir: "/Users/theo", environmentPath: "" }),
130 ],
131 [
132 "a task",
133 "C:\\Users\\theo\\T3 a&b <c>",
134 (plan: BootService.BootServicePlan) =>
135 BootService.renderBootServiceTask(plan, windowsTaskOptions),
136 ],
137 ] as const)("reads the launcher back out of %s", (_, baseDir, render) => {
138 const program = `${baseDir}/runtime/versions/1.2.3/t3`;
139 expect(
140 BootService.bootServiceProgramOf(
141 render({ program: [program, "__service-launcher"], baseDir, logPath: "/log", unitPath: "" }),
142 ),
143 ).toBe(program);
144 });
145
146 // systemd rejects a unit whose executable has a control character, quote or backslash, even quoted.
147 it.each([
148 ["a double quote", '/home/theo/T3 "Data"'],
149 ["a single quote", "/home/theo/Theo's T3"],
150 ["a backslash", "/home/theo/T3\\Data"],
151 ["a newline", "/home/theo/T3\nData"],
152 ])("renders a loadable unit, or refuses, for a T3 home with %s", (_, baseDir) => {
153 let unit: string;
154 try {
155 unit = BootService.renderBootServiceUnit({
156 program: [`${baseDir}/runtime/versions/1.2.3/t3`, "__service-launcher"],
157 baseDir,
158 logPath: `${baseDir}/userdata/logs/boot-service.log`,
159 unitPath: "/home/theo/.config/systemd/user/t3code.service",
160 });
161 } catch {
162 return;
163 }
164 for (const line of unit.split("\n")) {
165 expect(line === "" || line.startsWith("[") || line.includes("=")).toBe(true);
166 }
167 const execStart = unit.split("\n").find((line) => line.startsWith("ExecStart="));
168 const executable = execStart
169 ?.slice("ExecStart=".length)
170 .match(/^"((?:\\.|[^"\\])*)"|^(\S+)/)
171 ?.slice(1)
172 .find((group) => group !== undefined)
173 ?.replace(/\\(.)/g, "$1");
174 expect(executable).toBeDefined();
175 const unsafe = [...(executable ?? "")].filter(
176 (char) => char.charCodeAt(0) < 0x20 || `"'\\`.includes(char),
177 );
178 expect(unsafe).toEqual([]);
179 });
180
181 const macInstallerPath =
182 "/opt/homebrew/bin:/Users/theo/.npm-global/bin:/Users/theo/.nvm/versions/node/v22.16.0/bin:/usr/bin:/bin";
183
184 const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
185 platform: NodeJS.Platform = "linux",
186 installerPath = macInstallerPath,
187 xdgConfigHome?: string,
188 managerXdgConfigHome = xdgConfigHome,
189 installBinDir?: string,
190 ) {
191 const fs = yield* FileSystem.FileSystem;
192 const path = yield* Path.Path;
193 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-boot-service-test-" });
194 const managerUnitDir = path.join(
195 managerXdgConfigHome !== undefined && path.isAbsolute(managerXdgConfigHome)
196 ? managerXdgConfigHome
197 : path.join(home, ".config"),
198 "systemd",
199 "user",
200 );
201 const baseDir = path.join(home, ".t3");
202 const statePath = path.join(baseDir, "runtime", "service-state.json");
203 const runtime = pinnedRuntimePaths(path, baseDir, "1.2.3", platform);
204 yield* fs.makeDirectory(path.dirname(runtime.entryPath), { recursive: true });
205 yield* fs.writeFileString(runtime.entryPath, "#!/bin/sh\n");
206 yield* fs.writeFileString(runtime.sentinelPath, "1.2.3\n");
207
208 const markersAtStop: boolean[] = [];
209 const markersAtPreparation: boolean[] = [];
210 const commands: string[] = [];
211 const invocations: ProcessRunner.ProcessRunInput[] = [];
212 const timeouts = new Map<string, unknown>();
213 const control: {
214 failCommand: string | undefined;
215 interruptCommand?: string;
216 stateAfterStop?: string;
217 /** `undefined` makes `loginctl show-user` fail, as when logind does not know the user. */
218 linger: string | undefined;
219 managerReachable: boolean;
220 /** The user bus is found only through `XDG_RUNTIME_DIR`, as without a login session. */
221 busNeedsRuntimeDir: boolean;
222 lingerStartsManager: boolean;
223 enabled: boolean;
224 active: boolean;
225 /** systemd refuses starts until `reset-failed`, as after `StartLimitBurst` trips. */
226 startLimitHit: boolean;
227 /** A Windows launcher: it holds its lock until its task ends. */
228 launcher?: { readonly close: () => void };
229 /** Task Scheduler's own copy of the task. */
230 task?: { xml: string; enabled: boolean };
231 } = {
232 failCommand: undefined,
233 linger: "yes",
234 managerReachable: true,
235 busNeedsRuntimeDir: false,
236 lingerStartsManager: true,
237 enabled: true,
238 active: true,
239 startLimitHit: false,
240 };
241 const runner = ProcessRunner.ProcessRunner.of({
242 run: Effect.fn("test.run_boot_service_command")(function* (
243 input: ProcessRunner.ProcessRunInput,
244 ) {
245 const command = `${input.command} ${input.args.join(" ")}`;
246 commands.push(command);
247 const marker = path.join(baseDir, "runtime", DESKTOP_UPDATE_RESTART_MARKER_FILE);
248 if (
249 command === "systemctl --user stop t3code.service" ||
250 command === "systemctl --user disable --now t3code.service" ||
251 command === "systemctl --user restart --no-block t3code.service" ||
252 command.startsWith("launchctl bootout --wait ") ||
253 (input.command === "schtasks" && input.args[0] === "/End")
254 ) {
255 markersAtStop.push(yield* fs.exists(marker));
256 }
257 if (
258 command === "systemctl --user daemon-reload" ||
259 (input.command === "schtasks" && input.args[0] === "/Create")
260 ) {
261 markersAtPreparation.push(yield* fs.exists(marker));
262 }
263 if (command === control.interruptCommand) return yield* Effect.interrupt;
264 invocations.push(input);
265 timeouts.set(command, input.timeout);
266 if (command === "systemctl --user reset-failed t3code.service") control.startLimitHit = false;
267 const refusedStart = control.startLimitHit && command.startsWith("systemctl --user restart ");
268 // `--no-block` only queues the job, so systemd reports success even when it refuses it.
269 const failed =
270 command === control.failCommand ||
271 (refusedStart && command === "systemctl --user restart t3code.service");
272 if (!failed && command.startsWith("loginctl enable-linger --no-ask-password ")) {
273 control.linger = "yes";
274 control.managerReachable ||= control.lingerStartsManager;
275 }
276 if (!failed && command === "systemctl --user enable t3code.service") control.enabled = true;
277 const taskMissing =
278 input.command === "schtasks" && input.args[0] !== "/Create" && control.task === undefined;
279 if (input.command === "schtasks" && !failed) {
280 if (input.args[0] === "/Create") {
281 const xml = decodeServiceUnit(yield* fs.readFile(input.args[2] ?? ""));
282 control.task = { xml, enabled: !serviceTaskIsDisabled(xml) };
283 }
284 if (control.task !== undefined && input.args[0] === "/Change") {
285 control.task.enabled = input.args.includes("/ENABLE");
286 }
287 if (input.args[0] === "/Delete") delete control.task;
288 if (input.args[0] === "/End") control.launcher?.close();
289 }
290 if (!refusedStart && !failed && command.startsWith("systemctl --user restart "))
291 control.active = true;
292 // The manager loads units only from its own unit directory.
293 const unitOutsideManager =
294 command === "systemctl --user enable t3code.service" &&
295 !(yield* fs.exists(path.join(managerUnitDir, "t3code.service")));
296 // A timed-out stop may still stop the service.
297 if (command === "systemctl --user stop t3code.service") control.active = false;
298 if (
299 control.stateAfterStop !== undefined &&
300 (command === "systemctl --user stop t3code.service" ||
301 command.startsWith("launchctl bootout --wait "))
302 ) {
303 yield* fs.writeFileString(statePath, control.stateAfterStop);
304 }
305 return {
306 stdout:
307 input.command === "busctl"
308 ? JSON.stringify({
309 type: "as",
310 data: [
311 "/usr/lib/systemd/user",
312 `${managerUnitDir}.control`,
313 "/run/user/501/systemd/transient",
314 managerUnitDir,
315 "/etc/systemd/user",
316 ],
317 })
318 : input.args[0] === "--version"
319 ? `t3 v${/versions[\\/]([^\\/]+)[\\/]/.exec(input.command)?.[1] ?? "1.2.3"}\n`
320 : input.command === "schtasks" && input.args.includes("/XML")
321 ? control.task?.enabled === false
322 ? disabledServiceTask(control.task.xml)
323 : (control.task?.xml ?? "")
324 : input.command === "loginctl" && input.args[0] === "show-user"
325 ? `${control.linger ?? ""}\n`
326 : input.args[1] === "is-enabled"
327 ? control.enabled
328 ? "enabled\n"
329 : "disabled\n"
330 : "",
331 stderr: "",
332 code: ChildProcessSpawner.ExitCode(
333 taskMissing && input.args.includes("/HRESULT")
334 ? 0x80070002
335 : failed ||
336 taskMissing ||
337 unitOutsideManager ||
338 ((command === "systemctl --user show-environment" || input.command === "busctl") &&
339 (!control.managerReachable ||
340 (control.busNeedsRuntimeDir && input.env?.XDG_RUNTIME_DIR === undefined))) ||
341 (input.command === "loginctl" &&
342 input.args[0] === "show-user" &&
343 control.linger === undefined) ||
344 (input.args[1] === "is-active" && !control.active) ||
345 (input.args[1] === "is-enabled" && !control.enabled)
346 ? 1
347 : 0,
348 ),
349 timedOut: false,
350 stdoutTruncated: false,
351 stderrTruncated: false,
352 stdoutInvalidUtf8: false,
353 stderrInvalidUtf8: false,
354 };
355 }, Effect.orDie),
356 });
357 const makeService = (
358 environmentPath: string | undefined = installerPath,
359 cliVersion = "1.2.3",
360 serviceBaseDir = baseDir,
361 insideService = false,
362 hostExecPath = "/usr/bin/t3",
363 underSudo = false,
364 serviceInstallBinDir: string | null | undefined = installBinDir,
365 ) =>
366 Effect.gen(function* () {
367 const paths = pinnedRuntimePaths(path, serviceBaseDir, cliVersion, platform);
368 yield* fs.makeDirectory(path.dirname(paths.entryPath), { recursive: true });
369 yield* fs.writeFileString(paths.entryPath, "#!/bin/sh\n");
370 yield* fs.writeFileString(paths.sentinelPath, `${cliVersion}\n`);
371 return yield* BootService.make({
372 baseDir: serviceBaseDir,
373 logsDir: path.join(serviceBaseDir, "userdata", "logs"),
374 cliVersion,
375 host: { execPath: hostExecPath },
376 });
377 }).pipe(
378 Effect.provideService(ProcessRunner.ProcessRunner, runner),
379 Effect.provide(
380 Layer.mergeAll(
381 Layer.succeed(HostProcess.Platform, platform),
382 Layer.succeed(HostProcess.UserId, underSudo ? 0 : 501),
383 Layer.succeed(HostProcess.ExecutablePath, hostExecPath),
384 Layer.succeed(
385 HttpClient.HttpClient,
386 HttpClient.make(() => Effect.die("no release download expected")),
387 ),
388 ConfigProvider.layer(
389 ConfigProvider.fromEnv({
390 env: {
391 HOME: home,
392 ...(serviceInstallBinDir === undefined || serviceInstallBinDir === null
393 ? {}
394 : { T3CODE_INSTALL_BIN_DIR: serviceInstallBinDir }),
395 ...(xdgConfigHome === undefined ? {} : { XDG_CONFIG_HOME: xdgConfigHome }),
396 USERPROFILE: home,
397 LOCALAPPDATA: path.join(home, "AppData", "Local"),
398 USERDOMAIN: "PC",
399 USERNAME: "theo",
400 ...(environmentPath === undefined || environmentPath === ""
401 ? {}
402 : { PATH: environmentPath }),
403 ...(insideService
404 ? {
405 T3_BOOT_SERVICE_UNIT:
406 platform === "win32" ? "t3code-task.xml" : "t3code.service",
407 }
408 : {}),
409 ...(underSudo ? { SUDO_USER: "julius" } : {}),
410 },
411 }),
412 ),
413 ),
414 ),
415 );
416 const service = yield* makeService();
417 return {
418 service,
419 makeService,
420 fs,
421 home,
422 baseDir,
423 statePath,
424 commands,
425 invocations,
426 timeouts,
427 markersAtStop,
428 markersAtPreparation,
429 control,
430 runtime,
431 };
432 });
433
434 it.layer(NodeServices.layer)("boot service install", (it) => {
435 it.effect(
436 "marks immediate and deferred service restarts without blocking on a marker error",
437 () =>
438 Effect.gen(function* () {
439 const { service, fs, baseDir, control, markersAtStop, makeService } = yield* makeHarness();
440 const path = yield* Path.Path;
441 const marker = path.join(baseDir, "runtime", DESKTOP_UPDATE_RESTART_MARKER_FILE);
442 yield* service.install();
443 expect(markersAtStop).toEqual([]);
444 expect(yield* fs.exists(marker)).toBe(false);
445
446 const newer = yield* makeService(undefined, "1.2.4");
447 yield* newer.install();
448 expect(markersAtStop).toEqual([true]);
449 expect(yield* fs.exists(marker)).toBe(false);
450
451 const next = yield* makeService(undefined, "1.2.5");
452 yield* next.install({ start: false });
453 expect(markersAtStop).toEqual([true]);
454 expect(yield* fs.exists(marker)).toBe(false);
455 yield* next.restart;
456 expect(markersAtStop).toEqual([true, true]);
457 expect(yield* fs.exists(marker)).toBe(false);
458
459 control.failCommand = "systemctl --user stop t3code.service";
460 const error = yield* next.restart.pipe(Effect.flip);
461 expect(error._tag).toBe("BootServiceCommandError");
462 expect(markersAtStop).toEqual([true, true, true]);
463 expect(yield* fs.exists(marker)).toBe(false);
464
465 control.failCommand = undefined;
466 yield* fs.makeDirectory(marker);
467 expect(yield* next.restart).toBe("restarted");
468 expect((yield* fs.stat(marker)).type).toBe("Directory");
469 }),
470 );
471
472 it.effect(
473 "fails before installing files or validating a runtime when lingering needs an administrator",
474 () =>
475 Effect.gen(function* () {
476 const { service, fs, statePath, commands, control, runtime } = yield* makeHarness();
477 const before = yield* service.status;
478 control.linger = "no";
479 control.failCommand = "loginctl enable-linger --no-ask-password 501";
480 yield* fs.remove(runtime.sentinelPath);
481
482 const error = yield* service.install().pipe(Effect.flip);
483
484 expect(error).toMatchObject({
485 _tag: "BootServicePrerequisiteError",
486 problem: "linger-disabled",
487 });
488 expect(error.message).toContain('sudo loginctl enable-linger "$(id -un)"');
489 expect(error.message).toContain("last login session ends");
490 expect(yield* fs.exists(before.unitPath)).toBe(false);
491 expect(yield* fs.exists(statePath)).toBe(false);
492 expect(commands.some((command) => command.includes("--version"))).toBe(false);
493 expect(
494 commands.some(
495 (command) => command.includes("daemon-reload") || command.includes("restart"),
496 ),
497 ).toBe(false);
498 expect(yield* fs.readFileString(before.logPath)).toContain("[linger-disabled]");
499 }),
500 );
501
502 it.effect(
503 "detects a partial install and preserves the running service when repair lacks permission",
504 () =>
505 Effect.gen(function* () {
506 const { service, fs, statePath, commands, control } = yield* makeHarness();
507 const plan = yield* service.install();
508 const before = yield* fs.readFileString(statePath);
509 const unit = yield* fs.readFileString(plan.unitPath);
510 control.linger = "no";
511 control.failCommand = "loginctl enable-linger --no-ask-password 501";
512
513 expect(yield* service.status).toMatchObject({
514 current: false,
515 problems: ["linger-disabled"],
516 });
517 commands.length = 0;
518 expect((yield* service.install().pipe(Effect.flip))._tag).toBe(
519 "BootServicePrerequisiteError",
520 );
521 expect(yield* fs.readFileString(statePath)).toBe(before);
522 expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);
523 expect(commands).not.toContain("systemctl --user stop t3code.service");
524 }),
525 );
526
527 it.effect("enables lingering before installing and repairs stopped or disabled services", () =>
528 Effect.gen(function* () {
529 const { service, commands, control } = yield* makeHarness();
530 control.linger = "no";
531 yield* service.install();
532 expect(control.linger).toBe("yes");
533 expect(commands.indexOf("loginctl enable-linger --no-ask-password 501")).toBeLessThan(
534 commands.indexOf("systemctl --user daemon-reload"),
535 );
536
537 control.enabled = false;
538 control.active = false;
539 expect(yield* service.status).toMatchObject({
540 current: false,
541 problems: ["service-disabled", "service-stopped"],
542 });
543 yield* service.install();
544 expect((yield* service.status).current).toBe(true);
545 }),
546 );
547
548 // regression: #29881
549 it.effect.each([
550 { logind: "has lingering disabled", linger: "no" },
551 { logind: "does not know the user", linger: undefined },
552 ])(
553 "enables lingering to bring up an unreachable user manager when logind $logind",
554 ({ linger }) =>
555 Effect.gen(function* () {
556 const { service, commands, control } = yield* makeHarness();
557 control.linger = linger;
558 control.managerReachable = false;
559
560 yield* service.install();
561
562 expect(commands).toContain("loginctl enable-linger --no-ask-password 501");
563 expect((yield* service.status).current).toBe(true);
564 }),
565 );
566
567 it.effect("does not reach a running root user manager under sudo", () =>
568 Effect.gen(function* () {
569 const { makeService, commands, control } = yield* makeHarness();
570 control.busNeedsRuntimeDir = true;
571 const service = yield* makeService(undefined, "1.2.3", undefined, false, undefined, true);
572
573 expect(yield* service.install().pipe(Effect.flip)).toMatchObject({
574 _tag: "BootServicePrerequisiteError",
575 problem: "user-manager-unavailable",
576 });
577 expect(commands).not.toContain("systemctl --user enable t3code.service");
578 }),
579 );
580
581 it.effect("does not enable lingering for root under sudo", () =>
582 Effect.gen(function* () {
583 const { makeService, commands, control } = yield* makeHarness();
584 control.linger = undefined;
585 control.managerReachable = false;
586 const service = yield* makeService(undefined, "1.2.3", undefined, false, undefined, true);
587
588 expect(yield* service.install().pipe(Effect.flip)).toMatchObject({
589 _tag: "BootServicePrerequisiteError",
590 problem: "user-manager-unavailable",
591 });
592 expect(commands.filter((command) => command.includes("enable-linger"))).toEqual([]);
593 }),
594 );
595
596 // regression: #29881
597 it.effect("installs into the unit directory of the user manager that lingering starts", () =>
598 Effect.gen(function* () {
599 const path = yield* Path.Path;
600 const fs = yield* FileSystem.FileSystem;
601 const shellConfigHome = yield* fs.makeTempDirectoryScoped({ prefix: "t3-xdg-config-" });
602 const { makeService, home, control } = yield* makeHarness(
603 "linux",
604 undefined,
605 shellConfigHome,
606 "",
607 );
608 control.linger = "no";
609 control.managerReachable = false;
610 const service = yield* makeService();
611
612 const plan = yield* service.install();
613
614 const unitPath = path.join(home, ".config", "systemd", "user", "t3code.service");
615 expect(plan.unitPath).toBe(unitPath);
616 expect(yield* service.status).toMatchObject({ current: true, unitPath });
617 }),
618 );
619
620 // regression: #29881
621 it.effect.each([
622 { manager: "starts after three probes", upAfterPauses: 3, pauses: 3 },
623 { manager: "never starts", upAfterPauses: undefined, pauses: 10 },
624 ])(
625 "waits a bounded time for the user manager lingering starts when it $manager",
626 ({ upAfterPauses, pauses }) =>
627 Effect.gen(function* () {
628 const { service, fs, control } = yield* makeHarness();
629 const { unitPath } = yield* service.status;
630 control.linger = "no";
631 control.managerReachable = false;
632 control.lingerStartsManager = false;
633 const clock = yield* Clock.Clock;
634 const waited: number[] = [];
635
636 const result = yield* service.install().pipe(
637 Effect.provideService(Clock.Clock, {
638 ...clock,
639 sleep: (duration) =>
640 Effect.sync(() => {
641 if (waited.push(Duration.toMillis(duration)) === upAfterPauses) {
642 control.managerReachable = true;
643 }
644 }),
645 }),
646 Effect.result,
647 );
648
649 expect(waited).toEqual(Array.from({ length: pauses }, () => 500));
650 if (upAfterPauses === undefined) {
651 expect(result).toMatchObject({
652 failure: { _tag: "BootServicePrerequisiteError", problem: "user-manager-unavailable" },
653 });
654 expect(yield* fs.exists(unitPath)).toBe(false);
655 } else {
656 expect(result._tag).toBe("Success");
657 expect((yield* service.status).current).toBe(true);
658 }
659 }),
660 );
661
662 // regression: #29881
663 it.effect("points systemd user commands at the user's runtime directory when none is set", () =>
664 Effect.gen(function* () {
665 const { service, invocations, makeService } = yield* makeHarness();
666 yield* service.install();
667 const inside = yield* makeService(undefined, "1.2.4", undefined, true);
668 yield* inside.install({ allowDowngrade: true });
669
670 const systemdCalls = invocations.filter(({ command }) =>
671 ["systemctl", "busctl", "systemd-run", "loginctl"].includes(command),
672 );
673 expect(new Set(systemdCalls.map(({ command }) => command)).size).toBe(4);
674 expect(
675 systemdCalls
676 .filter(({ env }) => env?.XDG_RUNTIME_DIR !== "/run/user/501")
677 .map(({ command, args }) => `${command} ${args.join(" ")}`),
678 ).toEqual([]);
679 }),
680 );
681
682 it.effect.each([
683 { command: "systemctl --user show-environment", problem: "user-manager-unavailable" },
684 { command: "loginctl show-user 501 --property=Linger --value", problem: "linger-unavailable" },
685 ])("reports failed prerequisite probes without installing: $command", ({ command, problem }) =>
686 Effect.gen(function* () {
687 const { service, fs, statePath, control } = yield* makeHarness();
688 control.failCommand = command;
689 expect(yield* service.install().pipe(Effect.flip)).toMatchObject({
690 _tag: "BootServicePrerequisiteError",
691 problem,
692 });
693 expect(yield* fs.exists(statePath)).toBe(false);
694 }),
695 );
696
697 it.effect.each(["linux", "darwin"] as const)(
698 "preserves the custom install bin directory in the installed service on %s",
699 (platform) =>
700 Effect.gen(function* () {
701 const installBinDir = '/custom/T3\t& <100%>/"quoted"\\bin';
702 const { service, makeService, fs } = yield* makeHarness(
703 platform,
704 "",
705 undefined,
706 undefined,
707 installBinDir,
708 );
709 const plan = yield* service.install();
710 const unit = yield* fs.readFileString(plan.unitPath);
711 expect(unit).toContain(
712 platform === "linux"
713 ? 'Environment=T3CODE_INSTALL_BIN_DIR="/custom/T3\t& <100%%>/\\"quoted\\"\\\\bin"'
714 : '<key>T3CODE_INSTALL_BIN_DIR</key>\n <string>/custom/T3\t&amp; &lt;100%&gt;/"quoted"\\bin</string>',
715 );
716 expect((yield* service.status).current).toBe(true);
717
718 const ordinaryCli = yield* makeService(
719 "",
720 "1.2.3",
721 undefined,
722 false,
723 undefined,
724 false,
725 null,
726 );
727 expect((yield* ordinaryCli.status).current).toBe(true);
728 expect((yield* ordinaryCli.install()).installBinDir).toBe(installBinDir);
729 expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);
730
731 const updatedCli = yield* makeService(
732 "",
733 "1.2.4",
734 undefined,
735 false,
736 undefined,
737 false,
738 null,
739 );
740 expect((yield* updatedCli.install({ start: false })).installBinDir).toBe(installBinDir);
741 expect(yield* fs.readFileString(plan.unitPath)).toBe(unit.replaceAll("1.2.3", "1.2.4"));
742
743 const replacementCli = yield* makeService(
744 "",
745 "1.2.4",
746 undefined,
747 false,
748 undefined,
749 false,
750 "/replacement/bin",
751 );
752 expect((yield* replacementCli.status).current).toBe(false);
753 expect((yield* replacementCli.install()).installBinDir).toBe("/replacement/bin");
754 const laterCli = yield* makeService("", "1.2.4", undefined, false, undefined, false, "");
755 expect((yield* laterCli.status).current).toBe(true);
756 expect((yield* laterCli.install()).installBinDir).toBe("/replacement/bin");
757 }),
758 );
759
760 it.effect.each([
761 "unset",
762 "empty",
763 "relative",
764 "relocated",
765 "shell-only",
766 "manager-only",
767 "manager-unavailable",
768 ] as const)("installs, discovers, restarts, and uninstalls with $XDG_CONFIG_HOME %s", (setting) =>
769 Effect.gen(function* () {
770 const path = yield* Path.Path;
771 const fs = yield* FileSystem.FileSystem;
772 const configRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-xdg-config-" });
773 const xdgConfigHome = {
774 unset: undefined,
775 empty: "",
776 relative: "relative-config",
777 relocated: path.join(configRoot, "config root"),
778 "shell-only": path.join(configRoot, "config root"),
779 "manager-only": undefined,
780 "manager-unavailable": path.join(configRoot, "config root"),
781 }[setting];
782 const managerXdgConfigHome =
783 setting === "shell-only"
784 ? ""
785 : setting === "manager-only"
786 ? path.join(configRoot, "config root")
787 : undefined;
788 const { service, makeService, home, statePath, timeouts, runtime, control } =
789 yield* makeHarness("linux", undefined, xdgConfigHome, managerXdgConfigHome);
790 const unitPath = path.join(
791 setting === "relocated" || setting === "manager-only" || setting === "manager-unavailable"
792 ? path.join(configRoot, "config root")
793 : path.join(home, ".config"),
794 "systemd",
795 "user",
796 "t3code.service",
797 );
798 expect(yield* service.status).toMatchObject({ installed: false, unitPath });
799 const plan = yield* service.install();
800 expect(plan.unitPath).toBe(unitPath);
801 if (setting === "manager-unavailable") {
802 control.failCommand =
803 "busctl --user --json=short get-property org.freedesktop.systemd1 /org/freedesktop/systemd1 org.freedesktop.systemd1.Manager UnitPath";
804 }
805 const discoveredService = yield* makeService();
806
807 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
808 protocol: SERVICE_LAUNCHER_PROTOCOL,
809 activeVersion: "1.2.3",
810 });
811 expect(plan.program).toEqual([runtime.entryPath, "__service-launcher"]);
812 expect(yield* fs.readFileString(plan.unitPath)).not.toContain("T3CODE_INSTALL_BIN_DIR");
813 expect(yield* fs.readFileString(plan.unitPath)).toContain(
814 `ExecStart=${runtime.entryPath} __service-launcher`,
815 );
816 expect(yield* service.status).toMatchObject({
817 current: true,
818 installedVersion: "1.2.3",
819 });
820 expect(yield* discoveredService.status).toMatchObject({
821 installed: true,
822 current: true,
823 unitPath,
824 });
825 expect(yield* discoveredService.restart).toBe("restarted");
826 const pendingState = JSON.stringify({
827 protocol: SERVICE_LAUNCHER_PROTOCOL,
828 activeVersion: "1.2.3",
829 update: {
830 id: "u",
831 fromVersion: "1.2.3",
832 targetVersion: "1.2.4",
833 dbPath: "/tmp/state.sqlite",
834 status: "pending",
835 },
836 });
837 yield* fs.writeFileString(statePath, pendingState);
838 expect((yield* service.status).current).toBe(false);
839 expect(yield* discoveredService.uninstall).toBe(true);
840 expect(yield* fs.exists(unitPath)).toBe(false);
841 expect((yield* discoveredService.status).installed).toBe(false);
842 // systemd can take 90s to stop, exceeding the runner's 60s default.
843 expect(timeouts.get("systemctl --user disable --now t3code.service")).toEqual(
844 Duration.seconds(120),
845 );
846 }),
847 );
848
849 it.effect.each(["linux", "darwin"] as const)(
850 "reports the installed version across launcher protocols on %s",
851 (platform) =>
852 Effect.gen(function* () {
853 const { service, fs, statePath } = yield* makeHarness(platform);
854 yield* service.install();
855
856 for (const protocol of [SERVICE_LAUNCHER_PROTOCOL - 1, SERVICE_LAUNCHER_PROTOCOL + 1]) {
857 yield* fs.writeFileString(
858 statePath,
859 `{"protocol":${protocol},"activeVersion":"1.2.4-nightly.1","update":{"status":"unknown"}}`,
860 );
861 expect(yield* service.status).toMatchObject({
862 current: false,
863 installedVersion: "1.2.4-nightly.1",
864 });
865 yield* service.install({ allowDowngrade: true });
866 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
867 protocol: SERVICE_LAUNCHER_PROTOCOL,
868 activeVersion: "1.2.3",
869 });
870 }
871 }),
872 );
873
874 // regression: #5302 prevent accidental service downgrades
875 it.effect("reports an unknown version for invalid service state", () =>
876 Effect.gen(function* () {
877 const { service, fs, statePath } = yield* makeHarness();
878 yield* service.install();
879
880 for (const stateText of [
881 "{",
882 '{"activeVersion":"latest"}',
883 '{"activeVersion":"1.2"}',
884 '{"activeVersion":123}',
885 ]) {
886 yield* fs.writeFileString(statePath, stateText);
887 const status = yield* service.status;
888 expect(status.current).toBe(false);
889 expect(status.installedVersion).toBeUndefined();
890 }
891 }),
892 );
893
894 it.effect.each(["linux", "darwin"] as const)(
895 "preserves a newer version that finishes updating during stop on %s",
896 (platform) =>
897 Effect.gen(function* () {
898 const { service, fs, statePath, commands, control } = yield* makeHarness(platform);
899 const plan = yield* service.install();
900 const unit = yield* fs.readFileString(plan.unitPath);
901 control.stateAfterStop = `{"protocol":${SERVICE_LAUNCHER_PROTOCOL + 1},"activeVersion":"1.2.4"}`;
902 commands.length = 0;
903
904 const error = yield* service.install().pipe(Effect.flip);
905
906 expect(error).toMatchObject({
907 _tag: "BootServiceDowngradeRefusedError",
908 installedVersion: "1.2.4",
909 targetVersion: "1.2.3",
910 });
911 expect(yield* fs.readFileString(statePath)).toBe(control.stateAfterStop);
912 expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);
913 expect(
914 commands.filter(
915 (command) =>
916 command.startsWith(platform === "linux" ? "systemctl " : "launchctl ") &&
917 !command.includes("show-environment"),
918 ),
919 ).toEqual(
920 platform === "linux"
921 ? [
922 "systemctl --user stop t3code.service",
923 "systemctl --user reset-failed t3code.service",
924 "systemctl --user restart t3code.service",
925 ]
926 : [
927 "launchctl bootout --wait gui/501/com.t3tools.t3code.service",
928 `launchctl bootstrap gui/501 ${plan.unitPath}`,
929 ],
930 );
931 }),
932 );
933
934 // regression: #5302 prevent accidental service downgrades
935 it.effect("allows an explicit downgrade", () =>
936 Effect.gen(function* () {
937 const { service, fs, statePath } = yield* makeHarness();
938 yield* service.install();
939 yield* fs.writeFileString(
940 statePath,
941 `{"protocol":${SERVICE_LAUNCHER_PROTOCOL},"activeVersion":"1.2.4"}`,
942 );
943
944 yield* service.install({ allowDowngrade: true });
945
946 expect(parseServiceState(yield* fs.readFileString(statePath))?.activeVersion).toBe("1.2.3");
947 expect((yield* service.status).current).toBe(true);
948 }),
949 );
950
951 it.effect("repairs versions with equal SemVer precedence without an override", () =>
952 Effect.gen(function* () {
953 const { service, fs, statePath } = yield* makeHarness();
954 yield* service.install();
955 yield* fs.writeFileString(
956 statePath,
957 `{"protocol":${SERVICE_LAUNCHER_PROTOCOL},"activeVersion":"1.2.3+previous-build"}`,
958 );
959
960 yield* service.install();
961
962 expect((yield* service.status).current).toBe(true);
963 }),
964 );
965
966 it.effect.each(["linux", "darwin"] as const)(
967 "install with start=false rewrites files, preserves service.env, and marks a restart pending on %s",
968 (platform) =>
969 Effect.gen(function* () {
970 const { service, fs, baseDir, statePath, commands, makeService } =
971 yield* makeHarness(platform);
972 const path = yield* Path.Path;
973 const envPath = path.join(baseDir, SERVICE_ENV_FILE);
974 const envBytes = new TextEncoder().encode(
975 '# user configuration\r\nT3CODE_TOKEN="literal $HOME # token"',
976 );
977 yield* fs.writeFile(envPath, envBytes);
978 yield* service.install();
979 expect(new Uint8Array(yield* fs.readFile(envPath))).toEqual(envBytes);
980 yield* service.install();
981 expect(new Uint8Array(yield* fs.readFile(envPath))).toEqual(envBytes);
982 commands.length = 0;
983
984 const newer = yield* makeService(undefined, "1.2.4");
985 const plan = yield* newer.install({ start: false });
986 expect(new Uint8Array(yield* fs.readFile(envPath))).toEqual(envBytes);
987
988 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
989 protocol: SERVICE_LAUNCHER_PROTOCOL,
990 activeVersion: "1.2.4",
991 });
992 expect(yield* fs.readFileString(plan.unitPath)).toContain("versions/1.2.4/t3");
993 expect(
994 commands.filter(
995 (command) =>
996 /^(systemctl|launchctl) /.test(command) && !command.includes("show-environment"),
997 ),
998 ).toEqual([]);
999 const status = yield* newer.status;
1000 expect(status.current).toBe(false);
1001 expect(status.problems).toContain("restart-pending");
1002
1003 commands.length = 0;
1004 expect(yield* newer.restart).toBe("restarted");
1005 expect((yield* newer.status).problems).not.toContain("restart-pending");
1006 expect((yield* newer.status).current).toBe(true);
1007
1008 const latest = yield* makeService(undefined, "1.2.5");
1009 yield* latest.install({ start: true });
1010 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
1011 protocol: SERVICE_LAUNCHER_PROTOCOL,
1012 activeVersion: "1.2.5",
1013 });
1014 expect(yield* fs.readFileString(plan.unitPath)).toContain("versions/1.2.5/t3");
1015 expect((yield* latest.status).current).toBe(true);
1016 expect(
1017 yield* fs.exists(path.join(path.dirname(statePath), SERVICE_RESTART_PENDING_FILE)),
1018 ).toBe(false);
1019 }),
1020 );
1021
1022 it.effect(
1023 "serializes a local install with another process reconciling an older unit snapshot",
1024 () =>
1025 Effect.gen(function* () {
1026 const { service, fs, statePath, makeService, runtime } = yield* makeHarness();
1027 const path = yield* Path.Path;
1028 const plan = yield* service.install();
1029 const unit = yield* fs.readFileString(plan.unitPath);
1030 yield* fs.writeFileString(
1031 plan.unitPath,
1032 unit.replace("versions/1.2.3/t3", "versions/1.2.2/t3"),
1033 );
1034 yield* fs.writeFileString(
1035 statePath,
1036 JSON.stringify({
1037 protocol: SERVICE_LAUNCHER_PROTOCOL,
1038 activeVersion: "1.2.3",
1039 update: {
1040 id: "committed",
1041 fromVersion: "1.2.2",
1042 targetVersion: "1.2.3",
1043 status: "committed",
1044 },
1045 }),
1046 );
1047 const rejection = path.join(plan.baseDir, "rejected-update");
1048 const databasePath = path.join(plan.baseDir, "state.sqlite");
1049 yield* fs.writeFileString(databasePath, "database");
1050 yield* fs.writeFileString(
1051 runtime.entryPath,
1052 `#!${process.execPath}
1053 import { writeFileSync } from "node:fs";
1054 process.on("message", message => {
1055 if (message === "request-update") process.send({ type: "request-update", targetVersion: "1.2.5", dbPath: ${JSON.stringify(databasePath)} });
1056 if (message.type === "update-rejected") {
1057 writeFileSync(${JSON.stringify(rejection)}, message.reason);
1058 process.exit(0);
1059 }
1060 });
1061 `,
1062 );
1063 yield* fs.chmod(runtime.entryPath, 0o755);
1064 const newer = yield* makeService(undefined, "1.2.4");
1065 yield* makeService(undefined, "1.2.5");
1066 const snapshot = Promise.withResolvers<void>();
1067 const milestone = Promise.withResolvers<void>();
1068 const script = path.join(plan.baseDir, "launcher-contention.mjs");
1069 yield* fs.writeFileString(
1070 script,
1071 `
1072 import fs from "node:fs/promises";
1073 import cp from "node:child_process";
1074 import { syncBuiltinESMExports } from "node:module";
1075 const server = Promise.withResolvers();
1076 const originalSpawn = cp.spawn;
1077 cp.spawn = (...args) => { const child = originalSpawn(...args); server.resolve(child); return child; };
1078 process.on("message", async message => {
1079 if (message === "installed") (await server.promise).send("request-update");
1080 });
1081 const originalRead = fs.readFile;
1082 fs.readFile = async (...args) => {
1083 const contents = await originalRead(...args);
1084 if (args[0] === ${JSON.stringify(plan.unitPath)}) {
1085 fs.readFile = originalRead;
1086 syncBuiltinESMExports();
1087 const resume = new Promise(resolve => process.once("message", resolve));
1088 process.send("snapshot");
1089 await resume;
1090 }
1091 return contents;
1092 };
1093 syncBuiltinESMExports();
1094 const { Launcher, readServiceState } = await import(${JSON.stringify(import.meta.resolve("../serviceLauncher.ts"))});
1095 const launcher = new Launcher(${JSON.stringify(plan.baseDir)}, await readServiceState(${JSON.stringify(statePath)}), {
1096 serviceUnit: { path: ${JSON.stringify(plan.unitPath)}, reload: async () => {} },
1097 });
1098 try { await launcher.run(); throw Error("unexpected completion"); }
1099 catch (error) {
1100 if (!error.message.includes("Active child exited unexpectedly (0)")) throw error;
1101 }
1102 const { acquireServiceSelectionLock } = await import(${JSON.stringify(import.meta.resolve("./serviceSelectionLock.ts"))});
1103 // Exit owning the real lease, as a crashed process would.
1104 await acquireServiceSelectionLock(${JSON.stringify(plan.unitPath)});
1105 process.disconnect();
1106 `,
1107 );
1108 const child = yield* Effect.acquireRelease(
1109 Effect.sync(() =>
1110 NodeChildProcess.fork(script, [], {
1111 execArgv: [],
1112 stdio: ["ignore", "inherit", "inherit", "ipc"],
1113 }),
1114 ),
1115 (child) =>
1116 Effect.sync(() => {
1117 if (child.exitCode === null && child.signalCode === null) child.kill();
1118 }),
1119 );
1120 const exited = new Promise<void>((resolve, reject) => {
1121 child.once("error", reject);
1122 child.once("exit", (code) =>
1123 code === 0 ? resolve() : reject(new Error(`launcher exited ${code}`)),
1124 );
1125 });
1126 child.on("message", (message) => {
1127 if (message === "snapshot") snapshot.resolve();
1128 });
1129 yield* Effect.promise(() =>
1130 Promise.race([
1131 snapshot.promise,
1132 exited.then(() => {
1133 throw new Error("launcher exited before snapshot");
1134 }),
1135 ]),
1136 );
1137 leaseObserver.contended = (destination) => {
1138 if (destination === plan.unitPath + ".selection-lock") milestone.resolve();
1139 };
1140 yield* Effect.addFinalizer(() =>
1141 Effect.sync(() => {
1142 leaseObserver.contended = () => {};
1143 }),
1144 );
1145 const installing = yield* newer
1146 .install({ start: false })
1147 .pipe(Effect.ensuring(Effect.sync(() => milestone.resolve())), Effect.forkChild);
1148 // Resume the launcher once the installer contends for the unit lease, or once an
1149 // uncoordinated installer has finished, which makes the stale snapshot win.
1150 yield* Effect.promise(() => milestone.promise);
1151 child.send("resume");
1152 yield* Fiber.join(installing);
1153 child.send("installed");
1154 yield* Effect.promise(() => exited);
1155 expect(yield* fs.readFileString(rejection)).toContain("Service selection changed");
1156 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
1157 protocol: SERVICE_LAUNCHER_PROTOCOL,
1158 activeVersion: "1.2.4",
1159 });
1160 expect(yield* fs.readFileString(plan.unitPath)).toContain("versions/1.2.4/t3");
1161 expect(
1162 yield* fs.readFileString(
1163 path.join(path.dirname(statePath), SERVICE_RESTART_PENDING_FILE),
1164 ),
1165 ).toBe("1.2.4\n");
1166 // The next installer reclaims the dead owner and releases its own lease.
1167 yield* newer.install({ start: false });
1168 expect(yield* fs.exists(plan.unitPath + ".selection-lock")).toBe(false);
1169 }),
1170 );
1171
1172 it.effect("install with start=false keeps the marker when a later write fails", () =>
1173 Effect.gen(function* () {
1174 const { service, fs, statePath, makeService } = yield* makeHarness();
1175 const path = yield* Path.Path;
1176 yield* service.install();
1177 const newer = yield* makeService(undefined, "1.2.4");
1178 const unitPath = (yield* service.status).unitPath;
1179 yield* fs.remove(unitPath);
1180 yield* fs.makeDirectory(unitPath);
1181 yield* fs.writeFileString(path.join(unitPath, "occupied"), "");
1182
1183 const error = yield* newer.install({ start: false }).pipe(Effect.flip);
1184 expect(error._tag).toBe("BootServiceInstallError");
1185 expect(
1186 yield* fs.exists(path.join(path.dirname(statePath), SERVICE_RESTART_PENDING_FILE)),
1187 ).toBe(true);
1188 }),
1189 );
1190
1191 it.effect("install with start=false refuses while a remote update is pending", () =>
1192 Effect.gen(function* () {
1193 const { service, fs, statePath } = yield* makeHarness();
1194 yield* service.install();
1195 const pendingState = JSON.stringify({
1196 protocol: SERVICE_LAUNCHER_PROTOCOL,
1197 activeVersion: "1.2.3",
1198 update: {
1199 id: "u",
1200 fromVersion: "1.2.3",
1201 targetVersion: "1.2.4",
1202 dbPath: "/tmp/state.sqlite",
1203 status: "pending",
1204 },
1205 });
1206 yield* fs.writeFileString(statePath, pendingState);
1207
1208 const error = yield* service.install({ start: false }).pipe(Effect.flip);
1209 expect(error._tag).toBe("BootServiceUpdatePendingError");
1210 expect(yield* fs.readFileString(statePath)).toBe(pendingState);
1211 yield* fs.remove((yield* service.status).unitPath);
1212 expect((yield* service.install({ start: false }).pipe(Effect.flip))._tag).toBe(
1213 "BootServiceUpdatePendingError",
1214 );
1215 expect(yield* fs.readFileString(statePath)).toBe(pendingState);
1216 }),
1217 );
1218
1219 it.effect("pauses only this home's running service for maintenance, even when it fails", () =>
1220 Effect.gen(function* () {
1221 const { service, commands, control, makeService, markersAtStop } = yield* makeHarness();
1222 yield* service.install();
1223 const failure = yield* service
1224 .withStopped(Effect.failSync(() => (control.active ? "running" : "repair failed")))
1225 .pipe(Effect.flip);
1226 expect(failure).toBe("repair failed");
1227 expect(markersAtStop).toEqual([false]);
1228 expect(control.active).toBe(true);
1229
1230 control.failCommand = "systemctl --user stop t3code.service";
1231 let ran = false;
1232 const stopFailure = yield* service
1233 .withStopped(
1234 Effect.sync(() => {
1235 ran = true;
1236 }),
1237 )
1238 .pipe(Effect.flip);
1239 expect(stopFailure).toMatchObject({
1240 _tag: "BootServiceCommandError",
1241 step: "stopping the installed service",
1242 });
1243 expect(ran).toBe(false);
1244 expect(control.active).toBe(true);
1245 control.failCommand = undefined;
1246
1247 control.active = false;
1248 commands.length = 0;
1249 yield* service.withStopped(Effect.sync(() => commands.push("repair")));
1250 expect(commands).toEqual([
1251 "systemctl --user is-enabled t3code.service",
1252 "systemctl --user is-active t3code.service",
1253 "systemctl --user stop t3code.service",
1254 "repair",
1255 "systemctl --user reset-failed t3code.service",
1256 "systemctl --user restart t3code.service",
1257 ]);
1258 expect(control.active).toBe(true);
1259 control.enabled = false;
1260 yield* service.withStopped(Effect.void);
1261 expect(control).toMatchObject({ active: true, enabled: false });
1262 control.active = false;
1263 control.enabled = false;
1264 commands.length = 0;
1265 yield* service.withStopped(Effect.sync(() => commands.push("repair")));
1266 expect(commands).toContain("systemctl --user stop t3code.service");
1267 expect(commands).not.toContain("systemctl --user restart t3code.service");
1268 expect(control.active).toBe(false);
1269 control.enabled = true;
1270 control.active = true;
1271
1272 const fs = yield* FileSystem.FileSystem;
1273 const otherHome = yield* fs.makeTempDirectoryScoped({ prefix: "t3-doctor-other-" });
1274 const other = yield* makeService(undefined, "1.2.3", otherHome);
1275 commands.length = 0;
1276 expect(yield* other.withStopped(Effect.sync(() => control.active))).toBe(true);
1277 expect(commands).toEqual([]);
1278 }),
1279 );
1280
1281 it.effect("restart and install leave a service that serves another T3 home alone", () =>
1282 Effect.gen(function* () {
1283 const { service, fs, baseDir, commands, makeService } = yield* makeHarness();
1284 const plan = yield* service.install();
1285 const unit = yield* fs.readFileString(plan.unitPath);
1286 const path = yield* Path.Path;
1287 const otherHome = yield* fs.makeTempDirectoryScoped({ prefix: "t3-other-home-" });
1288
1289 const other = yield* makeService(undefined, "1.2.3", path.join(otherHome, ".t3"));
1290 commands.length = 0;
1291 expect(yield* other.restart).toBe("skipped");
1292 const refused = yield* other.install().pipe(Effect.flip);
1293 expect(refused._tag).toBe("BootServiceOtherBaseDirError");
1294 // The CLI prints a user message without a stack trace.
1295 expect(CliError.getUserMessage(refused)).toBe(refused.message);
1296 expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);
1297 expect(commands).toEqual([]);
1298 expect((yield* other.status).otherBaseDir).toBe(baseDir);
1299
1300 const quoted = yield* makeService(undefined, "1.2.3", path.join(otherHome, 'T3 "Data"'));
1301 commands.length = 0;
1302 const unloadable = yield* quoted.install().pipe(Effect.flip);
1303 expect(unloadable._tag).toBe("BootServiceBaseDirUnsupportedError");
1304 expect(CliError.getUserMessage(unloadable)).toBe(unloadable.message);
1305 expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);
1306 expect(commands).toEqual([]);
1307 }),
1308 );
1309
1310 it.effect("hands the whole install to systemd without changing the running service", () =>
1311 Effect.gen(function* () {
1312 const { fs, commands, invocations, control, makeService } = yield* makeHarness();
1313 const path = yield* Path.Path;
1314 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-handoff-" });
1315 const baseDir = path.join(home, "T3 Data 100%", "${UNSET}", "$literal");
1316 const outside = yield* makeService(undefined, "1.2.3", baseDir);
1317 const plan = yield* outside.install();
1318 const statePath = path.join(baseDir, "runtime", "service-state.json");
1319 const state = yield* fs.readFileString(statePath);
1320 const unit = yield* fs.readFileString(plan.unitPath);
1321 const inside = yield* makeService(undefined, "1.2.4", baseDir, true);
1322 commands.length = 0;
1323 invocations.length = 0;
1324
1325 const result = yield* inside.install({ allowDowngrade: true });
1326
1327 expect(yield* fs.readFileString(statePath)).toBe(state);
1328 expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);
1329 expect(commands).not.toContain("systemctl --user stop t3code.service");
1330 expect(result).toMatchObject({ handedOff: true, logPath: plan.logPath });
1331 const handoffs = invocations.filter(({ command }) => command === "systemd-run");
1332 expect(handoffs).toHaveLength(1);
1333 expect(handoffs[0]?.args).toEqual([
1334 "--user",
1335 "--collect",
1336 "--quiet",
1337 `--property=StandardOutput=append:${plan.logPath}`,
1338 `--property=StandardError=append:${plan.logPath}`,
1339 "--setenv=T3_BOOT_SERVICE_UNIT=",
1340 pinnedRuntimePaths(path, baseDir, "1.2.4", "linux").entryPath,
1341 "service",
1342 "install",
1343 "--base-dir",
1344 path.join(home, "T3 Data 100%", "$${UNSET}", "$$literal"),
1345 "--allow-downgrade",
1346 ]);
1347
1348 const handoff = handoffs[0]!;
1349 control.failCommand = `${handoff.command} ${handoff.args.join(" ")}`;
1350 const error = yield* inside.install({ allowDowngrade: true }).pipe(Effect.flip);
1351 expect(error).toMatchObject({ _tag: "BootServiceCommandError", exitCode: 1 });
1352 expect(yield* fs.readFileString(statePath)).toBe(state);
1353 expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);
1354 expect(control.active).toBe(true);
1355 expect(commands).not.toContain("systemctl --user stop t3code.service");
1356 }),
1357 );
1358
1359 it.effect(
1360 "queues an in-service restart without stopping the caller, even on handoff failure",
1361 () =>
1362 Effect.gen(function* () {
1363 const {
1364 service,
1365 fs,
1366 statePath,
1367 commands,
1368 control,
1369 makeService,
1370 markersAtStop,
1371 markersAtPreparation,
1372 } = yield* makeHarness();
1373 const plan = yield* service.install();
1374 const state = yield* fs.readFileString(statePath);
1375 const relayMarker = `${plan.baseDir}/runtime/${DESKTOP_UPDATE_RESTART_MARKER_FILE}`;
1376 const marker = `${plan.baseDir}/runtime/${SERVICE_RESTART_PENDING_FILE}`;
1377 yield* fs.writeFileString(marker, "1.2.3\n");
1378 const inside = yield* makeService(undefined, "1.2.3", undefined, true);
1379 commands.length = 0;
1380 control.failCommand = "systemctl --user daemon-reload";
1381
1382 const error = yield* inside.restart.pipe(Effect.flip);
1383 expect(error).toMatchObject({ _tag: "BootServiceCommandError", exitCode: 1 });
1384 expect(commands).toEqual(["systemctl --user daemon-reload"]);
1385 expect(control.active).toBe(true);
1386 expect(yield* fs.exists(relayMarker)).toBe(false);
1387 expect(markersAtPreparation.at(-1)).toBe(false);
1388 expect(markersAtStop).toEqual([]);
1389
1390 const queueCommand = "systemctl --user restart --no-block t3code.service";
1391 control.failCommand = queueCommand;
1392 expect((yield* inside.restart.pipe(Effect.flip))._tag).toBe("BootServiceCommandError");
1393 expect(markersAtStop).toEqual([true]);
1394 expect(yield* fs.exists(relayMarker)).toBe(false);
1395
1396 control.failCommand = undefined;
1397 control.interruptCommand = queueCommand;
1398 const interrupted = yield* inside.restart.pipe(Effect.forkScoped);
1399 expect((yield* Fiber.await(interrupted))._tag).toBe("Failure");
1400 expect(markersAtStop).toEqual([true, true]);
1401 expect(yield* fs.exists(relayMarker)).toBe(false);
1402 delete control.interruptCommand;
1403
1404 control.failCommand = undefined;
1405 commands.length = 0;
1406 const outcome = yield* inside.restart;
1407 expect(commands).toEqual([
1408 "systemctl --user daemon-reload",
1409 "systemctl --user enable t3code.service",
1410 "systemctl --user reset-failed t3code.service",
1411 "systemctl --user restart --no-block t3code.service",
1412 ]);
1413 expect(outcome).toBe("queued");
1414 expect(markersAtStop).toEqual([true, true, true]);
1415 expect(markersAtPreparation).not.toContain(true);
1416 expect(yield* fs.exists(relayMarker)).toBe(true);
1417 expect(yield* fs.readFileString(statePath)).toBe(state);
1418 expect(yield* fs.readFileString(marker)).toBe("1.2.3\n");
1419 }),
1420 );
1421
1422 // regression: #36319
1423 it.effect("starts a service whose systemd start limit tripped after repairing it", () =>
1424 Effect.gen(function* () {
1425 const { service, control, makeService } = yield* makeHarness();
1426 yield* service.install();
1427 control.active = false;
1428 control.startLimitHit = true;
1429
1430 yield* service.install();
1431 expect(control.active).toBe(true);
1432
1433 control.active = false;
1434 control.startLimitHit = true;
1435 const inside = yield* makeService(undefined, "1.2.3", undefined, true);
1436 expect(yield* inside.restart).toBe("queued");
1437 expect(control.active).toBe(true);
1438 }),
1439 );
1440
1441 it.effect("restarts an installed service when repair fails", () =>
1442 Effect.gen(function* () {
1443 const { service, commands, control } = yield* makeHarness();
1444 yield* service.install();
1445 commands.length = 0;
1446 control.failCommand = "systemctl --user daemon-reload";
1447
1448 const error = yield* service.install().pipe(Effect.flip);
1449 expect(error._tag).toBe("BootServiceCommandError");
1450 expect(
1451 commands.filter(
1452 (command) => command.startsWith("systemctl ") && !command.includes("show-environment"),
1453 ),
1454 ).toEqual([
1455 "systemctl --user stop t3code.service",
1456 "systemctl --user daemon-reload",
1457 "systemctl --user reset-failed t3code.service",
1458 "systemctl --user restart t3code.service",
1459 ]);
1460 }),
1461 );
1462
1463 it.effect("restarts without overwriting a pending remote update", () =>
1464 Effect.gen(function* () {
1465 const { service, fs, statePath, commands } = yield* makeHarness();
1466 yield* service.install();
1467 const pendingState = JSON.stringify({
1468 protocol: SERVICE_LAUNCHER_PROTOCOL - 1,
1469 activeVersion: "1.2.3",
1470 update: {
1471 id: "remote-update",
1472 fromVersion: "1.2.3",
1473 targetVersion: "1.2.4",
1474 status: "pending",
1475 },
1476 });
1477 yield* fs.writeFileString(statePath, pendingState);
1478 for (const allowDowngrade of [false, true]) {
1479 commands.length = 0;
1480
1481 expect((yield* service.install({ allowDowngrade }).pipe(Effect.flip))._tag).toBe(
1482 "BootServiceUpdatePendingError",
1483 );
1484 expect(serviceStateHasPendingUpdate(yield* fs.readFileString(statePath))).toBe(true);
1485 expect(
1486 commands.filter(
1487 (command) => command.startsWith("systemctl ") && !command.includes("show-environment"),
1488 ),
1489 ).toEqual([
1490 "systemctl --user stop t3code.service",
1491 "systemctl --user reset-failed t3code.service",
1492 "systemctl --user restart t3code.service",
1493 ]);
1494 }
1495 }),
1496 );
1497
1498 it.effect("installs, reports current state, and uninstalls on macOS", () =>
1499 Effect.gen(function* () {
1500 const { service, fs, statePath, commands, timeouts, runtime, markersAtStop } =
1501 yield* makeHarness("darwin");
1502 const path = yield* Path.Path;
1503 const plan = yield* service.install();
1504
1505 expect(
1506 plan.unitPath.endsWith(
1507 path.join("Library", "LaunchAgents", "com.t3tools.t3code.service.plist"),
1508 ),
1509 ).toBe(true);
1510 expect(yield* fs.readFileString(plan.unitPath)).toContain(
1511 ` <key>PATH</key>\n <string>${macInstallerPath}:/usr/local/bin:/usr/sbin:/sbin</string>`,
1512 );
1513 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
1514 protocol: SERVICE_LAUNCHER_PROTOCOL,
1515 activeVersion: "1.2.3",
1516 });
1517 expect(yield* fs.readFileString(plan.unitPath)).toContain(
1518 ` <string>${runtime.entryPath}</string>\n <string>__service-launcher</string>`,
1519 );
1520 expect(yield* service.status).toMatchObject({
1521 current: true,
1522 installedVersion: "1.2.3",
1523 });
1524 const relayMarker = path.join(plan.baseDir, "runtime", DESKTOP_UPDATE_RESTART_MARKER_FILE);
1525 expect(yield* service.restart).toBe("restarted");
1526 expect(markersAtStop).toEqual([true]);
1527 expect(yield* fs.exists(relayMarker)).toBe(false);
1528 expect(yield* service.uninstall).toBe(true);
1529 expect(markersAtStop).toEqual([true, false]);
1530 expect(yield* fs.exists(relayMarker)).toBe(false);
1531 expect((yield* service.status).installed).toBe(false);
1532 expect(commands.some((command) => command.startsWith("systemctl "))).toBe(false);
1533 // launchd can take 90s to bootout; the runner's 60s default could let bootstrap race it.
1534 expect(timeouts.get("launchctl bootout --wait gui/501/com.t3tools.t3code.service")).toEqual(
1535 Duration.seconds(120),
1536 );
1537 }),
1538 );
1539
1540 it.effect("installs, reports a stopped launcher, and uninstalls on Windows", () =>
1541 Effect.gen(function* () {
1542 const { service, fs, statePath, commands, control, runtime } = yield* makeHarness("win32");
1543 const path = yield* Path.Path;
1544 const plan = yield* service.install();
1545 const task = decodeServiceUnit(yield* fs.readFile(plan.unitPath));
1546
1547 expect(plan.unitPath).toBe(
1548 path.join(path.dirname(plan.baseDir), "AppData", "Local", "t3code", "t3code-task.xml"),
1549 );
1550 expect(BootService.bootServiceProgramOf(task)).toBe(runtime.entryPath);
1551 expect(BootService.bootServiceBaseDirOf(task)).toBe(plan.baseDir);
1552 expect(task).toContain("<UserId>PC\\theo</UserId>");
1553 expect(task).toContain("<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>");
1554 // schtasks decodes undeclared UTF-8 with the ANSI code page; UTF-16LE with a BOM is read as is.
1555 expect([...(yield* fs.readFile(plan.unitPath)).subarray(0, 2)]).toEqual([0xff, 0xfe]);
1556 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
1557 protocol: SERVICE_LAUNCHER_PROTOCOL,
1558 activeVersion: "1.2.3",
1559 });
1560 expect(commands.filter((command) => command.startsWith("schtasks "))).toEqual([
1561 `schtasks /Create /XML ${plan.unitPath} /TN t3code-PC-theo /F`,
1562 "schtasks /Run /TN t3code-PC-theo",
1563 ]);
1564 // No launcher holds the lock here.
1565 expect(yield* service.status).toMatchObject({
1566 installed: true,
1567 current: false,
1568 problems: ["service-stopped"],
1569 });
1570
1571 // A task that Task Scheduler refuses to delete stays installed, so a retry finds it.
1572 control.failCommand = "schtasks /Delete /TN t3code-PC-theo /F";
1573 expect((yield* service.uninstall.pipe(Effect.flip))._tag).toBe("BootServiceCommandError");
1574 expect((yield* service.status).installed).toBe(true);
1575 control.failCommand = undefined;
1576
1577 commands.length = 0;
1578 expect(yield* service.uninstall).toBe(true);
1579 expect(commands).toEqual([
1580 "schtasks /Change /TN t3code-PC-theo /DISABLE",
1581 "schtasks /End /TN t3code-PC-theo",
1582 "schtasks /Delete /TN t3code-PC-theo /F",
1583 ]);
1584 expect(control.task).toBeUndefined();
1585 expect((yield* service.status).installed).toBe(false);
1586
1587 // One removed by hand leaves nothing to disable or delete.
1588 yield* service.install();
1589 delete control.task;
1590 expect(yield* service.uninstall).toBe(true);
1591 }),
1592 );
1593
1594 it.effect("stops a Windows launcher by ending its task, and restarts one left disabled", () =>
1595 Effect.gen(function* () {
1596 const { service, commands, control, makeService } = yield* makeHarness("win32");
1597 const plan = yield* service.install();
1598 const launcher = new NodeSqlite.DatabaseSync(serviceLauncherLockPath(plan.baseDir));
1599 launcher.exec("BEGIN EXCLUSIVE");
1600 control.launcher = launcher;
1601
1602 // Task Scheduler runs its own copy of the task, so a deferred restart registers the new one.
1603 const newer = yield* makeService(undefined, "1.2.4");
1604 yield* newer.install({ start: false });
1605 const newerRuntime = pinnedRuntimePaths(yield* Path.Path, plan.baseDir, "1.2.4", "win32");
1606 expect(BootService.bootServiceProgramOf(control.task?.xml ?? "")).toBe(
1607 newerRuntime.entryPath,
1608 );
1609 expect(control.task?.enabled).toBe(true);
1610
1611 // An interrupted stop disables the task and leaves its launcher running.
1612 yield* service.install({ start: false, allowDowngrade: true });
1613 control.task = { xml: control.task?.xml ?? "", enabled: false };
1614 yield* newer.install({ start: false });
1615 expect(control.task).toMatchObject({ enabled: false });
1616 expect(BootService.bootServiceProgramOf(control.task.xml)).toBe(newerRuntime.entryPath);
1617 expect((yield* service.status).problems).toEqual(["service-disabled", "restart-pending"]);
1618
1619 commands.length = 0;
1620 yield* service.withStopped(Effect.sync(() => commands.push("repair")));
1621 expect(commands.filter((command) => !command.includes("/Query"))).toEqual([
1622 "schtasks /Change /TN t3code-PC-theo /DISABLE",
1623 "schtasks /End /TN t3code-PC-theo",
1624 "repair",
1625 "schtasks /Change /TN t3code-PC-theo /ENABLE",
1626 "schtasks /Run /TN t3code-PC-theo",
1627 ]);
1628 }),
1629 );
1630
1631 it.effect("hands an in-service install and restart to Task Scheduler on Windows", () =>
1632 Effect.gen(function* () {
1633 const {
1634 service,
1635 fs,
1636 statePath,
1637 commands,
1638 control,
1639 makeService,
1640 markersAtStop,
1641 markersAtPreparation,
1642 } = yield* makeHarness("win32");
1643 const plan = yield* service.install();
1644 const inside = yield* makeService(undefined, "1.2.4", undefined, true);
1645 const relayMarker = `${plan.baseDir}/runtime/${DESKTOP_UPDATE_RESTART_MARKER_FILE}`;
1646 const handoff = [
1647 `schtasks /Create /XML ${plan.unitPath} /TN t3code-PC-theo /F`,
1648 "schtasks /End /TN t3code-PC-theo",
1649 "schtasks /Run /TN t3code-PC-theo",
1650 ];
1651 commands.length = 0;
1652
1653 expect(yield* inside.install()).toMatchObject({ handedOff: true, logPath: plan.logPath });
1654 expect(commands.filter((command) => command.startsWith("schtasks "))).toEqual(handoff);
1655 expect(parseServiceState(yield* fs.readFileString(statePath))?.activeVersion).toBe("1.2.4");
1656 expect(
1657 yield* fs.readFileString(`${plan.baseDir}/runtime/${SERVICE_RESTART_PENDING_FILE}`),
1658 ).toBe("1.2.4\n");
1659
1660 expect(markersAtStop).toEqual([true]);
1661 expect(yield* fs.exists(relayMarker)).toBe(true);
1662 yield* fs.remove(relayMarker);
1663
1664 commands.length = 0;
1665 expect(yield* inside.restart).toBe("queued");
1666 expect(commands).toEqual(handoff);
1667 expect(markersAtStop).toEqual([true, true]);
1668 expect(yield* fs.exists(relayMarker)).toBe(true);
1669 yield* fs.remove(relayMarker);
1670
1671 expect(markersAtPreparation).not.toContain(true);
1672 control.failCommand = handoff[0];
1673 expect((yield* inside.restart.pipe(Effect.flip))._tag).toBe("BootServiceCommandError");
1674 expect(yield* fs.exists(relayMarker)).toBe(false);
1675 expect(markersAtPreparation.at(-1)).toBe(false);
1676 expect(markersAtStop).toEqual([true, true]);
1677 }),
1678 );
1679
1680 // regression: #8173 keep provider CLIs available in the macOS service
1681 it.effect("reconstructs a launch agent search path when the installer has no PATH", () =>
1682 Effect.gen(function* () {
1683 const { service, fs } = yield* makeHarness("darwin", "");
1684 const plan = yield* service.install();
1685
1686 expect(yield* fs.readFileString(plan.unitPath)).toContain(
1687 " <key>PATH</key>\n <string>/usr/bin:/opt/homebrew/bin:/usr/local/bin:/bin:/usr/sbin:/sbin</string>",
1688 );
1689 expect((yield* service.status).current).toBe(true);
1690 }),
1691 );
1692
1693 it.effect("adds missing provider directories to a minimal installer PATH", () =>
1694 Effect.gen(function* () {
1695 const { service, fs } = yield* makeHarness("darwin", "/usr/bin:/bin");
1696 const plan = yield* service.install();
1697
1698 expect(yield* fs.readFileString(plan.unitPath)).toContain(
1699 " <key>PATH</key>\n <string>/usr/bin:/bin:/opt/homebrew/bin:/usr/local/bin:/usr/sbin:/sbin</string>",
1700 );
1701 expect((yield* service.status).current).toBe(true);
1702 }),
1703 );
1704
1705 it.effect("keeps an installed launch agent current when the process PATH changes", () =>
1706 Effect.gen(function* () {
1707 const { service, makeService } = yield* makeHarness("darwin");
1708 yield* service.install();
1709
1710 const restartedService = yield* makeService("/usr/local/bin:/usr/bin:/bin");
1711 expect((yield* restartedService.status).current).toBe(true);
1712 }),
1713 );
1714
1715 // regression: #17532
1716 it.effect("puts the runtime an update installs on the launch agent PATH", () =>
1717 Effect.gen(function* () {
1718 const { makeService, fs, baseDir, runtime } = yield* makeHarness("darwin");
1719 const path = yield* Path.Path;
1720 const previous = runtime.versionDir;
1721 const installed = pinnedRuntimePaths(path, baseDir, "1.2.4", "darwin").versionDir;
1722 // The 1.2.3 CLI, or the 1.2.3 service's own PATH, installs 1.2.4.
1723 const updated = yield* makeService(
1724 `/usr/bin:${previous}:/bin`,
1725 "1.2.4",
1726 undefined,
1727 false,
1728 runtime.entryPath,
1729 );
1730 const plan = yield* updated.install();
1731
1732 expect(yield* fs.readFileString(plan.unitPath)).toContain(
1733 ` <key>PATH</key>\n <string>/usr/bin:${installed}:/bin:/opt/homebrew/bin:/usr/local/bin:/usr/sbin:/sbin</string>`,
1734 );
1735 }),
1736 );
1737
1738 it.effect("drops PATH directories that cannot be represented in a launch agent plist", () =>
1739 Effect.gen(function* () {
1740 const { service, fs } = yield* makeHarness(
1741 "darwin",
1742 "/opt/homebrew/bin:/Users/theo/\u0001invalid:/usr/bin",
1743 );
1744 const plan = yield* service.install();
1745 const plist = yield* fs.readFileString(plan.unitPath);
1746
1747 expect(plist).toContain(
1748 " <key>PATH</key>\n <string>/opt/homebrew/bin:/usr/bin:/usr/local/bin:/bin:/usr/sbin:/sbin</string>",
1749 );
1750 expect(plist).not.toContain("\u0001");
1751 expect((yield* service.status).current).toBe(true);
1752 }),
1753 );
1754
1755 it.effect("ignores a bootout for an agent that is not loaded", () =>
1756 Effect.gen(function* () {
1757 const { service, control } = yield* makeHarness("darwin");
1758 yield* service.install();
1759 control.failCommand = "launchctl bootout --wait gui/501/com.t3tools.t3code.service";
1760
1761 yield* service.install();
1762 expect((yield* service.status).current).toBe(true);
1763 }),
1764 );
1765
1766 it.effect("keeps failed launch agent installs pending until activation succeeds", () =>
1767 Effect.gen(function* () {
1768 const { service, fs, statePath, commands, control } = yield* makeHarness("darwin");
1769 const path = yield* Path.Path;
1770 const plan = yield* service.install();
1771 const markerPath = path.join(path.dirname(statePath), SERVICE_RESTART_PENDING_FILE);
1772 const bootstrap = `launchctl bootstrap gui/501 ${plan.unitPath}`;
1773 control.failCommand = bootstrap;
1774
1775 expect((yield* service.install().pipe(Effect.flip))._tag).toBe("BootServiceCommandError");
1776 expect(yield* service.status).toMatchObject({
1777 current: false,
1778 problems: ["restart-pending"],
1779 });
1780 expect(yield* fs.readFileString(markerPath)).toBe("1.2.3\n");
1781
1782 control.failCommand = undefined;
1783 commands.length = 0;
1784 yield* service.install();
1785
1786 expect(commands).toContain(bootstrap);
1787 expect(yield* fs.exists(markerPath)).toBe(false);
1788 expect((yield* service.status).current).toBe(true);
1789 }),
1790 );
1791 });