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 21, 21:00 UTC
fix(cli): thread, project, and connect commands skip a server that is gone (#34529)
Co-authored-by: maria-rcks <254055478+maria-rcks@users.noreply.github.com>
maria committed
Nov 12, 2026 at 00:24 UTC
35557e648f8db1dbd27f4dfc504c4ea45003a586
7 files changed
+128
-13
apps/server/src/cli/connect.test.ts
+35
-7
@@ -16,6 +16,7 @@ import * as TestConsole from "effect/testing/TestConsole";
16
import { Command } from "effect/cli";
17
18
import { makeCli } from "../binCli.ts";
19
+import { CLOUD_CLI_DESIRED_LINK_SECRET } from "../cloud/CliState.ts";
20
import {
21
makePersistedServerRuntimeState,
22
persistServerRuntimeState,
@@ -59,9 +60,12 @@ it.effect("does not install the relay client when the user declines the managed
60
);
61
62
it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer))(
62
- "t3 connect unlink",
63
+ "t3 connect unlink and status",
64
(it) => {
64
- const runUnlink = (recordedPid: number, options?: { readonly portFreed?: boolean }) =>
65
+ const runConnect = (
66
+ recordedPid: number,
67
+ options?: { readonly portFreed?: boolean; readonly command?: "unlink" | "status" },
68
+ ) =>
69
Effect.gen(function* () {
70
const requests: Array<string> = [];
71
const warnings: Array<string> = [];
@@ -96,10 +100,18 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer))
100
path: `${baseDir}/userdata/server-runtime.json`,
101
state: { ...state, pid: recordedPid },
102
});
103
+ if (options?.command === "status") {
104
+ // Status asks the server for reachability only for a managed link.
105
+ yield* fs.makeDirectory(`${baseDir}/userdata/secrets`, { recursive: true });
106
+ yield* fs.writeFileString(
107
+ `${baseDir}/userdata/secrets/${CLOUD_CLI_DESIRED_LINK_SECRET}.bin`,
108
+ "managed",
109
+ );
110
+ }
111
112
yield* Command.runWith(makeCli({ cloudEnabled: true }), { version: "0.0.0" })([
113
"connect",
102
- "unlink",
114
+ options?.command ?? "unlink",
115
"--base-dir",
116
baseDir,
117
]).pipe(
@@ -128,7 +140,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer))
140
141
it.effect("does not tell the user to restart a server that is gone", () =>
142
Effect.gen(function* () {
131
- const { printed, warnings } = yield* runUnlink(deadPid, { portFreed: true });
143
+ const { printed, warnings } = yield* runConnect(deadPid, { portFreed: true });
144
145
assert.include(printed, "T3 Connect is disabled locally.");
146
assert.notInclude(warnings.join("\n"), "Restart that server");
@@ -137,7 +149,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer))
149
150
it.effect("warns that a server that is gone may have left its connector running", () =>
151
Effect.gen(function* () {
140
- const { warnings } = yield* runUnlink(deadPid, { portFreed: true });
152
+ const { warnings } = yield* runConnect(deadPid, { portFreed: true });
153
154
assert.include(warnings.join("\n"), "its cloudflared process may still be running");
155
}),
@@ -145,15 +157,31 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer))
157
158
it.effect("does not send a token to whatever took over a dead server's port", () =>
159
Effect.gen(function* () {
148
- const { requests } = yield* runUnlink(deadPid);
160
+ const { requests } = yield* runConnect(deadPid);
161
+
162
+ assert.deepEqual(requests, []);
163
+ }),
164
+ );
165
+
166
+ it.effect("status does not send a token to whatever took over a dead server's port", () =>
167
+ Effect.gen(function* () {
168
+ const { requests } = yield* runConnect(deadPid, { command: "status" });
169
170
assert.deepEqual(requests, []);
171
}),
172
);
173
174
+ it.effect("status asks a running server to check reachability", () =>
175
+ Effect.gen(function* () {
176
+ const { requests } = yield* runConnect(process.pid, { command: "status" });
177
+
178
+ assert.deepEqual(requests, ["POST /api/connect/reachability"]);
179
+ }),
180
+ );
181
+
182
it.effect("asks a running server to stop its tunnel", () =>
183
Effect.gen(function* () {
156
- const { requests, printed, warnings } = yield* runUnlink(process.pid);
184
+ const { requests, printed, warnings } = yield* runConnect(process.pid);
185
186
assert.deepEqual(requests, ["POST /api/connect/unlink"]);
187
assert.include(printed, "T3 Connect is disabled locally.");
apps/server/src/cli/connect.ts
+6
-2
@@ -50,7 +50,11 @@ import * as RelayTracing from "../cloud/relayTracing.ts";
50
import * as ServerConfig from "../config.ts";
51
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
52
import * as ExternalLauncher from "../process/externalLauncher.ts";
53
-import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
53
+import {
54
+ isProcessAlive,
55
+ readLiveServerRuntimeState,
56
+ readPersistedServerRuntimeState,
57
+} from "../serverRuntimeState.ts";
58
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
59
import { resolveCliCommand } from "./invocation.ts";
60
import * as CliService from "./service.ts";
@@ -339,7 +343,7 @@ const CLOUD_CLI_REACHABILITY_RETRY = Duration.seconds(5);
343
/** Asks the running server to check T3 Connect now. `null` when no server answers. */
344
const checkLiveReachability = Effect.fn("cloud.cli.check_live_reachability")(function* () {
345
const config = yield* ServerConfig.ServerConfig;
342
- const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);
346
+ const runtimeState = yield* readLiveServerRuntimeState(config.serverRuntimeStatePath);
347
if (Option.isNone(runtimeState)) return null;
348
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
349
return yield* withCloudCliSessionToken(environmentAuth, AuthRelayReadScope, (token) =>
apps/server/src/cli/project.test.ts
+31
@@ -194,6 +194,37 @@ it.effect.each(["snapshot", "mutation"] as const)(
194
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
195
);
196
197
+it.effect("does not send a token to whatever took over a dead server's port", () =>
198
+ Effect.gen(function* () {
199
+ const fs = yield* FileSystem.FileSystem;
200
+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-dead-project-cli-" });
201
+ const baseDir = NodePath.join(root, "state");
202
+ const workspaceRoot = NodePath.join(root, "workspace");
203
+ yield* fs.makeDirectory(workspaceRoot);
204
+ const state = yield* makePersistedServerRuntimeState({
205
+ config: { host: "127.0.0.1", devUrl: undefined },
206
+ port: 3_773,
207
+ });
208
+ yield* persistServerRuntimeState({
209
+ path: NodePath.join(baseDir, "userdata", "server-runtime.json"),
210
+ // Above Linux's PID ceiling, as in pair.test.ts: no process can hold it.
211
+ state: { ...state, pid: 4_194_305 },
212
+ });
213
+ let requests = 0;
214
+ const fetch: typeof globalThis.fetch = async () => {
215
+ requests++;
216
+ return Response.json({ projects: [], updatedAt: "2026-01-01T00:00:00.000Z" });
217
+ };
218
+
219
+ yield* runCli(["project", "add", workspaceRoot, "--base-dir", baseDir]).pipe(
220
+ Effect.provideService(FetchHttpClient.Fetch, fetch),
221
+ );
222
+
223
+ assert.equal(requests, 0);
224
+ assert.equal((yield* readProjects(baseDir)).projects[0]?.workspaceRoot, workspaceRoot);
225
+ }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
226
+);
227
+
228
const makeProjectLookupFixture = Effect.fn("ProjectCliTest.makeProjectLookupFixture")(function* () {
229
const fs = yield* FileSystem.FileSystem;
230
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-v2-project-lookup-" });
apps/server/src/cli/project.ts
+2
-2
@@ -39,7 +39,7 @@ import * as ServerSettings from "../serverSettings.ts";
39
import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
40
import {
41
clearPersistedServerRuntimeState,
42
- readPersistedServerRuntimeState,
42
+ readLiveServerRuntimeState,
43
} from "../serverRuntimeState.ts";
44
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
45
import { type CliAuthLocationFlags, projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
@@ -360,7 +360,7 @@ const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecu
360
environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"],
361
config: ServerConfig.ServerConfig["Service"],
362
) {
363
- const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);
363
+ const runtimeState = yield* readLiveServerRuntimeState(config.serverRuntimeStatePath);
364
if (Option.isNone(runtimeState)) {
365
return Option.none<{ readonly origin: string }>();
366
}
apps/server/src/cli/thread.test.ts
+39
@@ -136,6 +136,45 @@ it.effect(
136
),
137
);
138
139
+it.effect("does not sign in to whatever took over a dead server's port", () =>
140
+ Effect.gen(function* () {
141
+ const fs = yield* FileSystem.FileSystem;
142
+ const path = yield* Path.Path;
143
+ const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-thread-dead-server-" });
144
+ const state = yield* makePersistedServerRuntimeState({
145
+ config: { host: "127.0.0.1", devUrl: undefined },
146
+ port: 3_773,
147
+ });
148
+ yield* persistServerRuntimeState({
149
+ path: path.join(baseDir, "userdata", "server-runtime.json"),
150
+ // Above Linux's PID ceiling, as in pair.test.ts: no process can hold it.
151
+ state: { ...state, pid: 4_194_305 },
152
+ });
153
+ using session = vi
154
+ .spyOn(McpBridge, "mcpToolSession")
155
+ .mockReturnValue(Effect.die("no session should open"));
156
+
157
+ const error = yield* Command.runWith(threadCommand, { version: "0.0.0" })([
158
+ "list",
159
+ "--base-dir",
160
+ baseDir,
161
+ ]).pipe(Effect.flip);
162
+
163
+ assert.strictEqual(error._tag, "ThreadServerNotRunningError");
164
+ assert.strictEqual(session.mock.calls.length, 0);
165
+ }).pipe(
166
+ Effect.scoped,
167
+ Effect.provide(
168
+ Layer.mergeAll(
169
+ NodeServices.layer,
170
+ NodeCrypto.layer,
171
+ NetService.layer,
172
+ ConfigProvider.layer(ConfigProvider.fromEnv({ env: { T3CODE_PORT: "3773" } })),
173
+ ),
174
+ ),
175
+ ),
176
+);
177
+
178
/** Answers each tool call with the next scripted response for that tool. */
179
const scriptedTools = (script: Record<string, Array<unknown>>) => {
180
const calls: Array<{ readonly tool: string; readonly args: unknown }> = [];
apps/server/src/cli/thread.ts
+2
-2
@@ -31,7 +31,7 @@ import * as ServerConfig from "../config.ts";
31
import { mcpToolSession, type McpToolSession } from "../mcp/AcpMcpStdioBridge.ts";
32
import { expandHomePath } from "../os-jank.ts";
33
import * as ProcessRunner from "../processRunner.ts";
34
-import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
34
+import { readLiveServerRuntimeState } from "../serverRuntimeState.ts";
35
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
36
37
/**
@@ -211,7 +211,7 @@ const withThreadTools = Effect.fn("cli.thread.withThreadTools")(function* <A, E,
211
const logLevel = yield* GlobalFlag.LogLevel;
212
const config = yield* resolveCliAuthConfig(flags, logLevel);
213
return yield* Effect.gen(function* () {
214
- const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);
214
+ const runtimeState = yield* readLiveServerRuntimeState(config.serverRuntimeStatePath);
215
if (Option.isNone(runtimeState)) {
216
return yield* new ThreadServerNotRunningError({ baseDir: config.baseDir });
217
}
apps/server/src/serverRuntimeState.ts
+13
@@ -192,3 +192,16 @@ export const readPersistedServerRuntimeState = Effect.fn(
192
),
193
}),
194
);
195
+
196
+/**
197
+ * The runtime record, only while its server process is alive. Read this before sending
198
+ * credentials to the recorded origin: a killed server leaves its record behind, and
199
+ * another process may own its port by now.
200
+ */
201
+export const readLiveServerRuntimeState = Effect.fn(
202
+ "serverRuntimeState.readLiveServerRuntimeState",
203
+)((path: string) =>
204
+ readPersistedServerRuntimeState(path).pipe(
205
+ Effect.map(Option.filter((state) => isProcessAlive(state.pid))),
206
+ ),
207
+);