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