Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off -- The integration fixture binds the same platform socket or named pipe as the CLI.
2import * as NodeChildProcess from "node:child_process";
3import * as NodeEvents from "node:events";
4import * as NodeFSP from "node:fs/promises";
5import * as NodeNet from "node:net";
6import * as NodeOS from "node:os";
7import * as NodePath from "node:path";
8
9import * as NodeServices from "@effect/platform-node/NodeServices";
10import { assert, it } from "@effect/vitest";
11import type { DesktopAppActivationRequest } from "@t3tools/contracts";
12import { resolveDesktopAppControlAddress } from "@t3tools/shared/desktopAppControl";
13import * as HostProcess from "@t3tools/shared/HostProcess";
14import * as NetService from "@t3tools/shared/Net";
15import * as ConfigProvider from "effect/ConfigProvider";
16import * as Effect from "effect/Effect";
17import * as Layer from "effect/Layer";
18import * as Schema from "effect/Schema";
19import { Command } from "effect/cli";
20import { describe, expect } from "vite-plus/test";
21
22import { makeCli } from "../binCli.ts";
23import { PersistedServerRuntimeState } from "../serverRuntimeState.ts";
24
25const liveProcess = Effect.acquireRelease(
26 Effect.promise(async () => {
27 const child = NodeChildProcess.spawn(process.execPath, ["-e", "process.stdin.resume()"], {
28 stdio: ["pipe", "ignore", "ignore"],
29 });
30 await NodeEvents.EventEmitter.once(child, "spawn");
31 return child;
32 }),
33 (child) =>
34 Effect.promise(async () => {
35 const exited = NodeEvents.EventEmitter.once(child, "exit");
36 child.kill();
37 await exited;
38 }),
39);
40
41const encodeRuntimeState = Schema.encodeEffect(Schema.fromJsonString(PersistedServerRuntimeState));
42
43const runCli = (args: ReadonlyArray<string>, env: Record<string, string> = {}) =>
44 Command.runWith(makeCli(), { version: "0.0.0" })(args).pipe(
45 Effect.provide(
46 Layer.mergeAll(
47 NodeServices.layer,
48 NetService.layer,
49 ConfigProvider.layer(ConfigProvider.fromEnv({ env })),
50 ),
51 ),
52 );
53
54const pathExists = (path: string) =>
55 Effect.promise(() =>
56 NodeFSP.stat(path).then(
57 () => true,
58 () => false,
59 ),
60 );
61
62async function startFakeDesktop(input: {
63 readonly baseDir: string;
64 readonly stateSubdirectory?: "userdata" | "dev";
65 readonly platform: NodeJS.Platform;
66 readonly userId: number | undefined;
67 readonly reply?: (request: DesktopAppActivationRequest) => unknown;
68}) {
69 const target = resolveDesktopAppControlAddress({
70 stateDir: NodePath.join(input.baseDir, input.stateSubdirectory ?? "userdata"),
71 platform: input.platform,
72 tempDir: NodeOS.tmpdir(),
73 userId: input.userId,
74 joinPath: NodePath.join,
75 });
76 if (target.directory !== null) {
77 await NodeFSP.mkdir(target.directory, { recursive: true, mode: 0o700 });
78 await NodeFSP.unlink(target.address).catch((error: NodeJS.ErrnoException) => {
79 if (error.code !== "ENOENT") throw error;
80 });
81 }
82
83 const received: DesktopAppActivationRequest[] = [];
84 const server = NodeNet.createServer((socket) => {
85 socket.setEncoding("utf8");
86 let buffer = "";
87 socket.on("data", (chunk) => {
88 buffer += chunk;
89 const newline = buffer.indexOf("\n");
90 if (newline === -1) return;
91 const request = JSON.parse(buffer.slice(0, newline)) as DesktopAppActivationRequest;
92 received.push(request);
93 const response = input.reply
94 ? input.reply(request)
95 : {
96 version: 1,
97 requestId: request.requestId,
98 ok: true,
99 projectId: "project-1",
100 threadId: `thread-${received.length}`,
101 };
102 socket.end(`${JSON.stringify(response)}\n`);
103 });
104 });
105 await new Promise<void>((resolve, reject) => {
106 server.once("error", reject);
107 server.listen(target.address, resolve);
108 });
109
110 return {
111 received,
112 close: async () => {
113 await new Promise<void>((resolve) => server.close(() => resolve()));
114 if (target.directory !== null) {
115 await NodeFSP.unlink(target.address).catch((error: NodeJS.ErrnoException) => {
116 if (error.code !== "ENOENT") throw error;
117 });
118 }
119 },
120 };
121}
122
123const fakeDesktop = Effect.fn(function* (
124 input: Omit<Parameters<typeof startFakeDesktop>[0], "platform" | "userId">,
125) {
126 const platform = yield* HostProcess.Platform;
127 const userId = yield* HostProcess.UserId;
128 return yield* Effect.acquireRelease(
129 Effect.promise(() => startFakeDesktop({ ...input, platform, userId })),
130 (server) => Effect.promise(() => server.close()),
131 );
132});
133
134const withTempDirectory = <A, E, R>(
135 prefix: string,
136 use: (root: string) => Effect.Effect<A, E, R>,
137) =>
138 Effect.acquireUseRelease(
139 Effect.promise(() => NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), prefix))),
140 use,
141 (root) => Effect.promise(() => NodeFSP.rm(root, { recursive: true, force: true })),
142 );
143
144describe("t3 server command safety", () => {
145 it.effect("rejects unknown command words without creating a home or project", () =>
146 withTempDirectory("t3-cli-unknown-", (root) =>
147 Effect.gen(function* () {
148 const baseDir = NodePath.join(root, "home");
149 for (const word of [
150 "account",
151 "login",
152 "clients",
153 "conenct",
154 "package.json",
155 "C:new-project",
156 ]) {
157 const error = yield* runCli([word, "--base-dir", baseDir]).pipe(
158 Effect.provideService(HostProcess.Platform, "linux"),
159 Effect.flip,
160 );
161 expect(String(error)).toContain(`Unknown command "${word}"`);
162 expect(yield* pathExists(word)).toBe(word === "package.json");
163 expect(yield* pathExists(baseDir)).toBe(false);
164 }
165 }),
166 ),
167 );
168
169 it.effect("shows help without creating state", () =>
170 withTempDirectory("t3-cli-help-", (root) =>
171 Effect.gen(function* () {
172 const baseDir = NodePath.join(root, "home");
173 const help = yield* runCli(["help"], { T3CODE_HOME: baseDir }).pipe(Effect.flip);
174 expect(help).toMatchObject({ _tag: "ShowHelp", commandPath: ["t3"], errors: [] });
175 expect(yield* pathExists(baseDir)).toBe(false);
176 }),
177 ),
178 );
179
180 it.effect("refuses manual startup over a live server before creating directories", () =>
181 withTempDirectory("t3-cli-running-", (root) =>
182 Effect.gen(function* () {
183 const baseDir = NodePath.join(root, "home");
184 const stateDir = NodePath.join(baseDir, "userdata");
185 const statePath = NodePath.join(stateDir, "server-runtime.json");
186 const child = yield* liveProcess;
187 assert(child.pid !== undefined);
188 const record = yield* encodeRuntimeState({
189 version: 1,
190 pid: child.pid,
191 port: 3773,
192 origin: "http://127.0.0.1:3773",
193 startedAt: "2026-10-01T00:00:00.000Z",
194 serviceManaged: true,
195 });
196 yield* Effect.promise(() => NodeFSP.mkdir(stateDir, { recursive: true }));
197 yield* Effect.promise(() => NodeFSP.writeFile(statePath, record));
198 const newDirectory = NodePath.join(root, "new-project");
199 const platform = yield* HostProcess.Platform;
200 for (const args of [
201 [],
202 ["start"],
203 ["."],
204 ["node_modules"],
205 ["C:new-project"],
206 [newDirectory],
207 ["start", newDirectory],
208 ]) {
209 const error = yield* runCli(args, { T3CODE_HOME: baseDir }).pipe(
210 Effect.provideService(
211 HostProcess.Platform,
212 args[0] === "C:new-project" ? "win32" : platform,
213 ),
214 Effect.flip,
215 );
216 expect(String(error)).toContain("A T3 Code server is already running");
217 expect(yield* Effect.promise(() => NodeFSP.readFile(statePath, "utf8"))).toBe(record);
218 expect(yield* pathExists(newDirectory)).toBe(false);
219 expect(yield* Effect.promise(() => NodeFSP.readdir(stateDir))).toEqual([
220 "server-runtime.json",
221 ]);
222 }
223 }),
224 ),
225 );
226});
227
228describe("t3 app", () => {
229 it.effect("rejects SSH before it tries to reach a desktop app", () =>
230 withTempDirectory("t3-app-ssh-test-", (root) =>
231 Effect.gen(function* () {
232 const baseDir = NodePath.join(root, "missing-t3-home");
233 const error = yield* runCli(["app", "--base-dir", baseDir], {
234 SSH_CONNECTION: "client server",
235 }).pipe(Effect.flip);
236
237 expect(error).toMatchObject({
238 _tag: "DesktopAppSshUnsupportedError",
239 message:
240 "`t3 app` only controls a desktop app on the same machine. It cannot run over SSH.",
241 });
242 expect(yield* pathExists(baseDir)).toBe(false);
243 }),
244 ),
245 );
246
247 it.effect("rejects unsupported platforms without creating state", () =>
248 withTempDirectory("t3-app-platform-test-", (root) =>
249 Effect.gen(function* () {
250 const baseDir = NodePath.join(root, "missing-t3-home");
251 const error = yield* runCli(["app", "--base-dir", baseDir]).pipe(
252 Effect.provideService(HostProcess.Platform, "freebsd"),
253 Effect.flip,
254 );
255
256 expect(error).toMatchObject({
257 _tag: "DesktopAppPlatformUnsupportedError",
258 platform: "freebsd",
259 message: "`t3 app` is not supported on freebsd.",
260 });
261 expect(yield* pathExists(baseDir)).toBe(false);
262 }),
263 ),
264 );
265
266 it.effect("does not create state when only a server or no desktop app is running", () =>
267 withTempDirectory("t3-app-missing-test-", (root) =>
268 Effect.gen(function* () {
269 const baseDir = NodePath.join(root, "missing-t3-home");
270 const error = yield* runCli(["app", "--base-dir", baseDir]).pipe(Effect.flip);
271
272 expect(error).toMatchObject({
273 _tag: "DesktopAppUnreachableError",
274 candidateAddresses: [expect.any(String)],
275 workspaceRoot: yield* HostProcess.WorkingDirectory,
276 message: expect.stringContaining("Could not reach the T3 Code desktop app."),
277 cause: { code: "ENOENT" },
278 });
279 expect(yield* pathExists(baseDir)).toBe(false);
280 }),
281 ),
282 );
283
284 it.effect("uses T3CODE_HOME or --base-dir and sends the default or explicit path", () =>
285 withTempDirectory("t3-app-command-test-", (root) =>
286 Effect.gen(function* () {
287 const baseDir = NodePath.join(root, "t3-home");
288 const explicitPath = NodePath.join(root, "project");
289 const platform = yield* HostProcess.Platform;
290 const workingDirectory = yield* HostProcess.WorkingDirectory;
291 const desktop = yield* fakeDesktop({ baseDir });
292
293 yield* runCli(["app"], { T3CODE_HOME: baseDir });
294 yield* runCli(["app", explicitPath, "--base-dir", baseDir]);
295
296 expect(desktop.received.map((request) => request.workspaceRoot)).toEqual([
297 workingDirectory,
298 explicitPath,
299 ]);
300 expect(desktop.received.every((request) => request.platform === platform)).toBe(true);
301 }).pipe(Effect.scoped),
302 ),
303 );
304
305 it.effect("prefers the installed desktop app when a dev desktop is also running", () =>
306 withTempDirectory("t3-app-preferred-test-", (root) =>
307 Effect.gen(function* () {
308 const baseDir = NodePath.join(root, ".t3");
309 const desktop = yield* fakeDesktop({ baseDir });
310 const development = yield* fakeDesktop({ baseDir, stateSubdirectory: "dev" });
311
312 yield* runCli(["app"]);
313
314 expect(desktop.received).toHaveLength(1);
315 expect(development.received).toHaveLength(0);
316 }).pipe(Effect.provideService(HostProcess.HomeDirectory, root), Effect.scoped),
317 ),
318 );
319
320 it.effect("finds the dev desktop when the default desktop socket is absent", () =>
321 withTempDirectory("t3-app-dev-test-", (root) =>
322 Effect.gen(function* () {
323 const baseDir = NodePath.join(root, ".t3");
324 const development = yield* fakeDesktop({ baseDir, stateSubdirectory: "dev" });
325
326 yield* runCli(["app"]);
327 yield* runCli(["app"], { T3CODE_HOME: " " });
328
329 expect(development.received).toHaveLength(2);
330 expect(yield* pathExists(baseDir)).toBe(false);
331 }).pipe(Effect.provideService(HostProcess.HomeDirectory, root), Effect.scoped),
332 ),
333 );
334
335 it.effect("never searches a dev state directory for an explicit T3 home", () =>
336 withTempDirectory("t3-app-explicit-test-", (root) =>
337 Effect.gen(function* () {
338 const baseDir = NodePath.join(root, ".t3");
339 const development = yield* fakeDesktop({ baseDir, stateSubdirectory: "dev" });
340
341 const flagError = yield* runCli(["app", "--base-dir", baseDir]).pipe(Effect.flip);
342 const envError = yield* runCli(["app"], { T3CODE_HOME: baseDir }).pipe(Effect.flip);
343
344 expect(flagError).toMatchObject({ _tag: "DesktopAppUnreachableError" });
345 expect(envError).toMatchObject({ _tag: "DesktopAppUnreachableError" });
346 expect(development.received).toHaveLength(0);
347 }).pipe(Effect.provideService(HostProcess.HomeDirectory, root), Effect.scoped),
348 ),
349 );
350
351 it.effect.each(["failure", "invalid"] as const)(
352 "never falls back after the default desktop sends a %s response",
353 (responseKind) =>
354 withTempDirectory("t3-app-response-test-", (root) =>
355 Effect.gen(function* () {
356 const baseDir = NodePath.join(root, ".t3");
357 const desktop = yield* fakeDesktop({
358 baseDir,
359 reply: (request) =>
360 responseKind === "failure"
361 ? {
362 version: 1,
363 requestId: request.requestId,
364 ok: false,
365 code: "project-create-failed",
366 message: "The project path is not available.",
367 }
368 : { invalid: true },
369 });
370 const development = yield* fakeDesktop({ baseDir, stateSubdirectory: "dev" });
371
372 const error = yield* runCli(["app"]).pipe(Effect.flip);
373
374 expect(desktop.received).toHaveLength(1);
375 expect(development.received).toHaveLength(0);
376 if (responseKind === "failure") {
377 expect(error).toMatchObject({
378 _tag: "DesktopAppRequestFailedError",
379 code: "project-create-failed",
380 requestId: desktop.received[0]?.requestId,
381 workspaceRoot: yield* HostProcess.WorkingDirectory,
382 message: expect.stringContaining("project-create-failed"),
383 cause: {
384 ok: false,
385 code: "project-create-failed",
386 message: "The project path is not available.",
387 },
388 });
389 } else {
390 expect(error).toMatchObject({
391 _tag: "DesktopAppUnreachableError",
392 cause: { message: "The desktop app response is invalid." },
393 });
394 }
395 }).pipe(Effect.provideService(HostProcess.HomeDirectory, root), Effect.scoped),
396 ),
397 );
398});