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("refuses manual startup over a live server before creating directories", () =>
170 withTempDirectory("t3-cli-running-", (root) =>
171 Effect.gen(function* () {
172 const baseDir = NodePath.join(root, "home");
173 const stateDir = NodePath.join(baseDir, "userdata");
174 const statePath = NodePath.join(stateDir, "server-runtime.json");
175 const child = yield* liveProcess;
176 assert(child.pid !== undefined);
177 const record = yield* encodeRuntimeState({
178 version: 1,
179 pid: child.pid,
180 port: 3773,
181 origin: "http://127.0.0.1:3773",
182 startedAt: "2026-10-01T00:00:00.000Z",
183 serviceManaged: true,
184 });
185 yield* Effect.promise(() => NodeFSP.mkdir(stateDir, { recursive: true }));
186 yield* Effect.promise(() => NodeFSP.writeFile(statePath, record));
187 const newDirectory = NodePath.join(root, "new-project");
188 const platform = yield* HostProcess.Platform;
189 for (const args of [
190 [],
191 ["start"],
192 ["."],
193 ["node_modules"],
194 ["C:new-project"],
195 [newDirectory],
196 ["start", newDirectory],
197 ]) {
198 const error = yield* runCli(args, { T3CODE_HOME: baseDir }).pipe(
199 Effect.provideService(
200 HostProcess.Platform,
201 args[0] === "C:new-project" ? "win32" : platform,
202 ),
203 Effect.flip,
204 );
205 expect(String(error)).toContain("A T3 Code server is already running");
206 expect(yield* Effect.promise(() => NodeFSP.readFile(statePath, "utf8"))).toBe(record);
207 expect(yield* pathExists(newDirectory)).toBe(false);
208 expect(yield* Effect.promise(() => NodeFSP.readdir(stateDir))).toEqual([
209 "server-runtime.json",
210 ]);
211 }
212 }),
213 ),
214 );
215});
216
217describe("t3 app", () => {
218 it.effect("uses T3CODE_HOME or --base-dir and sends the default or explicit path", () =>
219 withTempDirectory("t3-app-command-test-", (root) =>
220 Effect.gen(function* () {
221 const baseDir = NodePath.join(root, "t3-home");
222 const explicitPath = NodePath.join(root, "project");
223 const platform = yield* HostProcess.Platform;
224 const workingDirectory = yield* HostProcess.WorkingDirectory;
225 const desktop = yield* fakeDesktop({ baseDir });
226
227 yield* runCli(["app"], { T3CODE_HOME: baseDir });
228 yield* runCli(["app", explicitPath, "--base-dir", baseDir]);
229
230 expect(desktop.received.map((request) => request.workspaceRoot)).toEqual([
231 workingDirectory,
232 explicitPath,
233 ]);
234 expect(desktop.received.every((request) => request.platform === platform)).toBe(true);
235 }).pipe(Effect.scoped),
236 ),
237 );
238
239 it.effect("prefers the installed desktop app when a dev desktop is also running", () =>
240 withTempDirectory("t3-app-preferred-test-", (root) =>
241 Effect.gen(function* () {
242 const baseDir = NodePath.join(root, ".t3");
243 const desktop = yield* fakeDesktop({ baseDir });
244 const development = yield* fakeDesktop({ baseDir, stateSubdirectory: "dev" });
245
246 yield* runCli(["app"]);
247
248 expect(desktop.received).toHaveLength(1);
249 expect(development.received).toHaveLength(0);
250 }).pipe(Effect.provideService(HostProcess.HomeDirectory, root), Effect.scoped),
251 ),
252 );
253
254 it.effect("finds the dev desktop when the default desktop socket is absent", () =>
255 withTempDirectory("t3-app-dev-test-", (root) =>
256 Effect.gen(function* () {
257 const baseDir = NodePath.join(root, ".t3");
258 const development = yield* fakeDesktop({ baseDir, stateSubdirectory: "dev" });
259
260 yield* runCli(["app"]);
261 yield* runCli(["app"], { T3CODE_HOME: " " });
262
263 expect(development.received).toHaveLength(2);
264 expect(yield* pathExists(baseDir)).toBe(false);
265 }).pipe(Effect.provideService(HostProcess.HomeDirectory, root), Effect.scoped),
266 ),
267 );
268
269 it.effect("never searches a dev state directory for an explicit T3 home", () =>
270 withTempDirectory("t3-app-explicit-test-", (root) =>
271 Effect.gen(function* () {
272 const baseDir = NodePath.join(root, ".t3");
273 const development = yield* fakeDesktop({ baseDir, stateSubdirectory: "dev" });
274
275 const flagError = yield* runCli(["app", "--base-dir", baseDir]).pipe(Effect.flip);
276 const envError = yield* runCli(["app"], { T3CODE_HOME: baseDir }).pipe(Effect.flip);
277
278 expect(flagError).toMatchObject({ _tag: "DesktopAppUnreachableError" });
279 expect(envError).toMatchObject({ _tag: "DesktopAppUnreachableError" });
280 expect(development.received).toHaveLength(0);
281 }).pipe(Effect.provideService(HostProcess.HomeDirectory, root), Effect.scoped),
282 ),
283 );
284
285 it.effect.each(["failure", "invalid"] as const)(
286 "never falls back after the default desktop sends a %s response",
287 (responseKind) =>
288 withTempDirectory("t3-app-response-test-", (root) =>
289 Effect.gen(function* () {
290 const baseDir = NodePath.join(root, ".t3");
291 const desktop = yield* fakeDesktop({
292 baseDir,
293 reply: (request) =>
294 responseKind === "failure"
295 ? {
296 version: 1,
297 requestId: request.requestId,
298 ok: false,
299 code: "project-create-failed",
300 message: "The project path is not available.",
301 }
302 : { invalid: true },
303 });
304 const development = yield* fakeDesktop({ baseDir, stateSubdirectory: "dev" });
305
306 const error = yield* runCli(["app"]).pipe(Effect.flip);
307
308 expect(desktop.received).toHaveLength(1);
309 expect(development.received).toHaveLength(0);
310 if (responseKind === "failure") {
311 expect(error).toMatchObject({
312 _tag: "DesktopAppRequestFailedError",
313 code: "project-create-failed",
314 requestId: desktop.received[0]?.requestId,
315 workspaceRoot: yield* HostProcess.WorkingDirectory,
316 message: expect.stringContaining("project-create-failed"),
317 cause: {
318 ok: false,
319 code: "project-create-failed",
320 message: "The project path is not available.",
321 },
322 });
323 } else {
324 expect(error).toMatchObject({
325 _tag: "DesktopAppUnreachableError",
326 cause: { message: "The desktop app response is invalid." },
327 });
328 }
329 }).pipe(Effect.provideService(HostProcess.HomeDirectory, root), Effect.scoped),
330 ),
331 );
332});