Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - CLI integration exercises Node HTTP and filesystem boundaries.
2import * as NodeHttp from "node:http";
3import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
4import { tmpdir } from "node:os";
5import { join } from "node:path";
6
7import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
8import * as NodeServices from "@effect/platform-node/NodeServices";
9import { EnvironmentOrchestrationHttpApi } from "@t3tools/contracts";
10import * as NetService from "@t3tools/shared/Net";
11import { assert, it } from "@effect/vitest";
12import * as Effect from "effect/Effect";
13import * as Layer from "effect/Layer";
14import * as HttpRouter from "effect/unstable/http/HttpRouter";
15import * as HttpServer from "effect/unstable/http/HttpServer";
16import * as HttpApi from "effect/unstable/httpapi/HttpApi";
17import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
18import * as CliError from "effect/unstable/cli/CliError";
19import * as TestConsole from "effect/testing/TestConsole";
20import { Command } from "effect/unstable/cli";
21
22import { cli, makeCli } from "./bin.ts";
23import { deriveServerPaths, ServerConfig, type ServerConfigShape } from "./config.ts";
24import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
25import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
26import { orchestrationHttpApiLayer } from "./orchestration/http.ts";
27import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";
28import { RepositoryIdentityResolverLive } from "./project/Layers/RepositoryIdentityResolver.ts";
29import {
30 makePersistedServerRuntimeState,
31 persistServerRuntimeState,
32} from "./serverRuntimeState.ts";
33import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts";
34import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
35import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
36import { environmentAuthenticatedAuthLayer } from "./auth/http.ts";
37
38const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
39class ProjectCliHttpApi extends HttpApi.make("environment").add(EnvironmentOrchestrationHttpApi) {}
40
41const connectCli = makeCli({ cloudEnabled: true });
42const noConnectCli = makeCli({ cloudEnabled: false });
43const runCli = (args: ReadonlyArray<string>, command = cli) =>
44 Command.runWith(command, { version: "0.0.0" })(args);
45const runConnectCli = (args: ReadonlyArray<string>) => runCli(args, connectCli);
46const runCliWithRuntime = (args: ReadonlyArray<string>) =>
47 runCli(args).pipe(Effect.provide(CliRuntimeLayer));
48
49const captureStdout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
50 Effect.gen(function* () {
51 const result = yield* effect;
52 const output =
53 (yield* TestConsole.logLines).findLast((line): line is string => typeof line === "string") ??
54 "";
55 return { result, output };
56 }).pipe(Effect.provide(Layer.mergeAll(CliRuntimeLayer, TestConsole.layer)));
57
58const makeCliTestServerConfig = (baseDir: string) =>
59 Effect.gen(function* () {
60 const derivedPaths = yield* deriveServerPaths(baseDir, undefined);
61 return {
62 logLevel: "Info",
63 traceMinLevel: "Info",
64 traceTimingEnabled: true,
65 traceBatchWindowMs: 200,
66 traceMaxBytes: 10 * 1024 * 1024,
67 traceMaxFiles: 10,
68 otlpTracesUrl: undefined,
69 otlpMetricsUrl: undefined,
70 otlpExportIntervalMs: 10_000,
71 otlpServiceName: "t3-server",
72 mode: "web",
73 port: 0,
74 host: "127.0.0.1",
75 cwd: process.cwd(),
76 baseDir,
77 ...derivedPaths,
78 staticDir: undefined,
79 devUrl: undefined,
80 noBrowser: true,
81 startupPresentation: "browser",
82 desktopBootstrapToken: undefined,
83 autoBootstrapProjectFromCwd: false,
84 logWebSocketEvents: false,
85 tailscaleServeEnabled: false,
86 tailscaleServePort: 443,
87 } satisfies ServerConfigShape;
88 });
89
90const makeProjectPersistenceLayer = (config: ServerConfigShape) =>
91 Layer.mergeAll(
92 OrchestrationLayerLive.pipe(
93 Layer.provideMerge(RepositoryIdentityResolverLive),
94 Layer.provideMerge(SqlitePersistenceLayerLive),
95 ),
96 WorkspacePathsLive,
97 ).pipe(
98 Layer.provideMerge(NodeServices.layer),
99 Layer.provide(Layer.succeed(ServerConfig, config)),
100 );
101
102const readPersistedSnapshot = (baseDir: string) =>
103 Effect.gen(function* () {
104 const config = yield* makeCliTestServerConfig(baseDir);
105 return yield* Effect.gen(function* () {
106 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
107 return yield* projectionSnapshotQuery.getSnapshot();
108 }).pipe(Effect.provide(makeProjectPersistenceLayer(config)));
109 });
110
111const withLiveProjectCliServer = <A, E, R>(baseDir: string, run: () => Effect.Effect<A, E, R>) =>
112 Effect.gen(function* () {
113 const config = yield* makeCliTestServerConfig(baseDir);
114 const routesLayer = HttpApiBuilder.layer(ProjectCliHttpApi).pipe(
115 Layer.provide(orchestrationHttpApiLayer),
116 Layer.provide(environmentAuthenticatedAuthLayer),
117 );
118 const appLayer = HttpRouter.serve(routesLayer, {
119 disableListenLog: true,
120 disableLogger: true,
121 }).pipe(
122 Layer.provideMerge(
123 EnvironmentAuth.layer.pipe(
124 Layer.provideMerge(SqlitePersistenceLayerLive),
125 Layer.provide(ServerSecretStore.layer),
126 ),
127 ),
128 Layer.provideMerge(makeProjectPersistenceLayer(config)),
129 Layer.provideMerge(
130 NodeHttpServer.layer(NodeHttp.createServer, {
131 host: "127.0.0.1",
132 port: 0,
133 }),
134 ),
135 Layer.provideMerge(NodeServices.layer),
136 Layer.provide(Layer.succeed(ServerConfig, config)),
137 );
138
139 return yield* Effect.scoped(
140 Effect.gen(function* () {
141 const server = yield* HttpServer.HttpServer;
142 const address = server.address;
143 if (typeof address === "string" || !("port" in address)) {
144 assert.fail(`Expected TCP address, got ${address}`);
145 }
146 yield* persistServerRuntimeState({
147 path: config.serverRuntimeStatePath,
148 state: yield* makePersistedServerRuntimeState({
149 config,
150 port: address.port,
151 }),
152 });
153 return yield* run();
154 }).pipe(Effect.provide(Layer.mergeAll(appLayer, NodeServices.layer))),
155 );
156 });
157
158it.layer(NodeServices.layer)("bin cli parsing", (it) => {
159 it.effect("accepts the built-in lowercase log-level flag values", () =>
160 runCliWithRuntime(["--log-level", "debug", "--version"]),
161 );
162
163 it.effect("accepts canonical --no-<flag> boolean negation", () =>
164 runCliWithRuntime(["--no-log-websocket-events", "--version"]),
165 );
166
167 it.effect("rejects invalid log-level casing before launching the server", () =>
168 Effect.gen(function* () {
169 const error = yield* runCliWithRuntime(["--log-level", "Debug"]).pipe(Effect.flip);
170
171 if (!CliError.isCliError(error)) {
172 assert.fail(`Expected CliError, got ${String(error)}`);
173 }
174 if (error._tag !== "InvalidValue") {
175 assert.fail(`Expected InvalidValue, got ${error._tag}`);
176 }
177 assert.equal(error.option, "log-level");
178 assert.equal(error.value, "Debug");
179 }),
180 );
181
182 it.effect("rejects connect commands when public configuration is missing", () =>
183 Effect.gen(function* () {
184 const error = yield* runCli(["connect", "status"], noConnectCli).pipe(Effect.flip);
185
186 if (!CliError.isCliError(error)) {
187 assert.fail(`Expected CliError, got ${String(error)}`);
188 }
189 if (error._tag !== "ShowHelp") {
190 assert.fail(`Expected ShowHelp, got ${error._tag}`);
191 }
192 assert.deepEqual(error.commandPath, ["t3", "connect"]);
193 assert.include(error.errors[0]?.message ?? "", "missing T3 Connect public configuration");
194
195 const output = (yield* TestConsole.errorLines).join("\n");
196 assert.include(output, "ERROR");
197 assert.include(output, "missing T3 Connect public configuration");
198 }).pipe(Effect.provide(Layer.mergeAll(CliRuntimeLayer, TestConsole.layer))),
199 );
200
201 it.effect("reports fresh headless connect state without requiring local configuration", () =>
202 Effect.gen(function* () {
203 const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-status-test-"));
204 const { output } = yield* captureStdout(
205 runConnectCli(["connect", "status", "--base-dir", baseDir, "--json"]),
206 );
207 // @effect-diagnostics-next-line preferSchemaOverJson:off - CLI JSON output is decoded as a presentation DTO.
208 const status = JSON.parse(output) as {
209 readonly desired: boolean;
210 readonly authenticated: boolean;
211 readonly linked: boolean;
212 readonly cloudUserId: string | null;
213 readonly relayUrl: string | null;
214 };
215
216 assert.equal(status.desired, false);
217 assert.equal(status.authenticated, false);
218 assert.equal(status.linked, false);
219 assert.equal(status.cloudUserId, null);
220 assert.equal(status.relayUrl, null);
221 }),
222 );
223
224 it.effect("reports actionable human-readable headless connect state", () =>
225 Effect.gen(function* () {
226 const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-status-human-test-"));
227 const { output } = yield* captureStdout(
228 runConnectCli(["connect", "status", "--base-dir", baseDir]),
229 );
230
231 assert.include(output, "T3 Connect\n Exposure: disabled");
232 assert.include(output, " Authorization: missing");
233 assert.include(output, " Environment link: not provisioned");
234 assert.include(output, "Next: Run `t3 connect link` to authorize and enable T3 Connect.");
235 }),
236 );
237
238 it.effect("logs in to headless connect without enabling access", () =>
239 Effect.gen(function* () {
240 const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-login-test-"));
241 const { secretsDir } = yield* deriveServerPaths(baseDir, undefined);
242 mkdirSync(secretsDir, { recursive: true });
243 writeFileSync(
244 join(secretsDir, "cloud-cli-oauth-token.bin"),
245 // @effect-diagnostics-next-line preferSchemaOverJson:off - Test fixture matches the persisted CLI token representation.
246 JSON.stringify({
247 accessToken: "access-token",
248 refreshToken: "refresh-token",
249 expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
250 }),
251 );
252
253 const login = yield* captureStdout(
254 runConnectCli(["connect", "login", "--base-dir", baseDir]),
255 );
256 const status = yield* captureStdout(
257 runConnectCli(["connect", "status", "--base-dir", baseDir, "--json"]),
258 );
259 // @effect-diagnostics-next-line preferSchemaOverJson:off - CLI JSON output is decoded as a presentation DTO.
260 const decoded = JSON.parse(status.output) as {
261 readonly desired: boolean;
262 readonly authenticated: boolean;
263 };
264
265 assert.equal(login.output, "Signed in to T3 Connect.");
266 assert.isFalse(decoded.desired);
267 assert.isTrue(decoded.authenticated);
268 }),
269 );
270
271 it.effect("disables headless connect without a running server", () =>
272 Effect.gen(function* () {
273 const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-unlink-test-"));
274 const { output } = yield* captureStdout(
275 runConnectCli(["connect", "unlink", "--base-dir", baseDir]),
276 );
277
278 assert.equal(output, "T3 Connect is disabled locally.");
279 }),
280 );
281
282 it.effect("logs out of headless connect and removes the stored CLI authorization", () =>
283 Effect.gen(function* () {
284 const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-logout-test-"));
285 const { secretsDir } = yield* deriveServerPaths(baseDir, undefined);
286 const tokenPath = join(secretsDir, "cloud-cli-oauth-token.bin");
287 mkdirSync(secretsDir, { recursive: true });
288 writeFileSync(tokenPath, "invalid persisted token");
289
290 const { output } = yield* captureStdout(
291 runConnectCli(["connect", "logout", "--base-dir", baseDir]),
292 );
293
294 assert.equal(output, "Signed out of T3 Connect locally.");
295 assert.isFalse(existsSync(tokenPath));
296 }),
297 );
298
299 it.effect("executes auth pairing subcommands and redacts secrets from list output", () =>
300 Effect.gen(function* () {
301 const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-auth-pairing-test-"));
302
303 const createdOutput = yield* captureStdout(
304 runCli(["auth", "pairing", "create", "--base-dir", baseDir, "--json"]),
305 );
306 // @effect-diagnostics-next-line preferSchemaOverJson:off
307 const created = JSON.parse(createdOutput.output) as {
308 readonly id: string;
309 readonly credential: string;
310 };
311 const listedOutput = yield* captureStdout(
312 runCli(["auth", "pairing", "list", "--base-dir", baseDir, "--json"]),
313 );
314 // @effect-diagnostics-next-line preferSchemaOverJson:off
315 const listed = JSON.parse(listedOutput.output) as ReadonlyArray<{
316 readonly id: string;
317 readonly credential?: string;
318 }>;
319
320 assert.equal(typeof created.id, "string");
321 assert.equal(typeof created.credential, "string");
322 assert.equal(created.credential.length > 0, true);
323 assert.equal(listed.length, 1);
324 assert.equal(listed[0]?.id, created.id);
325 assert.equal("credential" in (listed[0] ?? {}), false);
326 }),
327 );
328
329 it.effect("executes auth session subcommands and redacts secrets from list output", () =>
330 Effect.gen(function* () {
331 const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-auth-session-test-"));
332
333 const issuedOutput = yield* captureStdout(
334 runCli(["auth", "session", "issue", "--base-dir", baseDir, "--json"]),
335 );
336 // @effect-diagnostics-next-line preferSchemaOverJson:off
337 const issued = JSON.parse(issuedOutput.output) as {
338 readonly sessionId: string;
339 readonly token: string;
340 readonly scopes: ReadonlyArray<string>;
341 };
342 const listedOutput = yield* captureStdout(
343 runCli(["auth", "session", "list", "--base-dir", baseDir, "--json"]),
344 );
345 // @effect-diagnostics-next-line preferSchemaOverJson:off
346 const listed = JSON.parse(listedOutput.output) as ReadonlyArray<{
347 readonly sessionId: string;
348 readonly token?: string;
349 readonly scopes: ReadonlyArray<string>;
350 }>;
351
352 assert.equal(typeof issued.sessionId, "string");
353 assert.equal(typeof issued.token, "string");
354 assert.deepEqual(issued.scopes, [
355 "orchestration:read",
356 "orchestration:operate",
357 "terminal:operate",
358 "review:write",
359 "relay:read",
360 "access:read",
361 "access:write",
362 "relay:write",
363 ]);
364 assert.equal(listed.length, 1);
365 assert.equal(listed[0]?.sessionId, issued.sessionId);
366 assert.deepEqual(listed[0]?.scopes, [
367 "orchestration:read",
368 "orchestration:operate",
369 "terminal:operate",
370 "review:write",
371 "relay:read",
372 "access:read",
373 "access:write",
374 "relay:write",
375 ]);
376 assert.equal("token" in (listed[0] ?? {}), false);
377 }),
378 );
379
380 it.effect("rejects invalid ttl values before running auth commands", () =>
381 Effect.gen(function* () {
382 const error = yield* runCliWithRuntime(["auth", "pairing", "create", "--ttl", "soon"]).pipe(
383 Effect.flip,
384 );
385
386 if (!CliError.isCliError(error)) {
387 assert.fail(`Expected CliError, got ${String(error)}`);
388 }
389 if (error._tag !== "ShowHelp") {
390 assert.fail(`Expected ShowHelp, got ${error._tag}`);
391 }
392 assert.deepEqual(error.commandPath, ["t3", "auth", "pairing", "create"]);
393 const ttlError = error.errors[0] as CliError.CliError | undefined;
394 if (!ttlError || ttlError._tag !== "InvalidValue") {
395 assert.fail(`Expected InvalidValue, got ${String(ttlError?._tag)}`);
396 }
397 assert.equal(ttlError.option, "ttl");
398 assert.equal(ttlError.value, "soon");
399 assert.isTrue(ttlError.message.includes("Invalid duration"));
400 assert.isTrue(ttlError.message.includes("5m, 1h, 30d, or 15 minutes"));
401 }),
402 );
403
404 it.effect("adds, renames, and removes projects offline through the orchestration engine", () =>
405 Effect.gen(function* () {
406 const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-projects-offline-test-"));
407 const workspaceRoot = mkdtempSync(join(tmpdir(), "t3-cli-projects-workspace-"));
408
409 yield* runCliWithRuntime([
410 "project",
411 "add",
412 workspaceRoot,
413 "--title",
414 "Alpha",
415 "--base-dir",
416 baseDir,
417 ]);
418 const afterAdd = yield* readPersistedSnapshot(baseDir);
419 const addedProject = afterAdd.projects.find(
420 (project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null,
421 );
422 assert.isTrue(addedProject !== undefined);
423 assert.equal(addedProject?.title, "Alpha");
424
425 yield* runCliWithRuntime(["project", "rename", workspaceRoot, "Beta", "--base-dir", baseDir]);
426 const afterRename = yield* readPersistedSnapshot(baseDir);
427 const renamedProject = afterRename.projects.find(
428 (project) => project.id === addedProject?.id,
429 );
430 assert.equal(renamedProject?.title, "Beta");
431 assert.equal(renamedProject?.deletedAt, null);
432
433 yield* runCliWithRuntime([
434 "project",
435 "remove",
436 addedProject?.id ?? "",
437 "--base-dir",
438 baseDir,
439 ]);
440 const afterRemove = yield* readPersistedSnapshot(baseDir);
441 const removedProject = afterRemove.projects.find(
442 (project) => project.id === addedProject?.id,
443 );
444 assert.isTrue((removedProject?.deletedAt ?? null) !== null);
445 }),
446 );
447
448 it.effect("routes project commands through a running server when runtime state is present", () =>
449 Effect.gen(function* () {
450 const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-projects-live-test-"));
451 const workspaceRoot = mkdtempSync(join(tmpdir(), "t3-cli-projects-live-workspace-"));
452
453 yield* withLiveProjectCliServer(baseDir, () =>
454 Effect.gen(function* () {
455 yield* runCliWithRuntime([
456 "project",
457 "add",
458 workspaceRoot,
459 "--title",
460 "Live Project",
461 "--base-dir",
462 baseDir,
463 ]);
464 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
465 const readModel = yield* projectionSnapshotQuery.getSnapshot();
466 const addedProject = readModel.projects.find(
467 (project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null,
468 );
469 assert.isTrue(addedProject !== undefined);
470 assert.equal(addedProject?.title, "Live Project");
471 }),
472 );
473 }),
474 );
475
476 it.effect("rejects dev-url on project commands", () =>
477 Effect.gen(function* () {
478 const workspaceRoot = mkdtempSync(
479 join(tmpdir(), "t3-cli-projects-unknown-option-workspace-"),
480 );
481 const error = yield* runCliWithRuntime([
482 "project",
483 "add",
484 workspaceRoot,
485 "--dev-url",
486 "http://127.0.0.1:5173",
487 ]).pipe(Effect.flip);
488
489 if (!CliError.isCliError(error)) {
490 assert.fail(`Expected CliError, got ${String(error)}`);
491 }
492 if (error._tag !== "ShowHelp") {
493 assert.fail(`Expected ShowHelp, got ${error._tag}`);
494 }
495 assert.deepEqual(error.commandPath, ["t3", "project", "add"]);
496 const optionError = error.errors[0] as CliError.CliError | undefined;
497 if (!optionError || optionError._tag !== "UnrecognizedOption") {
498 assert.fail(`Expected UnrecognizedOption, got ${String(optionError?._tag)}`);
499 }
500 assert.equal(optionError.option, "--dev-url");
501 }),
502 );
503});