Open History to see the last commit
1import {
2 EnvironmentId,
3 NodeId,
4 type OrchestrationV2ThreadProjection,
5 type OrchestrationV2ThreadShell,
6 ProjectId,
7 ProviderDriverKind,
8 ProviderInstanceId,
9 RunId,
10 ScheduledTaskId,
11 ThreadId,
12} from "@t3tools/contracts";
13import * as DateTime from "effect/DateTime";
14import * as Effect from "effect/Effect";
15import * as Layer from "effect/Layer";
16import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
17import { expect, it } from "vite-plus/test";
18
19import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";
20import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
21import * as ProjectService from "../project/ProjectService.ts";
22import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
23import * as SecretRequests from "../secrets/SecretRequests.ts";
24import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
25import type * as McpInvocationContext from "./McpInvocationContext.ts";
26import * as OrchestratorMcpService from "./OrchestratorMcpService.ts";
27
28const environmentId = EnvironmentId.make("environment-mcp-orchestrator-detail");
29const projectId = ProjectId.make("project-mcp-orchestrator-detail");
30const parentThreadId = ThreadId.make("thread-mcp-orchestrator-parent");
31const childThreadId = ThreadId.make("thread-mcp-orchestrator-child");
32const activeRunId = RunId.make("run-mcp-active");
33const cancelledRunId = RunId.make("run-mcp-cancelled");
34const childRunId = RunId.make("run-mcp-child");
35const taskId = NodeId.make("node-mcp-task-1");
36const now = DateTime.makeUnsafe("2026-08-04T12:00:00.000Z");
37const codexDriver = ProviderDriverKind.make("codex");
38// Distinct from driver kind so a regression that re-derives from driver fails.
39const customCodexInstanceId = ProviderInstanceId.make("codex-custom-workspace");
40const parentInstanceId = ProviderInstanceId.make("codex");
41
42const makeScope = (): McpInvocationContext.McpInvocationScope => ({
43 environmentId,
44 requestNamespace: "provider-session-mcp-orchestrator-detail",
45 thread: {
46 threadId: parentThreadId,
47 providerSessionId: "provider-session-mcp-orchestrator-detail",
48 providerInstanceId: parentInstanceId,
49 },
50 client: undefined,
51 capabilities: new Set(["orchestration"]),
52 issuedAt: 1,
53});
54
55function baseThread(input: {
56 readonly threadId: ThreadId;
57 readonly title: string;
58 readonly instanceId: ProviderInstanceId;
59 readonly model: string;
60}) {
61 return {
62 id: input.threadId,
63 projectId,
64 title: input.title,
65 createdBy: "user" as const,
66 creationSource: "mcp" as const,
67 modelSelection: {
68 instanceId: input.instanceId,
69 model: input.model,
70 },
71 runtimeMode: "full-access" as const,
72 interactionMode: "default" as const,
73 branch: null,
74 worktreePath: null,
75 lineage: {
76 parentThreadId: null,
77 relationshipToParent: null,
78 rootThreadId: input.threadId,
79 },
80 archivedAt: null,
81 deletedAt: null,
82 providerInstanceId: input.instanceId,
83 createdAt: now,
84 updatedAt: now,
85 };
86}
87
88function makeRun(input: {
89 readonly id: RunId;
90 readonly ordinal: number;
91 readonly status: "running" | "waiting" | "cancelled" | "queued" | "completed";
92 readonly instanceId?: ProviderInstanceId;
93}) {
94 return {
95 id: input.id,
96 ordinal: input.ordinal,
97 status: input.status,
98 modelSelection: {
99 instanceId: input.instanceId ?? parentInstanceId,
100 model: "gpt-5.4",
101 },
102 providerInstanceId: input.instanceId ?? parentInstanceId,
103 requestedAt: now,
104 startedAt: input.status === "cancelled" || input.status === "queued" ? null : now,
105 completedAt: input.status === "cancelled" || input.status === "completed" ? now : null,
106 };
107}
108
109it("readThread prefers activity-run status over a newer cancelled queued run", async () => {
110 const projection = {
111 thread: baseThread({
112 threadId: parentThreadId,
113 title: "Parent",
114 instanceId: parentInstanceId,
115 model: "gpt-5.4",
116 }),
117 runs: [
118 makeRun({ id: activeRunId, ordinal: 1, status: "running" }),
119 makeRun({ id: cancelledRunId, ordinal: 2, status: "cancelled" }),
120 ],
121 visibleTurnItems: [],
122 runtimeRequests: [],
123 messages: [],
124 contextTransfers: [],
125 subagents: [],
126 updatedAt: now,
127 } as unknown as OrchestrationV2ThreadProjection;
128
129 const layer = OrchestratorMcpService.layer.pipe(
130 Layer.provide(
131 Layer.mergeAll(
132 Layer.mock(ThreadManagementService.ThreadManagementService)({
133 getTimelinePage: () => Effect.succeed({ items: [], totalItems: 0, hasMore: false }),
134 getThreadRecords: (threadId) =>
135 threadId === parentThreadId
136 ? Effect.succeed(projection)
137 : Effect.die(`unexpected thread ${threadId}`),
138 getThreadShell: (threadId) =>
139 Effect.succeed(
140 threadId === parentThreadId
141 ? (projection.thread as unknown as OrchestrationV2ThreadShell)
142 : null,
143 ),
144 getProjectThreadRecords: (input) =>
145 input.threadId === parentThreadId
146 ? Effect.succeed(projection)
147 : Effect.die(`unexpected thread ${input.threadId}`),
148 } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
149 Layer.mock(ProviderRegistry.ProviderRegistry)({
150 getProviders: Effect.succeed([]),
151 } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>),
152 Layer.mock(ProjectService.ProjectService)({}),
153 Layer.mock(SecretRequests.SecretRequests)({}),
154 Layer.mock(ScheduledTaskService.ScheduledTaskService)({
155 list: () => Effect.succeed({ tasks: [] }),
156 } satisfies Partial<ScheduledTaskService.ScheduledTaskService["Service"]>),
157 Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
158 list: () => Effect.succeed([]),
159 } satisfies Partial<ProviderAdapterRegistry.ProviderAdapterRegistryV2["Service"]>),
160 NodeCrypto.layer,
161 ),
162 ),
163 );
164
165 await Effect.gen(function* () {
166 const service = yield* OrchestratorMcpService.OrchestratorMcpService;
167 const result = yield* service.readThread(makeScope(), { threadId: parentThreadId });
168 expect(result.thread.status).toBe("running");
169 expect(result.thread.latestRunId).toBe(cancelledRunId);
170 expect(result.thread.activeRunId).toBe(activeRunId);
171 }).pipe(Effect.provide(layer), Effect.runPromise);
172});
173
174it("readThread prefers waiting activity status over a newer cancelled queued run", async () => {
175 const projection = {
176 thread: baseThread({
177 threadId: parentThreadId,
178 title: "Parent waiting",
179 instanceId: parentInstanceId,
180 model: "gpt-5.4",
181 }),
182 runs: [
183 makeRun({ id: activeRunId, ordinal: 1, status: "waiting" }),
184 makeRun({ id: cancelledRunId, ordinal: 2, status: "cancelled" }),
185 ],
186 visibleTurnItems: [],
187 runtimeRequests: [],
188 messages: [],
189 contextTransfers: [],
190 subagents: [],
191 updatedAt: now,
192 } as unknown as OrchestrationV2ThreadProjection;
193
194 const layer = OrchestratorMcpService.layer.pipe(
195 Layer.provide(
196 Layer.mergeAll(
197 Layer.mock(ThreadManagementService.ThreadManagementService)({
198 getTimelinePage: () => Effect.succeed({ items: [], totalItems: 0, hasMore: false }),
199 getThreadRecords: (threadId) =>
200 threadId === parentThreadId
201 ? Effect.succeed(projection)
202 : Effect.die(`unexpected thread ${threadId}`),
203 getThreadShell: (threadId) =>
204 Effect.succeed(
205 threadId === parentThreadId
206 ? (projection.thread as unknown as OrchestrationV2ThreadShell)
207 : null,
208 ),
209 getProjectThreadRecords: (input) =>
210 input.threadId === parentThreadId
211 ? Effect.succeed(projection)
212 : Effect.die(`unexpected thread ${input.threadId}`),
213 } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
214 Layer.mock(ProviderRegistry.ProviderRegistry)({
215 getProviders: Effect.succeed([]),
216 } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>),
217 Layer.mock(ProjectService.ProjectService)({}),
218 Layer.mock(SecretRequests.SecretRequests)({}),
219 Layer.mock(ScheduledTaskService.ScheduledTaskService)({
220 list: () => Effect.succeed({ tasks: [] }),
221 } satisfies Partial<ScheduledTaskService.ScheduledTaskService["Service"]>),
222 Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
223 list: () => Effect.succeed([]),
224 } satisfies Partial<ProviderAdapterRegistry.ProviderAdapterRegistryV2["Service"]>),
225 NodeCrypto.layer,
226 ),
227 ),
228 );
229
230 await Effect.gen(function* () {
231 const service = yield* OrchestratorMcpService.OrchestratorMcpService;
232 const result = yield* service.readThread(makeScope(), { threadId: parentThreadId });
233 expect(result.thread.status).toBe("waiting");
234 expect(result.thread.activeRunId).toBe(activeRunId);
235 }).pipe(Effect.provide(layer), Effect.runPromise);
236});
237
238it("taskStatus returns task.providerInstanceId rather than the driver kind", async () => {
239 const parentProjection = {
240 thread: baseThread({
241 threadId: parentThreadId,
242 title: "Parent",
243 instanceId: parentInstanceId,
244 model: "gpt-5.4",
245 }),
246 runs: [makeRun({ id: activeRunId, ordinal: 1, status: "running" })],
247 visibleTurnItems: [],
248 runtimeRequests: [],
249 messages: [],
250 contextTransfers: [],
251 subagents: [
252 {
253 id: taskId,
254 threadId: parentThreadId,
255 runId: activeRunId,
256 parentNodeId: NodeId.make("node-parent"),
257 origin: "app_owned",
258 createdBy: "agent",
259 driver: codexDriver,
260 providerInstanceId: customCodexInstanceId,
261 providerThreadId: null,
262 childThreadId,
263 nativeTaskRef: null,
264 prompt: "Inspect the custom instance.",
265 title: null,
266 model: "gpt-5.4",
267 status: "running",
268 result: null,
269 startedAt: now,
270 completedAt: null,
271 updatedAt: now,
272 },
273 ],
274 updatedAt: now,
275 } as unknown as OrchestrationV2ThreadProjection;
276
277 const childProjection = {
278 thread: {
279 ...baseThread({
280 threadId: childThreadId,
281 title: "Child",
282 instanceId: customCodexInstanceId,
283 model: "gpt-5.4",
284 }),
285 lineage: {
286 parentThreadId,
287 relationshipToParent: "subagent",
288 rootThreadId: parentThreadId,
289 },
290 createdBy: "agent",
291 },
292 runs: [
293 makeRun({
294 id: childRunId,
295 ordinal: 1,
296 status: "running",
297 instanceId: customCodexInstanceId,
298 }),
299 ],
300 visibleTurnItems: [],
301 runtimeRequests: [],
302 messages: [],
303 contextTransfers: [
304 {
305 type: "subagent_spawn",
306 sourceThreadId: parentThreadId,
307 targetThreadId: childThreadId,
308 targetRunId: childRunId,
309 },
310 ],
311 subagents: [],
312 providerThreads: [],
313 updatedAt: now,
314 } as unknown as OrchestrationV2ThreadProjection;
315
316 const layer = OrchestratorMcpService.layer.pipe(
317 Layer.provide(
318 Layer.mergeAll(
319 Layer.mock(ThreadManagementService.ThreadManagementService)({
320 getTimelinePage: () => Effect.succeed({ items: [], totalItems: 0, hasMore: false }),
321 getThreadRecords: (threadId) => {
322 if (threadId === parentThreadId) return Effect.succeed(parentProjection);
323 if (threadId === childThreadId) return Effect.succeed(childProjection);
324 return Effect.die(`unexpected thread ${threadId}`);
325 },
326 } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
327 Layer.mock(ProviderRegistry.ProviderRegistry)({
328 getProviders: Effect.succeed([]),
329 } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>),
330 Layer.mock(ProjectService.ProjectService)({}),
331 Layer.mock(SecretRequests.SecretRequests)({}),
332 Layer.mock(ScheduledTaskService.ScheduledTaskService)({
333 list: () => Effect.succeed({ tasks: [] }),
334 } satisfies Partial<ScheduledTaskService.ScheduledTaskService["Service"]>),
335 Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
336 list: () => Effect.succeed([]),
337 } satisfies Partial<ProviderAdapterRegistry.ProviderAdapterRegistryV2["Service"]>),
338 NodeCrypto.layer,
339 ),
340 ),
341 );
342
343 await Effect.gen(function* () {
344 const service = yield* OrchestratorMcpService.OrchestratorMcpService;
345 const result = yield* service.taskStatus(makeScope(), taskId);
346 expect(result.providerInstanceId).toBe(customCodexInstanceId);
347 expect(result.providerInstanceId).not.toBe(ProviderInstanceId.make(String(codexDriver)));
348 expect(result.status).toBe("running");
349 expect(result.taskId).toBe(taskId);
350 expect(result.childThreadId).toBe(childThreadId);
351 }).pipe(Effect.provide(layer), Effect.runPromise);
352});
353
354it("readThread and sendToThread reach threads in other projects", async () => {
355 let parentRuns: ReadonlyArray<unknown> = [
356 makeRun({ id: RunId.make("run-parent-live"), ordinal: 1, status: "running" }),
357 ];
358 const foreignProjectId = ProjectId.make("project-mcp-orchestrator-foreign");
359 const foreignThreadId = ThreadId.make("thread-mcp-orchestrator-foreign");
360 const parentProjection = {
361 thread: baseThread({
362 threadId: parentThreadId,
363 title: "Parent",
364 instanceId: parentInstanceId,
365 model: "gpt-5.4",
366 }),
367 get runs() {
368 return parentRuns;
369 },
370 visibleTurnItems: [],
371 runtimeRequests: [],
372 messages: [],
373 contextTransfers: [],
374 subagents: [],
375 updatedAt: now,
376 } as unknown as OrchestrationV2ThreadProjection;
377 const foreignProjection = (threadId: ThreadId) =>
378 ({
379 thread: {
380 ...baseThread({
381 threadId,
382 title: "Foreign",
383 instanceId: parentInstanceId,
384 model: "gpt-5.4",
385 }),
386 projectId: foreignProjectId,
387 },
388 runs: [],
389 visibleTurnItems: [
390 {
391 position: 0,
392 visibility: "inherited",
393 sourceThreadId: threadId,
394 sourceItemId: "item-1",
395 item: {
396 id: "item-1",
397 type: "assistant_message",
398 messageId: "assistant-1",
399 status: "completed",
400 title: null,
401 text: "Foreign thread said hello",
402 createdAt: now,
403 updatedAt: now,
404 },
405 },
406 ],
407 runtimeRequests: [],
408 messages: [],
409 contextTransfers: [],
410 subagents: [],
411 updatedAt: now,
412 }) as unknown as OrchestrationV2ThreadProjection;
413
414 const layer = OrchestratorMcpService.layer.pipe(
415 Layer.provide(
416 Layer.mergeAll(
417 Layer.mock(ThreadManagementService.ThreadManagementService)({
418 getThreadRecords: (threadId) => {
419 if (threadId === parentThreadId) return Effect.succeed(parentProjection);
420 if (threadId === foreignThreadId) return Effect.succeed(foreignProjection(threadId));
421 return Effect.die(`unexpected thread ${threadId}`);
422 },
423 getThreadShell: (threadId) =>
424 Effect.succeed(
425 threadId === foreignThreadId
426 ? (foreignProjection(threadId).thread as unknown as OrchestrationV2ThreadShell)
427 : null,
428 ),
429 getTimelinePage: (threadId) =>
430 Effect.succeed({
431 items: foreignProjection(threadId).visibleTurnItems,
432 totalItems: 1,
433 hasMore: false,
434 }),
435 getProjectThreadRecords: (input) =>
436 input.threadId === foreignThreadId && input.projectId === foreignProjectId
437 ? Effect.succeed(foreignProjection(input.threadId))
438 : Effect.fail(
439 new ThreadManagementService.ThreadManagementThreadNotFoundError({
440 projectId: input.projectId,
441 threadId: input.threadId,
442 }),
443 ),
444 sendToThread: () =>
445 Effect.succeed({
446 run: { id: "run-foreign", status: "queued" },
447 delivery: "started",
448 } as unknown as ThreadManagementService.ThreadManagementSendResult),
449 } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
450 Layer.mock(ProviderRegistry.ProviderRegistry)({
451 getProviders: Effect.succeed([]),
452 } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>),
453 Layer.mock(ProjectService.ProjectService)({}),
454 Layer.mock(SecretRequests.SecretRequests)({}),
455 Layer.mock(ScheduledTaskService.ScheduledTaskService)({
456 list: () =>
457 Effect.succeed({
458 tasks: [
459 {
460 id: "task-foreign",
461 projectId: foreignProjectId,
462 runtimeMode: "approval-required",
463 interactionMode: "default",
464 } as never,
465 ],
466 }),
467 } satisfies Partial<ScheduledTaskService.ScheduledTaskService["Service"]>),
468 Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
469 list: () => Effect.succeed([]),
470 } satisfies Partial<ProviderAdapterRegistry.ProviderAdapterRegistryV2["Service"]>),
471 NodeCrypto.layer,
472 ),
473 ),
474 );
475
476 await Effect.gen(function* () {
477 const service = yield* OrchestratorMcpService.OrchestratorMcpService;
478 const foreign = yield* service.readThread(makeScope(), { threadId: foreignThreadId });
479 expect(foreign.thread.threadId).toBe(foreignThreadId);
480 expect(foreign.thread.projectId).toBe(foreignProjectId);
481 expect(foreign.items.map((item) => item.text)).toEqual(["Foreign thread said hello"]);
482
483 const sent = yield* service.sendToThread(makeScope(), {
484 threadId: foreignThreadId,
485 message: "hi",
486 });
487 expect(sent.threadId).toBe(foreignThreadId);
488
489 // Once the caller's run ends, it can still read other threads but no longer write to them.
490 parentRuns = [];
491 yield* service.readThread(makeScope(), { threadId: foreignThreadId });
492 const stale = yield* service
493 .sendToThread(makeScope(), { threadId: foreignThreadId, message: "hi again" })
494 .pipe(Effect.flip);
495 expect(stale.code).toBe("parent_not_active");
496 const staleInterrupt = yield* service
497 .interruptThread(makeScope(), { threadId: foreignThreadId })
498 .pipe(Effect.flip);
499 expect(staleInterrupt.code).toBe("parent_not_active");
500 // Nor create, change or remove scheduled work in another project.
501 const staleSchedule = yield* service
502 .scheduleTask(makeScope(), {
503 projectId: foreignProjectId,
504 prompt: "check in later",
505 schedule: { type: "interval", everyMs: 3_600_000 },
506 })
507 .pipe(Effect.flip);
508 expect(staleSchedule.code).toBe("parent_not_active");
509 const staleUpdate = yield* service
510 .updateScheduledTask(makeScope(), {
511 scheduledTaskId: ScheduledTaskId.make("task-foreign"),
512 enabled: false,
513 })
514 .pipe(Effect.flip);
515 expect(staleUpdate.code).toBe("parent_not_active");
516 const staleDelete = yield* service
517 .deleteScheduledTask(makeScope(), { scheduledTaskId: ScheduledTaskId.make("task-foreign") })
518 .pipe(Effect.flip);
519 expect(staleDelete.code).toBe("parent_not_active");
520 }).pipe(Effect.provide(layer), Effect.runPromise);
521});