Open History to see the last commit
1import { expect, it } from "@effect/vitest";
2import {
3 CommandId,
4 MessageId,
5 NodeId,
6 type OrchestrationV2Command,
7 type OrchestrationV2ThreadProjection,
8 ProjectId,
9 ProviderInstanceId,
10 RunId,
11 ThreadId,
12} from "@t3tools/contracts";
13import * as Effect from "effect/Effect";
14import * as Layer from "effect/Layer";
15
16import { LegacyV1ThreadImporter, LegacyV1ThreadImportError } from "./LegacyV1ThreadImporter.ts";
17import { OrchestratorProjectionError, OrchestratorV2 } from "./Orchestrator.ts";
18import {
19 existingThreadIdsForCommand,
20 layer,
21 layerWithLegacyImporter,
22 ThreadManagementDurableRunProjectionError,
23 ThreadManagementProjectThreadsListError,
24 ThreadManagementProjectionLoadError,
25 ThreadManagementRunNotFoundError,
26 ThreadManagementService,
27 ThreadManagementThreadNotFoundError,
28 ThreadManagementThreadNotInterruptibleError,
29 ThreadManagementThreadArchivedError,
30 ThreadManagementNoSteerableRunError,
31 withCreationProvenance,
32} from "./ThreadManagementService.ts";
33
34it("stamps authoritative provenance on commands that create threads or messages", () => {
35 const command: OrchestrationV2Command = {
36 type: "thread.create",
37 createdBy: "agent",
38 creationSource: "mcp",
39 commandId: CommandId.make("command:thread-management:create"),
40 threadId: ThreadId.make("thread:thread-management:create"),
41 projectId: ProjectId.make("project:thread-management"),
42 title: "Thread management",
43 modelSelection: {
44 instanceId: ProviderInstanceId.make("codex"),
45 model: "gpt-5-codex",
46 },
47 runtimeMode: "full-access",
48 interactionMode: "default",
49 branch: null,
50 worktreePath: null,
51 };
52
53 expect(
54 withCreationProvenance(command, {
55 createdBy: "user",
56 creationSource: "web",
57 }),
58 ).toMatchObject({
59 createdBy: "user",
60 creationSource: "web",
61 });
62});
63
64it("leaves commands that do not create durable authored content unchanged", () => {
65 const command: OrchestrationV2Command = {
66 type: "run.interrupt",
67 commandId: CommandId.make("command:thread-management:interrupt"),
68 threadId: ThreadId.make("thread:thread-management:interrupt"),
69 runId: RunId.make("run:thread-management:interrupt"),
70 };
71
72 expect(
73 withCreationProvenance(command, {
74 createdBy: "user",
75 creationSource: "web",
76 }),
77 ).toBe(command);
78});
79
80it("identifies every existing thread that must be hydrated before dispatch", () => {
81 const sourceThreadId = ThreadId.make("thread:thread-management:source");
82 const targetThreadId = ThreadId.make("thread:thread-management:target");
83 const parentThreadId = ThreadId.make("thread:thread-management:parent");
84
85 expect(
86 existingThreadIdsForCommand({
87 type: "thread.create",
88 createdBy: "user",
89 creationSource: "web",
90 commandId: CommandId.make("command:thread-management:create"),
91 threadId: targetThreadId,
92 projectId: ProjectId.make("project:thread-management"),
93 title: "Created thread",
94 modelSelection: {
95 instanceId: ProviderInstanceId.make("codex"),
96 model: "gpt-5-codex",
97 },
98 runtimeMode: "full-access",
99 interactionMode: "default",
100 branch: null,
101 worktreePath: null,
102 }),
103 ).toEqual([]);
104
105 expect(
106 existingThreadIdsForCommand({
107 type: "thread.archive",
108 commandId: CommandId.make("command:thread-management:archive"),
109 threadId: targetThreadId,
110 }),
111 ).toEqual([targetThreadId]);
112
113 // Read-state commands skip transcript hydration entirely: they fire on
114 // every activity bump while a thread is open and never touch messages.
115 expect(
116 existingThreadIdsForCommand({
117 type: "thread.visit",
118 commandId: CommandId.make("command:thread-management:visit"),
119 threadId: targetThreadId,
120 visitedAt: "2026-07-30T00:00:00.000Z",
121 }),
122 ).toEqual([]);
123
124 expect(
125 existingThreadIdsForCommand({
126 type: "thread.mark-unread",
127 commandId: CommandId.make("command:thread-management:mark-unread"),
128 threadId: targetThreadId,
129 }),
130 ).toEqual([]);
131
132 expect(
133 existingThreadIdsForCommand({
134 type: "thread.fork",
135 createdBy: "user",
136 creationSource: "web",
137 commandId: CommandId.make("command:thread-management:fork"),
138 sourceThreadId,
139 targetThreadId,
140 sourcePoint: {
141 type: "run",
142 runId: RunId.make("run:thread-management:source"),
143 },
144 }),
145 ).toEqual([sourceThreadId]);
146
147 expect(
148 existingThreadIdsForCommand({
149 type: "thread.merge_back",
150 createdBy: "user",
151 creationSource: "web",
152 commandId: CommandId.make("command:thread-management:merge"),
153 sourceThreadId,
154 targetThreadId,
155 sourcePoint: {
156 type: "run",
157 runId: RunId.make("run:thread-management:source"),
158 },
159 }),
160 ).toEqual([sourceThreadId, targetThreadId]);
161
162 expect(
163 existingThreadIdsForCommand({
164 type: "delegated_task.request",
165 createdBy: "agent",
166 creationSource: "provider",
167 commandId: CommandId.make("command:thread-management:delegate"),
168 parentThreadId,
169 parentRunId: RunId.make("run:thread-management:parent"),
170 parentNodeId: NodeId.make("node:thread-management:parent"),
171 task: "Inspect the migration",
172 modelSelection: {
173 instanceId: ProviderInstanceId.make("codex"),
174 model: "gpt-5-codex",
175 },
176 runtimeMode: "full-access",
177 interactionMode: "default",
178 }),
179 ).toEqual([parentThreadId]);
180
181 expect(
182 existingThreadIdsForCommand({
183 type: "delegated_task.wake-policy",
184 commandId: CommandId.make("command:thread-management:wake-policy"),
185 parentThreadId,
186 taskId: NodeId.make("node:thread-management:delegated"),
187 completionWake: "always",
188 }),
189 ).toEqual([parentThreadId]);
190
191 expect(
192 existingThreadIdsForCommand({
193 type: "thread.created.record",
194 commandId: CommandId.make("command:thread-management:record"),
195 parentThreadId,
196 parentRunId: RunId.make("run:thread-management:parent"),
197 parentNodeId: NodeId.make("node:thread-management:parent"),
198 targetThreadId,
199 targetRunId: null,
200 }),
201 ).toEqual([parentThreadId, targetThreadId]);
202});
203
204it("derives thread management messages from structural error attributes", () => {
205 const projectId = ProjectId.make("project:thread-management:errors");
206 const threadId = ThreadId.make("thread:thread-management:errors");
207 const runId = RunId.make("run:thread-management:errors");
208 const messageId = MessageId.make("message:thread-management:errors");
209 const infrastructureCause = new Error("private sqlite detail");
210
211 const threadNotFound = new ThreadManagementThreadNotFoundError({
212 projectId,
213 threadId,
214 });
215 expect(threadNotFound).toMatchObject({ projectId, threadId });
216 expect(threadNotFound.message).toBe(`Thread ${threadId} was not found in project ${projectId}.`);
217
218 const runNotFound = new ThreadManagementRunNotFoundError({ threadId, runId });
219 expect(runNotFound).toMatchObject({ threadId, runId });
220 expect(runNotFound.message).toBe(`Run ${runId} does not belong to thread ${threadId}.`);
221
222 const archived = new ThreadManagementThreadArchivedError({
223 threadId,
224 });
225 expect(archived).toMatchObject({ threadId });
226 expect(archived.message).toBe(`Thread ${threadId} is archived and cannot receive messages.`);
227
228 const notSteerable = new ThreadManagementNoSteerableRunError({
229 threadId,
230 mode: "restart",
231 });
232 expect(notSteerable).toMatchObject({
233 threadId,
234 mode: "restart",
235 });
236 expect(notSteerable.message).toBe(
237 `Thread ${threadId} has no running turn that can be restarted.`,
238 );
239
240 const notInterruptible = new ThreadManagementThreadNotInterruptibleError({
241 threadId,
242 runId,
243 });
244 expect(notInterruptible).toMatchObject({ threadId, runId });
245 expect(notInterruptible.message).toBe(`Run ${runId} is not currently interruptible.`);
246
247 const listFailure = new ThreadManagementProjectThreadsListError({
248 projectId,
249 cause: infrastructureCause,
250 });
251 expect(listFailure).toMatchObject({ projectId, cause: infrastructureCause });
252 expect(listFailure.message).toBe(`Unable to list threads in project ${projectId}.`);
253 expect(listFailure.message).not.toContain(infrastructureCause.message);
254
255 const durableProjectionFailure = new ThreadManagementDurableRunProjectionError({
256 threadId,
257 messageId,
258 });
259 expect(durableProjectionFailure).toMatchObject({ threadId, messageId });
260 expect(durableProjectionFailure.message).toBe(
261 `Message ${messageId} was accepted on thread ${threadId} without a durable run projection.`,
262 );
263});
264
265it.effect("classifies projection infrastructure failures separately from a missing thread", () => {
266 const projectId = ProjectId.make("project:thread-management:projection-failure");
267 const threadId = ThreadId.make("thread:thread-management:projection-failure");
268 const infrastructureCause = new Error("sqlite read failed");
269 const projectionError = new OrchestratorProjectionError({
270 threadId,
271 cause: infrastructureCause,
272 });
273 const testLayer = layer.pipe(
274 Layer.provide(
275 Layer.mock(OrchestratorV2)({
276 getThreadProjection: () => Effect.fail(projectionError),
277 }),
278 ),
279 );
280
281 return Effect.gen(function* () {
282 const service = yield* ThreadManagementService;
283 const error = yield* Effect.flip(service.getProjectThread({ projectId, threadId }));
284
285 expect(error).toBeInstanceOf(ThreadManagementProjectionLoadError);
286 expect(error).toMatchObject({
287 projectId,
288 threadId,
289 cause: projectionError,
290 });
291 expect(error.message).toBe(`Unable to load thread ${threadId} in project ${projectId}.`);
292 }).pipe(Effect.provide(testLayer));
293});
294
295it.effect("uses thread-not-found only after a projection loads outside the project", () => {
296 const projectId = ProjectId.make("project:thread-management:requested");
297 const otherProjectId = ProjectId.make("project:thread-management:other");
298 const threadId = ThreadId.make("thread:thread-management:wrong-project");
299 const projection = {
300 thread: {
301 id: threadId,
302 projectId: otherProjectId,
303 deletedAt: null,
304 },
305 } as OrchestrationV2ThreadProjection;
306 const testLayer = layer.pipe(
307 Layer.provide(
308 Layer.mock(OrchestratorV2)({
309 getThreadProjection: () => Effect.succeed(projection),
310 }),
311 ),
312 );
313
314 return Effect.gen(function* () {
315 const service = yield* ThreadManagementService;
316 const error = yield* Effect.flip(service.getProjectThread({ projectId, threadId }));
317
318 expect(error).toBeInstanceOf(ThreadManagementThreadNotFoundError);
319 expect(error).toMatchObject({ projectId, threadId });
320 expect("cause" in error).toBe(false);
321 }).pipe(Effect.provide(testLayer));
322});
323
324it.effect("preserves failed legacy materialization when reading checkpoint context", () => {
325 const threadId = ThreadId.make("thread:thread-management:checkpoint-import-failure");
326 const importError = new LegacyV1ThreadImportError({
327 threadId,
328 operation: "hydrate transcript for",
329 cause: new Error("checkpoint import failed"),
330 });
331 const testLayer = layerWithLegacyImporter.pipe(
332 Layer.provide(
333 Layer.mergeAll(
334 Layer.mock(OrchestratorV2)({
335 getCheckpointContext: () =>
336 Effect.succeed({ runs: [], checkpointScopes: [], checkpoints: [] }),
337 }),
338 Layer.mock(LegacyV1ThreadImporter)({
339 ensureTranscript: () => Effect.fail(importError),
340 }),
341 ),
342 ),
343 );
344 return Effect.gen(function* () {
345 const service = yield* ThreadManagementService;
346 const error = yield* service.getCheckpointContext(threadId).pipe(Effect.flip);
347 expect(error).toBeInstanceOf(OrchestratorProjectionError);
348 expect(error).toMatchObject({ threadId, cause: importError });
349 }).pipe(Effect.provide(testLayer));
350});