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

orchestrationV2.test.ts

573 lines19.9 KB

1import { describe, expect, it } from "@effect/vitest";
2import * as DateTime from "effect/DateTime";
3import * as Schema from "effect/Schema";
4​
5import { NodeId, RunAttemptId, TrimmedNonEmptyString } from "./index.ts";
6import {
7 latestProviderTurnForAttempt,
8 OrchestrationV2ProviderCapabilities,
9 OrchestrationV2ProviderThread,
10 OrchestrationV2ProviderThreadJson,
11 OrchestrationV2RpcSchemas,
12 OrchestrationV2Subagent,
13 OrchestrationV2SubagentJson,
14 OrchestrationV2ThreadHistoryPage,
15 OrchestrationV2TurnItem,
16 OrchestrationV2TurnItemJson,
17} from "./orchestrationV2.ts";
18​
19const now = DateTime.makeUnsafe("2026-04-20T00:00:00.000Z");
20​
21const decodeOrchestrationV2TurnItemJson = Schema.decodeUnknownSync(OrchestrationV2TurnItemJson);
22const encodeOrchestrationV2TurnItemJson = Schema.encodeSync(OrchestrationV2TurnItemJson);
23const decodeOrchestrationV2Subagent = Schema.decodeUnknownSync(OrchestrationV2Subagent);
24const encodeOrchestrationV2SubagentJson = Schema.encodeSync(OrchestrationV2SubagentJson);
25const decodeOrchestrationV2ProviderThreadJson = Schema.decodeUnknownSync(
26 OrchestrationV2ProviderThreadJson,
27);
28const encodeOrchestrationV2ProviderThreadJson = Schema.encodeSync(
29 OrchestrationV2ProviderThreadJson,
30);
31const decodeOrchestrationV2ProviderThread = Schema.decodeUnknownSync(OrchestrationV2ProviderThread);
32const decodeOrchestrationV2ProviderCapabilities = Schema.decodeUnknownSync(
33 OrchestrationV2ProviderCapabilities,
34);
35​
36describe("orchestration V2 contracts", () => {
37 it("decodes thread event types from a newer server as skippable items", () => {
38 const decodeWireItems = Schema.decodeUnknownSync(
39 Schema.toCodecJson(Schema.Array(OrchestrationV2RpcSchemas.subscribeThread.output)),
40 );
41 const detached = (id: string, sequence: number) => ({
42 kind: "event",
43 sequence,
44 event: {
45 id,
46 type: "provider-session.detached",
47 threadId: "thread-1",
48 occurredAt: DateTime.formatIso(now),
49 payload: { providerSessionId: "provider-session-1", detachedAt: DateTime.formatIso(now) },
50 },
51 });
52​
53 const items = decodeWireItems([
54 detached("event-1", 1),
55 {
56 kind: "event",
57 sequence: 2,
58 event: {
59 id: "event-2",
60 type: "run.from-a-future-server",
61 threadId: "thread-1",
62 occurredAt: DateTime.formatIso(now),
63 payload: { runId: "run-1" },
64 },
65 },
66 detached("event-3", 3),
67 ]);
68​
69 expect(items.map((item) => item.kind)).toEqual(["event", "unknown-event", "event"]);
70 expect(items[1]).toEqual({
71 kind: "unknown-event",
72 sequence: 2,
73 eventType: "run.from-a-future-server",
74 });
75 expect(() =>
76 decodeWireItems([
77 { ...detached("event-4", 4), event: { ...detached("event-4", 4).event, payload: {} } },
78 ]),
79 ).toThrow();
80 });
81​
82 it("skips turn item types from a newer server in snapshots and turn-item events", () => {
83 const decodeWireItems = Schema.decodeUnknownSync(
84 Schema.toCodecJson(Schema.Array(OrchestrationV2RpcSchemas.subscribeThread.output)),
85 );
86 const decodeHistoryPage = Schema.decodeUnknownSync(
87 Schema.toCodecJson(OrchestrationV2ThreadHistoryPage),
88 );
89 const item = (id: string, type: string, extra: Record<string, unknown>) => ({
90 id,
91 type,
92 threadId: "thread-1",
93 runId: null,
94 nodeId: null,
95 providerThreadId: null,
96 providerTurnId: null,
97 nativeItemRef: null,
98 parentItemId: null,
99 ordinal: 1,
100 status: "completed",
101 title: null,
102 startedAt: null,
103 completedAt: null,
104 updatedAt: DateTime.formatIso(now),
105 ...extra,
106 });
107 const known = item("item-known", "system_notice", { message: "Hello" });
108 const future = item("item-future", "hologram", { beam: "ref-1" });
109 const projected = (position: number, turnItem: { readonly id: string }) => ({
110 position,
111 visibility: "local",
112 sourceThreadId: "thread-1",
113 sourceItemId: turnItem.id,
114 item: turnItem,
115 });
116 const projection = {
117 thread: {
118 createdBy: "user",
119 creationSource: "web",
120 id: "thread-1",
121 projectId: "project-1",
122 title: "Thread",
123 providerInstanceId: "codex",
124 modelSelection: { instanceId: "codex", model: "gpt-5-codex" },
125 runtimeMode: "full-access",
126 interactionMode: "default",
127 branch: null,
128 worktreePath: null,
129 activeProviderThreadId: null,
130 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: "thread-1" },
131 forkedFrom: null,
132 createdAt: DateTime.formatIso(now),
133 updatedAt: DateTime.formatIso(now),
134 archivedAt: null,
135 deletedAt: null,
136 },
137 runs: [],
138 attempts: [],
139 nodes: [],
140 subagents: [],
141 providerSessions: [],
142 providerThreads: [],
143 providerTurns: [],
144 runtimeRequests: [],
145 messages: [],
146 plans: [],
147 turnItems: [future, known],
148 checkpointScopes: [],
149 checkpoints: [],
150 contextHandoffs: [],
151 contextTransfers: [],
152 visibleTurnItems: [projected(0, future), projected(1, known)],
153 updatedAt: DateTime.formatIso(now),
154 };
155 const turnItemEvent = (sequence: number, payload: unknown) => ({
156 kind: "event",
157 sequence,
158 event: {
159 id: `event-${sequence}`,
160 type: "turn-item.updated",
161 threadId: "thread-1",
162 occurredAt: DateTime.formatIso(now),
163 payload,
164 },
165 });
166​
167 const [snapshot, futureEvent, knownEvent] = decodeWireItems([
168 { kind: "snapshot", snapshotSequence: 1, projection },
169 turnItemEvent(2, future),
170 turnItemEvent(3, known),
171 ]);
172​
173 expect(snapshot).toMatchObject({ kind: "snapshot" });
174 if (snapshot?.kind !== "snapshot") throw new Error("expected a snapshot");
175 expect(snapshot.projection.turnItems.map((turnItem) => turnItem.id)).toEqual(["item-known"]);
176 expect(snapshot.projection.visibleTurnItems.map((row) => row.item.id)).toEqual(["item-known"]);
177 expect(futureEvent).toEqual({
178 kind: "unknown-event",
179 sequence: 2,
180 eventType: "turn-item.updated",
181 });
182 expect(knownEvent).toMatchObject({
183 kind: "event",
184 event: { type: "turn-item.updated", payload: { id: "item-known", type: "system_notice" } },
185 });
186 expect(
187 decodeHistoryPage({
188 snapshotSequence: 1,
189 items: [projected(0, future), projected(1, known)],
190 nextCursor: null,
191 hasMoreHistory: false,
192 }).items.map((row) => row.item.id),
193 ).toEqual(["item-known"]);
194​
195 const broken = item("item-broken", "system_notice", {});
196 expect(() => decodeWireItems([turnItemEvent(4, broken)])).toThrow();
197 expect(() =>
198 decodeWireItems([
199 {
200 kind: "snapshot",
201 snapshotSequence: 1,
202 projection: { ...projection, turnItems: [broken] },
203 },
204 ]),
205 ).toThrow();
206 });
207​
208 it("decodes persisted capability snapshots that predate runtimePolicy", () => {
209 const legacyCapabilities = {
210 sessions: {
211 supportsMultipleProviderThreadsPerSession: false,
212 supportsModelSwitchInSession: false,
213 supportsProviderSwitchingViaHandoff: true,
214 supportsRuntimeModeSwitchInSession: false,
215 pendingRequestsSurviveRestart: false,
216 },
217 threads: {
218 canCreateEmptyThread: true,
219 canReadThreadSnapshot: false,
220 canRollbackThread: true,
221 canForkThread: false,
222 canForkFromTurn: false,
223 canForkFromSubagentThread: false,
224 exposesNativeThreadId: true,
225 },
226 turns: {
227 exposesNativeTurnId: false,
228 emitsTurnStarted: true,
229 emitsTurnCompleted: true,
230 supportsInterrupt: true,
231 supportsActiveSteering: false,
232 supportsSteeringByInterruptRestart: true,
233 supportsQueuedMessages: true,
234 terminalStatusQuality: "strong",
235 },
236 streaming: {
237 streamsAssistantText: true,
238 streamsReasoning: true,
239 streamsToolOutput: true,
240 streamsPlanText: false,
241 emitsMessageCompleted: true,
242 },
243 tools: {
244 exposesToolItemIds: true,
245 emitsToolStarted: true,
246 emitsToolCompleted: true,
247 emitsToolOutput: true,
248 supportsMcpTools: false,
249 supportsDynamicToolCallbacks: false,
250 },
251 approvals: {
252 supportsCommandApproval: true,
253 supportsFileReadApproval: true,
254 supportsFileChangeApproval: true,
255 supportsApplyPatchApproval: false,
256 approvalsHaveNativeRequestIds: false,
257 approvalCallbacksAreLiveOnly: true,
258 approvalsCanOriginateFromSubagents: false,
259 },
260 planning: {
261 emitsPlanUpdated: true,
262 emitsTodoList: true,
263 emitsProposedPlan: false,
264 supportsStructuredQuestions: true,
265 planDeltasHaveItemIds: false,
266 },
267 subagents: {
268 supportsSubagents: false,
269 exposesSubagentThreadIds: false,
270 emitsSubagentLifecycle: false,
271 canWaitForSubagents: false,
272 canCloseSubagents: false,
273 canForkSubagentThread: false,
274 },
275 context: {
276 acceptsSystemContext: false,
277 acceptsDeveloperContext: false,
278 acceptsSyntheticUserContext: true,
279 canGenerateSummaries: true,
280 canConsumeHandoffSummaries: true,
281 supportsDeltaHandoff: true,
282 supportsFullThreadHandoff: true,
283 maxRecommendedHandoffChars: null,
284 },
285 checkpointing: {
286 appCanCheckpointFilesystem: true,
287 supportsNestedCheckpointScopes: true,
288 providerCanRollbackConversation: true,
289 providerRollbackReturnsSnapshot: true,
290 providerCanReadConversationSnapshot: false,
291 },
292 identity: {
293 nativeThreadIds: "strong",
294 nativeTurnIds: "weak",
295 nativeItemIds: "weak",
296 nativeRequestIds: "weak",
297 },
298 };
299​
300 const decoded = decodeOrchestrationV2ProviderCapabilities(legacyCapabilities);
301 expect(decoded.runtimePolicy).toEqual({ enforcement: "client-boundary" });
302​
303 const explicit = decodeOrchestrationV2ProviderCapabilities({
304 ...legacyCapabilities,
305 runtimePolicy: { enforcement: "native" },
306 });
307 expect(explicit.runtimePolicy).toEqual({ enforcement: "native" });
308 });
309​
310 it.each([" indented prompt\n", "\n \t\n"])(
311 "preserves workflow prompt and result %j in stored and wire JSON",
312 (preview) => {
313 const subagent = {
314 ...decodeOrchestrationV2Subagent({
315 id: "workflow-coordinator",
316 threadId: "thread-1",
317 runId: "run-1",
318 parentNodeId: "node-root-1",
319 origin: "provider_native",
320 createdBy: "agent",
321 driver: "claudeAgent",
322 providerInstanceId: "claudeAgent",
323 providerThreadId: null,
324 childThreadId: null,
325 nativeTaskRef: null,
326 prompt: "Run workflow",
327 title: null,
328 model: null,
329 status: "running",
330 result: null,
331 startedAt: now,
332 completedAt: null,
333 updatedAt: now,
334 }),
335 workflow: {
336 phases: [],
337 agents: [
338 {
339 index: 1,
340 label: "Member",
341 state: "completed" as const,
342 prompt: preview,
343 result: preview,
344 },
345 ],
346 },
347 };
348 const { workflow, ...coordinator } = subagent;
349 const incoming = { ...encodeOrchestrationV2SubagentJson(coordinator), workflow };
350 for (const codec of [
351 OrchestrationV2SubagentJson,
352 Schema.toCodecJson(OrchestrationV2Subagent),
353 ]) {
354 const encode = Schema.encodeSync(codec);
355 const decode = Schema.decodeUnknownSync(codec);
356 const json: unknown = JSON.parse(JSON.stringify(encode(subagent)));
357 expect(json).toMatchObject({
358 workflow: { agents: [{ prompt: preview, result: preview }] },
359 });
360 expect(decode(json).workflow?.agents[0]).toMatchObject({
361 prompt: preview,
362 result: preview,
363 });
364 expect(decode(incoming).workflow?.agents[0]).toMatchObject({
365 prompt: preview,
366 result: preview,
367 });
368 }
369 },
370 );
371​
372 it("decodes historical provider-thread JSON without pendingBackgroundTasks as empty roster", () => {
373 const providerThread = decodeOrchestrationV2ProviderThreadJson({
374 id: "provider-thread-1",
375 driver: "claude",
376 providerInstanceId: "claudeAgent",
377 providerSessionId: "provider-session-1",
378 appThreadId: "thread-1",
379 ownerNodeId: null,
380 nativeThreadRef: {
381 driver: "claude",
382 nativeId: "native-session-1",
383 strength: "strong",
384 },
385 nativeConversationHeadRef: null,
386 status: "idle",
387 firstRunOrdinal: 1,
388 lastRunOrdinal: 1,
389 handoffIds: [],
390 forkedFrom: null,
391 createdAt: "2026-04-20T00:00:00.000Z",
392 updatedAt: "2026-04-20T00:00:00.000Z",
393 });
394​
395 expect(providerThread.pendingBackgroundTasks).toEqual([]);
396 expect(providerThread.contextUsage).toBeNull();
397 expect(providerThread.nativeMetadata).toBeNull();
398​
399 const runtimeThread = decodeOrchestrationV2ProviderThread({
400 id: "provider-thread-2",
401 driver: "claude",
402 providerInstanceId: "claudeAgent",
403 providerSessionId: null,
404 appThreadId: "thread-2",
405 ownerNodeId: null,
406 nativeThreadRef: null,
407 nativeConversationHeadRef: null,
408 status: "idle",
409 firstRunOrdinal: null,
410 lastRunOrdinal: null,
411 handoffIds: [],
412 forkedFrom: null,
413 createdAt: now,
414 updatedAt: now,
415 });
416 expect(runtimeThread.pendingBackgroundTasks).toEqual([]);
417 expect(runtimeThread.contextUsage).toBeNull();
418 expect(runtimeThread.nativeMetadata).toBeNull();
419 });
420});
421​
422describe("background work kinds from older or newer servers", () => {
423 const storedNotification = (source: unknown) => ({
424 id: "notification",
425 threadId: "parent",
426 runId: null,
427 nodeId: null,
428 providerThreadId: null,
429 providerTurnId: null,
430 nativeItemRef: null,
431 parentItemId: null,
432 ordinal: 1,
433 status: "completed",
434 title: null,
435 startedAt: null,
436 completedAt: null,
437 updatedAt: "2026-09-09T00:00:00.000Z",
438 type: "notification",
439 outcome: "completed",
440 summary: "Background activity updated",
441 source,
442 });
443​
444 it("decodes notification sources stored before specific kinds existed", () => {
445 const sourceOf = (source: unknown) => {
446 const item = decodeOrchestrationV2TurnItemJson(storedNotification(source));
447 return item.type === "notification" ? item.source : undefined;
448 };
449 expect(
450 sourceOf({ kind: "background_task", nativeRef: { driver: "claude", nativeId: "task-1" } }),
451 ).toEqual({ kind: "background_task" });
452 expect(sourceOf({ kind: "background_command" })).toEqual({ kind: "command" });
453 expect(sourceOf({ kind: "monitor" })).toEqual({ kind: "monitor" });
454 });
455​
456 it("sends and stores sources that clients from before specific kinds still decode", () => {
457 const PreSpecificKindsNotification = Schema.Struct({
458 type: Schema.Literal("notification"),
459 source: Schema.Union([
460 Schema.Struct({ kind: Schema.Literal("delegated_task"), taskIds: Schema.Array(NodeId) }),
461 Schema.Struct({
462 kind: Schema.Literals(["background_task", "background_command", "monitor"]),
463 nativeRef: Schema.optional(Schema.Unknown),
464 }),
465 ]),
466 outcome: Schema.Literals(["completed", "failed", "cancelled", "updated", "unknown"]),
467 summary: Schema.String,
468 detail: Schema.optional(Schema.String),
469 });
470 const decodePreSpecificKinds = Schema.decodeUnknownSync(PreSpecificKindsNotification);
471 const sendOverWire = Schema.encodeSync(Schema.toCodecJson(OrchestrationV2TurnItem));
472 const cases = [
473 [{ kind: "subagent", childThreadId: "child" }, { kind: "background_task" }],
474 [{ kind: "subagent" }, { kind: "background_task" }],
475 [{ kind: "command" }, { kind: "background_command" }],
476 [{ kind: "monitor" }, { kind: "monitor" }],
477 [{ kind: "background_task" }, { kind: "background_task" }],
478 [
479 { kind: "delegated_task", taskIds: ["task-1"], childThreadId: "child" },
480 { kind: "delegated_task", taskIds: ["task-1"] },
481 ],
482 ] as const;
483 for (const [source, preSpecificKindsSource] of cases) {
484 const item = decodeOrchestrationV2TurnItemJson(storedNotification(source));
485 for (const encoded of [encodeOrchestrationV2TurnItemJson(item), sendOverWire(item)]) {
486 expect(decodePreSpecificKinds(encoded).source).toEqual(preSpecificKindsSource);
487 expect(decodeOrchestrationV2TurnItemJson(encoded)).toEqual(item);
488 }
489 expect(item).toMatchObject({ source });
490 }
491 });
492​
493 it("decodes a notification source kind from a newer server as generic background work", () => {
494 const item = decodeOrchestrationV2TurnItemJson(
495 storedNotification({ kind: "workflow", workflowId: "wf-1" }),
496 );
497 expect(item).toMatchObject({ type: "notification", source: { kind: "background_task" } });
498 });
499​
500 it("decodes rosters stored before kinds existed, and kinds from a newer server, as generic tasks", () => {
501 const providerThread = decodeOrchestrationV2ProviderThreadJson({
502 id: "provider-thread-1",
503 driver: "claude",
504 providerInstanceId: "claudeAgent",
505 providerSessionId: null,
506 appThreadId: "thread-1",
507 ownerNodeId: null,
508 nativeThreadRef: null,
509 nativeConversationHeadRef: null,
510 status: "idle",
511 firstRunOrdinal: 1,
512 lastRunOrdinal: 1,
513 handoffIds: [],
514 forkedFrom: null,
515 createdAt: "2026-04-20T00:00:00.000Z",
516 updatedAt: "2026-04-20T00:00:00.000Z",
517 pendingBackgroundTasks: [
518 { taskId: "bg-1", description: "Background sleep", taskType: "local_bash" },
519 { taskId: "bg-2" },
520 { taskId: "bg-3", description: "Nightly", kind: "workflow", schedule: "0 3 * * *" },
521 { taskId: "bg-4", description: "npm test", kind: "command" },
522 { taskId: "bg-5", kind: "subagent", childThreadId: "thread-child" },
523 { taskId: "bg-6", kind: "subagent", providerInstanceId: "claudeAgent" },
524 ],
525 });
526 expect(providerThread.pendingBackgroundTasks).toEqual([
527 { taskId: "bg-1", description: "Background sleep", kind: "background_task" },
528 { taskId: "bg-2", kind: "background_task" },
529 { taskId: "bg-3", description: "Nightly", kind: "background_task" },
530 { taskId: "bg-4", description: "npm test", kind: "command" },
531 { taskId: "bg-5", kind: "subagent", childThreadId: "thread-child" },
532 { taskId: "bg-6", kind: "subagent", providerInstanceId: "claudeAgent" },
533 ]);
534 const encoded = encodeOrchestrationV2ProviderThreadJson(providerThread).pendingBackgroundTasks;
535 expect(encoded).toEqual(providerThread.pendingBackgroundTasks);
536 const decodePreKindsRoster = Schema.decodeUnknownSync(
537 Schema.Array(
538 Schema.Struct({
539 taskId: TrimmedNonEmptyString,
540 description: Schema.optional(TrimmedNonEmptyString),
541 taskType: Schema.optional(TrimmedNonEmptyString),
542 }),
543 ),
544 );
545 expect(decodePreKindsRoster(encoded).map((task) => task.taskId)).toEqual([
546 "bg-1",
547 "bg-2",
548 "bg-3",
549 "bg-4",
550 "bg-5",
551 "bg-6",
552 ]);
553 expect(() =>
554 decodeOrchestrationV2ProviderThreadJson({
555 ...encodeOrchestrationV2ProviderThreadJson(providerThread),
556 pendingBackgroundTasks: [{ taskId: "", kind: "command" }],
557 }),
558 ).toThrow();
559 });
560});
561​
562describe("latestProviderTurnForAttempt", () => {
563 it("returns the attempt's highest-ordinal turn, as a Codex goal run spans several", () => {
564 const turns = [
565 { id: "first", runAttemptId: RunAttemptId.make("goal-attempt"), ordinal: 3 },
566 { id: "other", runAttemptId: RunAttemptId.make("other-attempt"), ordinal: 9 },
567 { id: "last", runAttemptId: RunAttemptId.make("goal-attempt"), ordinal: 5 },
568 { id: "subagent", runAttemptId: null, ordinal: 7 },
569 ];
570 expect(latestProviderTurnForAttempt(turns, RunAttemptId.make("goal-attempt"))?.id).toBe("last");
571 expect(latestProviderTurnForAttempt(turns, null)).toBeUndefined();
572 });
573});