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

OrchestratorMcpService.activity.test.ts

455 lines15.1 KB

1import {
2 EnvironmentId,
3 NodeId,
4 type OrchestrationV2ThreadProjection,
5 ProjectId,
6 ProviderDriverKind,
7 ProviderInstanceId,
8 RunId,
9 ThreadId,
10} from "@t3tools/contracts";
11import * as DateTime from "effect/DateTime";
12import * as Effect from "effect/Effect";
13import * as Layer from "effect/Layer";
14import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
15import { expect, it } from "vite-plus/test";
16​
17import { ProviderAdapterRegistryV2 } from "../orchestration-v2/ProviderAdapterRegistry.ts";
18import { ProviderRegistry } from "../provider/Services/ProviderRegistry.ts";
19import { ScheduledTaskService } from "../scheduledTasks/ScheduledTaskService.ts";
20import {
21 ThreadManagementService,
22 ThreadManagementThreadNotFoundError,
23} from "../orchestration-v2/ThreadManagementService.ts";
24import type * as McpInvocationContext from "./McpInvocationContext.ts";
25import {
26 layer as orchestratorMcpServiceLayer,
27 OrchestratorMcpService,
28} from "./OrchestratorMcpService.ts";
29​
30const environmentId = EnvironmentId.make("environment-mcp-orchestrator-detail");
31const projectId = ProjectId.make("project-mcp-orchestrator-detail");
32const parentThreadId = ThreadId.make("thread-mcp-orchestrator-parent");
33const childThreadId = ThreadId.make("thread-mcp-orchestrator-child");
34const activeRunId = RunId.make("run-mcp-active");
35const cancelledRunId = RunId.make("run-mcp-cancelled");
36const childRunId = RunId.make("run-mcp-child");
37const taskId = NodeId.make("node-mcp-task-1");
38const now = DateTime.makeUnsafe("2026-08-04T12:00:00.000Z");
39const codexDriver = ProviderDriverKind.make("codex");
40// Distinct from driver kind so a regression that re-derives from driver fails.
41const customCodexInstanceId = ProviderInstanceId.make("codex-custom-workspace");
42const parentInstanceId = ProviderInstanceId.make("codex");
43​
44const makeScope = (): McpInvocationContext.McpInvocationScope => ({
45 environmentId,
46 threadId: parentThreadId,
47 providerSessionId: "provider-session-mcp-orchestrator-detail",
48 providerInstanceId: parentInstanceId,
49 capabilities: new Set(["orchestration"]),
50 issuedAt: 1,
51});
52​
53function baseThread(input: {
54 readonly threadId: ThreadId;
55 readonly title: string;
56 readonly instanceId: ProviderInstanceId;
57 readonly model: string;
58}) {
59 return {
60 id: input.threadId,
61 projectId,
62 title: input.title,
63 createdBy: "user" as const,
64 creationSource: "mcp" as const,
65 modelSelection: {
66 instanceId: input.instanceId,
67 model: input.model,
68 },
69 runtimeMode: "full-access" as const,
70 interactionMode: "default" as const,
71 branch: null,
72 worktreePath: null,
73 lineage: {
74 parentThreadId: null,
75 relationshipToParent: null,
76 rootThreadId: input.threadId,
77 },
78 archivedAt: null,
79 deletedAt: null,
80 providerInstanceId: input.instanceId,
81 createdAt: now,
82 updatedAt: now,
83 };
85​
86function makeRun(input: {
87 readonly id: RunId;
88 readonly ordinal: number;
89 readonly status: "running" | "waiting" | "cancelled" | "queued" | "completed";
90 readonly instanceId?: ProviderInstanceId;
91}) {
92 return {
93 id: input.id,
94 ordinal: input.ordinal,
95 status: input.status,
96 modelSelection: {
97 instanceId: input.instanceId ?? parentInstanceId,
98 model: "gpt-5.4",
99 },
100 providerInstanceId: input.instanceId ?? parentInstanceId,
101 requestedAt: now,
102 startedAt: input.status === "cancelled" || input.status === "queued" ? null : now,
103 completedAt: input.status === "cancelled" || input.status === "completed" ? now : null,
104 };
106​
107it("readThread prefers activity-run status over a newer cancelled queued run", async () => {
108 const projection = {
109 thread: baseThread({
110 threadId: parentThreadId,
111 title: "Parent",
112 instanceId: parentInstanceId,
113 model: "gpt-5.4",
114 }),
115 runs: [
116 makeRun({ id: activeRunId, ordinal: 1, status: "running" }),
117 makeRun({ id: cancelledRunId, ordinal: 2, status: "cancelled" }),
118 ],
119 visibleTurnItems: [],
120 runtimeRequests: [],
121 messages: [],
122 contextTransfers: [],
123 subagents: [],
124 updatedAt: now,
125 } as unknown as OrchestrationV2ThreadProjection;
126​
127 const layer = orchestratorMcpServiceLayer.pipe(
128 Layer.provide(
129 Layer.mergeAll(
130 Layer.mock(ThreadManagementService)({
131 getThreadProjection: (threadId) =>
132 threadId === parentThreadId
133 ? Effect.succeed(projection)
134 : Effect.die(`unexpected thread ${threadId}`),
135 } satisfies Partial<ThreadManagementService["Service"]>),
136 Layer.mock(ProviderRegistry)({
137 getProviders: Effect.succeed([]),
138 } satisfies Partial<ProviderRegistry["Service"]>),
139 Layer.mock(ScheduledTaskService)({
140 list: () => Effect.succeed({ tasks: [] }),
141 } satisfies Partial<ScheduledTaskService["Service"]>),
142 Layer.mock(ProviderAdapterRegistryV2)({
143 list: () => Effect.succeed([]),
144 } satisfies Partial<ProviderAdapterRegistryV2["Service"]>),
145 NodeCrypto.layer,
146 ),
147 ),
148 );
149​
150 await Effect.gen(function* () {
151 const service = yield* OrchestratorMcpService;
152 const result = yield* service.readThread(makeScope(), { threadId: parentThreadId });
153 expect(result.thread.status).toBe("running");
154 expect(result.thread.latestRunId).toBe(cancelledRunId);
155 expect(result.thread.activeRunId).toBe(activeRunId);
156 }).pipe(Effect.provide(layer), Effect.runPromise);
157});
158​
159it("readThread prefers waiting activity status over a newer cancelled queued run", async () => {
160 const projection = {
161 thread: baseThread({
162 threadId: parentThreadId,
163 title: "Parent waiting",
164 instanceId: parentInstanceId,
165 model: "gpt-5.4",
166 }),
167 runs: [
168 makeRun({ id: activeRunId, ordinal: 1, status: "waiting" }),
169 makeRun({ id: cancelledRunId, ordinal: 2, status: "cancelled" }),
170 ],
171 visibleTurnItems: [],
172 runtimeRequests: [],
173 messages: [],
174 contextTransfers: [],
175 subagents: [],
176 updatedAt: now,
177 } as unknown as OrchestrationV2ThreadProjection;
178​
179 const layer = orchestratorMcpServiceLayer.pipe(
180 Layer.provide(
181 Layer.mergeAll(
182 Layer.mock(ThreadManagementService)({
183 getThreadProjection: (threadId) =>
184 threadId === parentThreadId
185 ? Effect.succeed(projection)
186 : Effect.die(`unexpected thread ${threadId}`),
187 } satisfies Partial<ThreadManagementService["Service"]>),
188 Layer.mock(ProviderRegistry)({
189 getProviders: Effect.succeed([]),
190 } satisfies Partial<ProviderRegistry["Service"]>),
191 Layer.mock(ScheduledTaskService)({
192 list: () => Effect.succeed({ tasks: [] }),
193 } satisfies Partial<ScheduledTaskService["Service"]>),
194 Layer.mock(ProviderAdapterRegistryV2)({
195 list: () => Effect.succeed([]),
196 } satisfies Partial<ProviderAdapterRegistryV2["Service"]>),
197 NodeCrypto.layer,
198 ),
199 ),
200 );
201​
202 await Effect.gen(function* () {
203 const service = yield* OrchestratorMcpService;
204 const result = yield* service.readThread(makeScope(), { threadId: parentThreadId });
205 expect(result.thread.status).toBe("waiting");
206 expect(result.thread.activeRunId).toBe(activeRunId);
207 }).pipe(Effect.provide(layer), Effect.runPromise);
208});
209​
210it("taskStatus returns task.providerInstanceId rather than the driver kind", async () => {
211 const parentProjection = {
212 thread: baseThread({
213 threadId: parentThreadId,
214 title: "Parent",
215 instanceId: parentInstanceId,
216 model: "gpt-5.4",
217 }),
218 runs: [makeRun({ id: activeRunId, ordinal: 1, status: "running" })],
219 visibleTurnItems: [],
220 runtimeRequests: [],
221 messages: [],
222 contextTransfers: [],
223 subagents: [
224 {
225 id: taskId,
226 threadId: parentThreadId,
227 runId: activeRunId,
228 parentNodeId: NodeId.make("node-parent"),
229 origin: "app_owned",
230 createdBy: "agent",
231 driver: codexDriver,
232 providerInstanceId: customCodexInstanceId,
233 providerThreadId: null,
234 childThreadId,
235 nativeTaskRef: null,
236 prompt: "Inspect the custom instance.",
237 title: null,
238 model: "gpt-5.4",
239 status: "running",
240 result: null,
241 startedAt: now,
242 completedAt: null,
243 updatedAt: now,
244 },
245 ],
246 updatedAt: now,
247 } as unknown as OrchestrationV2ThreadProjection;
248​
249 const childProjection = {
250 thread: {
251 ...baseThread({
252 threadId: childThreadId,
253 title: "Child",
254 instanceId: customCodexInstanceId,
255 model: "gpt-5.4",
256 }),
257 lineage: {
258 parentThreadId,
259 relationshipToParent: "subagent",
260 rootThreadId: parentThreadId,
261 },
262 createdBy: "agent",
263 },
264 runs: [
265 makeRun({
266 id: childRunId,
267 ordinal: 1,
268 status: "running",
269 instanceId: customCodexInstanceId,
270 }),
271 ],
272 visibleTurnItems: [],
273 runtimeRequests: [],
274 messages: [],
275 contextTransfers: [
276 {
277 type: "subagent_spawn",
278 sourceThreadId: parentThreadId,
279 targetThreadId: childThreadId,
280 targetRunId: childRunId,
281 },
282 ],
283 subagents: [],
284 providerThreads: [],
285 updatedAt: now,
286 } as unknown as OrchestrationV2ThreadProjection;
287​
288 const layer = orchestratorMcpServiceLayer.pipe(
289 Layer.provide(
290 Layer.mergeAll(
291 Layer.mock(ThreadManagementService)({
292 getThreadProjection: (threadId) => {
293 if (threadId === parentThreadId) return Effect.succeed(parentProjection);
294 if (threadId === childThreadId) return Effect.succeed(childProjection);
295 return Effect.die(`unexpected thread ${threadId}`);
296 },
297 } satisfies Partial<ThreadManagementService["Service"]>),
298 Layer.mock(ProviderRegistry)({
299 getProviders: Effect.succeed([]),
300 } satisfies Partial<ProviderRegistry["Service"]>),
301 Layer.mock(ScheduledTaskService)({
302 list: () => Effect.succeed({ tasks: [] }),
303 } satisfies Partial<ScheduledTaskService["Service"]>),
304 Layer.mock(ProviderAdapterRegistryV2)({
305 list: () => Effect.succeed([]),
306 } satisfies Partial<ProviderAdapterRegistryV2["Service"]>),
307 NodeCrypto.layer,
308 ),
309 ),
310 );
311​
312 await Effect.gen(function* () {
313 const service = yield* OrchestratorMcpService;
314 const result = yield* service.taskStatus(makeScope(), taskId);
315 expect(result.providerInstanceId).toBe(customCodexInstanceId);
316 expect(result.providerInstanceId).not.toBe(ProviderInstanceId.make(String(codexDriver)));
317 expect(result.status).toBe("running");
318 expect(result.taskId).toBe(taskId);
319 expect(result.childThreadId).toBe(childThreadId);
320 }).pipe(Effect.provide(layer), Effect.runPromise);
321});
322​
323it("readThread reaches a thread the user attached as context, but not one an agent attached", async () => {
324 const foreignProjectId = ProjectId.make("project-mcp-orchestrator-foreign");
325 const foreignThreadId = ThreadId.make("thread-mcp-orchestrator-foreign");
326 const agentOnlyThreadId = ThreadId.make("thread-mcp-orchestrator-agent-only");
327 const threadRecord = (threadId: ThreadId) => ({
328 version: 1,
329 kind: "thread",
330 contextId: `thread_${threadId}`,
331 label: "Attached",
332 environmentId,
333 threadId,
334 title: "Attached",
335 });
336 const message = (input: { createdBy: "user" | "agent"; threadId: ThreadId }) => ({
337 id: `message-${input.threadId}`,
338 threadId: parentThreadId,
339 runId: null,
340 nodeId: null,
341 role: "user",
342 text: `[Attached](t3-context://v1/thread/thread_${input.threadId})`,
343 context: { version: 1, records: [threadRecord(input.threadId)] },
344 attachments: [],
345 streaming: false,
346 createdBy: input.createdBy,
347 creationSource: input.createdBy === "user" ? "user" : "mcp",
348 createdAt: now,
349 updatedAt: now,
350 });
351 const parentProjection = {
352 thread: baseThread({
353 threadId: parentThreadId,
354 title: "Parent",
355 instanceId: parentInstanceId,
356 model: "gpt-5.4",
357 }),
358 runs: [],
359 visibleTurnItems: [],
360 runtimeRequests: [],
361 messages: [
362 message({ createdBy: "user", threadId: foreignThreadId }),
363 message({ createdBy: "agent", threadId: agentOnlyThreadId }),
364 ],
365 contextTransfers: [],
366 subagents: [],
367 updatedAt: now,
368 } as unknown as OrchestrationV2ThreadProjection;
369 const foreignProjection = (threadId: ThreadId) =>
370 ({
371 thread: {
372 ...baseThread({
373 threadId,
374 title: "Foreign",
375 instanceId: parentInstanceId,
376 model: "gpt-5.4",
377 }),
378 projectId: foreignProjectId,
379 },
380 runs: [],
381 visibleTurnItems: [
382 {
383 position: 0,
384 visibility: "inherited",
385 sourceThreadId: threadId,
386 sourceItemId: "item-1",
387 item: {
388 id: "item-1",
389 type: "assistant_message",
390 messageId: "assistant-1",
391 status: "completed",
392 title: null,
393 text: "Foreign thread said hello",
394 createdAt: now,
395 updatedAt: now,
396 },
397 },
398 ],
399 runtimeRequests: [],
400 messages: [],
401 contextTransfers: [],
402 subagents: [],
403 updatedAt: now,
404 }) as unknown as OrchestrationV2ThreadProjection;
405​
406 const layer = orchestratorMcpServiceLayer.pipe(
407 Layer.provide(
408 Layer.mergeAll(
409 Layer.mock(ThreadManagementService)({
410 getThreadProjection: (threadId) => {
411 if (threadId === parentThreadId) return Effect.succeed(parentProjection);
412 if (threadId === foreignThreadId || threadId === agentOnlyThreadId) {
413 return Effect.succeed(foreignProjection(threadId));
414 }
415 return Effect.die(`unexpected thread ${threadId}`);
416 },
417 getProjectThread: (input) =>
418 Effect.fail(
419 new ThreadManagementThreadNotFoundError({
420 projectId: input.projectId,
421 threadId: input.threadId,
422 }),
423 ),
424 } satisfies Partial<ThreadManagementService["Service"]>),
425 Layer.mock(ProviderRegistry)({
426 getProviders: Effect.succeed([]),
427 } satisfies Partial<ProviderRegistry["Service"]>),
428 Layer.mock(ScheduledTaskService)({
429 list: () => Effect.succeed({ tasks: [] }),
430 } satisfies Partial<ScheduledTaskService["Service"]>),
431 Layer.mock(ProviderAdapterRegistryV2)({
432 list: () => Effect.succeed([]),
433 } satisfies Partial<ProviderAdapterRegistryV2["Service"]>),
434 NodeCrypto.layer,
435 ),
436 ),
437 );
438​
439 await Effect.gen(function* () {
440 const service = yield* OrchestratorMcpService;
441 const attached = yield* service.readThread(makeScope(), { threadId: foreignThreadId });
442 expect(attached.thread.threadId).toBe(foreignThreadId);
443 expect(attached.items.map((item) => item.text)).toEqual(["Foreign thread said hello"]);
444​
445 const denied = yield* service
446 .readThread(makeScope(), { threadId: agentOnlyThreadId })
447 .pipe(Effect.flip);
448 expect(denied.code).toBe("thread_not_found");
449​
450 const write = yield* service
451 .sendToThread(makeScope(), { threadId: foreignThreadId, message: "hi" })
452 .pipe(Effect.flip);
453 expect(write.code).toBe("thread_not_found");
454 }).pipe(Effect.provide(layer), Effect.runPromise);
455});