Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import {
4 CommandId,
5 EventId,
6 type OrchestrationV2AppThread,
7 ProjectId,
8 ProviderInstanceId,
9 ThreadId,
10} from "@t3tools/contracts";
11import * as DateTime from "effect/DateTime";
12import * as Effect from "effect/Effect";
13import * as Layer from "effect/Layer";
14import * as Option from "effect/Option";
15import * as Schema from "effect/Schema";
16import { TestClock } from "effect/testing";
17import * as SqlClient from "effect/unstable/sql/SqlClient";
18
19import * as ServerConfig from "../config.ts";
20import { OrchestrationEffectRequestV2 } from "../orchestration-v2/EffectOutbox.ts";
21import * as EventSink from "../orchestration-v2/EventSink.ts";
22import * as EventStore from "../orchestration-v2/EventStore.ts";
23import * as IdAllocator from "../orchestration-v2/IdAllocator.ts";
24import * as LegacyV1ThreadImporter from "../orchestration-v2/legacy/LegacyV1ThreadImporter.ts";
25import * as ProjectionMaintenance from "../orchestration-v2/ProjectionMaintenance.ts";
26import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
27import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";
28import * as ThreadCommandExecutor from "../orchestration-v2/ThreadCommandExecutor.ts";
29import { planThreadDeletion } from "../orchestration-v2/ThreadDeletion.ts";
30import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
31import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
32import * as ProjectEnrichmentService from "./ProjectEnrichmentService.ts";
33import * as ProjectFaviconResolver from "./ProjectFaviconResolver.ts";
34import * as ProjectService from "./ProjectService.ts";
35import * as RepositoryIdentityResolver from "./RepositoryIdentityResolver.ts";
36
37const eventPersistenceLayer = EventSink.layer.pipe(
38 Layer.provideMerge(Layer.merge(EventStore.layer, ProjectionStore.layer)),
39);
40const servicesLayer = Layer.mergeAll(
41 LegacyV1ThreadImporter.layer.pipe(Layer.provideMerge(eventPersistenceLayer)),
42 ProjectionMaintenance.layer.pipe(Layer.provide(eventPersistenceLayer)),
43 ProjectStore.layer,
44 IdAllocator.layer,
45 ThreadCommandExecutor.layer,
46 Layer.succeed(WorkspacePaths.WorkspacePaths, {
47 normalizeWorkspaceRoot: (workspaceRoot) => Effect.succeed(workspaceRoot),
48 resolveRelativePathWithinRoot: ({ workspaceRoot, relativePath }) =>
49 Effect.succeed({ absolutePath: `${workspaceRoot}/${relativePath}`, relativePath }),
50 }),
51).pipe(
52 Layer.provideMerge(
53 ProjectEnrichmentService.layer.pipe(
54 Layer.provide(
55 Layer.merge(
56 Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, {
57 resolve: () => Effect.succeed(null),
58 }),
59 Layer.succeed(ProjectFaviconResolver.ProjectFaviconResolver, {
60 resolvePath: () => Effect.succeed(null),
61 }),
62 ),
63 ),
64 ),
65 ),
66);
67const databaseLayer = SqlitePersistenceMemory.pipe(
68 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "project-deletion-test-" })),
69 Layer.provideMerge(NodeServices.layer),
70);
71const decodeEffectRequest = Schema.decodeUnknownEffect(
72 Schema.fromJsonString(OrchestrationEffectRequestV2),
73);
74
75const seedProject = Effect.fn("ProjectDeletionTest.seedProject")(function* (projectId: ProjectId) {
76 const sql = yield* SqlClient.SqlClient;
77 yield* sql`
78 INSERT INTO projection_projects (
79 project_id, title, workspace_root, default_model_selection_json,
80 scripts_json, created_at, updated_at, deleted_at
81 ) VALUES (
82 ${projectId}, 'Deletion test', ${`/work/${projectId}`}, NULL,
83 '[]', '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL
84 )
85 `;
86});
87
88function nativeThreadCreated(projectId: ProjectId, threadId: ThreadId) {
89 const createdAt = DateTime.makeUnsafe("2026-01-01T00:00:00.000Z");
90 const providerInstanceId = ProviderInstanceId.make("codex");
91 const payload: OrchestrationV2AppThread = {
92 createdBy: "user",
93 creationSource: "web",
94 id: threadId,
95 projectId,
96 title: threadId,
97 providerInstanceId,
98 modelSelection: { instanceId: providerInstanceId, model: "gpt-5" },
99 runtimeMode: "full-access",
100 interactionMode: "default",
101 branch: null,
102 worktreePath: null,
103 activeProviderThreadId: null,
104 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
105 forkedFrom: null,
106 createdAt,
107 updatedAt: createdAt,
108 archivedAt: null,
109 settledOverride: null,
110 settledAt: null,
111 lastVisitedAt: null,
112 deletedAt: null,
113 };
114 return {
115 id: EventId.make(`created:${threadId}`),
116 type: "thread.created" as const,
117 threadId,
118 providerInstanceId,
119 occurredAt: createdAt,
120 payload,
121 };
122}
123
124it.effect("retries a partial project deletion without repeating child events or cleanup", () =>
125 Effect.gen(function* () {
126 const sql = yield* SqlClient.SqlClient;
127 const projectId = ProjectId.make("project:partial-deletion");
128 const threadIds = [ThreadId.make("thread:delete-a"), ThreadId.make("thread:delete-b")] as const;
129 const commandId = CommandId.make("command:partial-project-delete");
130 yield* seedProject(projectId);
131 yield* TestClock.setTime(Date.parse("2026-09-04T12:00:00.000Z"));
132
133 yield* Effect.gen(function* () {
134 const eventSink = yield* EventSink.EventSinkV2;
135 const projections = yield* ProjectionStore.ProjectionStoreV2;
136 yield* eventSink.write({
137 events: threadIds.map((threadId) => nativeThreadCreated(projectId, threadId)),
138 });
139 const attempts: ThreadId[] = [];
140 const failingEventSink = EventSink.EventSinkV2.of({
141 ...eventSink,
142 commitCommand: Effect.fn("ProjectDeletionTest.failSecondChild")(function* (
143 input: Parameters<EventSink.EventSinkV2Shape["commitCommand"]>[0],
144 ) {
145 attempts.push(input.threadId);
146 if (attempts.length === 2) {
147 return yield* new EventSink.EventSinkWriteError({
148 commandId: input.commandId,
149 eventCount: input.events.length,
150 cause: new Error("Injected failure for the second child"),
151 });
152 }
153 return yield* eventSink.commitCommand(input);
154 }),
155 });
156 const service = yield* ProjectService.make.pipe(
157 Effect.provideService(EventSink.EventSinkV2, failingEventSink),
158 );
159 const input = { commandId, projectId, force: true };
160 const failure = yield* service.delete(input).pipe(Effect.flip);
161 assert.instanceOf(failure, ProjectService.ProjectOperationError);
162 if (failure._tag !== "ProjectOperationError") return assert.fail("Expected a child failure");
163 assert.equal(failure.operation, "delete-thread");
164 assert.lengthOf(attempts, 2);
165 const firstThreadId = attempts[0] ?? assert.fail("The first child was not attempted");
166 const failedThreadId = attempts[1] ?? assert.fail("The second child was not attempted");
167 assert.notEqual(firstThreadId, failedThreadId);
168 assert.isTrue(Option.isSome(yield* service.getById(projectId)));
169 assert.isNotNull((yield* projections.getThreadProjection(firstThreadId)).thread.deletedAt);
170 assert.isNull((yield* projections.getThreadProjection(failedThreadId)).thread.deletedAt);
171
172 const readDeletions = sql<{
173 readonly sequence: number;
174 readonly stream_id: string;
175 readonly command_id: string;
176 readonly event_type: string;
177 }>`
178 SELECT sequence, stream_id, command_id, event_type
179 FROM orchestration_events
180 WHERE event_type IN ('thread.deleted', 'project.deleted')
181 AND stream_id IN (${threadIds[0]}, ${threadIds[1]}, ${projectId})
182 ORDER BY sequence ASC
183 `;
184 const readCleanup = sql<{
185 readonly effect_id: string;
186 readonly thread_id: string;
187 readonly command_id: string;
188 readonly effect_type: string;
189 }>`
190 SELECT effect_id, thread_id, command_id, effect_type
191 FROM orchestration_v2_effect_outbox
192 WHERE thread_id IN (${threadIds[0]}, ${threadIds[1]})
193 ORDER BY effect_id ASC
194 `;
195 const partialEvents = yield* readDeletions;
196 const partialCleanup = yield* readCleanup;
197 assert.lengthOf(partialEvents, 1);
198 assert.equal(partialEvents[0]?.stream_id, firstThreadId);
199 assert.equal(partialEvents[0]?.event_type, "thread.deleted");
200 assert.lengthOf(partialCleanup, 1);
201 assert.equal(partialCleanup[0]?.thread_id, firstThreadId);
202 assert.equal(partialCleanup[0]?.effect_type, "terminal.cleanup");
203
204 const deletedProject = yield* service.delete(input);
205 assert.isNotNull(deletedProject.deletedAt);
206 assert.isTrue(Option.isNone(yield* service.getById(projectId)));
207 assert.deepEqual(attempts, [firstThreadId, failedThreadId, failedThreadId]);
208 for (const threadId of threadIds) {
209 assert.isNotNull((yield* projections.getThreadProjection(threadId)).thread.deletedAt);
210 }
211 const finalEvents = yield* readDeletions;
212 assert.deepEqual(
213 finalEvents.map((event) => [event.stream_id, event.event_type]),
214 [
215 [firstThreadId, "thread.deleted"],
216 [failedThreadId, "thread.deleted"],
217 [projectId, "project.deleted"],
218 ],
219 );
220 assert.deepEqual(finalEvents[0], partialEvents[0]);
221 assert.equal(finalEvents[2]?.command_id, commandId);
222 const finalCleanup = yield* readCleanup;
223 assert.lengthOf(finalCleanup, 2);
224 assert.deepEqual(
225 finalCleanup.filter((effect) => effect.thread_id === firstThreadId),
226 partialCleanup,
227 );
228 for (const threadId of threadIds) {
229 const expectedCommandId = `${commandId}:delete-thread:${threadId}`;
230 assert.deepEqual(
231 finalCleanup.filter((effect) => effect.thread_id === threadId),
232 [
233 {
234 effect_id: `effect:${expectedCommandId}:terminal.cleanup`,
235 thread_id: threadId,
236 command_id: expectedCommandId,
237 effect_type: "terminal.cleanup",
238 },
239 ],
240 );
241 }
242 }).pipe(Effect.provide(servicesLayer));
243 }).pipe(Effect.provide(databaseLayer)),
244);
245
246it.effect(
247 "hydrates a migrated transcript before deleting its project and cleaning attachments",
248 () =>
249 Effect.gen(function* () {
250 const sql = yield* SqlClient.SqlClient;
251 const projectId = ProjectId.make("project:legacy-deletion");
252 const threadId = ThreadId.make("thread:legacy-deletion");
253 const commandId = CommandId.make("command:legacy-project-delete");
254 yield* seedProject(projectId);
255 yield* sql`
256 INSERT INTO projection_threads (
257 thread_id, project_id, title, model_selection_json,
258 runtime_mode, interaction_mode, branch, worktree_path, latest_turn_id,
259 created_at, updated_at, archived_at, deleted_at
260 ) VALUES (
261 ${threadId}, ${projectId}, 'Legacy thread', '{"instanceId":"codex","model":"gpt-5.4"}',
262 'full-access', 'default', NULL, NULL, NULL,
263 '2026-01-01T00:00:00.000Z', '2026-01-04T00:00:00.000Z', NULL, NULL
264 )
265 `;
266 yield* sql`
267 INSERT INTO projection_thread_messages (
268 message_id, thread_id, turn_id, role, text, attachments_json,
269 is_streaming, created_at, updated_at
270 ) VALUES
271 (
272 'message:legacy-delete:1', ${threadId}, NULL, 'user', 'First question with screenshot',
273 '[{"type":"image","id":"legacy_screenshot","name":"screenshot.png","mimeType":"image/png","sizeBytes":128}]',
274 0, '2026-01-01T01:00:00.000Z', '2026-01-01T01:00:00.000Z'
275 ),
276 (
277 'message:legacy-delete:2', ${threadId}, NULL, 'assistant', 'First answer', '[]',
278 0, '2026-01-02T01:00:00.000Z', '2026-01-02T01:00:00.000Z'
279 ),
280 (
281 'message:legacy-delete:3', ${threadId}, NULL, 'user', 'Follow-up question', '[]',
282 0, '2026-01-03T01:00:00.000Z', '2026-01-03T01:00:00.000Z'
283 ),
284 (
285 'message:legacy-delete:4', ${threadId}, NULL, 'assistant', 'Follow-up answer', '[]',
286 0, '2026-01-04T01:00:00.000Z', '2026-01-04T01:00:00.000Z'
287 )
288 `;
289 yield* TestClock.setTime(Date.parse("2026-09-04T12:00:00.000Z"));
290
291 // Build the engine after seeding the legacy database, as on a real restart.
292 yield* Effect.gen(function* () {
293 const importer = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
294 const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
295 const projections = yield* ProjectionStore.ProjectionStoreV2;
296 const service = yield* ProjectService.make;
297 assert.deepEqual(yield* importer.reconcileShells, {
298 importedThreadCount: 1,
299 importedMessageCount: 2,
300 });
301 assert.equal(yield* importer.pendingThreadCount, 1);
302 assert.isTrue((yield* maintenance.rebuild).valid);
303 const shellProjection = yield* projections.getThreadProjection(threadId);
304 assert.deepEqual(
305 shellProjection.messages.map((message) => message.id),
306 ["message:legacy-delete:3", "message:legacy-delete:4"],
307 );
308 assert.deepEqual(
309 shellProjection.messages.flatMap((message) => message.attachments),
310 [],
311 );
312
313 const deletedProject = yield* service.delete({ commandId, projectId, force: true });
314 assert.isNotNull(deletedProject.deletedAt);
315 assert.isTrue(Option.isNone(yield* service.getById(projectId)));
316 const projection = yield* projections.getThreadProjection(threadId);
317 assert.isNotNull(projection.thread.deletedAt);
318 assert.lengthOf(projection.messages, 4);
319 assert.equal(yield* importer.pendingThreadCount, 0);
320 const rows = yield* sql<{
321 readonly v2_deleted_at: string | null;
322 readonly project_deleted_at: string | null;
323 }>`
324 SELECT v2.deleted_at AS v2_deleted_at,
325 project.deleted_at AS project_deleted_at
326 FROM orchestration_v2_projection_threads AS v2
327 JOIN projection_projects AS project ON project.project_id = v2.project_id
328 WHERE v2.thread_id = ${threadId}
329 `;
330 assert.lengthOf(rows, 1);
331 assert.isNotNull(rows[0]?.v2_deleted_at);
332 assert.isNotNull(rows[0]?.project_deleted_at);
333 // The legacy V1 row is only an import source; deletion writes V2 events only.
334 const legacyEvents = yield* sql`
335 SELECT sequence FROM orchestration_events
336 WHERE application_event_version = 1 AND stream_id = ${threadId}
337 `;
338 assert.deepEqual(legacyEvents, []);
339
340 const cleanup = yield* sql<{
341 readonly command_id: string;
342 readonly payload_json: string;
343 readonly status: string;
344 }>`
345 SELECT command_id, payload_json, status
346 FROM orchestration_v2_effect_outbox
347 WHERE thread_id = ${threadId} AND effect_type = 'attachment.cleanup'
348 `;
349 assert.lengthOf(cleanup, 1);
350 assert.equal(cleanup[0]?.command_id, `${commandId}:delete-thread:${threadId}`);
351 assert.equal(cleanup[0]?.status, "pending");
352 const request = yield* decodeEffectRequest(cleanup[0]?.payload_json);
353 assert.deepEqual(request, {
354 type: "attachment.cleanup",
355 attachmentIds: ["legacy_screenshot"],
356 });
357 }).pipe(Effect.provide(servicesLayer));
358 }).pipe(Effect.provide(databaseLayer)),
359);
360
361it.effect("rejects a child deletion command ID already accepted for an unrelated thread", () =>
362 Effect.gen(function* () {
363 const sql = yield* SqlClient.SqlClient;
364 const projectId = ProjectId.make("project:receipt-collision");
365 const otherProjectId = ProjectId.make("project:unrelated-receipt");
366 const threadId = ThreadId.make("thread:receipt-collision");
367 const otherThreadId = ThreadId.make("thread:unrelated-receipt");
368 const commandId = CommandId.make("command:collision-project-delete");
369 yield* seedProject(projectId);
370 yield* seedProject(otherProjectId);
371
372 yield* Effect.gen(function* () {
373 const eventSink = yield* EventSink.EventSinkV2;
374 const projections = yield* ProjectionStore.ProjectionStoreV2;
375 const service = yield* ProjectService.make;
376 yield* eventSink.write({ events: [nativeThreadCreated(projectId, threadId)] });
377 const accepted = yield* eventSink.commitCommand({
378 commandId: CommandId.make(`${commandId}:delete-thread:${threadId}`),
379 commandType: "thread.create",
380 threadId: otherThreadId,
381 acceptedAt: DateTime.makeUnsafe("2026-01-01T00:00:00.000Z"),
382 events: [nativeThreadCreated(otherProjectId, otherThreadId)],
383 effects: [],
384 });
385 assert.equal(accepted.receipt.status, "accepted");
386
387 const failure = yield* service
388 .delete({ commandId, projectId, force: true })
389 .pipe(Effect.flip);
390 assert.instanceOf(failure, ProjectService.ProjectOperationError);
391 if (failure._tag !== "ProjectOperationError") return assert.fail("Expected a child failure");
392 assert.equal(failure.operation, "delete-thread");
393 assert.isTrue(Option.isSome(yield* service.getById(projectId)));
394 assert.isNull((yield* projections.getThreadProjection(threadId)).thread.deletedAt);
395 assert.isNull((yield* projections.getThreadProjection(otherThreadId)).thread.deletedAt);
396 const deletions = yield* sql`
397 SELECT sequence FROM orchestration_events
398 WHERE event_type IN ('thread.deleted', 'project.deleted')
399 AND stream_id IN (${threadId}, ${otherThreadId}, ${projectId})
400 `;
401 assert.deepEqual(deletions, []);
402 const cleanup = yield* sql`
403 SELECT effect_id FROM orchestration_v2_effect_outbox
404 WHERE thread_id = ${threadId}
405 `;
406 assert.deepEqual(cleanup, []);
407 }).pipe(Effect.provide(servicesLayer));
408 }).pipe(Effect.provide(databaseLayer)),
409);
410
411it.effect("deletes a project without force once its imported threads were deleted in V2", () =>
412 Effect.gen(function* () {
413 const sql = yield* SqlClient.SqlClient;
414 const projectId = ProjectId.make("project:imported-emptied");
415 const threadId = ThreadId.make("thread:imported-emptied");
416 yield* seedProject(projectId);
417 // V2 never writes the V1 thread table, so this row stays live there.
418 yield* sql`
419 INSERT INTO projection_threads (
420 thread_id, project_id, title, model_selection_json,
421 runtime_mode, interaction_mode, branch, worktree_path, latest_turn_id,
422 created_at, updated_at, archived_at, deleted_at
423 ) VALUES (
424 ${threadId}, ${projectId}, 'Imported thread', '{"instanceId":"codex","model":"gpt-5.4"}',
425 'full-access', 'default', NULL, NULL, NULL,
426 '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL, NULL
427 )
428 `;
429 yield* TestClock.setTime(Date.parse("2026-09-04T12:00:00.000Z"));
430
431 yield* Effect.gen(function* () {
432 const importer = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
433 const projections = yield* ProjectionStore.ProjectionStoreV2;
434 const eventSink = yield* EventSink.EventSinkV2;
435 const idAllocator = yield* IdAllocator.IdAllocatorV2;
436 const service = yield* ProjectService.make;
437 yield* importer.reconcileShells;
438 const early = yield* service
439 .delete({ commandId: CommandId.make("command:emptied:early"), projectId })
440 .pipe(Effect.flip);
441 assert.equal(early._tag, "ProjectNotEmptyError");
442
443 // Delete the imported thread the way thread.delete does.
444 yield* importer.ensureTranscript(threadId);
445 const command = {
446 type: "thread.delete" as const,
447 commandId: CommandId.make("command:emptied:thread-delete"),
448 threadId,
449 };
450 const now = yield* DateTime.now;
451 const plan = yield* planThreadDeletion({
452 command,
453 projection: yield* projections.getThreadRecords(threadId, [
454 "runs",
455 "attempts",
456 "nodes",
457 "runtimeRequests",
458 "subagents",
459 "providerSessions",
460 ]),
461 attachmentIds: [],
462 now,
463 idAllocator,
464 });
465 yield* eventSink.commitCommand({
466 commandId: command.commandId,
467 commandType: command.type,
468 threadId,
469 acceptedAt: now,
470 events: plan.events,
471 effects: plan.effects,
472 });
473 const legacy = yield* sql<{ readonly deleted_at: string | null }>`
474 SELECT deleted_at FROM projection_threads WHERE thread_id = ${threadId}
475 `;
476 assert.deepEqual(legacy, [{ deleted_at: null }]);
477
478 const deleted = yield* service.delete({
479 commandId: CommandId.make("command:emptied:project-delete"),
480 projectId,
481 });
482 assert.isNotNull(deleted.deletedAt);
483 assert.isTrue(Option.isNone(yield* service.getById(projectId)));
484 }).pipe(Effect.provide(servicesLayer));
485 }).pipe(Effect.provide(databaseLayer)),
486);