@devries-cameron20 / t3code-1 / commits / 60ec7fc7f4
Fork 0

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

fix(desktop): check T3 home ownership before starting the local backend (#34512)

Julius Marminge committed Nov 11, 2026 at 16:01 UTC 60ec7fc7f4f9fd3799f33f10dea58780e6473b8e
6 files changed +251 -6
apps/desktop/src/app/DesktopApp.test.ts
+1
@@ -109,6 +109,7 @@ it.effect.each([false, true])(
109 platform: "linux",
110 isDevelopment: false,
111 isPackaged: true,
112 + stateDir: "/isolated/userdata",
113 configuredBackendPort: Option.some(3773),
114 defaultDesktopSettings: { serverExposureMode: "local-only" },
115 } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]),
apps/desktop/src/app/DesktopApp.ts
+17
@@ -21,6 +21,7 @@ import * as DesktopWindow from "../window/DesktopWindow.ts";
21 import * as PreviewPasskeys from "../preview/Passkeys.ts";
22 import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
23 import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
24 +import * as DesktopHomeOwner from "../backend/DesktopHomeOwner.ts";
25 import * as DesktopEnvironment from "./DesktopEnvironment.ts";
26 import * as DesktopLegacyLocalStorage from "./DesktopLegacyLocalStorage.ts";
27 import * as DesktopLifecycle from "./DesktopLifecycle.ts";
@@ -223,6 +224,22 @@ const bootstrap = Effect.gen(function* () {
224 return yield* new DesktopDevelopmentBackendPortRequiredError();
225 }
226
227 + // A backend started while another server holds this home's lock can only exit with code 78.
228 + if (
229 + !(settings.wslOnly && settings.wslBackendEnabled) &&
230 + (yield* DesktopHomeOwner.isHomeOwnershipLocked())
231 + ) {
232 + const owner = yield* DesktopHomeOwner.readLiveHomeOwner();
233 + yield* logBootstrapWarning("bootstrap found another server owning the T3 home", {
234 + owner: Option.getOrNull(owner),
235 + });
236 + yield* (yield* ElectronDialog.ElectronDialog).showErrorBox(
237 + "This T3 home is unavailable",
238 + DesktopHomeOwner.homeOwnedMessage(owner),
239 + );
240 + return yield* (yield* ElectronApp.ElectronApp).quit;
241 + }
242 +
243 const backendPortSelection = yield* resolveDesktopBackendPort(environment.configuredBackendPort);
244 const backendPort = backendPortSelection.port;
245 yield* logBootstrapInfo(
apps/desktop/src/backend/DesktopBackendPool.test.ts
+19
@@ -1,3 +1,4 @@
1 +import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { assert, describe, it } from "@effect/vitest";
3 import * as Deferred from "effect/Deferred";
4 import * as Duration from "effect/Duration";
@@ -8,12 +9,15 @@ import * as TestClock from "effect/testing/TestClock";
9 import * as FileSystem from "effect/FileSystem";
10 import * as Layer from "effect/Layer";
11 import * as Option from "effect/Option";
12 +import * as Path from "effect/Path";
13 import * as Ref from "effect/Ref";
14 import * as Sink from "effect/Sink";
15 import * as Stream from "effect/Stream";
16 import { HttpClient, HttpClientResponse } from "effect/http";
17 import { ChildProcessSpawner } from "effect/process";
18
19 +import * as DesktopConfig from "../app/DesktopConfig.ts";
20 +import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
21 import * as DesktopObservability from "../app/DesktopObservability.ts";
22 import * as DesktopState from "../app/DesktopState.ts";
23 import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
@@ -112,6 +116,7 @@ function layerPool(
116 Layer.provideMerge(
117 Layer.mergeAll(
118 FileSystem.layerNoop({ exists: () => Effect.succeed(true) }),
119 + Path.layer,
120 backend?.layer ??
121 Layer.succeed(
122 ChildProcessSpawner.ChildProcessSpawner,
@@ -156,6 +161,20 @@ function layerPool(
161 currentBootstrapToken: Effect.die("unexpected bootstrap token read"),
162 } satisfies DesktopBackendConfiguration.DesktopBackendConfiguration["Service"]),
163 DesktopAppSettings.layerTest(),
164 + DesktopEnvironment.layer({
165 + dirname: "/repo/apps/desktop/src",
166 + homeDirectory: "/home/test",
167 + platform: "linux",
168 + processArch: "x64",
169 + appVersion: "0.0.0",
170 + appPath: "/repo",
171 + isPackaged: true,
172 + resourcesPath: "/missing/resources",
173 + runningUnderArm64Translation: false,
174 + }).pipe(
175 + Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))),
176 + Layer.orDie,
177 + ),
178 DesktopState.layer,
179 DesktopWslEnvironment.layerTest(),
180 ElectronDialog.layer,
apps/desktop/src/backend/DesktopBackendPool.ts
+16 -6
@@ -4,6 +4,7 @@ import * as Effect from "effect/Effect";
4 import * as Exit from "effect/Exit";
5 import * as Layer from "effect/Layer";
6 import * as Option from "effect/Option";
7 +import * as Path from "effect/Path";
8 import * as Schema from "effect/Schema";
9 import * as Scope from "effect/Scope";
10 import * as SubscriptionRef from "effect/SubscriptionRef";
@@ -15,6 +16,8 @@ import { ChildProcessSpawner } from "effect/process";
16
17 import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
18 import * as DesktopBackendManager from "./DesktopBackendManager.ts";
19 +import * as DesktopHomeOwner from "./DesktopHomeOwner.ts";
20 +import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
21 import * as DesktopObservability from "../app/DesktopObservability.ts";
22 import * as DesktopState from "../app/DesktopState.ts";
23 import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
@@ -112,6 +115,9 @@ export const layer = Layer.effect(
115 // Parent instance scopes to the pool so shutdown runs stop finalizers before the OS kills backends.
116 const layerScope = yield* Scope.Scope;
117 const factoryContext = yield* Effect.context<BackendInstanceFactoryRequirements>();
118 + const homeOwnerContext = yield* Effect.context<
119 + FileSystem.FileSystem | Path.Path | DesktopEnvironment.DesktopEnvironment
120 + >();
121
122 // Persist fatal Windows fallbacks; transient transport failures must preserve the user's WSL preference.
123 const handlePrimaryPreflightFailure = Effect.fn("desktop.backendPool.primaryPreflightFailed")(
@@ -174,12 +180,16 @@ export const layer = Layer.effect(
180 onShutdown: () => desktopWindow.handleBackendNotReady,
181 onPreflightFailed: handlePrimaryPreflightFailure,
182 onStateDirOwned: () =>
177 - electronDialog
178 - .showErrorBox(
179 - "This T3 home is unavailable",
180 - "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.",
181 - )
182 - .pipe(Effect.andThen(electronApp.quit)),
183 + DesktopHomeOwner.readLiveHomeOwner().pipe(
184 + Effect.flatMap((owner) =>
185 + electronDialog.showErrorBox(
186 + "This T3 home is unavailable",
187 + DesktopHomeOwner.homeOwnedMessage(owner),
188 + ),
189 + ),
190 + Effect.provideContext(homeOwnerContext),
191 + Effect.andThen(electronApp.quit),
192 + ),
193 });
194
195 const instancesRef = yield* SynchronizedRef.make<
apps/desktop/src/backend/DesktopHomeOwner.test.ts new
+110
@@ -0,0 +1,110 @@
1 +import * as NodeSqlite from "node:sqlite";
2 +
3 +import * as NodeServices from "@effect/platform-node/NodeServices";
4 +import { assert, describe, it } from "@effect/vitest";
5 +import * as Effect from "effect/Effect";
6 +import * as FileSystem from "effect/FileSystem";
7 +import * as Layer from "effect/Layer";
8 +import * as Option from "effect/Option";
9 +import * as Path from "effect/Path";
10 +
11 +import * as DesktopConfig from "../app/DesktopConfig.ts";
12 +import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
13 +import * as DesktopHomeOwner from "./DesktopHomeOwner.ts";
14 +
15 +const withTempHome = <A, E>(
16 + run: (
17 + userdata: string,
18 + ) => Effect.Effect<
19 + A,
20 + E,
21 + DesktopEnvironment.DesktopEnvironment | FileSystem.FileSystem | Path.Path
22 + >,
23 +) =>
24 + Effect.gen(function* () {
25 + const fs = yield* FileSystem.FileSystem;
26 + const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-desktop-home-owner-" });
27 + yield* fs.makeDirectory(`${home}/userdata`, { recursive: true });
28 + return yield* run(`${home}/userdata`).pipe(
29 + Effect.provide(
30 + DesktopEnvironment.layer({
31 + dirname: "/repo/apps/desktop/src",
32 + homeDirectory: home,
33 + platform: "linux",
34 + processArch: "x64",
35 + appVersion: "0.0.0",
36 + appPath: "/repo",
37 + isPackaged: true,
38 + resourcesPath: "/missing/resources",
39 + runningUnderArm64Translation: false,
40 + }).pipe(
41 + Layer.provide(
42 + Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: home })),
43 + ),
44 + ),
45 + ),
46 + );
47 + }).pipe(Effect.provide(NodeServices.layer));
48 +
49 +const readOwnerWithRuntimeFile = (contents: string | undefined) =>
50 + withTempHome((userdata) =>
51 + Effect.gen(function* () {
52 + if (contents !== undefined) {
53 + yield* (yield* FileSystem.FileSystem).writeFileString(
54 + `${userdata}/server-runtime.json`,
55 + contents,
56 + );
57 + }
58 + return yield* DesktopHomeOwner.readLiveHomeOwner();
59 + }),
60 + );
61 +
62 +describe("DesktopHomeOwner.readLiveHomeOwner", () => {
63 + it.effect("reports a live server recorded in server-runtime.json", () =>
64 + Effect.gen(function* () {
65 + const owner = yield* readOwnerWithRuntimeFile(
66 + JSON.stringify({
67 + version: 1,
68 + pid: process.pid,
69 + port: 3790,
70 + origin: "http://127.0.0.1:3790",
71 + startedAt: "2026-01-01T00:00:00.000Z",
72 + serverVersion: "1.2.3",
73 + }),
74 + );
75 + assert.deepStrictEqual(
76 + owner,
77 + Option.some({ pid: process.pid, port: 3790, serverVersion: "1.2.3" }),
78 + );
79 + assert.include(
80 + DesktopHomeOwner.homeOwnedMessage(owner),
81 + `PID ${process.pid}, port 3790, version 1.2.3`,
82 + );
83 + }),
84 + );
85 +
86 + it.effect("ignores a missing, malformed or dead owner record", () =>
87 + Effect.gen(function* () {
88 + assert.isTrue(Option.isNone(yield* readOwnerWithRuntimeFile(undefined)));
89 + assert.isTrue(Option.isNone(yield* readOwnerWithRuntimeFile("{not json")));
90 + assert.isTrue(
91 + Option.isNone(yield* readOwnerWithRuntimeFile(JSON.stringify({ pid: 0, port: 3790 }))),
92 + );
93 + }),
94 + );
95 +});
96 +
97 +describe("DesktopHomeOwner.isHomeOwnershipLocked", () => {
98 + it.effect("reports the ownership lock only while a server holds it", () =>
99 + withTempHome((userdata) =>
100 + Effect.gen(function* () {
101 + assert.isFalse(yield* DesktopHomeOwner.isHomeOwnershipLocked());
102 + const lock = new NodeSqlite.DatabaseSync(`${userdata}/server-owner.sqlite`);
103 + lock.exec("BEGIN EXCLUSIVE;");
104 + assert.isTrue(yield* DesktopHomeOwner.isHomeOwnershipLocked());
105 + lock.close();
106 + assert.isFalse(yield* DesktopHomeOwner.isHomeOwnershipLocked());
107 + }),
108 + ),
109 + );
110 +});
apps/desktop/src/backend/DesktopHomeOwner.ts new
+88
@@ -0,0 +1,88 @@
1 +// @effect-diagnostics nodeBuiltinImport:off - Probes the server's native SQLite ownership lock.
2 +import * as NodeSqlite from "node:sqlite";
3 +
4 +import * as Effect from "effect/Effect";
5 +import * as FileSystem from "effect/FileSystem";
6 +import * as Option from "effect/Option";
7 +import * as Path from "effect/Path";
8 +import * as Schema from "effect/Schema";
9 +
10 +import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
11 +
12 +// The fields of the server's `server-runtime.json` that identify the owner of a T3 home.
13 +const HomeOwnerRuntimeState = Schema.Struct({
14 + pid: Schema.Int,
15 + port: Schema.Int,
16 + serviceManaged: Schema.optional(Schema.Boolean),
17 + serverVersion: Schema.optional(Schema.String),
18 +});
19 +export type HomeOwner = typeof HomeOwnerRuntimeState.Type;
20 +
21 +const decodeHomeOwner = Schema.decodeUnknownOption(Schema.fromJsonString(HomeOwnerRuntimeState));
22 +
23 +/** Signal 0 only probes existence; EPERM still means alive. */
24 +const isProcessAlive = (pid: number): boolean => {
25 + if (!Number.isInteger(pid) || pid <= 0) return false;
26 + try {
27 + process.kill(pid, 0);
28 + return true;
29 + } catch (error) {
30 + return error instanceof Error && "code" in error && error.code === "EPERM";
31 + }
32 +};
33 +
34 +/**
35 + * Whether a server holds the T3 home's ownership lock (an exclusive transaction on
36 + * `server-owner.sqlite`). A read-only read is refused with SQLITE_BUSY only while it is held.
37 + */
38 +export const isHomeOwnershipLocked = Effect.fn("DesktopHomeOwner.isHomeOwnershipLocked")(
39 + function* () {
40 + const path = yield* Path.Path;
41 + const { stateDir } = yield* DesktopEnvironment.DesktopEnvironment;
42 + const lockPath = path.join(stateDir, "server-owner.sqlite");
43 + return yield* Effect.sync(() => {
44 + try {
45 + const db = new NodeSqlite.DatabaseSync(lockPath, { readOnly: true });
46 + try {
47 + db.exec("PRAGMA busy_timeout = 0");
48 + db.prepare("SELECT count(*) FROM sqlite_master").get();
49 + return false;
50 + } finally {
51 + db.close();
52 + }
53 + } catch (cause) {
54 + // Anything but SQLITE_BUSY (a missing file included) leaves the decision to the backend.
55 + return cause instanceof Error && "errcode" in cause && cause.errcode === 5;
56 + }
57 + });
58 + },
59 +);
60 +
61 +/** The live server recorded as owning the desktop's T3 home. Only call once the ownership lock is known held: a live PID alone may be reused. */
62 +export const readLiveHomeOwner = Effect.fn("DesktopHomeOwner.readLiveHomeOwner")(function* () {
63 + const fs = yield* FileSystem.FileSystem;
64 + const path = yield* Path.Path;
65 + const { stateDir } = yield* DesktopEnvironment.DesktopEnvironment;
66 + const raw = yield* fs
67 + .readFileString(path.join(stateDir, "server-runtime.json"))
68 + .pipe(Effect.option);
69 + return Option.flatMap(raw, decodeHomeOwner).pipe(
70 + Option.filter((owner) => isProcessAlive(owner.pid)),
71 + );
72 +});
73 +
74 +export const homeOwnedMessage = (owner: Option.Option<HomeOwner>): string =>
75 + Option.match(owner, {
76 + onNone: () =>
77 + "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.",
78 + onSome: (owner) => {
79 + const kind = owner.serviceManaged
80 + ? "The T3 Code background service"
81 + : "Another T3 Code server (for example `t3 serve`, or one started over SSH)";
82 + const version = owner.serverVersion ? `, version ${owner.serverVersion}` : "";
83 + const stop = owner.serviceManaged
84 + ? "Stop it with `t3 service uninstall`, passing `--base-dir` with this T3 home"
85 + : "If a T3 Code app on another machine started it over SSH, that app restarts it: remove or disconnect that SSH environment there, or quit that app. Then stop the server";
86 + return `${kind} is using this T3 home (PID ${owner.pid}, port ${owner.port}${version}). ${stop}, and reopen T3 Code. You can also set a separate T3CODE_HOME and pair with the running server.`;
87 + },
88 + });