@devries-cameron20 / t3code Mirror · read-only / commits / 5b4f2aa153
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, 12:00 UTC

fix(server): report a deleted or replaced ownership lock (#21886)

Co-authored-by: maria-rcks <maria@kuuro.net>

Scott Norteman committed Oct 29, 2026 at 14:06 UTC 5b4f2aa1532730d4dd51d2cb48a57ff74a0f54eb
2 files changed +140 -5
apps/server/src/serverOwnership.ts
+49 -5
@@ -44,7 +44,7 @@ export class ServerAlreadyRunningError extends Schema.TaggedError<ServerAlreadyR
44 override readonly [Runtime.errorExitCode] = SERVER_EXIT_CODE_STATE_DIR_OWNED;
45
46 override get message(): string {
47 - return `A T3 Code server already owns ${this.stateDir}. Stop that server, or use a separate T3 home and pair with it, then retry. No server was stopped.`;
47 + return `A T3 Code server already owns ${this.stateDir}. Stop that server, or use a separate T3 home and pair with it, then retry. No server was stopped. server-owner.sqlite is the ownership lock; do not delete it while a server is running.`;
48 }
49 }
50
@@ -188,25 +188,36 @@ export const acquireServerOwnership = Effect.fn("acquireServerOwnership")(functi
188 const ownerId = yield* crypto
189 .randomUUIDv4()
190 .pipe(Effect.mapError((cause) => new ServerOwnershipError({ stateDir, cause })));
191 - yield* Effect.acquireRelease(
191 + const lockPath = NodePath.join(stateDir, "server-owner.sqlite");
192 + const lock = yield* Effect.acquireRelease(
193 Effect.try({
194 try: () => {
195 NodeFS.mkdirSync(stateDir, { recursive: true });
195 - const db = new NodeSqlite.DatabaseSync(NodePath.join(stateDir, "server-owner.sqlite"));
196 + let before = NodeFS.statSync(lockPath, { bigint: true, throwIfNoEntry: false });
197 + if (before === undefined) {
198 + NodeFS.closeSync(NodeFS.openSync(lockPath, "a", 0o644));
199 + before = NodeFS.statSync(lockPath, { bigint: true });
200 + }
201 + const db = new NodeSqlite.DatabaseSync(lockPath);
202 try {
203 db.exec("PRAGMA busy_timeout = 0; BEGIN EXCLUSIVE;");
204 + const identity = NodeFS.statSync(lockPath, { bigint: true });
205 + return {
206 + db,
207 + identity,
208 + replacedDuringAcquire: before.dev !== identity.dev || before.ino !== identity.ino,
209 + };
210 } catch (cause) {
211 db.close();
212 throw cause;
213 }
202 - return db;
214 },
215 catch: (cause) =>
216 isSqliteBusy(cause)
217 ? new ServerAlreadyRunningError({ stateDir })
218 : new ServerOwnershipError({ stateDir, cause }),
219 }),
209 - (db) =>
220 + ({ db }) =>
221 readPersistedServerRuntimeState(statePath).pipe(
222 Effect.flatMap((state) =>
223 Option.isSome(state) && state.value.ownerId === ownerId
@@ -233,6 +244,39 @@ export const acquireServerOwnership = Effect.fn("acquireServerOwnership")(functi
244 return yield* new OlderBootServiceError({ baseDir: olderServiceHome });
245 }
246
247 + yield* Effect.gen(function* () {
248 + let lost = lock.replacedDuringAcquire;
249 + let statWarningLogged = false;
250 + while (!lost) {
251 + yield* Effect.sleep("5 seconds");
252 + // Closing another descriptor for this inode releases SQLite's POSIX locks. Stat by path only.
253 + const current = yield* Effect.sync(() => {
254 + try {
255 + return NodeFS.statSync(lockPath, { bigint: true, throwIfNoEntry: false });
256 + } catch (cause) {
257 + return cause instanceof Error && "code" in cause ? String(cause.code) : "unknown";
258 + }
259 + });
260 + if (typeof current === "string") {
261 + if (!statWarningLogged) {
262 + yield* Effect.logWarning(
263 + `Cannot check server ownership lock at ${lockPath} (${current}).`,
264 + );
265 + statWarningLogged = true;
266 + }
267 + continue;
268 + }
269 + statWarningLogged = false;
270 + lost =
271 + current === undefined ||
272 + current.dev !== lock.identity.dev ||
273 + current.ino !== lock.identity.ino;
274 + }
275 + yield* Effect.logError(
276 + `Server ownership lock at ${lockPath} was deleted or replaced. Another server may now share this T3 home. Stop any other server using this home, then restart this server. Do not delete server-owner.sqlite while a server is running.`,
277 + );
278 + }).pipe(Effect.forkScoped);
279 +
280 return {
281 publish: (state: PersistedServerRuntimeState) =>
282 persistServerRuntimeState({ path: statePath, state: { ...state, ownerId } }),
apps/server/src/serverRuntimeState.test.ts
+91
@@ -1,13 +1,20 @@
1 +// @effect-diagnostics nodeBuiltinImport:off - Injects a real file replacement during the native SQLite transaction.
2 +import * as NodeFS from "node:fs";
3 +import * as NodeSqlite from "node:sqlite";
4 +
5 import { assert, describe, it } from "@effect/vitest";
6 import * as NodeServices from "@effect/platform-node/NodeServices";
7 import * as HostProcess from "@t3tools/shared/HostProcess";
8 import * as Effect from "effect/Effect";
9 import * as FileSystem from "effect/FileSystem";
10 import * as Layer from "effect/Layer";
11 +import * as Logger from "effect/Logger";
12 import * as Option from "effect/Option";
13 import * as Path from "effect/Path";
14 import * as Runtime from "effect/Runtime";
15 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
16 +import * as TestClock from "effect/testing/TestClock";
17 +import { vi } from "vite-plus/test";
18
19 import { renderBootServicePlist, renderBootServiceUnit } from "./cloud/bootService.ts";
20 import { ServiceLauncherHostProcess } from "./cloud/serviceLauncherClient.ts";
@@ -179,6 +186,7 @@ describe("server ownership", () => {
186 Effect.flip,
187 );
188 assert.equal(refused._tag, "ServerAlreadyRunningError");
189 + assert.include(refused.message, "do not delete it while a server is running");
190 assert.equal(yield* fs.readFileString(statePath), before);
191 }),
192 );
@@ -187,6 +195,89 @@ describe("server ownership", () => {
195 }).pipe(Effect.provide(layerOwnership)),
196 );
197
198 + describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("lock file checks", () => {
199 + it.effect.each([
200 + "unchanged",
201 + "unlink",
202 + "replace",
203 + "during acquisition",
204 + "first acquisition",
205 + // Root bypasses directory permissions, so chmod cannot force EACCES.
206 + ...(process.getuid?.() === 0 ? [] : (["stat error"] as const)),
207 + ] as const)("monitors ownership after %s", (operation) => {
208 + const messages: unknown[] = [];
209 + const warnings: unknown[] = [];
210 + const logger = Logger.make(({ message, logLevel }) =>
211 + (logLevel === "Warn" ? warnings : messages).push(message),
212 + );
213 + return Effect.gen(function* () {
214 + const fs = yield* FileSystem.FileSystem;
215 + const path = yield* Path.Path;
216 + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-owner-lost-" });
217 + const statePath = path.join(root, "server-runtime.json");
218 + const lockPath = path.join(root, "server-owner.sqlite");
219 + const replacement = path.join(root, "replacement.sqlite");
220 + if (operation === "during acquisition" || operation === "first acquisition") {
221 + if (operation === "during acquisition") yield* fs.writeFileString(lockPath, "");
222 + yield* fs.writeFileString(replacement, "");
223 + const exec = NodeSqlite.DatabaseSync.prototype.exec;
224 + yield* Effect.acquireRelease(
225 + Effect.sync(() =>
226 + vi.spyOn(NodeSqlite.DatabaseSync.prototype, "exec").mockImplementationOnce(function (
227 + this: NodeSqlite.DatabaseSync,
228 + sql: string,
229 + ) {
230 + exec.call(this, sql);
231 + NodeFS.renameSync(replacement, lockPath);
232 + }),
233 + ),
234 + (spy) => Effect.sync(() => spy.mockRestore()),
235 + );
236 + }
237 + yield* ServerOwnership.acquireServerOwnership(statePath);
238 + if (operation === "unlink") {
239 + yield* fs.remove(lockPath);
240 + } else if (operation === "replace") {
241 + yield* fs.writeFileString(replacement, "");
242 + yield* fs.rename(replacement, lockPath);
243 + }
244 + if (operation === "stat error") {
245 + yield* fs.chmod(root, 0);
246 + yield* TestClock.adjust("15 seconds").pipe(
247 + Effect.ensuring(fs.chmod(root, 0o700).pipe(Effect.orDie)),
248 + );
249 + assert.deepEqual(warnings, [
250 + [`Cannot check server ownership lock at ${lockPath} (EACCES).`],
251 + ]);
252 + yield* TestClock.adjust("5 seconds");
253 + assert.deepEqual(messages, []);
254 + yield* fs.remove(lockPath);
255 + }
256 + yield* TestClock.adjust("5 seconds");
257 + const expected =
258 + operation === "unchanged"
259 + ? []
260 + : [
261 + [
262 + `Server ownership lock at ${lockPath} was deleted or replaced. Another server may now share this T3 home. Stop any other server using this home, then restart this server. Do not delete server-owner.sqlite while a server is running.`,
263 + ],
264 + ];
265 + assert.deepEqual(messages, expected);
266 + if (operation !== "unchanged") {
267 + yield* fs.remove(`${lockPath}-journal`, { force: true });
268 + yield* Effect.scoped(ServerOwnership.acquireServerOwnership(statePath));
269 + }
270 + yield* TestClock.adjust("15 seconds");
271 + assert.deepEqual(messages, expected);
272 + assert.lengthOf(warnings, operation === "stat error" ? 1 : 0);
273 + }).pipe(
274 + Effect.provide(
275 + Layer.merge(layerOwnership, Logger.layer([logger], { mergeWithExisting: false })),
276 + ),
277 + );
278 + });
279 + });
280 +
281 it.effect("refuses beside a live pre-lock server and ignores a stale record", () =>
282 Effect.gen(function* () {
283 const fs = yield* FileSystem.FileSystem;