Skip to content

Commit 6a06471

Browse files
committed
fix(cli): thread, project, and connect commands skip a server that is gone
1 parent f31ce3e commit 6a06471

7 files changed

Lines changed: 125 additions & 13 deletions

File tree

‎apps/server/src/cli/connect.test.ts‎

Lines changed: 35 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import * as TestConsole from "effect/testing/TestConsole";
1616
import { Command } from "effect/cli";
1717

1818
import { makeCli } from "../binCli.ts";
19+
import { CLOUD_CLI_DESIRED_LINK_SECRET } from "../cloud/CliState.ts";
1920
import {
2021
makePersistedServerRuntimeState,
2122
persistServerRuntimeState,
@@ -59,9 +60,12 @@ it.effect("does not install the relay client when the user declines the managed
5960
);
6061

6162
it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer))(
62-
"t3 connect unlink",
63+
"t3 connect unlink and status",
6364
(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+
) =>
6569
Effect.gen(function* () {
6670
const requests: Array<string> = [];
6771
const warnings: Array<string> = [];
@@ -96,10 +100,18 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer))
96100
path: `${baseDir}/userdata/server-runtime.json`,
97101
state: { ...state, pid: recordedPid },
98102
});
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+
}
99111

100112
yield* Command.runWith(makeCli({ cloudEnabled: true }), { version: "0.0.0" })([
101113
"connect",
102-
"unlink",
114+
options?.command ?? "unlink",
103115
"--base-dir",
104116
baseDir,
105117
]).pipe(
@@ -128,7 +140,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer))
128140

