Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

app.test.ts

393 lines14.7 KB

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