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