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