Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
feat(server): run the background service on macOS via launchd (#6286)
Theo Browne2aa5f095fc3b
diff --git a/apps/server/src/cli/connect.ts b/apps/server/src/cli/connect.tsindex f330e62a5..74f469364 100644--- a/apps/server/src/cli/connect.ts+++ b/apps/server/src/cli/connect.ts@@ -5,6 +5,7 @@ import {type RelayClientInstallProgressStage,} from "@t3tools/contracts";import { RelayOkResponse } from "@t3tools/contracts/relay";+import { HostProcessPlatform } from "@t3tools/shared/hostProcess";import * as RelayClient from "@t3tools/shared/relayClient";import { withRelayClientTracing } from "@t3tools/shared/relayTracing";import * as Cause from "effect/Cause";@@ -695,8 +696,11 @@ export const connectCommand = Command.make("connect", {// fail the command, just tell the user what happened and move on.const background = yield* recoverServiceOnboardingOffer(offerServiceDuringOnboarding);if (background) {+ const platform = yield* HostProcessPlatform;yield* Console.log(- "\n✓ Background service ready\n\nT3 Code will stay reachable after you log out.",+ platform === "darwin"+ ? "\n✓ Background service ready\n\nT3 Code will stay reachable while you are logged in to this Mac."+ : "\n✓ Background service ready\n\nT3 Code will stay reachable after you log out.",);return;}diff --git a/apps/server/src/cli/service.test.ts b/apps/server/src/cli/service.test.tsindex e91e10000..08980faf7 100644--- a/apps/server/src/cli/service.test.ts+++ b/apps/server/src/cli/service.test.ts@@ -29,9 +29,9 @@ it("gives a direct repair command for a stale service", () => {);});-it("explains service availability without systemd", () => {+it("explains where the service is supported", () => {assert.include(formatServiceStatus({ ...status, supported: false, installed: false }, "0.0.29"),- "Supported on: Linux with systemd",+ "Supported on: Linux with systemd, macOS with launchd",);});diff --git a/apps/server/src/cli/service.ts b/apps/server/src/cli/service.tsindex d55b270f1..74d220610 100644--- a/apps/server/src/cli/service.ts+++ b/apps/server/src/cli/service.ts@@ -1,3 +1,4 @@+import { HostProcessPlatform } from "@t3tools/shared/hostProcess";import * as Console from "effect/Console";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";@@ -48,7 +49,7 @@ export function formatServiceStatus(cliVersion: string,): string {if (!status.supported) {- return "T3 Code service\n Status: unavailable on this machine\n Supported on: Linux with systemd";+ return "T3 Code service\n Status: unavailable on this machine\n Supported on: Linux with systemd, macOS with launchd";}if (!status.installed) {return "T3 Code service\n Status: not installed\n Next: Run `t3 service install`.";@@ -152,12 +153,18 @@ export const offerServiceDuringOnboarding = Effect.gen(function* () {yield* Console.log("T3 Code is already set up to run in the background on this machine.");return true;}+ // A LaunchAgent starts at login and dies at logout; there is no+ // enable-linger equivalent on macOS. Do not promise more than that.+ const platform = yield* HostProcessPlatform;const wanted = yield* Prompt.run(Prompt.confirm({message: installed? "The installed T3 Code service needs an update or repair. Update it now?"- : "Run T3 Code in the background whenever this machine boots? " +- "It stays reachable through T3 Connect even after you log out.",+ : platform === "darwin"+ ? "Run T3 Code in the background whenever you log in to this Mac? " ++ "It stays reachable through T3 Connect while you are logged in."+ : "Run T3 Code in the background whenever this machine boots? " ++ "It stays reachable through T3 Connect even after you log out.",initial: true,}),);diff --git a/apps/server/src/cloud/bootService.test.ts b/apps/server/src/cloud/bootService.test.tsindex 55d72bc66..1314ccfb9 100644--- a/apps/server/src/cloud/bootService.test.ts+++ b/apps/server/src/cloud/bootService.test.ts@@ -4,8 +4,10 @@ import {HostProcessArguments,HostProcessExecutablePath,HostProcessPlatform,+ HostProcessUserId,} from "@t3tools/shared/hostProcess";import * as ConfigProvider from "effect/ConfigProvider";+import * as Duration from "effect/Duration";import * as Effect from "effect/Effect";import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";@@ -47,6 +49,51 @@ it("survives the kernel OOM-killing a greedy agent child", () => {expect(unit).toContain("OOMPolicy=continue");});+const macPlan = {+ nodePath: "/opt/homebrew/bin/node",+ launcherPath: "/Users/theo/.t3/runtime/service-launcher.mjs",+ baseDir: "/Users/theo/.t3",+ logPath: "/Users/theo/.t3/userdata/logs/boot-service.log",+ unitPath: "/Users/theo/Library/LaunchAgents/com.t3tools.t3code.service.plist",+};++it("keeps launchd pinned to the stable launcher rather than a versioned server", () => {+ const plist = BootService.renderBootServicePlist(macPlan, { homeDir: "/Users/theo" });++ expect(plist).toContain("<string>/opt/homebrew/bin/node</string>");+ expect(plist).toContain("<string>/Users/theo/.t3/runtime/service-launcher.mjs</string>");+ expect(plist).not.toContain("versions/1.2.3");+});++it("restarts the launch agent on the systemd cadence", () => {+ const plist = BootService.renderBootServicePlist(macPlan, { homeDir: "/Users/theo" });++ expect(plist).toContain("<key>RunAtLoad</key>\n <true/>");+ expect(plist).toContain("<key>KeepAlive</key>\n <true/>");+ expect(plist).toContain("<key>ThrottleInterval</key>\n <integer>5</integer>");+ expect(plist).toContain("<key>ExitTimeOut</key>\n <integer>90</integer>");+});++it("appends both stdio streams to the boot service log", () => {+ const plist = BootService.renderBootServicePlist(macPlan, { homeDir: "/Users/theo" });++ expect(plist).toContain(+ "<key>StandardOutPath</key>\n <string>/Users/theo/.t3/userdata/logs/boot-service.log</string>",+ );+ expect(plist).toContain(+ "<key>StandardErrorPath</key>\n <string>/Users/theo/.t3/userdata/logs/boot-service.log</string>",+ );+});++it("escapes XML in host paths", () => {+ const plist = BootService.renderBootServicePlist(+ { ...macPlan, baseDir: "/Users/theo/T3 & <Co>" },+ { homeDir: "/Users/theo" },+ );++ expect(plist).toContain("<string>/Users/theo/T3 & <Co></string>");+});+const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (platform: NodeJS.Platform = "linux",usePinnedLauncher = false,@@ -68,12 +115,14 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (yield* fs.writeFileString(runtime.sentinelPath, "1.2.3\n");const commands: string[] = [];+ const timeouts = new Map<string, unknown>();const control: { failCommand: string | undefined } = { failCommand: undefined };const runner = ProcessRunner.ProcessRunner.of({run: (input) =>Effect.sync(() => {const command = `${input.command} ${input.args.join(" ")}`;commands.push(command);+ timeouts.set(command, input.timeout);return {stdout: input.args[1] === "--version" ? "t3 v1.2.3\n" : "",stderr: "",@@ -99,19 +148,20 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (Effect.provide(Layer.mergeAll(Layer.succeed(HostProcessPlatform, platform),+ Layer.succeed(HostProcessUserId, 501),Layer.succeed(HostProcessExecutablePath, "/usr/bin/node"),Layer.succeed(HostProcessArguments, ["/usr/bin/node", path.join(home, "bin.mjs")]),ConfigProvider.layer(ConfigProvider.fromEnv({ env: { HOME: home } })),),),);- return { service, fs, statePath, commands, control };+ return { service, fs, statePath, commands, timeouts, control };});it.layer(NodeServices.layer)("boot service install", (it) => {it.effect("installs, reports current state, and uninstalls", () =>Effect.gen(function* () {- const { service, fs, statePath, commands } = yield* makeHarness();+ const { service, fs, statePath, commands, timeouts } = yield* makeHarness();const plan = yield* service.install;expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({@@ -137,6 +187,11 @@ it.layer(NodeServices.layer)("boot service install", (it) => {expect(yield* service.uninstall).toBe(true);expect((yield* service.status).installed).toBe(false);expect(commands.some((command) => command.startsWith("npm "))).toBe(false);+ // The stop can block up to systemd's 90s TimeoutStopSec; the runner's+ // 60s default would cancel it mid-shutdown.+ expect(timeouts.get("systemctl --user disable --now t3code.service")).toEqual(+ Duration.seconds(120),+ );}),);@@ -195,11 +250,95 @@ it.layer(NodeServices.layer)("boot service install", (it) => {}),);- it.effect("fails closed off Linux", () =>+ it.effect("fails closed on Windows", () =>Effect.gen(function* () {- const { service } = yield* makeHarness("darwin");+ const { service } = yield* makeHarness("win32");expect((yield* service.status).supported).toBe(false);expect((yield* service.install.pipe(Effect.flip))._tag).toBe("BootServiceUnsupportedError");}),);++ it.effect("installs, reports current state, and uninstalls on macOS", () =>+ Effect.gen(function* () {+ const { service, fs, statePath, commands, timeouts } = yield* makeHarness("darwin");+ const plan = yield* service.install;++ expect(plan.unitPath.endsWith("Library/LaunchAgents/com.t3tools.t3code.service.plist")).toBe(+ true,+ );+ expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({+ protocol: SERVICE_LAUNCHER_PROTOCOL,+ activeVersion: "1.2.3",+ });+ expect(yield* fs.readFileString(plan.launcherPath)).toBe("export {};\n");+ expect((yield* service.status).current).toBe(true);+ expect(yield* service.uninstall).toBe(true);+ expect((yield* service.status).installed).toBe(false);+ expect(commands.some((command) => command.startsWith("npm "))).toBe(false);+ expect(commands.some((command) => command.startsWith("systemctl "))).toBe(false);+ // A bootout can block up to the plist's 90s ExitTimeOut; the runner's+ // 60s default would cancel it and let bootstrap race a loaded job.+ expect(timeouts.get("launchctl bootout --wait gui/501/com.t3tools.t3code.service")).toEqual(+ Duration.seconds(120),+ );+ }),+ );++ it.effect("restarts the launch agent when repair fails", () =>+ Effect.gen(function* () {+ const { service, commands, control } = yield* makeHarness("darwin");+ yield* service.install;+ const plistPath = (yield* service.status).unitPath;+ commands.length = 0;+ control.failCommand = `launchctl bootstrap gui/501 ${plistPath}`;++ const error = yield* service.install.pipe(Effect.flip);+ expect(error._tag).toBe("BootServiceCommandError");+ expect(commands.filter((command) => command.startsWith("launchctl "))).toEqual([+ "launchctl bootout --wait gui/501/com.t3tools.t3code.service",+ "launchctl enable gui/501/com.t3tools.t3code.service",+ `launchctl bootstrap gui/501 ${plistPath}`,+ `launchctl bootstrap gui/501 ${plistPath}`,+ ]);+ }),+ );++ it.effect("ignores a bootout for an agent that is not loaded", () =>+ Effect.gen(function* () {+ const { service, control } = yield* makeHarness("darwin");+ yield* service.install;+ control.failCommand = "launchctl bootout --wait gui/501/com.t3tools.t3code.service";++ yield* service.install;+ expect((yield* service.status).current).toBe(true);+ }),+ );++ it.effect("restarts without overwriting a pending remote update on macOS", () =>+ Effect.gen(function* () {+ const { service, fs, statePath, commands } = yield* makeHarness("darwin");+ yield* service.install;+ const plistPath = (yield* service.status).unitPath;+ // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.+ const pendingState = JSON.stringify({+ protocol: SERVICE_LAUNCHER_PROTOCOL - 1,+ activeVersion: "1.2.3",+ update: {+ id: "remote-update",+ fromVersion: "1.2.3",+ targetVersion: "1.2.4",+ status: "pending",+ },+ });+ yield* fs.writeFileString(statePath, pendingState);+ commands.length = 0;++ expect((yield* service.install.pipe(Effect.flip))._tag).toBe("BootServiceUpdatePendingError");+ expect(serviceStateHasPendingUpdate(yield* fs.readFileString(statePath))).toBe(true);+ expect(commands.filter((command) => command.startsWith("launchctl "))).toEqual([+ "launchctl bootout --wait gui/501/com.t3tools.t3code.service",+ `launchctl bootstrap gui/501 ${plistPath}`,+ ]);+ }),+ );});diff --git a/apps/server/src/cloud/bootService.ts b/apps/server/src/cloud/bootService.tsindex 7eef6feba..795bf38e9 100644--- a/apps/server/src/cloud/bootService.ts+++ b/apps/server/src/cloud/bootService.ts@@ -1,4 +1,8 @@-import { HostProcessExecutablePath, HostProcessPlatform } from "@t3tools/shared/hostProcess";+import {+ HostProcessExecutablePath,+ HostProcessPlatform,+ HostProcessUserId,+} from "@t3tools/shared/hostProcess";import * as Config from "effect/Config";import * as Context from "effect/Context";import * as DateTime from "effect/DateTime";@@ -27,6 +31,10 @@ import {const BOOT_SERVICE_NAME = "t3code";export const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;+// `.service` suffix keeps the label distinct from the desktop app's bundle id+// (com.t3tools.t3code), so launchd and TCC records never collide.+export const BOOT_SERVICE_LAUNCHD_LABEL = "com.t3tools.t3code.service";+export const BOOT_SERVICE_PLIST_FILE = `${BOOT_SERVICE_LAUNCHD_LABEL}.plist`;export const BOOT_SERVICE_UNIT_ENV = "T3_BOOT_SERVICE_UNIT";/** systemd expands `%` specifiers, including in unquoted append-log paths. */@@ -83,12 +91,280 @@ export function renderBootServiceUnit(plan: BootServicePlan): string {].join("\n");}+/** Plist values are emitted as XML text nodes; only these three need escaping. */+export function escapeXmlText(value: string): string {+ return value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");+}++/** Pure renderer: launch agents cannot rely on the user's shell or PATH. */+export function renderBootServicePlist(+ plan: BootServicePlan,+ options: { readonly homeDir: string },+): string {+ // KeepAlive + ThrottleInterval mirror Restart=always + RestartSec=5. launchd+ // has no StartLimitBurst analog; a hard crash loop respawns every 5s forever.+ // ExitTimeOut 90 matches systemd's default TimeoutStopSec. A plain stop+ // completes within the launcher's 5s child grace, but a stop that queues+ // behind an in-flight update transition can take much longer; launchd's+ // system-defined default (5s on current macOS) would SIGKILL the launcher+ // (and, with it, the process group) mid-handoff.+ // ProcessType Interactive opts out of background-job resource throttling.+ // AbandonProcessGroup stays at its default (false): launchd reaps leftover+ // process-group members only when the launcher itself exits — the analog of+ // KillMode=mixed's final cgroup kill — and not when the launcher restarts its+ // child, so agent children survive server updates.+ return [+ `<?xml version="1.0" encoding="UTF-8"?>`,+ `<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">`,+ `<plist version="1.0">`,+ `<dict>`,+ ` <key>Label</key>`,+ ` <string>${BOOT_SERVICE_LAUNCHD_LABEL}</string>`,+ ` <key>ProgramArguments</key>`,+ ` <array>`,+ ` <string>${escapeXmlText(plan.nodePath)}</string>`,+ ` <string>${escapeXmlText(plan.launcherPath)}</string>`,+ ` </array>`,+ ` <key>EnvironmentVariables</key>`,+ ` <dict>`,+ ` <key>T3CODE_HOME</key>`,+ ` <string>${escapeXmlText(plan.baseDir)}</string>`,+ ` <key>${BOOT_SERVICE_UNIT_ENV}</key>`,+ ` <string>${BOOT_SERVICE_PLIST_FILE}</string>`,+ ` </dict>`,+ ` <key>WorkingDirectory</key>`,+ ` <string>${escapeXmlText(options.homeDir)}</string>`,+ ` <key>RunAtLoad</key>`,+ ` <true/>`,+ ` <key>KeepAlive</key>`,+ ` <true/>`,+ ` <key>ThrottleInterval</key>`,+ ` <integer>5</integer>`,+ ` <key>ExitTimeOut</key>`,+ ` <integer>90</integer>`,+ ` <key>ProcessType</key>`,+ ` <string>Interactive</string>`,+ ` <key>StandardOutPath</key>`,+ ` <string>${escapeXmlText(plan.logPath)}</string>`,+ ` <key>StandardErrorPath</key>`,+ ` <string>${escapeXmlText(plan.logPath)}</string>`,+ `</dict>`,+ `</plist>`,+ ``,+ ].join("\n");+}++export interface BootServiceStep {+ readonly step: string;+ readonly command: string;+ readonly args: ReadonlyArray<string>;+ /**+ * Non-zero exit is logged and ignored. Reserved for steps whose common+ * failures (not loaded, already enabled) leave a state a later strict step+ * either tolerates or fails loudly on.+ */+ readonly optional?: boolean;+ /** Override the ProcessRunner default (60s) for steps that block longer. */+ readonly timeout?: Duration.Input;+}++/**+ * Stop commands block until the service manager gives up: 90s by default for+ * systemd's TimeoutStopSec, and ExitTimeOut=90 in the rendered plist. This+ * must stay above both, or the runner cancels the stop mid-shutdown and the+ * next step races a still-loaded service.+ */+const STOP_STEP_TIMEOUT = Duration.seconds(120);++/**+ * Platform service-manager integration as data: paths, a pure renderer, and+ * the command steps each flow runs. install/uninstall/status consume this and+ * never branch on platform.+ */+export interface BootServiceManager {+ readonly kind: "systemd" | "launchd";+ readonly unitPath: string;+ readonly render: (plan: BootServicePlan) => string;+ /** Before rewriting files, when a unit is already installed. */+ readonly stop: ReadonlyArray<BootServiceStep>;+ /** After files are written. The last entry starts the service. */+ readonly activate: ReadonlyArray<BootServiceStep>;+ /** Best-effort recovery after a failed repair of an installed service. */+ readonly restart: ReadonlyArray<BootServiceStep>;+ /** Uninstall, before the unit file is removed. */+ readonly deactivate: ReadonlyArray<BootServiceStep>;+ /** Uninstall, after the unit file is removed. */+ readonly finalize: ReadonlyArray<BootServiceStep>;+}++export function systemdManager(input: {+ readonly path: Path.Path;+ readonly homeDir: string;+}): BootServiceManager {+ const unitPath = input.path.join(+ input.homeDir,+ ".config",+ "systemd",+ "user",+ BOOT_SERVICE_UNIT_FILE,+ );+ return {+ kind: "systemd",+ unitPath,+ render: renderBootServiceUnit,+ stop: [+ {+ step: "stopping the installed service",+ command: "systemctl",+ args: ["--user", "stop", BOOT_SERVICE_UNIT_FILE],+ timeout: STOP_STEP_TIMEOUT,+ },+ ],+ activate: [+ {+ step: "reloading systemd user units",+ command: "systemctl",+ args: ["--user", "daemon-reload"],+ },+ {+ step: "enabling the service",+ command: "systemctl",+ args: ["--user", "enable", BOOT_SERVICE_UNIT_FILE],+ },+ { step: "enabling lingering for this user", command: "loginctl", args: ["enable-linger"] },+ // Start last. No administrative state write occurs after this succeeds.+ {+ step: "starting the service",+ command: "systemctl",+ args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],+ },+ ],+ restart: [+ {+ step: "restarting the service after a failed update",+ command: "systemctl",+ args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],+ },+ ],+ deactivate: [+ {+ step: "stopping the service",+ command: "systemctl",+ args: ["--user", "disable", "--now", BOOT_SERVICE_UNIT_FILE],+ timeout: STOP_STEP_TIMEOUT,+ },+ ],+ finalize: [+ {+ step: "reloading systemd user units",+ command: "systemctl",+ args: ["--user", "daemon-reload"],+ },+ ],+ };+}++export function launchdManager(input: {+ readonly path: Path.Path;+ readonly homeDir: string;+ readonly uid: number;+}): BootServiceManager {+ const unitPath = input.path.join(+ input.homeDir,+ "Library",+ "LaunchAgents",+ BOOT_SERVICE_PLIST_FILE,+ );+ const domainTarget = `gui/${input.uid}`;+ const serviceTarget = `${domainTarget}/${BOOT_SERVICE_LAUNCHD_LABEL}`;+ // bootout/enable are optional: they fail on not-loaded states that are fine+ // to proceed from. The strict `bootstrap` runs last and is also the start:+ // loading a RunAtLoad/KeepAlive plist starts the job, so a separate+ // kickstart would kill and restart a server it just booted. A lingering job+ // that survived bootout, or a gui domain with nobody logged in at the+ // screen (SSH install), makes bootstrap fail the flow loudly rather than+ // silently keeping a stale server.+ return {+ kind: "launchd",+ unitPath,+ render: (plan) => renderBootServicePlist(plan, { homeDir: input.homeDir }),+ // Without --wait, bootout returns in milliseconds while the job drains+ // for up to ExitTimeOut, and a bootstrap during the drain fails EIO.+ // --wait (present on modern macOS, absent from the man page) blocks until+ // the job is removed from the domain; STOP_STEP_TIMEOUT outlives it.+ stop: [+ {+ step: "stopping the installed launch agent",+ command: "launchctl",+ args: ["bootout", "--wait", serviceTarget],+ optional: true,+ timeout: STOP_STEP_TIMEOUT,+ },+ ],+ activate: [+ // A persisted `launchctl disable` override refuses bootstrap; clear it.+ {+ step: "enabling the launch agent",+ command: "launchctl",+ args: ["enable", serviceTarget],+ optional: true,+ },+ // Start last. No administrative state write occurs after this succeeds.+ {+ step: "starting the service",+ command: "launchctl",+ args: ["bootstrap", domainTarget, unitPath],+ },+ ],+ restart: [+ {+ step: "restarting the service after a failed update",+ command: "launchctl",+ args: ["bootstrap", domainTarget, unitPath],+ },+ ],+ // No `launchctl disable` here: a persisted override would sabotage a+ // later reinstall. Removing the plist is what stops the next login load.+ // A bootout that fails for a reason other than "not loaded" leaves the+ // job running until logout; the failure is in the boot-service log.+ deactivate: [+ {+ step: "stopping the service",+ command: "launchctl",+ args: ["bootout", "--wait", serviceTarget],+ optional: true,+ timeout: STOP_STEP_TIMEOUT,+ },+ ],+ finalize: [],+ };+}++/** Undefined means this host cannot run the background service. */+export function selectBootServiceManager(input: {+ readonly platform: NodeJS.Platform;+ readonly homeDir: string;+ readonly uid: number | undefined;+ readonly path: Path.Path;+}): BootServiceManager | undefined {+ if (input.homeDir === "") {+ return undefined;+ }+ if (input.platform === "linux") {+ return systemdManager({ path: input.path, homeDir: input.homeDir });+ }+ if (input.platform === "darwin" && input.uid !== undefined) {+ return launchdManager({ path: input.path, homeDir: input.homeDir, uid: input.uid });+ }+ return undefined;+}+export class BootServiceUnsupportedError extends Schema.TaggedErrorClass<BootServiceUnsupportedError>()("BootServiceUnsupportedError",{ platform: Schema.String },) {override get message(): string {- return `Background setup currently supports Linux with systemd; this machine reports '${this.platform}'.`;+ return `Background setup supports Linux with systemd and macOS with launchd; this machine reports '${this.platform}'.`;}}@@ -163,14 +439,15 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {}) {const hostExecPath = yield* HostProcessExecutablePath;const platform = yield* HostProcessPlatform;+ const uid = yield* HostProcessUserId;const homeDir = yield* Config.string("HOME").pipe(Config.withDefault(""));const fs = yield* FileSystem.FileSystem;const path = yield* Path.Path;const runner = yield* ProcessRunner.ProcessRunner;const host = input.host ?? { execPath: hostExecPath };- const unitDir = path.join(homeDir, ".config", "systemd", "user");- const unitPath = path.join(unitDir, BOOT_SERVICE_UNIT_FILE);+ const detectedManager = selectBootServiceManager({ platform, homeDir, uid, path });+ const unitPath = detectedManager?.unitPath ?? "";const logPath = path.join(input.logsDir, "boot-service.log");const launcherPath = path.join(input.baseDir, "runtime", SERVICE_LAUNCHER_FILE);const statePath = path.join(input.baseDir, "runtime", SERVICE_STATE_FILE);@@ -198,11 +475,11 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {unitPath,};- const requireSystemdLinux = Effect.gen(function* () {- if (platform !== "linux" || homeDir === "") {- return yield* new BootServiceUnsupportedError({ platform });- }- });+ const requireManager = Effect.suspend(() =>+ detectedManager === undefined+ ? new BootServiceUnsupportedError({ platform })+ : Effect.succeed(detectedManager),+ );const runStep = Effect.fn("cloud.boot_service.run_step")(function* (step: string,@@ -235,8 +512,25 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {);});+ const runSteps = (steps: ReadonlyArray<BootServiceStep>) =>+ Effect.forEach(+ steps,+ (entry) => {+ const run = runStep(+ entry.step,+ entry.command,+ entry.args,+ entry.timeout === undefined ? undefined : { timeout: entry.timeout },+ );+ // runStep's tapError already appends the failure to the log, so an+ // ignored optional step still leaves a trace.+ return entry.optional === true ? run.pipe(Effect.ignore) : run.pipe(Effect.asVoid);+ },+ { discard: true },+ );+const install: BootService["Service"]["install"] = Effect.gen(function* () {- yield* requireSystemdLinux;+ const manager = yield* requireManager;yield* fs.makeDirectory(input.logsDir, { recursive: true }).pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));@@ -298,11 +592,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {.exists(unitPath).pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));if (installed) {- yield* runStep("stopping the installed service", "systemctl", [- "--user",- "stop",- BOOT_SERVICE_UNIT_FILE,- ]);+ yield* runSteps(manager.stop);}yield* Effect.gen(function* () {@@ -316,7 +606,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {}}yield* fs- .makeDirectory(unitDir, { recursive: true })+ .makeDirectory(path.dirname(unitPath), { recursive: true }).pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));yield* writeDurably(launcherPath, launcherSource);yield* writeDurably(@@ -331,58 +621,35 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {2,)}\n`,);- yield* writeDurably(unitPath, renderBootServiceUnit(plan));+ yield* writeDurably(unitPath, manager.render(plan));- yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]);- yield* runStep("enabling the service", "systemctl", [- "--user",- "enable",- BOOT_SERVICE_UNIT_FILE,- ]);- yield* runStep("enabling lingering for this user", "loginctl", ["enable-linger"]);- // Start last. No administrative state write occurs after this succeeds.- yield* runStep("starting the service", "systemctl", [- "--user",- "restart",- BOOT_SERVICE_UNIT_FILE,- ]);+ yield* runSteps(manager.activate);}).pipe(Effect.tapError(() =>- installed- ? runStep("restarting the service after a failed update", "systemctl", [- "--user",- "restart",- BOOT_SERVICE_UNIT_FILE,- ]).pipe(Effect.ignore)- : Effect.void,+ installed ? runSteps(manager.restart).pipe(Effect.ignore) : Effect.void,),);return plan;}).pipe(Effect.withSpan("cloud.boot_service.install"));const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () {- yield* requireSystemdLinux;+ const manager = yield* requireManager;if (!(yield* fs.exists(unitPath).pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })))))return false;- yield* runStep("stopping the service", "systemctl", [- "--user",- "disable",- "--now",- BOOT_SERVICE_UNIT_FILE,- ]);+ yield* runSteps(manager.deactivate);yield* fs.remove(unitPath).pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));- yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]);+ yield* runSteps(manager.finalize);return true;}).pipe(Effect.withSpan("cloud.boot_service.uninstall"));const status: BootService["Service"]["status"] = Effect.gen(function* () {- if (platform !== "linux" || homeDir === "") {+ if (detectedManager === undefined) {return { supported: false, installed: false, current: false, unitPath, logPath };}if (!(yield* fs.exists(unitPath))) {@@ -401,7 +668,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {supported: true,installed: true,current:- unit === renderBootServiceUnit(plan) &&+ unit === detectedManager.render(plan) &&launcherExists &&runtimeEntryExists &&Option.isSome(runtimeSentinel) &&diff --git a/apps/server/src/cloud/http.ts b/apps/server/src/cloud/http.tsindex 5c744bbfb..29fdfe8ec 100644--- a/apps/server/src/cloud/http.ts+++ b/apps/server/src/cloud/http.ts@@ -649,7 +649,8 @@ export const pendingServiceUpdateExists = Effect.gen(function* () {});// A pending update alone is not proof a replacement server is coming: an-// explicit launcher stop (`t3 service uninstall`, `systemctl stop`) during+// explicit launcher stop (`t3 service uninstall`, `systemctl stop`,+// `launchctl bootout`) during// the pending window also tears this server down. The launcher marks that case// just before it signals the child, so pending + no marker is the handoff.const pendingUpdateHandoffExists = Effect.gen(function* () {diff --git a/apps/server/src/cloud/pinnedRuntime.ts b/apps/server/src/cloud/pinnedRuntime.tsindex ba3b380b0..06628d5cc 100644--- a/apps/server/src/cloud/pinnedRuntime.ts+++ b/apps/server/src/cloud/pinnedRuntime.ts@@ -10,8 +10,8 @@ import * as ProcessRunner from "../processRunner.ts";/*** A pinned runtime is an exact `t3@<version>` npm-installed into- * <baseDir>/runtime/versions/<version>. The boot service points its systemd- * unit here, and server self-update installs the target version here before+ * <baseDir>/runtime/versions/<version>. The boot service points its unit or+ * launch agent here, and server self-update installs the target version here before* switching over, never `npx t3`, whose cache is ephemeral and whose* registry fetch at boot would make startup depend on the network.*/diff --git a/apps/server/src/serviceLauncher.ts b/apps/server/src/serviceLauncher.tsindex 3641593ec..00fb4e410 100644--- a/apps/server/src/serviceLauncher.ts+++ b/apps/server/src/serviceLauncher.ts@@ -317,7 +317,9 @@ export class Launcher {// This must happen synchronously at signal receipt. A queued update// transition may already be terminating the active child, and that child// needs to see the marker in its shutdown finalizer. KillMode=mixed also- // ensures systemd signals the launcher before the rest of the cgroup.+ // ensures systemd signals the launcher before the rest of the cgroup, and+ // launchd signals only the job's main process (this launcher), so the+ // marker lands before the child sees any signal on both platforms.try {NodeFS.writeFileSync(stopMarkerPath(this.#baseDir), "", { mode: 0o600 });} catch {diff --git a/docs/internals/server-updates.md b/docs/internals/server-updates.mdindex c2ba77f6f..4648fa1fd 100644--- a/docs/internals/server-updates.md+++ b/docs/internals/server-updates.md@@ -2,14 +2,15 @@> For maintainers. Using T3 Code? See [docs/user](../user/).-Remote server updates use one stable systemd launcher. Foreground CLI processes do not self-update,-and a running server never edits its systemd unit or durable service state.+Remote server updates use one stable launcher selected by the platform service manager (systemd on+Linux, launchd on macOS). Foreground CLI processes do not self-update, and a running server never+edits its service definition or durable service state.## OwnershipThe service files under `<baseDir>/runtime` are:-- `service-launcher.mjs`, the stable process selected by systemd;+- `service-launcher.mjs`, the stable process selected by the service manager;- `service-state.json`, the launcher's durable selection state;- `versions/<version>`, immutable exact-version npm installs.@@ -22,7 +23,7 @@ The state contains one active version and, at most, one update record:- `pending A → B` selects B as a retryable trial;- `committed A → B` selects B for ordinary restarts;- `rolled-back A → B` or `failed A → B` selects A;-- invalid state fails closed so systemd cannot guess at a runtime.+- invalid state fails closed so the service manager cannot guess at a runtime.Every write uses same-directory replacement plus file and directory fsync.@@ -50,8 +51,8 @@ operations. It only opens prepared gates and publishes prepared lifecycle state.The launcher serializes child exits, IPC messages, and timers. A trial must report prepared within120 seconds. If the trial exits or times out before prepared, the launcher stops it, restores thesnapshot, records rollback, and starts A. A durable restore marker makes an interrupted restore-resume before either version can boot. After commit, B is active and normal systemd restart policy-applies.+resume before either version can boot. After commit, B is active and the service manager's normal+restart policy applies.## Database Rollbackdiff --git a/docs/user/background-service.md b/docs/user/background-service.mdindex 299e3b641..17de5777b 100644--- a/docs/user/background-service.md+++ b/docs/user/background-service.md@@ -1,7 +1,7 @@# Running T3 Code in the Background-On a Linux host, T3 Code can run as a background service for your user. It starts when the machine-boots and keeps running after you log out.+On Linux and macOS, T3 Code can run as a background service for your user, so it is ready without+keeping a terminal open.## Manage the Service@@ -32,18 +32,42 @@ npx t3@latest service uninstallUpdating restarts T3 Code briefly. Let active agent work and terminal commands finish first.If a remote update is already in progress, wait for it to finish before retrying a local update.-The systemd unit runs a small stable launcher. Exact T3 Code versions are installed separately, so-a failed remote candidate can return to the previous version without rewriting the unit. The-launcher snapshots the database before a remote candidate starts, so database updates roll back-with the server version. An older launcher may require one local `service update` before this is-available.+The service runs a small stable launcher. Exact T3 Code versions are installed separately, so a+failed remote candidate can return to the previous version without rewriting the service+definition. The launcher snapshots the database before a remote candidate starts, so database+updates roll back with the server version. An older launcher may require one local+`service update` before this is available.++## Platform Support++**Linux** uses a systemd user unit at `~/.config/systemd/user/t3code.service`. The service starts+when the machine boots and keeps running after you log out (lingering is enabled during install).++**macOS** uses a launch agent at `~/Library/LaunchAgents/com.t3tools.t3code.service.plist`. It+starts when you log in, not when the Mac boots, and it stops when you log out; macOS has no+equivalent of Linux lingering for user agents. For a Mac that should stay reachable unattended,+turn on automatic login (System Settings → Users & Groups; unavailable while FileVault is on) and+keep the Mac from sleeping.++A few more macOS notes:++- Installing over SSH needs someone logged in at the Mac's screen to start the agent right away.+ Without that, the install command reports an error at the final start step, but the agent is+ fully installed and starts at the next login.+- macOS may show privacy prompts for protected folders such as Desktop, Documents, or Downloads,+ attributed to a bare `node` process, or deny access without a prompt. If agent work fails to+ read those folders, grant Full Disk Access to the node binary listed in the launch agent's+ `ProgramArguments`.+- The agent appears under System Settings → General → Login Items. If it was switched off there,+ or disabled with `launchctl disable`, macOS will not start it at login until you switch it back+ on.++**Windows** is not supported yet.## Using It with T3 Connect-T3 Connect may offer to install the service during setup so the host stays reachable after you log-out. This is only an onboarding shortcut: the service and T3 Connect are managed separately.+T3 Connect may offer to install the service during setup so the host stays reachable in the+background. This is only an onboarding shortcut: the service and T3 Connect are managed separately.Signing out of T3 Connect does not remove the service. Use `t3 service uninstall` when you no longerwant T3 Code to start in the background.--The background service currently requires Linux with systemd.diff --git a/packages/shared/src/hostProcess.ts b/packages/shared/src/hostProcess.tsindex 4885072a0..7a6699ea5 100644--- a/packages/shared/src/hostProcess.ts+++ b/packages/shared/src/hostProcess.ts@@ -51,4 +51,12 @@ export const HostProcessArguments = Context.Reference<ReadonlyArray<string>>(},);+/** Undefined on platforms without POSIX uids (Windows). */+export const HostProcessUserId = Context.Reference<number | undefined>(+ "@t3tools/shared/hostProcess/HostProcessUserId",+ {+ defaultValue: () => process.getuid?.(),+ },+);+export const isHostWindows = Effect.map(HostProcessPlatform, (platform) => platform === "win32");