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