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

bin.test.ts

871 lines32.5 KB

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";
6import * as NodeChildProcess from "node:child_process";
7​
8import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
9import * as NodeServices from "@effect/platform-node/NodeServices";
10import {
11 CommandId,
12 EnvironmentOrchestrationHttpApi,
13 ProviderInstanceId,
14 ThreadId,
15} from "@t3tools/contracts";
16import * as NetService from "@t3tools/shared/Net";
17import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
18import { DEFAULT_SIGNAL_EXPORT } from "@t3tools/shared/observability";
19import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
20import { assert, it } from "@effect/vitest";
21import * as Effect from "effect/Effect";
22import * as DateTime from "effect/DateTime";
23import * as Layer from "effect/Layer";
24import * as HttpRouter from "effect/unstable/http/HttpRouter";
25import * as HttpServer from "effect/unstable/http/HttpServer";
26import * as HttpApi from "effect/unstable/httpapi/HttpApi";
27import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
28import * as CliError from "effect/unstable/cli/CliError";
29import * as TestConsole from "effect/testing/TestConsole";
30import { Command } from "effect/unstable/cli";
31​
32import { cli, makeCli } from "./bin.ts";
33import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts";
34import {
35 SERVICE_LAUNCHER_CONTEXT_ENV,
36 SERVICE_LAUNCHER_PROTOCOL,
37} from "./cloud/serviceProtocol.ts";
38import * as ServerConfig from "./config.ts";
39import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
40import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
41import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";
42import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
43import { orchestrationHttpApiLayer } from "./orchestration/http.ts";
44import * as ProjectCloneTracker from "./project/ProjectCloneTracker.ts";
45import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";
46import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts";
47import {
48 makePersistedServerRuntimeState,
49 persistServerRuntimeState,
50} from "./serverRuntimeState.ts";
51import * as WorkspacePaths from "./workspace/WorkspacePaths.ts";
52import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
53import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
54import { environmentAuthenticatedAuthLayer } from "./auth/http.ts";
55​
56import packageJson from "../package.json" with { type: "json" };
57​
58const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
59const DisconnectedLauncherChildLayer = Layer.mergeAll(
60 Layer.succeed(HostProcessEnvironment, {
61 ...process.env,
62 [SERVICE_LAUNCHER_CONTEXT_ENV]: JSON.stringify({
63 protocol: SERVICE_LAUNCHER_PROTOCOL,
64 childVersion: packageJson.version,
65 }),
66 }),
67 Layer.succeed(ServiceLauncherClient.ServiceLauncherHostProcess, {
68 connected: false,
69 send: () => false,
70 on: () => undefined,
71 off: () => undefined,
72 }),
73);
74class ProjectCliHttpApi extends HttpApi.make("environment").add(EnvironmentOrchestrationHttpApi) {}
75​
76const connectCli = makeCli({ cloudEnabled: true });
77const noConnectCli = makeCli({ cloudEnabled: false });
78const runCli = (args: ReadonlyArray<string>, command = cli) =>
79 Command.runWith(command, { version: "0.0.0" })(args);
80const runConnectCli = (args: ReadonlyArray<string>) => runCli(args, connectCli);
81const runCliWithRuntime = (args: ReadonlyArray<string>) =>
82 runCli(args).pipe(Effect.provide(CliRuntimeLayer));
83​
84const captureStdout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
85 Effect.gen(function* () {
86 const result = yield* effect;
87 const output =
88 (yield* TestConsole.logLines).findLast((line): line is string => typeof line === "string") ??
89 "";
90 return { result, output };
91 }).pipe(Effect.provide(Layer.mergeAll(CliRuntimeLayer, TestConsole.layer)));
92​
93const makeCliTestServerConfig = (baseDir: string) =>
94 Effect.gen(function* () {
95 const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, undefined);
96 return {
97 logLevel: "Info",
98 traceMinLevel: "Info",
99 traceTimingEnabled: true,
100 traceBatchWindowMs: 200,
101 traceMaxBytes: 10 * 1024 * 1024,
102 traceMaxFiles: 10,
103 otlpTracesUrl: undefined,
104 otlpMetricsUrl: undefined,
105 otlpLogsUrl: undefined,
106 otlpTracesExport: DEFAULT_SIGNAL_EXPORT,
107 otlpMetricsExport: DEFAULT_SIGNAL_EXPORT,
108 otlpLogsExport: DEFAULT_SIGNAL_EXPORT,
109 otlpServiceName: "t3-server",
110 otelEnvironment: OtelEnvironment.none,
111 mode: "web",
112 port: 0,
113 host: "127.0.0.1",
114 cwd: process.cwd(),
115 baseDir,
116 ...derivedPaths,
117 staticDir: undefined,
118 devUrl: undefined,
119 devAllowedOrigins: [],
120 noBrowser: true,
121 startupPresentation: "browser",
122 desktopBootstrapToken: undefined,
123 autoBootstrapProjectFromCwd: false,
124 logWebSocketEvents: false,
125 tailscaleServeEnabled: false,
126 tailscaleServePort: 443,
127 } satisfies ServerConfig.ServerConfig["Service"];
128 });
129​
130const makeProjectPersistenceLayer = (config: ServerConfig.ServerConfig["Service"]) =>
131 Layer.mergeAll(
132 OrchestrationLayerLive.pipe(
133 Layer.provideMerge(RepositoryIdentityResolver.layer),
134 Layer.provideMerge(SqlitePersistenceLayerLive),
135 ),
136 WorkspacePaths.layer,
137 ).pipe(Layer.provideMerge(NodeServices.layer), Layer.provide(ServerConfig.layer(config)));
138​
139const readPersistedSnapshot = (baseDir: string) =>
140 Effect.gen(function* () {
141 const config = yield* makeCliTestServerConfig(baseDir);
142 return yield* Effect.gen(function* () {
143 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
144 return yield* projectionSnapshotQuery.getSnapshot();
145 }).pipe(Effect.provide(makeProjectPersistenceLayer(config)));
146 });
147​
148const makeProjectLookupFixture = Effect.fn("makeProjectLookupFixture")(function* (
149 withThread: boolean,
150 removeWorkspace: boolean,
151) {
152 const baseDir = NodeFS.mkdtempSync(
153 NodePath.join(NodeOS.tmpdir(), "t3-cli-project-lookup-state-"),
154 );
155 const workspaceRoot = NodeFS.mkdtempSync(
156 NodePath.join(NodeOS.tmpdir(), "t3-cli-project-lookup-git-"),
157 );
158 NodeChildProcess.execFileSync("git", ["init", "--initial-branch=main", workspaceRoot], {
159 stdio: "ignore",
160 });
161 yield* runCliWithRuntime(["project", "add", workspaceRoot, "--base-dir", baseDir]);
162 const snapshot = yield* readPersistedSnapshot(baseDir);
163 const project = snapshot.projects.find((candidate) => candidate.workspaceRoot === workspaceRoot)!;
164 assert.isDefined(project);
165 if (withThread) {
166 const config = yield* makeCliTestServerConfig(baseDir);
167 yield* Effect.gen(function* () {
168 const engine = yield* OrchestrationEngine.OrchestrationEngineService;
169 yield* engine.dispatch({
170 type: "thread.create",
171 commandId: CommandId.make("cmd-project-lookup-thread"),
172 threadId: ThreadId.make("thread-project-lookup"),
173 projectId: project.id,
174 title: "Project lookup test",
175 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" },
176 interactionMode: "default",
177 runtimeMode: "approval-required",
178 branch: null,
179 worktreePath: null,
180 createdAt: DateTime.formatIso(yield* DateTime.now),
181 });
182 }).pipe(Effect.provide(makeProjectPersistenceLayer(config)));
183 }
184 if (removeWorkspace) {
185 NodeFS.renameSync(workspaceRoot, `${workspaceRoot}-removed`);
186 assert.isFalse(NodeFS.existsSync(workspaceRoot));
187 }
188 return { baseDir, workspaceRoot, project };
189});
190​
191it.layer(NodeServices.layer)("project lookup with unavailable workspaces", (it) => {
192 it.effect("removes an empty project by ID without force after its directory is gone", () =>
193 Effect.gen(function* () {
194 const { baseDir, project } = yield* makeProjectLookupFixture(false, true);
195 yield* runCliWithRuntime(["project", "remove", project.id, "--base-dir", baseDir]);
196 const after = yield* readPersistedSnapshot(baseDir);
197 assert.isNotNull(after.projects.find((candidate) => candidate.id === project.id)!.deletedAt);
198 }),
199 );
200​
201 it.effect.each([true, false])(
202 "requires force for child threads, then removes by ID; missing=%s",
203 (removeWorkspace) =>
204 Effect.gen(function* () {
205 const { baseDir, project } = yield* makeProjectLookupFixture(true, removeWorkspace);
206 const error = yield* runCliWithRuntime([
207 "project",
208 "remove",
209 project.id,
210 "--base-dir",
211 baseDir,
212 ]).pipe(Effect.flip);
213 assert.include(error.message, "cannot be deleted without force=true");
214 const retained = yield* readPersistedSnapshot(baseDir);
215 assert.isNull(
216 retained.projects.find((candidate) => candidate.id === project.id)!.deletedAt,
217 );
218 assert.isNull(
219 retained.threads.find((thread) => thread.id === "thread-project-lookup")!.deletedAt,
220 );
221 yield* runCliWithRuntime([
222 "project",
223 "remove",
224 project.id,
225 "--force",
226 "--base-dir",
227 baseDir,
228 ]);
229 const after = yield* readPersistedSnapshot(baseDir);
230 assert.isNotNull(
231 after.projects.find((candidate) => candidate.id === project.id)!.deletedAt,
232 );
233 assert.isNotNull(
234 after.threads.find((thread) => thread.id === "thread-project-lookup")!.deletedAt,
235 );
236 }),
237 );
238​
239 it.effect("cannot remove the old environment's ID from a replacement empty database", () =>
240 Effect.gen(function* () {
241 const { baseDir, project } = yield* makeProjectLookupFixture(true, true);
242 const replacementDir = NodeFS.mkdtempSync(
243 NodePath.join(NodeOS.tmpdir(), "t3-cli-project-lookup-new-state-"),
244 );
245 const error = yield* runCliWithRuntime([
246 "project",
247 "remove",
248 project.id,
249 "--force",
250 "--base-dir",
251 replacementDir,
252 ]).pipe(Effect.flip);
253 assert.include(error.message, "No active project found");
254 assert.include(String(error.cause), "Workspace root does not exist");
255 const original = yield* readPersistedSnapshot(baseDir);
256 assert.isNull(original.projects.find((candidate) => candidate.id === project.id)!.deletedAt);
257 const replacement = yield* readPersistedSnapshot(replacementDir);
258 assert.equal(replacement.projects.length, 0);
259 }),
260 );
261​
262 it.effect("renames by ID and stored path, then force removes after the directory is gone", () =>
263 Effect.gen(function* () {
264 const { baseDir, workspaceRoot, project } = yield* makeProjectLookupFixture(true, true);
265 yield* runCliWithRuntime([
266 "project",
267 "rename",
268 project.id,
269 "Renamed by ID",
270 "--base-dir",
271 baseDir,
272 ]);
273 const afterIdRename = yield* readPersistedSnapshot(baseDir);
274 assert.equal(
275 afterIdRename.projects.find((candidate) => candidate.id === project.id)!.title,
276 "Renamed by ID",
277 );
278 yield* runCliWithRuntime([
279 "project",
280 "rename",
281 workspaceRoot,
282 "Renamed by stored path",
283 "--base-dir",
284 baseDir,
285 ]);
286 const afterPathRename = yield* readPersistedSnapshot(baseDir);
287 assert.equal(
288 afterPathRename.projects.find((candidate) => candidate.id === project.id)!.title,
289 "Renamed by stored path",
290 );
291 const error = yield* runCliWithRuntime([
292 "project",
293 "remove",
294 workspaceRoot,
295 "--base-dir",
296 baseDir,
297 ]).pipe(Effect.flip);
298 assert.include(error.message, "cannot be deleted without force=true");
299 yield* runCliWithRuntime([
300 "project",
301 "remove",
302 workspaceRoot,
303 "--force",
304 "--base-dir",
305 baseDir,
306 ]);
307 const after = yield* readPersistedSnapshot(baseDir);
308 assert.isNotNull(after.projects.find((candidate) => candidate.id === project.id)!.deletedAt);
309 assert.isNotNull(
310 after.threads.find((thread) => thread.id === "thread-project-lookup")!.deletedAt,
311 );
312 assert.isFalse(NodeFS.existsSync(workspaceRoot));
313 }),
314 );
315​
316 it.effect("preserves normalized paths and distinct symlink project entries", () =>
317 Effect.gen(function* () {
318 const { baseDir, workspaceRoot, project } = yield* makeProjectLookupFixture(false, false);
319 const normalizedInput = `${workspaceRoot}${NodePath.sep}.`;
320 yield* runCliWithRuntime([
321 "project",
322 "rename",
323 normalizedInput,
324 "Normalized",
325 "--base-dir",
326 baseDir,
327 ]);
328 const renamed = yield* readPersistedSnapshot(baseDir);
329 assert.equal(
330 renamed.projects.find((candidate) => candidate.id === project.id)!.title,
331 "Normalized",
332 );
333 const aliasPath = `${workspaceRoot}-alias`;
334 NodeFS.symlinkSync(workspaceRoot, aliasPath, "junction");
335 const error = yield* runCliWithRuntime([
336 "project",
337 "remove",
338 aliasPath,
339 "--force",
340 "--base-dir",
341 baseDir,
342 ]).pipe(Effect.flip);
343 assert.include(error.message, "No active project found");
344 yield* runCliWithRuntime(["project", "add", aliasPath, "--base-dir", baseDir]);
345 const added = yield* readPersistedSnapshot(baseDir);
346 const aliasProject = added.projects.find(
347 (candidate) => candidate.workspaceRoot === aliasPath,
348 )!;
349 assert.notEqual(aliasProject.id, project.id);
350 yield* runCliWithRuntime([
351 "project",
352 "remove",
353 `${aliasPath}${NodePath.sep}.`,
354 "--base-dir",
355 baseDir,
356 ]);
357 const after = yield* readPersistedSnapshot(baseDir);
358 assert.isNotNull(
359 after.projects.find((candidate) => candidate.id === aliasProject.id)!.deletedAt,
360 );
361 assert.isNull(after.projects.find((candidate) => candidate.id === project.id)!.deletedAt);
362 assert.isTrue(NodeFS.existsSync(workspaceRoot));
363 }),
364 );
365});
366​
367const withLiveProjectCliServer = <A, E, R>(baseDir: string, run: () => Effect.Effect<A, E, R>) =>
368 Effect.gen(function* () {
369 const config = yield* makeCliTestServerConfig(baseDir);
370 const routesLayer = HttpApiBuilder.layer(ProjectCliHttpApi).pipe(
371 Layer.provide(
372 orchestrationHttpApiLayer.pipe(
373 Layer.provide(
374 Layer.mock(ProjectCloneTracker.ProjectCloneTracker)({
375 get: () => Effect.succeed(null),
376 discard: () => Effect.void,
377 }),
378 ),
379 ),
380 ),
381 Layer.provide(environmentAuthenticatedAuthLayer),
382 );
383 const appLayer = HttpRouter.serve(routesLayer, {
384 disableListenLog: true,
385 disableLogger: true,
386 }).pipe(
387 Layer.provideMerge(
388 EnvironmentAuth.layer.pipe(
389 Layer.provideMerge(SqlitePersistenceLayerLive),
390 Layer.provide(ServerEnvironment.identityLayer),
391 Layer.provide(ServerSecretStore.layer),
392 ),
393 ),
394 Layer.provideMerge(makeProjectPersistenceLayer(config)),
395 Layer.provideMerge(
396 NodeHttpServer.layer(NodeHttp.createServer, {
397 host: "127.0.0.1",
398 port: 0,
399 }),
400 ),
401 Layer.provideMerge(NodeServices.layer),
402 Layer.provide(ServerConfig.layer(config)),
403 );
404​
405 return yield* Effect.scoped(
406 Effect.gen(function* () {
407 const server = yield* HttpServer.HttpServer;
408 const address = server.address;
409 if (typeof address === "string" || !("port" in address)) {
410 assert.fail(`Expected TCP address, got ${address}`);
411 }
412 yield* persistServerRuntimeState({
413 path: config.serverRuntimeStatePath,
414 state: yield* makePersistedServerRuntimeState({
415 config,
416 port: address.port,
417 }),
418 });
419 return yield* run();
420 }).pipe(Effect.provide(Layer.mergeAll(appLayer, NodeServices.layer))),
421 );
422 });
423​
424it.layer(NodeServices.layer)("bin cli parsing", (it) => {
425 it.effect("accepts the built-in lowercase log-level flag values", () =>
426 Effect.gen(function* () {
427 const { output } = yield* captureStdout(runCli(["--log-level", "debug", "--version"]));
428​
429 assert.include(output, "0.0.0");
430 }),
431 );
432​
433 it.effect("accepts canonical --no-<flag> boolean negation", () =>
434 Effect.gen(function* () {
435 const { output } = yield* captureStdout(runCli(["--no-log-websocket-events", "--version"]));
436​
437 assert.include(output, "0.0.0");
438 }),
439 );
440​
441 it.effect("rejects invalid log-level casing before launching the server", () =>
442 Effect.gen(function* () {
443 const error = yield* runCliWithRuntime(["--log-level", "Debug"]).pipe(Effect.flip);
444​
445 if (!CliError.isCliError(error)) {
446 assert.fail(`Expected CliError, got ${String(error)}`);
447 }
448 if (error._tag !== "InvalidValue") {
449 assert.fail(`Expected InvalidValue, got ${error._tag}`);
450 }
451 assert.equal(error.option, "log-level");
452 assert.equal(error.value, "Debug");
453 }),
454 );
455​
456 it.effect("rejects connect commands when public configuration is missing", () =>
457 Effect.gen(function* () {
458 const error = yield* runCli(["connect", "status"], noConnectCli).pipe(Effect.flip);
459​
460 if (!CliError.isCliError(error)) {
461 assert.fail(`Expected CliError, got ${String(error)}`);
462 }
463 if (error._tag !== "ShowHelp") {
464 assert.fail(`Expected ShowHelp, got ${error._tag}`);
465 }
466 assert.deepEqual(error.commandPath, ["t3", "connect"]);
467 assert.include(error.errors[0]?.message ?? "", "missing T3 Connect public configuration");
468​
469 const output = (yield* TestConsole.errorLines).join("\n");
470 assert.include(output, "ERROR");
471 assert.include(output, "missing T3 Connect public configuration");
472 }).pipe(Effect.provide(Layer.mergeAll(CliRuntimeLayer, TestConsole.layer))),
473 );
474​
475 it.effect("exposes service lifecycle commands without T3 Connect configuration", () =>
476 Effect.gen(function* () {
477 const { output } = yield* captureStdout(runCli(["service", "--help"], noConnectCli));
478​
479 assert.include(output, "Manage the T3 Code background service.");
480 assert.include(output, "install");
481 assert.include(output, "uninstall");
482 assert.include(output, "update");
483 assert.include(output, "status");
484 }),
485 );
486​
487 it.effect("reports fresh headless connect state without requiring local configuration", () =>
488 Effect.gen(function* () {
489 const baseDir = NodeFS.mkdtempSync(
490 NodePath.join(NodeOS.tmpdir(), "t3-cli-cloud-status-test-"),
491 );
492 const { output } = yield* captureStdout(
493 runConnectCli(["connect", "status", "--base-dir", baseDir, "--json"]),
494 );
495 // @effect-diagnostics-next-line preferSchemaOverJson:off - CLI JSON output is decoded as a presentation DTO.
496 const status = JSON.parse(output) as {
497 readonly desired: boolean;
498 readonly authenticated: boolean;
499 readonly linked: boolean;
500 readonly cloudUserId: string | null;
501 readonly relayUrl: string | null;
502 };
503​
504 assert.equal(status.desired, false);
505 assert.equal(status.authenticated, false);
506 assert.equal(status.linked, false);
507 assert.equal(status.cloudUserId, null);
508 assert.equal(status.relayUrl, null);
509 }).pipe(Effect.provide(DisconnectedLauncherChildLayer)),
510 );
511​
512 it.effect("reports actionable human-readable headless connect state", () =>
513 Effect.gen(function* () {
514 const baseDir = NodeFS.mkdtempSync(
515 NodePath.join(NodeOS.tmpdir(), "t3-cli-cloud-status-human-test-"),
516 );
517 const { output } = yield* captureStdout(
518 runConnectCli(["connect", "status", "--base-dir", baseDir]),
519 );
520​
521 assert.include(output, "T3 Connect\n Exposure: disabled");
522 assert.include(output, " Authorization: missing");
523 assert.include(output, " Environment link: not provisioned");
524 assert.include(output, "Next: Run `t3 connect link` to authorize and enable T3 Connect.");
525 }),
526 );
527​
528 it.effect("accepts the --headless login override without enabling access", () =>
529 Effect.gen(function* () {
530 const baseDir = NodeFS.mkdtempSync(
531 NodePath.join(NodeOS.tmpdir(), "t3-cli-cloud-login-test-"),
532 );
533 const { secretsDir } = yield* ServerConfig.deriveServerPaths(baseDir, undefined);
534 NodeFS.mkdirSync(secretsDir, { recursive: true });
535 NodeFS.writeFileSync(
536 NodePath.join(secretsDir, "cloud-cli-oauth-token.bin"),
537 // @effect-diagnostics-next-line preferSchemaOverJson:off - Test fixture matches the persisted CLI token representation.
538 JSON.stringify({
539 accessToken: "access-token",
540 refreshToken: "refresh-token",
541 expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
542 }),
543 );
544​
545 const login = yield* captureStdout(
546 runConnectCli(["connect", "login", "--base-dir", baseDir, "--headless"]),
547 );
548 const status = yield* captureStdout(
549 runConnectCli(["connect", "status", "--base-dir", baseDir, "--json"]),
550 );
551 // @effect-diagnostics-next-line preferSchemaOverJson:off - CLI JSON output is decoded as a presentation DTO.
552 const decoded = JSON.parse(status.output) as {
553 readonly desired: boolean;
554 readonly authenticated: boolean;
555 };
556​
557 assert.equal(login.output, "✓ Signed in");
558 assert.isFalse(decoded.desired);
559 assert.isTrue(decoded.authenticated);
560 }),
561 );
562​
563 it.effect("disables headless connect without a running server", () =>
564 Effect.gen(function* () {
565 const baseDir = NodeFS.mkdtempSync(
566 NodePath.join(NodeOS.tmpdir(), "t3-cli-cloud-unlink-test-"),
567 );
568 const { output } = yield* captureStdout(
569 runConnectCli(["connect", "unlink", "--base-dir", baseDir]),
570 );
571​
572 assert.equal(output, "T3 Connect is disabled locally.");
573 }),
574 );
575​
576 it.effect("logs out of headless connect and removes the stored CLI authorization", () =>
577 Effect.gen(function* () {
578 const baseDir = NodeFS.mkdtempSync(
579 NodePath.join(NodeOS.tmpdir(), "t3-cli-cloud-logout-test-"),
580 );
581 const { secretsDir } = yield* ServerConfig.deriveServerPaths(baseDir, undefined);
582 const tokenPath = NodePath.join(secretsDir, "cloud-cli-oauth-token.bin");
583 NodeFS.mkdirSync(secretsDir, { recursive: true });
584 NodeFS.writeFileSync(tokenPath, "invalid persisted token");
585​
586 const { output } = yield* captureStdout(
587 runConnectCli(["connect", "logout", "--base-dir", baseDir]),
588 );
589​
590 assert.equal(
591 output,
592 "Signed out of T3 Connect locally.\nThe background service is managed separately with `t3 service`.",
593 );
594 assert.isFalse(NodeFS.existsSync(tokenPath));
595 }),
596 );
597​
598 it.effect("executes auth pairing subcommands and redacts secrets from list output", () =>
599 Effect.gen(function* () {
600 const baseDir = NodeFS.mkdtempSync(
601 NodePath.join(NodeOS.tmpdir(), "t3-cli-auth-pairing-test-"),
602 );
603​
604 const createdOutput = yield* captureStdout(
605 runCli(["auth", "pairing", "create", "--base-dir", baseDir, "--json"]),
606 );
607 // @effect-diagnostics-next-line preferSchemaOverJson:off
608 const created = JSON.parse(createdOutput.output) as {
609 readonly id: string;
610 readonly credential: string;
611 };
612 const listedOutput = yield* captureStdout(
613 runCli(["auth", "pairing", "list", "--base-dir", baseDir, "--json"]),
614 );
615 // @effect-diagnostics-next-line preferSchemaOverJson:off
616 const listed = JSON.parse(listedOutput.output) as ReadonlyArray<{
617 readonly id: string;
618 readonly credential?: string;
619 }>;
620​
621 assert.equal(typeof created.id, "string");
622 assert.equal(typeof created.credential, "string");
623 assert.equal(created.credential.length > 0, true);
624 assert.equal(listed.length, 1);
625 assert.equal(listed[0]?.id, created.id);
626 assert.equal("credential" in (listed[0] ?? {}), false);
627 }),
628 );
629​
630 it.effect("executes auth session subcommands and redacts secrets from list output", () =>
631 Effect.gen(function* () {
632 const baseDir = NodeFS.mkdtempSync(
633 NodePath.join(NodeOS.tmpdir(), "t3-cli-auth-session-test-"),
634 );
635​
636 const issuedOutput = yield* captureStdout(
637 runCli(["auth", "session", "issue", "--base-dir", baseDir, "--json"]),
638 );
639 // @effect-diagnostics-next-line preferSchemaOverJson:off
640 const issued = JSON.parse(issuedOutput.output) as {
641 readonly sessionId: string;
642 readonly token: string;
643 readonly scopes: ReadonlyArray<string>;
644 };
645 const listedOutput = yield* captureStdout(
646 runCli(["auth", "session", "list", "--base-dir", baseDir, "--json"]),
647 );
648 // @effect-diagnostics-next-line preferSchemaOverJson:off
649 const listed = JSON.parse(listedOutput.output) as ReadonlyArray<{
650 readonly sessionId: string;
651 readonly token?: string;
652 readonly scopes: ReadonlyArray<string>;
653 }>;
654​
655 assert.equal(typeof issued.sessionId, "string");
656 assert.equal(typeof issued.token, "string");
657 assert.deepEqual(issued.scopes, [
658 "orchestration:read",
659 "orchestration:operate",
660 "terminal:operate",
661 "review:write",
662 "relay:read",
663 "access:read",
664 "access:write",
665 "relay:write",
666 ]);
667 assert.equal(listed.length, 1);
668 assert.equal(listed[0]?.sessionId, issued.sessionId);
669 assert.deepEqual(listed[0]?.scopes, [
670 "orchestration:read",
671 "orchestration:operate",
672 "terminal:operate",
673 "review:write",
674 "relay:read",
675 "access:read",
676 "access:write",
677 "relay:write",
678 ]);
679 assert.equal("token" in (listed[0] ?? {}), false);
680 }).pipe(Effect.provide(DisconnectedLauncherChildLayer)),
681 );
682​
683 it.effect("rejects invalid ttl values before running auth commands", () =>
684 Effect.gen(function* () {
685 const error = yield* runCliWithRuntime(["auth", "pairing", "create", "--ttl", "soon"]).pipe(
686 Effect.flip,
687 );
688​
689 if (!CliError.isCliError(error)) {
690 assert.fail(`Expected CliError, got ${String(error)}`);
691 }
692 if (error._tag !== "ShowHelp") {
693 assert.fail(`Expected ShowHelp, got ${error._tag}`);
694 }
695 assert.deepEqual(error.commandPath, ["t3", "auth", "pairing", "create"]);
696 const ttlError = error.errors[0] as CliError.CliError | undefined;
697 if (!ttlError || ttlError._tag !== "InvalidValue") {
698 assert.fail(`Expected InvalidValue, got ${String(ttlError?._tag)}`);
699 }
700 assert.equal(ttlError.option, "ttl");
701 assert.equal(ttlError.value, "soon");
702 assert.isTrue(ttlError.message.includes("Invalid duration"));
703 assert.isTrue(ttlError.message.includes("5m, 1h, 30d, or 15 minutes"));
704 }),
705 );
706​
707 it.effect("adds, renames, and removes projects offline through the orchestration engine", () =>
708 Effect.gen(function* () {
709 const baseDir = NodeFS.mkdtempSync(
710 NodePath.join(NodeOS.tmpdir(), "t3-cli-projects-offline-test-"),
711 );
712 const workspaceRoot = NodeFS.mkdtempSync(
713 NodePath.join(NodeOS.tmpdir(), "t3-cli-projects-workspace-"),
714 );
715​
716 yield* runCliWithRuntime([
717 "project",
718 "add",
719 workspaceRoot,
720 "--title",
721 "Alpha",
722 "--base-dir",
723 baseDir,
724 ]);
725 const afterAdd = yield* readPersistedSnapshot(baseDir);
726 const addedProject = afterAdd.projects.find(
727 (project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null,
728 );
729 assert.isTrue(addedProject !== undefined);
730 assert.equal(addedProject?.title, "Alpha");
731​
732 yield* runCliWithRuntime(["project", "rename", workspaceRoot, "Beta", "--base-dir", baseDir]);
733 const afterRename = yield* readPersistedSnapshot(baseDir);
734 const renamedProject = afterRename.projects.find(
735 (project) => project.id === addedProject?.id,
736 );
737 assert.equal(renamedProject?.title, "Beta");
738 assert.equal(renamedProject?.deletedAt, null);
739​
740 yield* runCliWithRuntime([
741 "project",
742 "remove",
743 addedProject?.id ?? "",
744 "--base-dir",
745 baseDir,
746 ]);
747 const afterRemove = yield* readPersistedSnapshot(baseDir);
748 const removedProject = afterRemove.projects.find(
749 (project) => project.id === addedProject?.id,
750 );
751 assert.isTrue((removedProject?.deletedAt ?? null) !== null);
752 }),
753 );
754​
755 it.effect("force removes projects that still contain threads", () =>
756 Effect.gen(function* () {
757 const baseDir = NodeFS.mkdtempSync(
758 NodePath.join(NodeOS.tmpdir(), "t3-cli-projects-force-remove-test-"),
759 );
760 const workspaceRoot = NodeFS.mkdtempSync(
761 NodePath.join(NodeOS.tmpdir(), "t3-cli-projects-force-remove-workspace-"),
762 );
763​
764 yield* runCliWithRuntime(["project", "add", workspaceRoot, "--base-dir", baseDir]);
765 const afterAdd = yield* readPersistedSnapshot(baseDir);
766 const project = afterAdd.projects.find(
767 (candidate) => candidate.workspaceRoot === workspaceRoot && candidate.deletedAt === null,
768 );
769 assert.isTrue(project !== undefined);
770​
771 const config = yield* makeCliTestServerConfig(baseDir);
772 yield* Effect.gen(function* () {
773 const engine = yield* OrchestrationEngine.OrchestrationEngineService;
774 yield* engine.dispatch({
775 type: "thread.create",
776 commandId: CommandId.make("cmd-cli-force-remove-thread"),
777 threadId: ThreadId.make("thread-cli-force-remove"),
778 projectId: project!.id,
779 title: "Thread",
780 modelSelection: {
781 instanceId: ProviderInstanceId.make("codex"),
782 model: "gpt-5-codex",
783 },
784 interactionMode: "default",
785 runtimeMode: "approval-required",
786 branch: null,
787 worktreePath: null,
788 createdAt: DateTime.formatIso(yield* DateTime.now),
789 });
790 }).pipe(Effect.provide(makeProjectPersistenceLayer(config)));
791​
792 yield* runCliWithRuntime([
793 "project",
794 "remove",
795 project!.id,
796 "--force",
797 "--base-dir",
798 baseDir,
799 ]);
800 const afterRemove = yield* readPersistedSnapshot(baseDir);
801 assert.isTrue(
802 (afterRemove.projects.find((candidate) => candidate.id === project!.id)?.deletedAt ??
803 null) !== null,
804 );
805 assert.isTrue(
806 (afterRemove.threads.find((thread) => thread.id === "thread-cli-force-remove")?.deletedAt ??
807 null) !== null,
808 );
809 }),
810 );
811​
812 it.effect("routes project commands through a running server when runtime state is present", () =>
813 Effect.gen(function* () {
814 const baseDir = NodeFS.mkdtempSync(
815 NodePath.join(NodeOS.tmpdir(), "t3-cli-projects-live-test-"),
816 );
817 const workspaceRoot = NodeFS.mkdtempSync(
818 NodePath.join(NodeOS.tmpdir(), "t3-cli-projects-live-workspace-"),
819 );
820​
821 yield* withLiveProjectCliServer(baseDir, () =>
822 Effect.gen(function* () {
823 yield* runCliWithRuntime([
824 "project",
825 "add",
826 workspaceRoot,
827 "--title",
828 "Live Project",
829 "--base-dir",
830 baseDir,
831 ]);
832 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
833 const readModel = yield* projectionSnapshotQuery.getSnapshot();
834 const addedProject = readModel.projects.find(
835 (project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null,
836 );
837 assert.isTrue(addedProject !== undefined);
838 assert.equal(addedProject?.title, "Live Project");
839 }),
840 );
841 }),
842 );
843​
844 it.effect("rejects dev-url on project commands", () =>
845 Effect.gen(function* () {
846 const workspaceRoot = NodeFS.mkdtempSync(
847 NodePath.join(NodeOS.tmpdir(), "t3-cli-projects-unknown-option-workspace-"),
848 );
849 const error = yield* runCliWithRuntime([
850 "project",
851 "add",
852 workspaceRoot,
853 "--dev-url",
854 "http://127.0.0.1:5173",
855 ]).pipe(Effect.flip);
856​
857 if (!CliError.isCliError(error)) {
858 assert.fail(`Expected CliError, got ${String(error)}`);
859 }
860 if (error._tag !== "ShowHelp") {
861 assert.fail(`Expected ShowHelp, got ${error._tag}`);
862 }
863 assert.deepEqual(error.commandPath, ["t3", "project", "add"]);
864 const optionError = error.errors[0] as CliError.CliError | undefined;
865 if (!optionError || optionError._tag !== "UnrecognizedOption") {
866 assert.fail(`Expected UnrecognizedOption, got ${String(optionError?._tag)}`);
867 }
868 assert.equal(optionError.option, "--dev-url");
869 }),
870 );
871});