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