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

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

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

Synced Nov 22, 22:00 UTC

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

Co-authored-by: Julius Marminge <julius0216@outlook.com>

Arun Krishnamurthy committed Oct 20, 2026 at 00:08 UTC 353d8c55d88e65d04581c95da53377d2c28fd736
5 files changed +396 -6
apps/desktop/src/backend/DesktopBackendPool.ts
+1 -1
@@ -180,7 +180,7 @@ export const layer = Layer.effect(
180 electronDialog
181 .showErrorBox(
182 "This T3 home is unavailable",
183 - "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.",
183 + "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.",
184 )
185 .pipe(Effect.andThen(electronApp.quit)),
186 });
apps/desktop/src/wsl/DesktopWslBackend.ts
+1 -1
@@ -136,7 +136,7 @@ export const layer = Layer.effect(
136 Ref.set(
137 preflightErrorRef,
138 Option.some(
139 - "Another T3 Code server is using this distro's T3 home. Stop it, or pair with it instead.",
139 + "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.",
140 ),
141 ),
142 ),
apps/server/src/cloud/bootService.ts
+3 -3
@@ -33,11 +33,11 @@ import {
33 } from "./serviceProtocol.ts";
34
35 const BOOT_SERVICE_NAME = "t3code";
36 -const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
36 +export const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
37 // `.service` suffix keeps the label distinct from the desktop app's bundle id
38 // (com.t3tools.t3code), so launchd and TCC records never collide.
39 -const BOOT_SERVICE_LAUNCHD_LABEL = "com.t3tools.t3code.service";
40 -const BOOT_SERVICE_PLIST_FILE = `${BOOT_SERVICE_LAUNCHD_LABEL}.plist`;
39 +export const BOOT_SERVICE_LAUNCHD_LABEL = "com.t3tools.t3code.service";
40 +export const BOOT_SERVICE_PLIST_FILE = `${BOOT_SERVICE_LAUNCHD_LABEL}.plist`;
41 const BOOT_SERVICE_UNIT_ENV = "T3_BOOT_SERVICE_UNIT";
42 export const BOOT_SERVICE_LOG_FILE = "boot-service.log";
43
apps/server/src/serverOwnership.ts
+99
@@ -8,10 +8,25 @@ import * as HostProcess from "@t3tools/shared/HostProcess";
8 import * as Crypto from "effect/Crypto";
9 import * as Duration from "effect/Duration";
10 import * as Effect from "effect/Effect";
11 +import * as FileSystem from "effect/FileSystem";
12 import * as Option from "effect/Option";
13 import * as Runtime from "effect/Runtime";
14 import * as Schema from "effect/Schema";
15
16 +import {
17 + BOOT_SERVICE_LAUNCHD_LABEL,
18 + BOOT_SERVICE_PLIST_FILE,
19 + BOOT_SERVICE_UNIT_FILE,
20 + bootServiceBaseDirOf,
21 +} from "./cloud/bootService.ts";
22 +import { ServiceLauncherHostProcess } from "./cloud/serviceLauncherClient.ts";
23 +import {
24 + SERVICE_LAUNCHER_CONTEXT_ENV,
25 + SERVICE_RESTART_PENDING_FILE,
26 + SERVICE_STATE_FILE,
27 + compareExactServiceVersions,
28 + serviceStateActiveVersion,
29 +} from "./cloud/serviceProtocol.ts";
30 import * as ProcessRunner from "./processRunner.ts";
31 import {
32 clearPersistedServerRuntimeState,
@@ -34,6 +49,17 @@ export class ServerAlreadyRunningError extends Schema.TaggedError<ServerAlreadyR
49 }
50 }
51
52 +export class OlderBootServiceError extends Schema.TaggedError<OlderBootServiceError>()(
53 + "OlderBootServiceError",
54 + { baseDir: Schema.String },
55 +) {
56 + override readonly [Runtime.errorExitCode] = SERVER_EXIT_CODE_STATE_DIR_OWNED;
57 +
58 + override get message(): string {
59 + 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.`;
60 + }
61 +}
62 +
63 export class ServerOwnershipError extends Schema.TaggedError<ServerOwnershipError>()(
64 "ServerOwnershipError",
65 { stateDir: Schema.String, cause: Schema.Defect() },
@@ -83,6 +109,75 @@ const legacyOwnerIsLive = Effect.fn("legacyOwnerIsLive")(function* (
109 return !Number.isFinite(startedAt) || startedAt <= recordedAt + 1_000;
110 });
111
112 +// Pre-lock services become invisible when another server replaces their runtime
113 +// record. Unreadable configuration or an unavailable manager allows startup.
114 +const olderBootServiceHome = Effect.fn("olderBootServiceHome")(
115 + function* (stateDir: string) {
116 + if (
117 + (yield* ServiceLauncherHostProcess).connected &&
118 + (yield* HostProcess.Environment)[SERVICE_LAUNCHER_CONTEXT_ENV] !== undefined
119 + ) {
120 + return undefined;
121 + }
122 + const platform = yield* HostProcess.Platform;
123 + const uid = yield* HostProcess.UserId;
124 + if (platform !== "linux" && (platform !== "darwin" || uid === undefined)) return undefined;
125 +
126 + const homeDir = yield* HostProcess.HomeDirectory;
127 + const fs = yield* FileSystem.FileSystem;
128 + const runner = yield* ProcessRunner.ProcessRunner;
129 + const unitPath =
130 + platform === "darwin"
131 + ? NodePath.join(homeDir, "Library", "LaunchAgents", BOOT_SERVICE_PLIST_FILE)
132 + : NodePath.join(homeDir, ".config", "systemd", "user", BOOT_SERVICE_UNIT_FILE);
133 + const baseDir = bootServiceBaseDirOf(yield* fs.readFileString(unitPath));
134 + if (
135 + baseDir === undefined ||
136 + (yield* fs.realPath(NodePath.join(baseDir, "userdata"))) !== (yield* fs.realPath(stateDir))
137 + ) {
138 + return undefined;
139 + }
140 + const runtimeDir = NodePath.join(baseDir, "runtime");
141 + const version = serviceStateActiveVersion(
142 + yield* fs.readFileString(NodePath.join(runtimeDir, SERVICE_STATE_FILE)),
143 + );
144 + if (version === undefined) return undefined;
145 + const run = (command: string, args: ReadonlyArray<string>) =>
146 + runner.run({ command, args, timeout: Duration.seconds(5), maxOutputBytes: 65_536 });
147 + let loaded: boolean;
148 + if (platform === "darwin") {
149 + loaded =
150 + (yield* run("launchctl", ["print", `gui/${uid}/${BOOT_SERVICE_LAUNCHD_LABEL}`])).code === 0;
151 + if (!loaded) {
152 + const disabled = yield* run("launchctl", ["print-disabled", `gui/${uid}`]);
153 + // Older macOS versions print `true` instead of `disabled`.
154 + if (
155 + disabled.code !== 0 ||
156 + disabled.stdout.includes(`"${BOOT_SERVICE_LAUNCHD_LABEL}" => disabled`) ||
157 + disabled.stdout.includes(`"${BOOT_SERVICE_LAUNCHD_LABEL}" => true`)
158 + )
159 + return undefined;
160 + }
161 + } else {
162 + const active = yield* run("systemctl", ["--user", "is-active", BOOT_SERVICE_UNIT_FILE]);
163 + // A unit waiting out its Restart= delay is activating, with exit code 3.
164 + loaded = active.code === 0 || (active.code === 3 && active.stdout.trim() === "activating");
165 + if (!loaded) {
166 + const enabled = yield* run("systemctl", ["--user", "is-enabled", BOOT_SERVICE_UNIT_FILE]);
167 + if (enabled.code !== 0 || enabled.stdout.trim() !== "enabled") return undefined;
168 + }
169 + }
170 + // A deferred update names the staged runtime, not the loaded service's runtime.
171 + if (loaded && (yield* fs.exists(NodePath.join(runtimeDir, SERVICE_RESTART_PENDING_FILE)))) {
172 + return baseDir;
173 + }
174 + // Stable 0.1.0 shipped the ownership lock. Earlier lock-aware prereleases
175 + // are conservatively refused because older runtimes expose no capability marker.
176 + return compareExactServiceVersions(version, "0.1.0") < 0 ? baseDir : undefined;
177 + },
178 + Effect.orElseSucceed(() => undefined),
179 +);
180 +
181 /**
182 * Hold an exclusive lock on the state directory until the scope closes. The
183 * lock is an exclusive transaction on `server-owner.sqlite`, which never holds
@@ -137,6 +232,10 @@ export const acquireServerOwnership = Effect.fn("acquireServerOwnership")(functi
232 ) {
233 return yield* new ServerAlreadyRunningError({ stateDir });
234 }
235 + const olderServiceHome = yield* olderBootServiceHome(stateDir);
236 + if (olderServiceHome !== undefined) {
237 + return yield* new OlderBootServiceError({ baseDir: olderServiceHome });
238 + }
239
240 return {
241 publish: (state: PersistedServerRuntimeState) =>
apps/server/src/serverRuntimeState.test.ts
+292 -1
@@ -1,5 +1,6 @@
1 import { assert, describe, it } from "@effect/vitest";
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 +import * as HostProcess from "@t3tools/shared/HostProcess";
4 import * as Effect from "effect/Effect";
5 import * as FileSystem from "effect/FileSystem";
6 import * as Layer from "effect/Layer";
@@ -7,21 +8,147 @@ import * as Logger from "effect/Logger";
8 import * as Option from "effect/Option";
9 import * as Path from "effect/Path";
10 import * as References from "effect/References";
11 +import * as Runtime from "effect/Runtime";
12 import * as Schema from "effect/Schema";
13 +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
14
15 +import { renderBootServicePlist, renderBootServiceUnit } from "./cloud/bootService.ts";
16 +import { ServiceLauncherHostProcess } from "./cloud/serviceLauncherClient.ts";
17 +import { SERVICE_LAUNCHER_CONTEXT_ENV } from "./cloud/serviceProtocol.ts";
18 import * as ProcessRunner from "./processRunner.ts";
19 import * as ServerOwnership from "./serverOwnership.ts";
20 import * as ServerRuntimeState from "./serverRuntimeState.ts";
21
22 const isServerRuntimeStateError = Schema.is(ServerRuntimeState.ServerRuntimeStateError);
23
24 +const startBesideBootService = Effect.fn("test.startBesideBootService")(function* (input: {
25 + readonly platform: "darwin" | "linux";
26 + readonly outputs: Readonly<Record<string, { readonly code: number; readonly stdout?: string }>>;
27 + readonly unitServesOtherHome?: boolean;
28 + readonly restartPending?: boolean;
29 + readonly activeVersion?: string;
30 + readonly npmRuntime?: boolean;
31 + readonly missingServiceState?: boolean;
32 + readonly environment?: NodeJS.ProcessEnv;
33 + readonly connected?: boolean;
34 +}) {
35 + const fs = yield* FileSystem.FileSystem;
36 + const path = yield* Path.Path;
37 + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-owner-boot-service-" });
38 + const t3Home = path.join(root, ".t3");
39 + const serviceHome = input.unitServesOtherHome ? path.join(root, "other") : t3Home;
40 + for (const home of [t3Home, serviceHome]) {
41 + yield* fs.makeDirectory(path.join(home, "userdata"), { recursive: true });
42 + }
43 + yield* fs.makeDirectory(path.join(serviceHome, "runtime"));
44 + const activeVersion = input.activeVersion ?? "0.0.42";
45 + if (!input.missingServiceState) {
46 + yield* fs.writeFileString(
47 + path.join(serviceHome, "runtime", "service-state.json"),
48 + JSON.stringify({ protocol: input.npmRuntime ? 2 : 3, activeVersion }),
49 + );
50 + }
51 + if (input.npmRuntime) {
52 + const versionDir = path.join(serviceHome, "runtime", "versions", activeVersion);
53 + const entryPath = path.join(versionDir, "node_modules", "t3", "dist", "bin.mjs");
54 + yield* fs.makeDirectory(path.dirname(entryPath), { recursive: true });
55 + yield* fs.writeFileString(entryPath, "");
56 + }
57 +
58 + if (input.restartPending) {
59 + yield* fs.writeFileString(
60 + path.join(serviceHome, "runtime", ".restart-pending"),
61 + `${activeVersion}\n`,
62 + );
63 + }
64 + const plan = {
65 + program: input.npmRuntime
66 + ? ["/usr/bin/node", path.join(serviceHome, "runtime", "service-launcher.mjs")]
67 + : [],
68 + baseDir: serviceHome,
69 + logPath: "",
70 + unitPath: "",
71 + };
72 + const [unitPath, unit] =
73 + input.platform === "darwin"
74 + ? [
75 + path.join(root, "Library", "LaunchAgents", "com.t3tools.t3code.service.plist"),
76 + renderBootServicePlist(plan, { homeDir: root, environmentPath: "" }),
77 + ]
78 + : [
79 + path.join(root, ".config", "systemd", "user", "t3code.service"),
80 + renderBootServiceUnit(plan),
81 + ];
82 + yield* fs.makeDirectory(path.dirname(unitPath), { recursive: true });
83 + yield* fs.writeFileString(unitPath, unit);
84 +
85 + const probes: string[] = [];
86 + const runner = ProcessRunner.ProcessRunner.of({
87 + run: (run) =>
88 + Effect.gen(function* () {
89 + const probe = `${path.basename(run.command)} ${run.args.find((arg) => !arg.startsWith("--"))}`;
90 + probes.push(probe);
91 + const output = input.outputs[probe];
92 + return yield* output === undefined
93 + ? Effect.fail(
94 + new ProcessRunner.ProcessSpawnError({
95 + command: run.command,
96 + argumentCount: run.args.length,
97 + cause: new Error("not found"),
98 + }),
99 + )
100 + : Effect.succeed({
101 + stdout: output.stdout ?? "",
102 + stderr: "",
103 + code: ChildProcessSpawner.ExitCode(output.code),
104 + timedOut: false,
105 + stdoutTruncated: false,
106 + stderrTruncated: false,
107 + stdoutInvalidUtf8: false,
108 + stderrInvalidUtf8: false,
109 + });
110 + }),
111 + });
112 + const result = yield* Effect.scoped(
113 + ServerOwnership.acquireServerOwnership(path.join(t3Home, "userdata", "server-runtime.json")),
114 + ).pipe(
115 + Effect.provideService(ProcessRunner.ProcessRunner, runner),
116 + Effect.provideService(HostProcess.Platform, input.platform),
117 + Effect.provideService(HostProcess.UserId, 501),
118 + Effect.provideService(HostProcess.HomeDirectory, root),
119 + Effect.provideService(HostProcess.Environment, input.environment ?? {}),
120 + Effect.provideService(ServiceLauncherHostProcess, {
121 + connected: input.connected ?? false,
122 + send: () => false,
123 + on: () => undefined,
124 + off: () => undefined,
125 + }),
126 + Effect.result,
127 + );
128 + assert.includeMembers(
129 + ["launchctl print", "launchctl print-disabled", "systemctl is-active", "systemctl is-enabled"],
130 + probes,
131 + );
132 + return { result, t3Home };
133 +});
134 +
135 interface CapturedLog {
136 readonly message: unknown;
137 readonly annotations: Readonly<Record<string, unknown>>;
138 }
139
140 describe("server ownership", () => {
24 - const layerOwnership = ProcessRunner.layer.pipe(Layer.provideMerge(NodeServices.layer));
141 + // An empty home, so no boot service unit installed on this machine is read.
142 + const layerOwnership = Layer.mergeAll(
143 + ProcessRunner.layer,
144 + Layer.effect(
145 + HostProcess.HomeDirectory,
146 + Effect.gen(function* () {
147 + return yield* (yield* FileSystem.FileSystem).makeTempDirectoryScoped();
148 + }),
149 + ),
150 + Layer.succeed(HostProcess.Environment, {}),
151 + ).pipe(Layer.provideMerge(NodeServices.layer));
152 const makeState = ServerRuntimeState.makePersistedServerRuntimeState({
153 config: { host: undefined, devUrl: undefined },
154 port: 3773,
@@ -115,6 +242,170 @@ describe("server ownership", () => {
242 assert.equal(Option.getOrThrow(remaining).ownerId, "other-owner");
243 }).pipe(Effect.provide(layerOwnership)),
244 );
245 +
246 + describe("beside an installed boot service", () => {
247 + it.effect("refuses an old active or scheduled service even without its runtime record", () =>
248 + Effect.gen(function* () {
249 + for (const fixture of [
250 + {
251 + platform: "darwin",
252 + outputs: { "launchctl print": { code: 0 } },
253 + },
254 + {
255 + platform: "darwin",
256 + outputs: {
257 + "launchctl print": { code: 113 },
258 + "launchctl print-disabled": {
259 + code: 0,
260 + stdout: '"com.t3tools.t3code.service" => false',
261 + },
262 + },
263 + },
264 + {
265 + platform: "linux",
266 + outputs: {
267 + // Restart= keeps an otherwise disabled service alive during its restart delay.
268 + "systemctl is-active": { code: 3, stdout: "activating\n" },
269 + "systemctl is-enabled": { code: 1, stdout: "disabled\n" },
270 + },
271 + },
272 + {
273 + platform: "linux",
274 + outputs: {
275 + "systemctl is-active": { code: 3, stdout: "inactive\n" },
276 + "systemctl is-enabled": { code: 0, stdout: "enabled\n" },
277 + },
278 + },
279 + {
280 + platform: "darwin",
281 + outputs: { "launchctl print": { code: 0 } },
282 + environment: { [SERVICE_LAUNCHER_CONTEXT_ENV]: "{}" },
283 + },
284 + ] as const) {
285 + const { result, t3Home } = yield* startBesideBootService(fixture);
286 + assert.equal(result._tag, "Failure");
287 + if (result._tag !== "Failure") return;
288 + assert.equal(result.failure._tag, "OlderBootServiceError");
289 + assert.equal(Runtime.getErrorExitCode(result.failure), 78);
290 + assert.include(result.failure.message, t3Home);
291 + assert.include(result.failure.message, "t3 update");
292 + assert.include(result.failure.message, "t3 service restart");
293 + assert.include(result.failure.message, "No server was stopped");
294 + }
295 + }).pipe(Effect.provide(NodeServices.layer)),
296 + );
297 +
298 + it.effect(
299 + "refuses an active npm-installed service with no standalone executable or runtime record",
300 + () =>
301 + Effect.gen(function* () {
302 + const { result } = yield* startBesideBootService({
303 + platform: "linux",
304 + activeVersion: "0.0.40",
305 + npmRuntime: true,
306 + outputs: {
307 + "systemctl is-active": { code: 0, stdout: "active\n" },
308 + },
309 + });
310 + assert.equal(result._tag, "Failure");
311 + if (result._tag !== "Failure") return;
312 + assert.equal(result.failure._tag, "OlderBootServiceError");
313 + assert.equal(Runtime.getErrorExitCode(result.failure), 78);
314 + }).pipe(Effect.provide(NodeServices.layer)),
315 + );
316 +
317 + it.effect("refuses while the loaded service has not restarted into its lock-aware update", () =>
318 + Effect.gen(function* () {
319 + const { result } = yield* startBesideBootService({
320 + platform: "darwin",
321 + restartPending: true,
322 + activeVersion: "0.1.0",
323 + outputs: {
324 + "launchctl print": { code: 0 },
325 + },
326 + });
327 + assert.equal(result._tag === "Failure" && result.failure._tag, "OlderBootServiceError");
328 + }).pipe(Effect.provide(NodeServices.layer)),
329 + );
330 +
331 + it.effect("allows lock-aware stable services that are loaded or stopped and enabled", () =>
332 + Effect.gen(function* () {
333 + for (const fixture of [
334 + {
335 + platform: "darwin",
336 + outputs: {
337 + "launchctl print": { code: 0 },
338 + },
339 + },
340 + {
341 + platform: "linux",
342 + outputs: {
343 + "systemctl is-active": { code: 3, stdout: "inactive\n" },
344 + "systemctl is-enabled": { code: 0, stdout: "enabled\n" },
345 + },
346 + },
347 + ] as const) {
348 + const { result } = yield* startBesideBootService({ ...fixture, activeVersion: "0.1.0" });
349 + assert.equal(result._tag, "Success");
350 + }
351 + }).pipe(Effect.provide(NodeServices.layer)),
352 + );
353 +
354 + it.effect("allows services that cannot compete for this home", () =>
355 + Effect.gen(function* () {
356 + const outputs = {
357 + "launchctl print": { code: 0 },
358 + };
359 + for (const fixture of [
360 + { platform: "darwin", outputs, unitServesOtherHome: true },
361 + {
362 + platform: "darwin",
363 + outputs,
364 + environment: { [SERVICE_LAUNCHER_CONTEXT_ENV]: "{}" },
365 + connected: true,
366 + },
367 + {
368 + platform: "darwin",
369 + outputs: {
370 + "launchctl print": { code: 113 },
371 + "launchctl print-disabled": {
372 + code: 0,
373 + stdout: '"com.t3tools.t3code.service" => disabled',
374 + },
375 + },
376 + },
377 + {
378 + platform: "linux",
379 + outputs: {
380 + "systemctl is-active": { code: 3, stdout: "inactive\n" },
381 + "systemctl is-enabled": { code: 1, stdout: "disabled\n" },
382 + },
383 + },
384 + ] as const) {
385 + const { result } = yield* startBesideBootService(fixture);
386 + assert.equal(result._tag, "Success");
387 + }
388 + }).pipe(Effect.provide(NodeServices.layer)),
389 + );
390 +
391 + it.effect("allows startup when the service configuration or manager is unavailable", () =>
392 + Effect.gen(function* () {
393 + for (const fixture of [
394 + { outputs: {} },
395 + {
396 + outputs: {
397 + "launchctl print": { code: 113 },
398 + "launchctl print-disabled": { code: 1 },
399 + },
400 + },
401 + { outputs: { "launchctl print": { code: 0 } }, missingServiceState: true },
402 + ]) {
403 + const { result } = yield* startBesideBootService({ platform: "darwin", ...fixture });
404 + assert.equal(result._tag, "Success");
405 + }
406 + }).pipe(Effect.provide(NodeServices.layer)),
407 + );
408 + });
409 });
410
411 describe("serverRuntimeState", () => {