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

OrchestratorMcpService.activity.test.ts

657 lines23.9 KB

1import {
2 EnvironmentId,
3 NodeId,
4 type OrchestrationV2ThreadProjection,
5 type OrchestrationV2ThreadShell,
6 ProjectId,
7 ProviderDriverKind,
8 ProviderInstanceId,
9 RunId,
10 ScheduledTaskId,
11 ThreadId,
12 TurnItemId,
13} from "@t3tools/contracts";
14import * as DateTime from "effect/DateTime";
15import * as Effect from "effect/Effect";
16import * as Layer from "effect/Layer";
17import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
18import { expect, it } from "vite-plus/test";
19​
20import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";
21import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
22import * as ProjectService from "../project/ProjectService.ts";
23import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
24import * as ServerSettings from "../serverSettings.ts";
25import * as SecretRequests from "../secrets/SecretRequests.ts";
26import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts";
27import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
28import * as RemoteDelegation from "../peer/RemoteDelegation.ts";
29import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
30import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
31import type * as McpInvocationContext from "./McpInvocationContext.ts";
32import * as OrchestratorMcpService from "./OrchestratorMcpService.ts";
33import { liveThreadShell } from "./McpToolAccess.testkit.ts";
34​
35const layerOrchestratorService = OrchestratorMcpService.layer.pipe(
36 Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})),
37 Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
38);
39​
40const environmentId = EnvironmentId.make("environment-mcp-orchestrator-detail");
41const projectId = ProjectId.make("project-mcp-orchestrator-detail");
42const parentThreadId = ThreadId.make("thread-mcp-orchestrator-parent");
43const childThreadId = ThreadId.make("thread-mcp-orchestrator-child");
44const activeRunId = RunId.make("run-mcp-active");
45const cancelledRunId = RunId.make("run-mcp-cancelled");
46const childRunId = RunId.make("run-mcp-child");
47const taskId = NodeId.make("node-mcp-task-1");
48const now = DateTime.makeUnsafe("2026-08-04T12:00:00.000Z");
49const codexDriver = ProviderDriverKind.make("codex");
50​
51const customCodexInstanceId = ProviderInstanceId.make("codex-custom-workspace");
52const parentInstanceId = ProviderInstanceId.make("codex");
53​
54const makeScope = (): McpInvocationContext.McpInvocationScope => ({
55 environmentId,
56 requestNamespace: "provider-session-mcp-orchestrator-detail",
57 thread: {
58 threadId: parentThreadId,
59 providerSessionId: "provider-session-mcp-orchestrator-detail",
60 providerInstanceId: parentInstanceId,
61 },
62 client: undefined,
63 capabilities: new Set(["orchestration"]),
64 issuedAt: 1,
65});
66​
67function baseThread(input: {
68 readonly threadId: ThreadId;
69 readonly title: string;
70 readonly instanceId: ProviderInstanceId;
71 readonly model: string;
72}) {
73 return {
74 id: input.threadId,
75 projectId,
76 title: input.title,
77 createdBy: "user" as const,
78 creationSource: "mcp" as const,
79 modelSelection: {
80 instanceId: input.instanceId,
81 model: input.model,
82 },
83 runtimeMode: "full-access" as const,
84 interactionMode: "default" as const,
85 branch: null,
86 worktreePath: null,
87 lineage: {
88 parentThreadId: null,
89 relationshipToParent: null,
90 rootThreadId: input.threadId,
91 },
92 archivedAt: null,
93 deletedAt: null,
94 providerInstanceId: input.instanceId,
95 createdAt: now,
96 updatedAt: now,
97 };
99​
100function makeRun(input: {
101 readonly id: RunId;
102 readonly ordinal: number;
103 readonly status: "running" | "waiting" | "cancelled" | "queued" | "completed";
104 readonly instanceId?: ProviderInstanceId;
105}) {
106 return {
107 id: input.id,
108 ordinal: input.ordinal,
109 status: input.status,
110 modelSelection: {
111 instanceId: input.instanceId ?? parentInstanceId,
112 model: "gpt-5.4",
113 },
114 providerInstanceId: input.instanceId ?? parentInstanceId,
115 requestedAt: now,
116 startedAt: input.status === "cancelled" || input.status === "queued" ? null : now,
117 completedAt: input.status === "cancelled" || input.status === "completed" ? now : null,
118 };
120​
121it("readThread preserves caller access errors and prefers activity-run status over a newer cancelled queued run", async () => {
122 let callerUnavailable = false;
123 const projection = {
124 thread: baseThread({
125 threadId: parentThreadId,
126 title: "Parent",
127 instanceId: parentInstanceId,
128 model: "gpt-5.4",
129 }),
130 runs: [
131 makeRun({ id: activeRunId, ordinal: 1, status: "running" }),
132 makeRun({ id: cancelledRunId, ordinal: 2, status: "cancelled" }),
133 ],
134 visibleTurnItems: [],
135 runtimeRequests: [],
136 messages: [],
137 contextTransfers: [],
138 subagents: [],
139 updatedAt: now,
140 } as unknown as OrchestrationV2ThreadProjection;
141​
142 const layer = layerOrchestratorService.pipe(
143 Layer.provide(
144 Layer.mergeAll(
145 Layer.mock(ThreadManagementService.ThreadManagementService)({
146 getTimelinePage: () => Effect.succeed({ items: [], totalItems: 0, hasMore: false }),
147 getThreadRecords: (threadId) =>
148 callerUnavailable
149 ? Effect.fail(
150 new Orchestrator.OrchestratorProjectionError({
151 threadId,
152 cause: "Caller unavailable",
153 }),
154 )
155 : threadId === parentThreadId
156 ? Effect.succeed(projection)
157 : Effect.die(`unexpected thread ${threadId}`),
158 getThreadShell: (threadId) =>
159 callerUnavailable
160 ? Effect.die("A failed caller read must not reach the target")
161 : Effect.succeed(
162 threadId === parentThreadId
163 ? (projection.thread as unknown as OrchestrationV2ThreadShell)
164 : null,
165 ),
166 getProjectThreadRecords: (input) =>
167 input.threadId === parentThreadId
168 ? Effect.succeed(projection)
169 : Effect.die(`unexpected thread ${input.threadId}`),
170 } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
171 ServerSettings.layerTest(),
172 Layer.mock(ProviderRegistry.ProviderRegistry)({
173 getProviders: Effect.succeed([]),
174 } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>),
175 Layer.mock(ProjectService.ProjectService)({}),
176 Layer.mock(SecretRequests.SecretRequests)({}),
177 Layer.mock(RemoteDelegation.RemoteDelegation)({}),
178 Layer.mock(ScheduledTaskService.ScheduledTaskService)({
179 list: () => Effect.succeed({ tasks: [] }),
180 } satisfies Partial<ScheduledTaskService.ScheduledTaskService["Service"]>),
181 Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
182 list: () => Effect.succeed([]),
183 } satisfies Partial<ProviderAdapterRegistry.ProviderAdapterRegistryV2["Service"]>),
184 NodeCrypto.layer,
185 ),
186 ),
187 );
188​
189 await Effect.gen(function* () {
190 const service = yield* OrchestratorMcpService.OrchestratorMcpService;
191 const result = yield* service.readThread(makeScope(), { threadId: parentThreadId });
192 expect(result.thread.status).toBe("running");
193 expect(result.thread.latestRunId).toBe(cancelledRunId);
194 expect(result.thread.activeRunId).toBe(activeRunId);
195​
196 callerUnavailable = true;
197 const denied = yield* service
198 .readThread({ ...makeScope(), capabilities: new Set() }, { threadId: parentThreadId })
199 .pipe(Effect.flip);
200 expect(denied.code).toBe("capability_denied");
201 const missingCaller = yield* service
202 .readThread(makeScope(), { threadId: parentThreadId })
203 .pipe(Effect.flip);
204 expect(missingCaller.code).toBe("orchestration_error");
205 expect(missingCaller.message).toContain(`Unable to read thread ${parentThreadId}:`);
206 }).pipe(Effect.provide(layer), Effect.runPromise);
207});
208​
209it("readThread pages cut-off text without splitting an emoji across pages", async () => {
210 const text = "aπŸ˜€bc";
211 const itemId = TurnItemId.make("turn-item-mcp-reasoning");
212 const projection = {
213 thread: baseThread({
214 threadId: parentThreadId,
215 title: "Parent",
216 instanceId: parentInstanceId,
217 model: "gpt-5.4",
218 }),
219 runs: [makeRun({ id: activeRunId, ordinal: 1, status: "running" })],
220 visibleTurnItems: [],
221 runtimeRequests: [],
222 messages: [],
223 contextTransfers: [],
224 subagents: [],
225 updatedAt: now,
226 } as unknown as OrchestrationV2ThreadProjection;
227 const row = {
228 position: 0,
229 visibility: "visible",
230 sourceThreadId: parentThreadId,
231 sourceItemId: itemId,
232 item: {
233 type: "reasoning",
234 runId: activeRunId,
235 status: "completed",
236 title: null,
237 text,
238 updatedAt: now,
239 },
240 };
241​
242 const layer = layerOrchestratorService.pipe(
243 Layer.provide(
244 Layer.mergeAll(
245 Layer.mock(ThreadManagementService.ThreadManagementService)({
246 getTimelinePage: () =>
247 Effect.succeed({
248 items: [row] as unknown as OrchestrationV2ThreadProjection["visibleTurnItems"],
249 totalItems: 1,
250 hasMore: false,
251 }),
252 getThreadRecords: () => Effect.succeed(projection),
253 getProjectThreadRecords: () => Effect.succeed(projection),
254 getThreadShell: () =>
255 Effect.succeed(projection.thread as unknown as OrchestrationV2ThreadShell),
256 } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
257 ServerSettings.layerTest(),
258 Layer.mock(ProviderRegistry.ProviderRegistry)({
259 getProviders: Effect.succeed([]),
260 } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>),
261 Layer.mock(ProjectService.ProjectService)({}),
262 Layer.mock(SecretRequests.SecretRequests)({}),
263 Layer.mock(RemoteDelegation.RemoteDelegation)({}),
264 Layer.mock(ScheduledTaskService.ScheduledTaskService)({
265 list: () => Effect.succeed({ tasks: [] }),
266 } satisfies Partial<ScheduledTaskService.ScheduledTaskService["Service"]>),
267 Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
268 list: () => Effect.succeed([]),
269 } satisfies Partial<ProviderAdapterRegistry.ProviderAdapterRegistryV2["Service"]>),
270 NodeCrypto.layer,
271 ),
272 ),
273 );
274​
275 await Effect.gen(function* () {
276 const service = yield* OrchestratorMcpService.OrchestratorMcpService;
277 for (const [maxCharsPerItem, expected] of [
278 [2, ["a", "πŸ˜€", "bc"]],
279 [1, ["a", "πŸ˜€", "b", "c"]],
280 ] as const) {
281 let textOffset = 0;
282 for (const [index, text] of expected.entries()) {
283 const result = yield* service.readThread(makeScope(), {
284 threadId: parentThreadId,
285 view: "activity",
286 itemId,
287 textOffset,
288 maxCharsPerItem,
289 });
290 textOffset += text.length;
291 expect(result.items[0]).toMatchObject({
292 text,
293 textTruncated: index < expected.length - 1,
294 nextTextOffset: index < expected.length - 1 ? textOffset : null,
295 });
296 }
297 }
298 }).pipe(Effect.provide(layer), Effect.runPromise);
299});
300​
301it("taskStatus returns task.providerInstanceId rather than the driver kind", async () => {
302 const parentProjection = {
303 thread: baseThread({
304 threadId: parentThreadId,
305 title: "Parent",
306 instanceId: parentInstanceId,
307 model: "gpt-5.4",
308 }),
309 runs: [makeRun({ id: activeRunId, ordinal: 1, status: "running" })],
310 visibleTurnItems: [],
311 runtimeRequests: [],
312 messages: [],
313 contextTransfers: [],
314 subagents: [
315 {
316 id: taskId,
317 threadId: parentThreadId,
318 runId: activeRunId,
319 parentNodeId: NodeId.make("node-parent"),
320 origin: "app_owned",
321 createdBy: "agent",
322 driver: codexDriver,
323 providerInstanceId: customCodexInstanceId,
324 providerThreadId: null,
325 childThreadId,
326 nativeTaskRef: null,
327 prompt: "Inspect the custom instance.",
328 title: null,
329 model: "gpt-5.4",
330 status: "running",
331 result: null,
332 startedAt: now,
333 completedAt: null,
334 updatedAt: now,
335 },
336 ],
337 updatedAt: now,
338 } as unknown as OrchestrationV2ThreadProjection;
339​
340 const childProjection = {
341 thread: {
342 ...baseThread({
343 threadId: childThreadId,
344 title: "Child",
345 instanceId: customCodexInstanceId,
346 model: "gpt-5.4",
347 }),
348 lineage: {
349 parentThreadId,
350 relationshipToParent: "subagent",
351 rootThreadId: parentThreadId,
352 },
353 createdBy: "agent",
354 },
355 runs: [
356 makeRun({
357 id: childRunId,
358 ordinal: 1,
359 status: "running",
360 instanceId: customCodexInstanceId,
361 }),
362 ],
363 visibleTurnItems: [],
364 runtimeRequests: [],
365 messages: [],
366 contextTransfers: [
367 {
368 type: "subagent_spawn",
369 sourceThreadId: parentThreadId,
370 targetThreadId: childThreadId,
371 targetRunId: childRunId,
372 },
373 ],
374 subagents: [],
375 providerThreads: [],
376 updatedAt: now,
377 } as unknown as OrchestrationV2ThreadProjection;
378​
379 const layer = layerOrchestratorService.pipe(
380 Layer.provide(
381 Layer.mergeAll(
382 Layer.mock(ThreadManagementService.ThreadManagementService)({
383 getTimelinePage: () => Effect.succeed({ items: [], totalItems: 0, hasMore: false }),
384 getThreadRecords: (threadId) => {
385 if (threadId === parentThreadId) return Effect.succeed(parentProjection);
386 if (threadId === childThreadId) return Effect.succeed(childProjection);
387 return Effect.die(`unexpected thread ${threadId}`);
388 },
389 } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
390 ServerSettings.layerTest(),
391 Layer.mock(ProviderRegistry.ProviderRegistry)({
392 getProviders: Effect.succeed([]),
393 } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>),
394 Layer.mock(ProjectService.ProjectService)({}),
395 Layer.mock(SecretRequests.SecretRequests)({}),
396 Layer.mock(RemoteDelegation.RemoteDelegation)({}),
397 Layer.mock(ScheduledTaskService.ScheduledTaskService)({
398 list: () => Effect.succeed({ tasks: [] }),
399 } satisfies Partial<ScheduledTaskService.ScheduledTaskService["Service"]>),
400 Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
401 list: () => Effect.succeed([]),
402 } satisfies Partial<ProviderAdapterRegistry.ProviderAdapterRegistryV2["Service"]>),
403 NodeCrypto.layer,
404 ),
405 ),
406 );
407​
408 await Effect.gen(function* () {
409 const service = yield* OrchestratorMcpService.OrchestratorMcpService;
410 const result = yield* service.taskStatus(makeScope(), taskId);
411 expect(result.providerInstanceId).toBe(customCodexInstanceId);
412 expect(result.providerInstanceId).not.toBe(ProviderInstanceId.make(String(codexDriver)));
413 expect(result.status).toBe("running");
414 expect(result.taskId).toBe(taskId);
415 expect(result.childThreadId).toBe(childThreadId);
416 }).pipe(Effect.provide(layer), Effect.runPromise);
417});
418​
419it("readThread and sendToThread reach threads in other projects", async () => {
420 let parentShell: OrchestrationV2ThreadShell | null = null;
421 let parentRuns: ReadonlyArray<unknown> = [
422 makeRun({ id: RunId.make("run-parent-live"), ordinal: 1, status: "running" }),
423 ];
424 const foreignProjectId = ProjectId.make("project-mcp-orchestrator-foreign");
425 const foreignThreadId = ThreadId.make("thread-mcp-orchestrator-foreign");
426 const parentProjection = {
427 thread: baseThread({
428 threadId: parentThreadId,
429 title: "Parent",
430 instanceId: parentInstanceId,
431 model: "gpt-5.4",
432 }),
433 get runs() {
434 return parentRuns;
435 },
436 visibleTurnItems: [],
437 runtimeRequests: [],
438 messages: [],
439 contextTransfers: [],
440 subagents: [],
441 updatedAt: now,
442 } as unknown as OrchestrationV2ThreadProjection;
443 const foreignProjection = (threadId: ThreadId) =>
444 ({
445 thread: {
446 ...baseThread({
447 threadId,
448 title: "Foreign",
449 instanceId: parentInstanceId,
450 model: "gpt-5.4",
451 }),
452 projectId: foreignProjectId,
453 },
454 runs: [],
455 visibleTurnItems: [
456 {
457 position: 0,
458 visibility: "inherited",
459 sourceThreadId: threadId,
460 sourceItemId: "item-1",
461 item: {
462 id: "item-1",
463 type: "assistant_message",
464 messageId: "assistant-1",
465 status: "completed",
466 title: null,
467 text: "Foreign thread said hello",
468 createdAt: now,
469 updatedAt: now,
470 },
471 },
472 ],
473 runtimeRequests: [],
474 messages: [],
475 contextTransfers: [],
476 subagents: [],
477 updatedAt: now,
478 }) as unknown as OrchestrationV2ThreadProjection;
479​
480 const layer = layerOrchestratorService.pipe(
481 Layer.provide(
482 Layer.mergeAll(
483 Layer.mock(ThreadManagementService.ThreadManagementService)({
484 getThreadRecords: (threadId) => {
485 if (threadId === parentThreadId) return Effect.succeed(parentProjection);
486 if (threadId === foreignThreadId) return Effect.succeed(foreignProjection(threadId));
487 return Effect.die(`unexpected thread ${threadId}`);
488 },
489 getThreadShell: (threadId) =>
490 Effect.succeed(
491 threadId === foreignThreadId
492 ? (foreignProjection(threadId).thread as unknown as OrchestrationV2ThreadShell)
493 : threadId === parentThreadId
494 ? parentShell
495 : null,
496 ),
497 getTimelinePage: (threadId) =>
498 Effect.succeed({
499 items: foreignProjection(threadId).visibleTurnItems,
500 totalItems: 1,
501 hasMore: false,
502 }),
503 getProjectThreadRecords: (input) =>
504 input.threadId === foreignThreadId && input.projectId === foreignProjectId
505 ? Effect.succeed(foreignProjection(input.threadId))
506 : Effect.fail(
507 new ThreadManagementService.ThreadManagementThreadNotFoundError({
508 projectId: input.projectId,
509 threadId: input.threadId,
510 }),
511 ),
512 sendToThread: () =>
513 Effect.succeed({
514 run: { id: "run-foreign", status: "queued" },
515 delivery: "started",
516 } as unknown as ThreadManagementService.ThreadManagementSendResult),
517 } satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
518 ServerSettings.layerTest(),
519 Layer.mock(ProviderRegistry.ProviderRegistry)({
520 getProviders: Effect.succeed([]),
521 } satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>),
522 Layer.mock(ProjectService.ProjectService)({}),
523 Layer.mock(SecretRequests.SecretRequests)({}),
524 Layer.mock(RemoteDelegation.RemoteDelegation)({}),
525 Layer.mock(ScheduledTaskService.ScheduledTaskService)({
526 list: () =>
527 Effect.succeed({
528 tasks: [
529 {
530 id: "task-foreign",
531 projectId: foreignProjectId,
532 runtimeMode: "approval-required",
533 interactionMode: "default",
534 } as never,
535 ],
536 }),
537 } satisfies Partial<ScheduledTaskService.ScheduledTaskService["Service"]>),
538 Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
539 list: () => Effect.succeed([]),
540 } satisfies Partial<ProviderAdapterRegistry.ProviderAdapterRegistryV2["Service"]>),
541 NodeCrypto.layer,
542 ),
543 ),
544 );
545​
546 await Effect.gen(function* () {
547 const service = yield* OrchestratorMcpService.OrchestratorMcpService;
548 const foreign = yield* service.readThread(makeScope(), { threadId: foreignThreadId });
549 expect(foreign.thread.threadId).toBe(foreignThreadId);
550 expect(foreign.thread.projectId).toBe(foreignProjectId);
551 expect(foreign.items.map((item) => item.text)).toEqual(["Foreign thread said hello"]);
552​
553 const sent = yield* service.sendToThread(makeScope(), {
554 threadId: foreignThreadId,
555 message: "hi",
556 });
557 expect(sent.threadId).toBe(foreignThreadId);
558​
559 parentRuns = [];
560 yield* service.readThread(makeScope(), { threadId: foreignThreadId });
561 const stale = yield* service
562 .sendToThread(makeScope(), { threadId: foreignThreadId, message: "hi again" })
563 .pipe(Effect.flip);
564 expect(stale.code).toBe("parent_not_active");
565 const staleInterrupt = yield* service
566 .interruptThread(makeScope(), { threadId: foreignThreadId })
567 .pipe(Effect.flip);
568 expect(staleInterrupt.code).toBe("parent_not_active");
569​
570 const staleSchedule = yield* service
571 .scheduleTask(makeScope(), {
572 projectId: foreignProjectId,
573 prompt: "check in later",
574 schedule: { type: "interval", everyMs: 3_600_000 },
575 })
576 .pipe(Effect.flip);
577 expect(staleSchedule.code).toBe("parent_not_active");
578 const staleUpdate = yield* service
579 .updateScheduledTask(makeScope(), {
580 scheduledTaskId: ScheduledTaskId.make("task-foreign"),
581 enabled: false,
582 })
583 .pipe(Effect.flip);
584 expect(staleUpdate.code).toBe("parent_not_active");
585 const staleDelete = yield* service
586 .deleteScheduledTask(makeScope(), { scheduledTaskId: ScheduledTaskId.make("task-foreign") })
587 .pipe(Effect.flip);
588 expect(staleDelete.code).toBe("parent_not_active");
589​
590 const backgroundTasks = [
591 {
592 taskId: "background-subagent",
593 kind: "subagent" as const,
594 providerInstanceId: parentInstanceId,
595 },
596 ];
597 parentShell = {
598 ...liveThreadShell(parentThreadId, { activeRunId: null }),
599 pendingBackgroundTasks: backgroundTasks,
600 };
601 const backgroundSent = yield* service.sendToThread(makeScope(), {
602 threadId: foreignThreadId,
603 message: "background",
604 });
605 expect(backgroundSent.threadId).toBe(foreignThreadId);
606 const delegate = yield* service
607 .delegateTask(makeScope(), { task: "requires a run" })
608 .pipe(Effect.flip);
609 expect(delegate.code).toBe("parent_not_active");
610 const create = yield* service
611 .createThreads(makeScope(), { threads: [{ prompt: "requires a run" }] })
612 .pipe(Effect.flip);
613 expect(create.code).toBe("parent_not_active");
614 const secret = yield* service
615 .requestSecret(makeScope(), { label: "Secret", reason: "requires a run" })
616 .pipe(Effect.flip);
617 expect(secret.code).toBe("parent_not_active");
618​
619 parentShell = { ...parentShell, providerInstanceId: customCodexInstanceId };
620 const switchedScope = {
621 ...makeScope(),
622 thread: { ...makeScope().thread!, providerInstanceId: customCodexInstanceId },
623 };
624 const switched = yield* service
625 .sendToThread(switchedScope, { threadId: foreignThreadId, message: "wrong owner" })
626 .pipe(Effect.flip);
627 expect(switched.code).toBe("parent_not_active");
628 const mismatched = yield* service
629 .sendToThread(makeScope(), { threadId: foreignThreadId, message: "stale provider" })
630 .pipe(Effect.flip);
631 expect(mismatched.code).toBe("parent_not_active");
632​
633 parentShell = liveThreadShell(parentThreadId);
634 const restarted = yield* service.sendToThread(makeScope(), {
635 threadId: foreignThreadId,
636 message: "new run",
637 });
638 expect(restarted.threadId).toBe(foreignThreadId);
639​
640 parentShell = {
641 ...parentShell,
642 activeRunId: null,
643 pendingBackgroundTasks: backgroundTasks,
644 archivedAt: now,
645 };
646 const archived = yield* service
647 .sendToThread(makeScope(), { threadId: foreignThreadId, message: "archived" })
648 .pipe(Effect.flip);
649 expect(archived.code).toBe("parent_not_active");
650​
651 parentShell = { ...parentShell, archivedAt: null, pendingBackgroundTasks: [] };
652 const stopped = yield* service
653 .sendToThread(makeScope(), { threadId: foreignThreadId, message: "after stop" })
654 .pipe(Effect.flip);
655 expect(stopped.code).toBe("parent_not_active");
656 }).pipe(Effect.provide(layer), Effect.runPromise);
657});