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