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/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 "@t3tools/provider-core/server/IdAllocator";
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 * as SqlitePersistence from "../persistence/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 layerEventPersistence = EventSink.layer.pipe(
38 Layer.provideMerge(Layer.merge(EventStore.layer, ProjectionStore.layer)),
39);
40const layerServices = Layer.mergeAll(
41 LegacyV1ThreadImporter.layer.pipe(Layer.provideMerge(layerEventPersistence)),
42 ProjectionMaintenance.layer.pipe(Layer.provide(layerEventPersistence)),
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 layerDatabase = SqlitePersistence.layerMemory.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.deepEqual(
201 partialCleanup.map((effect) => [effect.thread_id, effect.effect_type]),
202 [
203 [firstThreadId, "preview.cleanup"],
204 [firstThreadId, "terminal.cleanup"],
205 ],
206 );
207
208 const deletedProject = yield* service.delete(input);
209 assert.isNotNull(deletedProject.deletedAt);
210 assert.isTrue(Option.isNone(yield* service.getById(projectId)));
211 assert.deepEqual(attempts, [firstThreadId, failedThreadId, failedThreadId]);
212 for (const threadId of threadIds) {
213 assert.isNotNull((yield* projections.getThreadProjection(threadId)).thread.deletedAt);
214 }
215 const finalEvents = yield* readDeletions;
216 assert.deepEqual(
217 finalEvents.map((event) => [event.stream_id, event.event_type]),
218 [
219 [firstThreadId, "thread.deleted"],
220 [failedThreadId, "thread.deleted"],
221 [projectId, "project.deleted"],
222 ],
223 );
224 assert.deepEqual(finalEvents[0], partialEvents[0]);
225 assert.equal(finalEvents[2]?.command_id, commandId);
226 const finalCleanup = yield* readCleanup;
227 assert.lengthOf(finalCleanup, 4);
228 assert.deepEqual(
229 finalCleanup.filter((effect) => effect.thread_id === firstThreadId),
230 partialCleanup,
231 );
232 for (const threadId of threadIds) {
233 const expectedCommandId = `${commandId}:delete-thread:${threadId}`;
234 assert.deepEqual(
235 finalCleanup.filter((effect) => effect.thread_id === threadId),
236 [
237 {
238 effect_id: `effect:${expectedCommandId}:preview.cleanup`,
239 thread_id: threadId,
240 command_id: expectedCommandId,
241 effect_type: "preview.cleanup",
242 },
243 {
244 effect_id: `effect:${expectedCommandId}:terminal.cleanup`,
245 thread_id: threadId,
246 command_id: expectedCommandId,
247 effect_type: "terminal.cleanup",
248 },
249 ],
250 );
251 }
252 }).pipe(Effect.provide(layerServices));
253 }).pipe(Effect.provide(layerDatabase)),
254);
255
256it.effect(
257 "hydrates a migrated transcript before deleting its project and cleaning attachments",
258 () =>
259 Effect.gen(function* () {
260 const sql = yield* SqlClient.SqlClient;
261 const projectId = ProjectId.make("project:legacy-deletion");
262 const threadId = ThreadId.make("thread:legacy-deletion");
263 const commandId = CommandId.make("command:legacy-project-delete");
264 yield* seedProject(projectId);
265 yield* sql`
266 INSERT INTO projection_threads (
267 thread_id, project_id, title, model_selection_json,
268 runtime_mode, interaction_mode, branch, worktree_path, latest_turn_id,
269 created_at, updated_at, archived_at, deleted_at
270 ) VALUES (
271 ${threadId}, ${projectId}, 'Legacy thread', '{"instanceId":"codex","model":"gpt-5.4"}',
272 'full-access', 'default', NULL, NULL, NULL,
273 '2026-01-01T00:00:00.000Z', '2026-01-04T00:00:00.000Z', NULL, NULL
274 )
275 `;
276 yield* sql`
277 INSERT INTO projection_thread_messages (
278 message_id, thread_id, turn_id, role, text, attachments_json,
279 is_streaming, created_at, updated_at
280 ) VALUES
281 (
282 'message:legacy-delete:1', ${threadId}, NULL, 'user', 'First question with screenshot',
283 '[{"type":"image","id":"legacy_screenshot","name":"screenshot.png","mimeType":"image/png","sizeBytes":128}]',
284 0, '2026-01-01T01:00:00.000Z', '2026-01-01T01:00:00.000Z'
285 ),
286 (
287 'message:legacy-delete:2', ${threadId}, NULL, 'assistant', 'First answer', '[]',
288 0, '2026-01-02T01:00:00.000Z', '2026-01-02T01:00:00.000Z'
289 ),
290 (
291 'message:legacy-delete:3', ${threadId}, NULL, 'user', 'Follow-up question', '[]',
292 0, '2026-01-03T01:00:00.000Z', '2026-01-03T01:00:00.000Z'
293 ),
294 (
295 'message:legacy-delete:4', ${threadId}, NULL, 'assistant', 'Follow-up answer', '[]',
296 0, '2026-01-04T01:00:00.000Z', '2026-01-04T01:00:00.000Z'
297 )
298 `;
299 yield* TestClock.setTime(Date.parse("2026-09-04T12:00:00.000Z"));
300
301 // Build the engine after seeding the legacy database, as on a real restart.
302 yield* Effect.gen(function* () {
303 const importer = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
304 const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
305 const projections = yield* ProjectionStore.ProjectionStoreV2;
306 const service = yield* ProjectService.make;
307 assert.deepEqual(yield* importer.reconcileShells, {
308 importedThreadCount: 1,
309 importedMessageCount: 2,
310 });
311 assert.equal(yield* importer.pendingThreadCount, 1);
312 assert.isTrue((yield* maintenance.rebuild).valid);
313 const shellProjection = yield* projections.getThreadProjection(threadId);
314 assert.deepEqual(
315 shellProjection.messages.map((message) => message.id),
316 ["message:legacy-delete:3", "message:legacy-delete:4"],
317 );
318 assert.deepEqual(
319 shellProjection.messages.flatMap((message) => message.attachments),
320 [],
321 );
322
323 const deletedProject = yield* service.delete({ commandId, projectId, force: true });
324 assert.isNotNull(deletedProject.deletedAt);
325 assert.isTrue(Option.isNone(yield* service.getById(projectId)));
326 const projection = yield* projections.getThreadProjection(threadId);
327 assert.isNotNull(projection.thread.deletedAt);
328 assert.lengthOf(projection.messages, 4);
329 assert.equal(yield* importer.pendingThreadCount, 0);
330 const rows = yield* sql<{
331 readonly v2_deleted_at: string | null;
332 readonly project_deleted_at: string | null;
333 }>`
334 SELECT v2.deleted_at AS v2_deleted_at,
335 project.deleted_at AS project_deleted_at
336 FROM orchestration_v2_projection_threads AS v2
337 JOIN projection_projects AS project ON project.project_id = v2.project_id
338 WHERE v2.thread_id = ${threadId}
339 `;
340 assert.lengthOf(rows, 1);
341 assert.isNotNull(rows[0]?.v2_deleted_at);
342 assert.isNotNull(rows[0]?.project_deleted_at);
343 // The legacy V1 row is only an import source; deletion writes V2 events only.
344 const legacyEvents = yield* sql`
345 SELECT sequence FROM orchestration_events
346 WHERE application_event_version = 1 AND stream_id = ${threadId}
347 `;
348 assert.deepEqual(legacyEvents, []);
349
350 const cleanup = yield* sql<{
351 readonly command_id: string;
352 readonly payload_json: string;
353 readonly status: string;
354 }>`
355 SELECT command_id, payload_json, status
356 FROM orchestration_v2_effect_outbox
357 WHERE thread_id = ${threadId} AND effect_type = 'attachment.cleanup'
358 `;
359 assert.lengthOf(cleanup, 1);
360 assert.equal(cleanup[0]?.command_id, `${commandId}:delete-thread:${threadId}`);
361 assert.equal(cleanup[0]?.status, "pending");
362 const request = yield* decodeEffectRequest(cleanup[0]?.payload_json);
363 assert.deepEqual(request, {
364 type: "attachment.cleanup",
365 attachmentIds: ["legacy_screenshot"],
366 });
367 }).pipe(Effect.provide(layerServices));
368 }).pipe(Effect.provide(layerDatabase)),
369);
370
371it.effect("rejects a child deletion command ID already accepted for an unrelated thread", () =>
372 Effect.gen(function* () {
373 const sql = yield* SqlClient.SqlClient;
374 const projectId = ProjectId.make("project:receipt-collision");
375 const otherProjectId = ProjectId.make("project:unrelated-receipt");
376 const threadId = ThreadId.make("thread:receipt-collision");
377 const otherThreadId = ThreadId.make("thread:unrelated-receipt");
378 const commandId = CommandId.make("command:collision-project-delete");
379 yield* seedProject(projectId);
380 yield* seedProject(otherProjectId);
381
382 yield* Effect.gen(function* () {
383 const eventSink = yield* EventSink.EventSinkV2;
384 const projections = yield* ProjectionStore.ProjectionStoreV2;
385 const service = yield* ProjectService.make;
386 yield* eventSink.write({ events: [nativeThreadCreated(projectId, threadId)] });
387 const accepted = yield* eventSink.commitCommand({
388 commandId: CommandId.make(`${commandId}:delete-thread:${threadId}`),
389 commandType: "thread.create",
390 threadId: otherThreadId,
391 acceptedAt: DateTime.makeUnsafe("2026-01-01T00:00:00.000Z"),
392 events: [nativeThreadCreated(otherProjectId, otherThreadId)],
393 effects: [],
394 });
395 assert.equal(accepted.receipt.status, "accepted");
396
397 const failure = yield* service
398 .delete({ commandId, projectId, force: true })
399 .pipe(Effect.flip);
400 assert.instanceOf(failure, ProjectService.ProjectOperationError);
401 if (failure._tag !== "ProjectOperationError") return assert.fail("Expected a child failure");
402 assert.equal(failure.operation, "delete-thread");
403 assert.isTrue(Option.isSome(yield* service.getById(projectId)));
404 assert.isNull((yield* projections.getThreadProjection(threadId)).thread.deletedAt);
405 assert.isNull((yield* projections.getThreadProjection(otherThreadId)).thread.deletedAt);
406 const deletions = yield* sql`
407 SELECT sequence FROM orchestration_events
408 WHERE event_type IN ('thread.deleted', 'project.deleted')
409 AND stream_id IN (${threadId}, ${otherThreadId}, ${projectId})
410 `;
411 assert.deepEqual(deletions, []);
412 const cleanup = yield* sql`
413 SELECT effect_id FROM orchestration_v2_effect_outbox
414 WHERE thread_id = ${threadId}
415 `;
416 assert.deepEqual(cleanup, []);
417 }).pipe(Effect.provide(layerServices));
418 }).pipe(Effect.provide(layerDatabase)),
419);
420
421it.effect("deletes a project without force once its imported threads were deleted in V2", () =>
422 Effect.gen(function* () {
423 const sql = yield* SqlClient.SqlClient;
424 const projectId = ProjectId.make("project:imported-emptied");
425 const threadId = ThreadId.make("thread:imported-emptied");
426 yield* seedProject(projectId);
427 // V2 never writes the V1 thread table, so this row stays live there.
428 yield* sql`
429 INSERT INTO projection_threads (
430 thread_id, project_id, title, model_selection_json,
431 runtime_mode, interaction_mode, branch, worktree_path, latest_turn_id,
432 created_at, updated_at, archived_at, deleted_at
433 ) VALUES (
434 ${threadId}, ${projectId}, 'Imported thread', '{"instanceId":"codex","model":"gpt-5.4"}',
435 'full-access', 'default', NULL, NULL, NULL,
436 '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL, NULL
437 )
438 `;
439 yield* TestClock.setTime(Date.parse("2026-09-04T12:00:00.000Z"));
440
441 yield* Effect.gen(function* () {
442 const importer = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
443 const projections = yield* ProjectionStore.ProjectionStoreV2;
444 const eventSink = yield* EventSink.EventSinkV2;
445 const idAllocator = yield* IdAllocator.IdAllocatorV2;
446 const service = yield* ProjectService.make;
447 yield* importer.reconcileShells;
448 const early = yield* service
449 .delete({ commandId: CommandId.make("command:emptied:early"), projectId })
450 .pipe(Effect.flip);
451 assert.equal(early._tag, "ProjectNotEmptyError");
452
453 // Delete the imported thread the way thread.delete does.
454 yield* importer.ensureTranscript(threadId);
455 const command = {
456 type: "thread.delete" as const,
457 commandId: CommandId.make("command:emptied:thread-delete"),
458 threadId,
459 };
460 const now = yield* DateTime.now;
461 const plan = yield* planThreadDeletion({
462 command,
463 projection: yield* projections.getThreadRecords(threadId, [
464 "runs",
465 "attempts",
466 "nodes",
467 "runtimeRequests",
468 "subagents",
469 "providerSessions",
470 ]),
471 attachmentIds: [],
472 now,
473 idAllocator,
474 });
475 yield* eventSink.commitCommand({
476 commandId: command.commandId,
477 commandType: command.type,
478 threadId,
479 acceptedAt: now,
480 events: plan.events,
481 effects: plan.effects,
482 });
483 const legacy = yield* sql<{ readonly deleted_at: string | null }>`
484 SELECT deleted_at FROM projection_threads WHERE thread_id = ${threadId}
485 `;
486 assert.deepEqual(legacy, [{ deleted_at: null }]);
487
488 const deleted = yield* service.delete({
489 commandId: CommandId.make("command:emptied:project-delete"),
490 projectId,
491 });
492 assert.isNotNull(deleted.deletedAt);
493 assert.isTrue(Option.isNone(yield* service.getById(projectId)));
494 }).pipe(Effect.provide(layerServices));
495 }).pipe(Effect.provide(layerDatabase)),
496);