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

project.test.ts

449 lines17.3 KB

1import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
2import { DEFAULT_SIGNAL_EXPORT } from "@t3tools/shared/observability";
3// @effect-diagnostics nodeBuiltinImport:off - CLI integration uses temporary Node paths.
4import * as NodeFS from "node:fs";
5import * as NodeOS from "node:os";
6import * as NodePath from "node:path";
7​
8import * as NodeServices from "@effect/platform-node/NodeServices";
9import { assert, it } from "@effect/vitest";
10import {
11 CommandId,
12 EnvironmentInternalError,
13 EventId,
14 ProviderInstanceId,
15 ThreadId,
16 type OrchestrationV2AppThread,
17 type ProjectId,
18} from "@t3tools/contracts";
19import * as NetService from "@t3tools/shared/Net";
20import * as DateTime from "effect/DateTime";
21import * as Effect from "effect/Effect";
22import * as FileSystem from "effect/FileSystem";
23import * as Layer from "effect/Layer";
24import * as References from "effect/References";
25import * as Stream from "effect/Stream";
26import { Command } from "effect/unstable/cli";
27​
28import { cli } from "../binCli.ts";
29import * as ServerConfig from "../config.ts";
30import { EventSinkV2 } from "../orchestration-v2/EventSink.ts";
31import * as EventStore from "../orchestration-v2/EventStore.ts";
32import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
33import {
34 OrchestrationV2EventSinkLayerLive,
35 ProjectServiceLayerLive,
36} from "../orchestration-v2/runtimeLayer.ts";
37import { layerConfig as SqlitePersistenceLayerLive } from "../persistence/Layers/Sqlite.ts";
38import * as ProjectEnrichmentService from "../project/ProjectEnrichmentService.ts";
39import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
40import * as ProjectService from "../project/ProjectService.ts";
41import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
42import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts";
43import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
44import {
45 ProjectLiveServerDeclaredResponseError,
46 ProjectLiveServerRequestError,
47 projectCommandErrorFromLiveServerRequest,
48} from "./project.ts";
49​
50const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
51const runCli = (args: ReadonlyArray<string>) =>
52 Command.runWith(cli, { version: "0.0.0" })(args).pipe(Effect.provide(CliRuntimeLayer));
53​
54const makeConfig = (baseDir: string) =>
55 Effect.gen(function* () {
56 const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, undefined);
57 return {
58 logLevel: "Info",
59 traceMinLevel: "Info",
60 traceTimingEnabled: true,
61 traceBatchWindowMs: 200,
62 traceMaxBytes: 10 * 1024 * 1024,
63 traceMaxFiles: 10,
64 otelEnvironment: OtelEnvironment.none,
65 otlpTracesUrl: undefined,
66 otlpMetricsUrl: undefined,
67 otlpLogsUrl: undefined,
68 otlpTracesExport: DEFAULT_SIGNAL_EXPORT,
69 otlpMetricsExport: DEFAULT_SIGNAL_EXPORT,
70 otlpLogsExport: DEFAULT_SIGNAL_EXPORT,
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 devAllowedOrigins: [],
81 noBrowser: true,
82 startupPresentation: "browser",
83 desktopBootstrapToken: undefined,
84 autoBootstrapProjectFromCwd: false,
85 logWebSocketEvents: false,
86 tailscaleServeEnabled: false,
87 tailscaleServePort: 443,
88 } satisfies ServerConfig.ServerConfig["Service"];
89 });
90​
91const readProjects = (baseDir: string) =>
92 Effect.gen(function* () {
93 const config = yield* makeConfig(baseDir);
94 const layer = ProjectServiceLayerLive.pipe(
95 Layer.provideMerge(ProjectEnrichmentService.layer),
96 Layer.provideMerge(RepositoryIdentityResolver.layer),
97 Layer.provideMerge(ProjectFaviconResolver.layer),
98 Layer.provideMerge(T3ProjectFileLoader.layer),
99 Layer.provideMerge(WorkspacePaths.layer),
100 Layer.provideMerge(SqlitePersistenceLayerLive),
101 Layer.provideMerge(NodeServices.layer),
102 Layer.provide(ServerConfig.layer(config)),
103 Layer.provide(Layer.succeed(References.MinimumLogLevel, config.logLevel)),
104 );
105 return yield* ProjectService.ProjectService.pipe(
106 Effect.flatMap((projects) => projects.snapshot),
107 Effect.provide(layer),
108 );
109 });
110​
111it("maps declared server failures into structural project command errors", () => {
112 const cause = new EnvironmentInternalError({
113 code: "internal_error",
114 reason: "access_token_issuance_failed",
115 traceId: "trace-123",
116 });
117​
118 const error = projectCommandErrorFromLiveServerRequest(cause);
119​
120 assert.instanceOf(error, ProjectLiveServerDeclaredResponseError);
121 assert.strictEqual(error.operation, "callLiveServer");
122 assert.strictEqual(error.code, "internal_error");
123 assert.strictEqual(error.traceId, "trace-123");
124 assert.strictEqual(error.message, "Server request failed (internal_error, trace trace-123).");
125 assert.strictEqual(error.cause, cause);
126});
127​
128it("preserves unexpected server failures without deriving the message from them", () => {
129 const cause = new Error("credential abc123 was rejected");
130​
131 const error = projectCommandErrorFromLiveServerRequest(cause);
132​
133 assert.instanceOf(error, ProjectLiveServerRequestError);
134 assert.strictEqual(error.operation, "callLiveServer");
135 assert.strictEqual(error.message, "Failed to call the running server.");
136 assert.strictEqual(error.cause, cause);
137});
138​
139it.effect("adds, renames, and removes projects through the V2 project CLI domain", () =>
140 Effect.gen(function* () {
141 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-v2-project-cli-"));
142 const workspaceRoot = NodeFS.mkdtempSync(
143 NodePath.join(NodeOS.tmpdir(), "t3-v2-project-workspace-"),
144 );
145​
146 yield* runCli(["project", "add", workspaceRoot, "--title", "Alpha", "--base-dir", baseDir]);
147 const added = (yield* readProjects(baseDir)).projects[0];
148 assert.equal(added?.title, "Alpha");
149 assert.equal(added?.workspaceRoot, workspaceRoot);
150​
151 yield* runCli(["project", "rename", workspaceRoot, "Beta", "--base-dir", baseDir]);
152 assert.equal((yield* readProjects(baseDir)).projects[0]?.title, "Beta");
153​
154 yield* runCli(["project", "remove", added?.id ?? "", "--base-dir", baseDir]);
155 assert.deepEqual((yield* readProjects(baseDir)).projects, []);
156 }).pipe(Effect.provide(NodeServices.layer)),
157);
158​
159const makeProjectLookupFixture = Effect.fn("ProjectCliTest.makeProjectLookupFixture")(function* () {
160 const fs = yield* FileSystem.FileSystem;
161 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-v2-project-lookup-" });
162 const baseDir = NodePath.join(root, "state");
163 const workspaceRoot = NodePath.join(root, "workspace");
164 yield* fs.makeDirectory(workspaceRoot);
165 yield* runCli(["project", "add", workspaceRoot, "--base-dir", baseDir]);
166 const project = (yield* readProjects(baseDir)).projects[0];
167 assert.isDefined(project);
168 return { baseDir, workspaceRoot, project: project! };
169});
170​
171const makeThreadPersistenceLayer = Effect.fn("ProjectCliTest.makeThreadPersistenceLayer")(
172 function* (baseDir: string) {
173 const config = yield* makeConfig(baseDir);
174 return Layer.mergeAll(
175 OrchestrationV2EventSinkLayerLive,
176 ProjectionStore.layer,
177 EventStore.layer,
178 ).pipe(
179 Layer.provideMerge(SqlitePersistenceLayerLive),
180 Layer.provideMerge(NodeServices.layer),
181 Layer.provide(ServerConfig.layer(config)),
182 Layer.provide(Layer.succeed(References.MinimumLogLevel, config.logLevel)),
183 );
184 },
185);
186​
187const seedNativeThreads = Effect.fn("ProjectCliTest.seedNativeThreads")(function* (
188 baseDir: string,
189 threads: ReadonlyArray<{
190 readonly id: ThreadId;
191 readonly projectId: ProjectId;
192 readonly archived: boolean;
193 }>,
194) {
195 const layer = yield* makeThreadPersistenceLayer(baseDir);
196 const createdAt = DateTime.makeUnsafe("2026-09-04T12:00:00.000Z");
197 const providerInstanceId = ProviderInstanceId.make("codex");
198 yield* Effect.gen(function* () {
199 const eventSink = yield* EventSinkV2;
200 yield* eventSink.write({
201 commandId: CommandId.make("project-cli-seed-threads"),
202 events: threads.map(({ id, projectId, archived }) => {
203 const payload: OrchestrationV2AppThread = {
204 createdBy: "user",
205 creationSource: "web",
206 id,
207 projectId,
208 title: id,
209 providerInstanceId,
210 modelSelection: { instanceId: providerInstanceId, model: "gpt-5" },
211 runtimeMode: "full-access",
212 interactionMode: "default",
213 branch: null,
214 worktreePath: null,
215 activeProviderThreadId: null,
216 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: id },
217 forkedFrom: null,
218 createdAt,
219 updatedAt: createdAt,
220 archivedAt: archived ? createdAt : null,
221 settledOverride: null,
222 settledAt: null,
223 lastVisitedAt: null,
224 deletedAt: null,
225 };
226 return {
227 id: EventId.make(`project-cli-create-${id}`),
228 type: "thread.created" as const,
229 threadId: id,
230 providerInstanceId,
231 occurredAt: createdAt,
232 payload,
233 };
234 }),
235 });
236 }).pipe(Effect.provide(layer));
237});
238​
239const readNativeThreadState = Effect.fn("ProjectCliTest.readNativeThreadState")(function* (
240 baseDir: string,
241 threadId: ThreadId,
242) {
243 const layer = yield* makeThreadPersistenceLayer(baseDir);
244 return yield* Effect.gen(function* () {
245 const projections = yield* ProjectionStore.ProjectionStoreV2;
246 const events = yield* EventStore.EventStoreV2;
247 return {
248 thread: yield* projections.getThread(threadId),
249 events: yield* events.read({ threadId }).pipe(Stream.runCollect),
250 };
251 }).pipe(Effect.provide(layer));
252});
253​
254it.layer(NodeServices.layer)("project deletion with native V2 threads", (it) => {
255 it.effect.each([
256 { label: "an active thread", archived: false, missing: false },
257 { label: "an archived thread", archived: true, missing: false },
258 {
259 label: "an active thread after its workspace disappears",
260 archived: false,
261 missing: true,
262 },
263 {
264 label: "an archived thread after its workspace disappears",
265 archived: true,
266 missing: true,
267 },
268 ])("rejects unforced removal of a project with $label", ({ archived, missing }) =>
269 Effect.gen(function* () {
270 const fs = yield* FileSystem.FileSystem;
271 const { baseDir, workspaceRoot, project } = yield* makeProjectLookupFixture();
272 const threadId = ThreadId.make("project-cli-preserved-thread");
273 yield* seedNativeThreads(baseDir, [{ id: threadId, projectId: project.id, archived }]);
274 const before = yield* readNativeThreadState(baseDir, threadId);
275 if (missing) yield* fs.rename(workspaceRoot, `${workspaceRoot}-removed`);
276​
277 const error = yield* runCli([
278 "project",
279 "remove",
280 missing ? workspaceRoot : project.id,
281 "--base-dir",
282 baseDir,
283 ]).pipe(
284 Effect.match({
285 onFailure: (error) => error,
286 onSuccess: () => assert.fail("Removing a nonempty project must require --force."),
287 }),
288 );
289​
290 assert.include(error.message, "not empty");
291 assert.deepEqual(
292 (yield* readProjects(baseDir)).projects.map((entry) => entry.id),
293 [project.id],
294 );
295 assert.deepEqual(yield* readNativeThreadState(baseDir, threadId), before);
296 assert.equal(yield* fs.exists(workspaceRoot), !missing);
297 }),
298 );
299​
300 it.effect.each(["present", "missing"] as const)(
301 "force-removes active and archived V2 threads with the workspace %s, preserving unrelated projects",
302 (workspace) =>
303 Effect.gen(function* () {
304 const fs = yield* FileSystem.FileSystem;
305 const { baseDir, workspaceRoot, project } = yield* makeProjectLookupFixture();
306 const otherWorkspace = `${workspaceRoot}-other`;
307 yield* fs.makeDirectory(otherWorkspace);
308 yield* runCli(["project", "add", otherWorkspace, "--base-dir", baseDir]);
309 const otherProject = (yield* readProjects(baseDir)).projects.find(
310 (entry) => entry.workspaceRoot === otherWorkspace,
311 );
312 assert.isDefined(otherProject);
313 const activeId = ThreadId.make("project-cli-deleted-active");
314 const archivedId = ThreadId.make("project-cli-deleted-archived");
315 const unrelatedId = ThreadId.make("project-cli-unrelated-thread");
316 yield* seedNativeThreads(baseDir, [
317 { id: activeId, projectId: project.id, archived: false },
318 { id: archivedId, projectId: project.id, archived: true },
319 { id: unrelatedId, projectId: otherProject!.id, archived: false },
320 ]);
321 const unrelatedBefore = yield* readNativeThreadState(baseDir, unrelatedId);
322 if (workspace === "missing") {
323 yield* fs.rename(workspaceRoot, `${workspaceRoot}-removed`);
324 }
325​
326 yield* runCli([
327 "project",
328 "remove",
329 workspace === "missing" ? workspaceRoot : project.id,
330 "--force",
331 "--base-dir",
332 baseDir,
333 ]);
334​
335 assert.deepEqual(
336 (yield* readProjects(baseDir)).projects.map((entry) => entry.id),
337 [otherProject!.id],
338 );
339 for (const threadId of [activeId, archivedId]) {
340 const state = yield* readNativeThreadState(baseDir, threadId);
341 assert.isNotNull(state.thread.deletedAt);
342 assert.lengthOf(
343 state.events.filter((record) => record.event.type === "thread.deleted"),
344 1,
345 );
346 }
347 assert.deepEqual(yield* readNativeThreadState(baseDir, unrelatedId), unrelatedBefore);
348 assert.equal(yield* fs.exists(workspaceRoot), workspace === "present");
349 assert.isTrue(yield* fs.exists(otherWorkspace));
350 }),
351 );
352});
353​
354it.layer(NodeServices.layer)("project lookup with unavailable workspaces", (it) => {
355 it.effect.each(["id", "stored path"] as const)(
356 "removes an empty project by %s after its directory is gone",
357 (identifier) =>
358 Effect.gen(function* () {
359 const fs = yield* FileSystem.FileSystem;
360 const { baseDir, workspaceRoot, project } = yield* makeProjectLookupFixture();
361 yield* fs.rename(workspaceRoot, `${workspaceRoot}-removed`);
362 yield* runCli([
363 "project",
364 "remove",
365 identifier === "id" ? project.id : workspaceRoot,
366 "--base-dir",
367 baseDir,
368 ]);
369 assert.deepEqual((yield* readProjects(baseDir)).projects, []);
370 assert.isFalse(yield* fs.exists(workspaceRoot));
371 }),
372 );
373​
374 it.effect("renames by ID and stored path after the directory is gone", () =>
375 Effect.gen(function* () {
376 const fs = yield* FileSystem.FileSystem;
377 const { baseDir, workspaceRoot, project } = yield* makeProjectLookupFixture();
378 yield* fs.rename(workspaceRoot, `${workspaceRoot}-removed`);
379 for (const [identifier, title] of [
380 [project.id, "Renamed by ID"],
381 [workspaceRoot, "Renamed by stored path"],
382 ] as const) {
383 yield* runCli(["project", "rename", identifier, title, "--base-dir", baseDir]);
384 assert.equal((yield* readProjects(baseDir)).projects[0]?.title, title);
385 }
386 assert.isFalse(yield* fs.exists(workspaceRoot));
387 }),
388 );
389​
390 it.effect("does not resolve another environment's project ID in an empty database", () =>
391 Effect.gen(function* () {
392 const fs = yield* FileSystem.FileSystem;
393 const { baseDir, workspaceRoot, project } = yield* makeProjectLookupFixture();
394 yield* fs.rename(workspaceRoot, `${workspaceRoot}-removed`);
395 const replacementDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-v2-project-empty-" });
396 const error = yield* runCli([
397 "project",
398 "remove",
399 project.id,
400 "--force",
401 "--base-dir",
402 replacementDir,
403 ]).pipe(Effect.flip);
404 assert.include(error.message, "No active project found");
405 assert.deepEqual(
406 (yield* readProjects(baseDir)).projects.map((entry) => entry.id),
407 [project.id],
408 );
409 assert.deepEqual((yield* readProjects(replacementDir)).projects, []);
410 }),
411 );
412​
413 it.effect("normalizes existing paths without conflating separately registered symlinks", () =>
414 Effect.gen(function* () {
415 const { baseDir, workspaceRoot, project } = yield* makeProjectLookupFixture();
416 yield* runCli([
417 "project",
418 "rename",
419 `${workspaceRoot}${NodePath.sep}.`,
420 "Normalized",
421 "--base-dir",
422 baseDir,
423 ]);
424 assert.equal((yield* readProjects(baseDir)).projects[0]?.title, "Normalized");
425 const aliasPath = `${workspaceRoot}-alias`;
426 NodeFS.symlinkSync(workspaceRoot, aliasPath, "junction");
427 const unknownAlias = yield* runCli([
428 "project",
429 "remove",
430 aliasPath,
431 "--base-dir",
432 baseDir,
433 ]).pipe(Effect.flip);
434 assert.include(unknownAlias.message, "No active project found");
435 yield* runCli(["project", "add", aliasPath, "--base-dir", baseDir]);
436 const added = (yield* readProjects(baseDir)).projects;
437 assert.equal(added.length, 2);
438 const aliasProject = added.find((entry) => entry.workspaceRoot === aliasPath);
439 assert.isDefined(aliasProject);
440 assert.notEqual(aliasProject?.id, project.id);
441 yield* runCli(["project", "remove", `${aliasPath}${NodePath.sep}.`, "--base-dir", baseDir]);
442 assert.deepEqual(
443 (yield* readProjects(baseDir)).projects.map((entry) => entry.id),
444 [project.id],
445 );
446 assert.isTrue(NodeFS.existsSync(workspaceRoot));
447 }),
448 );
449});