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

OrchestratorMcpService.activity.test.ts

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