Open History to see the last commit
1import {
2 EnvironmentId,
3 NodeId,
4 type OrchestrationV2ThreadProjection,
5 type OrchestrationV2ThreadShell,
6 ProjectId,
7 ProviderDriverKind,
8 ProviderInstanceId,
9 RunId,
10 ScheduledTaskId,
11 SECRET_REQUEST_UNSAVED_NOTE,
12 ThreadId,
13 TurnItemId,
14} from "@t3tools/contracts";
15import * as DateTime from "effect/DateTime";
16import * as Effect from "effect/Effect";
17import * as Fiber from "effect/Fiber";
18import * as Layer from "effect/Layer";
19import * as Metric from "effect/Metric";
20import * as TestClock from "effect/testing/TestClock";
21import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
22import { expect, it } from "vite-plus/test";
23โ
24import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";
25import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
26import * as ProjectService from "../project/ProjectService.ts";
27import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
28import * as ServerSettings from "../serverSettings.ts";
29import * as SecretRequests from "../secrets/SecretRequests.ts";
30import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts";
31import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
32import * as RemoteDelegation from "../peer/RemoteDelegation.ts";
33import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
34import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
35import type * as McpInvocationContext from "./McpInvocationContext.ts";
36import * as OrchestratorMcpService from "./OrchestratorMcpService.ts";
37import { liveThreadShell } from "./McpToolAccess.testkit.ts";
38โ
39const layerOrchestratorService = OrchestratorMcpService.layer.pipe(
40 Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})),
41 Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
42);
43โ
44const environmentId = EnvironmentId.make("environment-mcp-orchestrator-detail");
45const projectId = ProjectId.make("project-mcp-orchestrator-detail");
46const parentThreadId = ThreadId.make("thread-mcp-orchestrator-parent");
47const childThreadId = ThreadId.make("thread-mcp-orchestrator-child");
48const activeRunId = RunId.make("run-mcp-active");
49const cancelledRunId = RunId.make("run-mcp-cancelled");
50const childRunId = RunId.make("run-mcp-child");
51const taskId = NodeId.make("node-mcp-task-1");
52const now = DateTime.makeUnsafe("2026-08-04T12:00:00.000Z");
53const codexDriver = ProviderDriverKind.make("codex");
54โ
55const customCodexInstanceId = ProviderInstanceId.make("codex-custom-workspace");
56const parentInstanceId = ProviderInstanceId.make("codex");
57โ
58const makeScope = (): McpInvocationContext.McpInvocationScope => ({
59 environmentId,
60 requestNamespace: "provider-session-mcp-orchestrator-detail",
61 thread: {
62 threadId: parentThreadId,
63 providerSessionId: "provider-session-mcp-orchestrator-detail",
64 providerInstanceId: parentInstanceId,
65 },
66 client: undefined,
67 capabilities: new Set(["orchestration"]),
68 issuedAt: 1,
69});
70โ
71function baseThread(input: {
72 readonly threadId: ThreadId;
73 readonly title: string;
74 readonly instanceId: ProviderInstanceId;
75 readonly model: string;
76}) {
77 return {
78 id: input.threadId,
79 projectId,
80 title: input.title,
81 createdBy: "user" as const,
82 creationSource: "mcp" as const,
83 modelSelection: {
84 instanceId: input.instanceId,
85 model: input.model,
86 },
87 runtimeMode: "full-access" as const,
88 interactionMode: "default" as const,
89 branch: null,
90 worktreePath: null,
91 lineage: {
92 parentThreadId: null,
93 relationshipToParent: null,
94 rootThreadId: input.threadId,
95 },
96 archivedAt: null,
97 deletedAt: null,
98 providerInstanceId: input.instanceId,
99 createdAt: now,
100 updatedAt: now,
101 };
102}
103โ
104function makeRun(input: {
105 readonly id: RunId;
106 readonly ordinal: number;
107 readonly status: "running" | "waiting" | "cancelled" | "queued" | "completed";
108 readonly instanceId?: ProviderInstanceId;
109}) {
110 return {
111 id: input.id,
112 ordinal: input.ordinal,
113 status: input.status,
114 modelSelection: {
115 instanceId: input.instanceId ?? parentInstanceId,
116 model: "gpt-5.4",
117 },
118 providerInstanceId: input.instanceId ?? parentInstanceId,
119 requestedAt: now,
120 startedAt: input.status === "cancelled" || input.status === "queued" ? null : now,
121 completedAt: input.status === "cancelled" || input.status === "completed" ? now : null,
122 };
123}
124โ
125it("readThread preserves caller access errors and prefers activity-run status over a newer cancelled queued run", async () => {
126 let callerUnavailable = false;
127 const projection = {
128 thread: baseThread({
129 threadId: parentThreadId,
130 title: "Parent",
131 instanceId: parentInstanceId,
132 model: "gpt-5.4",
133 }),
134 runs: [
135 makeRun({ id: activeRunId, ordinal: 1, status: "running" }),
136 makeRun({ id: cancelledRunId, ordinal: 2, status: "cancelled" }),
137 ],
138 visibleTurnItems: [],
139 providerTurns: [],
140 runtimeRequests: [],
141 messages: [],
142 contextTransfers: [],
143 subagents: [],
144 updatedAt: now,
145 } as unknown as OrchestrationV2ThreadProjection;
146โ
147 const layer = layerOrchestratorService.pipe(
148 Layer.provide(
149 Layer.mergeAll(
150 Layer.mock(ThreadManagementService.ThreadManagementService)({
151 getTimelinePage: () => Effect.succeed({ items: [], totalItems: 0, hasMore: false }),
152 getThreadRecords: (threadId) =>
153 callerUnavailable
154 ? Effect.fail(
155 new Orchestrator.OrchestratorProjectionError({
156 threadId,
157 cause: "Caller unavailable",
158 }),
159 )
160 : threadId === parentThreadId
161 ? Effect.succeed(projection)
162 : Effect.die(`unexpected thread ${threadId}`),
163 getThreadShell: (threadId) =>
164 callerUnavailable
165 ? Effect.die("A failed caller read must not reach the target")
166 : Effect.succeed(
167 threadId === parentThreadId
168 ? (projection.thread as unknown as OrchestrationV2ThreadShell)
169 : null,
170 ),
171 getProjectThreadRecords: (input) =>
172 input.threadId === parentThreadId
173 ? Effect.succeed(projection)
174 : Effect.die(`unexpected thread ${input.threadId}`),
175 } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
176 ServerSettings.layerTest(),
177 Layer.mock(ProviderRegistry.ProviderRegistry)({
178 getProviders: Effect.succeed([]),
179 } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>),
180 Layer.mock(ProjectService.ProjectService)({}),
181 Layer.mock(SecretRequests.SecretRequests)({}),
182 Layer.mock(RemoteDelegation.RemoteDelegation)({}),
183 Layer.mock(ScheduledTaskService.ScheduledTaskService)({
184 list: () => Effect.succeed({ tasks: [] }),
185 } satisfies Partial<ScheduledTaskService.ScheduledTaskService["Service"]>),
186 Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
187 list: () => Effect.succeed([]),
188 } satisfies Partial<ProviderAdapterRegistry.ProviderAdapterRegistryV2["Service"]>),
189 NodeCrypto.layer,
190 ),
191 ),
192 );
193โ
194 await Effect.gen(function* () {
195 const service = yield* OrchestratorMcpService.OrchestratorMcpService;
196 const result = yield* service.readThread(makeScope(), { threadId: parentThreadId });
197 expect(result.thread.status).toBe("running");
198 expect(result.thread.latestRunId).toBe(cancelledRunId);
199 expect(result.thread.activeRunId).toBe(activeRunId);
200โ
201 callerUnavailable = true;
202 const denied = yield* service
203 .readThread({ ...makeScope(), capabilities: new Set() }, { threadId: parentThreadId })
204 .pipe(Effect.flip);
205 expect(denied.code).toBe("capability_denied");
206 const missingCaller = yield* service
207 .readThread(makeScope(), { threadId: parentThreadId })
208 .pipe(Effect.flip);
209 expect(missingCaller.code).toBe("orchestration_error");
210 expect(missingCaller.message).toContain(`Unable to read thread ${parentThreadId}:`);
211 }).pipe(Effect.provide(layer), Effect.runPromise);
212});
213โ
214it("readThread pages cut-off text without splitting an emoji across pages", async () => {
215 const text = "a๐bc";
216 const itemId = TurnItemId.make("turn-item-mcp-reasoning");
217 const projection = {
218 thread: baseThread({
219 threadId: parentThreadId,
220 title: "Parent",
221 instanceId: parentInstanceId,
222 model: "gpt-5.4",
223 }),
224 runs: [makeRun({ id: activeRunId, ordinal: 1, status: "running" })],
225 visibleTurnItems: [],
226 providerTurns: [],
227 runtimeRequests: [],
228 messages: [],
229 contextTransfers: [],
230 subagents: [],
231 updatedAt: now,
232 } as unknown as OrchestrationV2ThreadProjection;
233 const row = {
234 position: 0,
235 visibility: "visible",
236 sourceThreadId: parentThreadId,
237 sourceItemId: itemId,
238 item: {
239 type: "reasoning",
240 runId: activeRunId,
241 status: "completed",
242 title: null,
243 text,
244 updatedAt: now,
245 },
246 };
247โ
248 const layer = layerOrchestratorService.pipe(
249 Layer.provide(
250 Layer.mergeAll(
251 Layer.mock(ThreadManagementService.ThreadManagementService)({
252 getTimelinePage: () =>
253 Effect.succeed({
254 items: [row] as unknown as OrchestrationV2ThreadProjection["visibleTurnItems"],
255 totalItems: 1,
256 hasMore: false,
257 }),
258 getThreadRecords: () => Effect.succeed(projection),
259 getProjectThreadRecords: () => Effect.succeed(projection),
260 getThreadShell: () =>
261 Effect.succeed(projection.thread as unknown as OrchestrationV2ThreadShell),
262 } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
263 ServerSettings.layerTest(),
264 Layer.mock(ProviderRegistry.ProviderRegistry)({
265 getProviders: Effect.succeed([]),
266 } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>),
267 Layer.mock(ProjectService.ProjectService)({}),
268 Layer.mock(SecretRequests.SecretRequests)({}),
269 Layer.mock(RemoteDelegation.RemoteDelegation)({}),
270 Layer.mock(ScheduledTaskService.ScheduledTaskService)({
271 list: () => Effect.succeed({ tasks: [] }),
272 } satisfies Partial<ScheduledTaskService.ScheduledTaskService["Service"]>),
273 Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
274 list: () => Effect.succeed([]),
275 } satisfies Partial<ProviderAdapterRegistry.ProviderAdapterRegistryV2["Service"]>),
276 NodeCrypto.layer,
277 ),
278 ),
279 );
280โ
281 await Effect.gen(function* () {
282 const service = yield* OrchestratorMcpService.OrchestratorMcpService;
283 for (const [maxCharsPerItem, expected] of [
284 [2, ["a", "๐", "bc"]],
285 [1, ["a", "๐", "b", "c"]],
286 ] as const) {
287 let textOffset = 0;
288 for (const [index, text] of expected.entries()) {
289 const result = yield* service.readThread(makeScope(), {
290 threadId: parentThreadId,
291 view: "activity",
292 itemId,
293 textOffset,
294 maxCharsPerItem,
295 });
296 textOffset += text.length;
297 expect(result.items[0]).toMatchObject({
298 text,
299 textTruncated: index < expected.length - 1,
300 nextTextOffset: index < expected.length - 1 ? textOffset : null,
301 });
302 }
303 }
304 }).pipe(Effect.provide(layer), Effect.runPromise);
305});
306โ
307it("taskStatus returns task.providerInstanceId rather than the driver kind", async () => {
308 const parentProjection = {
309 thread: baseThread({
310 threadId: parentThreadId,
311 title: "Parent",
312 instanceId: parentInstanceId,
313 model: "gpt-5.4",
314 }),
315 runs: [makeRun({ id: activeRunId, ordinal: 1, status: "running" })],
316 visibleTurnItems: [],
317 providerTurns: [],
318 runtimeRequests: [],
319 messages: [],
320 contextTransfers: [],
321 subagents: [
322 {
323 id: taskId,
324 threadId: parentThreadId,
325 runId: activeRunId,
326 parentNodeId: NodeId.make("node-parent"),
327 origin: "app_owned",
328 createdBy: "agent",
329 driver: codexDriver,
330 providerInstanceId: customCodexInstanceId,
331 providerThreadId: null,
332 childThreadId,
333 nativeTaskRef: null,
334 prompt: "Inspect the custom instance.",
335 title: null,
336 model: "gpt-5.4",
337 status: "running",
338 result: null,
339 startedAt: now,
340 completedAt: null,
341 updatedAt: now,
342 },
343 ],
344 updatedAt: now,
345 } as unknown as OrchestrationV2ThreadProjection;
346โ
347 const childProjection = {
348 thread: {
349 ...baseThread({
350 threadId: childThreadId,
351 title: "Child",
352 instanceId: customCodexInstanceId,
353 model: "gpt-5.4",
354 }),
355 lineage: {
356 parentThreadId,
357 relationshipToParent: "subagent",
358 rootThreadId: parentThreadId,
359 },
360 createdBy: "agent",
361 },
362 runs: [
363 makeRun({
364 id: childRunId,
365 ordinal: 1,
366 status: "running",
367 instanceId: customCodexInstanceId,
368 }),
369 ],
370 visibleTurnItems: [],
371 providerTurns: [],
372 runtimeRequests: [],
373 messages: [],
374 contextTransfers: [
375 {
376 type: "subagent_spawn",
377 sourceThreadId: parentThreadId,
378 targetThreadId: childThreadId,
379 targetRunId: childRunId,
380 },
381 ],
382 subagents: [],
383 providerThreads: [],
384 updatedAt: now,
385 } as unknown as OrchestrationV2ThreadProjection;
386โ
387 const layer = layerOrchestratorService.pipe(
388 Layer.provide(
389 Layer.mergeAll(
390 Layer.mock(ThreadManagementService.ThreadManagementService)({
391 getTimelinePage: () => Effect.succeed({ items: [], totalItems: 0, hasMore: false }),
392 getThreadRecords: (threadId) => {
393 if (threadId === parentThreadId) return Effect.succeed(parentProjection);
394 if (threadId === childThreadId) return Effect.succeed(childProjection);
395 return Effect.die(`unexpected thread ${threadId}`);
396 },
397 } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
398 ServerSettings.layerTest(),
399 Layer.mock(ProviderRegistry.ProviderRegistry)({
400 getProviders: Effect.succeed([]),
401 } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>),
402 Layer.mock(ProjectService.ProjectService)({}),
403 Layer.mock(SecretRequests.SecretRequests)({}),
404 Layer.mock(RemoteDelegation.RemoteDelegation)({}),
405 Layer.mock(ScheduledTaskService.ScheduledTaskService)({
406 list: () => Effect.succeed({ tasks: [] }),
407 } satisfies Partial<ScheduledTaskService.ScheduledTaskService["Service"]>),
408 Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
409 list: () => Effect.succeed([]),
410 } satisfies Partial<ProviderAdapterRegistry.ProviderAdapterRegistryV2["Service"]>),
411 NodeCrypto.layer,
412 ),
413 ),
414 );
415โ
416 await Effect.gen(function* () {
417 const service = yield* OrchestratorMcpService.OrchestratorMcpService;
418 const result = yield* service.taskStatus(makeScope(), taskId);
419 expect(result.providerInstanceId).toBe(customCodexInstanceId);
420 expect(result.providerInstanceId).not.toBe(ProviderInstanceId.make(String(codexDriver)));
421 expect(result.status).toBe("running");
422 expect(result.taskId).toBe(taskId);
423 expect(result.childThreadId).toBe(childThreadId);
424 }).pipe(Effect.provide(layer), Effect.runPromise);
425});
426โ
427it("readThread and sendToThread reach threads in other projects", async () => {
428 let parentShell: OrchestrationV2ThreadShell | null = null;
429 let parentRuns: ReadonlyArray<unknown> = [
430 makeRun({ id: RunId.make("run-parent-live"), ordinal: 1, status: "running" }),
431 ];
432 const foreignProjectId = ProjectId.make("project-mcp-orchestrator-foreign");
433 const foreignThreadId = ThreadId.make("thread-mcp-orchestrator-foreign");
434 const parentProjection = {
435 thread: baseThread({
436 threadId: parentThreadId,
437 title: "Parent",
438 instanceId: parentInstanceId,
439 model: "gpt-5.4",
440 }),
441 get runs() {
442 return parentRuns;
443 },
444 visibleTurnItems: [],
445 providerTurns: [],
446 runtimeRequests: [],
447 messages: [],
448 contextTransfers: [],
449 subagents: [],
450 updatedAt: now,
451 } as unknown as OrchestrationV2ThreadProjection;
452 const foreignProjection = (threadId: ThreadId) =>
453 ({
454 thread: {
455 ...baseThread({
456 threadId,
457 title: "Foreign",
458 instanceId: parentInstanceId,
459 model: "gpt-5.4",
460 }),
461 projectId: foreignProjectId,
462 },
463 runs: [],
464 visibleTurnItems: [
465 {
466 position: 0,
467 visibility: "inherited",
468 sourceThreadId: threadId,
469 sourceItemId: "item-1",
470 item: {
471 id: "item-1",
472 type: "assistant_message",
473 messageId: "assistant-1",
474 status: "completed",
475 title: null,
476 text: "Foreign thread said hello",
477 createdAt: now,
478 updatedAt: now,
479 },
480 },
481 ],
482 providerTurns: [],
483 runtimeRequests: [],
484 messages: [],
485 contextTransfers: [],
486 subagents: [],
487 updatedAt: now,
488 }) as unknown as OrchestrationV2ThreadProjection;
489โ
490 const layer = layerOrchestratorService.pipe(
491 Layer.provide(
492 Layer.mergeAll(
493 Layer.mock(ThreadManagementService.ThreadManagementService)({
494 getThreadRecords: (threadId) => {
495 if (threadId === parentThreadId) return Effect.succeed(parentProjection);
496 if (threadId === foreignThreadId) return Effect.succeed(foreignProjection(threadId));
497 return Effect.die(`unexpected thread ${threadId}`);
498 },
499 getThreadShell: (threadId) =>
500 Effect.succeed(
501 threadId === foreignThreadId
502 ? (foreignProjection(threadId).thread as unknown as OrchestrationV2ThreadShell)
503 : threadId === parentThreadId
504 ? parentShell
505 : null,
506 ),
507 getTimelinePage: (threadId) =>
508 Effect.succeed({
509 items: foreignProjection(threadId).visibleTurnItems,
510 totalItems: 1,
511 hasMore: false,
512 }),
513 getProjectThreadRecords: (input) =>
514 input.threadId === foreignThreadId && input.projectId === foreignProjectId
515 ? Effect.succeed(foreignProjection(input.threadId))
516 : Effect.fail(
517 new ThreadManagementService.ThreadManagementThreadNotFoundError({
518 projectId: input.projectId,
519 threadId: input.threadId,
520 }),
521 ),
522 sendToThread: () =>
523 Effect.succeed({
524 run: { id: "run-foreign", status: "queued" },
525 delivery: "started",
526 } as unknown as ThreadManagementService.ThreadManagementSendResult),
527 } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
528 ServerSettings.layerTest(),
529 Layer.mock(ProviderRegistry.ProviderRegistry)({
530 getProviders: Effect.succeed([]),
531 } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>),
532 Layer.mock(ProjectService.ProjectService)({}),
533 Layer.mock(SecretRequests.SecretRequests)({}),
534 Layer.mock(RemoteDelegation.RemoteDelegation)({}),
535 Layer.mock(ScheduledTaskService.ScheduledTaskService)({
536 list: () =>
537 Effect.succeed({
538 tasks: [
539 {
540 id: "task-foreign",
541 projectId: foreignProjectId,
542 runtimeMode: "approval-required",
543 interactionMode: "default",
544 } as never,
545 ],
546 }),
547 } satisfies Partial<ScheduledTaskService.ScheduledTaskService["Service"]>),
548 Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
549 list: () => Effect.succeed([]),
550 } satisfies Partial<ProviderAdapterRegistry.ProviderAdapterRegistryV2["Service"]>),
551 NodeCrypto.layer,
552 ),
553 ),
554 );
555โ
556 await Effect.gen(function* () {
557 const service = yield* OrchestratorMcpService.OrchestratorMcpService;
558 const foreign = yield* service.readThread(makeScope(), { threadId: foreignThreadId });
559 expect(foreign.thread.threadId).toBe(foreignThreadId);
560 expect(foreign.thread.projectId).toBe(foreignProjectId);
561 expect(foreign.items.map((item) => item.text)).toEqual(["Foreign thread said hello"]);
562โ
563 const sent = yield* service.sendToThread(makeScope(), {
564 threadId: foreignThreadId,
565 message: "hi",
566 });
567 expect(sent.threadId).toBe(foreignThreadId);
568โ
569 parentRuns = [];
570 yield* service.readThread(makeScope(), { threadId: foreignThreadId });
571 const stale = yield* service
572 .sendToThread(makeScope(), { threadId: foreignThreadId, message: "hi again" })
573 .pipe(Effect.flip);
574 expect(stale.code).toBe("parent_not_active");
575 const staleInterrupt = yield* service
576 .interruptThread(makeScope(), { threadId: foreignThreadId })
577 .pipe(Effect.flip);
578 expect(staleInterrupt.code).toBe("parent_not_active");
579โ
580 const staleSchedule = yield* service
581 .scheduleTask(makeScope(), {
582 projectId: foreignProjectId,
583 prompt: "check in later",
584 schedule: { type: "interval", everyMs: 3_600_000 },
585 })
586 .pipe(Effect.flip);
587 expect(staleSchedule.code).toBe("parent_not_active");
588 const staleUpdate = yield* service
589 .updateScheduledTask(makeScope(), {
590 scheduledTaskId: ScheduledTaskId.make("task-foreign"),
591 enabled: false,
592 })
593 .pipe(Effect.flip);
594 expect(staleUpdate.code).toBe("parent_not_active");
595 const staleDelete = yield* service
596 .deleteScheduledTask(makeScope(), { scheduledTaskId: ScheduledTaskId.make("task-foreign") })
597 .pipe(Effect.flip);
598 expect(staleDelete.code).toBe("parent_not_active");
599โ
600 const backgroundTasks = [
601 {
602 taskId: "background-subagent",
603 kind: "subagent" as const,
604 providerInstanceId: parentInstanceId,
605 },
606 ];
607 parentShell = {
608 ...liveThreadShell(parentThreadId, { activeRunId: null }),
609 pendingBackgroundTasks: backgroundTasks,
610 };
611 const backgroundSent = yield* service.sendToThread(makeScope(), {
612 threadId: foreignThreadId,
613 message: "background",
614 });
615 expect(backgroundSent.threadId).toBe(foreignThreadId);
616 const delegate = yield* service
617 .delegateTask(makeScope(), { task: "requires a run" })
618 .pipe(Effect.flip);
619 expect(delegate.code).toBe("parent_not_active");
620 const create = yield* service
621 .createThreads(makeScope(), { threads: [{ prompt: "requires a run" }] })
622 .pipe(Effect.flip);
623 expect(create.code).toBe("parent_not_active");
624 const secret = yield* service
625 .requestSecret(makeScope(), { label: "Secret", reason: "requires a run" })
626 .pipe(Effect.flip);
627 expect(secret.code).toBe("parent_not_active");
628โ
629 parentShell = { ...parentShell, providerInstanceId: customCodexInstanceId };
630 const switchedScope = {
631 ...makeScope(),
632 thread: { ...makeScope().thread!, providerInstanceId: customCodexInstanceId },
633 };
634 const switched = yield* service
635 .sendToThread(switchedScope, { threadId: foreignThreadId, message: "wrong owner" })
636 .pipe(Effect.flip);
637 expect(switched.code).toBe("parent_not_active");
638 const mismatched = yield* service
639 .sendToThread(makeScope(), { threadId: foreignThreadId, message: "stale provider" })
640 .pipe(Effect.flip);
641 expect(mismatched.code).toBe("parent_not_active");
642โ
643 parentShell = liveThreadShell(parentThreadId);
644 const restarted = yield* service.sendToThread(makeScope(), {
645 threadId: foreignThreadId,
646 message: "new run",
647 });
648 expect(restarted.threadId).toBe(foreignThreadId);
649โ
650 parentShell = {
651 ...parentShell,
652 activeRunId: null,
653 pendingBackgroundTasks: backgroundTasks,
654 archivedAt: now,
655 };
656 const archived = yield* service
657 .sendToThread(makeScope(), { threadId: foreignThreadId, message: "archived" })
658 .pipe(Effect.flip);
659 expect(archived.code).toBe("parent_not_active");
660โ
661 parentShell = { ...parentShell, archivedAt: null, pendingBackgroundTasks: [] };
662 const stopped = yield* service
663 .sendToThread(makeScope(), { threadId: foreignThreadId, message: "after stop" })
664 .pipe(Effect.flip);
665 expect(stopped.code).toBe("parent_not_active");
666 }).pipe(Effect.provide(layer), Effect.runPromise);
667});
668โ
669it("requestSecret saves a pasted value to a file without opening a card", async () => {
670 const projection = {
671 thread: baseThread({
672 threadId: parentThreadId,
673 title: "Parent",
674 instanceId: parentInstanceId,
675 model: "gpt-5.4",
676 }),
677 runs: [{ ...makeRun({ id: activeRunId, ordinal: 1, status: "running" }), rootNodeId: taskId }],
678 visibleTurnItems: [],
679 providerTurns: [],
680 runtimeRequests: [],
681 messages: [],
682 contextTransfers: [],
683 subagents: [],
684 updatedAt: now,
685 } as unknown as OrchestrationV2ThreadProjection;
686 const dispatched: Array<unknown> = [];
687 const saved: Array<{
688 readonly requestNamespace: string;
689 readonly requestKey: string;
690 readonly value: string;
691 }> = [];
692 const file = "/home/user/.t3/userdata/secrets/files/0123456789abcdef0123456789abcdef";
693โ
694 const layer = layerOrchestratorService.pipe(
695 Layer.provide(
696 Layer.mergeAll(
697 Layer.mock(ThreadManagementService.ThreadManagementService)({
698 getThreadRecords: (threadId) =>
699 threadId === parentThreadId
700 ? Effect.succeed(projection)
701 : Effect.die(`unexpected thread ${threadId}`),
702 getThreadShell: (threadId) =>
703 Effect.succeed(
704 threadId === parentThreadId
705 ? (projection.thread as unknown as OrchestrationV2ThreadShell)
706 : null,
707 ),
708 dispatch: (command) => Effect.sync(() => void dispatched.push(command) as never),
709 } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
710 ServerSettings.layerTest(),
711 Layer.mock(ProviderRegistry.ProviderRegistry)({
712 getProviders: Effect.succeed([]),
713 } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>),
714 Layer.mock(ProjectService.ProjectService)({}),
715 Layer.mock(SecretRequests.SecretRequests)({
716 savePasted: (input) =>
717 Effect.sync(() => {
718 saved.push({
719 requestNamespace: input.requestNamespace,
720 requestKey: input.requestKey,
721 value: input.value,
722 });
723 return file;
724 }),
725 }),
726 Layer.mock(RemoteDelegation.RemoteDelegation)({}),
727 Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
728 Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({}),
729 NodeCrypto.layer,
730 ),
731 ),
732 );
733 const counted = Metric.snapshot.pipe(
734 Effect.map((snapshots) => {
735 const found = snapshots.find(
736 (snapshot) =>
737 snapshot.id === "t3_secret_requests_total" &&
738 snapshot.attributes?.status === "saved_pasted",
739 );
740 return found?.type === "Counter" ? Number(found.state.count) : 0;
741 }),
742 );
743โ
744 await Effect.gen(function* () {
745 const service = yield* OrchestratorMcpService.OrchestratorMcpService;
746 const before = yield* counted;
747 const result = yield* service.requestSecret(makeScope(), {
748 label: "Pixel PIN",
749 reason: "Unlocks the test phone.",
750 value: "482916",
751 clientRequestId: "pin-1",
752 });
753 expect(result).toEqual({ status: "saved", file });
754 expect(JSON.stringify(result)).not.toContain("482916");
755 expect(saved).toEqual([
756 {
757 requestNamespace: "provider-session-mcp-orchestrator-detail",
758 requestKey: "pin-1",
759 value: "482916",
760 },
761 ]);
762 expect(dispatched).toEqual([]);
763 expect((yield* counted) - before).toBe(1);
764โ
765 const asRef = yield* service
766 .requestSecret(makeScope(), {
767 label: "Pixel PIN",
768 reason: "Unlocks the test phone.",
769 value: "482916",
770 delivery: "secretRef",
771 })
772 .pipe(Effect.flip);
773 expect(asRef.code).toBe("invalid_request");
774 expect(asRef.message).not.toContain("482916");
775 expect(saved).toHaveLength(1);
776 expect(dispatched).toEqual([]);
777 }).pipe(Effect.provide(layer), Effect.runPromise);
778});
779โ
780it("requestSecret returns the unsaved note for a declined, cancelled or timed-out card", async () => {
781 const outcomes = ["declined", "cancelled", "pending"] as const;
782 const results = await Effect.forEach(outcomes, (outcome) => {
783 const dispatched: Array<{ readonly type: string; readonly turnItemId?: string }> = [];
784 const projection = () => {
785 const card = dispatched.find((command) => command.type === "secret_request.record");
786 return {
787 thread: baseThread({
788 threadId: parentThreadId,
789 title: "Parent",
790 instanceId: parentInstanceId,
791 model: "gpt-5.4",
792 }),
793 runs: [
794 { ...makeRun({ id: activeRunId, ordinal: 1, status: "running" }), rootNodeId: taskId },
795 ],
796 visibleTurnItems: [],
797 turnItems:
798 card === undefined
799 ? []
800 : [{ type: "secret_request", id: card.turnItemId, secretStatus: outcome }],
801 providerTurns: [],
802 runtimeRequests: [],
803 messages: [],
804 contextTransfers: [],
805 subagents: [],
806 updatedAt: now,
807 } as unknown as OrchestrationV2ThreadProjection;
808 };
809 const layer = layerOrchestratorService.pipe(
810 Layer.provide(
811 Layer.mergeAll(
812 Layer.mock(ThreadManagementService.ThreadManagementService)({
813 getThreadRecords: () => Effect.sync(projection),
814 getThreadShell: () =>
815 Effect.sync(() => projection().thread as unknown as OrchestrationV2ThreadShell),
816 dispatch: (command) => Effect.sync(() => void dispatched.push(command) as never),
817 } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
818 ServerSettings.layerTest(),
819 Layer.mock(ProviderRegistry.ProviderRegistry)({
820 getProviders: Effect.succeed([]),
821 } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>),
822 Layer.mock(ProjectService.ProjectService)({}),
823 Layer.mock(SecretRequests.SecretRequests)({}),
824 Layer.mock(RemoteDelegation.RemoteDelegation)({}),
825 Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
826 Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({}),
827 NodeCrypto.layer,
828 ),
829 ),
830 );
831 return Effect.gen(function* () {
832 const service = yield* OrchestratorMcpService.OrchestratorMcpService;
833 const request = yield* service
834 .requestSecret(makeScope(), {
835 label: "Staging password",
836 reason: "Signs in the QA account.",
837 delivery: "file",
838 timeoutMs: 1_000,
839 })
840 .pipe(Effect.forkChild({ startImmediately: true }));
841 yield* TestClock.adjust("2 seconds");
842 return yield* Fiber.join(request);
843 }).pipe(Effect.provide(Layer.merge(layer, TestClock.layer())));
844 }).pipe(Effect.runPromise);
845โ
846 expect(results).toEqual([
847 { status: "declined", note: SECRET_REQUEST_UNSAVED_NOTE.declined },
848 { status: "cancelled", note: SECRET_REQUEST_UNSAVED_NOTE.cancelled },
849 { status: "timed_out", note: SECRET_REQUEST_UNSAVED_NOTE.timed_out },
850 ]);
851});