From 8fa6582a7fb60fb324f1a8d6e230daecc1baa32a Mon Sep 17 00:00:00 2001 From: 657kbps Date: Mon, 23 Nov 2026 02:36:40 +0800 Subject: [PATCH] fix(server): stop the macOS launch agent without bootout --wait macOS 15 rejects `launchctl bootout --wait` with a usage error, and the optional stop step ignored it, so the old job kept the label and the following bootstrap failed with EIO (exit 5). t3 update, t3 service install and t3 service restart all failed and left the old service running. Boot the agent out with a plain `launchctl bootout`, then poll `launchctl print` until the label is gone within the stop timeout. That covers both a job draining through ExitTimeOut and macOS versions without the flag. The launchd test harness now models launchctl's exit codes (64, 5, 36, 3, 113). Recorded in docs/operations/fork-changes.md: take upstream's fix once it lands. --- apps/server/src/cloud/bootService.test.ts | 162 ++++++++++++++++++++-- apps/server/src/cloud/bootService.ts | 106 ++++++++------ docs/operations/fork-changes.md | 17 +++ 3 files changed, 233 insertions(+), 52 deletions(-) diff --git a/apps/server/src/cloud/bootService.test.ts b/apps/server/src/cloud/bootService.test.ts index ad926f2b5154d..50be7c1a71f31 100644 --- a/apps/server/src/cloud/bootService.test.ts +++ b/apps/server/src/cloud/bootService.test.ts @@ -7,12 +7,15 @@ import { expect, it } from "@effect/vitest"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Clock from "effect/Clock"; import * as ConfigProvider from "effect/ConfigProvider"; +import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; +import * as TestClock from "effect/testing/TestClock"; import { CliError } from "effect/cli"; import { HttpClient } from "effect/http"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; @@ -181,6 +184,48 @@ it.each([ const macInstallerPath = "/opt/homebrew/bin:/Users/theo/.npm-global/bin:/Users/theo/.nvm/versions/node/v22.16.0/bin:/usr/bin:/bin"; +const processOutput = { + stdout: "", + stderr: "", + timedOut: false, + stdoutTruncated: false, + stderrTruncated: false, + stdoutInvalidUtf8: false, + stderrInvalidUtf8: false, +}; + +// launchctl on macOS 15: `bootout --wait` is a usage error (64) that leaves the job loaded, +// bootout of an unloaded job fails with ESRCH (3), and bootstrap over a loaded label is EIO (5). +// A booted-out job stays loaded for `exitPrints` more prints while it drains through ExitTimeOut, +// and bootout then returns EINPROGRESS (36). +interface LaunchdJob { + loaded: boolean; + exitPrints?: number; + exiting?: number | undefined; +} +const launchctl = (job: LaunchdJob, args: ReadonlyArray) => { + if (args.includes("--wait")) return 64; + switch (args[0]) { + case "bootout": + if (!job.loaded) return 3; + job.exiting = job.exitPrints ?? 0; + job.loaded = job.exiting > 0; + return job.loaded ? 36 : 0; + case "print": + if (job.exiting !== undefined && --job.exiting < 0) { + job.loaded = false; + job.exiting = undefined; + } + return job.loaded ? 0 : 113; + case "bootstrap": + if (job.loaded) return 5; + job.loaded = true; + return 0; + default: + return 0; + } +}; + const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( platform: NodeJS.Platform = "linux", installerPath = macInstallerPath, @@ -228,6 +273,9 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( launcher?: { readonly close: () => void }; /** Task Scheduler's own copy of the task. */ task?: { xml: string; enabled: boolean }; + /** launchd's model of the agent, so a bootout can be seen to unload it before bootstrap. */ + launchd: LaunchdJob | undefined; + onCommand?: (command: string) => Effect.Effect; } = { failCommand: undefined, linger: "yes", @@ -237,6 +285,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( enabled: true, active: true, startLimitHit: false, + launchd: platform === "darwin" ? { loaded: false } : undefined, }; const runner = ProcessRunner.ProcessRunner.of({ run: Effect.fn("test.run_boot_service_command")(function* ( @@ -249,20 +298,21 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( command === "systemctl --user stop t3code.service" || command === "systemctl --user disable --now t3code.service" || command === "systemctl --user restart --no-block t3code.service" || - command.startsWith("launchctl bootout --wait ") || + command.startsWith("launchctl bootout ") || (input.command === "schtasks" && input.args[0] === "/End") ) { - markersAtStop.push(yield* fs.exists(marker)); + markersAtStop.push(yield* fs.exists(marker).pipe(Effect.orDie)); } if ( command === "systemctl --user daemon-reload" || (input.command === "schtasks" && input.args[0] === "/Create") ) { - markersAtPreparation.push(yield* fs.exists(marker)); + markersAtPreparation.push(yield* fs.exists(marker).pipe(Effect.orDie)); } if (command === control.interruptCommand) return yield* Effect.interrupt; invocations.push(input); timeouts.set(command, input.timeout); + if (control.onCommand !== undefined) yield* control.onCommand(command); if (command === "systemctl --user reset-failed t3code.service") control.startLimitHit = false; const refusedStart = control.startLimitHit && command.startsWith("systemctl --user restart "); // `--no-block` only queues the job, so systemd reports success even when it refuses it. @@ -278,7 +328,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( input.command === "schtasks" && input.args[0] !== "/Create" && control.task === undefined; if (input.command === "schtasks" && !failed) { if (input.args[0] === "/Create") { - const xml = decodeServiceUnit(yield* fs.readFile(input.args[2] ?? "")); + const xml = decodeServiceUnit(yield* fs.readFile(input.args[2] ?? "").pipe(Effect.orDie)); control.task = { xml, enabled: !serviceTaskIsDisabled(xml) }; } if (control.task !== undefined && input.args[0] === "/Change") { @@ -292,15 +342,21 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( // The manager loads units only from its own unit directory. const unitOutsideManager = command === "systemctl --user enable t3code.service" && - !(yield* fs.exists(path.join(managerUnitDir, "t3code.service"))); + !(yield* fs.exists(path.join(managerUnitDir, "t3code.service")).pipe(Effect.orDie)); // A timed-out stop may still stop the service. if (command === "systemctl --user stop t3code.service") control.active = false; if ( control.stateAfterStop !== undefined && (command === "systemctl --user stop t3code.service" || - command.startsWith("launchctl bootout --wait ")) + command.startsWith("launchctl bootout ")) ) { - yield* fs.writeFileString(statePath, control.stateAfterStop); + yield* fs.writeFileString(statePath, control.stateAfterStop).pipe(Effect.orDie); + } + if (control.launchd !== undefined && input.command === "launchctl") { + return { + ...processOutput, + code: ChildProcessSpawner.ExitCode(failed ? 1 : launchctl(control.launchd, input.args)), + }; } return { stdout: @@ -352,7 +408,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( stdoutInvalidUtf8: false, stderrInvalidUtf8: false, }; - }, Effect.orDie), + }), }); const makeService = ( environmentPath: string | undefined = installerPath, @@ -924,7 +980,8 @@ it.layer(NodeServices.layer)("boot service install", (it) => { "systemctl --user restart t3code.service", ] : [ - "launchctl bootout --wait gui/501/com.t3tools.t3code.service", + "launchctl bootout gui/501/com.t3tools.t3code.service", + "launchctl print gui/501/com.t3tools.t3code.service", `launchctl bootstrap gui/501 ${plan.unitPath}`, ], ); @@ -1531,7 +1588,7 @@ process.disconnect(); expect((yield* service.status).installed).toBe(false); expect(commands.some((command) => command.startsWith("systemctl "))).toBe(false); // launchd can take 90s to bootout; the runner's 60s default could let bootstrap race it. - expect(timeouts.get("launchctl bootout --wait gui/501/com.t3tools.t3code.service")).toEqual( + expect(timeouts.get("launchctl bootout gui/501/com.t3tools.t3code.service")).toEqual( Duration.seconds(120), ); }), @@ -1756,13 +1813,96 @@ process.disconnect(); Effect.gen(function* () { const { service, control } = yield* makeHarness("darwin"); yield* service.install(); - control.failCommand = "launchctl bootout --wait gui/501/com.t3tools.t3code.service"; + control.launchd = { loaded: false }; yield* service.install(); expect((yield* service.status).current).toBe(true); }), ); + // regression: #11995 macOS 15 launchctl rejects `bootout --wait` without stopping the job + it.effect("uninstall unloads the launch agent when launchctl rejects bootout --wait", () => + Effect.gen(function* () { + const { service, control } = yield* makeHarness("darwin"); + yield* service.install(); + + expect(yield* service.uninstall).toBe(true); + expect(control.launchd?.loaded).toBe(false); + }), + ); + + it.effect("waits for a booted-out launch agent to exit before bootstrapping it again", () => + Effect.gen(function* () { + const { service, control, commands } = yield* makeHarness("darwin"); + yield* service.install(); + control.launchd = { loaded: true, exitPrints: 2 }; + // The first command after bootout is the wait's print, or a premature bootstrap. + const afterBootout = yield* Deferred.make(); + control.onCommand = (command) => + /^launchctl (print|bootstrap) /.test(command) + ? Deferred.succeed(afterBootout, undefined) + : Effect.void; + commands.length = 0; + + const reinstall = yield* service.install().pipe(Effect.forkChild); + yield* Deferred.await(afterBootout); + yield* TestClock.adjust("1 second"); + yield* Fiber.join(reinstall); + + expect(control.launchd.loaded).toBe(true); + expect(commands.filter((command) => command.startsWith("launchctl print "))).toHaveLength(3); + }), + ); + + it.effect("keeps waiting for a draining launch agent when a print times out", () => + Effect.gen(function* () { + const { service, control } = yield* makeHarness("darwin"); + yield* service.install(); + control.launchd = { loaded: true, exitPrints: 1 }; + const afterBootout = yield* Deferred.make(); + // The first print times out; a premature bootstrap also releases the clock. + control.onCommand = (command) => + Effect.gen(function* () { + if (!/^launchctl (print|bootstrap) /.test(command)) return; + const first = yield* Deferred.succeed(afterBootout, undefined); + if (first && command.startsWith("launchctl print ")) { + return yield* new ProcessRunner.ProcessTimeoutError({ + command: "launchctl", + argumentCount: 2, + timeoutMs: 5000, + }); + } + }); + + const reinstall = yield* service.install().pipe(Effect.forkChild); + yield* Deferred.await(afterBootout); + yield* TestClock.adjust("1 second"); + yield* Fiber.join(reinstall); + + expect(control.launchd.loaded).toBe(true); + }), + ); + + it.effect("keeps the launch agent installed when it is still loaded at the stop deadline", () => + Effect.gen(function* () { + const { service, control, fs } = yield* makeHarness("darwin"); + const plan = yield* service.install(); + control.launchd = { loaded: true, exitPrints: Number.POSITIVE_INFINITY }; + const polling = yield* Deferred.make(); + control.onCommand = (command) => + command.startsWith("launchctl print ") + ? Deferred.succeed(polling, undefined).pipe(Effect.asVoid) + : Effect.void; + + const uninstall = yield* service.uninstall.pipe(Effect.exit, Effect.forkChild); + yield* Deferred.await(polling); + yield* TestClock.adjust("121 seconds"); + + expect(Exit.isFailure(yield* Fiber.join(uninstall))).toBe(true); + expect(yield* fs.exists(plan.unitPath)).toBe(true); + }), + ); + it.effect("keeps failed launch agent installs pending until activation succeeds", () => Effect.gen(function* () { const { service, fs, statePath, commands, control } = yield* makeHarness("darwin"); diff --git a/apps/server/src/cloud/bootService.ts b/apps/server/src/cloud/bootService.ts index 4f81ec8641931..198e0c2f53d86 100644 --- a/apps/server/src/cloud/bootService.ts +++ b/apps/server/src/cloud/bootService.ts @@ -278,13 +278,22 @@ export type BootServiceStep = { readonly optional?: boolean; readonly timeout?: Duration.Input; } & ( - | { readonly command: string; readonly args: ReadonlyArray } + | { + readonly command: string; + readonly args: ReadonlyArray; + /** + * Then rerun `command` with these args until it runs and exits non-zero, within `timeout`. + * The step succeeds then, whatever the first command exited with. + */ + readonly waitWhile?: ReadonlyArray; + } /** A step no command can do, such as waiting for the Windows launcher to exit. */ | { readonly run: Effect.Effect } ); /** Must exceed systemd TimeoutStopSec and launchd ExitTimeOut (both 90s) to avoid shutdown races. */ const STOP_STEP_TIMEOUT = Duration.seconds(120); +const WAIT_WHILE_INTERVAL = Duration.millis(500); interface BootServiceHandoff { readonly prepare: ReadonlyArray; @@ -408,6 +417,15 @@ function launchdManager(input: { const domainTarget = `gui/${input.uid}`; const serviceTarget = `${domainTarget}/${BOOT_SERVICE_LAUNCHD_LABEL}`; // Unloaded jobs may reject bootout/enable. Bootstrap starts RunAtLoad/KeepAlive jobs; kickstart would restart them. + // bootout can return (0, or 36 EINPROGRESS) while the job drains through ExitTimeOut, and a bootstrap + // then fails EIO, so wait until `print` no longer finds the label. macOS 15 rejects `bootout --wait`. + // Not optional: an unloaded job passes the wait, and one still loaded at the deadline must stop the caller. + const bootout = { + command: "launchctl", + args: ["bootout", serviceTarget], + waitWhile: ["print", serviceTarget], + timeout: STOP_STEP_TIMEOUT, + }; return { kind: "launchd", unitPath, @@ -416,16 +434,7 @@ function launchdManager(input: { homeDir: input.homeDir, environmentPath: input.environmentPath, }), - // bootout --wait is undocumented but waits through ExitTimeOut, preventing bootstrap EIO races. - stop: [ - { - step: "stopping the installed launch agent", - command: "launchctl", - args: ["bootout", "--wait", serviceTarget], - optional: true, - timeout: STOP_STEP_TIMEOUT, - }, - ], + stop: [{ step: "stopping the installed launch agent", ...bootout }], activate: [ // A persisted `launchctl disable` override refuses bootstrap; clear it. { @@ -448,15 +457,7 @@ function launchdManager(input: { }, ], // Persisted launchctl disable overrides would block reinstall. - deactivate: [ - { - step: "stopping the service", - command: "launchctl", - args: ["bootout", "--wait", serviceTarget], - optional: true, - timeout: STOP_STEP_TIMEOUT, - }, - ], + deactivate: [{ step: "stopping the service", ...bootout }], finalize: [], }; } @@ -1089,34 +1090,57 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { ); }); + const probe = (command: string, args: ReadonlyArray) => + runner.run({ command, args, timeout: Duration.seconds(5) }).pipe(Effect.option); + const succeeded = (result: Option.Option) => + Option.isSome(result) && result.value.code === 0; + + const waitWhile = ( + entry: { readonly step: string; readonly command: string; readonly timeout?: Duration.Input }, + args: ReadonlyArray, + ) => + probe(entry.command, args).pipe( + // A probe that fails to run or times out proves nothing about the job; keep waiting. + Effect.repeat({ + while: (result) => Option.isNone(result) || result.value.code === 0, + schedule: Schedule.spaced(WAIT_WHILE_INTERVAL), + }), + Effect.timeoutOrElse({ + duration: entry.timeout ?? STOP_STEP_TIMEOUT, + orElse: () => Effect.fail(new BootServiceCommandError({ step: entry.step })), + }), + Effect.tapError(logFailure), + ); + const runSteps = (steps: ReadonlyArray) => Effect.forEach( steps, (entry) => { - const run = - "run" in entry - ? entry.run.pipe( - Effect.timeoutOrElse({ - duration: entry.timeout ?? Duration.seconds(60), - orElse: () => Effect.fail(new BootServiceCommandError({ step: entry.step })), - }), - Effect.tapError(logFailure), - ) - : runStep( - entry.step, - entry.command, - entry.args, - entry.timeout === undefined ? undefined : { timeout: entry.timeout }, - ); - return entry.optional === true ? run.pipe(Effect.ignore) : run.pipe(Effect.asVoid); + let run: Effect.Effect; + if ("run" in entry) { + run = entry.run.pipe( + Effect.timeoutOrElse({ + duration: entry.timeout ?? Duration.seconds(60), + orElse: () => Effect.fail(new BootServiceCommandError({ step: entry.step })), + }), + Effect.tapError(logFailure), + ); + } else { + const command = runStep( + entry.step, + entry.command, + entry.args, + entry.timeout === undefined ? undefined : { timeout: entry.timeout }, + ); + run = + entry.waitWhile === undefined + ? command.pipe(Effect.asVoid) + : command.pipe(Effect.ignore, Effect.andThen(waitWhile(entry, entry.waitWhile))); + } + return entry.optional === true ? run.pipe(Effect.ignore) : run; }, { discard: true }, ); - - const probe = (command: string, args: ReadonlyArray) => - runner.run({ command, args, timeout: Duration.seconds(5) }).pipe(Effect.option); - const succeeded = (result: Option.Option) => - Option.isSome(result) && result.value.code === 0; const lingerArgs = [ "show-user", ...(uid === undefined ? [] : [String(uid)]), diff --git a/docs/operations/fork-changes.md b/docs/operations/fork-changes.md index dc02ff771328f..e9d7135f4362d 100644 --- a/docs/operations/fork-changes.md +++ b/docs/operations/fork-changes.md @@ -20,6 +20,23 @@ and can drop it. `CLI_RELEASE_REPOSITORY` at `657kbps/t3code`, and `apps/server/src/cli/update.test.ts` asserts the same URL. +## Temporary fixes for upstream bugs + +A fix here exists only until upstream lands its own. When a sync finds upstream's fix, +take upstream's code for the whole change and delete the fork's version and this entry; +never re-apply the fork's code on top of it. If upstream has no fix yet, keep this one. + +- **Stopping the macOS launch agent** — upstream + [#11995](https://github.com/pingdotgg/t3code/issues/11995), fix + [PR #26088](https://github.com/pingdotgg/t3code/pull/26088). macOS 15 rejects + `launchctl bootout --wait` with a usage error (exit 64) and stops nothing, so the old job + kept the label and the following `bootstrap` failed with EIO (exit 5); `t3 update`, + `t3 service install` and `t3 service restart` all failed and left the old service + running. `apps/server/src/cloud/bootService.ts` boots the agent out with a plain + `launchctl bootout` and polls `launchctl print` until the label is gone, within the stop + timeout. The launchd tests in `apps/server/src/cloud/bootService.test.ts` model those + exit codes. When upstream merges its fix, take upstream's `bootService.ts` and tests. + ## Where it meets upstream Registering a provider touches shared files, so a sync conflicts there. Each seam keeps