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

project.test.ts

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