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