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