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