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

bin.test.ts

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