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

app.test.ts

393 lines14.3 KB

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