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

project.test.ts

447 lines17.2 KB

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