Skip to content
TypeScript

fix(server): refuse to share a T3 home with an older background service (#19715)

Arun Krishnamurthy353d8c55d88e
diff --git a/apps/desktop/src/backend/DesktopBackendPool.ts b/apps/desktop/src/backend/DesktopBackendPool.ts
index 0ee88b04667..135df79c63a 100644
--- a/apps/desktop/src/backend/DesktopBackendPool.ts
+++ b/apps/desktop/src/backend/DesktopBackendPool.ts
@@ -180,7 +180,7 @@ export const layer = Layer.effect(
electronDialog
.showErrorBox(
"This T3 home is unavailable",
- "Another T3 Code server, such as the background service, is using this data directory. Stop that server and reopen T3 Code, or set a separate T3CODE_HOME and pair with the running server.",
+ "Another T3 Code server, such as the background service, is using this data directory, or an older background service is set up for it. Stop that server or try `t3 update`. If the older launcher cannot update, run `t3 service uninstall` and optionally reinstall with `t3 service install` from a current CLI. Use `npx t3@latest` if `t3` is missing or outdated, and pass `--base-dir` with the service's T3 home to each command. Then reopen T3 Code. You can also set a separate T3CODE_HOME and pair with the running server.",
)
.pipe(Effect.andThen(electronApp.quit)),
});
diff --git a/apps/desktop/src/wsl/DesktopWslBackend.ts b/apps/desktop/src/wsl/DesktopWslBackend.ts
index 95e5e84d913..d1f61ecc0bd 100644
--- a/apps/desktop/src/wsl/DesktopWslBackend.ts
+++ b/apps/desktop/src/wsl/DesktopWslBackend.ts
@@ -136,7 +136,7 @@ export const layer = Layer.effect(
Ref.set(
preflightErrorRef,
Option.some(
- "Another T3 Code server is using this distro's T3 home. Stop it, or pair with it instead.",
+ "Another T3 Code server is using this distro's T3 home, or an older background service is set up for it. Stop that server or pair with it, or try `t3 update` in the distro. If the older launcher cannot update, run `t3 service uninstall` and optionally reinstall with `t3 service install` from a current CLI in the distro. Use `npx t3@latest` if `t3` is missing or outdated, and pass `--base-dir` with the service's T3 home to each command.",
),
),
),
diff --git a/apps/server/src/cloud/bootService.ts b/apps/server/src/cloud/bootService.ts
index ac82b3bb828..b821d1951a8 100644
--- a/apps/server/src/cloud/bootService.ts
+++ b/apps/server/src/cloud/bootService.ts
@@ -33,11 +33,11 @@ import {
} from "./serviceProtocol.ts";
const BOOT_SERVICE_NAME = "t3code";
-const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
+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.
-const BOOT_SERVICE_LAUNCHD_LABEL = "com.t3tools.t3code.service";
-const BOOT_SERVICE_PLIST_FILE = `${BOOT_SERVICE_LAUNCHD_LABEL}.plist`;
+export const BOOT_SERVICE_LAUNCHD_LABEL = "com.t3tools.t3code.service";
+export const BOOT_SERVICE_PLIST_FILE = `${BOOT_SERVICE_LAUNCHD_LABEL}.plist`;
const BOOT_SERVICE_UNIT_ENV = "T3_BOOT_SERVICE_UNIT";
export const BOOT_SERVICE_LOG_FILE = "boot-service.log";
diff --git a/apps/server/src/serverOwnership.ts b/apps/server/src/serverOwnership.ts
index 4c4811de09e..50d0b2332c2 100644
--- a/apps/server/src/serverOwnership.ts
+++ b/apps/server/src/serverOwnership.ts
@@ -8,10 +8,25 @@ import * as HostProcess from "@t3tools/shared/HostProcess";
import * as Crypto from "effect/Crypto";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Runtime from "effect/Runtime";
import * as Schema from "effect/Schema";
+import {
+ BOOT_SERVICE_LAUNCHD_LABEL,
+ BOOT_SERVICE_PLIST_FILE,
+ BOOT_SERVICE_UNIT_FILE,
+ bootServiceBaseDirOf,
+} from "./cloud/bootService.ts";
+import { ServiceLauncherHostProcess } from "./cloud/serviceLauncherClient.ts";
+import {
+ SERVICE_LAUNCHER_CONTEXT_ENV,
+ SERVICE_RESTART_PENDING_FILE,
+ SERVICE_STATE_FILE,
+ compareExactServiceVersions,
+ serviceStateActiveVersion,
+} from "./cloud/serviceProtocol.ts";
import * as ProcessRunner from "./processRunner.ts";
import {
clearPersistedServerRuntimeState,
@@ -34,6 +49,17 @@ export class ServerAlreadyRunningError extends Schema.TaggedError<ServerAlreadyR
}
}
+export class OlderBootServiceError extends Schema.TaggedError<OlderBootServiceError>()(
+ "OlderBootServiceError",
+ { baseDir: Schema.String },
+) {
+ override readonly [Runtime.errorExitCode] = SERVER_EXIT_CODE_STATE_DIR_OWNED;
+
+ override get message(): string {
+ return `A T3 Code background service set up for ${this.baseDir} may still run a release without the ownership lock. On that machine, try \`t3 update\` and let it restart (or run \`t3 service restart\` if the update is already installed). If the older launcher cannot update, run \`t3 service uninstall\`, then reinstall with \`t3 service install\` from a current CLI. You can also leave the service uninstalled. Pass \`--base-dir ${this.baseDir}\` to each command, and use \`npx t3@latest\` if \`t3\` is not installed or is outdated. Then retry. No server was stopped.`;
+ }
+}
+
export class ServerOwnershipError extends Schema.TaggedError<ServerOwnershipError>()(
"ServerOwnershipError",
{ stateDir: Schema.String, cause: Schema.Defect() },
@@ -83,6 +109,75 @@ const legacyOwnerIsLive = Effect.fn("legacyOwnerIsLive")(function* (
return !Number.isFinite(startedAt) || startedAt <= recordedAt + 1_000;
});
+// Pre-lock services become invisible when another server replaces their runtime
+// record. Unreadable configuration or an unavailable manager allows startup.
+const olderBootServiceHome = Effect.fn("olderBootServiceHome")(
+ function* (stateDir: string) {
+ if (
+ (yield* ServiceLauncherHostProcess).connected &&
+ (yield* HostProcess.Environment)[SERVICE_LAUNCHER_CONTEXT_ENV] !== undefined
+ ) {
+ return undefined;
+ }
+ const platform = yield* HostProcess.Platform;
+ const uid = yield* HostProcess.UserId;
+ if (platform !== "linux" && (platform !== "darwin" || uid === undefined)) return undefined;
+
+ const homeDir = yield* HostProcess.HomeDirectory;
+ const fs = yield* FileSystem.FileSystem;
+ const runner = yield* ProcessRunner.ProcessRunner;
+ const unitPath =
+ platform === "darwin"
+ ? NodePath.join(homeDir, "Library", "LaunchAgents", BOOT_SERVICE_PLIST_FILE)
+ : NodePath.join(homeDir, ".config", "systemd", "user", BOOT_SERVICE_UNIT_FILE);
+ const baseDir = bootServiceBaseDirOf(yield* fs.readFileString(unitPath));
+ if (
+ baseDir === undefined ||
+ (yield* fs.realPath(NodePath.join(baseDir, "userdata"))) !== (yield* fs.realPath(stateDir))
+ ) {
+ return undefined;
+ }
+ const runtimeDir = NodePath.join(baseDir, "runtime");
+ const version = serviceStateActiveVersion(
+ yield* fs.readFileString(NodePath.join(runtimeDir, SERVICE_STATE_FILE)),
+ );
+ if (version === undefined) return undefined;
+ const run = (command: string, args: ReadonlyArray<string>) =>
+ runner.run({ command, args, timeout: Duration.seconds(5), maxOutputBytes: 65_536 });
+ let loaded: boolean;
+ if (platform === "darwin") {
+ loaded =
+ (yield* run("launchctl", ["print", `gui/${uid}/${BOOT_SERVICE_LAUNCHD_LABEL}`])).code === 0;
+ if (!loaded) {
+ const disabled = yield* run("launchctl", ["print-disabled", `gui/${uid}`]);
+ // Older macOS versions print `true` instead of `disabled`.
+ if (
+ disabled.code !== 0 ||
+ disabled.stdout.includes(`"${BOOT_SERVICE_LAUNCHD_LABEL}" => disabled`) ||
+ disabled.stdout.includes(`"${BOOT_SERVICE_LAUNCHD_LABEL}" => true`)
+ )
+ return undefined;
+ }
+ } else {
+ const active = yield* run("systemctl", ["--user", "is-active", BOOT_SERVICE_UNIT_FILE]);
+ // A unit waiting out its Restart= delay is activating, with exit code 3.
+ loaded = active.code === 0 || (active.code === 3 && active.stdout.trim() === "activating");
+ if (!loaded) {
+ const enabled = yield* run("systemctl", ["--user", "is-enabled", BOOT_SERVICE_UNIT_FILE]);
+ if (enabled.code !== 0 || enabled.stdout.trim() !== "enabled") return undefined;
+ }
+ }
+ // A deferred update names the staged runtime, not the loaded service's runtime.
+ if (loaded && (yield* fs.exists(NodePath.join(runtimeDir, SERVICE_RESTART_PENDING_FILE)))) {
+ return baseDir;
+ }
+ // Stable 0.1.0 shipped the ownership lock. Earlier lock-aware prereleases
+ // are conservatively refused because older runtimes expose no capability marker.
+ return compareExactServiceVersions(version, "0.1.0") < 0 ? baseDir : undefined;
+ },
+ Effect.orElseSucceed(() => undefined),
+);
+
/**
* Hold an exclusive lock on the state directory until the scope closes. The
* lock is an exclusive transaction on `server-owner.sqlite`, which never holds
@@ -137,6 +232,10 @@ export const acquireServerOwnership = Effect.fn("acquireServerOwnership")(functi
) {
return yield* new ServerAlreadyRunningError({ stateDir });
}
+ const olderServiceHome = yield* olderBootServiceHome(stateDir);
+ if (olderServiceHome !== undefined) {
+ return yield* new OlderBootServiceError({ baseDir: olderServiceHome });
+ }
return {
publish: (state: PersistedServerRuntimeState) =>
diff --git a/apps/server/src/serverRuntimeState.test.ts b/apps/server/src/serverRuntimeState.test.ts
index 34ab05bc3a7..86b1cd09321 100644
--- a/apps/server/src/serverRuntimeState.test.ts
+++ b/apps/server/src/serverRuntimeState.test.ts
@@ -1,5 +1,6 @@
import { assert, describe, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
+import * as HostProcess from "@t3tools/shared/HostProcess";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
@@ -7,21 +8,147 @@ import * as Logger from "effect/Logger";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as References from "effect/References";
+import * as Runtime from "effect/Runtime";
import * as Schema from "effect/Schema";
+import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
+import { renderBootServicePlist, renderBootServiceUnit } from "./cloud/bootService.ts";
+import { ServiceLauncherHostProcess } from "./cloud/serviceLauncherClient.ts";
+import { SERVICE_LAUNCHER_CONTEXT_ENV } from "./cloud/serviceProtocol.ts";
import * as ProcessRunner from "./processRunner.ts";
import * as ServerOwnership from "./serverOwnership.ts";
import * as ServerRuntimeState from "./serverRuntimeState.ts";
const isServerRuntimeStateError = Schema.is(ServerRuntimeState.ServerRuntimeStateError);
+const startBesideBootService = Effect.fn("test.startBesideBootService")(function* (input: {
+ readonly platform: "darwin" | "linux";
+ readonly outputs: Readonly<Record<string, { readonly code: number; readonly stdout?: string }>>;
+ readonly unitServesOtherHome?: boolean;
+ readonly restartPending?: boolean;
+ readonly activeVersion?: string;
+ readonly npmRuntime?: boolean;
+ readonly missingServiceState?: boolean;
+ readonly environment?: NodeJS.ProcessEnv;
+ readonly connected?: boolean;
+}) {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-owner-boot-service-" });
+ const t3Home = path.join(root, ".t3");
+ const serviceHome = input.unitServesOtherHome ? path.join(root, "other") : t3Home;
+ for (const home of [t3Home, serviceHome]) {
+ yield* fs.makeDirectory(path.join(home, "userdata"), { recursive: true });
+ }
+ yield* fs.makeDirectory(path.join(serviceHome, "runtime"));
+ const activeVersion = input.activeVersion ?? "0.0.42";
+ if (!input.missingServiceState) {
+ yield* fs.writeFileString(
+ path.join(serviceHome, "runtime", "service-state.json"),
+ JSON.stringify({ protocol: input.npmRuntime ? 2 : 3, activeVersion }),
+ );
+ }
+ if (input.npmRuntime) {
+ const versionDir = path.join(serviceHome, "runtime", "versions", activeVersion);
+ const entryPath = path.join(versionDir, "node_modules", "t3", "dist", "bin.mjs");
+ yield* fs.makeDirectory(path.dirname(entryPath), { recursive: true });
+ yield* fs.writeFileString(entryPath, "");
+ }
+
+ if (input.restartPending) {
+ yield* fs.writeFileString(
+ path.join(serviceHome, "runtime", ".restart-pending"),
+ `${activeVersion}\n`,
+ );
+ }
+ const plan = {
+ program: input.npmRuntime
+ ? ["/usr/bin/node", path.join(serviceHome, "runtime", "service-launcher.mjs")]
+ : [],
+ baseDir: serviceHome,
+ logPath: "",
+ unitPath: "",
+ };
+ const [unitPath, unit] =
+ input.platform === "darwin"
+ ? [
+ path.join(root, "Library", "LaunchAgents", "com.t3tools.t3code.service.plist"),
+ renderBootServicePlist(plan, { homeDir: root, environmentPath: "" }),
+ ]
+ : [
+ path.join(root, ".config", "systemd", "user", "t3code.service"),
+ renderBootServiceUnit(plan),
+ ];
+ yield* fs.makeDirectory(path.dirname(unitPath), { recursive: true });
+ yield* fs.writeFileString(unitPath, unit);
+
+ const probes: string[] = [];
+ const runner = ProcessRunner.ProcessRunner.of({
+ run: (run) =>
+ Effect.gen(function* () {
+ const probe = `${path.basename(run.command)} ${run.args.find((arg) => !arg.startsWith("--"))}`;
+ probes.push(probe);
+ const output = input.outputs[probe];
+ return yield* output === undefined
+ ? Effect.fail(
+ new ProcessRunner.ProcessSpawnError({
+ command: run.command,
+ argumentCount: run.args.length,
+ cause: new Error("not found"),
+ }),
+ )
+ : Effect.succeed({
+ stdout: output.stdout ?? "",
+ stderr: "",
+ code: ChildProcessSpawner.ExitCode(output.code),
+ timedOut: false,
+ stdoutTruncated: false,
+ stderrTruncated: false,
+ stdoutInvalidUtf8: false,
+ stderrInvalidUtf8: false,
+ });
+ }),
+ });
+ const result = yield* Effect.scoped(
+ ServerOwnership.acquireServerOwnership(path.join(t3Home, "userdata", "server-runtime.json")),
+ ).pipe(
+ Effect.provideService(ProcessRunner.ProcessRunner, runner),
+ Effect.provideService(HostProcess.Platform, input.platform),
+ Effect.provideService(HostProcess.UserId, 501),
+ Effect.provideService(HostProcess.HomeDirectory, root),
+ Effect.provideService(HostProcess.Environment, input.environment ?? {}),
+ Effect.provideService(ServiceLauncherHostProcess, {
+ connected: input.connected ?? false,
+ send: () => false,
+ on: () => undefined,
+ off: () => undefined,
+ }),
+ Effect.result,
+ );
+ assert.includeMembers(
+ ["launchctl print", "launchctl print-disabled", "systemctl is-active", "systemctl is-enabled"],
+ probes,
+ );
+ return { result, t3Home };
+});
+
interface CapturedLog {
readonly message: unknown;
readonly annotations: Readonly<Record<string, unknown>>;
}
describe("server ownership", () => {
- const layerOwnership = ProcessRunner.layer.pipe(Layer.provideMerge(NodeServices.layer));
+ // An empty home, so no boot service unit installed on this machine is read.
+ const layerOwnership = Layer.mergeAll(
+ ProcessRunner.layer,
+ Layer.effect(
+ HostProcess.HomeDirectory,
+ Effect.gen(function* () {
+ return yield* (yield* FileSystem.FileSystem).makeTempDirectoryScoped();
+ }),
+ ),
+ Layer.succeed(HostProcess.Environment, {}),
+ ).pipe(Layer.provideMerge(NodeServices.layer));
const makeState = ServerRuntimeState.makePersistedServerRuntimeState({
config: { host: undefined, devUrl: undefined },
port: 3773,
@@ -115,6 +242,170 @@ describe("server ownership", () => {
assert.equal(Option.getOrThrow(remaining).ownerId, "other-owner");
}).pipe(Effect.provide(layerOwnership)),
);
+
+ describe("beside an installed boot service", () => {
+ it.effect("refuses an old active or scheduled service even without its runtime record", () =>
+ Effect.gen(function* () {
+ for (const fixture of [
+ {
+ platform: "darwin",
+ outputs: { "launchctl print": { code: 0 } },
+ },
+ {
+ platform: "darwin",
+ outputs: {
+ "launchctl print": { code: 113 },
+ "launchctl print-disabled": {
+ code: 0,
+ stdout: '"com.t3tools.t3code.service" => false',
+ },
+ },
+ },
+ {
+ platform: "linux",
+ outputs: {
+ // Restart= keeps an otherwise disabled service alive during its restart delay.
+ "systemctl is-active": { code: 3, stdout: "activating\n" },
+ "systemctl is-enabled": { code: 1, stdout: "disabled\n" },
+ },
+ },
+ {
+ platform: "linux",
+ outputs: {
+ "systemctl is-active": { code: 3, stdout: "inactive\n" },
+ "systemctl is-enabled": { code: 0, stdout: "enabled\n" },
+ },
+ },
+ {
+ platform: "darwin",
+ outputs: { "launchctl print": { code: 0 } },
+ environment: { [SERVICE_LAUNCHER_CONTEXT_ENV]: "{}" },
+ },
+ ] as const) {
+ const { result, t3Home } = yield* startBesideBootService(fixture);
+ assert.equal(result._tag, "Failure");
+ if (result._tag !== "Failure") return;
+ assert.equal(result.failure._tag, "OlderBootServiceError");
+ assert.equal(Runtime.getErrorExitCode(result.failure), 78);
+ assert.include(result.failure.message, t3Home);
+ assert.include(result.failure.message, "t3 update");
+ assert.include(result.failure.message, "t3 service restart");
+ assert.include(result.failure.message, "No server was stopped");
+ }
+ }).pipe(Effect.provide(NodeServices.layer)),
+ );
+
+ it.effect(
+ "refuses an active npm-installed service with no standalone executable or runtime record",
+ () =>
+ Effect.gen(function* () {
+ const { result } = yield* startBesideBootService({
+ platform: "linux",
+ activeVersion: "0.0.40",
+ npmRuntime: true,
+ outputs: {
+ "systemctl is-active": { code: 0, stdout: "active\n" },
+ },
+ });
+ assert.equal(result._tag, "Failure");
+ if (result._tag !== "Failure") return;
+ assert.equal(result.failure._tag, "OlderBootServiceError");
+ assert.equal(Runtime.getErrorExitCode(result.failure), 78);
+ }).pipe(Effect.provide(NodeServices.layer)),
+ );
+
+ it.effect("refuses while the loaded service has not restarted into its lock-aware update", () =>
+ Effect.gen(function* () {
+ const { result } = yield* startBesideBootService({
+ platform: "darwin",
+ restartPending: true,
+ activeVersion: "0.1.0",
+ outputs: {
+ "launchctl print": { code: 0 },
+ },
+ });
+ assert.equal(result._tag === "Failure" && result.failure._tag, "OlderBootServiceError");
+ }).pipe(Effect.provide(NodeServices.layer)),
+ );
+
+ it.effect("allows lock-aware stable services that are loaded or stopped and enabled", () =>
+ Effect.gen(function* () {
+ for (const fixture of [
+ {
+ platform: "darwin",
+ outputs: {
+ "launchctl print": { code: 0 },
+ },
+ },
+ {
+ platform: "linux",
+ outputs: {
+ "systemctl is-active": { code: 3, stdout: "inactive\n" },
+ "systemctl is-enabled": { code: 0, stdout: "enabled\n" },
+ },
+ },
+ ] as const) {
+ const { result } = yield* startBesideBootService({ ...fixture, activeVersion: "0.1.0" });
+ assert.equal(result._tag, "Success");
+ }
+ }).pipe(Effect.provide(NodeServices.layer)),
+ );
+
+ it.effect("allows services that cannot compete for this home", () =>
+ Effect.gen(function* () {
+ const outputs = {
+ "launchctl print": { code: 0 },
+ };
+ for (const fixture of [
+ { platform: "darwin", outputs, unitServesOtherHome: true },
+ {
+ platform: "darwin",
+ outputs,
+ environment: { [SERVICE_LAUNCHER_CONTEXT_ENV]: "{}" },
+ connected: true,
+ },
+ {
+ platform: "darwin",
+ outputs: {
+ "launchctl print": { code: 113 },
+ "launchctl print-disabled": {
+ code: 0,
+ stdout: '"com.t3tools.t3code.service" => disabled',
+ },
+ },
+ },
+ {
+ platform: "linux",
+ outputs: {
+ "systemctl is-active": { code: 3, stdout: "inactive\n" },
+ "systemctl is-enabled": { code: 1, stdout: "disabled\n" },
+ },
+ },
+ ] as const) {
+ const { result } = yield* startBesideBootService(fixture);
+ assert.equal(result._tag, "Success");
+ }
+ }).pipe(Effect.provide(NodeServices.layer)),
+ );
+
+ it.effect("allows startup when the service configuration or manager is unavailable", () =>
+ Effect.gen(function* () {
+ for (const fixture of [
+ { outputs: {} },
+ {
+ outputs: {
+ "launchctl print": { code: 113 },
+ "launchctl print-disabled": { code: 1 },
+ },
+ },
+ { outputs: { "launchctl print": { code: 0 } }, missingServiceState: true },
+ ]) {
+ const { result } = yield* startBesideBootService({ platform: "darwin", ...fixture });
+ assert.equal(result._tag, "Success");
+ }
+ }).pipe(Effect.provide(NodeServices.layer)),
+ );
+ });
});
describe("serverRuntimeState", () => {