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