@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

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