diff --git a/apps/server/src/atomicWrite.ts b/apps/server/src/atomicWrite.ts
index fcd0345fc8..a567f067cf 100644
--- a/apps/server/src/atomicWrite.ts
+++ b/apps/server/src/atomicWrite.ts
@@ -23,3 +23,25 @@ export const writeFileStringAtomically = (input: {
yield* fs.rename(tempPath, input.filePath);
}),
);
+
+export const writeSymbolicLinkAtomically = (input: {
+ readonly linkPath: string;
+ readonly targetPath: string;
+}) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const targetDirectory = path.dirname(input.linkPath);
+
+ yield* fs.makeDirectory(targetDirectory, { recursive: true });
+ const tempDirectory = yield* fs.makeTempDirectoryScoped({
+ directory: targetDirectory,
+ prefix: `${path.basename(input.linkPath)}.`,
+ });
+ const tempPath = path.join(tempDirectory, "link.tmp");
+
+ yield* fs.symlink(input.targetPath, tempPath);
+ yield* fs.rename(tempPath, input.linkPath);
+ }),
+ );
diff --git a/apps/server/src/cli/connect.ts b/apps/server/src/cli/connect.ts
index ef15e650a6..cd90dbec26 100644
--- a/apps/server/src/cli/connect.ts
+++ b/apps/server/src/cli/connect.ts
@@ -695,7 +695,7 @@ export const connectCommand = Command.make("connect", {
const background = yield* recoverServiceOnboardingOffer(offerServiceDuringOnboarding);
if (background) {
yield* Console.log(
- "\n✓ Background service ready\n\nT3 Code will stay reachable after you log out.",
+ "\n✓ Background service ready\n\nT3 Code will start automatically and stay reachable in the background.",
);
return;
}
diff --git a/apps/server/src/cli/service.test.ts b/apps/server/src/cli/service.test.ts
index e91e10000b..0513697dca 100644
--- a/apps/server/src/cli/service.test.ts
+++ b/apps/server/src/cli/service.test.ts
@@ -16,7 +16,7 @@ it("reports the installed service version and host paths", () => {
[
"T3 Code service",
" Status: installed · t3@0.0.29",
- " Unit: /home/me/.config/systemd/user/t3code.service",
+ " Definition: /home/me/.config/systemd/user/t3code.service",
" Logs: /home/me/.t3/userdata/logs/boot-service.log",
].join("\n"),
);
@@ -29,9 +29,9 @@ it("gives a direct repair command for a stale service", () => {
);
});
-it("explains service availability without systemd", () => {
+it("explains service availability on unsupported platforms", () => {
assert.include(
formatServiceStatus({ ...status, supported: false, installed: false }, "0.0.29"),
- "Supported on: Linux with systemd",
+ "Supported on: macOS with launchd or Linux with systemd",
);
});
diff --git a/apps/server/src/cli/service.ts b/apps/server/src/cli/service.ts
index bd846eeee3..610034e3e5 100644
--- a/apps/server/src/cli/service.ts
+++ b/apps/server/src/cli/service.ts
@@ -48,7 +48,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: macOS with launchd or Linux with systemd";
}
if (!status.installed) {
return "T3 Code service\n Status: not installed\n Next: Run `t3 service install`.";
@@ -56,7 +56,7 @@ export function formatServiceStatus(
return [
"T3 Code service",
` Status: ${status.current ? `installed · t3@${cliVersion}` : "needs an update or repair"}`,
- ` Unit: ${status.unitPath}`,
+ ` Definition: ${status.unitPath}`,
` Logs: ${status.logPath}`,
...(status.current ? [] : [" Next: Run `npx t3@latest service update`."]),
].join("\n");
@@ -156,8 +156,7 @@ export const offerServiceDuringOnboarding = Effect.gen(function* () {
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.",
+ : "Start T3 Code automatically and keep this machine reachable in the background?",
initial: true,
}),
);
diff --git a/apps/server/src/cloud/bootService.test.ts b/apps/server/src/cloud/bootService.test.ts
index 46e9a1da98..b0507e5862 100644
--- a/apps/server/src/cloud/bootService.test.ts
+++ b/apps/server/src/cloud/bootService.test.ts
@@ -12,6 +12,7 @@ import {
HostProcessArguments,
HostProcessExecutablePath,
HostProcessPlatform,
+ HostProcessUserId,
} from "@t3tools/shared/hostProcess";
import { reconcileService } from "../cli/service.ts";
@@ -64,6 +65,7 @@ const provideHostRefs = (home: string, platform: NodeJS.Platform = "linux") =>
Effect.provide(
Layer.mergeAll(
Layer.succeed(HostProcessPlatform, platform),
+ Layer.succeed(HostProcessUserId, 501),
ConfigProvider.layer(ConfigProvider.fromEnv({ env: { HOME: home } })),
),
);
@@ -143,6 +145,34 @@ it("quotes systemd values containing spaces and escapes percent specifiers", ()
assert.include(unit, "StandardError=append:/home/me/100%%logs/boot.log");
});
+it("renders a restartable per-user macOS LaunchAgent", () => {
+ const launchAgent = BootService.renderBootServiceLaunchAgent({
+ nodePath: "/opt/homebrew/bin/node",
+ t3EntryPath: "/Users/theo/T3 & Data/runtime/service/current/node_modules/t3/dist/bin.mjs",
+ baseDir: "/Users/theo/T3 & Data",
+ logPath: "/Users/theo/T3 & Data/userdata/logs/boot-service.log",
+ unitPath: "/Users/theo/Library/LaunchAgents/com.t3tools.t3code.server.plist",
+ pathEnvironment: "/opt/homebrew/bin:/usr/bin:/bin",
+ });
+
+ assert.include(launchAgent, "com.t3tools.t3code.server");
+ assert.include(launchAgent, "RunAtLoad\n ");
+ assert.include(launchAgent, "KeepAlive\n ");
+ assert.include(launchAgent, "/Users/theo/T3 & Data");
+ assert.include(
+ launchAgent,
+ "/Users/theo/T3 & Data/runtime/service/current/node_modules/t3/dist/bin.mjs",
+ );
+ assert.include(
+ launchAgent,
+ "T3_BOOT_SERVICE_UNIT\n com.t3tools.t3code.server",
+ );
+ assert.include(
+ launchAgent,
+ "PATH\n /opt/homebrew/bin:/usr/bin:/bin",
+ );
+});
+
it("flags package-manager cache entry points as ephemeral", () => {
assert.isTrue(
BootService.isEphemeralCacheEntry("/home/theo/.npm/_npx/abc123/node_modules/t3/dist/bin.mjs"),
@@ -388,7 +418,117 @@ it.layer(NodeServices.layer)("BootService", (it) => {
}),
);
- it.effect("fails on non-Linux platforms without touching the filesystem", () =>
+ it.effect("installs and starts a pinned macOS LaunchAgent", () =>
+ Effect.gen(function* () {
+ const { dirs, fs, path } = yield* makeTestContext();
+ const commands: Array = [];
+ const service = yield* BootService.make({
+ baseDir: dirs.baseDir,
+ logsDir: dirs.logsDir,
+ cliVersion: "0.0.27",
+ host: makeHost(dirs.stableEntry),
+ }).pipe(
+ Effect.provide(makeRecordingRunnerLayer(commands)),
+ provideHostRefs(dirs.home, "darwin"),
+ );
+
+ const plan = yield* service.install;
+ const runtimeDir = path.join(dirs.baseDir, "runtime", "versions", "0.0.27");
+ const activeRuntimeLink = path.join(dirs.baseDir, "runtime", "service", "current");
+ const launchAgentPath = path.join(
+ dirs.home,
+ "Library",
+ "LaunchAgents",
+ "com.t3tools.t3code.server.plist",
+ );
+
+ assert.equal(
+ plan.t3EntryPath,
+ path.join(activeRuntimeLink, "node_modules", "t3", "dist", "bin.mjs"),
+ );
+ assert.equal(yield* fs.readLink(activeRuntimeLink), runtimeDir);
+ assert.deepEqual(
+ commands.map((entry) => [entry.command, ...entry.args].join(" ")),
+ [
+ `npm install --prefix ${runtimeDir} --no-fund --no-audit t3@0.0.27`,
+ "/bin/launchctl enable gui/501/com.t3tools.t3code.server",
+ "/bin/launchctl bootout gui/501/com.t3tools.t3code.server",
+ `/bin/launchctl bootstrap gui/501 ${launchAgentPath}`,
+ "/bin/launchctl print gui/501/com.t3tools.t3code.server",
+ ],
+ );
+
+ const plist = yield* fs.readFileString(launchAgentPath);
+ assert.include(plist, `${plan.t3EntryPath}`);
+ assert.notInclude(plist, dirs.stableEntry);
+
+ // The recording npm runner does not materialize files, so complete the
+ // managed runtime before checking the current-state contract.
+ yield* fs.makeDirectory(path.dirname(path.join(runtimeDir, "node_modules/t3/dist/bin.mjs")), {
+ recursive: true,
+ });
+ yield* fs.writeFileString(
+ path.join(runtimeDir, "node_modules", "t3", "dist", "bin.mjs"),
+ "#!/usr/bin/env node\n",
+ );
+ const status = yield* service.status;
+ assert.isTrue(status.supported);
+ assert.isTrue(status.installed);
+ assert.isTrue(status.current);
+
+ assert.isTrue(yield* service.uninstall);
+ assert.isFalse(yield* fs.exists(launchAgentPath));
+ }),
+ );
+
+ it.effect("restores the previous macOS runtime when LaunchAgent activation fails", () =>
+ Effect.gen(function* () {
+ const { dirs, fs, path } = yield* makeTestContext();
+ const initialCommands: Array = [];
+ const initialService = yield* BootService.make({
+ baseDir: dirs.baseDir,
+ logsDir: dirs.logsDir,
+ cliVersion: "0.0.27",
+ host: makeHost(dirs.stableEntry),
+ }).pipe(
+ Effect.provide(makeRecordingRunnerLayer(initialCommands)),
+ provideHostRefs(dirs.home, "darwin"),
+ );
+ yield* initialService.install;
+
+ const activeRuntimeLink = path.join(dirs.baseDir, "runtime", "service", "current");
+ const previousRuntime = yield* fs.readLink(activeRuntimeLink);
+ const launchAgentPath = path.join(
+ dirs.home,
+ "Library",
+ "LaunchAgents",
+ "com.t3tools.t3code.server.plist",
+ );
+ const previousLaunchAgent = yield* fs.readFileString(launchAgentPath);
+ const repairCommands: Array = [];
+ const repairService = yield* BootService.make({
+ baseDir: dirs.baseDir,
+ logsDir: dirs.logsDir,
+ cliVersion: "0.0.28",
+ host: makeHost(dirs.stableEntry),
+ }).pipe(
+ Effect.provide(
+ makeRecordingRunnerLayer(repairCommands, {
+ failWhen: (command, args) => command === "/bin/launchctl" && args.includes("bootstrap"),
+ }),
+ ),
+ provideHostRefs(dirs.home, "darwin"),
+ );
+
+ const error = yield* repairService.install.pipe(Effect.flip);
+
+ assert.isTrue(isCommandError(error));
+ assert.equal(yield* fs.readLink(activeRuntimeLink), previousRuntime);
+ assert.equal(yield* fs.readFileString(launchAgentPath), previousLaunchAgent);
+ }),
+ );
+
+ it.effect("fails on unsupported platforms without touching the filesystem", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const commands: Array = [];
@@ -399,7 +539,7 @@ it.layer(NodeServices.layer)("BootService", (it) => {
host: makeHost("/usr/local/lib/node_modules/t3/dist/bin.mjs"),
}).pipe(
Effect.provide(makeRecordingRunnerLayer(commands)),
- provideHostRefs(dirs.home, "darwin"),
+ provideHostRefs(dirs.home, "win32"),
);
const error = yield* service.install.pipe(Effect.flip);
diff --git a/apps/server/src/cloud/bootService.ts b/apps/server/src/cloud/bootService.ts
index d7e13e834f..0eabc69ede 100644
--- a/apps/server/src/cloud/bootService.ts
+++ b/apps/server/src/cloud/bootService.ts
@@ -11,16 +11,19 @@ import * as Schema from "effect/Schema";
import {
HostProcessArguments,
+ HostProcessEnvironment,
HostProcessExecutablePath,
HostProcessPlatform,
+ HostProcessUserId,
} from "@t3tools/shared/hostProcess";
+import { writeFileStringAtomically, writeSymbolicLinkAtomically } from "../atomicWrite.ts";
import * as ProcessRunner from "../processRunner.ts";
import { ensurePinnedRuntimeInstalled, pinnedRuntimePaths } from "./pinnedRuntime.ts";
/**
- * Installs T3 Code as a per-user boot service. Linux-only for now: systemd
- * user unit + loginctl enable-linger. The service runs a stable or pinned
+ * Installs T3 Code as a per-user background service: systemd + linger on
+ * Linux, or a LaunchAgent on macOS. The service runs a stable or pinned
* runtime — never an ephemeral `npx t3` cache whose eviction could break
* startup.
*/
@@ -29,6 +32,8 @@ const BOOT_SERVICE_NAME = "t3code";
export const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
export const BOOT_SERVICE_UNIT_ENV = "T3_BOOT_SERVICE_UNIT";
+export const BOOT_SERVICE_LAUNCH_AGENT_LABEL = "com.t3tools.t3code.server";
+export const BOOT_SERVICE_LAUNCH_AGENT_FILE = `${BOOT_SERVICE_LAUNCH_AGENT_LABEL}.plist`;
const EPHEMERAL_CACHE_SEGMENTS = [
"/_npx/", // npx
@@ -76,6 +81,39 @@ export interface BootServicePlan {
readonly baseDir: string;
readonly logPath: string;
readonly unitPath: string;
+ /** Captured for launchd, whose default PATH omits common CLI install locations. */
+ readonly pathEnvironment?: string;
+}
+
+export interface LaunchAgentPaths {
+ readonly unitPath: string;
+ readonly activeRuntimeLinkPath: string;
+ readonly activeEntryPath: string;
+ readonly serviceTarget: string;
+}
+
+export function launchAgentPaths(
+ path: Path.Path,
+ homeDir: string,
+ baseDir: string,
+ userId: number,
+): LaunchAgentPaths {
+ const activeRuntimeLinkPath = path.join(baseDir, "runtime", "service", "current");
+ return {
+ unitPath: path.join(homeDir, "Library", "LaunchAgents", BOOT_SERVICE_LAUNCH_AGENT_FILE),
+ activeRuntimeLinkPath,
+ activeEntryPath: path.join(activeRuntimeLinkPath, "node_modules", "t3", "dist", "bin.mjs"),
+ serviceTarget: `gui/${String(userId)}/${BOOT_SERVICE_LAUNCH_AGENT_LABEL}`,
+ };
+}
+
+export function escapeLaunchdXml(value: string): string {
+ return value
+ .replaceAll("&", "&")
+ .replaceAll("<", "<")
+ .replaceAll(">", ">")
+ .replaceAll('"', """)
+ .replaceAll("'", "'");
}
/**
@@ -114,12 +152,61 @@ export function renderBootServiceUnit(plan: BootServicePlan): string {
].join("\n");
}
+/**
+ * LaunchAgents are loaded for a user's GUI session after login. KeepAlive
+ * restarts crashes, while the stable entry path lets remote updates switch
+ * exact runtimes without rewriting or unloading the plist from inside the
+ * process it owns.
+ */
+export function renderBootServiceLaunchAgent(plan: BootServicePlan): string {
+ const value = escapeLaunchdXml;
+ return [
+ '',
+ '',
+ '',
+ "",
+ " Label",
+ ` ${BOOT_SERVICE_LAUNCH_AGENT_LABEL}`,
+ " ProgramArguments",
+ " ",
+ ` ${value(plan.nodePath)}`,
+ ` ${value(plan.t3EntryPath)}`,
+ " serve",
+ " ",
+ " EnvironmentVariables",
+ " ",
+ " T3CODE_HOME",
+ ` ${value(plan.baseDir)}`,
+ ` ${BOOT_SERVICE_UNIT_ENV}`,
+ ` ${BOOT_SERVICE_LAUNCH_AGENT_LABEL}`,
+ ...(plan.pathEnvironment === undefined
+ ? []
+ : [" PATH", ` ${value(plan.pathEnvironment)}`]),
+ " ",
+ " WorkingDirectory",
+ ` ${value(plan.baseDir)}`,
+ " RunAtLoad",
+ " ",
+ " KeepAlive",
+ " ",
+ " ThrottleInterval",
+ " 5",
+ " StandardOutPath",
+ ` ${value(plan.logPath)}`,
+ " StandardErrorPath",
+ ` ${value(plan.logPath)}`,
+ "",
+ "",
+ "",
+ ].join("\n");
+}
+
export class BootServiceUnsupportedError extends Schema.TaggedErrorClass()(
"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}'.`;
}
}
@@ -134,9 +221,13 @@ export class BootServiceCommandError extends Schema.TaggedErrorClass General > Login Items & Extensions.`
+ : detail;
}
}
@@ -157,7 +248,7 @@ export type BootServiceError =
export interface BootServiceStatus {
readonly supported: boolean;
readonly installed: boolean;
- /** False when the installed unit no longer matches what install would write. */
+ /** False when the installed service no longer matches what install would write. */
readonly current: boolean;
readonly unitPath: string;
readonly logPath: string;
@@ -166,7 +257,7 @@ export interface BootServiceStatus {
export class BootService extends Context.Service<
BootService,
{
- /** Installs the pinned runtime + unit, enables linger, starts the service. */
+ /** Installs the runtime + user service and starts it immediately. */
readonly install: Effect.Effect;
/**
* Stops and removes the unit; leaves the pinned runtime for reuse.
@@ -192,23 +283,37 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
const hostArguments = yield* HostProcessArguments;
const host = input.host ?? {
execPath: hostExecPath,
- // When running the packed CLI this is dist/bin.mjs; when stable (global
- // install, repo checkout) the boot service runs this same artifact.
+ // When running the packed CLI this is dist/bin.mjs. Linux can reuse a
+ // stable global install or checkout; macOS pins the exact CLI version.
cliEntryPath: hostArguments[1] ?? "",
};
const platform = yield* HostProcessPlatform;
+ const hostEnvironment = yield* HostProcessEnvironment;
+ const userId = 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 unitDir = path.join(homeDir, ".config", "systemd", "user");
- const unitPath = path.join(unitDir, BOOT_SERVICE_UNIT_FILE);
+ const systemdUnitDir = path.join(homeDir, ".config", "systemd", "user");
+ const systemdUnitPath = path.join(systemdUnitDir, BOOT_SERVICE_UNIT_FILE);
+ const launchAgent =
+ userId === null ? null : launchAgentPaths(path, homeDir, input.baseDir, userId);
+ const unitDir =
+ platform === "darwin" && launchAgent !== null
+ ? path.dirname(launchAgent.unitPath)
+ : systemdUnitDir;
+ const unitPath =
+ platform === "darwin" && launchAgent !== null ? launchAgent.unitPath : systemdUnitPath;
const logPath = path.join(input.logsDir, "boot-service.log");
const runtimePaths = pinnedRuntimePaths(path, input.baseDir, input.cliVersion);
- const requireSystemdLinux = Effect.gen(function* () {
- if (platform !== "linux" || homeDir === "") {
+ const requireSupportedPlatform = Effect.gen(function* () {
+ if (
+ homeDir === "" ||
+ (platform !== "linux" && platform !== "darwin") ||
+ (platform === "darwin" && userId === null)
+ ) {
return yield* new BootServiceUnsupportedError({ platform });
}
});
@@ -244,15 +349,24 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
);
});
+ const runOptionalStep = Effect.fn("cloud.boot_service.run_optional_step")(function* (
+ command: string,
+ args: ReadonlyArray,
+ ) {
+ return yield* runner.run({ command, args }).pipe(
+ Effect.map((result) => result.code === 0),
+ Effect.orElseSucceed(() => false),
+ );
+ });
+
/**
- * Ensures plannedEntryPath exists before the unit points at it. A stable
- * install (global bin, repo checkout) is used as-is; an ephemeral cache
- * entry is replaced by `npm install --prefix`-ing the exact running
- * version into /runtime/versions/. A real install (not a copy
- * of bin.mjs) because t3 ships native deps like node-pty.
+ * Ensures plannedRuntimeEntryPath exists before the service points at it.
+ * macOS always gets an exact managed runtime so the LaunchAgent can use a
+ * stable symlink across remote updates. Linux can reuse a stable global or
+ * checkout entry; ephemeral cache entries are pinned on both platforms.
*/
const ensurePinnedRuntime = Effect.gen(function* () {
- if (!isEphemeralCacheEntry(host.cliEntryPath)) {
+ if (platform !== "darwin" && !isEphemeralCacheEntry(host.cliEntryPath)) {
return;
}
yield* ensurePinnedRuntimeInstalled({
@@ -286,21 +400,44 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
);
});
- // Where the unit will point: derivable without touching the network, so
- // status can compare units purely; install materializes it first.
- const plannedEntryPath = isEphemeralCacheEntry(host.cliEntryPath)
- ? runtimePaths.entryPath
- : host.cliEntryPath;
+ // Where the service definition will point; install materializes it first.
+ const plannedRuntimeEntryPath =
+ platform === "darwin" || isEphemeralCacheEntry(host.cliEntryPath)
+ ? runtimePaths.entryPath
+ : host.cliEntryPath;
+ const plannedEntryPath =
+ platform === "darwin" && launchAgent !== null
+ ? launchAgent.activeEntryPath
+ : plannedRuntimeEntryPath;
const plan: BootServicePlan = {
nodePath: host.execPath,
t3EntryPath: plannedEntryPath,
baseDir: input.baseDir,
logPath,
unitPath,
+ pathEnvironment: hostEnvironment.PATH ?? "/usr/bin:/bin:/usr/sbin:/sbin",
+ };
+
+ const writeUnit = (contents: string) =>
+ writeFileStringAtomically({ filePath: unitPath, contents }).pipe(
+ Effect.provideService(FileSystem.FileSystem, fs),
+ Effect.provideService(Path.Path, path),
+ );
+ const writeActiveRuntimeLink = (targetPath: string) => {
+ if (launchAgent === null) {
+ return Effect.void;
+ }
+ return writeSymbolicLinkAtomically({
+ linkPath: launchAgent.activeRuntimeLinkPath,
+ targetPath,
+ }).pipe(
+ Effect.provideService(FileSystem.FileSystem, fs),
+ Effect.provideService(Path.Path, path),
+ );
};
const install: BootService["Service"]["install"] = Effect.gen(function* () {
- yield* requireSystemdLinux;
+ yield* requireSupportedPlatform;
yield* fs
.makeDirectory(input.logsDir, { recursive: true })
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
@@ -316,15 +453,54 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
Effect.mapError((cause) => new BootServiceInstallError({ cause })),
);
+ const previousRuntimeLink =
+ platform === "darwin" && launchAgent !== null
+ ? yield* fs.exists(launchAgent.activeRuntimeLinkPath).pipe(
+ Effect.flatMap((exists) =>
+ exists
+ ? fs.readLink(launchAgent.activeRuntimeLinkPath).pipe(Effect.map(Option.some))
+ : Effect.succeed(Option.none()),
+ ),
+ Effect.mapError((cause) => new BootServiceInstallError({ cause })),
+ )
+ : Option.none();
+
yield* fs.makeDirectory(unitDir, { recursive: true }).pipe(
- Effect.andThen(fs.writeFileString(unitPath, renderBootServiceUnit(plan))),
+ Effect.andThen(
+ platform === "darwin"
+ ? writeActiveRuntimeLink(runtimePaths.versionDir).pipe(
+ Effect.andThen(writeUnit(renderBootServiceLaunchAgent(plan))),
+ )
+ : writeUnit(renderBootServiceUnit(plan)),
+ ),
Effect.mapError((cause) => new BootServiceInstallError({ cause })),
+ Effect.tapError(() => rollbackFailedInstall(previousUnit, previousRuntimeLink)),
);
- // If any activation step fails, remove the unit again: a leftover file
- // would make service status report it as installed even though it was
- // never enabled or lingered.
yield* Effect.gen(function* () {
+ if (platform === "darwin" && launchAgent !== null && userId !== null) {
+ const domain = `gui/${String(userId)}`;
+ // An explicit install repairs a background item the user previously
+ // disabled in System Settings.
+ yield* runStep("enabling the LaunchAgent", "/bin/launchctl", [
+ "enable",
+ launchAgent.serviceTarget,
+ ]);
+ // bootout is expected to fail on first install. On repair it stops
+ // the old job before bootstrap loads the new definition.
+ yield* runOptionalStep("/bin/launchctl", ["bootout", launchAgent.serviceTarget]);
+ yield* runStep("loading the LaunchAgent", "/bin/launchctl", [
+ "bootstrap",
+ domain,
+ unitPath,
+ ]);
+ yield* runStep("checking the LaunchAgent", "/bin/launchctl", [
+ "print",
+ launchAgent.serviceTarget,
+ ]);
+ return;
+ }
+
yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]);
yield* runStep("enabling the service", "systemctl", [
"--user",
@@ -344,7 +520,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
// username argument: loginctl defaults to the calling user, which is
// always right, while $USER can be stale (su without -l) or unset.
yield* runStep("enabling lingering for this user", "loginctl", ["enable-linger"]);
- }).pipe(Effect.tapError(() => rollbackFailedInstall(previousUnit)));
+ }).pipe(Effect.tapError(() => rollbackFailedInstall(previousUnit, previousRuntimeLink)));
return plan;
}).pipe(Effect.withSpan("cloud.boot_service.install"));
@@ -356,9 +532,26 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
// next lifecycle command misreports the state.
const rollbackFailedInstall = Effect.fn("cloud.boot_service.rollback_failed_install")(function* (
previousUnit: Option.Option,
+ previousRuntimeLink: Option.Option,
) {
+ if (platform === "darwin" && launchAgent !== null && userId !== null) {
+ yield* runOptionalStep("/bin/launchctl", ["bootout", launchAgent.serviceTarget]);
+ if (Option.isSome(previousRuntimeLink)) {
+ yield* writeActiveRuntimeLink(previousRuntimeLink.value).pipe(Effect.ignore);
+ } else {
+ yield* fs.remove(launchAgent.activeRuntimeLinkPath).pipe(Effect.ignore);
+ }
+ if (Option.isSome(previousUnit)) {
+ yield* writeUnit(previousUnit.value).pipe(Effect.ignore);
+ yield* runOptionalStep("/bin/launchctl", ["bootstrap", `gui/${String(userId)}`, unitPath]);
+ } else {
+ yield* fs.remove(unitPath).pipe(Effect.ignore);
+ }
+ return;
+ }
+
if (Option.isSome(previousUnit)) {
- yield* fs.writeFileString(unitPath, previousUnit.value).pipe(Effect.ignore);
+ yield* writeUnit(previousUnit.value).pipe(Effect.ignore);
} else {
yield* runStep("cleaning up the service", "systemctl", [
"--user",
@@ -381,13 +574,22 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
});
const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () {
- yield* requireSystemdLinux;
+ yield* requireSupportedPlatform;
const exists = yield* fs
.exists(unitPath)
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
if (!exists) {
return false;
}
+ if (platform === "darwin" && launchAgent !== null) {
+ // A disabled or already-unloaded agent returns non-zero from bootout;
+ // the plist is still safe to remove and is the durable source of truth.
+ yield* runOptionalStep("/bin/launchctl", ["bootout", launchAgent.serviceTarget]);
+ yield* fs
+ .remove(unitPath)
+ .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
+ return true;
+ }
yield* runStep("stopping the service", "systemctl", [
"--user",
"disable",
@@ -402,7 +604,11 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
}).pipe(Effect.withSpan("cloud.boot_service.uninstall"));
const status: BootService["Service"]["status"] = Effect.gen(function* () {
- if (platform !== "linux" || homeDir === "") {
+ if (
+ homeDir === "" ||
+ (platform !== "linux" && platform !== "darwin") ||
+ (platform === "darwin" && launchAgent === null)
+ ) {
return { supported: false, installed: false, current: false, unitPath, logPath };
}
const unitExists = yield* fs.exists(unitPath);
@@ -410,11 +616,25 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
return { supported: true, installed: false, current: false, unitPath, logPath };
}
const unit = yield* fs.readFileString(unitPath);
+ const entryExists = yield* fs.exists(plannedEntryPath);
+ if (platform === "darwin" && launchAgent !== null) {
+ const activeRuntimeIsCurrent = yield* fs.readLink(launchAgent.activeRuntimeLinkPath).pipe(
+ Effect.map((target) => target === runtimePaths.versionDir),
+ Effect.orElseSucceed(() => false),
+ );
+ const loaded = yield* runOptionalStep("/bin/launchctl", ["print", launchAgent.serviceTarget]);
+ const current =
+ unit === renderBootServiceLaunchAgent(plan) &&
+ entryExists &&
+ activeRuntimeIsCurrent &&
+ loaded;
+ return { supported: true, installed: true, current, unitPath, logPath };
+ }
+
// A unit is current only if it matches what install would write now (an
// older CLI wrote a different runtime/node path) AND the entry point it
// references still exists (a pinned runtime under ~/.t3 can be deleted to
// reclaim space). Either mismatch makes connect offer a repair.
- const entryExists = yield* fs.exists(plannedEntryPath);
const current = unit === renderBootServiceUnit(plan) && entryExists;
return { supported: true, installed: true, current, unitPath, logPath };
}).pipe(
diff --git a/apps/server/src/cloud/selfUpdate.test.ts b/apps/server/src/cloud/selfUpdate.test.ts
index 9d6e380170..2b18657dd2 100644
--- a/apps/server/src/cloud/selfUpdate.test.ts
+++ b/apps/server/src/cloud/selfUpdate.test.ts
@@ -13,13 +13,17 @@ import {
HostProcessEnvironment,
HostProcessExecutablePath,
HostProcessPlatform,
+ HostProcessUserId,
} from "@t3tools/shared/hostProcess";
import * as ServerConfig from "../config.ts";
import * as ProcessRunner from "../processRunner.ts";
import {
+ BOOT_SERVICE_LAUNCH_AGENT_LABEL,
BOOT_SERVICE_UNIT_ENV,
BOOT_SERVICE_UNIT_FILE,
+ launchAgentPaths,
+ renderBootServiceLaunchAgent,
renderBootServiceUnit,
} from "./bootService.ts";
import * as SelfUpdate from "./selfUpdate.ts";
@@ -76,6 +80,7 @@ const provideHostRefs = (input: {
Layer.succeed(HostProcessEnvironment, input.env),
Layer.succeed(HostProcessExecutablePath, NODE_PATH),
Layer.succeed(HostProcessArguments, [NODE_PATH, input.entryPath, "serve"]),
+ Layer.succeed(HostProcessUserId, 501),
),
);
@@ -192,6 +197,41 @@ it.layer(NodeServices.layer)("resolveServerSelfUpdateCapability", (it) => {
}),
);
+ it.effect("reports boot-service for the T3-managed macOS LaunchAgent", () =>
+ Effect.gen(function* () {
+ const { fs, home, path } = yield* makeHome();
+ const baseDir = path.join(home, ".t3");
+ const launchAgent = launchAgentPaths(path, home, baseDir, 501);
+ yield* fs.makeDirectory(path.dirname(launchAgent.unitPath), { recursive: true });
+ yield* fs.writeFileString(
+ launchAgent.unitPath,
+ renderBootServiceLaunchAgent({
+ nodePath: NODE_PATH,
+ t3EntryPath: launchAgent.activeEntryPath,
+ baseDir,
+ logPath: path.join(baseDir, "userdata", "logs", "boot-service.log"),
+ unitPath: launchAgent.unitPath,
+ }),
+ );
+
+ const method = yield* SelfUpdate.resolveServerSelfUpdateCapability({
+ desktopManaged: false,
+ }).pipe(
+ provideHostRefs({
+ platform: "darwin",
+ env: {
+ HOME: home,
+ T3CODE_HOME: baseDir,
+ [BOOT_SERVICE_UNIT_ENV]: BOOT_SERVICE_LAUNCH_AGENT_LABEL,
+ },
+ entryPath: launchAgent.activeEntryPath,
+ }),
+ );
+
+ assert.equal(method, "boot-service");
+ }),
+ );
+
it.effect("reports desktop-managed for desktop-supervised backends", () =>
Effect.gen(function* () {
const { home, path } = yield* makeHome();
@@ -262,11 +302,21 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
const path = yield* Path.Path;
const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-self-update-test-" });
const baseDir = path.join(home, ".t3");
+ const platform = options?.platform ?? "linux";
+ const launchdBootService = options?.bootService === true && platform === "darwin";
+ const launchAgent = launchAgentPaths(path, home, baseDir, 501);
const entryPath =
options?.entryPath ??
- path.join(home, ".t3/runtime/versions/0.0.28/node_modules/t3/dist/bin.mjs");
- const env: NodeJS.ProcessEnv =
- options?.bootService === true
+ (launchdBootService
+ ? launchAgent.activeEntryPath
+ : path.join(home, ".t3/runtime/versions/0.0.28/node_modules/t3/dist/bin.mjs"));
+ const env: NodeJS.ProcessEnv = launchdBootService
+ ? {
+ HOME: home,
+ T3CODE_HOME: baseDir,
+ [BOOT_SERVICE_UNIT_ENV]: BOOT_SERVICE_LAUNCH_AGENT_LABEL,
+ }
+ : options?.bootService === true
? {
HOME: home,
INVOCATION_ID: "abc123",
@@ -274,18 +324,37 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
}
: { HOME: home };
if (options?.bootService === true) {
- const unitDir = path.join(home, ".config", "systemd", "user");
- yield* fs.makeDirectory(unitDir, { recursive: true });
- yield* fs.writeFileString(
- path.join(unitDir, "t3code.service"),
- renderBootServiceUnit({
- nodePath: NODE_PATH,
- t3EntryPath: entryPath,
- baseDir,
- logPath: path.join(baseDir, "userdata", "logs", "boot-service.log"),
- unitPath: path.join(unitDir, "t3code.service"),
- }),
- );
+ if (launchdBootService) {
+ const previousRuntime = path.join(baseDir, "runtime", "versions", "0.0.28");
+ yield* fs.makeDirectory(path.dirname(launchAgent.unitPath), { recursive: true });
+ yield* fs.makeDirectory(path.dirname(launchAgent.activeRuntimeLinkPath), {
+ recursive: true,
+ });
+ yield* fs.symlink(previousRuntime, launchAgent.activeRuntimeLinkPath);
+ yield* fs.writeFileString(
+ launchAgent.unitPath,
+ renderBootServiceLaunchAgent({
+ nodePath: NODE_PATH,
+ t3EntryPath: entryPath,
+ baseDir,
+ logPath: path.join(baseDir, "userdata", "logs", "boot-service.log"),
+ unitPath: launchAgent.unitPath,
+ }),
+ );
+ } else {
+ const unitDir = path.join(home, ".config", "systemd", "user");
+ yield* fs.makeDirectory(unitDir, { recursive: true });
+ yield* fs.writeFileString(
+ path.join(unitDir, "t3code.service"),
+ renderBootServiceUnit({
+ nodePath: NODE_PATH,
+ t3EntryPath: entryPath,
+ baseDir,
+ logPath: path.join(baseDir, "userdata", "logs", "boot-service.log"),
+ unitPath: path.join(unitDir, "t3code.service"),
+ }),
+ );
+ }
}
const commands: Array = [];
@@ -333,7 +402,7 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
configLayer,
),
),
- provideHostRefs({ platform: options?.platform ?? "linux", env, entryPath }),
+ provideHostRefs({ platform, env, entryPath }),
);
return {
fs,
@@ -341,6 +410,7 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
home,
baseDir,
entryPath,
+ launchAgent,
commands,
spawns,
exitCount: () => exited,
@@ -520,6 +590,53 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
}).pipe(Effect.provide(TestClock.layer())),
);
+ it.effect("switches the macOS LaunchAgent runtime and restarts it", () =>
+ Effect.gen(function* () {
+ const context = yield* makeContext({
+ platform: "darwin",
+ bootService: true,
+ });
+
+ const result = yield* context.service.update({ targetVersion: "0.0.29" });
+
+ assert.deepEqual(result, { targetVersion: "0.0.29", method: "boot-service" });
+ assert.equal(
+ yield* context.fs.readLink(context.launchAgent.activeRuntimeLinkPath),
+ context.path.join(context.baseDir, "runtime", "versions", "0.0.29"),
+ );
+ assert.deepEqual(
+ context.commands.map((entry) => entry.command),
+ ["npm", NODE_PATH, "/bin/launchctl"],
+ );
+ assert.deepEqual(context.commands[2], {
+ command: "/bin/launchctl",
+ args: ["kickstart", "-k", "gui/501/com.t3tools.t3code.server"],
+ });
+ assert.lengthOf(context.spawns, 0);
+ assert.equal(context.exitCount(), 0);
+ }).pipe(Effect.provide(TestClock.layer())),
+ );
+
+ it.effect("restores the previous macOS runtime when launchd rejects the restart", () =>
+ Effect.gen(function* () {
+ const context = yield* makeContext({
+ platform: "darwin",
+ bootService: true,
+ failWhen: (command) => command === "/bin/launchctl",
+ });
+ const previousRuntime = yield* context.fs.readLink(context.launchAgent.activeRuntimeLinkPath);
+
+ const error = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
+
+ assert.include(error.reason, "Restarting the T3 Code LaunchAgent failed");
+ assert.equal(
+ yield* context.fs.readLink(context.launchAgent.activeRuntimeLinkPath),
+ previousRuntime,
+ );
+ assert.lengthOf(context.spawns, 0);
+ }).pipe(Effect.provide(TestClock.layer())),
+ );
+
it.effect("restores the previous unit and permits a retry when systemd restart fails", () =>
Effect.gen(function* () {
let failRestart = true;
diff --git a/apps/server/src/cloud/selfUpdate.ts b/apps/server/src/cloud/selfUpdate.ts
index 62bd07fbbc..26de331e5f 100644
--- a/apps/server/src/cloud/selfUpdate.ts
+++ b/apps/server/src/cloud/selfUpdate.ts
@@ -13,6 +13,7 @@ import {
HostProcessEnvironment,
HostProcessExecutablePath,
HostProcessPlatform,
+ HostProcessUserId,
} from "@t3tools/shared/hostProcess";
import * as NodeChildProcess from "node:child_process";
import * as Context from "effect/Context";
@@ -24,11 +25,13 @@ import * as Path from "effect/Path";
import * as Ref from "effect/Ref";
import * as ServerConfig from "../config.ts";
-import { writeFileStringAtomically } from "../atomicWrite.ts";
+import { writeFileStringAtomically, writeSymbolicLinkAtomically } from "../atomicWrite.ts";
import * as ProcessRunner from "../processRunner.ts";
import {
+ BOOT_SERVICE_LAUNCH_AGENT_LABEL,
BOOT_SERVICE_UNIT_ENV,
BOOT_SERVICE_UNIT_FILE,
+ launchAgentPaths,
quoteSystemdValue,
renderBootServiceUnit,
} from "./bootService.ts";
@@ -82,11 +85,11 @@ export function isPublishedCliEntry(entryPath: string): boolean {
* The update path this process can offer, or null when only a manual
* relaunch works. "desktop-managed" — the T3 Code desktop app spawned this
* backend and owns its version; only updating the app updates it.
- * "boot-service" — this is the systemd-supervised process from
- * bootService.ts: rewrite the unit and let systemd swap it. "respawn" — a
- * foreground POSIX process running a published artifact: replace it with a
- * detached child. Windows foreground runs are unsupported for now (no
- * equivalent of the detach-and-exec handoff below).
+ * "boot-service" — this is the systemd- or launchd-supervised process from
+ * bootService.ts: switch the service to the verified runtime and restart it.
+ * "respawn" — a foreground POSIX process running a published artifact:
+ * replace it with a detached child. Windows foreground runs are unsupported
+ * for now (no equivalent of the detach-and-exec handoff below).
*/
export const resolveServerSelfUpdateCapability = Effect.fn(
"cloud.server_self_update.resolve_capability",
@@ -101,6 +104,7 @@ export const resolveServerSelfUpdateCapability = Effect.fn(
const platform = yield* HostProcessPlatform;
const env = yield* HostProcessEnvironment;
const hostArguments = yield* HostProcessArguments;
+ const userId = yield* HostProcessUserId;
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -110,6 +114,26 @@ export const resolveServerSelfUpdateCapability = Effect.fn(
}
const homeDir = env.HOME ?? "";
+ if (platform === "darwin" && homeDir !== "" && userId !== null) {
+ const launchAgent = launchAgentPaths(path, homeDir, env.T3CODE_HOME ?? "", userId);
+ const unitExists = yield* fs
+ .exists(launchAgent.unitPath)
+ .pipe(Effect.orElseSucceed(() => false));
+ if (
+ unitExists &&
+ entryPath === launchAgent.activeEntryPath &&
+ env[BOOT_SERVICE_UNIT_ENV] === BOOT_SERVICE_LAUNCH_AGENT_LABEL
+ ) {
+ return "boot-service" as const;
+ }
+
+ // A marked LaunchAgent process with an unexpected definition must not
+ // detach a second server outside its supervisor.
+ if (env[BOOT_SERVICE_UNIT_ENV] === BOOT_SERVICE_LAUNCH_AGENT_LABEL) {
+ return null;
+ }
+ }
+
if (platform === "linux" && homeDir !== "") {
const unitPath = path.join(homeDir, ".config", "systemd", "user", BOOT_SERVICE_UNIT_FILE);
const unitReferencesEntry = yield* fs.readFileString(unitPath).pipe(
@@ -159,6 +183,8 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* (option
const path = yield* Path.Path;
const runner = yield* ProcessRunner.ProcessRunner;
const env = yield* HostProcessEnvironment;
+ const platform = yield* HostProcessPlatform;
+ const userId = yield* HostProcessUserId;
const hostExecPath = yield* HostProcessExecutablePath;
const hostArguments = yield* HostProcessArguments;
const capability: ServerSelfUpdateCapability | null = yield* resolveServerSelfUpdateCapability({
@@ -224,6 +250,11 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* (option
Effect.provideService(FileSystem.FileSystem, fs),
Effect.provideService(Path.Path, path),
);
+ const writeRuntimeLinkAtomically = (linkPath: string, targetPath: string) =>
+ writeSymbolicLinkAtomically({ linkPath, targetPath }).pipe(
+ Effect.provideService(FileSystem.FileSystem, fs),
+ Effect.provideService(Path.Path, path),
+ );
const update: ServerSelfUpdate["Service"]["update"] = Effect.fn(
"cloud.server_self_update.update",
@@ -297,7 +328,58 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* (option
);
}
- if (activeMethod === "boot-service") {
+ if (activeMethod === "boot-service" && platform === "darwin" && userId !== null) {
+ const homeDir = env.HOME ?? "";
+ const launchAgent = launchAgentPaths(path, homeDir, serverConfig.baseDir, userId);
+ const previousRuntime = yield* fs
+ .readLink(launchAgent.activeRuntimeLinkPath)
+ .pipe(
+ Effect.mapError((cause) =>
+ failWith("Could not read the active launchd runtime.", cause),
+ ),
+ );
+ yield* writeRuntimeLinkAtomically(
+ launchAgent.activeRuntimeLinkPath,
+ runtimePaths.versionDir,
+ ).pipe(
+ Effect.mapError((cause) =>
+ failWith("Could not activate the requested launchd runtime.", cause),
+ ),
+ );
+ yield* Effect.logInfo("Server self-update installed; restarting LaunchAgent.", {
+ targetVersion,
+ });
+
+ yield* Effect.gen(function* () {
+ const kickstart = yield* runner
+ .run({
+ command: "/bin/launchctl",
+ args: ["kickstart", "-k", launchAgent.serviceTarget],
+ })
+ .pipe(
+ Effect.mapError((cause) =>
+ failWith("Could not restart the T3 Code LaunchAgent.", cause),
+ ),
+ );
+ if (kickstart.code !== 0) {
+ return yield* failWith(
+ `Restarting the T3 Code LaunchAgent failed (exit code ${String(kickstart.code)}).`,
+ );
+ }
+ }).pipe(
+ Effect.catch((restartError) =>
+ writeRuntimeLinkAtomically(launchAgent.activeRuntimeLinkPath, previousRuntime).pipe(
+ Effect.mapError((rollbackCause) =>
+ failWith("Could not restore the previous launchd runtime.", {
+ restartError,
+ rollbackCause,
+ }),
+ ),
+ Effect.andThen(Effect.fail(restartError)),
+ ),
+ ),
+ );
+ } else if (activeMethod === "boot-service") {
const homeDir = env.HOME ?? "";
const unitPath = path.join(homeDir, ".config", "systemd", "user", BOOT_SERVICE_UNIT_FILE);
const previousUnit = yield* fs
diff --git a/docs/architecture/server-updates.md b/docs/architecture/server-updates.md
index 2e8c9d6ef6..a0dfa05c4b 100644
--- a/docs/architecture/server-updates.md
+++ b/docs/architecture/server-updates.md
@@ -32,17 +32,17 @@ the mismatch and action disappear.
The server resolves its capability once at startup and publishes it in the environment descriptor.
-| Advertised value | Process shape | Client behavior |
-| ----------------- | --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- |
-| `boot-service` | Linux server running under the T3-managed systemd user service | Call the update RPC; the service unit is replaced and restarted. |
-| `respawn` | Published npm CLI running in the foreground on macOS or Linux | Call the update RPC; the process hands off to a detached replacement. |
-| `desktop-managed` | Backend supervised by the desktop app | Tell the user to update the desktop app on the server machine. |
-| absent | Older server, development checkout, Windows foreground process, or an unrecognized supervisor | Offer the exact manual relaunch command. |
+| Advertised value | Process shape | Client behavior |
+| ----------------- | --------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
+| `boot-service` | Server running under the T3-managed systemd user service or macOS LaunchAgent | Call the update RPC; the managed service switches runtime and restarts. |
+| `respawn` | Published npm CLI running in the foreground on macOS or Linux | Call the update RPC; the process hands off to a detached replacement. |
+| `desktop-managed` | Backend supervised by the desktop app | Tell the user to update the desktop app on the server machine. |
+| absent | Older server, development checkout, Windows foreground process, or an unrecognized supervisor | Offer the exact manual relaunch command. |
Desktop ownership takes precedence over process-shape detection. A desktop-managed backend must
never spawn a second CLI server beside the app-owned process. Likewise, a process launched by an
-unrecognized systemd unit does not claim the foreground respawn path because its supervisor could
-bring the old version back.
+unrecognized systemd unit or marked LaunchAgent does not claim the foreground respawn path because
+its supervisor could bring the old version back.
## Update Flow
@@ -56,7 +56,7 @@ flowchart TD
F --> G[Run version preflight]
G -->|fails| H[Remove failed runtime and keep current server]
G -->|passes| I{Handoff method}
- I -->|boot-service| J[Rewrite and restart T3 systemd unit]
+ I -->|boot-service| J[Switch runtime and restart managed service]
I -->|respawn| K[Start delayed replacement and exit current process]
J --> L[Client reconnects]
K --> L
@@ -77,10 +77,11 @@ preflight also removes the candidate runtime so retrying the same version perfor
## Host Service Lifecycle
-The systemd user service is a host lifecycle concern, not a T3 Connect resource. The standalone
-`t3 service install`, `uninstall`, `update`, and `status` commands own it. Install and update both
-reconcile the unit through `BootService`; running `npx t3@latest service update` therefore pins and
-activates the latest CLI release without requiring a connected client.
+The systemd user service or macOS LaunchAgent is a host lifecycle concern, not a T3 Connect
+resource. The standalone `t3 service install`, `uninstall`, `update`, and `status` commands own it.
+Install and update both reconcile the unit through `BootService`; running
+`npx t3@latest service update` therefore pins and activates the latest CLI release without requiring
+a connected client.
The `t3 connect` onboarding flow may offer service installation, but it calls the same reconciliation
operation as `t3 service install`. Connect logout only disables cloud access and clears its
@@ -88,9 +89,13 @@ authorization; it does not uninstall the host service.
## Process Handoff
-For `boot-service`, the server atomically rewrites the T3-managed user unit to point at the verified
-runtime, reloads systemd, and restarts the unit. Reload and restart failures restore the previous
-unit before returning an error.
+For a systemd `boot-service`, the server atomically rewrites the T3-managed user unit to point at
+the verified runtime, reloads systemd, and restarts the unit. Reload and restart failures restore
+the previous unit before returning an error.
+
+For a macOS `boot-service`, the LaunchAgent always starts a stable entry path. The server atomically
+switches that path to the verified runtime and asks launchd to restart the job. A rejected restart
+restores the previous runtime link before returning an error.
For `respawn`, the server starts a detached, delayed replacement that replays the original CLI
arguments. It then acknowledges the request and schedules the current process to exit. The delays
diff --git a/docs/user/background-service.md b/docs/user/background-service.md
index 8f1f68dc06..4671abccdb 100644
--- a/docs/user/background-service.md
+++ b/docs/user/background-service.md
@@ -1,7 +1,14 @@
# 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 macOS or Linux, T3 Code can run as a background service for your user. The simplest setup is:
+
+```sh
+npx t3 connect
+```
+
+After T3 Connect links the machine, accept the default background setup. T3 Code starts immediately
+and returns automatically after a reboot. On macOS, the per-user LaunchAgent starts after you sign
+in. On Linux, the systemd user service starts at boot and keeps running after you log out.
## Manage the Service
@@ -33,10 +40,10 @@ Updating restarts T3 Code briefly. Let active agent work and terminal commands f
## 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 offers to install the service during setup so the host starts automatically and stays
+reachable in the background. The service and T3 Connect are still managed separately.
Signing out of T3 Connect does not remove the service. Use `t3 service uninstall` when you no longer
want T3 Code to start in the background.
-The background service currently requires Linux with systemd.
+The background service requires macOS with launchd or Linux with systemd.
diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts
index 7f4b6c1654..26735ee5d0 100644
--- a/packages/contracts/src/environment.ts
+++ b/packages/contracts/src/environment.ts
@@ -21,8 +21,8 @@ export const ExecutionEnvironmentPlatform = Schema.Struct({
export type ExecutionEnvironmentPlatform = typeof ExecutionEnvironmentPlatform.Type;
/** How a server can replace itself with another version when asked over RPC:
- "boot-service" rewrites the systemd user unit and restarts it; "respawn"
- installs the target version and respawns the foreground process. */
+ "boot-service" hands off through its systemd unit or macOS LaunchAgent;
+ "respawn" installs the target version and replaces the foreground process. */
export const ServerSelfUpdateMethod = Schema.Literals(["boot-service", "respawn"]);
export type ServerSelfUpdateMethod = typeof ServerSelfUpdateMethod.Type;
diff --git a/packages/shared/src/hostProcess.ts b/packages/shared/src/hostProcess.ts
index 4885072a07..e250c587d1 100644
--- a/packages/shared/src/hostProcess.ts
+++ b/packages/shared/src/hostProcess.ts
@@ -51,4 +51,11 @@ export const HostProcessArguments = Context.Reference>(
},
);
+export const HostProcessUserId = Context.Reference(
+ "@t3tools/shared/hostProcess/HostProcessUserId",
+ {
+ defaultValue: () => (typeof process.getuid === "function" ? process.getuid() : null),
+ },
+);
+
export const isHostWindows = Effect.map(HostProcessPlatform, (platform) => platform === "win32");