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