Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import {
3 CommandId,
4 EventId,
5 MessageId,
6 NodeId,
7 type OrchestrationV2Run,
8 type OrchestrationV2ThreadProjection,
9 ProjectId,
10 ProviderDriverKind,
11 ProviderInstanceId,
12 ProviderSessionId,
13 ProviderThreadId,
14 RunAttemptId,
15 RunId,
16 RuntimeRequestId,
17 ThreadId,
18} from "@t3tools/contracts";
19import * as DateTime from "effect/DateTime";
20import * as Effect from "effect/Effect";
21
22import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
23import { IdAllocatorV2, layer as idAllocatorLayer } from "./IdAllocator.ts";
24import { applyToProjection, emptyProjection } from "./ProjectionStore.ts";
25import { planThreadDeletion } from "./ThreadDeletion.ts";
26
27const threadId = ThreadId.make("thread:delete-plan");
28const providerInstanceId = ProviderInstanceId.make("codex");
29const driver = ProviderDriverKind.make("codex");
30const providerThreadId = ProviderThreadId.make("provider-thread:delete-plan");
31const modelSelection = { instanceId: providerInstanceId, model: "gpt-5.4" };
32const createdAt = DateTime.makeUnsafe("2026-09-01T00:00:00.000Z");
33const deletedAt = DateTime.makeUnsafe("2026-09-04T00:00:00.000Z");
34const command = {
35 type: "thread.delete" as const,
36 commandId: CommandId.make("command:delete-plan"),
37 threadId,
38};
39
40function makeProjection(): OrchestrationV2ThreadProjection {
41 const base = emptyProjection({
42 id: EventId.make("event:delete-plan-created"),
43 type: "thread.created",
44 threadId,
45 occurredAt: createdAt,
46 payload: {
47 id: threadId,
48 createdBy: "user",
49 creationSource: "web",
50 projectId: ProjectId.make("project:delete-plan"),
51 title: "Delete the thread",
52 providerInstanceId,
53 modelSelection,
54 runtimeMode: "full-access",
55 interactionMode: "default",
56 branch: "feature",
57 worktreePath: "/workspace/feature",
58 activeProviderThreadId: null,
59 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
60 forkedFrom: null,
61 createdAt,
62 updatedAt: createdAt,
63 archivedAt: null,
64 settledOverride: null,
65 settledAt: null,
66 lastVisitedAt: null,
67 deletedAt: null,
68 },
69 });
70 const runs: Array<OrchestrationV2Run> = (
71 ["preparing", "queued", "starting", "running", "waiting", "completed"] as const
72 ).map((status, index) => ({
73 id: RunId.make(`run:delete-plan:${status}`),
74 threadId,
75 ordinal: index + 1,
76 providerInstanceId,
77 modelSelection,
78 providerThreadId,
79 userMessageId: MessageId.make(`message:delete-plan:${status}`),
80 rootNodeId: NodeId.make(`node:delete-plan:${status}`),
81 activeAttemptId: RunAttemptId.make(`attempt:delete-plan:${status}`),
82 status,
83 queuePosition: status === "queued" ? 1 : null,
84 requestedAt: createdAt,
85 startedAt: createdAt,
86 completedAt: status === "completed" ? createdAt : null,
87 checkpointId: null,
88 contextHandoffId: null,
89 }));
90 return {
91 ...base,
92 runs,
93 attempts: runs.map((run) => ({
94 id: run.activeAttemptId!,
95 runId: run.id,
96 attemptOrdinal: 1,
97 rootNodeId: run.rootNodeId!,
98 providerInstanceId,
99 providerThreadId,
100 providerTurnId: null,
101 reason: "initial",
102 status: run.status === "completed" ? "completed" : "running",
103 startedAt: createdAt,
104 completedAt: run.completedAt,
105 })),
106 nodes: runs.map((run) => ({
107 id: run.rootNodeId!,
108 threadId,
109 runId: run.id,
110 parentNodeId: null,
111 rootNodeId: run.rootNodeId!,
112 kind: "root_turn",
113 status: run.status === "completed" ? "completed" : "waiting",
114 countsForRun: true,
115 providerThreadId,
116 providerTurnId: null,
117 nativeItemRef: null,
118 runtimeRequestId: null,
119 checkpointScopeId: null,
120 startedAt: createdAt,
121 completedAt: run.completedAt,
122 })),
123 runtimeRequests: ["pending", "resolved"].map((status) => ({
124 id: RuntimeRequestId.make(`request:delete-plan:${status}`),
125 nodeId: runs[3]!.rootNodeId!,
126 providerTurnId: null,
127 nativeRequestRef: null,
128 kind: "user_input",
129 status: status === "pending" ? "pending" : "resolved",
130 responseCapability: { type: "message" },
131 createdAt,
132 resolvedAt: status === "resolved" ? createdAt : null,
133 })),
134 };
135}
136
137it.effect("cancels active work without reviving a run while disposing delegated completion", () =>
138 Effect.gen(function* () {
139 const base = makeProjection();
140 const parentRun = base.runs.find((run) => run.status === "running")!;
141 const queuedRun = base.runs.find((run) => run.status === "queued")!;
142 const taskId = NodeId.make("task:delete-plan");
143 const projection: OrchestrationV2ThreadProjection = {
144 ...base,
145 runs: base.runs.map((run) =>
146 run.id === parentRun.id
147 ? {
148 ...run,
149 delegatedCompletion: {
150 disposition: "open",
151 nextGeneration: 3,
152 settledDeliveryCount: 1,
153 delivery: { generation: 2, messageId: queuedRun.userMessageId, taskIds: [taskId] },
154 },
155 }
156 : run,
157 ),
158 subagents: [
159 {
160 id: taskId,
161 threadId,
162 runId: parentRun.id,
163 parentNodeId: parentRun.rootNodeId!,
164 origin: "app_owned",
165 createdBy: "agent",
166 driver,
167 providerInstanceId,
168 providerThreadId: null,
169 childThreadId: null,
170 nativeTaskRef: null,
171 prompt: "Inspect the project",
172 title: null,
173 model: null,
174 completionDelivery: { state: "claimed", observedByRunId: null },
175 status: "completed",
176 result: "done",
177 startedAt: createdAt,
178 completedAt: createdAt,
179 updatedAt: createdAt,
180 },
181 ],
182 };
183 const plan = yield* planThreadDeletion({
184 command,
185 projection,
186 attachmentIds: projection.messages.flatMap((message) =>
187 message.attachments.map((attachment) => attachment.id),
188 ),
189 now: deletedAt,
190 idAllocator: yield* IdAllocatorV2,
191 });
192 const deleted = plan.events.reduce(applyToProjection, projection);
193 assert.deepEqual(deleted.thread.deletedAt, deletedAt);
194 assert.equal(deleted.thread.worktreePath, "/workspace/feature");
195 assert.isNull(projection.thread.deletedAt);
196 for (const run of deleted.runs) {
197 assert.equal(run.status, run.id.endsWith(":completed") ? "completed" : "cancelled");
198 assert.deepEqual(run.completedAt, run.id.endsWith(":completed") ? createdAt : deletedAt);
199 }
200 for (const attempt of deleted.attempts) {
201 assert.equal(
202 attempt.status,
203 attempt.runId.endsWith(":completed") ? "completed" : "cancelled",
204 );
205 }
206 for (const node of deleted.nodes) {
207 assert.equal(node.status, node.runId?.endsWith(":completed") ? "completed" : "cancelled");
208 }
209 const pending = deleted.runtimeRequests.find((request) => request.id.endsWith(":pending"))!;
210 assert.equal(pending.status, "cancelled");
211 assert.deepEqual(pending.responseCapability, {
212 type: "not_resumable",
213 reason: "The thread was deleted.",
214 });
215 assert.deepEqual(deleted.runtimeRequests[1], projection.runtimeRequests[1]);
216 assert.deepEqual(deleted.runs.find((run) => run.id === parentRun.id)?.delegatedCompletion, {
217 disposition: "disposed",
218 nextGeneration: 3,
219 settledDeliveryCount: 1,
220 delivery: null,
221 });
222 assert.equal(deleted.subagents[0]?.completionDelivery?.state, "disposed");
223 const queuedRunUpdates = plan.events.filter(
224 (event) => event.type === "run.updated" && event.payload.id === queuedRun.id,
225 );
226 assert.lengthOf(queuedRunUpdates, 1);
227 }).pipe(Effect.provide(idAllocatorLayer)),
228);
229
230it.effect("queues provider and resource cleanup and preserves an earlier deletion timestamp", () =>
231 Effect.gen(function* () {
232 const base = makeProjection();
233 const projection: OrchestrationV2ThreadProjection = {
234 ...base,
235 thread: { ...base.thread, deletedAt: createdAt },
236 providerSessions: ["running", "stopped", "error"].map((status) => ({
237 id: ProviderSessionId.make(`session:delete-plan:${status}`),
238 driver,
239 providerInstanceId,
240 status: status === "running" ? "running" : status === "stopped" ? "stopped" : "error",
241 cwd: "/workspace/feature",
242 model: null,
243 capabilities: CodexProviderCapabilitiesV2,
244 createdAt,
245 updatedAt: createdAt,
246 lastError: null,
247 })),
248 messages: [0, 1].map((index) => ({
249 id: MessageId.make(`message:attachment:${index}`),
250 threadId,
251 createdBy: "user",
252 creationSource: "web",
253 runId: null,
254 nodeId: null,
255 role: "user",
256 text: "Inspect this file",
257 attachments: [
258 {
259 type: "file",
260 id: "shared_file",
261 name: "input.txt",
262 mimeType: "text/plain",
263 sizeBytes: 10,
264 },
265 ],
266 streaming: false,
267 createdAt,
268 updatedAt: createdAt,
269 })),
270 };
271 const plan = yield* planThreadDeletion({
272 command,
273 projection,
274 attachmentIds: projection.messages.flatMap((message) =>
275 message.attachments.map((attachment) => attachment.id),
276 ),
277 now: deletedAt,
278 idAllocator: yield* IdAllocatorV2,
279 });
280 const deleted = plan.events.reduce(applyToProjection, projection);
281 assert.deepEqual(deleted.thread.deletedAt, createdAt);
282 assert.deepEqual(
283 deleted.providerSessions.map((session) => session.status),
284 ["stopped", "error"],
285 );
286 assert.deepEqual(
287 plan.effects.map((effect) => effect.request),
288 [
289 {
290 type: "provider-session.detach",
291 providerSessionId: ProviderSessionId.make("session:delete-plan:running"),
292 detail: "Thread deleted.",
293 revokeMcpCredential: true,
294 },
295 { type: "terminal.cleanup" },
296 { type: "attachment.cleanup", attachmentIds: ["shared_file"] },
297 ],
298 );
299 }).pipe(Effect.provide(idAllocatorLayer)),
300);