Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

OrchestratorMcpService.activity.test.ts

892 lines32.6 KB

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