Skip to content

Commit f6d6c71

Browse files
committed
fix(cli): reject accidental server launches
1 parent efecd3c commit f6d6c71

6 files changed

Lines changed: 183 additions & 5 deletions

File tree

‎apps/server/src/binCli.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import { pairCommand } from "./cli/pair.ts";
1515
import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
1616
import { sharedServerCommandFlags } from "./cli/config.ts";
1717
import { projectCommand } from "./cli/project.ts";
18-
import { runServerCommand, serveCommand, startCommand } from "./cli/server.ts";
18+
import { runDefaultServerCommand, serveCommand, startCommand } from "./cli/server.ts";
1919
import { updateCommand } from "./cli/update.ts";
2020
import { uninstallCommand } from "./cli/uninstall.ts";
2121
import { serviceLauncherCommand } from "./cli/serviceLauncher.ts";
@@ -56,8 +56,14 @@ const connectUnavailableCommand = Command.make("connect", {
5656
export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
5757
Command.make("t3", { ...sharedServerCommandFlags }).pipe(
5858
Command.withDescription("Run the T3 Code server."),
59-
Command.withHandler((flags) => runServerCommand(flags)),
59+
Command.withHandler(runDefaultServerCommand),
6060
Command.withSubcommands([
61+
Command.make("help").pipe(
62+
Command.withDescription("Show command help."),
63+
Command.withHandler(() =>
64+
Effect.fail(new CliError.ShowHelp({ commandPath: ["t3"], errors: [] })),
65+
),
66+
),
6167
acpMcpBridgeCommand,
6268
acpMcpCallCommand,
6369
startCommand,

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

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,12 @@ import * as NetService from "@t3tools/shared/Net";
1717
import * as ConfigProvider from "effect/ConfigProvider";
1818
import * as Effect from "effect/Effect";
1919
import * as Layer from "effect/Layer";
20+
import * as Schema from "effect/Schema";
2021
import { Command } from "effect/unstable/cli";
2122
import { afterEach, describe, expect, vi } from "vite-plus/test";
2223

2324
import { makeCli } from "../binCli.ts";
25+
import { PersistedServerRuntimeState } from "../serverRuntimeState.ts";
2426

2527
vi.mock("node:os", async (importOriginal) => {
2628
const os = await importOriginal<typeof import("node:os")>();
@@ -29,6 +31,8 @@ vi.mock("node:os", async (importOriginal) => {
2931

3032
afterEach(() => vi.mocked(NodeOS.homedir).mockReset());
3133

34+
const encodeRuntimeState = Schema.encodeEffect(Schema.fromJsonString(PersistedServerRuntimeState));
35+
3236
const runCli = (args: ReadonlyArray<string>, env: Record<string, string> = {}) =>
3337
Command.runWith(makeCli(), { version: "0.0.0" })(args).pipe(
3438
Effect.provide(
@@ -130,6 +134,70 @@ const withTempDirectory = <A, E, R>(
130134
(root) => Effect.promise(() => NodeFSP.rm(root, { recursive: true, force: true })),
131135
);
132136

137+
describe("t3 server command safety", () => {
138+
it.effect("rejects unknown command words without creating a home or project", () =>
139+
withTempDirectory("t3-cli-unknown-", (root) =>
140+
Effect.gen(function* () {
141+
const baseDir = NodePath.join(root, "home");
142+
for (const word of ["account", "login", "clients", "conenct"]) {
143+
const error = yield* runCli([word, "--base-dir", baseDir]).pipe(Effect.flip);
144+
expect(String(error)).toContain(`Unknown command "${word}"`);
145+
expect(yield* pathExists(word)).toBe(false);
146+
expect(yield* pathExists(baseDir)).toBe(false);
147+
}
148+
}),
149+
),
150+
);
151+
152+
it.effect("shows help without creating state", () =>
153+
withTempDirectory("t3-cli-help-", (root) =>
154+
Effect.gen(function* () {
155+
const baseDir = NodePath.join(root, "home");
156+
const help = yield* runCli(["help"], { T3CODE_HOME: baseDir }).pipe(Effect.flip);
157+
expect(help).toMatchObject({ _tag: "ShowHelp", commandPath: ["t3"], errors: [] });
158+
expect(yield* pathExists(baseDir)).toBe(false);
159+
}),
160+
),
161+
);
162+
163+
it.effect("refuses manual startup over a live server before creating directories", () =>
164+
withTempDirectory("t3-cli-running-", (root) =>
165+
Effect.gen(function* () {
166+
const baseDir = NodePath.join(root, "home");
167+
const stateDir = NodePath.join(baseDir, "userdata");
168+
const statePath = NodePath.join(stateDir, "server-runtime.json");
169+
const record = yield* encodeRuntimeState({
170+
version: 1,
171+
pid: process.pid,
172+
port: 3773,
173+
origin: "http://127.0.0.1:3773",
174+
startedAt: "2026-10-01T00:00:00.000Z",
175+
serviceManaged: true,
176+
});
177+
yield* Effect.promise(() => NodeFSP.mkdir(stateDir, { recursive: true }));
178+
yield* Effect.promise(() => NodeFSP.writeFile(statePath, record));
179+
const newDirectory = NodePath.join(root, "new-project");
180+
for (const args of [
181+
[],
182+
["start"],
183+
["."],
184+
["node_modules"],
185+
[newDirectory],
186+
["start", newDirectory],
187+
]) {
188+
const error = yield* runCli(args, { T3CODE_HOME: baseDir }).pipe(Effect.flip);
189+
expect(String(error)).toContain("A T3 Code server is already running");
190+
expect(yield* Effect.promise(() => NodeFSP.readFile(statePath, "utf8"))).toBe(record);
191+
expect(yield* pathExists(newDirectory)).toBe(false);
192+
expect(yield* Effect.promise(() => NodeFSP.readdir(stateDir))).toEqual([
193+
"server-runtime.json",
194+
]);
195+
}
196+
}),
197+
),
198+
);
199+
});
200+
133201
describe("t3 app", () => {
134202
it.effect("rejects SSH before it tries to reach a desktop app", () =>
135203
withTempDirectory("t3-app-ssh-test-", (root) =>

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

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,61 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
8080
);
8181
});
8282

83+
it.effect("keeps stale records and supervised startup out of the manual launch preflight", () =>
84+
Effect.gen(function* () {
85+
const fs = yield* FileSystem.FileSystem;
86+
const path = yield* Path.Path;
87+
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-preflight-" });
88+
for (const [name, pid, mode, rejectRunningServer] of [
89+
["stale", 2_147_483_647, "web", true],
90+
["desktop", process.pid, "desktop", true],
91+
["serve", process.pid, "web", false],
92+
] as const) {
93+
const baseDir = path.join(root, name);
94+
const stateDir = path.join(baseDir, "userdata");
95+
yield* fs.makeDirectory(stateDir, { recursive: true });
96+
yield* fs.writeFileString(
97+
path.join(stateDir, "server-runtime.json"),
98+
yield* encodeUnknownJson({
99+
version: 1,
100+
pid,
101+
port: 3773,
102+
origin: "http://127.0.0.1:3773",
103+
startedAt: "2026-10-01T00:00:00.000Z",
104+
}),
105+
);
106+
const cwd = path.join(root, `${name}-project`);
107+
const config = yield* resolveServerConfig(
108+
{
109+
mode: Option.some(mode),
110+
port: Option.some(8788),
111+
host: Option.none(),
112+
baseDir: Option.some(baseDir),
113+
cwd: Option.some(cwd),
114+
devUrl: Option.none(),
115+
noBrowser: Option.none(),
116+
bootstrapFd: Option.none(),
117+
autoBootstrapProjectFromCwd: Option.none(),
118+
logWebSocketEvents: Option.none(),
119+
tailscaleServeEnabled: Option.none(),
120+
tailscaleServePort: Option.none(),
121+
},
122+
Option.none(),
123+
{ rejectRunningServer },
124+
).pipe(
125+
Effect.provide(
126+
Layer.merge(
127+
NetService.layer,
128+
ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
129+
),
130+
),
131+
);
132+
expect(config.cwd).toBe(cwd);
133+
expect(yield* fs.exists(cwd)).toBe(true);
134+
}
135+
}),
136+
);
137+
83138
it.effect("enables a trimmed reusable auth token only for web dev mode", () =>
84139
Effect.gen(function* () {
85140
const baseDir = yield* FileSystem.FileSystem.pipe(

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

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,12 @@ import * as Schema from "effect/Schema";
1919
import * as SchemaIssue from "effect/SchemaIssue";
2020
import * as SchemaTransformation from "effect/SchemaTransformation";
2121
import { Argument, Flag } from "effect/unstable/cli";
22+
import * as CliError from "effect/unstable/cli/CliError";
2223

2324
import { readBootstrapEnvelope } from "../bootstrap.ts";
2425
import * as ServerConfig from "../config.ts";
2526
import { expandHomePath, resolveBaseDir } from "../os-jank.ts";
27+
import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
2628

2729
const modeFlag = Flag.Literals("mode", ServerConfig.RuntimeMode.literals).pipe(
2830
Flag.withDescription("Runtime mode. `desktop` keeps loopback defaults unless overridden."),
@@ -248,12 +250,19 @@ const loadPersistedObservabilitySettings = Effect.fn(function* (settingsPath: st
248250
return parsePersistedServerObservabilitySettings(raw);
249251
});
250252

253+
class ServerAlreadyRunningError extends CliError.UserError {
254+
override get message() {
255+
return String(this.cause);
256+
}
257+
}
258+
251259
export const resolveServerConfig = (
252260
flags: CliServerFlags,
253261
cliLogLevel: Option.Option<LogLevel.LogLevel>,
254262
options?: {
255263
readonly startupPresentation?: ServerConfig.StartupPresentation;
256264
readonly forceAutoBootstrapProjectFromCwd?: boolean;
265+
readonly rejectRunningServer?: boolean;
257266
},
258267
) =>
259268
Effect.gen(function* () {
@@ -324,10 +333,20 @@ export const resolveServerConfig = (
324333
);
325334
const rawCwd = Option.getOrElse(normalizedFlags.cwd, () => process.cwd());
326335
const cwd = path.resolve(yield* expandHomePath(rawCwd.trim()));
327-
yield* fs.makeDirectory(cwd, { recursive: true });
328336
const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, devUrl, {
329337
baseDirIsExplicit: Option.isSome(explicitBaseDir),
330338
});
339+
// An interactive CLI must not start over a discovered server. Lifetime locking
340+
// and supervisor handoff are separate; this preflight cannot arbitrate two starts.
341+
if (options?.rejectRunningServer && mode === "web") {
342+
const runtime = yield* readPersistedServerRuntimeState(derivedPaths.serverRuntimeStatePath);
343+
if (Option.isSome(runtime) && runtime.value.pid > 0 && isProcessAlive(runtime.value.pid)) {
344+
return yield* new ServerAlreadyRunningError({
345+
cause: `A T3 Code server is already running for ${baseDir} (pid ${runtime.value.pid}, ${runtime.value.origin}). Connect to that server, stop it before starting another, or use a different --base-dir.`,
346+
});
347+
}
348+
}
349+
yield* fs.makeDirectory(cwd, { recursive: true });
331350
yield* ServerConfig.ensureServerDirectories(derivedPaths);
332351
const persistedObservabilitySettings = yield* loadPersistedObservabilitySettings(
333352
derivedPaths.settingsPath,

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

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
import * as Effect from "effect/Effect";
2+
import * as FileSystem from "effect/FileSystem";
3+
import * as Option from "effect/Option";
24
import { Command, GlobalFlag } from "effect/unstable/cli";
5+
import * as CliError from "effect/unstable/cli/CliError";
36

47
import * as ServerConfig from "../config.ts";
58
import { runServer } from "../server.ts";
@@ -10,6 +13,7 @@ export const runServerCommand = (
1013
options?: {
1114
readonly startupPresentation?: ServerConfig.StartupPresentation;
1215
readonly forceAutoBootstrapProjectFromCwd?: boolean;
16+
readonly rejectRunningServer?: boolean;
1317
},
1418
) =>
1519
Effect.gen(function* () {
@@ -18,9 +22,29 @@ export const runServerCommand = (
1822
return yield* runServer.pipe(Effect.provideService(ServerConfig.ServerConfig, config));
1923
});
2024

25+
class UnknownServerCommandError extends CliError.UserError {
26+
override get message() {
27+
return `Unknown command ${JSON.stringify(this.cause)}. Use "t3 --help" for commands or an explicit path such as "t3 ./my-project" for a new directory.`;
28+
}
29+
}
30+
31+
/** Bare words can name existing directories, but must not create typo projects. */
32+
export const runDefaultServerCommand = (flags: CliServerFlags) =>
33+
Effect.gen(function* () {
34+
if (Option.isSome(flags.cwd)) {
35+
const cwd = flags.cwd.value.trim();
36+
const fs = yield* FileSystem.FileSystem;
37+
const explicitPath = cwd === "." || cwd === ".." || cwd === "~" || /[/\\]/.test(cwd);
38+
if (!explicitPath && !(yield* fs.exists(cwd))) {
39+
return yield* new UnknownServerCommandError({ cause: cwd });
40+
}
41+
}
42+
return yield* runServerCommand(flags, { rejectRunningServer: true });
43+
});
44+
2145
export const startCommand = Command.make("start", { ...sharedServerCommandFlags }).pipe(
2246
Command.withDescription("Run the T3 Code server."),
23-
Command.withHandler((flags) => runServerCommand(flags)),
47+
Command.withHandler((flags) => runServerCommand(flags, { rejectRunningServer: true })),
2448
);
2549

2650
export const serveCommand = Command.make("serve", { ...sharedServerCommandFlags }).pipe(

‎docs/user/install.md‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,13 @@ line to add. Set `T3CODE_CHANNEL=nightly` to install the nightly train, or
3333
| Move to the newest release | `t3 update` |
3434
| Remove it again | `t3 uninstall` |
3535

36-
Run `t3 --help` for the full reference.
36+
Run `t3 help` or `t3 --help` for the full reference. To start in a new working
37+
directory, use an explicit path such as `t3 ./my-project`. A bare directory name
38+
is accepted only if it already exists.
39+
40+
If `t3` or `t3 start` reports an already running server, connect to that server
41+
instead. Stop it before starting a replacement, or use a different `--base-dir`
42+
for an independent server.
3743

3844
To try T3 Code once without installing it, run `npx t3@latest` instead (needs
3945
Node.js for `npx`).

0 commit comments

Comments
 (0)