Open History to see the last commit
1import {
2 EnvironmentId,
3 NodeId,
4 type OrchestratorMcpThreadReadResult,
5 type OrchestrationV2ThreadProjection,
6 type OrchestrationV2ThreadShell,
7 ProjectId,
8 ProviderDriverKind,
9 ProviderInstanceId,
10 RunId,
11 ScheduledTaskId,
12 SECRET_REQUEST_UNSAVED_NOTE,
13 ThreadId,
14 TurnItemId,
15} from "@t3tools/contracts";
16import * as DateTime from "effect/DateTime";
17import * as Effect from "effect/Effect";
18import * as Fiber from "effect/Fiber";
19import * as Layer from "effect/Layer";
20import * as Metric from "effect/Metric";
21import * as TestClock from "effect/testing/TestClock";
22import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
23import { expect, it } from "vite-plus/test";
24β
25import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";
26import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
27import * as ProjectService from "../project/ProjectService.ts";
28import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
29import * as ServerSettings from "../serverSettings.ts";
30import * as SecretRequests from "../secrets/SecretRequests.ts";
31import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts";
32import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
33import * as RemoteDelegation from "../peer/RemoteDelegation.ts";
34import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
35import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
36import type * as McpInvocationContext from "./McpInvocationContext.ts";
37import * as OrchestratorMcpService from "./OrchestratorMcpService.ts";
38import { liveThreadShell } from "./McpToolAccess.testkit.ts";
39β
40const layerOrchestratorService = OrchestratorMcpService.layer.pipe(
41 Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})),
42 Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
43);
44β
45const environmentId = EnvironmentId.make("environment-mcp-orchestrator-detail");
46const projectId = ProjectId.make("project-mcp-orchestrator-detail");
47const parentThreadId = ThreadId.make("thread-mcp-orchestrator-parent");
48const childThreadId = ThreadId.make("thread-mcp-orchestrator-child");
49const activeRunId = RunId.make("run-mcp-active");
50const cancelledRunId = RunId.make("run-mcp-cancelled");
51const childRunId = RunId.make("run-mcp-child");
52const taskId = NodeId.make("node-mcp-task-1");
53const now = DateTime.makeUnsafe("2026-08-04T12:00:00.000Z");
54const codexDriver = ProviderDriverKind.make("codex");
55β
56const customCodexInstanceId = ProviderInstanceId.make("codex-custom-workspace");
57const parentInstanceId = ProviderInstanceId.make("codex");
58β
59const makeScope = (): McpInvocationContext.McpInvocationScope => ({
60 environmentId,
61 requestNamespace: "provider-session-mcp-orchestrator-detail",
62 thread: {
63 threadId: parentThreadId,
64 providerSessionId: "provider-session-mcp-orchestrator-detail",
65 providerInstanceId: parentInstanceId,
66 },
67 client: undefined,
68 capabilities: new Set(["orchestration"]),
69 issuedAt: 1,
70});
71β
72function baseThread(input: {
73 readonly threadId: ThreadId;
74 readonly title: string;
75 readonly instanceId: ProviderInstanceId;
76 readonly model: string;
77}) {
78 return {
79 id: input.threadId,
80 projectId,
81 title: input.title,
82 createdBy: "user" as const,
83 creationSource: "mcp" as const,
84 modelSelection: {
85 instanceId: input.instanceId,
86 model: input.model,
87 },
88 runtimeMode: "full-access" as const,
89 interactionMode: "default" as const,
90 branch: null,
91 worktreePath: null,
92 lineage: {
93 parentThreadId: null,
94 relationshipToParent: null,
95 rootThreadId: input.threadId,
96 },
97 archivedAt: null,
98 deletedAt: null,
99 providerInstanceId: input.instanceId,
100 createdAt: now,
101 updatedAt: now,
102 };
103}
104β
105function makeRun(input: {
106 readonly id: RunId;
107 readonly ordinal: number;
108 readonly status: "running" | "waiting" | "cancelled" | "queued" | "completed" | "failed";
109 readonly instanceId?: ProviderInstanceId;
110}) {
111 return {
112 id: input.id,
113 ordinal: input.ordinal,
114 status: input.status,
115 modelSelection: {
116 instanceId: input.instanceId ?? parentInstanceId,
117 model: "gpt-5.4",
118 },
119 providerInstanceId: input.instanceId ?? parentInstanceId,
120 requestedAt: now,
121 startedAt: input.status === "cancelled" || input.status === "queued" ? null : now,
122 completedAt: input.status === "cancelled" || input.status === "completed" ? now : null,
123 };
124}
125β
126it("readThread preserves caller access errors and prefers activity-run status over a newer cancelled queued run", async () => {
127 let callerUnavailable = false;
128 let pendingBackgroundTasks: OrchestrationV2ThreadShell["pendingBackgroundTasks"] = [
129 {
130 taskId: "task-subagent",
131 kind: "subagent",
132 parentTaskId: "task-parent",
133 providerInstanceId: parentInstanceId,
134 childThreadId,
135 },
136 ];
137 const pullRequestLink = (number: number, state: "open" | "merged", watched: boolean) => ({
138 host: "github.com",
139 repository: "acme/web",
140 number,
141 url: `https://github.com/acme/web/pull/${number}`,
142 source: "agent",
143 linkedAt: `2026-08-04T11:0${number}:00.000Z`,
144 snapshot: { state },
145 stack: null,
146 ...(watched
147 ? {
148 watch: {
149 startedAt: "2026-08-04T11:30:00.000Z",
150 headSha: null,
151 failedChecks: [],
152 passed: false,
153 passedChecks: [],
154 remarksThrough: "2026-08-04T11:30:00.000Z",
155 remarkIds: [],
156 conflicting: false,
157 wakes: 0,
158 },
159 }
160 : {}),
161 });
162 const projection = {
163 thread: {
164 ...baseThread({
165 threadId: parentThreadId,
166 title: "Parent",
167 instanceId: parentInstanceId,
168 model: "gpt-5.4",
169 }),
170 pullRequests: [
171 pullRequestLink(1, "merged", false),
172 pullRequestLink(2, "open", true),
173 ...[3, 4, 5, 6, 7, 8].map((number) => pullRequestLink(number, "open", false)),
174 ],
175 },
176 runs: [
177 makeRun({ id: activeRunId, ordinal: 1, status: "running" }),
178 makeRun({ id: cancelledRunId, ordinal: 2, status: "cancelled" }),
179 ],
180 visibleTurnItems: [],
181 providerTurns: [],
182 runtimeRequests: [],
183 messages: [],
184 contextTransfers: [],
185 subagents: [],
186 updatedAt: now,
187 } as unknown as OrchestrationV2ThreadProjection;
188β
189 const layer = layerOrchestratorService.pipe(
190 Layer.provide(
191 Layer.mergeAll(
192 Layer.mock(ThreadManagementService.ThreadManagementService)({
193 getTimelinePage: () =>
194 Effect.succeed({ items: [], totalItems: 0, hasMore: false, hasEarlier: false }),
195 getThreadRecords: (threadId) =>
196 callerUnavailable
197 ? Effect.fail(
198 new Orchestrator.OrchestratorProjectionError({
199 threadId,
200 cause: "Caller unavailable",
201 }),
202 )
203 : threadId === parentThreadId
204 ? Effect.succeed(projection)
205 : Effect.die(`unexpected thread ${threadId}`),
206 getThreadShell: (threadId) =>
207 callerUnavailable
208 ? Effect.die("A failed caller read must not reach the target")
209 : Effect.succeed(
210 threadId === parentThreadId
211 ? ({
212 ...projection.thread,
213 pinnedAt: now,
214 blockedOnThreadWait: true,
215 pendingBackgroundTasks,
216 } as unknown as OrchestrationV2ThreadShell)
217 : null,
218 ),
219 getProjectThreadRecords: (input) =>
220 input.threadId === parentThreadId
221 ? Effect.succeed(projection)
222 : Effect.die(`unexpected thread ${input.threadId}`),
223 } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
224 ServerSettings.layerTest(),
225 Layer.mock(ProviderRegistry.ProviderRegistry)({
226 getProviders: Effect.succeed([]),
227 } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>),
228 Layer.mock(ProjectService.ProjectService)({}),
229 Layer.mock(SecretRequests.SecretRequests)({}),
230 Layer.mock(RemoteDelegation.RemoteDelegation)({}),
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("running");
246 expect(result.thread.latestRunId).toBe(cancelledRunId);
247 expect(result.thread.activeRunId).toBe(activeRunId);
248 expect(result.thread.pinned).toBe(true);
249 expect(result.thread.blockedOnThreadWait).toBe(true);
250 expect(result.thread.pendingBackgroundTasks).toEqual([
251 { taskId: "task-subagent", kind: "subagent", childThreadId },
252 ]);
253 // Every page read must not repeat each linked PR, and an open PR shows whether it is watched.
254 // A thread with many open PRs previews a few, watched first, then newest.
255 const listed = result.thread.pullRequests ?? [];
256 expect(listed.map((link) => link.number)).toEqual([2, 8, 7, 6, 5]);
257 expect(result.thread.openPullRequestCount).toBe(7);
258 expect(listed.find((link) => link.number === 2)).toMatchObject({
259 watching: true,
260 watchStartedAt: "2026-08-04T11:30:00.000Z",
261 });
262 const laterPage = yield* service.readThread(makeScope(), {
263 threadId: parentThreadId,
264 afterPosition: 0,
265 });
266 expect(laterPage.thread.pullRequests).toBeUndefined();
267 expect(laterPage.thread.pullRequestCount).toBe(8);
268β
269 Object.assign(projection, {
270 runs: [makeRun({ id: activeRunId, ordinal: 1, status: "completed" })],
271 });
272 const awaiting = yield* service.readThread(makeScope(), { threadId: parentThreadId });
273 expect(awaiting.thread.status).toBe("waiting");
274β
275 Object.assign(projection, {
276 runs: [makeRun({ id: activeRunId, ordinal: 1, status: "failed" })],
277 });
278 const failed = yield* service.readThread(makeScope(), { threadId: parentThreadId });
279 expect(failed.thread.status).toBe("failed");
280β
281 Object.assign(projection, {
282 runs: [makeRun({ id: activeRunId, ordinal: 1, status: "completed" })],
283 });
284 // An unawaited command (a dev server) does not hold the thread once its turn ends.
285 pendingBackgroundTasks = [{ taskId: "dev-server", kind: "command" }];
286 const released = yield* service.readThread(makeScope(), { threadId: parentThreadId });
287 expect(released.thread.status).toBe("completed");
288β
289 callerUnavailable = true;
290 const denied = yield* service
291 .readThread({ ...makeScope(), capabilities: new Set() }, { threadId: parentThreadId })
292 .pipe(Effect.flip);
293 expect(denied.code).toBe("capability_denied");
294 const missingCaller = yield* service
295 .readThread(makeScope(), { threadId: parentThreadId })
296 .pipe(Effect.flip);
297 expect(missingCaller.code).toBe("orchestration_error");
298 expect(missingCaller.message).toContain(`Unable to read thread ${parentThreadId}:`);
299 }).pipe(Effect.provide(layer), Effect.runPromise);
300});
301β
302it("readThread pages cut-off text without splitting an emoji across pages", async () => {
303 const text = "aπbc";
304 const itemId = TurnItemId.make("turn-item-mcp-reasoning");
305 const projection = {
306 thread: baseThread({
307 threadId: parentThreadId,
308 title: "Parent",
309 instanceId: parentInstanceId,
310 model: "gpt-5.4",
311 }),
312 runs: [makeRun({ id: activeRunId, ordinal: 1, status: "running" })],
313 visibleTurnItems: [],
314 providerTurns: [],
315 runtimeRequests: [],
316 messages: [],
317 contextTransfers: [],
318 subagents: [],
319 updatedAt: now,
320 } as unknown as OrchestrationV2ThreadProjection;
321 const row = {
322 position: 0,
323 visibility: "visible",
324 sourceThreadId: parentThreadId,
325 sourceItemId: itemId,
326 item: {
327 type: "reasoning",
328 runId: activeRunId,
329 status: "completed",
330 title: null,
331 text,
332 updatedAt: now,
333 },
334 };
335 const rows = [
336 row,
337 ...Array.from({ length: 11 }, (_, index) => ({
338 ...row,
339 position: index + 1,
340 sourceItemId: TurnItemId.make(`turn-item-mcp-${index}`),
341 item: { ...row.item, text: "x".repeat(600) },
342 })),
343 ];
344β
345 const layer = layerOrchestratorService.pipe(
346 Layer.provide(
347 Layer.mergeAll(
348 Layer.mock(ThreadManagementService.ThreadManagementService)({
349 getTimelinePage: (_threadId, options) => {
350 const remaining = rows.filter(
351 (candidate) =>
352 candidate.position > (options.afterPosition ?? -1) &&
353 (options.itemId === undefined || candidate.sourceItemId === options.itemId),
354 );
355 return Effect.succeed({
356 items: remaining.slice(
357 0,
358 options.limit,
359 ) as unknown as OrchestrationV2ThreadProjection["visibleTurnItems"],
360 totalItems: rows.length,
361 hasMore: remaining.length > options.limit,
362 hasEarlier: false,
363 });
364 },
365 getThreadRecords: () => Effect.succeed(projection),
366 getProjectThreadRecords: () => Effect.succeed(projection),
367 getThreadShell: () =>
368 Effect.succeed(projection.thread as unknown as OrchestrationV2ThreadShell),
369 } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
370 ServerSettings.layerTest(),
371 Layer.mock(ProviderRegistry.ProviderRegistry)({
372 getProviders: Effect.succeed([]),
373 } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>),
374 Layer.mock(ProjectService.ProjectService)({}),
375 Layer.mock(SecretRequests.SecretRequests)({}),
376 Layer.mock(RemoteDelegation.RemoteDelegation)({}),
377 Layer.mock(ScheduledTaskService.ScheduledTaskService)({
378 list: () => Effect.succeed({ tasks: [] }),
379 } satisfies Partial<ScheduledTaskService.ScheduledTaskService["Service"]>),
380 Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
381 list: () => Effect.succeed([]),
382 } satisfies Partial<ProviderAdapterRegistry.ProviderAdapterRegistryV2["Service"]>),
383 NodeCrypto.layer,
384 ),
385 ),
386 );
387β
388 await Effect.gen(function* () {
389 const service = yield* OrchestratorMcpService.OrchestratorMcpService;
390 for (const [maxCharsPerItem, expected] of [
391 [2, ["a", "π", "bc"]],
392 [1, ["a", "π", "b", "c"]],
393 ] as const) {
394 let textOffset = 0;
395 for (const [index, text] of expected.entries()) {
396 const result = yield* service.readThread(makeScope(), {
397 threadId: parentThreadId,
398 view: "activity",
399 itemId,
400 textOffset,
401 maxCharsPerItem,
402 });
403 textOffset += text.length;
404 expect(result.items[0]).toMatchObject({
405 text,
406 textTruncated: index < expected.length - 1,
407 nextTextOffset: index < expected.length - 1 ? textOffset : null,
408 });
409 }
410 }
411 const first = yield* service.readThread(makeScope(), {
412 threadId: parentThreadId,
413 view: "activity",
414 });
415 expect(first.items[1]).toMatchObject({
416 text: "x".repeat(500),
417 textTruncated: true,
418 nextTextOffset: 500,
419 });
420 expect(first.items).toHaveLength(10);
421 expect(first).toMatchObject({ nextPosition: 9, hasMore: true });
422 }).pipe(Effect.provide(layer), Effect.runPromise);
423});
424β
425it("readThread returns the newest items that fit the response budget", async () => {
426 const projection = {
427 thread: baseThread({
428 threadId: parentThreadId,
429 title: "Parent",
430 instanceId: parentInstanceId,
431 model: "gpt-5.4",
432 }),
433 runs: [makeRun({ id: activeRunId, ordinal: 1, status: "running" })],
434 visibleTurnItems: [],
435 providerTurns: [],
436 runtimeRequests: [],
437 messages: [],
438 contextTransfers: [],
439 subagents: [],
440 updatedAt: now,
441 } as unknown as OrchestrationV2ThreadProjection;
442 // A long thread's newest 100 activity items, the read agents make most.
443 const rows = Array.from({ length: 100 }, (_, position) => ({
444 position,
445 visibility: "local",
446 sourceThreadId: parentThreadId,
447 sourceItemId: TurnItemId.make(`turn-item-mcp-long-${position}`),
448 item: {
449 type: "reasoning",
450 runId: activeRunId,
451 status: "completed",
452 title: null,
453 text: "x".repeat(1_500),
454 updatedAt: now,
455 },
456 }));
457 const pageOptions: Array<unknown> = [];
458β
459 const layer = layerOrchestratorService.pipe(
460 Layer.provide(
461 Layer.mergeAll(
462 Layer.mock(ThreadManagementService.ThreadManagementService)({
463 getTimelinePage: (_threadId, options) => {
464 pageOptions.push(options);
465 return Effect.succeed({
466 items: rows as unknown as OrchestrationV2ThreadProjection["visibleTurnItems"],
467 totalItems: 3_000,
468 hasMore: false,
469 hasEarlier: true,
470 });
471 },
472 getThreadRecords: () => Effect.succeed(projection),
473 getProjectThreadRecords: () => Effect.succeed(projection),
474 getThreadShell: () =>
475 Effect.succeed(projection.thread as unknown as OrchestrationV2ThreadShell),
476 } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
477 ServerSettings.layerTest(),
478 Layer.mock(ProviderRegistry.ProviderRegistry)({
479 getProviders: Effect.succeed([]),
480 } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>),
481 Layer.mock(ProjectService.ProjectService)({}),
482 Layer.mock(SecretRequests.SecretRequests)({}),
483 Layer.mock(RemoteDelegation.RemoteDelegation)({}),
484 Layer.mock(ScheduledTaskService.ScheduledTaskService)({
485 list: () => Effect.succeed({ tasks: [] }),
486 } satisfies Partial<ScheduledTaskService.ScheduledTaskService["Service"]>),
487 Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
488 list: () => Effect.succeed([]),
489 } satisfies Partial<ProviderAdapterRegistry.ProviderAdapterRegistryV2["Service"]>),
490 NodeCrypto.layer,
491 ),
492 ),
493 );
494β
495 await Effect.gen(function* () {
496 const service = yield* OrchestratorMcpService.OrchestratorMcpService;
497 const read = {
498 threadId: parentThreadId,
499 view: "activity" as const,
500 limit: 100,
501 maxCharsPerItem: 1_500,
502 };
503 const result = yield* service.readThread(makeScope(), read);
504 // Linked environments and the CLI read as clients without a cursor and follow only hasMore.
505 const first = yield* service.readThread({ ...makeScope(), thread: undefined }, read);
506 const fromStart = yield* service.readThread(makeScope(), { ...read, afterPosition: -1 });
507β
508 expect(pageOptions).toEqual([
509 { beforePosition: Number.POSITIVE_INFINITY, limit: 100, view: "activity" },
510 { limit: 100, view: "activity" },
511 { afterPosition: -1, limit: 100, view: "activity" },
512 ]);
513 // Claude Code saves results over ~50k chars of this JSON to a file instead of showing them.
514 expect(JSON.stringify(result).length).toBeLessThan(31_000);
515 expect(result.items.length).toBeLessThan(100);
516 expect(result.items.at(-1)?.position).toBe(99);
517 expect(result.earlierPosition).toBe(result.items[0]?.position);
518 expect(result.hasMore).toBe(false);
519 expect(first.items[0]?.position).toBe(0);
520 expect(first.hasMore).toBe(true);
521 expect(first.nextPosition).toBe(first.items.at(-1)?.position);
522 expect(fromStart.items[0]?.position).toBe(0);
523 }).pipe(Effect.provide(layer), Effect.runPromise);
524});
525β
526it("readThread keeps an activity page within an MCP client's output limit and pages the rest", async () => {
527 const projection = {
528 thread: baseThread({
529 threadId: parentThreadId,
530 title: "Parent",
531 instanceId: parentInstanceId,
532 model: "gpt-5.4",
533 }),
534 runs: [makeRun({ id: activeRunId, ordinal: 1, status: "running" })],
535 visibleTurnItems: [],
536 providerTurns: [],
537 runtimeRequests: [],
538 messages: [],
539 contextTransfers: [],
540 subagents: [],
541 updatedAt: now,
542 } as unknown as OrchestrationV2ThreadProjection;
543 const rows = Array.from({ length: 60 }, (_, position) => ({
544 position,
545 visibility: "visible",
546 sourceThreadId: parentThreadId,
547 sourceItemId: TurnItemId.make(`turn-item-mcp-reasoning-${position}`),
548 item: {
549 type: "reasoning",
550 runId: activeRunId,
551 status: "completed",
552 // Command titles can carry a whole command.
553 title: position === 1 ? "ζ¨".repeat(60_000) : null,
554 text: position === 0 ? "πa".repeat(30_000) : `${position} `.padEnd(3_000, "x"),
555 updatedAt: now,
556 },
557 }));
558β
559 const layer = layerOrchestratorService.pipe(
560 Layer.provide(
561 Layer.mergeAll(
562 Layer.mock(ThreadManagementService.ThreadManagementService)({
563 getTimelinePage: (_threadId, options) => {
564 const after =
565 options.itemId === undefined
566 ? rows.filter((row) => row.position > (options.afterPosition ?? -1))
567 : rows.filter((row) => row.sourceItemId === options.itemId);
568 return Effect.succeed({
569 items: after.slice(
570 0,
571 options.limit,
572 ) as unknown as OrchestrationV2ThreadProjection["visibleTurnItems"],
573 totalItems: rows.length,
574 hasMore: after.length > options.limit,
575 hasEarlier: false,
576 });
577 },
578 getThreadRecords: () => Effect.succeed(projection),
579 getProjectThreadRecords: () => Effect.succeed(projection),
580 getThreadShell: () =>
581 Effect.succeed(projection.thread as unknown as OrchestrationV2ThreadShell),
582 } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
583 ServerSettings.layerTest(),
584 Layer.mock(ProviderRegistry.ProviderRegistry)({
585 getProviders: Effect.succeed([]),
586 } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>),
587 Layer.mock(ProjectService.ProjectService)({}),
588 Layer.mock(SecretRequests.SecretRequests)({}),
589 Layer.mock(RemoteDelegation.RemoteDelegation)({}),
590 Layer.mock(ScheduledTaskService.ScheduledTaskService)({
591 list: () => Effect.succeed({ tasks: [] }),
592 } satisfies Partial<ScheduledTaskService.ScheduledTaskService["Service"]>),
593 Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
594 list: () => Effect.succeed([]),
595 } satisfies Partial<ProviderAdapterRegistry.ProviderAdapterRegistryV2["Service"]>),
596 NodeCrypto.layer,
597 ),
598 ),
599 );
600β
601 await Effect.gen(function* () {
602 const service = yield* OrchestratorMcpService.OrchestratorMcpService;
603 const positions: Array<number> = [];
604 let afterPosition: number | undefined;
605 for (let page = 0; page < rows.length; page++) {
606 const result = yield* service.readThread(makeScope(), {
607 threadId: parentThreadId,
608 view: "activity",
609 limit: 100,
610 maxCharsPerItem: 1_500,
611 afterPosition: afterPosition ?? -1,
612 });
613 // Claude Code rejects MCP results over 25k tokens; CJK text is about a token per char.
614 expect(Buffer.byteLength(JSON.stringify(result))).toBeLessThanOrEqual(50_000);
615 if (page === 0) expect(result.hasMore).toBe(true);
616 positions.push(...result.items.map((item) => item.position));
617 if (!result.hasMore) break;
618 afterPosition = result.nextPosition ?? undefined;
619 }
620 expect(positions).toEqual(rows.map((row) => row.position));
621β
622 const longText = rows[0]!.item.text;
623 const pages: Array<string> = [];
624 let textOffset: number | null = 0;
625 while (textOffset !== null) {
626 const result: OrchestratorMcpThreadReadResult = yield* service.readThread(makeScope(), {
627 threadId: parentThreadId,
628 view: "activity",
629 itemId: rows[0]!.sourceItemId,
630 textOffset,
631 maxCharsPerItem: 50_000,
632 });
633 expect(Buffer.byteLength(JSON.stringify(result))).toBeLessThanOrEqual(50_000);
634 const [item] = result.items;
635 expect(item?.text?.isWellFormed()).toBe(true);
636 pages.push(item!.text!);
637 textOffset = item!.nextTextOffset ?? null;
638 }
639 expect(pages.length).toBeGreaterThan(1);
640 expect(pages.join("")).toBe(longText);
641β
642 (projection.thread as { title: string }).title = "ζ¨".repeat(30_000);
643 const underHugeTitle = yield* service.readThread(makeScope(), {
644 threadId: parentThreadId,
645 view: "activity",
646 itemId: rows[0]!.sourceItemId,
647 maxCharsPerItem: 50_000,
648 });
649 expect(underHugeTitle.items[0]?.text?.length).toBeGreaterThan(1_000);
650 }).pipe(Effect.provide(layer), Effect.runPromise);
651});
652β
653it("taskStatus returns task.providerInstanceId rather than the driver kind", async () => {
654 const parentProjection = {
655 thread: baseThread({
656 threadId: parentThreadId,
657 title: "Parent",
658 instanceId: parentInstanceId,
659 model: "gpt-5.4",
660 }),
661 runs: [makeRun({ id: activeRunId, ordinal: 1, status: "running" })],
662 visibleTurnItems: [],
663 providerTurns: [],
664 runtimeRequests: [],
665 messages: [],
666 contextTransfers: [],
667 subagents: [
668 {
669 id: taskId,
670 threadId: parentThreadId,
671 runId: activeRunId,
672 parentNodeId: NodeId.make("node-parent"),
673 origin: "app_owned",
674 createdBy: "agent",
675 driver: codexDriver,
676 providerInstanceId: customCodexInstanceId,
677 providerThreadId: null,
678 childThreadId,
679 nativeTaskRef: null,
680 prompt: "Inspect the custom instance.",
681 title: null,
682 model: "gpt-5.4",
683 status: "running",
684 result: null,
685 startedAt: now,
686 completedAt: null,
687 updatedAt: now,
688 },
689 ],
690 updatedAt: now,
691 } as unknown as OrchestrationV2ThreadProjection;
692β
693 const childProjection = {
694 thread: {
695 ...baseThread({
696 threadId: childThreadId,
697 title: "Child",
698 instanceId: customCodexInstanceId,
699 model: "gpt-5.4",
700 }),
701 lineage: {
702 parentThreadId,
703 relationshipToParent: "subagent",
704 rootThreadId: parentThreadId,
705 },
706 createdBy: "agent",
707 },
708 runs: [
709 makeRun({
710 id: childRunId,
711 ordinal: 1,
712 status: "running",
713 instanceId: customCodexInstanceId,
714 }),
715 ],
716 visibleTurnItems: [],
717 providerTurns: [],
718 runtimeRequests: [],
719 messages: [],
720 contextTransfers: [
721 {
722 type: "subagent_spawn",
723 sourceThreadId: parentThreadId,
724 targetThreadId: childThreadId,
725 targetRunId: childRunId,
726 },
727 ],
728 subagents: [],
729 providerThreads: [],
730 updatedAt: now,
731 } as unknown as OrchestrationV2ThreadProjection;
732β
733 const layer = layerOrchestratorService.pipe(
734 Layer.provide(
735 Layer.mergeAll(
736 Layer.mock(ThreadManagementService.ThreadManagementService)({
737 getTimelinePage: () =>
738 Effect.succeed({ items: [], totalItems: 0, hasMore: false, hasEarlier: false }),
739 getThreadRecords: (threadId) => {
740 if (threadId === parentThreadId) return Effect.succeed(parentProjection);
741 if (threadId === childThreadId) return Effect.succeed(childProjection);
742 return Effect.die(`unexpected thread ${threadId}`);
743 },
744 } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
745 ServerSettings.layerTest(),
746 Layer.mock(ProviderRegistry.ProviderRegistry)({
747 getProviders: Effect.succeed([]),
748 } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>),
749 Layer.mock(ProjectService.ProjectService)({}),
750 Layer.mock(SecretRequests.SecretRequests)({}),
751 Layer.mock(RemoteDelegation.RemoteDelegation)({}),
752 Layer.mock(ScheduledTaskService.ScheduledTaskService)({
753 list: () => Effect.succeed({ tasks: [] }),
754 } satisfies Partial<ScheduledTaskService.ScheduledTaskService["Service"]>),
755 Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
756 list: () => Effect.succeed([]),
757 } satisfies Partial<ProviderAdapterRegistry.ProviderAdapterRegistryV2["Service"]>),
758 NodeCrypto.layer,
759 ),
760 ),
761 );
762β
763 await Effect.gen(function* () {
764 const service = yield* OrchestratorMcpService.OrchestratorMcpService;
765 const result = yield* service.taskStatus(makeScope(), taskId);
766 expect(result.providerInstanceId).toBe(customCodexInstanceId);
767 expect(result.providerInstanceId).not.toBe(ProviderInstanceId.make(String(codexDriver)));
768 expect(result.status).toBe("running");
769 expect(result.taskId).toBe(taskId);
770 expect(result.childThreadId).toBe(childThreadId);
771 }).pipe(Effect.provide(layer), Effect.runPromise);
772});
773β
774it("readThread and sendToThread reach threads in other projects", async () => {
775 let parentShell: OrchestrationV2ThreadShell | null = null;
776 let parentRuns: ReadonlyArray<unknown> = [
777 makeRun({ id: RunId.make("run-parent-live"), ordinal: 1, status: "running" }),
778 ];
779 const foreignProjectId = ProjectId.make("project-mcp-orchestrator-foreign");
780 const foreignThreadId = ThreadId.make("thread-mcp-orchestrator-foreign");
781 const parentProjection = {
782 thread: baseThread({
783 threadId: parentThreadId,
784 title: "Parent",
785 instanceId: parentInstanceId,
786 model: "gpt-5.4",
787 }),
788 get runs() {
789 return parentRuns;
790 },
791 visibleTurnItems: [],
792 providerTurns: [],
793 runtimeRequests: [],
794 messages: [],
795 contextTransfers: [],
796 subagents: [],
797 updatedAt: now,
798 } as unknown as OrchestrationV2ThreadProjection;
799 const foreignProjection = (threadId: ThreadId) =>
800 ({
801 thread: {
802 ...baseThread({
803 threadId,
804 title: "Foreign",
805 instanceId: parentInstanceId,
806 model: "gpt-5.4",
807 }),
808 projectId: foreignProjectId,
809 },
810 runs: [],
811 visibleTurnItems: [
812 {
813 position: 0,
814 visibility: "inherited",
815 sourceThreadId: threadId,
816 sourceItemId: "item-1",
817 item: {
818 id: "item-1",
819 type: "assistant_message",
820 messageId: "assistant-1",
821 status: "completed",
822 title: null,
823 text: "Foreign thread said hello",
824 createdAt: now,
825 updatedAt: now,
826 },
827 },
828 ],
829 providerTurns: [],
830 runtimeRequests: [],
831 messages: [],
832 contextTransfers: [],
833 subagents: [],
834 updatedAt: now,
835 }) as unknown as OrchestrationV2ThreadProjection;
836β
837 const layer = layerOrchestratorService.pipe(
838 Layer.provide(
839 Layer.mergeAll(
840 Layer.mock(ThreadManagementService.ThreadManagementService)({
841 getThreadRecords: (threadId) => {
842 if (threadId === parentThreadId) return Effect.succeed(parentProjection);
843 if (threadId === foreignThreadId) return Effect.succeed(foreignProjection(threadId));
844 return Effect.die(`unexpected thread ${threadId}`);
845 },
846 getThreadShell: (threadId) =>
847 Effect.succeed(
848 threadId === foreignThreadId
849 ? (foreignProjection(threadId).thread as unknown as OrchestrationV2ThreadShell)
850 : threadId === parentThreadId
851 ? parentShell
852 : null,
853 ),
854 getTimelinePage: (threadId) =>
855 Effect.succeed({
856 items: foreignProjection(threadId).visibleTurnItems,
857 totalItems: 1,
858 hasMore: false,
859 hasEarlier: false,
860 }),
861 getProjectThreadRecords: (input) =>
862 input.threadId === foreignThreadId && input.projectId === foreignProjectId
863 ? Effect.succeed(foreignProjection(input.threadId))
864 : Effect.fail(
865 new ThreadManagementService.ThreadManagementThreadNotFoundError({
866 projectId: input.projectId,
867 threadId: input.threadId,
868 }),
869 ),
870 sendToThread: () =>
871 Effect.succeed({
872 run: { id: "run-foreign", status: "queued" },
873 delivery: "started",
874 } as unknown as ThreadManagementService.ThreadManagementSendResult),
875 } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
876 ServerSettings.layerTest(),
877 Layer.mock(ProviderRegistry.ProviderRegistry)({
878 getProviders: Effect.succeed([]),
879 } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>),
880 Layer.mock(ProjectService.ProjectService)({}),
881 Layer.mock(SecretRequests.SecretRequests)({}),
882 Layer.mock(RemoteDelegation.RemoteDelegation)({}),
883 Layer.mock(ScheduledTaskService.ScheduledTaskService)({
884 list: () =>
885 Effect.succeed({
886 tasks: [
887 {
888 id: "task-foreign",
889 projectId: foreignProjectId,
890 runtimeMode: "approval-required",
891 interactionMode: "default",
892 } as never,
893 ],
894 }),
895 } satisfies Partial<ScheduledTaskService.ScheduledTaskService["Service"]>),
896 Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
897 list: () => Effect.succeed([]),
898 } satisfies Partial<ProviderAdapterRegistry.ProviderAdapterRegistryV2["Service"]>),
899 NodeCrypto.layer,
900 ),
901 ),
902 );
903β
904 await Effect.gen(function* () {
905 const service = yield* OrchestratorMcpService.OrchestratorMcpService;
906 const foreign = yield* service.readThread(makeScope(), { threadId: foreignThreadId });
907 expect(foreign.thread.threadId).toBe(foreignThreadId);
908 expect(foreign.thread.projectId).toBe(foreignProjectId);
909 expect(foreign.items.map((item) => item.text)).toEqual(["Foreign thread said hello"]);
910β
911 const sent = yield* service.sendToThread(makeScope(), {
912 threadId: foreignThreadId,
913 message: "hi",
914 });
915 expect(sent.threadId).toBe(foreignThreadId);
916β
917 parentRuns = [];
918 yield* service.readThread(makeScope(), { threadId: foreignThreadId });
919 const stale = yield* service
920 .sendToThread(makeScope(), { threadId: foreignThreadId, message: "hi again" })
921 .pipe(Effect.flip);
922 expect(stale.code).toBe("parent_not_active");
923 const staleInterrupt = yield* service
924 .interruptThread(makeScope(), { threadId: foreignThreadId })
925 .pipe(Effect.flip);
926 expect(staleInterrupt.code).toBe("parent_not_active");
927β
928 const staleSchedule = yield* service
929 .scheduleTask(makeScope(), {
930 projectId: foreignProjectId,
931 prompt: "check in later",
932 schedule: { type: "interval", everyMs: 3_600_000 },
933 })
934 .pipe(Effect.flip);
935 expect(staleSchedule.code).toBe("parent_not_active");
936 const staleUpdate = yield* service
937 .updateScheduledTask(makeScope(), {
938 scheduledTaskId: ScheduledTaskId.make("task-foreign"),
939 enabled: false,
940 })
941 .pipe(Effect.flip);
942 expect(staleUpdate.code).toBe("parent_not_active");
943 const staleDelete = yield* service
944 .deleteScheduledTask(makeScope(), { scheduledTaskId: ScheduledTaskId.make("task-foreign") })
945 .pipe(Effect.flip);
946 expect(staleDelete.code).toBe("parent_not_active");
947β
948 const backgroundTasks = [
949 {
950 taskId: "background-subagent",
951 kind: "subagent" as const,
952 providerInstanceId: parentInstanceId,
953 },
954 ];
955 parentShell = {
956 ...liveThreadShell(parentThreadId, { activeRunId: null }),
957 pendingBackgroundTasks: backgroundTasks,
958 };
959 const backgroundSent = yield* service.sendToThread(makeScope(), {
960 threadId: foreignThreadId,
961 message: "background",
962 });
963 expect(backgroundSent.threadId).toBe(foreignThreadId);
964 const delegate = yield* service
965 .delegateTask(makeScope(), { task: "requires a run" })
966 .pipe(Effect.flip);
967 expect(delegate.code).toBe("parent_not_active");
968 const create = yield* service
969 .createThreads(makeScope(), { threads: [{ prompt: "requires a run" }] })
970 .pipe(Effect.flip);
971 expect(create.code).toBe("parent_not_active");
972 const secret = yield* service
973 .requestSecret(makeScope(), { label: "Secret", reason: "requires a run" })
974 .pipe(Effect.flip);
975 expect(secret.code).toBe("parent_not_active");
976β
977 parentShell = { ...parentShell, providerInstanceId: customCodexInstanceId };
978 const switchedScope = {
979 ...makeScope(),
980 thread: { ...makeScope().thread!, providerInstanceId: customCodexInstanceId },
981 };
982 const switched = yield* service
983 .sendToThread(switchedScope, { threadId: foreignThreadId, message: "wrong owner" })
984 .pipe(Effect.flip);
985 expect(switched.code).toBe("parent_not_active");
986 const mismatched = yield* service
987 .sendToThread(makeScope(), { threadId: foreignThreadId, message: "stale provider" })
988 .pipe(Effect.flip);
989 expect(mismatched.code).toBe("parent_not_active");
990β
991 parentShell = liveThreadShell(parentThreadId);
992 const restarted = yield* service.sendToThread(makeScope(), {
993 threadId: foreignThreadId,
994 message: "new run",
995 });
996 expect(restarted.threadId).toBe(foreignThreadId);
997β
998 parentShell = {
999 ...parentShell,
1000 activeRunId: null,
1001 pendingBackgroundTasks: backgroundTasks,
1002 archivedAt: now,
1003 };
1004 const archived = yield* service
1005 .sendToThread(makeScope(), { threadId: foreignThreadId, message: "archived" })
1006 .pipe(Effect.flip);
1007 expect(archived.code).toBe("parent_not_active");
1008β
1009 parentShell = { ...parentShell, archivedAt: null, pendingBackgroundTasks: [] };
1010 const stopped = yield* service
1011 .sendToThread(makeScope(), { threadId: foreignThreadId, message: "after stop" })
1012 .pipe(Effect.flip);
1013 expect(stopped.code).toBe("parent_not_active");
1014 }).pipe(Effect.provide(layer), Effect.runPromise);
1015});
1016β
1017it("requestSecret saves a pasted value to a file without opening a card", async () => {
1018 const projection = {
1019 thread: baseThread({
1020 threadId: parentThreadId,
1021 title: "Parent",
1022 instanceId: parentInstanceId,
1023 model: "gpt-5.4",
1024 }),
1025 runs: [{ ...makeRun({ id: activeRunId, ordinal: 1, status: "running" }), rootNodeId: taskId }],
1026 visibleTurnItems: [],
1027 providerTurns: [],
1028 runtimeRequests: [],
1029 messages: [],
1030 contextTransfers: [],
1031 subagents: [],
1032 updatedAt: now,
1033 } as unknown as OrchestrationV2ThreadProjection;
1034 const dispatched: Array<unknown> = [];
1035 const saved: Array<{
1036 readonly requestNamespace: string;
1037 readonly requestKey: string;
1038 readonly value: string;
1039 }> = [];
1040 const file = "/home/user/.t3/userdata/secrets/files/0123456789abcdef0123456789abcdef";
1041β
1042 const layer = layerOrchestratorService.pipe(
1043 Layer.provide(
1044 Layer.mergeAll(
1045 Layer.mock(ThreadManagementService.ThreadManagementService)({
1046 getThreadRecords: (threadId) =>
1047 threadId === parentThreadId
1048 ? Effect.succeed(projection)
1049 : Effect.die(`unexpected thread ${threadId}`),
1050 getThreadShell: (threadId) =>
1051 Effect.succeed(
1052 threadId === parentThreadId
1053 ? (projection.thread as unknown as OrchestrationV2ThreadShell)
1054 : null,
1055 ),
1056 dispatch: (command) => Effect.sync(() => void dispatched.push(command) as never),
1057 } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
1058 ServerSettings.layerTest(),
1059 Layer.mock(ProviderRegistry.ProviderRegistry)({
1060 getProviders: Effect.succeed([]),
1061 } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>),
1062 Layer.mock(ProjectService.ProjectService)({}),
1063 Layer.mock(SecretRequests.SecretRequests)({
1064 savePasted: (input) =>
1065 Effect.sync(() => {
1066 saved.push({
1067 requestNamespace: input.requestNamespace,
1068 requestKey: input.requestKey,
1069 value: input.value,
1070 });
1071 return file;
1072 }),
1073 }),
1074 Layer.mock(RemoteDelegation.RemoteDelegation)({}),
1075 Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
1076 Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({}),
1077 NodeCrypto.layer,
1078 ),
1079 ),
1080 );
1081 const counted = Metric.snapshot.pipe(
1082 Effect.map((snapshots) => {
1083 const found = snapshots.find(
1084 (snapshot) =>
1085 snapshot.id === "t3_secret_requests_total" &&
1086 snapshot.attributes?.status === "saved_pasted",
1087 );
1088 return found?.type === "Counter" ? Number(found.state.count) : 0;
1089 }),
1090 );
1091β
1092 await Effect.gen(function* () {
1093 const service = yield* OrchestratorMcpService.OrchestratorMcpService;
1094 const before = yield* counted;
1095 const result = yield* service.requestSecret(makeScope(), {
1096 label: "Pixel PIN",
1097 reason: "Unlocks the test phone.",
1098 value: "482916",
1099 clientRequestId: "pin-1",
1100 });
1101 expect(result).toEqual({ status: "saved", file });
1102 expect(JSON.stringify(result)).not.toContain("482916");
1103 expect(saved).toEqual([
1104 {
1105 requestNamespace: "provider-session-mcp-orchestrator-detail",
1106 requestKey: "pin-1",
1107 value: "482916",
1108 },
1109 ]);
1110 expect(dispatched).toEqual([]);
1111 expect((yield* counted) - before).toBe(1);
1112β
1113 const asRef = yield* service
1114 .requestSecret(makeScope(), {
1115 label: "Pixel PIN",
1116 reason: "Unlocks the test phone.",
1117 value: "482916",
1118 delivery: "secretRef",
1119 })
1120 .pipe(Effect.flip);
1121 expect(asRef.code).toBe("invalid_request");
1122 expect(asRef.message).not.toContain("482916");
1123 expect(saved).toHaveLength(1);
1124 expect(dispatched).toEqual([]);
1125 }).pipe(Effect.provide(layer), Effect.runPromise);
1126});
1127β
1128it("requestSecret returns the unsaved note for a declined, cancelled or timed-out card", async () => {
1129 const outcomes = ["declined", "cancelled", "pending"] as const;
1130 const results = await Effect.forEach(outcomes, (outcome) => {
1131 const dispatched: Array<{ readonly type: string; readonly turnItemId?: string }> = [];
1132 const projection = () => {
1133 const card = dispatched.find((command) => command.type === "secret_request.record");
1134 return {
1135 thread: baseThread({
1136 threadId: parentThreadId,
1137 title: "Parent",
1138 instanceId: parentInstanceId,
1139 model: "gpt-5.4",
1140 }),
1141 runs: [
1142 { ...makeRun({ id: activeRunId, ordinal: 1, status: "running" }), rootNodeId: taskId },
1143 ],
1144 visibleTurnItems: [],
1145 turnItems:
1146 card === undefined
1147 ? []
1148 : [{ type: "secret_request", id: card.turnItemId, secretStatus: outcome }],
1149 providerTurns: [],
1150 runtimeRequests: [],
1151 messages: [],
1152 contextTransfers: [],
1153 subagents: [],
1154 updatedAt: now,
1155 } as unknown as OrchestrationV2ThreadProjection;
1156 };
1157 const layer = layerOrchestratorService.pipe(
1158 Layer.provide(
1159 Layer.mergeAll(
1160 Layer.mock(ThreadManagementService.ThreadManagementService)({
1161 getThreadRecords: () => Effect.sync(projection),
1162 getThreadShell: () =>
1163 Effect.sync(() => projection().thread as unknown as OrchestrationV2ThreadShell),
1164 dispatch: (command) => Effect.sync(() => void dispatched.push(command) as never),
1165 } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
1166 ServerSettings.layerTest(),
1167 Layer.mock(ProviderRegistry.ProviderRegistry)({
1168 getProviders: Effect.succeed([]),
1169 } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>),
1170 Layer.mock(ProjectService.ProjectService)({}),
1171 Layer.mock(SecretRequests.SecretRequests)({}),
1172 Layer.mock(RemoteDelegation.RemoteDelegation)({}),
1173 Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
1174 Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({}),
1175 NodeCrypto.layer,
1176 ),
1177 ),
1178 );
1179 return Effect.gen(function* () {
1180 const service = yield* OrchestratorMcpService.OrchestratorMcpService;
1181 const request = yield* service
1182 .requestSecret(makeScope(), {
1183 label: "Staging password",
1184 reason: "Signs in the QA account.",
1185 delivery: "file",
1186 timeoutMs: 1_000,
1187 })
1188 .pipe(Effect.forkChild({ startImmediately: true }));
1189 yield* TestClock.adjust("2 seconds");
1190 return yield* Fiber.join(request);
1191 }).pipe(Effect.provide(Layer.merge(layer, TestClock.layer())));
1192 }).pipe(Effect.runPromise);
1193β
1194 expect(results).toEqual([
1195 { status: "declined", note: SECRET_REQUEST_UNSAVED_NOTE.declined },
1196 { status: "cancelled", note: SECRET_REQUEST_UNSAVED_NOTE.cancelled },
1197 { status: "timed_out", note: SECRET_REQUEST_UNSAVED_NOTE.timed_out },
1198 ]);
1199});