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 { OrchestratorDispatchError } from "../orchestration-v2/Orchestrator.ts";
28import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
29import type * as McpInvocationContext from "./McpInvocationContext.ts";
30import * as OrchestratorMcpService from "./OrchestratorMcpService.ts";
31import { idleThreadProjection, 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(ScheduledTaskService.ScheduledTaskService)({
166 list: () => Effect.succeed({ tasks: [] }),
167 } satisfies Partial<ScheduledTaskService.ScheduledTaskService["Service"]>),
168 Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
169 list: () => Effect.succeed([]),
170 } satisfies Partial<ProviderAdapterRegistry.ProviderAdapterRegistryV2["Service"]>),
171 NodeCrypto.layer,
172 ),
173 ),
174 );
175
176 await Effect.gen(function* () {
177 const service = yield* OrchestratorMcpService.OrchestratorMcpService;
178 const result = yield* service.readThread(makeScope(), { threadId: parentThreadId });
179 expect(result.thread.status).toBe("running");
180 expect(result.thread.latestRunId).toBe(cancelledRunId);
181 expect(result.thread.activeRunId).toBe(activeRunId);
182 }).pipe(Effect.provide(layer), Effect.runPromise);
183});
184
185it("readThread prefers waiting activity status over a newer cancelled queued run", async () => {
186 const projection = {
187 thread: baseThread({
188 threadId: parentThreadId,
189 title: "Parent waiting",
190 instanceId: parentInstanceId,
191 model: "gpt-5.4",
192 }),
193 runs: [
194 makeRun({ id: activeRunId, ordinal: 1, status: "waiting" }),
195 makeRun({ id: cancelledRunId, ordinal: 2, status: "cancelled" }),
196 ],
197 visibleTurnItems: [],
198 runtimeRequests: [],
199 messages: [],
200 contextTransfers: [],
201 subagents: [],
202 updatedAt: now,
203 } as unknown as OrchestrationV2ThreadProjection;
204
205 const layer = layerOrchestratorService.pipe(
206 Layer.provide(
207 Layer.mergeAll(
208 Layer.mock(ThreadManagementService.ThreadManagementService)({
209 getTimelinePage: () => Effect.succeed({ items: [], totalItems: 0, hasMore: false }),
210 getThreadRecords: (threadId) =>
211 threadId === parentThreadId
212 ? Effect.succeed(projection)
213 : Effect.die(`unexpected thread ${threadId}`),
214 getThreadShell: (threadId) =>
215 Effect.succeed(
216 threadId === parentThreadId
217 ? (projection.thread as unknown as OrchestrationV2ThreadShell)
218 : null,
219 ),
220 getProjectThreadRecords: (input) =>
221 input.threadId === parentThreadId
222 ? Effect.succeed(projection)
223 : Effect.die(`unexpected thread ${input.threadId}`),
224 } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
225 ServerSettings.layerTest(),
226 Layer.mock(ProviderRegistry.ProviderRegistry)({
227 getProviders: Effect.succeed([]),
228 } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>),
229 Layer.mock(ProjectService.ProjectService)({}),
230 Layer.mock(SecretRequests.SecretRequests)({}),
231 Layer.mock(ScheduledTaskService.ScheduledTaskService)({
232 list: () => Effect.succeed({ tasks: [] }),
233 } satisfies Partial<ScheduledTaskService.ScheduledTaskService["Service"]>),
234 Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
235 list: () => Effect.succeed([]),
236 } satisfies Partial<ProviderAdapterRegistry.ProviderAdapterRegistryV2["Service"]>),
237 NodeCrypto.layer,
238 ),
239 ),
240 );
241
242 await Effect.gen(function* () {
243 const service = yield* OrchestratorMcpService.OrchestratorMcpService;
244 const result = yield* service.readThread(makeScope(), { threadId: parentThreadId });
245 expect(result.thread.status).toBe("waiting");
246 expect(result.thread.activeRunId).toBe(activeRunId);
247 }).pipe(Effect.provide(layer), Effect.runPromise);
248});
249
250it("taskStatus returns task.providerInstanceId rather than the driver kind", async () => {
251 const parentProjection = {
252 thread: baseThread({
253 threadId: parentThreadId,
254 title: "Parent",
255 instanceId: parentInstanceId,
256 model: "gpt-5.4",
257 }),
258 runs: [makeRun({ id: activeRunId, ordinal: 1, status: "running" })],
259 visibleTurnItems: [],
260 runtimeRequests: [],
261 messages: [],
262 contextTransfers: [],
263 subagents: [
264 {
265 id: taskId,
266 threadId: parentThreadId,
267 runId: activeRunId,
268 parentNodeId: NodeId.make("node-parent"),
269 origin: "app_owned",
270 createdBy: "agent",
271 driver: codexDriver,
272 providerInstanceId: customCodexInstanceId,
273 providerThreadId: null,
274 childThreadId,
275 nativeTaskRef: null,
276 prompt: "Inspect the custom instance.",
277 title: null,
278 model: "gpt-5.4",
279 status: "running",
280 result: null,
281 startedAt: now,
282 completedAt: null,
283 updatedAt: now,
284 },
285 ],
286 updatedAt: now,
287 } as unknown as OrchestrationV2ThreadProjection;
288
289 const childProjection = {
290 thread: {
291 ...baseThread({
292 threadId: childThreadId,
293 title: "Child",
294 instanceId: customCodexInstanceId,
295 model: "gpt-5.4",
296 }),
297 lineage: {
298 parentThreadId,
299 relationshipToParent: "subagent",
300 rootThreadId: parentThreadId,
301 },
302 createdBy: "agent",
303 },
304 runs: [
305 makeRun({
306 id: childRunId,
307 ordinal: 1,
308 status: "running",
309 instanceId: customCodexInstanceId,
310 }),
311 ],
312 visibleTurnItems: [],
313 runtimeRequests: [],
314 messages: [],
315 contextTransfers: [
316 {
317 type: "subagent_spawn",
318 sourceThreadId: parentThreadId,
319 targetThreadId: childThreadId,
320 targetRunId: childRunId,
321 },
322 ],
323 subagents: [],
324 providerThreads: [],
325 updatedAt: now,
326 } as unknown as OrchestrationV2ThreadProjection;
327
328 const layer = layerOrchestratorService.pipe(
329 Layer.provide(
330 Layer.mergeAll(
331 Layer.mock(ThreadManagementService.ThreadManagementService)({
332 getTimelinePage: () => Effect.succeed({ items: [], totalItems: 0, hasMore: false }),
333 getThreadRecords: (threadId) => {
334 if (threadId === parentThreadId) return Effect.succeed(parentProjection);
335 if (threadId === childThreadId) return Effect.succeed(childProjection);
336 return Effect.die(`unexpected thread ${threadId}`);
337 },
338 } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
339 ServerSettings.layerTest(),
340 Layer.mock(ProviderRegistry.ProviderRegistry)({
341 getProviders: Effect.succeed([]),
342 } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>),
343 Layer.mock(ProjectService.ProjectService)({}),
344 Layer.mock(SecretRequests.SecretRequests)({}),
345 Layer.mock(ScheduledTaskService.ScheduledTaskService)({
346 list: () => Effect.succeed({ tasks: [] }),
347 } satisfies Partial<ScheduledTaskService.ScheduledTaskService["Service"]>),
348 Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
349 list: () => Effect.succeed([]),
350 } satisfies Partial<ProviderAdapterRegistry.ProviderAdapterRegistryV2["Service"]>),
351 NodeCrypto.layer,
352 ),
353 ),
354 );
355
356 await Effect.gen(function* () {
357 const service = yield* OrchestratorMcpService.OrchestratorMcpService;
358 const result = yield* service.taskStatus(makeScope(), taskId);
359 expect(result.providerInstanceId).toBe(customCodexInstanceId);
360 expect(result.providerInstanceId).not.toBe(ProviderInstanceId.make(String(codexDriver)));
361 expect(result.status).toBe("running");
362 expect(result.taskId).toBe(taskId);
363 expect(result.childThreadId).toBe(childThreadId);
364 }).pipe(Effect.provide(layer), Effect.runPromise);
365});
366
367it("readThread and sendToThread reach threads in other projects", async () => {
368 let parentShell: OrchestrationV2ThreadShell | null = null;
369 let parentRuns: ReadonlyArray<unknown> = [
370 makeRun({ id: RunId.make("run-parent-live"), ordinal: 1, status: "running" }),
371 ];
372 const foreignProjectId = ProjectId.make("project-mcp-orchestrator-foreign");
373 const foreignThreadId = ThreadId.make("thread-mcp-orchestrator-foreign");
374 const parentProjection = {
375 thread: baseThread({
376 threadId: parentThreadId,
377 title: "Parent",
378 instanceId: parentInstanceId,
379 model: "gpt-5.4",
380 }),
381 get runs() {
382 return parentRuns;
383 },
384 visibleTurnItems: [],
385 runtimeRequests: [],
386 messages: [],
387 contextTransfers: [],
388 subagents: [],
389 updatedAt: now,
390 } as unknown as OrchestrationV2ThreadProjection;
391 const foreignProjection = (threadId: ThreadId) =>
392 ({
393 thread: {
394 ...baseThread({
395 threadId,
396 title: "Foreign",
397 instanceId: parentInstanceId,
398 model: "gpt-5.4",
399 }),
400 projectId: foreignProjectId,
401 },
402 runs: [],
403 visibleTurnItems: [
404 {
405 position: 0,
406 visibility: "inherited",
407 sourceThreadId: threadId,
408 sourceItemId: "item-1",
409 item: {
410 id: "item-1",
411 type: "assistant_message",
412 messageId: "assistant-1",
413 status: "completed",
414 title: null,
415 text: "Foreign thread said hello",
416 createdAt: now,
417 updatedAt: now,
418 },
419 },
420 ],
421 runtimeRequests: [],
422 messages: [],
423 contextTransfers: [],
424 subagents: [],
425 updatedAt: now,
426 }) as unknown as OrchestrationV2ThreadProjection;
427
428 const layer = layerOrchestratorService.pipe(
429 Layer.provide(
430 Layer.mergeAll(
431 Layer.mock(ThreadManagementService.ThreadManagementService)({
432 getThreadRecords: (threadId) => {
433 if (threadId === parentThreadId) return Effect.succeed(parentProjection);
434 if (threadId === foreignThreadId) return Effect.succeed(foreignProjection(threadId));
435 return Effect.die(`unexpected thread ${threadId}`);
436 },
437 getThreadShell: (threadId) =>
438 Effect.succeed(
439 threadId === foreignThreadId
440 ? (foreignProjection(threadId).thread as unknown as OrchestrationV2ThreadShell)
441 : threadId === parentThreadId
442 ? parentShell
443 : null,
444 ),
445 getTimelinePage: (threadId) =>
446 Effect.succeed({
447 items: foreignProjection(threadId).visibleTurnItems,
448 totalItems: 1,
449 hasMore: false,
450 }),
451 getProjectThreadRecords: (input) =>
452 input.threadId === foreignThreadId && input.projectId === foreignProjectId
453 ? Effect.succeed(foreignProjection(input.threadId))
454 : Effect.fail(
455 new ThreadManagementService.ThreadManagementThreadNotFoundError({
456 projectId: input.projectId,
457 threadId: input.threadId,
458 }),
459 ),
460 sendToThread: () =>
461 Effect.succeed({
462 run: { id: "run-foreign", status: "queued" },
463 delivery: "started",
464 } as unknown as ThreadManagementService.ThreadManagementSendResult),
465 } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
466 ServerSettings.layerTest(),
467 Layer.mock(ProviderRegistry.ProviderRegistry)({
468 getProviders: Effect.succeed([]),
469 } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>),
470 Layer.mock(ProjectService.ProjectService)({}),
471 Layer.mock(SecretRequests.SecretRequests)({}),
472 Layer.mock(ScheduledTaskService.ScheduledTaskService)({
473 list: () =>
474 Effect.succeed({
475 tasks: [
476 {
477 id: "task-foreign",
478 projectId: foreignProjectId,
479 runtimeMode: "approval-required",
480 interactionMode: "default",
481 } as never,
482 ],
483 }),
484 } satisfies Partial<ScheduledTaskService.ScheduledTaskService["Service"]>),
485 Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
486 list: () => Effect.succeed([]),
487 } satisfies Partial<ProviderAdapterRegistry.ProviderAdapterRegistryV2["Service"]>),
488 NodeCrypto.layer,
489 ),
490 ),
491 );
492
493 await Effect.gen(function* () {
494 const service = yield* OrchestratorMcpService.OrchestratorMcpService;
495 const foreign = yield* service.readThread(makeScope(), { threadId: foreignThreadId });
496 expect(foreign.thread.threadId).toBe(foreignThreadId);
497 expect(foreign.thread.projectId).toBe(foreignProjectId);
498 expect(foreign.items.map((item) => item.text)).toEqual(["Foreign thread said hello"]);
499
500 const sent = yield* service.sendToThread(makeScope(), {
501 threadId: foreignThreadId,
502 message: "hi",
503 });
504 expect(sent.threadId).toBe(foreignThreadId);
505
506 parentRuns = [];
507 yield* service.readThread(makeScope(), { threadId: foreignThreadId });
508 const stale = yield* service
509 .sendToThread(makeScope(), { threadId: foreignThreadId, message: "hi again" })
510 .pipe(Effect.flip);
511 expect(stale.code).toBe("parent_not_active");
512 const staleInterrupt = yield* service
513 .interruptThread(makeScope(), { threadId: foreignThreadId })
514 .pipe(Effect.flip);
515 expect(staleInterrupt.code).toBe("parent_not_active");
516
517 const staleSchedule = yield* service
518 .scheduleTask(makeScope(), {
519 projectId: foreignProjectId,
520 prompt: "check in later",
521 schedule: { type: "interval", everyMs: 3_600_000 },
522 })
523 .pipe(Effect.flip);
524 expect(staleSchedule.code).toBe("parent_not_active");
525 const staleUpdate = yield* service
526 .updateScheduledTask(makeScope(), {
527 scheduledTaskId: ScheduledTaskId.make("task-foreign"),
528 enabled: false,
529 })
530 .pipe(Effect.flip);
531 expect(staleUpdate.code).toBe("parent_not_active");
532 const staleDelete = yield* service
533 .deleteScheduledTask(makeScope(), { scheduledTaskId: ScheduledTaskId.make("task-foreign") })
534 .pipe(Effect.flip);
535 expect(staleDelete.code).toBe("parent_not_active");
536
537 // A background item keeps only its owning instance live, even after a switch.
538 const backgroundTasks = [
539 {
540 taskId: "background-subagent",
541 kind: "subagent" as const,
542 providerInstanceId: parentInstanceId,
543 },
544 ];
545 parentShell = {
546 ...liveThreadShell(parentThreadId, { activeRunId: null }),
547 pendingBackgroundTasks: backgroundTasks,
548 };
549 const backgroundSent = yield* service.sendToThread(makeScope(), {
550 threadId: foreignThreadId,
551 message: "background",
552 });
553 expect(backgroundSent.threadId).toBe(foreignThreadId);
554 const delegate = yield* service
555 .delegateTask(makeScope(), { task: "requires a run" })
556 .pipe(Effect.flip);
557 expect(delegate.code).toBe("parent_not_active");
558 const create = yield* service
559 .createThreads(makeScope(), { threads: [{ prompt: "requires a run" }] })
560 .pipe(Effect.flip);
561 expect(create.code).toBe("parent_not_active");
562 const secret = yield* service
563 .requestSecret(makeScope(), { label: "Secret", reason: "requires a run" })
564 .pipe(Effect.flip);
565 expect(secret.code).toBe("parent_not_active");
566
567 parentShell = { ...parentShell, providerInstanceId: customCodexInstanceId };
568 const switchedScope = {
569 ...makeScope(),
570 thread: { ...makeScope().thread!, providerInstanceId: customCodexInstanceId },
571 };
572 const switched = yield* service
573 .sendToThread(switchedScope, { threadId: foreignThreadId, message: "wrong owner" })
574 .pipe(Effect.flip);
575 expect(switched.code).toBe("parent_not_active");
576 const mismatched = yield* service
577 .sendToThread(makeScope(), { threadId: foreignThreadId, message: "stale provider" })
578 .pipe(Effect.flip);
579 expect(mismatched.code).toBe("parent_not_active");
580
581 // A fresh active run wins over the earlier inactive projection and empty roster.
582 parentShell = liveThreadShell(parentThreadId);
583 const restarted = yield* service.sendToThread(makeScope(), {
584 threadId: foreignThreadId,
585 message: "new run",
586 });
587 expect(restarted.threadId).toBe(foreignThreadId);
588
589 parentShell = {
590 ...parentShell,
591 activeRunId: null,
592 pendingBackgroundTasks: backgroundTasks,
593 archivedAt: now,
594 };
595 const archived = yield* service
596 .sendToThread(makeScope(), { threadId: foreignThreadId, message: "archived" })
597 .pipe(Effect.flip);
598 expect(archived.code).toBe("parent_not_active");
599
600 parentShell = { ...parentShell, archivedAt: null, pendingBackgroundTasks: [] };
601 const stopped = yield* service
602 .sendToThread(makeScope(), { threadId: foreignThreadId, message: "after stop" })
603 .pipe(Effect.flip);
604 expect(stopped.code).toBe("parent_not_active");
605 }).pipe(Effect.provide(layer), Effect.runPromise);
606});
607
608it("sendToThread reports why the orchestrator refused the message", async () => {
609 const targetThreadId = ThreadId.make("thread-mcp-orchestrator-dead-session");
610 const targetProjection = {
611 thread: baseThread({
612 threadId: targetThreadId,
613 title: "Stalled",
614 instanceId: parentInstanceId,
615 model: "gpt-5.4",
616 }),
617 runs: [],
618 visibleTurnItems: [],
619 runtimeRequests: [],
620 messages: [],
621 contextTransfers: [],
622 subagents: [],
623 updatedAt: now,
624 } as unknown as OrchestrationV2ThreadProjection;
625
626 const layer = layerOrchestratorService.pipe(
627 Layer.provide(
628 Layer.mergeAll(
629 Layer.mock(ThreadManagementService.ThreadManagementService)({
630 getThreadShell: (threadId) =>
631 Effect.succeed(
632 threadId === targetThreadId
633 ? (targetProjection.thread as unknown as OrchestrationV2ThreadShell)
634 : liveThreadShell(parentThreadId),
635 ),
636 getThreadRecords: (threadId) =>
637 Effect.succeed(
638 threadId === targetThreadId
639 ? targetProjection
640 : ({
641 ...targetProjection,
642 thread: baseThread({
643 threadId: parentThreadId,
644 title: "Parent",
645 instanceId: parentInstanceId,
646 model: "gpt-5.4",
647 }),
648 runs: [
649 makeRun({ id: RunId.make("run-parent-live"), ordinal: 1, status: "running" }),
650 ],
651 } as unknown as OrchestrationV2ThreadProjection),
652 ),
653 getProjectThreadRecords: () => Effect.succeed(targetProjection),
654 sendToThread: (input) =>
655 Effect.fail(
656 new OrchestratorDispatchError({
657 commandId: input.commandId,
658 commandType: "message.dispatch",
659 cause: "Provider session provider-session-dead is not active.",
660 }),
661 ),
662 } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
663 ServerSettings.layerTest(),
664 Layer.mock(ProviderRegistry.ProviderRegistry)({
665 getProviders: Effect.succeed([]),
666 } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>),
667 Layer.mock(ProjectService.ProjectService)({}),
668 Layer.mock(SecretRequests.SecretRequests)({}),
669 Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
670 Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
671 list: () => Effect.succeed([]),
672 } satisfies Partial<ProviderAdapterRegistry.ProviderAdapterRegistryV2["Service"]>),
673 NodeCrypto.layer,
674 ),
675 ),
676 );
677
678 await Effect.gen(function* () {
679 const service = yield* OrchestratorMcpService.OrchestratorMcpService;
680 const failure = yield* service
681 .sendToThread(makeScope(), { threadId: targetThreadId, message: "restart", mode: "restart" })
682 .pipe(Effect.flip);
683 expect(failure.code).toBe("orchestration_error");
684 expect(failure.message).toBe(
685 `Unable to send to thread ${targetThreadId}: Provider session provider-session-dead is not active.`,
686 );
687 }).pipe(Effect.provide(layer), Effect.runPromise);
688});
689
690it("readThread exposes the stored sender thread only for thread-sent messages", async () => {
691 const shell = liveThreadShell(parentThreadId);
692 const messages = [
693 { id: "message-from-child", text: "Child reporting in", senderThreadId: childThreadId },
694 { id: "message-from-user", text: "Thanks" },
695 ];
696 const projection = {
697 ...idleThreadProjection(shell),
698 messages,
699 visibleTurnItems: messages.map((message, position) => ({
700 position,
701 visibility: "local",
702 sourceThreadId: parentThreadId,
703 sourceItemId: `item-${message.id}`,
704 item: {
705 id: `item-${message.id}`,
706 type: "user_message",
707 messageId: message.id,
708 runId: activeRunId,
709 status: "completed",
710 title: null,
711 text: message.text,
712 updatedAt: now,
713 },
714 })),
715 } as unknown as OrchestrationV2ThreadProjection;
716 const layer = layerOrchestratorService.pipe(
717 Layer.provide(
718 Layer.mergeAll(
719 Layer.mock(ThreadManagementService.ThreadManagementService)({
720 getThreadShell: () => Effect.succeed(shell),
721 getThreadRecords: () => Effect.succeed(projection),
722 getProjectThreadRecords: () => Effect.succeed(projection),
723 getTimelinePage: () =>
724 Effect.succeed({ items: projection.visibleTurnItems, totalItems: 2, hasMore: false }),
725 }),
726 ServerSettings.layerTest(),
727 Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),
728 Layer.mock(ProjectService.ProjectService)({}),
729 Layer.mock(SecretRequests.SecretRequests)({}),
730 Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
731 Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({}),
732 NodeCrypto.layer,
733 ),
734 ),
735 );
736
737 await Effect.gen(function* () {
738 const service = yield* OrchestratorMcpService.OrchestratorMcpService;
739 const result = yield* service.readThread(makeScope(), { threadId: parentThreadId });
740 expect(result.items).toMatchObject([
741 { messageId: "message-from-child", senderThreadId: childThreadId },
742 { messageId: "message-from-user" },
743 ]);
744 expect(result.items[1]).not.toHaveProperty("senderThreadId");
745 }).pipe(Effect.provide(layer), Effect.runPromise);
746});
747
748const readThreadId = ThreadId.make("thread-mcp-orchestrator-read");
749
750function assistantRow(position: number, text: string) {
751 return {
752 position,
753 visibility: "local",
754 sourceThreadId: readThreadId,
755 sourceItemId: `item-${position}`,
756 item: {
757 id: `item-${position}`,
758 type: "assistant_message",
759 runId: "run-read-1",
760 messageId: `message-${position}`,
761 status: "completed",
762 title: null,
763 text,
764 createdAt: now,
765 updatedAt: now,
766 },
767 };
768}
769
770function readThreadLayer(input: {
771 readonly rows: ReadonlyArray<{
772 readonly position: number;
773 readonly sourceItemId: string;
774 readonly item: { readonly type: string };
775 }>;
776 readonly runCount?: number;
777}) {
778 const projection = {
779 thread: baseThread({
780 threadId: readThreadId,
781 title: "Read",
782 instanceId: parentInstanceId,
783 model: "gpt-5.4",
784 }),
785 runs: Array.from({ length: input.runCount ?? 1 }, (_, index) =>
786 makeRun({ id: RunId.make(`run-read-${index + 1}`), ordinal: index + 1, status: "completed" }),
787 ),
788 visibleTurnItems: input.rows,
789 runtimeRequests: [],
790 messages: [],
791 contextTransfers: [],
792 subagents: [],
793 updatedAt: now,
794 } as unknown as OrchestrationV2ThreadProjection;
795 return layerOrchestratorService.pipe(
796 Layer.provide(
797 Layer.mergeAll(
798 Layer.mock(ThreadManagementService.ThreadManagementService)({
799 getThreadRecords: () => Effect.succeed(projection),
800 getThreadShell: () =>
801 Effect.succeed(projection.thread as unknown as OrchestrationV2ThreadShell),
802 getTimelinePage: (_threadId, options) => {
803 // Match ProjectionStore: itemId bypasses the message-only default view.
804 const matching = input.rows.filter((row) =>
805 options.itemId === undefined
806 ? row.position > (options.afterPosition ?? -1) &&
807 (options.view === "activity" ||
808 ["user_message", "assistant_message", "proposed_plan"].includes(row.item.type))
809 : row.sourceItemId === options.itemId,
810 );
811 return Effect.succeed({
812 items: matching.slice(0, options.limit),
813 totalItems: input.rows.length,
814 hasMore: matching.length > options.limit,
815 } as never);
816 },
817 getProjectThreadRecords: () => Effect.succeed(projection),
818 } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
819 ServerSettings.layerTest(),
820 Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),
821 Layer.mock(ProjectService.ProjectService)({}),
822 Layer.mock(SecretRequests.SecretRequests)({}),
823 Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
824 Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
825 list: () => Effect.succeed([]),
826 }),
827 NodeCrypto.layer,
828 ),
829 ),
830 );
831}
832
833it("readThread defaults to 20 items and the 5 newest runs on the first page", async () => {
834 const rows = Array.from({ length: 30 }, (_, position) => assistantRow(position, "reply"));
835 await Effect.gen(function* () {
836 const service = yield* OrchestratorMcpService.OrchestratorMcpService;
837 const first = yield* service.readThread(makeScope(), { threadId: readThreadId });
838 expect(first.items).toHaveLength(20);
839 expect(first.hasMore).toBe(true);
840 expect(first.recentRuns.map((run) => run.ordinal)).toEqual([8, 7, 6, 5, 4]);
841
842 const next = yield* service.readThread(makeScope(), {
843 threadId: readThreadId,
844 afterPosition: first.nextPosition!,
845 });
846 expect(next.items.map((item) => item.position)).toEqual(
847 rows.slice(20).map((row) => row.position),
848 );
849 expect(next.hasMore).toBe(false);
850 expect(next.recentRuns).toEqual([]);
851 const withRuns = yield* service.readThread(makeScope(), {
852 threadId: readThreadId,
853 afterPosition: first.nextPosition!,
854 runLimit: 2,
855 });
856 expect(withRuns.recentRuns.map((run) => run.ordinal)).toEqual([8, 7]);
857 }).pipe(Effect.provide(readThreadLayer({ rows, runCount: 8 })), Effect.runPromise);
858});
859
860it("readThread previews tool output and long messages, and continues one item on request", async () => {
861 const toolOutput = "tool-output-line\n".repeat(200);
862 const longReply = "r".repeat(10_000);
863 const toolRow = {
864 ...assistantRow(0, ""),
865 sourceItemId: "item-tool",
866 item: {
867 id: "item-tool",
868 type: "dynamic_tool",
869 runId: "run-read-1",
870 status: "completed",
871 title: null,
872 toolName: "fetch",
873 input: { url: "https://example.com" },
874 output: toolOutput,
875 createdAt: now,
876 updatedAt: now,
877 },
878 };
879 const rows = [toolRow, assistantRow(1, longReply)];
880 await Effect.gen(function* () {
881 const service = yield* OrchestratorMcpService.OrchestratorMcpService;
882 const messages = yield* service.readThread(makeScope(), { threadId: readThreadId });
883 expect(messages.items.map((item) => item.itemId)).toEqual(["item-1"]);
884 const page = yield* service.readThread(makeScope(), {
885 threadId: readThreadId,
886 view: "activity",
887 });
888 const [tool, reply] = page.items;
889 expect(tool).toMatchObject({ textTruncated: true, nextTextOffset: 600 });
890 expect(tool!.text).toHaveLength(600);
891 expect(reply).toMatchObject({ textTruncated: true, nextTextOffset: 4_000 });
892 expect(reply!.text).toBe(longReply.slice(0, 4_000));
893
894 const rest = yield* service.readThread(makeScope(), {
895 threadId: readThreadId,
896 itemId: tool!.itemId,
897 textOffset: tool!.nextTextOffset,
898 maxCharsPerItem: 50_000,
899 });
900 expect(rest.items).toHaveLength(1);
901 expect(rest.items[0]).toMatchObject({ textTruncated: false });
902 expect(rest.items[0]).not.toHaveProperty("nextTextOffset");
903 expect(JSON.parse(tool!.text! + rest.items[0]!.text!)).toEqual({
904 toolName: "fetch",
905 input: { url: "https://example.com" },
906 output: toolOutput,
907 });
908
909 const explicit = yield* service.readThread(makeScope(), {
910 threadId: readThreadId,
911 view: "activity",
912 maxCharsPerItem: 1_000,
913 });
914 expect(explicit.items.map((item) => item.text?.length)).toEqual([1_000, 1_000]);
915 }).pipe(Effect.provide(readThreadLayer({ rows })), Effect.runPromise);
916});
917
918it("readThread omits item metadata that is empty or implied by the read thread", async () => {
919 const inherited = {
920 ...assistantRow(1, "from the parent"),
921 visibility: "inherited",
922 sourceThreadId: parentThreadId,
923 };
924 const rows = [
925 assistantRow(0, "reply"),
926 { ...inherited, item: { ...inherited.item, runId: null } },
927 ];
928 await Effect.gen(function* () {
929 const service = yield* OrchestratorMcpService.OrchestratorMcpService;
930 const page = yield* service.readThread(makeScope(), { threadId: readThreadId });
931 expect(page.items).toEqual([
932 {
933 position: 0,
934 itemId: "item-0",
935 runId: "run-read-1",
936 messageId: "message-0",
937 type: "assistant_message",
938 status: "completed",
939 text: "reply",
940 textTruncated: false,
941 updatedAt: "2026-08-04T12:00:00.000Z",
942 },
943 {
944 position: 1,
945 visibility: "inherited",
946 sourceThreadId: parentThreadId,
947 itemId: "item-1",
948 messageId: "message-1",
949 type: "assistant_message",
950 status: "completed",
951 text: "from the parent",
952 textTruncated: false,
953 updatedAt: "2026-08-04T12:00:00.000Z",
954 },
955 ]);
956 }).pipe(Effect.provide(readThreadLayer({ rows })), Effect.runPromise);
957});