Skip to content

Commit 35557e6

Browse files
authored
fix(cli): thread, project, and connect commands skip a server that is gone (pingdotgg#34529)
Co-authored-by: maria-rcks <[email protected]>
1 parent b9d9aab commit 35557e6

7 files changed

Lines changed: 128 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
@@ -136,6 +136,45 @@ it.effect(
136136
),
137137
);
138138

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+
139178
/** Answers each tool call with the next scripted response for that tool. */
140179
const scriptedTools = (script: Record<string, Array<unknown>>) => {
141180
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
@@ -31,7 +31,7 @@ import * as ServerConfig from "../config.ts";
3131
import { mcpToolSession, type McpToolSession } from "../mcp/AcpMcpStdioBridge.ts";
3232
import { expandHomePath } from "../os-jank.ts";
3333
import * as ProcessRunner from "../processRunner.ts";
34-
import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
34+
import { readLiveServerRuntimeState } from "../serverRuntimeState.ts";
3535
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
3636

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

‎apps/server/src/serverRuntimeState.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,3 +192,16 @@ 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 = Effect.fn(
202+
"serverRuntimeState.readLiveServerRuntimeState",
203+
)((path: string) =>
204+
readPersistedServerRuntimeState(path).pipe(
205+
Effect.map(Option.filter((state) => isProcessAlive(state.pid))),
206+
),
207+
);

0 commit comments

Comments
 (0)