129141
it.effect("does not tell the user to restart a server that is gone", () =>
130142
Effect.gen(function* () {
131-
const { printed, warnings } = yield* runUnlink(deadPid, { portFreed: true });
143+
const { printed, warnings } = yield* runConnect(deadPid, { portFreed: true });
132144

133145
assert.include(printed, "T3 Connect is disabled locally.");
134146
assert.notInclude(warnings.join("\n"), "Restart that server");
@@ -137,23 +149,39 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer))
137149

138150
it.effect("warns that a server that is gone may have left its connector running", () =>
139151
Effect.gen(function* () {
140-
const { warnings } = yield* runUnlink(deadPid, { portFreed: true });
152+
const { warnings } = yield* runConnect(deadPid, { portFreed: true });
141153

142154
assert.include(warnings.join("\n"), "its cloudflared process may still be running");
143155
}),
144156
);
145157

146158
it.effect("does not send a token to whatever took over a dead server's port", () =>
147159
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" });
149169

150170
assert.deepEqual(requests, []);
151171
}),
152172
);
153173

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+
154182
it.effect("asks a running server to stop its tunnel", () =>
155183
Effect.gen(function* () {
156-
const { requests, printed, warnings } = yield* runUnlink(process.pid);
184+
const { requests, printed, warnings } = yield* runConnect(process.pid);
157185

158186
assert.deepEqual(requests, ["POST /api/connect/unlink"]);
159187
assert.include(printed, "T3 Connect is disabled locally.");

‎apps/server/src/cli/connect.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,11 @@ import * as RelayTracing from "../cloud/relayTracing.ts";
5050
import * as ServerConfig from "../config.ts";
5151
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
5252
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";
5458
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
5559
import { resolveCliCommand } from "./invocation.ts";
5660
import * as CliService from "./service.ts";
@@ -339,7 +343,7 @@ const CLOUD_CLI_REACHABILITY_RETRY = Duration.seconds(5);
339343
/** Asks the running server to check T3 Connect now. `null` when no server answers. */
340344
const checkLiveReachability = Effect.fn("cloud.cli.check_live_reachability")(function* () {
341345
const config = yield* ServerConfig.ServerConfig;
342-
const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);
346+
const runtimeState = yield* readLiveServerRuntimeState(config.serverRuntimeStatePath);
343347
if (Option.isNone(runtimeState)) return null;
344348
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
345349
return yield* withCloudCliSessionToken(environmentAuth, AuthRelayReadScope, (token) =>

‎apps/server/src/cli/project.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,37 @@ it.effect.each(["snapshot", "mutation"] as const)(
194194
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
195195
);
196196

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+
197228
const makeProjectLookupFixture = Effect.fn("ProjectCliTest.makeProjectLookupFixture")(function* () {
198229
const fs = yield* FileSystem.FileSystem;
199230
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-v2-project-lookup-" });

‎apps/server/src/cli/project.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ import * as ServerSettings from "../serverSettings.ts";
3939
import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
4040
import {
4141
clearPersistedServerRuntimeState,
42-
readPersistedServerRuntimeState,
42+
readLiveServerRuntimeState,
4343
} from "../serverRuntimeState.ts";
4444
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
4545
import { type CliAuthLocationFlags, projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
@@ -360,7 +360,7 @@ const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecu
360360
environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"],
361361
config: ServerConfig.ServerConfig["Service"],
362362
) {
363-
const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);
363+
const runtimeState = yield* readLiveServerRuntimeState(config.serverRuntimeStatePath);
364364
if (Option.isNone(runtimeState)) {
365365
return Option.none<{ readonly origin: string }>();
366366
}

‎apps/server/src/cli/thread.test.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,45 @@ it.effect(
134134
),
135135
);
136136

137+
it.effect("does not sign in to whatever took over a dead server's port", () =>
138+
Effect.gen(function* () {
139+
const fs = yield* FileSystem.FileSystem;
140+
const path = yield* Path.Path;
141+
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-thread-dead-server-" });
142+
const state = yield* makePersistedServerRuntimeState({
143+
config: { host: "127.0.0.1", devUrl: undefined },
144+
port: 3_773,
145+
});
146+
yield* persistServerRuntimeState({
147+
path: path.join(baseDir, "userdata", "server-runtime.json"),
148+
// Above Linux's PID ceiling, as in pair.test.ts: no process can hold it.
149+
state: { ...state, pid: 4_194_305 },
150+
});
151+
using session = vi
152+
.spyOn(McpBridge, "mcpToolSession")
153+
.mockReturnValue(Effect.die("no session should open"));
154+
155+
const error = yield* Command.runWith(threadCommand, { version: "0.0.0" })([
156+
"list",
157+
"--base-dir",
158+
baseDir,
159+
]).pipe(Effect.flip);
160+
161+
assert.strictEqual(error._tag, "ThreadServerNotRunningError");
162+
assert.strictEqual(session.mock.calls.length, 0);
163+
}).pipe(
164+
Effect.scoped,
165+
Effect.provide(
166+
Layer.mergeAll(
167+
NodeServices.layer,
168+
NodeCrypto.layer,
169+
NetService.layer,
170+
ConfigProvider.layer(ConfigProvider.fromEnv({ env: { T3CODE_PORT: "3773" } })),
171+
),
172+
),
173+
),
174+
);
175+
137176
/** Answers each tool call with the next scripted response for that tool. */
138177
const scriptedTools = (script: Record<string, Array<unknown>>) => {
139178
const calls: Array<{ readonly tool: string; readonly args: unknown }> = [];

‎apps/server/src/cli/thread.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
3030
import * as ServerConfig from "../config.ts";
3131
import { mcpToolSession, type McpToolSession } from "../mcp/AcpMcpStdioBridge.ts";
3232
import { expandHomePath } from "../os-jank.ts";
33-
import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
33+
import { readLiveServerRuntimeState } from "../serverRuntimeState.ts";
3434
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
3535

3636
/**
@@ -210,7 +210,7 @@ const withThreadTools = Effect.fn("cli.thread.withThreadTools")(function* <A, E,
210210
const logLevel = yield* GlobalFlag.LogLevel;
211211
const config = yield* resolveCliAuthConfig(flags, logLevel);
212212
return yield* Effect.gen(function* () {
213-
const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);
213+
const runtimeState = yield* readLiveServerRuntimeState(config.serverRuntimeStatePath);
214214
if (Option.isNone(runtimeState)) {
215215
return yield* new ThreadServerNotRunningError({ baseDir: config.baseDir });
216216
}

‎apps/server/src/serverRuntimeState.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,3 +192,13 @@ export const readPersistedServerRuntimeState = Effect.fn(
192192
),
193193
}),
194194
);
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 = (path: string) =>
202+
readPersistedServerRuntimeState(path).pipe(
203+
Effect.map(Option.filter((state) => isProcessAlive(state.pid))),
204+
);

0 commit comments

Comments
 (0)