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